Compare commits
10 Commits
2f2a14f2c5
...
988adf6cc5
| Author | SHA1 | Date | |
|---|---|---|---|
| 988adf6cc5 | |||
| 04022b835e | |||
| b02c1d44c8 | |||
| 54e1866997 | |||
| cf4bf9505a | |||
| a2990f02ba | |||
| 01603a0722 | |||
| cba2096adf | |||
| 4cac2b2592 | |||
| dfe460cb03 |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -7,7 +7,7 @@
|
||||
bin/
|
||||
dist/
|
||||
platform
|
||||
api-gateway
|
||||
/api-gateway
|
||||
/audit-service
|
||||
/identity-service
|
||||
/auth-service
|
||||
@@ -60,8 +60,6 @@ temp/
|
||||
docs/site/
|
||||
docs/.mkdocs_cache/
|
||||
|
||||
# Docker
|
||||
.dockerignore
|
||||
|
||||
# OS-specific
|
||||
Thumbs.db
|
||||
@@ -117,10 +117,10 @@ docker-compose -f docker-compose.dev.yml up -d
|
||||
docker-compose -f docker-compose.dev.yml ps
|
||||
|
||||
# Start services locally (in separate terminals)
|
||||
go run ./cmd/auth-service/main.go # Port 8081
|
||||
go run ./cmd/identity-service/main.go # Port 8082
|
||||
go run ./cmd/authz-service/main.go # Port 8083
|
||||
go run ./cmd/audit-service/main.go # Port 8084
|
||||
go run ./cmd/auth-service/*.go # Port 8081
|
||||
go run ./cmd/identity-service/*.go # Port 8082
|
||||
go run ./cmd/authz-service/*.go # Port 8083
|
||||
go run ./cmd/audit-service/*.go # Port 8084
|
||||
```
|
||||
|
||||
#### Option 2: Full Docker Deployment
|
||||
|
||||
1187
api/proto/generated/api/proto/identity.pb.go
Normal file
1187
api/proto/generated/api/proto/identity.pb.go
Normal file
File diff suppressed because it is too large
Load Diff
447
api/proto/generated/api/proto/identity_grpc.pb.go
Normal file
447
api/proto/generated/api/proto/identity_grpc.pb.go
Normal file
@@ -0,0 +1,447 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v6.30.2
|
||||
// source: api/proto/identity.proto
|
||||
|
||||
package identityv1
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
IdentityService_GetUser_FullMethodName = "/identity.v1.IdentityService/GetUser"
|
||||
IdentityService_GetUserByEmail_FullMethodName = "/identity.v1.IdentityService/GetUserByEmail"
|
||||
IdentityService_CreateUser_FullMethodName = "/identity.v1.IdentityService/CreateUser"
|
||||
IdentityService_UpdateUser_FullMethodName = "/identity.v1.IdentityService/UpdateUser"
|
||||
IdentityService_DeleteUser_FullMethodName = "/identity.v1.IdentityService/DeleteUser"
|
||||
IdentityService_VerifyEmail_FullMethodName = "/identity.v1.IdentityService/VerifyEmail"
|
||||
IdentityService_RequestPasswordReset_FullMethodName = "/identity.v1.IdentityService/RequestPasswordReset"
|
||||
IdentityService_ResetPassword_FullMethodName = "/identity.v1.IdentityService/ResetPassword"
|
||||
IdentityService_VerifyPassword_FullMethodName = "/identity.v1.IdentityService/VerifyPassword"
|
||||
)
|
||||
|
||||
// IdentityServiceClient is the client API for IdentityService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
//
|
||||
// IdentityService provides user management operations.
|
||||
type IdentityServiceClient interface {
|
||||
// GetUser retrieves a user by ID.
|
||||
GetUser(ctx context.Context, in *GetUserRequest, opts ...grpc.CallOption) (*GetUserResponse, error)
|
||||
// GetUserByEmail retrieves a user by email address.
|
||||
GetUserByEmail(ctx context.Context, in *GetUserByEmailRequest, opts ...grpc.CallOption) (*GetUserByEmailResponse, error)
|
||||
// CreateUser creates a new user.
|
||||
CreateUser(ctx context.Context, in *CreateUserRequest, opts ...grpc.CallOption) (*CreateUserResponse, error)
|
||||
// UpdateUser updates an existing user.
|
||||
UpdateUser(ctx context.Context, in *UpdateUserRequest, opts ...grpc.CallOption) (*UpdateUserResponse, error)
|
||||
// DeleteUser deletes a user.
|
||||
DeleteUser(ctx context.Context, in *DeleteUserRequest, opts ...grpc.CallOption) (*DeleteUserResponse, error)
|
||||
// VerifyEmail verifies a user's email address using a verification token.
|
||||
VerifyEmail(ctx context.Context, in *VerifyEmailRequest, opts ...grpc.CallOption) (*VerifyEmailResponse, error)
|
||||
// RequestPasswordReset requests a password reset token.
|
||||
RequestPasswordReset(ctx context.Context, in *RequestPasswordResetRequest, opts ...grpc.CallOption) (*RequestPasswordResetResponse, error)
|
||||
// ResetPassword resets a user's password using a reset token.
|
||||
ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*ResetPasswordResponse, error)
|
||||
// VerifyPassword verifies a user's password.
|
||||
VerifyPassword(ctx context.Context, in *VerifyPasswordRequest, opts ...grpc.CallOption) (*VerifyPasswordResponse, error)
|
||||
}
|
||||
|
||||
type identityServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewIdentityServiceClient(cc grpc.ClientConnInterface) IdentityServiceClient {
|
||||
return &identityServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *identityServiceClient) GetUser(ctx context.Context, in *GetUserRequest, opts ...grpc.CallOption) (*GetUserResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetUserResponse)
|
||||
err := c.cc.Invoke(ctx, IdentityService_GetUser_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *identityServiceClient) GetUserByEmail(ctx context.Context, in *GetUserByEmailRequest, opts ...grpc.CallOption) (*GetUserByEmailResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetUserByEmailResponse)
|
||||
err := c.cc.Invoke(ctx, IdentityService_GetUserByEmail_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *identityServiceClient) CreateUser(ctx context.Context, in *CreateUserRequest, opts ...grpc.CallOption) (*CreateUserResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(CreateUserResponse)
|
||||
err := c.cc.Invoke(ctx, IdentityService_CreateUser_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *identityServiceClient) UpdateUser(ctx context.Context, in *UpdateUserRequest, opts ...grpc.CallOption) (*UpdateUserResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(UpdateUserResponse)
|
||||
err := c.cc.Invoke(ctx, IdentityService_UpdateUser_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *identityServiceClient) DeleteUser(ctx context.Context, in *DeleteUserRequest, opts ...grpc.CallOption) (*DeleteUserResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(DeleteUserResponse)
|
||||
err := c.cc.Invoke(ctx, IdentityService_DeleteUser_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *identityServiceClient) VerifyEmail(ctx context.Context, in *VerifyEmailRequest, opts ...grpc.CallOption) (*VerifyEmailResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(VerifyEmailResponse)
|
||||
err := c.cc.Invoke(ctx, IdentityService_VerifyEmail_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *identityServiceClient) RequestPasswordReset(ctx context.Context, in *RequestPasswordResetRequest, opts ...grpc.CallOption) (*RequestPasswordResetResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(RequestPasswordResetResponse)
|
||||
err := c.cc.Invoke(ctx, IdentityService_RequestPasswordReset_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *identityServiceClient) ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*ResetPasswordResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ResetPasswordResponse)
|
||||
err := c.cc.Invoke(ctx, IdentityService_ResetPassword_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *identityServiceClient) VerifyPassword(ctx context.Context, in *VerifyPasswordRequest, opts ...grpc.CallOption) (*VerifyPasswordResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(VerifyPasswordResponse)
|
||||
err := c.cc.Invoke(ctx, IdentityService_VerifyPassword_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// IdentityServiceServer is the server API for IdentityService service.
|
||||
// All implementations must embed UnimplementedIdentityServiceServer
|
||||
// for forward compatibility.
|
||||
//
|
||||
// IdentityService provides user management operations.
|
||||
type IdentityServiceServer interface {
|
||||
// GetUser retrieves a user by ID.
|
||||
GetUser(context.Context, *GetUserRequest) (*GetUserResponse, error)
|
||||
// GetUserByEmail retrieves a user by email address.
|
||||
GetUserByEmail(context.Context, *GetUserByEmailRequest) (*GetUserByEmailResponse, error)
|
||||
// CreateUser creates a new user.
|
||||
CreateUser(context.Context, *CreateUserRequest) (*CreateUserResponse, error)
|
||||
// UpdateUser updates an existing user.
|
||||
UpdateUser(context.Context, *UpdateUserRequest) (*UpdateUserResponse, error)
|
||||
// DeleteUser deletes a user.
|
||||
DeleteUser(context.Context, *DeleteUserRequest) (*DeleteUserResponse, error)
|
||||
// VerifyEmail verifies a user's email address using a verification token.
|
||||
VerifyEmail(context.Context, *VerifyEmailRequest) (*VerifyEmailResponse, error)
|
||||
// RequestPasswordReset requests a password reset token.
|
||||
RequestPasswordReset(context.Context, *RequestPasswordResetRequest) (*RequestPasswordResetResponse, error)
|
||||
// ResetPassword resets a user's password using a reset token.
|
||||
ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error)
|
||||
// VerifyPassword verifies a user's password.
|
||||
VerifyPassword(context.Context, *VerifyPasswordRequest) (*VerifyPasswordResponse, error)
|
||||
mustEmbedUnimplementedIdentityServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedIdentityServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedIdentityServiceServer struct{}
|
||||
|
||||
func (UnimplementedIdentityServiceServer) GetUser(context.Context, *GetUserRequest) (*GetUserResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetUser not implemented")
|
||||
}
|
||||
func (UnimplementedIdentityServiceServer) GetUserByEmail(context.Context, *GetUserByEmailRequest) (*GetUserByEmailResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetUserByEmail not implemented")
|
||||
}
|
||||
func (UnimplementedIdentityServiceServer) CreateUser(context.Context, *CreateUserRequest) (*CreateUserResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method CreateUser not implemented")
|
||||
}
|
||||
func (UnimplementedIdentityServiceServer) UpdateUser(context.Context, *UpdateUserRequest) (*UpdateUserResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method UpdateUser not implemented")
|
||||
}
|
||||
func (UnimplementedIdentityServiceServer) DeleteUser(context.Context, *DeleteUserRequest) (*DeleteUserResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method DeleteUser not implemented")
|
||||
}
|
||||
func (UnimplementedIdentityServiceServer) VerifyEmail(context.Context, *VerifyEmailRequest) (*VerifyEmailResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VerifyEmail not implemented")
|
||||
}
|
||||
func (UnimplementedIdentityServiceServer) RequestPasswordReset(context.Context, *RequestPasswordResetRequest) (*RequestPasswordResetResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method RequestPasswordReset not implemented")
|
||||
}
|
||||
func (UnimplementedIdentityServiceServer) ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ResetPassword not implemented")
|
||||
}
|
||||
func (UnimplementedIdentityServiceServer) VerifyPassword(context.Context, *VerifyPasswordRequest) (*VerifyPasswordResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VerifyPassword not implemented")
|
||||
}
|
||||
func (UnimplementedIdentityServiceServer) mustEmbedUnimplementedIdentityServiceServer() {}
|
||||
func (UnimplementedIdentityServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeIdentityServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to IdentityServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeIdentityServiceServer interface {
|
||||
mustEmbedUnimplementedIdentityServiceServer()
|
||||
}
|
||||
|
||||
func RegisterIdentityServiceServer(s grpc.ServiceRegistrar, srv IdentityServiceServer) {
|
||||
// If the following call pancis, it indicates UnimplementedIdentityServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&IdentityService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _IdentityService_GetUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetUserRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(IdentityServiceServer).GetUser(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: IdentityService_GetUser_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(IdentityServiceServer).GetUser(ctx, req.(*GetUserRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _IdentityService_GetUserByEmail_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetUserByEmailRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(IdentityServiceServer).GetUserByEmail(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: IdentityService_GetUserByEmail_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(IdentityServiceServer).GetUserByEmail(ctx, req.(*GetUserByEmailRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _IdentityService_CreateUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(CreateUserRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(IdentityServiceServer).CreateUser(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: IdentityService_CreateUser_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(IdentityServiceServer).CreateUser(ctx, req.(*CreateUserRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _IdentityService_UpdateUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(UpdateUserRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(IdentityServiceServer).UpdateUser(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: IdentityService_UpdateUser_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(IdentityServiceServer).UpdateUser(ctx, req.(*UpdateUserRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _IdentityService_DeleteUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(DeleteUserRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(IdentityServiceServer).DeleteUser(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: IdentityService_DeleteUser_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(IdentityServiceServer).DeleteUser(ctx, req.(*DeleteUserRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _IdentityService_VerifyEmail_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(VerifyEmailRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(IdentityServiceServer).VerifyEmail(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: IdentityService_VerifyEmail_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(IdentityServiceServer).VerifyEmail(ctx, req.(*VerifyEmailRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _IdentityService_RequestPasswordReset_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(RequestPasswordResetRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(IdentityServiceServer).RequestPasswordReset(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: IdentityService_RequestPasswordReset_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(IdentityServiceServer).RequestPasswordReset(ctx, req.(*RequestPasswordResetRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _IdentityService_ResetPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ResetPasswordRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(IdentityServiceServer).ResetPassword(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: IdentityService_ResetPassword_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(IdentityServiceServer).ResetPassword(ctx, req.(*ResetPasswordRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _IdentityService_VerifyPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(VerifyPasswordRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(IdentityServiceServer).VerifyPassword(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: IdentityService_VerifyPassword_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(IdentityServiceServer).VerifyPassword(ctx, req.(*VerifyPasswordRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// IdentityService_ServiceDesc is the grpc.ServiceDesc for IdentityService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var IdentityService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "identity.v1.IdentityService",
|
||||
HandlerType: (*IdentityServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "GetUser",
|
||||
Handler: _IdentityService_GetUser_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetUserByEmail",
|
||||
Handler: _IdentityService_GetUserByEmail_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "CreateUser",
|
||||
Handler: _IdentityService_CreateUser_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "UpdateUser",
|
||||
Handler: _IdentityService_UpdateUser_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "DeleteUser",
|
||||
Handler: _IdentityService_DeleteUser_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "VerifyEmail",
|
||||
Handler: _IdentityService_VerifyEmail_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "RequestPasswordReset",
|
||||
Handler: _IdentityService_RequestPasswordReset_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ResetPassword",
|
||||
Handler: _IdentityService_ResetPassword_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "VerifyPassword",
|
||||
Handler: _IdentityService_VerifyPassword_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "api/proto/identity.proto",
|
||||
}
|
||||
486
api/proto/generated/audit.pb.go
Normal file
486
api/proto/generated/audit.pb.go
Normal file
@@ -0,0 +1,486 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.10
|
||||
// protoc v6.30.2
|
||||
// source: audit.proto
|
||||
|
||||
package auditv1
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
// AuditLogEntry represents an audit log entry.
|
||||
type AuditLogEntry struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
|
||||
Action string `protobuf:"bytes,2,opt,name=action,proto3" json:"action,omitempty"` // e.g., "user.create", "user.update"
|
||||
Resource string `protobuf:"bytes,3,opt,name=resource,proto3" json:"resource,omitempty"` // e.g., "user", "role"
|
||||
ResourceId string `protobuf:"bytes,4,opt,name=resource_id,json=resourceId,proto3" json:"resource_id,omitempty"`
|
||||
IpAddress string `protobuf:"bytes,5,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"`
|
||||
UserAgent string `protobuf:"bytes,6,opt,name=user_agent,json=userAgent,proto3" json:"user_agent,omitempty"`
|
||||
Metadata map[string]string `protobuf:"bytes,7,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
|
||||
Timestamp int64 `protobuf:"varint,8,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *AuditLogEntry) Reset() {
|
||||
*x = AuditLogEntry{}
|
||||
mi := &file_audit_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *AuditLogEntry) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*AuditLogEntry) ProtoMessage() {}
|
||||
|
||||
func (x *AuditLogEntry) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_audit_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use AuditLogEntry.ProtoReflect.Descriptor instead.
|
||||
func (*AuditLogEntry) Descriptor() ([]byte, []int) {
|
||||
return file_audit_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *AuditLogEntry) GetUserId() string {
|
||||
if x != nil {
|
||||
return x.UserId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *AuditLogEntry) GetAction() string {
|
||||
if x != nil {
|
||||
return x.Action
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *AuditLogEntry) GetResource() string {
|
||||
if x != nil {
|
||||
return x.Resource
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *AuditLogEntry) GetResourceId() string {
|
||||
if x != nil {
|
||||
return x.ResourceId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *AuditLogEntry) GetIpAddress() string {
|
||||
if x != nil {
|
||||
return x.IpAddress
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *AuditLogEntry) GetUserAgent() string {
|
||||
if x != nil {
|
||||
return x.UserAgent
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *AuditLogEntry) GetMetadata() map[string]string {
|
||||
if x != nil {
|
||||
return x.Metadata
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *AuditLogEntry) GetTimestamp() int64 {
|
||||
if x != nil {
|
||||
return x.Timestamp
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// RecordRequest contains an audit log entry to record.
|
||||
type RecordRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Entry *AuditLogEntry `protobuf:"bytes,1,opt,name=entry,proto3" json:"entry,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *RecordRequest) Reset() {
|
||||
*x = RecordRequest{}
|
||||
mi := &file_audit_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *RecordRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*RecordRequest) ProtoMessage() {}
|
||||
|
||||
func (x *RecordRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_audit_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use RecordRequest.ProtoReflect.Descriptor instead.
|
||||
func (*RecordRequest) Descriptor() ([]byte, []int) {
|
||||
return file_audit_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *RecordRequest) GetEntry() *AuditLogEntry {
|
||||
if x != nil {
|
||||
return x.Entry
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecordResponse indicates success.
|
||||
type RecordResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"`
|
||||
Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` // Audit log entry ID
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *RecordResponse) Reset() {
|
||||
*x = RecordResponse{}
|
||||
mi := &file_audit_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *RecordResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*RecordResponse) ProtoMessage() {}
|
||||
|
||||
func (x *RecordResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_audit_proto_msgTypes[2]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use RecordResponse.ProtoReflect.Descriptor instead.
|
||||
func (*RecordResponse) Descriptor() ([]byte, []int) {
|
||||
return file_audit_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *RecordResponse) GetSuccess() bool {
|
||||
if x != nil {
|
||||
return x.Success
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *RecordResponse) GetId() string {
|
||||
if x != nil {
|
||||
return x.Id
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// QueryRequest contains filters for querying audit logs.
|
||||
type QueryRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
UserId *string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3,oneof" json:"user_id,omitempty"`
|
||||
Action *string `protobuf:"bytes,2,opt,name=action,proto3,oneof" json:"action,omitempty"`
|
||||
Resource *string `protobuf:"bytes,3,opt,name=resource,proto3,oneof" json:"resource,omitempty"`
|
||||
ResourceId *string `protobuf:"bytes,4,opt,name=resource_id,json=resourceId,proto3,oneof" json:"resource_id,omitempty"`
|
||||
StartTime *int64 `protobuf:"varint,5,opt,name=start_time,json=startTime,proto3,oneof" json:"start_time,omitempty"`
|
||||
EndTime *int64 `protobuf:"varint,6,opt,name=end_time,json=endTime,proto3,oneof" json:"end_time,omitempty"`
|
||||
Limit int32 `protobuf:"varint,7,opt,name=limit,proto3" json:"limit,omitempty"` // Max number of results
|
||||
Offset int32 `protobuf:"varint,8,opt,name=offset,proto3" json:"offset,omitempty"` // Pagination offset
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *QueryRequest) Reset() {
|
||||
*x = QueryRequest{}
|
||||
mi := &file_audit_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *QueryRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*QueryRequest) ProtoMessage() {}
|
||||
|
||||
func (x *QueryRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_audit_proto_msgTypes[3]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use QueryRequest.ProtoReflect.Descriptor instead.
|
||||
func (*QueryRequest) Descriptor() ([]byte, []int) {
|
||||
return file_audit_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
func (x *QueryRequest) GetUserId() string {
|
||||
if x != nil && x.UserId != nil {
|
||||
return *x.UserId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *QueryRequest) GetAction() string {
|
||||
if x != nil && x.Action != nil {
|
||||
return *x.Action
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *QueryRequest) GetResource() string {
|
||||
if x != nil && x.Resource != nil {
|
||||
return *x.Resource
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *QueryRequest) GetResourceId() string {
|
||||
if x != nil && x.ResourceId != nil {
|
||||
return *x.ResourceId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *QueryRequest) GetStartTime() int64 {
|
||||
if x != nil && x.StartTime != nil {
|
||||
return *x.StartTime
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *QueryRequest) GetEndTime() int64 {
|
||||
if x != nil && x.EndTime != nil {
|
||||
return *x.EndTime
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *QueryRequest) GetLimit() int32 {
|
||||
if x != nil {
|
||||
return x.Limit
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *QueryRequest) GetOffset() int32 {
|
||||
if x != nil {
|
||||
return x.Offset
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// QueryResponse contains audit log entries.
|
||||
type QueryResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Entries []*AuditLogEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"`
|
||||
Total int32 `protobuf:"varint,2,opt,name=total,proto3" json:"total,omitempty"` // Total number of matching entries
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *QueryResponse) Reset() {
|
||||
*x = QueryResponse{}
|
||||
mi := &file_audit_proto_msgTypes[4]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *QueryResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*QueryResponse) ProtoMessage() {}
|
||||
|
||||
func (x *QueryResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_audit_proto_msgTypes[4]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use QueryResponse.ProtoReflect.Descriptor instead.
|
||||
func (*QueryResponse) Descriptor() ([]byte, []int) {
|
||||
return file_audit_proto_rawDescGZIP(), []int{4}
|
||||
}
|
||||
|
||||
func (x *QueryResponse) GetEntries() []*AuditLogEntry {
|
||||
if x != nil {
|
||||
return x.Entries
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *QueryResponse) GetTotal() int32 {
|
||||
if x != nil {
|
||||
return x.Total
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
var File_audit_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_audit_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\vaudit.proto\x12\baudit.v1\"\xd9\x02\n" +
|
||||
"\rAuditLogEntry\x12\x17\n" +
|
||||
"\auser_id\x18\x01 \x01(\tR\x06userId\x12\x16\n" +
|
||||
"\x06action\x18\x02 \x01(\tR\x06action\x12\x1a\n" +
|
||||
"\bresource\x18\x03 \x01(\tR\bresource\x12\x1f\n" +
|
||||
"\vresource_id\x18\x04 \x01(\tR\n" +
|
||||
"resourceId\x12\x1d\n" +
|
||||
"\n" +
|
||||
"ip_address\x18\x05 \x01(\tR\tipAddress\x12\x1d\n" +
|
||||
"\n" +
|
||||
"user_agent\x18\x06 \x01(\tR\tuserAgent\x12A\n" +
|
||||
"\bmetadata\x18\a \x03(\v2%.audit.v1.AuditLogEntry.MetadataEntryR\bmetadata\x12\x1c\n" +
|
||||
"\ttimestamp\x18\b \x01(\x03R\ttimestamp\x1a;\n" +
|
||||
"\rMetadataEntry\x12\x10\n" +
|
||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\">\n" +
|
||||
"\rRecordRequest\x12-\n" +
|
||||
"\x05entry\x18\x01 \x01(\v2\x17.audit.v1.AuditLogEntryR\x05entry\":\n" +
|
||||
"\x0eRecordResponse\x12\x18\n" +
|
||||
"\asuccess\x18\x01 \x01(\bR\asuccess\x12\x0e\n" +
|
||||
"\x02id\x18\x02 \x01(\tR\x02id\"\xd2\x02\n" +
|
||||
"\fQueryRequest\x12\x1c\n" +
|
||||
"\auser_id\x18\x01 \x01(\tH\x00R\x06userId\x88\x01\x01\x12\x1b\n" +
|
||||
"\x06action\x18\x02 \x01(\tH\x01R\x06action\x88\x01\x01\x12\x1f\n" +
|
||||
"\bresource\x18\x03 \x01(\tH\x02R\bresource\x88\x01\x01\x12$\n" +
|
||||
"\vresource_id\x18\x04 \x01(\tH\x03R\n" +
|
||||
"resourceId\x88\x01\x01\x12\"\n" +
|
||||
"\n" +
|
||||
"start_time\x18\x05 \x01(\x03H\x04R\tstartTime\x88\x01\x01\x12\x1e\n" +
|
||||
"\bend_time\x18\x06 \x01(\x03H\x05R\aendTime\x88\x01\x01\x12\x14\n" +
|
||||
"\x05limit\x18\a \x01(\x05R\x05limit\x12\x16\n" +
|
||||
"\x06offset\x18\b \x01(\x05R\x06offsetB\n" +
|
||||
"\n" +
|
||||
"\b_user_idB\t\n" +
|
||||
"\a_actionB\v\n" +
|
||||
"\t_resourceB\x0e\n" +
|
||||
"\f_resource_idB\r\n" +
|
||||
"\v_start_timeB\v\n" +
|
||||
"\t_end_time\"X\n" +
|
||||
"\rQueryResponse\x121\n" +
|
||||
"\aentries\x18\x01 \x03(\v2\x17.audit.v1.AuditLogEntryR\aentries\x12\x14\n" +
|
||||
"\x05total\x18\x02 \x01(\x05R\x05total2\x85\x01\n" +
|
||||
"\fAuditService\x12;\n" +
|
||||
"\x06Record\x12\x17.audit.v1.RecordRequest\x1a\x18.audit.v1.RecordResponse\x128\n" +
|
||||
"\x05Query\x12\x16.audit.v1.QueryRequest\x1a\x17.audit.v1.QueryResponseBGZEgit.dcentral.systems/toolz/goplt/api/proto/generated/audit/v1;auditv1b\x06proto3"
|
||||
|
||||
var (
|
||||
file_audit_proto_rawDescOnce sync.Once
|
||||
file_audit_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_audit_proto_rawDescGZIP() []byte {
|
||||
file_audit_proto_rawDescOnce.Do(func() {
|
||||
file_audit_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_audit_proto_rawDesc), len(file_audit_proto_rawDesc)))
|
||||
})
|
||||
return file_audit_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_audit_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
|
||||
var file_audit_proto_goTypes = []any{
|
||||
(*AuditLogEntry)(nil), // 0: audit.v1.AuditLogEntry
|
||||
(*RecordRequest)(nil), // 1: audit.v1.RecordRequest
|
||||
(*RecordResponse)(nil), // 2: audit.v1.RecordResponse
|
||||
(*QueryRequest)(nil), // 3: audit.v1.QueryRequest
|
||||
(*QueryResponse)(nil), // 4: audit.v1.QueryResponse
|
||||
nil, // 5: audit.v1.AuditLogEntry.MetadataEntry
|
||||
}
|
||||
var file_audit_proto_depIdxs = []int32{
|
||||
5, // 0: audit.v1.AuditLogEntry.metadata:type_name -> audit.v1.AuditLogEntry.MetadataEntry
|
||||
0, // 1: audit.v1.RecordRequest.entry:type_name -> audit.v1.AuditLogEntry
|
||||
0, // 2: audit.v1.QueryResponse.entries:type_name -> audit.v1.AuditLogEntry
|
||||
1, // 3: audit.v1.AuditService.Record:input_type -> audit.v1.RecordRequest
|
||||
3, // 4: audit.v1.AuditService.Query:input_type -> audit.v1.QueryRequest
|
||||
2, // 5: audit.v1.AuditService.Record:output_type -> audit.v1.RecordResponse
|
||||
4, // 6: audit.v1.AuditService.Query:output_type -> audit.v1.QueryResponse
|
||||
5, // [5:7] is the sub-list for method output_type
|
||||
3, // [3:5] is the sub-list for method input_type
|
||||
3, // [3:3] is the sub-list for extension type_name
|
||||
3, // [3:3] is the sub-list for extension extendee
|
||||
0, // [0:3] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_audit_proto_init() }
|
||||
func file_audit_proto_init() {
|
||||
if File_audit_proto != nil {
|
||||
return
|
||||
}
|
||||
file_audit_proto_msgTypes[3].OneofWrappers = []any{}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_audit_proto_rawDesc), len(file_audit_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 6,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_audit_proto_goTypes,
|
||||
DependencyIndexes: file_audit_proto_depIdxs,
|
||||
MessageInfos: file_audit_proto_msgTypes,
|
||||
}.Build()
|
||||
File_audit_proto = out.File
|
||||
file_audit_proto_goTypes = nil
|
||||
file_audit_proto_depIdxs = nil
|
||||
}
|
||||
167
api/proto/generated/audit_grpc.pb.go
Normal file
167
api/proto/generated/audit_grpc.pb.go
Normal file
@@ -0,0 +1,167 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v6.30.2
|
||||
// source: audit.proto
|
||||
|
||||
package auditv1
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
AuditService_Record_FullMethodName = "/audit.v1.AuditService/Record"
|
||||
AuditService_Query_FullMethodName = "/audit.v1.AuditService/Query"
|
||||
)
|
||||
|
||||
// AuditServiceClient is the client API for AuditService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
//
|
||||
// AuditService provides audit logging operations.
|
||||
type AuditServiceClient interface {
|
||||
// Record records an audit log entry.
|
||||
Record(ctx context.Context, in *RecordRequest, opts ...grpc.CallOption) (*RecordResponse, error)
|
||||
// Query queries audit logs based on filters.
|
||||
Query(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error)
|
||||
}
|
||||
|
||||
type auditServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewAuditServiceClient(cc grpc.ClientConnInterface) AuditServiceClient {
|
||||
return &auditServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *auditServiceClient) Record(ctx context.Context, in *RecordRequest, opts ...grpc.CallOption) (*RecordResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(RecordResponse)
|
||||
err := c.cc.Invoke(ctx, AuditService_Record_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *auditServiceClient) Query(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(QueryResponse)
|
||||
err := c.cc.Invoke(ctx, AuditService_Query_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// AuditServiceServer is the server API for AuditService service.
|
||||
// All implementations must embed UnimplementedAuditServiceServer
|
||||
// for forward compatibility.
|
||||
//
|
||||
// AuditService provides audit logging operations.
|
||||
type AuditServiceServer interface {
|
||||
// Record records an audit log entry.
|
||||
Record(context.Context, *RecordRequest) (*RecordResponse, error)
|
||||
// Query queries audit logs based on filters.
|
||||
Query(context.Context, *QueryRequest) (*QueryResponse, error)
|
||||
mustEmbedUnimplementedAuditServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedAuditServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedAuditServiceServer struct{}
|
||||
|
||||
func (UnimplementedAuditServiceServer) Record(context.Context, *RecordRequest) (*RecordResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Record not implemented")
|
||||
}
|
||||
func (UnimplementedAuditServiceServer) Query(context.Context, *QueryRequest) (*QueryResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Query not implemented")
|
||||
}
|
||||
func (UnimplementedAuditServiceServer) mustEmbedUnimplementedAuditServiceServer() {}
|
||||
func (UnimplementedAuditServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeAuditServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to AuditServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeAuditServiceServer interface {
|
||||
mustEmbedUnimplementedAuditServiceServer()
|
||||
}
|
||||
|
||||
func RegisterAuditServiceServer(s grpc.ServiceRegistrar, srv AuditServiceServer) {
|
||||
// If the following call pancis, it indicates UnimplementedAuditServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&AuditService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _AuditService_Record_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(RecordRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(AuditServiceServer).Record(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: AuditService_Record_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(AuditServiceServer).Record(ctx, req.(*RecordRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _AuditService_Query_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(QueryRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(AuditServiceServer).Query(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: AuditService_Query_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(AuditServiceServer).Query(ctx, req.(*QueryRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// AuditService_ServiceDesc is the grpc.ServiceDesc for AuditService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var AuditService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "audit.v1.AuditService",
|
||||
HandlerType: (*AuditServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "Record",
|
||||
Handler: _AuditService_Record_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "Query",
|
||||
Handler: _AuditService_Query_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "audit.proto",
|
||||
}
|
||||
568
api/proto/generated/auth.pb.go
Normal file
568
api/proto/generated/auth.pb.go
Normal file
@@ -0,0 +1,568 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.10
|
||||
// protoc v6.30.2
|
||||
// source: auth.proto
|
||||
|
||||
package authv1
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
// LoginRequest contains login credentials.
|
||||
type LoginRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`
|
||||
Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *LoginRequest) Reset() {
|
||||
*x = LoginRequest{}
|
||||
mi := &file_auth_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *LoginRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*LoginRequest) ProtoMessage() {}
|
||||
|
||||
func (x *LoginRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_auth_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use LoginRequest.ProtoReflect.Descriptor instead.
|
||||
func (*LoginRequest) Descriptor() ([]byte, []int) {
|
||||
return file_auth_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *LoginRequest) GetEmail() string {
|
||||
if x != nil {
|
||||
return x.Email
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *LoginRequest) GetPassword() string {
|
||||
if x != nil {
|
||||
return x.Password
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// LoginResponse contains authentication tokens.
|
||||
type LoginResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
AccessToken string `protobuf:"bytes,1,opt,name=access_token,json=accessToken,proto3" json:"access_token,omitempty"`
|
||||
RefreshToken string `protobuf:"bytes,2,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"`
|
||||
ExpiresIn int64 `protobuf:"varint,3,opt,name=expires_in,json=expiresIn,proto3" json:"expires_in,omitempty"` // seconds
|
||||
TokenType string `protobuf:"bytes,4,opt,name=token_type,json=tokenType,proto3" json:"token_type,omitempty"` // "Bearer"
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *LoginResponse) Reset() {
|
||||
*x = LoginResponse{}
|
||||
mi := &file_auth_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *LoginResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*LoginResponse) ProtoMessage() {}
|
||||
|
||||
func (x *LoginResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_auth_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use LoginResponse.ProtoReflect.Descriptor instead.
|
||||
func (*LoginResponse) Descriptor() ([]byte, []int) {
|
||||
return file_auth_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *LoginResponse) GetAccessToken() string {
|
||||
if x != nil {
|
||||
return x.AccessToken
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *LoginResponse) GetRefreshToken() string {
|
||||
if x != nil {
|
||||
return x.RefreshToken
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *LoginResponse) GetExpiresIn() int64 {
|
||||
if x != nil {
|
||||
return x.ExpiresIn
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *LoginResponse) GetTokenType() string {
|
||||
if x != nil {
|
||||
return x.TokenType
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// RefreshTokenRequest contains a refresh token.
|
||||
type RefreshTokenRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
RefreshToken string `protobuf:"bytes,1,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *RefreshTokenRequest) Reset() {
|
||||
*x = RefreshTokenRequest{}
|
||||
mi := &file_auth_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *RefreshTokenRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*RefreshTokenRequest) ProtoMessage() {}
|
||||
|
||||
func (x *RefreshTokenRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_auth_proto_msgTypes[2]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use RefreshTokenRequest.ProtoReflect.Descriptor instead.
|
||||
func (*RefreshTokenRequest) Descriptor() ([]byte, []int) {
|
||||
return file_auth_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *RefreshTokenRequest) GetRefreshToken() string {
|
||||
if x != nil {
|
||||
return x.RefreshToken
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// RefreshTokenResponse contains new authentication tokens.
|
||||
type RefreshTokenResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
AccessToken string `protobuf:"bytes,1,opt,name=access_token,json=accessToken,proto3" json:"access_token,omitempty"`
|
||||
RefreshToken string `protobuf:"bytes,2,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"`
|
||||
ExpiresIn int64 `protobuf:"varint,3,opt,name=expires_in,json=expiresIn,proto3" json:"expires_in,omitempty"` // seconds
|
||||
TokenType string `protobuf:"bytes,4,opt,name=token_type,json=tokenType,proto3" json:"token_type,omitempty"` // "Bearer"
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *RefreshTokenResponse) Reset() {
|
||||
*x = RefreshTokenResponse{}
|
||||
mi := &file_auth_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *RefreshTokenResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*RefreshTokenResponse) ProtoMessage() {}
|
||||
|
||||
func (x *RefreshTokenResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_auth_proto_msgTypes[3]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use RefreshTokenResponse.ProtoReflect.Descriptor instead.
|
||||
func (*RefreshTokenResponse) Descriptor() ([]byte, []int) {
|
||||
return file_auth_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
func (x *RefreshTokenResponse) GetAccessToken() string {
|
||||
if x != nil {
|
||||
return x.AccessToken
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *RefreshTokenResponse) GetRefreshToken() string {
|
||||
if x != nil {
|
||||
return x.RefreshToken
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *RefreshTokenResponse) GetExpiresIn() int64 {
|
||||
if x != nil {
|
||||
return x.ExpiresIn
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *RefreshTokenResponse) GetTokenType() string {
|
||||
if x != nil {
|
||||
return x.TokenType
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ValidateTokenRequest contains a JWT token to validate.
|
||||
type ValidateTokenRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *ValidateTokenRequest) Reset() {
|
||||
*x = ValidateTokenRequest{}
|
||||
mi := &file_auth_proto_msgTypes[4]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *ValidateTokenRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*ValidateTokenRequest) ProtoMessage() {}
|
||||
|
||||
func (x *ValidateTokenRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_auth_proto_msgTypes[4]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use ValidateTokenRequest.ProtoReflect.Descriptor instead.
|
||||
func (*ValidateTokenRequest) Descriptor() ([]byte, []int) {
|
||||
return file_auth_proto_rawDescGZIP(), []int{4}
|
||||
}
|
||||
|
||||
func (x *ValidateTokenRequest) GetToken() string {
|
||||
if x != nil {
|
||||
return x.Token
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ValidateTokenResponse contains token claims.
|
||||
type ValidateTokenResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
|
||||
Email string `protobuf:"bytes,2,opt,name=email,proto3" json:"email,omitempty"`
|
||||
Roles []string `protobuf:"bytes,3,rep,name=roles,proto3" json:"roles,omitempty"`
|
||||
ExpiresAt int64 `protobuf:"varint,4,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *ValidateTokenResponse) Reset() {
|
||||
*x = ValidateTokenResponse{}
|
||||
mi := &file_auth_proto_msgTypes[5]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *ValidateTokenResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*ValidateTokenResponse) ProtoMessage() {}
|
||||
|
||||
func (x *ValidateTokenResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_auth_proto_msgTypes[5]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use ValidateTokenResponse.ProtoReflect.Descriptor instead.
|
||||
func (*ValidateTokenResponse) Descriptor() ([]byte, []int) {
|
||||
return file_auth_proto_rawDescGZIP(), []int{5}
|
||||
}
|
||||
|
||||
func (x *ValidateTokenResponse) GetUserId() string {
|
||||
if x != nil {
|
||||
return x.UserId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ValidateTokenResponse) GetEmail() string {
|
||||
if x != nil {
|
||||
return x.Email
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ValidateTokenResponse) GetRoles() []string {
|
||||
if x != nil {
|
||||
return x.Roles
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *ValidateTokenResponse) GetExpiresAt() int64 {
|
||||
if x != nil {
|
||||
return x.ExpiresAt
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// LogoutRequest contains a refresh token to invalidate.
|
||||
type LogoutRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
RefreshToken string `protobuf:"bytes,1,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *LogoutRequest) Reset() {
|
||||
*x = LogoutRequest{}
|
||||
mi := &file_auth_proto_msgTypes[6]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *LogoutRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*LogoutRequest) ProtoMessage() {}
|
||||
|
||||
func (x *LogoutRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_auth_proto_msgTypes[6]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use LogoutRequest.ProtoReflect.Descriptor instead.
|
||||
func (*LogoutRequest) Descriptor() ([]byte, []int) {
|
||||
return file_auth_proto_rawDescGZIP(), []int{6}
|
||||
}
|
||||
|
||||
func (x *LogoutRequest) GetRefreshToken() string {
|
||||
if x != nil {
|
||||
return x.RefreshToken
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// LogoutResponse indicates success.
|
||||
type LogoutResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *LogoutResponse) Reset() {
|
||||
*x = LogoutResponse{}
|
||||
mi := &file_auth_proto_msgTypes[7]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *LogoutResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*LogoutResponse) ProtoMessage() {}
|
||||
|
||||
func (x *LogoutResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_auth_proto_msgTypes[7]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use LogoutResponse.ProtoReflect.Descriptor instead.
|
||||
func (*LogoutResponse) Descriptor() ([]byte, []int) {
|
||||
return file_auth_proto_rawDescGZIP(), []int{7}
|
||||
}
|
||||
|
||||
func (x *LogoutResponse) GetSuccess() bool {
|
||||
if x != nil {
|
||||
return x.Success
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var File_auth_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_auth_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\n" +
|
||||
"auth.proto\x12\aauth.v1\"@\n" +
|
||||
"\fLoginRequest\x12\x14\n" +
|
||||
"\x05email\x18\x01 \x01(\tR\x05email\x12\x1a\n" +
|
||||
"\bpassword\x18\x02 \x01(\tR\bpassword\"\x95\x01\n" +
|
||||
"\rLoginResponse\x12!\n" +
|
||||
"\faccess_token\x18\x01 \x01(\tR\vaccessToken\x12#\n" +
|
||||
"\rrefresh_token\x18\x02 \x01(\tR\frefreshToken\x12\x1d\n" +
|
||||
"\n" +
|
||||
"expires_in\x18\x03 \x01(\x03R\texpiresIn\x12\x1d\n" +
|
||||
"\n" +
|
||||
"token_type\x18\x04 \x01(\tR\ttokenType\":\n" +
|
||||
"\x13RefreshTokenRequest\x12#\n" +
|
||||
"\rrefresh_token\x18\x01 \x01(\tR\frefreshToken\"\x9c\x01\n" +
|
||||
"\x14RefreshTokenResponse\x12!\n" +
|
||||
"\faccess_token\x18\x01 \x01(\tR\vaccessToken\x12#\n" +
|
||||
"\rrefresh_token\x18\x02 \x01(\tR\frefreshToken\x12\x1d\n" +
|
||||
"\n" +
|
||||
"expires_in\x18\x03 \x01(\x03R\texpiresIn\x12\x1d\n" +
|
||||
"\n" +
|
||||
"token_type\x18\x04 \x01(\tR\ttokenType\",\n" +
|
||||
"\x14ValidateTokenRequest\x12\x14\n" +
|
||||
"\x05token\x18\x01 \x01(\tR\x05token\"{\n" +
|
||||
"\x15ValidateTokenResponse\x12\x17\n" +
|
||||
"\auser_id\x18\x01 \x01(\tR\x06userId\x12\x14\n" +
|
||||
"\x05email\x18\x02 \x01(\tR\x05email\x12\x14\n" +
|
||||
"\x05roles\x18\x03 \x03(\tR\x05roles\x12\x1d\n" +
|
||||
"\n" +
|
||||
"expires_at\x18\x04 \x01(\x03R\texpiresAt\"4\n" +
|
||||
"\rLogoutRequest\x12#\n" +
|
||||
"\rrefresh_token\x18\x01 \x01(\tR\frefreshToken\"*\n" +
|
||||
"\x0eLogoutResponse\x12\x18\n" +
|
||||
"\asuccess\x18\x01 \x01(\bR\asuccess2\x9d\x02\n" +
|
||||
"\vAuthService\x126\n" +
|
||||
"\x05Login\x12\x15.auth.v1.LoginRequest\x1a\x16.auth.v1.LoginResponse\x12K\n" +
|
||||
"\fRefreshToken\x12\x1c.auth.v1.RefreshTokenRequest\x1a\x1d.auth.v1.RefreshTokenResponse\x12N\n" +
|
||||
"\rValidateToken\x12\x1d.auth.v1.ValidateTokenRequest\x1a\x1e.auth.v1.ValidateTokenResponse\x129\n" +
|
||||
"\x06Logout\x12\x16.auth.v1.LogoutRequest\x1a\x17.auth.v1.LogoutResponseBEZCgit.dcentral.systems/toolz/goplt/api/proto/generated/auth/v1;authv1b\x06proto3"
|
||||
|
||||
var (
|
||||
file_auth_proto_rawDescOnce sync.Once
|
||||
file_auth_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_auth_proto_rawDescGZIP() []byte {
|
||||
file_auth_proto_rawDescOnce.Do(func() {
|
||||
file_auth_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_auth_proto_rawDesc), len(file_auth_proto_rawDesc)))
|
||||
})
|
||||
return file_auth_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_auth_proto_msgTypes = make([]protoimpl.MessageInfo, 8)
|
||||
var file_auth_proto_goTypes = []any{
|
||||
(*LoginRequest)(nil), // 0: auth.v1.LoginRequest
|
||||
(*LoginResponse)(nil), // 1: auth.v1.LoginResponse
|
||||
(*RefreshTokenRequest)(nil), // 2: auth.v1.RefreshTokenRequest
|
||||
(*RefreshTokenResponse)(nil), // 3: auth.v1.RefreshTokenResponse
|
||||
(*ValidateTokenRequest)(nil), // 4: auth.v1.ValidateTokenRequest
|
||||
(*ValidateTokenResponse)(nil), // 5: auth.v1.ValidateTokenResponse
|
||||
(*LogoutRequest)(nil), // 6: auth.v1.LogoutRequest
|
||||
(*LogoutResponse)(nil), // 7: auth.v1.LogoutResponse
|
||||
}
|
||||
var file_auth_proto_depIdxs = []int32{
|
||||
0, // 0: auth.v1.AuthService.Login:input_type -> auth.v1.LoginRequest
|
||||
2, // 1: auth.v1.AuthService.RefreshToken:input_type -> auth.v1.RefreshTokenRequest
|
||||
4, // 2: auth.v1.AuthService.ValidateToken:input_type -> auth.v1.ValidateTokenRequest
|
||||
6, // 3: auth.v1.AuthService.Logout:input_type -> auth.v1.LogoutRequest
|
||||
1, // 4: auth.v1.AuthService.Login:output_type -> auth.v1.LoginResponse
|
||||
3, // 5: auth.v1.AuthService.RefreshToken:output_type -> auth.v1.RefreshTokenResponse
|
||||
5, // 6: auth.v1.AuthService.ValidateToken:output_type -> auth.v1.ValidateTokenResponse
|
||||
7, // 7: auth.v1.AuthService.Logout:output_type -> auth.v1.LogoutResponse
|
||||
4, // [4:8] is the sub-list for method output_type
|
||||
0, // [0:4] is the sub-list for method input_type
|
||||
0, // [0:0] is the sub-list for extension type_name
|
||||
0, // [0:0] is the sub-list for extension extendee
|
||||
0, // [0:0] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_auth_proto_init() }
|
||||
func file_auth_proto_init() {
|
||||
if File_auth_proto != nil {
|
||||
return
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_auth_proto_rawDesc), len(file_auth_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 8,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_auth_proto_goTypes,
|
||||
DependencyIndexes: file_auth_proto_depIdxs,
|
||||
MessageInfos: file_auth_proto_msgTypes,
|
||||
}.Build()
|
||||
File_auth_proto = out.File
|
||||
file_auth_proto_goTypes = nil
|
||||
file_auth_proto_depIdxs = nil
|
||||
}
|
||||
247
api/proto/generated/auth_grpc.pb.go
Normal file
247
api/proto/generated/auth_grpc.pb.go
Normal file
@@ -0,0 +1,247 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v6.30.2
|
||||
// source: auth.proto
|
||||
|
||||
package authv1
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
AuthService_Login_FullMethodName = "/auth.v1.AuthService/Login"
|
||||
AuthService_RefreshToken_FullMethodName = "/auth.v1.AuthService/RefreshToken"
|
||||
AuthService_ValidateToken_FullMethodName = "/auth.v1.AuthService/ValidateToken"
|
||||
AuthService_Logout_FullMethodName = "/auth.v1.AuthService/Logout"
|
||||
)
|
||||
|
||||
// AuthServiceClient is the client API for AuthService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
//
|
||||
// AuthService provides authentication operations.
|
||||
type AuthServiceClient interface {
|
||||
// Login authenticates a user and returns access and refresh tokens.
|
||||
Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error)
|
||||
// RefreshToken refreshes an access token using a refresh token.
|
||||
RefreshToken(ctx context.Context, in *RefreshTokenRequest, opts ...grpc.CallOption) (*RefreshTokenResponse, error)
|
||||
// ValidateToken validates a JWT token and returns the token claims.
|
||||
ValidateToken(ctx context.Context, in *ValidateTokenRequest, opts ...grpc.CallOption) (*ValidateTokenResponse, error)
|
||||
// Logout invalidates a refresh token.
|
||||
Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*LogoutResponse, error)
|
||||
}
|
||||
|
||||
type authServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewAuthServiceClient(cc grpc.ClientConnInterface) AuthServiceClient {
|
||||
return &authServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *authServiceClient) Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(LoginResponse)
|
||||
err := c.cc.Invoke(ctx, AuthService_Login_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *authServiceClient) RefreshToken(ctx context.Context, in *RefreshTokenRequest, opts ...grpc.CallOption) (*RefreshTokenResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(RefreshTokenResponse)
|
||||
err := c.cc.Invoke(ctx, AuthService_RefreshToken_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *authServiceClient) ValidateToken(ctx context.Context, in *ValidateTokenRequest, opts ...grpc.CallOption) (*ValidateTokenResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ValidateTokenResponse)
|
||||
err := c.cc.Invoke(ctx, AuthService_ValidateToken_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *authServiceClient) Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*LogoutResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(LogoutResponse)
|
||||
err := c.cc.Invoke(ctx, AuthService_Logout_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// AuthServiceServer is the server API for AuthService service.
|
||||
// All implementations must embed UnimplementedAuthServiceServer
|
||||
// for forward compatibility.
|
||||
//
|
||||
// AuthService provides authentication operations.
|
||||
type AuthServiceServer interface {
|
||||
// Login authenticates a user and returns access and refresh tokens.
|
||||
Login(context.Context, *LoginRequest) (*LoginResponse, error)
|
||||
// RefreshToken refreshes an access token using a refresh token.
|
||||
RefreshToken(context.Context, *RefreshTokenRequest) (*RefreshTokenResponse, error)
|
||||
// ValidateToken validates a JWT token and returns the token claims.
|
||||
ValidateToken(context.Context, *ValidateTokenRequest) (*ValidateTokenResponse, error)
|
||||
// Logout invalidates a refresh token.
|
||||
Logout(context.Context, *LogoutRequest) (*LogoutResponse, error)
|
||||
mustEmbedUnimplementedAuthServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedAuthServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedAuthServiceServer struct{}
|
||||
|
||||
func (UnimplementedAuthServiceServer) Login(context.Context, *LoginRequest) (*LoginResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Login not implemented")
|
||||
}
|
||||
func (UnimplementedAuthServiceServer) RefreshToken(context.Context, *RefreshTokenRequest) (*RefreshTokenResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method RefreshToken not implemented")
|
||||
}
|
||||
func (UnimplementedAuthServiceServer) ValidateToken(context.Context, *ValidateTokenRequest) (*ValidateTokenResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ValidateToken not implemented")
|
||||
}
|
||||
func (UnimplementedAuthServiceServer) Logout(context.Context, *LogoutRequest) (*LogoutResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Logout not implemented")
|
||||
}
|
||||
func (UnimplementedAuthServiceServer) mustEmbedUnimplementedAuthServiceServer() {}
|
||||
func (UnimplementedAuthServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeAuthServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to AuthServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeAuthServiceServer interface {
|
||||
mustEmbedUnimplementedAuthServiceServer()
|
||||
}
|
||||
|
||||
func RegisterAuthServiceServer(s grpc.ServiceRegistrar, srv AuthServiceServer) {
|
||||
// If the following call pancis, it indicates UnimplementedAuthServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&AuthService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _AuthService_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(LoginRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(AuthServiceServer).Login(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: AuthService_Login_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(AuthServiceServer).Login(ctx, req.(*LoginRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _AuthService_RefreshToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(RefreshTokenRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(AuthServiceServer).RefreshToken(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: AuthService_RefreshToken_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(AuthServiceServer).RefreshToken(ctx, req.(*RefreshTokenRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _AuthService_ValidateToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ValidateTokenRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(AuthServiceServer).ValidateToken(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: AuthService_ValidateToken_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(AuthServiceServer).ValidateToken(ctx, req.(*ValidateTokenRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _AuthService_Logout_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(LogoutRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(AuthServiceServer).Logout(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: AuthService_Logout_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(AuthServiceServer).Logout(ctx, req.(*LogoutRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// AuthService_ServiceDesc is the grpc.ServiceDesc for AuthService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var AuthService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "auth.v1.AuthService",
|
||||
HandlerType: (*AuthServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "Login",
|
||||
Handler: _AuthService_Login_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "RefreshToken",
|
||||
Handler: _AuthService_RefreshToken_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ValidateToken",
|
||||
Handler: _AuthService_ValidateToken_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "Logout",
|
||||
Handler: _AuthService_Logout_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "auth.proto",
|
||||
}
|
||||
658
api/proto/generated/authz.pb.go
Normal file
658
api/proto/generated/authz.pb.go
Normal file
@@ -0,0 +1,658 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.10
|
||||
// protoc v6.30.2
|
||||
// source: authz.proto
|
||||
|
||||
package authzv1
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
// Permission represents a permission in the system.
|
||||
type Permission struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||
Code string `protobuf:"bytes,2,opt,name=code,proto3" json:"code,omitempty"`
|
||||
Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"`
|
||||
Description string `protobuf:"bytes,4,opt,name=description,proto3" json:"description,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Permission) Reset() {
|
||||
*x = Permission{}
|
||||
mi := &file_authz_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Permission) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Permission) ProtoMessage() {}
|
||||
|
||||
func (x *Permission) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_authz_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Permission.ProtoReflect.Descriptor instead.
|
||||
func (*Permission) Descriptor() ([]byte, []int) {
|
||||
return file_authz_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Permission) GetId() string {
|
||||
if x != nil {
|
||||
return x.Id
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Permission) GetCode() string {
|
||||
if x != nil {
|
||||
return x.Code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Permission) GetName() string {
|
||||
if x != nil {
|
||||
return x.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Permission) GetDescription() string {
|
||||
if x != nil {
|
||||
return x.Description
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Role represents a role in the system.
|
||||
type Role struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
|
||||
Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"`
|
||||
Permissions []string `protobuf:"bytes,4,rep,name=permissions,proto3" json:"permissions,omitempty"` // Permission codes
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Role) Reset() {
|
||||
*x = Role{}
|
||||
mi := &file_authz_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Role) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Role) ProtoMessage() {}
|
||||
|
||||
func (x *Role) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_authz_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Role.ProtoReflect.Descriptor instead.
|
||||
func (*Role) Descriptor() ([]byte, []int) {
|
||||
return file_authz_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *Role) GetId() string {
|
||||
if x != nil {
|
||||
return x.Id
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Role) GetName() string {
|
||||
if x != nil {
|
||||
return x.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Role) GetDescription() string {
|
||||
if x != nil {
|
||||
return x.Description
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Role) GetPermissions() []string {
|
||||
if x != nil {
|
||||
return x.Permissions
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AuthorizeRequest contains user ID and permission to check.
|
||||
type AuthorizeRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
|
||||
Permission string `protobuf:"bytes,2,opt,name=permission,proto3" json:"permission,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *AuthorizeRequest) Reset() {
|
||||
*x = AuthorizeRequest{}
|
||||
mi := &file_authz_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *AuthorizeRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*AuthorizeRequest) ProtoMessage() {}
|
||||
|
||||
func (x *AuthorizeRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_authz_proto_msgTypes[2]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use AuthorizeRequest.ProtoReflect.Descriptor instead.
|
||||
func (*AuthorizeRequest) Descriptor() ([]byte, []int) {
|
||||
return file_authz_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *AuthorizeRequest) GetUserId() string {
|
||||
if x != nil {
|
||||
return x.UserId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *AuthorizeRequest) GetPermission() string {
|
||||
if x != nil {
|
||||
return x.Permission
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// AuthorizeResponse indicates authorization result.
|
||||
type AuthorizeResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Authorized bool `protobuf:"varint,1,opt,name=authorized,proto3" json:"authorized,omitempty"`
|
||||
Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *AuthorizeResponse) Reset() {
|
||||
*x = AuthorizeResponse{}
|
||||
mi := &file_authz_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *AuthorizeResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*AuthorizeResponse) ProtoMessage() {}
|
||||
|
||||
func (x *AuthorizeResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_authz_proto_msgTypes[3]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use AuthorizeResponse.ProtoReflect.Descriptor instead.
|
||||
func (*AuthorizeResponse) Descriptor() ([]byte, []int) {
|
||||
return file_authz_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
func (x *AuthorizeResponse) GetAuthorized() bool {
|
||||
if x != nil {
|
||||
return x.Authorized
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *AuthorizeResponse) GetMessage() string {
|
||||
if x != nil {
|
||||
return x.Message
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// HasPermissionRequest contains user ID and permission to check.
|
||||
type HasPermissionRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
|
||||
Permission string `protobuf:"bytes,2,opt,name=permission,proto3" json:"permission,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *HasPermissionRequest) Reset() {
|
||||
*x = HasPermissionRequest{}
|
||||
mi := &file_authz_proto_msgTypes[4]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *HasPermissionRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*HasPermissionRequest) ProtoMessage() {}
|
||||
|
||||
func (x *HasPermissionRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_authz_proto_msgTypes[4]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use HasPermissionRequest.ProtoReflect.Descriptor instead.
|
||||
func (*HasPermissionRequest) Descriptor() ([]byte, []int) {
|
||||
return file_authz_proto_rawDescGZIP(), []int{4}
|
||||
}
|
||||
|
||||
func (x *HasPermissionRequest) GetUserId() string {
|
||||
if x != nil {
|
||||
return x.UserId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *HasPermissionRequest) GetPermission() string {
|
||||
if x != nil {
|
||||
return x.Permission
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// HasPermissionResponse indicates if the user has the permission.
|
||||
type HasPermissionResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
HasPermission bool `protobuf:"varint,1,opt,name=has_permission,json=hasPermission,proto3" json:"has_permission,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *HasPermissionResponse) Reset() {
|
||||
*x = HasPermissionResponse{}
|
||||
mi := &file_authz_proto_msgTypes[5]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *HasPermissionResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*HasPermissionResponse) ProtoMessage() {}
|
||||
|
||||
func (x *HasPermissionResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_authz_proto_msgTypes[5]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use HasPermissionResponse.ProtoReflect.Descriptor instead.
|
||||
func (*HasPermissionResponse) Descriptor() ([]byte, []int) {
|
||||
return file_authz_proto_rawDescGZIP(), []int{5}
|
||||
}
|
||||
|
||||
func (x *HasPermissionResponse) GetHasPermission() bool {
|
||||
if x != nil {
|
||||
return x.HasPermission
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// GetUserPermissionsRequest contains a user ID.
|
||||
type GetUserPermissionsRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *GetUserPermissionsRequest) Reset() {
|
||||
*x = GetUserPermissionsRequest{}
|
||||
mi := &file_authz_proto_msgTypes[6]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *GetUserPermissionsRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetUserPermissionsRequest) ProtoMessage() {}
|
||||
|
||||
func (x *GetUserPermissionsRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_authz_proto_msgTypes[6]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetUserPermissionsRequest.ProtoReflect.Descriptor instead.
|
||||
func (*GetUserPermissionsRequest) Descriptor() ([]byte, []int) {
|
||||
return file_authz_proto_rawDescGZIP(), []int{6}
|
||||
}
|
||||
|
||||
func (x *GetUserPermissionsRequest) GetUserId() string {
|
||||
if x != nil {
|
||||
return x.UserId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetUserPermissionsResponse contains all permissions for the user.
|
||||
type GetUserPermissionsResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Permissions []*Permission `protobuf:"bytes,1,rep,name=permissions,proto3" json:"permissions,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *GetUserPermissionsResponse) Reset() {
|
||||
*x = GetUserPermissionsResponse{}
|
||||
mi := &file_authz_proto_msgTypes[7]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *GetUserPermissionsResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetUserPermissionsResponse) ProtoMessage() {}
|
||||
|
||||
func (x *GetUserPermissionsResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_authz_proto_msgTypes[7]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetUserPermissionsResponse.ProtoReflect.Descriptor instead.
|
||||
func (*GetUserPermissionsResponse) Descriptor() ([]byte, []int) {
|
||||
return file_authz_proto_rawDescGZIP(), []int{7}
|
||||
}
|
||||
|
||||
func (x *GetUserPermissionsResponse) GetPermissions() []*Permission {
|
||||
if x != nil {
|
||||
return x.Permissions
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetUserRolesRequest contains a user ID.
|
||||
type GetUserRolesRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *GetUserRolesRequest) Reset() {
|
||||
*x = GetUserRolesRequest{}
|
||||
mi := &file_authz_proto_msgTypes[8]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *GetUserRolesRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetUserRolesRequest) ProtoMessage() {}
|
||||
|
||||
func (x *GetUserRolesRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_authz_proto_msgTypes[8]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetUserRolesRequest.ProtoReflect.Descriptor instead.
|
||||
func (*GetUserRolesRequest) Descriptor() ([]byte, []int) {
|
||||
return file_authz_proto_rawDescGZIP(), []int{8}
|
||||
}
|
||||
|
||||
func (x *GetUserRolesRequest) GetUserId() string {
|
||||
if x != nil {
|
||||
return x.UserId
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetUserRolesResponse contains all roles for the user.
|
||||
type GetUserRolesResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Roles []*Role `protobuf:"bytes,1,rep,name=roles,proto3" json:"roles,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *GetUserRolesResponse) Reset() {
|
||||
*x = GetUserRolesResponse{}
|
||||
mi := &file_authz_proto_msgTypes[9]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *GetUserRolesResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetUserRolesResponse) ProtoMessage() {}
|
||||
|
||||
func (x *GetUserRolesResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_authz_proto_msgTypes[9]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetUserRolesResponse.ProtoReflect.Descriptor instead.
|
||||
func (*GetUserRolesResponse) Descriptor() ([]byte, []int) {
|
||||
return file_authz_proto_rawDescGZIP(), []int{9}
|
||||
}
|
||||
|
||||
func (x *GetUserRolesResponse) GetRoles() []*Role {
|
||||
if x != nil {
|
||||
return x.Roles
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_authz_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_authz_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\vauthz.proto\x12\bauthz.v1\"f\n" +
|
||||
"\n" +
|
||||
"Permission\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" +
|
||||
"\x04code\x18\x02 \x01(\tR\x04code\x12\x12\n" +
|
||||
"\x04name\x18\x03 \x01(\tR\x04name\x12 \n" +
|
||||
"\vdescription\x18\x04 \x01(\tR\vdescription\"n\n" +
|
||||
"\x04Role\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" +
|
||||
"\x04name\x18\x02 \x01(\tR\x04name\x12 \n" +
|
||||
"\vdescription\x18\x03 \x01(\tR\vdescription\x12 \n" +
|
||||
"\vpermissions\x18\x04 \x03(\tR\vpermissions\"K\n" +
|
||||
"\x10AuthorizeRequest\x12\x17\n" +
|
||||
"\auser_id\x18\x01 \x01(\tR\x06userId\x12\x1e\n" +
|
||||
"\n" +
|
||||
"permission\x18\x02 \x01(\tR\n" +
|
||||
"permission\"M\n" +
|
||||
"\x11AuthorizeResponse\x12\x1e\n" +
|
||||
"\n" +
|
||||
"authorized\x18\x01 \x01(\bR\n" +
|
||||
"authorized\x12\x18\n" +
|
||||
"\amessage\x18\x02 \x01(\tR\amessage\"O\n" +
|
||||
"\x14HasPermissionRequest\x12\x17\n" +
|
||||
"\auser_id\x18\x01 \x01(\tR\x06userId\x12\x1e\n" +
|
||||
"\n" +
|
||||
"permission\x18\x02 \x01(\tR\n" +
|
||||
"permission\">\n" +
|
||||
"\x15HasPermissionResponse\x12%\n" +
|
||||
"\x0ehas_permission\x18\x01 \x01(\bR\rhasPermission\"4\n" +
|
||||
"\x19GetUserPermissionsRequest\x12\x17\n" +
|
||||
"\auser_id\x18\x01 \x01(\tR\x06userId\"T\n" +
|
||||
"\x1aGetUserPermissionsResponse\x126\n" +
|
||||
"\vpermissions\x18\x01 \x03(\v2\x14.authz.v1.PermissionR\vpermissions\".\n" +
|
||||
"\x13GetUserRolesRequest\x12\x17\n" +
|
||||
"\auser_id\x18\x01 \x01(\tR\x06userId\"<\n" +
|
||||
"\x14GetUserRolesResponse\x12$\n" +
|
||||
"\x05roles\x18\x01 \x03(\v2\x0e.authz.v1.RoleR\x05roles2\xd6\x02\n" +
|
||||
"\fAuthzService\x12D\n" +
|
||||
"\tAuthorize\x12\x1a.authz.v1.AuthorizeRequest\x1a\x1b.authz.v1.AuthorizeResponse\x12P\n" +
|
||||
"\rHasPermission\x12\x1e.authz.v1.HasPermissionRequest\x1a\x1f.authz.v1.HasPermissionResponse\x12_\n" +
|
||||
"\x12GetUserPermissions\x12#.authz.v1.GetUserPermissionsRequest\x1a$.authz.v1.GetUserPermissionsResponse\x12M\n" +
|
||||
"\fGetUserRoles\x12\x1d.authz.v1.GetUserRolesRequest\x1a\x1e.authz.v1.GetUserRolesResponseBGZEgit.dcentral.systems/toolz/goplt/api/proto/generated/authz/v1;authzv1b\x06proto3"
|
||||
|
||||
var (
|
||||
file_authz_proto_rawDescOnce sync.Once
|
||||
file_authz_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_authz_proto_rawDescGZIP() []byte {
|
||||
file_authz_proto_rawDescOnce.Do(func() {
|
||||
file_authz_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_authz_proto_rawDesc), len(file_authz_proto_rawDesc)))
|
||||
})
|
||||
return file_authz_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_authz_proto_msgTypes = make([]protoimpl.MessageInfo, 10)
|
||||
var file_authz_proto_goTypes = []any{
|
||||
(*Permission)(nil), // 0: authz.v1.Permission
|
||||
(*Role)(nil), // 1: authz.v1.Role
|
||||
(*AuthorizeRequest)(nil), // 2: authz.v1.AuthorizeRequest
|
||||
(*AuthorizeResponse)(nil), // 3: authz.v1.AuthorizeResponse
|
||||
(*HasPermissionRequest)(nil), // 4: authz.v1.HasPermissionRequest
|
||||
(*HasPermissionResponse)(nil), // 5: authz.v1.HasPermissionResponse
|
||||
(*GetUserPermissionsRequest)(nil), // 6: authz.v1.GetUserPermissionsRequest
|
||||
(*GetUserPermissionsResponse)(nil), // 7: authz.v1.GetUserPermissionsResponse
|
||||
(*GetUserRolesRequest)(nil), // 8: authz.v1.GetUserRolesRequest
|
||||
(*GetUserRolesResponse)(nil), // 9: authz.v1.GetUserRolesResponse
|
||||
}
|
||||
var file_authz_proto_depIdxs = []int32{
|
||||
0, // 0: authz.v1.GetUserPermissionsResponse.permissions:type_name -> authz.v1.Permission
|
||||
1, // 1: authz.v1.GetUserRolesResponse.roles:type_name -> authz.v1.Role
|
||||
2, // 2: authz.v1.AuthzService.Authorize:input_type -> authz.v1.AuthorizeRequest
|
||||
4, // 3: authz.v1.AuthzService.HasPermission:input_type -> authz.v1.HasPermissionRequest
|
||||
6, // 4: authz.v1.AuthzService.GetUserPermissions:input_type -> authz.v1.GetUserPermissionsRequest
|
||||
8, // 5: authz.v1.AuthzService.GetUserRoles:input_type -> authz.v1.GetUserRolesRequest
|
||||
3, // 6: authz.v1.AuthzService.Authorize:output_type -> authz.v1.AuthorizeResponse
|
||||
5, // 7: authz.v1.AuthzService.HasPermission:output_type -> authz.v1.HasPermissionResponse
|
||||
7, // 8: authz.v1.AuthzService.GetUserPermissions:output_type -> authz.v1.GetUserPermissionsResponse
|
||||
9, // 9: authz.v1.AuthzService.GetUserRoles:output_type -> authz.v1.GetUserRolesResponse
|
||||
6, // [6:10] is the sub-list for method output_type
|
||||
2, // [2:6] is the sub-list for method input_type
|
||||
2, // [2:2] is the sub-list for extension type_name
|
||||
2, // [2:2] is the sub-list for extension extendee
|
||||
0, // [0:2] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_authz_proto_init() }
|
||||
func file_authz_proto_init() {
|
||||
if File_authz_proto != nil {
|
||||
return
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_authz_proto_rawDesc), len(file_authz_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 10,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_authz_proto_goTypes,
|
||||
DependencyIndexes: file_authz_proto_depIdxs,
|
||||
MessageInfos: file_authz_proto_msgTypes,
|
||||
}.Build()
|
||||
File_authz_proto = out.File
|
||||
file_authz_proto_goTypes = nil
|
||||
file_authz_proto_depIdxs = nil
|
||||
}
|
||||
247
api/proto/generated/authz_grpc.pb.go
Normal file
247
api/proto/generated/authz_grpc.pb.go
Normal file
@@ -0,0 +1,247 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v6.30.2
|
||||
// source: authz.proto
|
||||
|
||||
package authzv1
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
AuthzService_Authorize_FullMethodName = "/authz.v1.AuthzService/Authorize"
|
||||
AuthzService_HasPermission_FullMethodName = "/authz.v1.AuthzService/HasPermission"
|
||||
AuthzService_GetUserPermissions_FullMethodName = "/authz.v1.AuthzService/GetUserPermissions"
|
||||
AuthzService_GetUserRoles_FullMethodName = "/authz.v1.AuthzService/GetUserRoles"
|
||||
)
|
||||
|
||||
// AuthzServiceClient is the client API for AuthzService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
//
|
||||
// AuthzService provides authorization operations.
|
||||
type AuthzServiceClient interface {
|
||||
// Authorize checks if a user has a specific permission and returns an error if not.
|
||||
Authorize(ctx context.Context, in *AuthorizeRequest, opts ...grpc.CallOption) (*AuthorizeResponse, error)
|
||||
// HasPermission checks if a user has a specific permission.
|
||||
HasPermission(ctx context.Context, in *HasPermissionRequest, opts ...grpc.CallOption) (*HasPermissionResponse, error)
|
||||
// GetUserPermissions returns all permissions for a user.
|
||||
GetUserPermissions(ctx context.Context, in *GetUserPermissionsRequest, opts ...grpc.CallOption) (*GetUserPermissionsResponse, error)
|
||||
// GetUserRoles returns all roles for a user.
|
||||
GetUserRoles(ctx context.Context, in *GetUserRolesRequest, opts ...grpc.CallOption) (*GetUserRolesResponse, error)
|
||||
}
|
||||
|
||||
type authzServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewAuthzServiceClient(cc grpc.ClientConnInterface) AuthzServiceClient {
|
||||
return &authzServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *authzServiceClient) Authorize(ctx context.Context, in *AuthorizeRequest, opts ...grpc.CallOption) (*AuthorizeResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(AuthorizeResponse)
|
||||
err := c.cc.Invoke(ctx, AuthzService_Authorize_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *authzServiceClient) HasPermission(ctx context.Context, in *HasPermissionRequest, opts ...grpc.CallOption) (*HasPermissionResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(HasPermissionResponse)
|
||||
err := c.cc.Invoke(ctx, AuthzService_HasPermission_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *authzServiceClient) GetUserPermissions(ctx context.Context, in *GetUserPermissionsRequest, opts ...grpc.CallOption) (*GetUserPermissionsResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetUserPermissionsResponse)
|
||||
err := c.cc.Invoke(ctx, AuthzService_GetUserPermissions_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *authzServiceClient) GetUserRoles(ctx context.Context, in *GetUserRolesRequest, opts ...grpc.CallOption) (*GetUserRolesResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetUserRolesResponse)
|
||||
err := c.cc.Invoke(ctx, AuthzService_GetUserRoles_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// AuthzServiceServer is the server API for AuthzService service.
|
||||
// All implementations must embed UnimplementedAuthzServiceServer
|
||||
// for forward compatibility.
|
||||
//
|
||||
// AuthzService provides authorization operations.
|
||||
type AuthzServiceServer interface {
|
||||
// Authorize checks if a user has a specific permission and returns an error if not.
|
||||
Authorize(context.Context, *AuthorizeRequest) (*AuthorizeResponse, error)
|
||||
// HasPermission checks if a user has a specific permission.
|
||||
HasPermission(context.Context, *HasPermissionRequest) (*HasPermissionResponse, error)
|
||||
// GetUserPermissions returns all permissions for a user.
|
||||
GetUserPermissions(context.Context, *GetUserPermissionsRequest) (*GetUserPermissionsResponse, error)
|
||||
// GetUserRoles returns all roles for a user.
|
||||
GetUserRoles(context.Context, *GetUserRolesRequest) (*GetUserRolesResponse, error)
|
||||
mustEmbedUnimplementedAuthzServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedAuthzServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedAuthzServiceServer struct{}
|
||||
|
||||
func (UnimplementedAuthzServiceServer) Authorize(context.Context, *AuthorizeRequest) (*AuthorizeResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Authorize not implemented")
|
||||
}
|
||||
func (UnimplementedAuthzServiceServer) HasPermission(context.Context, *HasPermissionRequest) (*HasPermissionResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method HasPermission not implemented")
|
||||
}
|
||||
func (UnimplementedAuthzServiceServer) GetUserPermissions(context.Context, *GetUserPermissionsRequest) (*GetUserPermissionsResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetUserPermissions not implemented")
|
||||
}
|
||||
func (UnimplementedAuthzServiceServer) GetUserRoles(context.Context, *GetUserRolesRequest) (*GetUserRolesResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetUserRoles not implemented")
|
||||
}
|
||||
func (UnimplementedAuthzServiceServer) mustEmbedUnimplementedAuthzServiceServer() {}
|
||||
func (UnimplementedAuthzServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeAuthzServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to AuthzServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeAuthzServiceServer interface {
|
||||
mustEmbedUnimplementedAuthzServiceServer()
|
||||
}
|
||||
|
||||
func RegisterAuthzServiceServer(s grpc.ServiceRegistrar, srv AuthzServiceServer) {
|
||||
// If the following call pancis, it indicates UnimplementedAuthzServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&AuthzService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _AuthzService_Authorize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(AuthorizeRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(AuthzServiceServer).Authorize(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: AuthzService_Authorize_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(AuthzServiceServer).Authorize(ctx, req.(*AuthorizeRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _AuthzService_HasPermission_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(HasPermissionRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(AuthzServiceServer).HasPermission(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: AuthzService_HasPermission_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(AuthzServiceServer).HasPermission(ctx, req.(*HasPermissionRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _AuthzService_GetUserPermissions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetUserPermissionsRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(AuthzServiceServer).GetUserPermissions(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: AuthzService_GetUserPermissions_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(AuthzServiceServer).GetUserPermissions(ctx, req.(*GetUserPermissionsRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _AuthzService_GetUserRoles_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetUserRolesRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(AuthzServiceServer).GetUserRoles(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: AuthzService_GetUserRoles_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(AuthzServiceServer).GetUserRoles(ctx, req.(*GetUserRolesRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// AuthzService_ServiceDesc is the grpc.ServiceDesc for AuthzService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var AuthzService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "authz.v1.AuthzService",
|
||||
HandlerType: (*AuthzServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "Authorize",
|
||||
Handler: _AuthzService_Authorize_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "HasPermission",
|
||||
Handler: _AuthzService_HasPermission_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetUserPermissions",
|
||||
Handler: _AuthzService_GetUserPermissions_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetUserRoles",
|
||||
Handler: _AuthzService_GetUserRoles_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "authz.proto",
|
||||
}
|
||||
@@ -914,6 +914,104 @@ func (x *ResetPasswordResponse) GetSuccess() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// VerifyPasswordRequest contains email and password.
|
||||
type VerifyPasswordRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"`
|
||||
Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *VerifyPasswordRequest) Reset() {
|
||||
*x = VerifyPasswordRequest{}
|
||||
mi := &file_identity_proto_msgTypes[17]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *VerifyPasswordRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*VerifyPasswordRequest) ProtoMessage() {}
|
||||
|
||||
func (x *VerifyPasswordRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_identity_proto_msgTypes[17]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use VerifyPasswordRequest.ProtoReflect.Descriptor instead.
|
||||
func (*VerifyPasswordRequest) Descriptor() ([]byte, []int) {
|
||||
return file_identity_proto_rawDescGZIP(), []int{17}
|
||||
}
|
||||
|
||||
func (x *VerifyPasswordRequest) GetEmail() string {
|
||||
if x != nil {
|
||||
return x.Email
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *VerifyPasswordRequest) GetPassword() string {
|
||||
if x != nil {
|
||||
return x.Password
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// VerifyPasswordResponse contains the user if password is valid.
|
||||
type VerifyPasswordResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
User *User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *VerifyPasswordResponse) Reset() {
|
||||
*x = VerifyPasswordResponse{}
|
||||
mi := &file_identity_proto_msgTypes[18]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *VerifyPasswordResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*VerifyPasswordResponse) ProtoMessage() {}
|
||||
|
||||
func (x *VerifyPasswordResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_identity_proto_msgTypes[18]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use VerifyPasswordResponse.ProtoReflect.Descriptor instead.
|
||||
func (*VerifyPasswordResponse) Descriptor() ([]byte, []int) {
|
||||
return file_identity_proto_rawDescGZIP(), []int{18}
|
||||
}
|
||||
|
||||
func (x *VerifyPasswordResponse) GetUser() *User {
|
||||
if x != nil {
|
||||
return x.User
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_identity_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_identity_proto_rawDesc = "" +
|
||||
@@ -978,7 +1076,12 @@ const file_identity_proto_rawDesc = "" +
|
||||
"\x05token\x18\x01 \x01(\tR\x05token\x12!\n" +
|
||||
"\fnew_password\x18\x02 \x01(\tR\vnewPassword\"1\n" +
|
||||
"\x15ResetPasswordResponse\x12\x18\n" +
|
||||
"\asuccess\x18\x01 \x01(\bR\asuccess2\xb6\x05\n" +
|
||||
"\asuccess\x18\x01 \x01(\bR\asuccess\"I\n" +
|
||||
"\x15VerifyPasswordRequest\x12\x14\n" +
|
||||
"\x05email\x18\x01 \x01(\tR\x05email\x12\x1a\n" +
|
||||
"\bpassword\x18\x02 \x01(\tR\bpassword\"?\n" +
|
||||
"\x16VerifyPasswordResponse\x12%\n" +
|
||||
"\x04user\x18\x01 \x01(\v2\x11.identity.v1.UserR\x04user2\x91\x06\n" +
|
||||
"\x0fIdentityService\x12D\n" +
|
||||
"\aGetUser\x12\x1b.identity.v1.GetUserRequest\x1a\x1c.identity.v1.GetUserResponse\x12Y\n" +
|
||||
"\x0eGetUserByEmail\x12\".identity.v1.GetUserByEmailRequest\x1a#.identity.v1.GetUserByEmailResponse\x12M\n" +
|
||||
@@ -990,7 +1093,8 @@ const file_identity_proto_rawDesc = "" +
|
||||
"DeleteUser\x12\x1e.identity.v1.DeleteUserRequest\x1a\x1f.identity.v1.DeleteUserResponse\x12P\n" +
|
||||
"\vVerifyEmail\x12\x1f.identity.v1.VerifyEmailRequest\x1a .identity.v1.VerifyEmailResponse\x12k\n" +
|
||||
"\x14RequestPasswordReset\x12(.identity.v1.RequestPasswordResetRequest\x1a).identity.v1.RequestPasswordResetResponse\x12V\n" +
|
||||
"\rResetPassword\x12!.identity.v1.ResetPasswordRequest\x1a\".identity.v1.ResetPasswordResponseBMZKgit.dcentral.systems/toolz/goplt/api/proto/generated/identity/v1;identityv1b\x06proto3"
|
||||
"\rResetPassword\x12!.identity.v1.ResetPasswordRequest\x1a\".identity.v1.ResetPasswordResponse\x12Y\n" +
|
||||
"\x0eVerifyPassword\x12\".identity.v1.VerifyPasswordRequest\x1a#.identity.v1.VerifyPasswordResponseBMZKgit.dcentral.systems/toolz/goplt/api/proto/generated/identity/v1;identityv1b\x06proto3"
|
||||
|
||||
var (
|
||||
file_identity_proto_rawDescOnce sync.Once
|
||||
@@ -1004,7 +1108,7 @@ func file_identity_proto_rawDescGZIP() []byte {
|
||||
return file_identity_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_identity_proto_msgTypes = make([]protoimpl.MessageInfo, 17)
|
||||
var file_identity_proto_msgTypes = make([]protoimpl.MessageInfo, 19)
|
||||
var file_identity_proto_goTypes = []any{
|
||||
(*User)(nil), // 0: identity.v1.User
|
||||
(*GetUserRequest)(nil), // 1: identity.v1.GetUserRequest
|
||||
@@ -1023,33 +1127,38 @@ var file_identity_proto_goTypes = []any{
|
||||
(*RequestPasswordResetResponse)(nil), // 14: identity.v1.RequestPasswordResetResponse
|
||||
(*ResetPasswordRequest)(nil), // 15: identity.v1.ResetPasswordRequest
|
||||
(*ResetPasswordResponse)(nil), // 16: identity.v1.ResetPasswordResponse
|
||||
(*VerifyPasswordRequest)(nil), // 17: identity.v1.VerifyPasswordRequest
|
||||
(*VerifyPasswordResponse)(nil), // 18: identity.v1.VerifyPasswordResponse
|
||||
}
|
||||
var file_identity_proto_depIdxs = []int32{
|
||||
0, // 0: identity.v1.GetUserResponse.user:type_name -> identity.v1.User
|
||||
0, // 1: identity.v1.GetUserByEmailResponse.user:type_name -> identity.v1.User
|
||||
0, // 2: identity.v1.CreateUserResponse.user:type_name -> identity.v1.User
|
||||
0, // 3: identity.v1.UpdateUserResponse.user:type_name -> identity.v1.User
|
||||
1, // 4: identity.v1.IdentityService.GetUser:input_type -> identity.v1.GetUserRequest
|
||||
3, // 5: identity.v1.IdentityService.GetUserByEmail:input_type -> identity.v1.GetUserByEmailRequest
|
||||
5, // 6: identity.v1.IdentityService.CreateUser:input_type -> identity.v1.CreateUserRequest
|
||||
7, // 7: identity.v1.IdentityService.UpdateUser:input_type -> identity.v1.UpdateUserRequest
|
||||
9, // 8: identity.v1.IdentityService.DeleteUser:input_type -> identity.v1.DeleteUserRequest
|
||||
11, // 9: identity.v1.IdentityService.VerifyEmail:input_type -> identity.v1.VerifyEmailRequest
|
||||
13, // 10: identity.v1.IdentityService.RequestPasswordReset:input_type -> identity.v1.RequestPasswordResetRequest
|
||||
15, // 11: identity.v1.IdentityService.ResetPassword:input_type -> identity.v1.ResetPasswordRequest
|
||||
2, // 12: identity.v1.IdentityService.GetUser:output_type -> identity.v1.GetUserResponse
|
||||
4, // 13: identity.v1.IdentityService.GetUserByEmail:output_type -> identity.v1.GetUserByEmailResponse
|
||||
6, // 14: identity.v1.IdentityService.CreateUser:output_type -> identity.v1.CreateUserResponse
|
||||
8, // 15: identity.v1.IdentityService.UpdateUser:output_type -> identity.v1.UpdateUserResponse
|
||||
10, // 16: identity.v1.IdentityService.DeleteUser:output_type -> identity.v1.DeleteUserResponse
|
||||
12, // 17: identity.v1.IdentityService.VerifyEmail:output_type -> identity.v1.VerifyEmailResponse
|
||||
14, // 18: identity.v1.IdentityService.RequestPasswordReset:output_type -> identity.v1.RequestPasswordResetResponse
|
||||
16, // 19: identity.v1.IdentityService.ResetPassword:output_type -> identity.v1.ResetPasswordResponse
|
||||
12, // [12:20] is the sub-list for method output_type
|
||||
4, // [4:12] is the sub-list for method input_type
|
||||
4, // [4:4] is the sub-list for extension type_name
|
||||
4, // [4:4] is the sub-list for extension extendee
|
||||
0, // [0:4] is the sub-list for field type_name
|
||||
0, // 4: identity.v1.VerifyPasswordResponse.user:type_name -> identity.v1.User
|
||||
1, // 5: identity.v1.IdentityService.GetUser:input_type -> identity.v1.GetUserRequest
|
||||
3, // 6: identity.v1.IdentityService.GetUserByEmail:input_type -> identity.v1.GetUserByEmailRequest
|
||||
5, // 7: identity.v1.IdentityService.CreateUser:input_type -> identity.v1.CreateUserRequest
|
||||
7, // 8: identity.v1.IdentityService.UpdateUser:input_type -> identity.v1.UpdateUserRequest
|
||||
9, // 9: identity.v1.IdentityService.DeleteUser:input_type -> identity.v1.DeleteUserRequest
|
||||
11, // 10: identity.v1.IdentityService.VerifyEmail:input_type -> identity.v1.VerifyEmailRequest
|
||||
13, // 11: identity.v1.IdentityService.RequestPasswordReset:input_type -> identity.v1.RequestPasswordResetRequest
|
||||
15, // 12: identity.v1.IdentityService.ResetPassword:input_type -> identity.v1.ResetPasswordRequest
|
||||
17, // 13: identity.v1.IdentityService.VerifyPassword:input_type -> identity.v1.VerifyPasswordRequest
|
||||
2, // 14: identity.v1.IdentityService.GetUser:output_type -> identity.v1.GetUserResponse
|
||||
4, // 15: identity.v1.IdentityService.GetUserByEmail:output_type -> identity.v1.GetUserByEmailResponse
|
||||
6, // 16: identity.v1.IdentityService.CreateUser:output_type -> identity.v1.CreateUserResponse
|
||||
8, // 17: identity.v1.IdentityService.UpdateUser:output_type -> identity.v1.UpdateUserResponse
|
||||
10, // 18: identity.v1.IdentityService.DeleteUser:output_type -> identity.v1.DeleteUserResponse
|
||||
12, // 19: identity.v1.IdentityService.VerifyEmail:output_type -> identity.v1.VerifyEmailResponse
|
||||
14, // 20: identity.v1.IdentityService.RequestPasswordReset:output_type -> identity.v1.RequestPasswordResetResponse
|
||||
16, // 21: identity.v1.IdentityService.ResetPassword:output_type -> identity.v1.ResetPasswordResponse
|
||||
18, // 22: identity.v1.IdentityService.VerifyPassword:output_type -> identity.v1.VerifyPasswordResponse
|
||||
14, // [14:23] is the sub-list for method output_type
|
||||
5, // [5:14] is the sub-list for method input_type
|
||||
5, // [5:5] is the sub-list for extension type_name
|
||||
5, // [5:5] is the sub-list for extension extendee
|
||||
0, // [0:5] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_identity_proto_init() }
|
||||
@@ -1064,7 +1173,7 @@ func file_identity_proto_init() {
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_identity_proto_rawDesc), len(file_identity_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 17,
|
||||
NumMessages: 19,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
|
||||
@@ -27,6 +27,7 @@ const (
|
||||
IdentityService_VerifyEmail_FullMethodName = "/identity.v1.IdentityService/VerifyEmail"
|
||||
IdentityService_RequestPasswordReset_FullMethodName = "/identity.v1.IdentityService/RequestPasswordReset"
|
||||
IdentityService_ResetPassword_FullMethodName = "/identity.v1.IdentityService/ResetPassword"
|
||||
IdentityService_VerifyPassword_FullMethodName = "/identity.v1.IdentityService/VerifyPassword"
|
||||
)
|
||||
|
||||
// IdentityServiceClient is the client API for IdentityService service.
|
||||
@@ -51,6 +52,8 @@ type IdentityServiceClient interface {
|
||||
RequestPasswordReset(ctx context.Context, in *RequestPasswordResetRequest, opts ...grpc.CallOption) (*RequestPasswordResetResponse, error)
|
||||
// ResetPassword resets a user's password using a reset token.
|
||||
ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*ResetPasswordResponse, error)
|
||||
// VerifyPassword verifies a user's password.
|
||||
VerifyPassword(ctx context.Context, in *VerifyPasswordRequest, opts ...grpc.CallOption) (*VerifyPasswordResponse, error)
|
||||
}
|
||||
|
||||
type identityServiceClient struct {
|
||||
@@ -141,6 +144,16 @@ func (c *identityServiceClient) ResetPassword(ctx context.Context, in *ResetPass
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *identityServiceClient) VerifyPassword(ctx context.Context, in *VerifyPasswordRequest, opts ...grpc.CallOption) (*VerifyPasswordResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(VerifyPasswordResponse)
|
||||
err := c.cc.Invoke(ctx, IdentityService_VerifyPassword_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// IdentityServiceServer is the server API for IdentityService service.
|
||||
// All implementations must embed UnimplementedIdentityServiceServer
|
||||
// for forward compatibility.
|
||||
@@ -163,6 +176,8 @@ type IdentityServiceServer interface {
|
||||
RequestPasswordReset(context.Context, *RequestPasswordResetRequest) (*RequestPasswordResetResponse, error)
|
||||
// ResetPassword resets a user's password using a reset token.
|
||||
ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error)
|
||||
// VerifyPassword verifies a user's password.
|
||||
VerifyPassword(context.Context, *VerifyPasswordRequest) (*VerifyPasswordResponse, error)
|
||||
mustEmbedUnimplementedIdentityServiceServer()
|
||||
}
|
||||
|
||||
@@ -197,6 +212,9 @@ func (UnimplementedIdentityServiceServer) RequestPasswordReset(context.Context,
|
||||
func (UnimplementedIdentityServiceServer) ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ResetPassword not implemented")
|
||||
}
|
||||
func (UnimplementedIdentityServiceServer) VerifyPassword(context.Context, *VerifyPasswordRequest) (*VerifyPasswordResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method VerifyPassword not implemented")
|
||||
}
|
||||
func (UnimplementedIdentityServiceServer) mustEmbedUnimplementedIdentityServiceServer() {}
|
||||
func (UnimplementedIdentityServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
@@ -362,6 +380,24 @@ func _IdentityService_ResetPassword_Handler(srv interface{}, ctx context.Context
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _IdentityService_VerifyPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(VerifyPasswordRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(IdentityServiceServer).VerifyPassword(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: IdentityService_VerifyPassword_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(IdentityServiceServer).VerifyPassword(ctx, req.(*VerifyPasswordRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// IdentityService_ServiceDesc is the grpc.ServiceDesc for IdentityService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
@@ -401,6 +437,10 @@ var IdentityService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "ResetPassword",
|
||||
Handler: _IdentityService_ResetPassword_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "VerifyPassword",
|
||||
Handler: _IdentityService_VerifyPassword_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "identity.proto",
|
||||
|
||||
@@ -29,6 +29,9 @@ service IdentityService {
|
||||
|
||||
// ResetPassword resets a user's password using a reset token.
|
||||
rpc ResetPassword(ResetPasswordRequest) returns (ResetPasswordResponse);
|
||||
|
||||
// VerifyPassword verifies a user's password.
|
||||
rpc VerifyPassword(VerifyPasswordRequest) returns (VerifyPasswordResponse);
|
||||
}
|
||||
|
||||
// User represents a user in the system.
|
||||
@@ -132,3 +135,14 @@ message ResetPasswordResponse {
|
||||
bool success = 1;
|
||||
}
|
||||
|
||||
// VerifyPasswordRequest contains email and password.
|
||||
message VerifyPasswordRequest {
|
||||
string email = 1;
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
// VerifyPasswordResponse contains the user if password is valid.
|
||||
message VerifyPasswordResponse {
|
||||
User user = 1;
|
||||
}
|
||||
|
||||
|
||||
BIN
auth-service
BIN
auth-service
Binary file not shown.
BIN
authz-service
BIN
authz-service
Binary file not shown.
36
cmd/api-gateway/Dockerfile
Normal file
36
cmd/api-gateway/Dockerfile
Normal file
@@ -0,0 +1,36 @@
|
||||
# Build stage
|
||||
FROM golang:1.25-alpine AS builder
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# Install build dependencies
|
||||
RUN apk add --no-cache git make
|
||||
|
||||
# Copy go mod files
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
# Copy source code
|
||||
COPY . .
|
||||
|
||||
# Build the service
|
||||
WORKDIR /build/cmd/api-gateway
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o api-gateway -a -installsuffix cgo .
|
||||
|
||||
# Runtime stage
|
||||
FROM alpine:latest
|
||||
|
||||
RUN apk --no-cache add ca-certificates tzdata
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy binary from builder
|
||||
COPY --from=builder /build/cmd/api-gateway/api-gateway .
|
||||
|
||||
# Copy config files
|
||||
COPY --from=builder /build/config ./config
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
CMD ["./api-gateway"]
|
||||
|
||||
@@ -58,14 +58,25 @@ func main() {
|
||||
}
|
||||
gateway.SetupRoutes(srv.Router())
|
||||
|
||||
// Register with Consul
|
||||
// Determine port and host for registration
|
||||
gatewayPort := cfg.GetInt("gateway.port")
|
||||
if gatewayPort == 0 {
|
||||
gatewayPort = 8080
|
||||
gatewayPort = cfg.GetInt("server.port")
|
||||
if gatewayPort == 0 {
|
||||
gatewayPort = 8080
|
||||
}
|
||||
}
|
||||
|
||||
// In Docker, always use the Docker service name for health checks
|
||||
// Consul (also in Docker) needs to reach the service via Docker DNS
|
||||
gatewayHost := cfg.GetString("gateway.host")
|
||||
if gatewayHost == "" {
|
||||
gatewayHost = "localhost"
|
||||
if os.Getenv("ENVIRONMENT") == "production" || os.Getenv("DOCKER") == "true" {
|
||||
gatewayHost = "api-gateway" // Docker service name - required for Consul health checks
|
||||
} else if gatewayHost == "" {
|
||||
gatewayHost = cfg.GetString("server.host")
|
||||
if gatewayHost == "" || gatewayHost == "0.0.0.0" {
|
||||
gatewayHost = "localhost" // Local development
|
||||
}
|
||||
}
|
||||
|
||||
serviceInstance := ®istry.ServiceInstance{
|
||||
@@ -75,7 +86,8 @@ func main() {
|
||||
Port: gatewayPort,
|
||||
Tags: []string{"gateway", "http"},
|
||||
Metadata: map[string]string{
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.0",
|
||||
"protocol": "http",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
156
cmd/api-gateway/main_test.go
Normal file
156
cmd/api-gateway/main_test.go
Normal file
@@ -0,0 +1,156 @@
|
||||
// Package main provides tests for the API Gateway service entry point.
|
||||
// Note: Full integration tests for the API Gateway should be in integration test suite
|
||||
// with testcontainers for service discovery and backend services.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/internal/di"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/registry"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.uber.org/fx"
|
||||
)
|
||||
|
||||
// TestAPIGatewaySetup verifies that the API Gateway setup structure is correct.
|
||||
// Note: Full DI setup requires config files, so this test verifies the structure
|
||||
// without actually starting the container.
|
||||
func TestAPIGatewaySetup(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Verify that container can be created
|
||||
// Full setup requires config files which are not available in unit tests
|
||||
container := di.NewContainer()
|
||||
require.NotNil(t, container)
|
||||
|
||||
// Test that container can be stopped (without starting)
|
||||
// This verifies the container structure is correct
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Stop should work even if container wasn't started
|
||||
err := container.Stop(ctx)
|
||||
// It's okay if it errors - we're just testing structure
|
||||
_ = err
|
||||
}
|
||||
|
||||
// TestServiceInstanceCreation verifies that service instance is created correctly.
|
||||
func TestServiceInstanceCreation(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
host string
|
||||
port int
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "default host and port",
|
||||
host: "",
|
||||
port: 0,
|
||||
expected: "localhost:8080",
|
||||
},
|
||||
{
|
||||
name: "custom host and port",
|
||||
host: "gateway.example.com",
|
||||
port: 9090,
|
||||
expected: "gateway.example.com:9090",
|
||||
},
|
||||
{
|
||||
name: "custom host default port",
|
||||
host: "gateway.example.com",
|
||||
port: 0,
|
||||
expected: "gateway.example.com:8080",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Simulate service instance creation logic from main.go
|
||||
gatewayPort := tt.port
|
||||
if gatewayPort == 0 {
|
||||
gatewayPort = 8080
|
||||
}
|
||||
gatewayHost := tt.host
|
||||
if gatewayHost == "" {
|
||||
gatewayHost = "localhost"
|
||||
}
|
||||
|
||||
serviceInstance := ®istry.ServiceInstance{
|
||||
ID: "api-gateway-test",
|
||||
Name: "api-gateway",
|
||||
Address: gatewayHost,
|
||||
Port: gatewayPort,
|
||||
Tags: []string{"gateway", "http"},
|
||||
Metadata: map[string]string{
|
||||
"version": "1.0.0",
|
||||
},
|
||||
}
|
||||
|
||||
assert.Equal(t, "api-gateway", serviceInstance.Name)
|
||||
assert.Equal(t, gatewayHost, serviceInstance.Address)
|
||||
assert.Equal(t, gatewayPort, serviceInstance.Port)
|
||||
assert.Contains(t, serviceInstance.Tags, "gateway")
|
||||
assert.Contains(t, serviceInstance.Tags, "http")
|
||||
assert.Equal(t, "1.0.0", serviceInstance.Metadata["version"])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLifecycleHooksStructure verifies that lifecycle hooks can be registered.
|
||||
// Note: Full lifecycle testing requires config files and should be done in integration tests.
|
||||
func TestLifecycleHooksStructure(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var onStartCalled bool
|
||||
var onStopCalled bool
|
||||
|
||||
// Create a test container with custom lifecycle hooks (without core module)
|
||||
// This tests the hook registration mechanism
|
||||
container := di.NewContainer(
|
||||
fx.Invoke(func(lc fx.Lifecycle) {
|
||||
lc.Append(fx.Hook{
|
||||
OnStart: func(ctx context.Context) error {
|
||||
onStartCalled = true
|
||||
return nil
|
||||
},
|
||||
OnStop: func(ctx context.Context) error {
|
||||
onStopCalled = true
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
require.NotNil(t, container)
|
||||
|
||||
// Start the container to trigger OnStart
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
// Start in goroutine since it blocks on signal
|
||||
go func() {
|
||||
_ = container.Start(ctx)
|
||||
}()
|
||||
|
||||
// Give it a moment to start
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
// Stop to trigger OnStop
|
||||
stopCtx, stopCancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer stopCancel()
|
||||
|
||||
err := container.Stop(stopCtx)
|
||||
// Stop may error if container wasn't fully started, which is okay
|
||||
_ = err
|
||||
|
||||
// Verify hooks were called
|
||||
// Note: OnStart may not be called if container fails to start due to missing config
|
||||
// This is expected in unit tests - full testing should be in integration tests
|
||||
if onStartCalled {
|
||||
assert.True(t, onStopCalled, "OnStop should be called if OnStart was called")
|
||||
}
|
||||
}
|
||||
343
cmd/audit-service/audit_service_fx.go
Normal file
343
cmd/audit-service/audit_service_fx.go
Normal file
@@ -0,0 +1,343 @@
|
||||
// Package main provides FX providers for Audit Service.
|
||||
// This file creates the service inline to avoid importing internal packages.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
auditv1 "git.dcentral.systems/toolz/goplt/api/proto/generated/audit/v1"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/auditlog"
|
||||
"git.dcentral.systems/toolz/goplt/internal/infra/database"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/config"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
"go.uber.org/fx"
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/health"
|
||||
"google.golang.org/grpc/health/grpc_health_v1"
|
||||
"google.golang.org/grpc/reflection"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// auditLogEntry represents an audit log entry.
|
||||
type auditLogEntry struct {
|
||||
UserID string
|
||||
Action string
|
||||
Resource string
|
||||
ResourceID string
|
||||
IPAddress string
|
||||
UserAgent string
|
||||
Metadata map[string]string
|
||||
Timestamp int64
|
||||
}
|
||||
|
||||
// auditLogFilters contains filters for querying audit logs.
|
||||
type auditLogFilters struct {
|
||||
UserID *string
|
||||
Action *string
|
||||
Resource *string
|
||||
ResourceID *string
|
||||
StartTime *int64
|
||||
EndTime *int64
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// auditService provides audit logging functionality.
|
||||
type auditService struct {
|
||||
client *database.Client
|
||||
logger logger.Logger
|
||||
}
|
||||
|
||||
// record records an audit log entry.
|
||||
func (s *auditService) record(ctx context.Context, entry *auditLogEntry) error {
|
||||
// Convert metadata map to JSON
|
||||
metadataJSON := make(map[string]interface{})
|
||||
for k, v := range entry.Metadata {
|
||||
metadataJSON[k] = v
|
||||
}
|
||||
|
||||
// Create audit log entry
|
||||
timestamp := time.Unix(entry.Timestamp, 0)
|
||||
if entry.Timestamp == 0 {
|
||||
timestamp = time.Now()
|
||||
}
|
||||
|
||||
create := s.client.AuditLog.Create().
|
||||
SetID(fmt.Sprintf("%d-%d", time.Now().Unix(), time.Now().UnixNano()%1000000)).
|
||||
SetUserID(entry.UserID).
|
||||
SetAction(entry.Action).
|
||||
SetMetadata(metadataJSON).
|
||||
SetTimestamp(timestamp)
|
||||
|
||||
if entry.Resource != "" {
|
||||
create = create.SetResource(entry.Resource)
|
||||
}
|
||||
if entry.ResourceID != "" {
|
||||
create = create.SetResourceID(entry.ResourceID)
|
||||
}
|
||||
if entry.IPAddress != "" {
|
||||
create = create.SetIPAddress(entry.IPAddress)
|
||||
}
|
||||
if entry.UserAgent != "" {
|
||||
create = create.SetUserAgent(entry.UserAgent)
|
||||
}
|
||||
|
||||
_, err := create.Save(ctx)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to record audit log",
|
||||
zap.Error(err),
|
||||
zap.String("user_id", entry.UserID),
|
||||
zap.String("action", entry.Action),
|
||||
)
|
||||
return fmt.Errorf("failed to record audit log: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// query queries audit logs based on filters.
|
||||
func (s *auditService) query(ctx context.Context, filters *auditLogFilters) ([]*auditLogEntry, error) {
|
||||
query := s.client.AuditLog.Query()
|
||||
|
||||
// Apply filters
|
||||
if filters.UserID != nil {
|
||||
query = query.Where(auditlog.UserID(*filters.UserID))
|
||||
}
|
||||
if filters.Action != nil {
|
||||
query = query.Where(auditlog.Action(*filters.Action))
|
||||
}
|
||||
if filters.Resource != nil {
|
||||
query = query.Where(auditlog.Resource(*filters.Resource))
|
||||
}
|
||||
if filters.ResourceID != nil {
|
||||
query = query.Where(auditlog.ResourceID(*filters.ResourceID))
|
||||
}
|
||||
if filters.StartTime != nil {
|
||||
query = query.Where(auditlog.TimestampGTE(time.Unix(*filters.StartTime, 0)))
|
||||
}
|
||||
if filters.EndTime != nil {
|
||||
query = query.Where(auditlog.TimestampLTE(time.Unix(*filters.EndTime, 0)))
|
||||
}
|
||||
|
||||
// Apply pagination
|
||||
if filters.Limit > 0 {
|
||||
query = query.Limit(filters.Limit)
|
||||
}
|
||||
if filters.Offset > 0 {
|
||||
query = query.Offset(filters.Offset)
|
||||
}
|
||||
|
||||
// Order by timestamp descending
|
||||
query = query.Order(ent.Desc(auditlog.FieldTimestamp))
|
||||
|
||||
// Execute query
|
||||
auditLogs, err := query.All(ctx)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to query audit logs",
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, fmt.Errorf("failed to query audit logs: %w", err)
|
||||
}
|
||||
|
||||
// Convert to service entries
|
||||
entries := make([]*auditLogEntry, 0, len(auditLogs))
|
||||
for _, log := range auditLogs {
|
||||
// Convert metadata from map[string]interface{} to map[string]string
|
||||
metadata := make(map[string]string)
|
||||
if log.Metadata != nil {
|
||||
for k, v := range log.Metadata {
|
||||
if str, ok := v.(string); ok {
|
||||
metadata[k] = str
|
||||
} else {
|
||||
metadata[k] = fmt.Sprintf("%v", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
entry := &auditLogEntry{
|
||||
UserID: log.UserID,
|
||||
Action: log.Action,
|
||||
Resource: log.Resource,
|
||||
ResourceID: log.ResourceID,
|
||||
IPAddress: log.IPAddress,
|
||||
UserAgent: log.UserAgent,
|
||||
Metadata: metadata,
|
||||
Timestamp: log.Timestamp.Unix(),
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// auditServerImpl implements the AuditService gRPC server.
|
||||
type auditServerImpl struct {
|
||||
auditv1.UnimplementedAuditServiceServer
|
||||
service *auditService
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// Record records an audit log entry.
|
||||
func (s *auditServerImpl) Record(ctx context.Context, req *auditv1.RecordRequest) (*auditv1.RecordResponse, error) {
|
||||
if req.Entry == nil {
|
||||
return nil, status.Error(codes.InvalidArgument, "entry is required")
|
||||
}
|
||||
|
||||
entry := req.Entry
|
||||
|
||||
// Convert proto entry to service entry
|
||||
serviceEntry := &auditLogEntry{
|
||||
UserID: entry.UserId,
|
||||
Action: entry.Action,
|
||||
Resource: entry.Resource,
|
||||
ResourceID: entry.ResourceId,
|
||||
IPAddress: entry.IpAddress,
|
||||
UserAgent: entry.UserAgent,
|
||||
Metadata: entry.Metadata,
|
||||
Timestamp: entry.Timestamp,
|
||||
}
|
||||
|
||||
// Record the audit log
|
||||
if err := s.service.record(ctx, serviceEntry); err != nil {
|
||||
s.logger.Error("Failed to record audit log",
|
||||
zap.Error(err),
|
||||
zap.String("user_id", entry.UserId),
|
||||
zap.String("action", entry.Action),
|
||||
)
|
||||
return nil, status.Errorf(codes.Internal, "failed to record audit log: %v", err)
|
||||
}
|
||||
|
||||
return &auditv1.RecordResponse{
|
||||
Success: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Query queries audit logs based on filters.
|
||||
func (s *auditServerImpl) Query(ctx context.Context, req *auditv1.QueryRequest) (*auditv1.QueryResponse, error) {
|
||||
// Convert proto filters to service filters
|
||||
filters := &auditLogFilters{
|
||||
Limit: int(req.Limit),
|
||||
Offset: int(req.Offset),
|
||||
}
|
||||
|
||||
if req.UserId != nil {
|
||||
userID := *req.UserId
|
||||
filters.UserID = &userID
|
||||
}
|
||||
if req.Action != nil {
|
||||
action := *req.Action
|
||||
filters.Action = &action
|
||||
}
|
||||
if req.Resource != nil {
|
||||
resource := *req.Resource
|
||||
filters.Resource = &resource
|
||||
}
|
||||
if req.ResourceId != nil {
|
||||
resourceID := *req.ResourceId
|
||||
filters.ResourceID = &resourceID
|
||||
}
|
||||
if req.StartTime != nil {
|
||||
startTime := *req.StartTime
|
||||
filters.StartTime = &startTime
|
||||
}
|
||||
if req.EndTime != nil {
|
||||
endTime := *req.EndTime
|
||||
filters.EndTime = &endTime
|
||||
}
|
||||
|
||||
// Query audit logs
|
||||
entries, err := s.service.query(ctx, filters)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to query audit logs",
|
||||
zap.Error(err),
|
||||
)
|
||||
return nil, status.Errorf(codes.Internal, "failed to query audit logs: %v", err)
|
||||
}
|
||||
|
||||
// Convert service entries to proto entries
|
||||
protoEntries := make([]*auditv1.AuditLogEntry, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
protoEntries = append(protoEntries, &auditv1.AuditLogEntry{
|
||||
UserId: entry.UserID,
|
||||
Action: entry.Action,
|
||||
Resource: entry.Resource,
|
||||
ResourceId: entry.ResourceID,
|
||||
IpAddress: entry.IPAddress,
|
||||
UserAgent: entry.UserAgent,
|
||||
Metadata: entry.Metadata,
|
||||
Timestamp: entry.Timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
return &auditv1.QueryResponse{
|
||||
Entries: protoEntries,
|
||||
Total: int32(len(protoEntries)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// provideAuditService creates the audit service and gRPC server.
|
||||
func provideAuditService() fx.Option {
|
||||
return fx.Options(
|
||||
// Audit service
|
||||
fx.Provide(func(client *database.Client, log logger.Logger) (*auditService, error) {
|
||||
return &auditService{
|
||||
client: client,
|
||||
logger: log,
|
||||
}, nil
|
||||
}),
|
||||
|
||||
// gRPC server implementation
|
||||
fx.Provide(func(auditService *auditService, log logger.Logger) (*auditServerImpl, error) {
|
||||
zapLogger, _ := zap.NewProduction()
|
||||
return &auditServerImpl{
|
||||
service: auditService,
|
||||
logger: zapLogger,
|
||||
}, nil
|
||||
}),
|
||||
|
||||
// gRPC server wrapper
|
||||
fx.Provide(func(
|
||||
serverImpl *auditServerImpl,
|
||||
cfg config.ConfigProvider,
|
||||
log logger.Logger,
|
||||
) (*grpcServerWrapper, error) {
|
||||
port := cfg.GetInt("services.audit.port")
|
||||
if port == 0 {
|
||||
port = 8084
|
||||
}
|
||||
|
||||
addr := fmt.Sprintf("0.0.0.0:%d", port)
|
||||
listener, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to listen on %s: %w", addr, err)
|
||||
}
|
||||
|
||||
grpcServer := grpc.NewServer()
|
||||
auditv1.RegisterAuditServiceServer(grpcServer, serverImpl)
|
||||
|
||||
// Register health service
|
||||
healthServer := health.NewServer()
|
||||
grpc_health_v1.RegisterHealthServer(grpcServer, healthServer)
|
||||
// Set serving status for the default service (empty string) - this is what Consul checks
|
||||
healthServer.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)
|
||||
// Also set for the specific service name
|
||||
healthServer.SetServingStatus("audit.v1.AuditService", grpc_health_v1.HealthCheckResponse_SERVING)
|
||||
|
||||
// Register reflection for grpcurl
|
||||
reflection.Register(grpcServer)
|
||||
|
||||
return &grpcServerWrapper{
|
||||
server: grpcServer,
|
||||
listener: listener,
|
||||
port: port,
|
||||
logger: log,
|
||||
}, nil
|
||||
}),
|
||||
)
|
||||
}
|
||||
228
cmd/audit-service/main.go
Normal file
228
cmd/audit-service/main.go
Normal file
@@ -0,0 +1,228 @@
|
||||
// Package main provides the entry point for the Audit Service.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/internal/di"
|
||||
healthpkg "git.dcentral.systems/toolz/goplt/internal/health"
|
||||
"git.dcentral.systems/toolz/goplt/internal/infra/database"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/config"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/registry"
|
||||
"go.uber.org/fx"
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// grpcServerWrapper wraps the gRPC server for lifecycle management.
|
||||
type grpcServerWrapper struct {
|
||||
server *grpc.Server
|
||||
listener net.Listener
|
||||
port int
|
||||
logger logger.Logger
|
||||
}
|
||||
|
||||
func (s *grpcServerWrapper) Start() error {
|
||||
s.logger.Info("Starting Audit Service gRPC server",
|
||||
zap.Int("port", s.port),
|
||||
zap.String("addr", s.listener.Addr().String()),
|
||||
)
|
||||
|
||||
errChan := make(chan error, 1)
|
||||
go func() {
|
||||
if err := s.server.Serve(s.listener); err != nil {
|
||||
errChan <- err
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-errChan:
|
||||
return fmt.Errorf("gRPC server failed to start: %w", err)
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
s.logger.Info("Audit Service gRPC server started successfully",
|
||||
zap.Int("port", s.port),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *grpcServerWrapper) Stop(ctx context.Context) error {
|
||||
s.logger.Info("Stopping Audit Service gRPC server")
|
||||
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
s.server.GracefulStop()
|
||||
close(stopped)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-stopped:
|
||||
s.logger.Info("Audit Service gRPC server stopped gracefully")
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
s.logger.Warn("Audit Service gRPC server stop timeout, forcing stop")
|
||||
s.server.Stop()
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *grpcServerWrapper) Port() int {
|
||||
return s.port
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Create DI container - services will be created via fx.Provide
|
||||
// Note: CoreModule() is automatically included by NewContainer()
|
||||
container := di.NewContainer(
|
||||
// Database for audit service (audit schema)
|
||||
fx.Provide(func(cfg config.ConfigProvider, log logger.Logger) (*database.Client, error) {
|
||||
dsn := cfg.GetString("database.dsn")
|
||||
if dsn == "" {
|
||||
return nil, fmt.Errorf("database.dsn is required")
|
||||
}
|
||||
client, err := database.NewClientWithSchema(dsn, "audit")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Run migrations
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := client.Migrate(ctx); err != nil {
|
||||
log.Warn("Failed to run migrations",
|
||||
zap.Error(err),
|
||||
)
|
||||
} else {
|
||||
log.Info("Database migrations completed for audit service")
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}),
|
||||
|
||||
// Register database health checker with existing health registry
|
||||
fx.Invoke(func(registry *healthpkg.Registry, db *database.Client) {
|
||||
registry.Register("database", healthpkg.NewDatabaseChecker(db))
|
||||
}),
|
||||
|
||||
// Provide audit service and gRPC server (defined in audit_service_fx.go)
|
||||
provideAuditService(),
|
||||
|
||||
// Lifecycle hooks
|
||||
fx.Invoke(registerLifecycle),
|
||||
)
|
||||
|
||||
// Create root context
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
// Handle signals
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
// Start the application
|
||||
if err := container.Start(ctx); err != nil {
|
||||
log := logger.GetGlobalLogger()
|
||||
if log != nil {
|
||||
log.Error("Failed to start Audit Service",
|
||||
logger.Error(err),
|
||||
)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Failed to start Audit Service: %v\n", err)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Wait for interrupt signal
|
||||
<-sigChan
|
||||
fmt.Println("\nShutting down Audit Service...")
|
||||
|
||||
// Create shutdown context with timeout
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer shutdownCancel()
|
||||
|
||||
// Stop the application
|
||||
if err := container.Stop(shutdownCtx); err != nil {
|
||||
log := logger.GetGlobalLogger()
|
||||
if log != nil {
|
||||
log.Error("Error during Audit Service shutdown",
|
||||
logger.Error(err),
|
||||
)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error during shutdown: %v\n", err)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Println("Audit Service stopped successfully")
|
||||
}
|
||||
|
||||
// registerLifecycle registers lifecycle hooks for the service.
|
||||
func registerLifecycle(
|
||||
lc fx.Lifecycle,
|
||||
grpcServer *grpcServerWrapper,
|
||||
serviceRegistry registry.ServiceRegistry,
|
||||
cfg config.ConfigProvider,
|
||||
log logger.Logger,
|
||||
) {
|
||||
lc.Append(fx.Hook{
|
||||
OnStart: func(ctx context.Context) error {
|
||||
// Start gRPC server
|
||||
if err := grpcServer.Start(); err != nil {
|
||||
return fmt.Errorf("failed to start gRPC server: %w", err)
|
||||
}
|
||||
|
||||
// Register with service registry
|
||||
serviceID := fmt.Sprintf("audit-service-%d", time.Now().Unix())
|
||||
// In Docker, always use the Docker service name for health checks
|
||||
// Consul (also in Docker) needs to reach the service via Docker DNS
|
||||
host := cfg.GetString("services.audit.host")
|
||||
if os.Getenv("ENVIRONMENT") == "production" || os.Getenv("DOCKER") == "true" {
|
||||
host = "audit-service" // Docker service name - required for Consul health checks
|
||||
} else if host == "" {
|
||||
host = "localhost" // Local development
|
||||
}
|
||||
port := grpcServer.Port()
|
||||
|
||||
instance := ®istry.ServiceInstance{
|
||||
ID: serviceID,
|
||||
Name: "audit-service",
|
||||
Address: host,
|
||||
Port: port,
|
||||
Tags: []string{"grpc", "audit"},
|
||||
Metadata: map[string]string{
|
||||
"version": "1.0.0",
|
||||
"protocol": "grpc",
|
||||
},
|
||||
}
|
||||
|
||||
if err := serviceRegistry.Register(ctx, instance); err != nil {
|
||||
log.Warn("Failed to register with service registry",
|
||||
zap.Error(err),
|
||||
)
|
||||
} else {
|
||||
log.Info("Registered Audit Service with service registry",
|
||||
zap.String("service_id", serviceID),
|
||||
zap.String("name", instance.Name),
|
||||
zap.Int("port", port),
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
OnStop: func(ctx context.Context) error {
|
||||
// Stop gRPC server
|
||||
if err := grpcServer.Stop(ctx); err != nil {
|
||||
return fmt.Errorf("failed to stop gRPC server: %w", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -12,7 +12,8 @@ import (
|
||||
"time"
|
||||
|
||||
authv1 "git.dcentral.systems/toolz/goplt/api/proto/generated/auth/v1"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken"
|
||||
"git.dcentral.systems/toolz/goplt/internal/infra/database"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/config"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/services"
|
||||
@@ -34,9 +35,10 @@ const (
|
||||
|
||||
// authService provides authentication functionality.
|
||||
type authService struct {
|
||||
client *ent.Client
|
||||
client *database.Client
|
||||
logger logger.Logger
|
||||
identityClient services.IdentityServiceClient
|
||||
authzClient services.AuthzServiceClient
|
||||
jwtSecret []byte
|
||||
accessTokenExpiry time.Duration
|
||||
refreshTokenExpiry time.Duration
|
||||
@@ -79,18 +81,25 @@ func (s *authService) generateAccessToken(userID, email string, roles []string)
|
||||
}
|
||||
|
||||
// generateRefreshToken generates a refresh token and stores it in the database.
|
||||
// Note: This is a simplified version - RefreshToken entity needs to be generated first
|
||||
func (s *authService) generateRefreshToken(ctx context.Context, userID string) (string, error) {
|
||||
token, err := generateRefreshToken()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// TODO: Store refresh token in database using RefreshToken entity once generated
|
||||
// For now, we'll just return the token
|
||||
// tokenHash := hashToken(token)
|
||||
// expiresAt := time.Now().Add(s.refreshTokenExpiry)
|
||||
// _, err = s.client.RefreshToken.Create()...
|
||||
tokenHash := hashToken(token)
|
||||
expiresAt := time.Now().Add(s.refreshTokenExpiry)
|
||||
|
||||
// Store refresh token in database
|
||||
_, err = s.client.RefreshToken.Create().
|
||||
SetID(fmt.Sprintf("%d-%d", time.Now().Unix(), time.Now().UnixNano()%1000000)).
|
||||
SetUserID(userID).
|
||||
SetTokenHash(tokenHash).
|
||||
SetExpiresAt(expiresAt).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to store refresh token: %w", err)
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
||||
@@ -128,41 +137,67 @@ func (s *authService) validateAccessToken(tokenString string) (*jwt.Token, jwt.M
|
||||
}
|
||||
|
||||
// validateRefreshToken validates a refresh token.
|
||||
// Note: This is a simplified version - RefreshToken entity needs to be generated first
|
||||
func (s *authService) validateRefreshToken(ctx context.Context, tokenString string) (string, error) {
|
||||
// TODO: Use RefreshToken entity once generated
|
||||
// tokenHash := hashToken(tokenString)
|
||||
// rt, err := s.client.RefreshToken.Query()...
|
||||
// return rt.UserID, nil
|
||||
tokenHash := hashToken(tokenString)
|
||||
|
||||
// For now, return error to indicate this needs proper implementation
|
||||
return "", fmt.Errorf("refresh token validation not yet implemented - RefreshToken entity needs to be generated")
|
||||
// Find refresh token by hash
|
||||
rt, err := s.client.RefreshToken.Query().
|
||||
Where(refreshtoken.TokenHash(tokenHash)).
|
||||
Only(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid refresh token")
|
||||
}
|
||||
|
||||
// Check if token has expired
|
||||
if rt.ExpiresAt.Before(time.Now()) {
|
||||
// Delete expired token
|
||||
_ = s.client.RefreshToken.DeleteOneID(rt.ID).Exec(ctx)
|
||||
return "", fmt.Errorf("refresh token expired")
|
||||
}
|
||||
|
||||
return rt.UserID, nil
|
||||
}
|
||||
|
||||
// revokeRefreshToken revokes a refresh token.
|
||||
// Note: This is a simplified version - RefreshToken entity needs to be generated first
|
||||
func (s *authService) revokeRefreshToken(ctx context.Context, tokenString string) error {
|
||||
// TODO: Implement once RefreshToken entity is generated
|
||||
// tokenHash := hashToken(tokenString)
|
||||
// rt, err := s.client.RefreshToken.Query()...
|
||||
// return s.client.RefreshToken.DeleteOneID(rt.ID).Exec(ctx)
|
||||
return nil // Placeholder
|
||||
tokenHash := hashToken(tokenString)
|
||||
|
||||
// Find and delete refresh token
|
||||
rt, err := s.client.RefreshToken.Query().
|
||||
Where(refreshtoken.TokenHash(tokenHash)).
|
||||
Only(ctx)
|
||||
if err != nil {
|
||||
// Token not found, consider it already revoked
|
||||
return nil
|
||||
}
|
||||
|
||||
return s.client.RefreshToken.DeleteOneID(rt.ID).Exec(ctx)
|
||||
}
|
||||
|
||||
// login authenticates a user and returns tokens.
|
||||
func (s *authService) login(ctx context.Context, email, password string) (*authv1.LoginResponse, error) {
|
||||
// Verify credentials with Identity Service
|
||||
user, err := s.identityClient.GetUserByEmail(ctx, email)
|
||||
user, err := s.identityClient.VerifyPassword(ctx, email, password)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid credentials")
|
||||
}
|
||||
|
||||
// Note: In a real implementation, we'd call VerifyPassword on Identity Service
|
||||
// For now, we'll assume Identity Service validates the password
|
||||
// This is a simplified version - the Identity Service should expose VerifyPassword
|
||||
|
||||
// Get user roles (simplified - would come from Authz Service)
|
||||
roles := []string{} // TODO: Get from Authz Service
|
||||
// Get user roles from Authz Service
|
||||
roles := []string{}
|
||||
if s.authzClient != nil {
|
||||
userRoles, err := s.authzClient.GetUserRoles(ctx, user.ID)
|
||||
if err != nil {
|
||||
s.logger.Warn("Failed to get user roles",
|
||||
zap.String("user_id", user.ID),
|
||||
zap.Error(err),
|
||||
)
|
||||
// Continue without roles rather than failing login
|
||||
} else {
|
||||
for _, role := range userRoles {
|
||||
roles = append(roles, role.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate tokens
|
||||
accessToken, expiresIn, err := s.generateAccessToken(user.ID, user.Email, roles)
|
||||
@@ -197,8 +232,22 @@ func (s *authService) refreshToken(ctx context.Context, refreshTokenString strin
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
// Get user roles (simplified)
|
||||
roles := []string{} // TODO: Get from Authz Service
|
||||
// Get user roles from Authz Service
|
||||
roles := []string{}
|
||||
if s.authzClient != nil {
|
||||
userRoles, err := s.authzClient.GetUserRoles(ctx, user.ID)
|
||||
if err != nil {
|
||||
s.logger.Warn("Failed to get user roles",
|
||||
zap.String("user_id", user.ID),
|
||||
zap.Error(err),
|
||||
)
|
||||
// Continue without roles rather than failing refresh
|
||||
} else {
|
||||
for _, role := range userRoles {
|
||||
roles = append(roles, role.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate new tokens
|
||||
accessToken, expiresIn, err := s.generateAccessToken(user.ID, user.Email, roles)
|
||||
@@ -303,20 +352,22 @@ func provideAuthService() fx.Option {
|
||||
return fx.Options(
|
||||
// Auth service
|
||||
fx.Provide(func(
|
||||
client *ent.Client,
|
||||
client *database.Client,
|
||||
log logger.Logger,
|
||||
identityClient services.IdentityServiceClient,
|
||||
authzClient services.AuthzServiceClient,
|
||||
cfg config.ConfigProvider,
|
||||
) (*authService, error) {
|
||||
jwtSecret := cfg.GetString("auth.jwt_secret")
|
||||
if jwtSecret == "" {
|
||||
jwtSecret = "default-secret-change-in-production" // TODO: Generate or require
|
||||
return nil, fmt.Errorf("auth.jwt_secret is required in configuration")
|
||||
}
|
||||
|
||||
return &authService{
|
||||
client: client,
|
||||
logger: log,
|
||||
identityClient: identityClient,
|
||||
authzClient: authzClient,
|
||||
jwtSecret: []byte(jwtSecret),
|
||||
accessTokenExpiry: accessTokenLifetime,
|
||||
refreshTokenExpiry: refreshTokenLifetime,
|
||||
@@ -355,6 +406,9 @@ func provideAuthService() fx.Option {
|
||||
// Register health service
|
||||
healthServer := health.NewServer()
|
||||
grpc_health_v1.RegisterHealthServer(grpcServer, healthServer)
|
||||
// Set serving status for the default service (empty string) - this is what Consul checks
|
||||
healthServer.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)
|
||||
// Also set for the specific service name
|
||||
healthServer.SetServingStatus("auth.v1.AuthService", grpc_health_v1.HealthCheckResponse_SERVING)
|
||||
|
||||
// Register reflection for grpcurl
|
||||
|
||||
@@ -81,10 +81,8 @@ func (s *grpcServerWrapper) Port() int {
|
||||
|
||||
func main() {
|
||||
// Create DI container
|
||||
// Note: CoreModule() is automatically included by NewContainer()
|
||||
container := di.NewContainer(
|
||||
// Core kernel services
|
||||
di.CoreModule(),
|
||||
|
||||
// Database for auth service (auth schema)
|
||||
fx.Provide(func(cfg config.ConfigProvider, log logger.Logger) (*database.Client, error) {
|
||||
dsn := cfg.GetString("database.dsn")
|
||||
@@ -111,11 +109,9 @@ func main() {
|
||||
return client, nil
|
||||
}),
|
||||
|
||||
// Health registry with database checker
|
||||
fx.Provide(func(db *database.Client, log logger.Logger) (*healthpkg.Registry, error) {
|
||||
registry := healthpkg.NewRegistry()
|
||||
// Register database health checker with existing health registry
|
||||
fx.Invoke(func(registry *healthpkg.Registry, db *database.Client) {
|
||||
registry.Register("database", healthpkg.NewDatabaseChecker(db))
|
||||
return registry, nil
|
||||
}),
|
||||
|
||||
// Identity Service client
|
||||
@@ -123,6 +119,11 @@ func main() {
|
||||
return factory.GetIdentityClient()
|
||||
}),
|
||||
|
||||
// Authz Service client
|
||||
fx.Provide(func(factory *client.ServiceClientFactory) (services.AuthzServiceClient, error) {
|
||||
return factory.GetAuthzClient()
|
||||
}),
|
||||
|
||||
// Provide auth service and gRPC server (defined in auth_service_fx.go)
|
||||
provideAuthService(),
|
||||
|
||||
@@ -192,9 +193,13 @@ func registerLifecycle(
|
||||
|
||||
// Register with service registry
|
||||
serviceID := fmt.Sprintf("auth-service-%d", time.Now().Unix())
|
||||
// In Docker, always use the Docker service name for health checks
|
||||
// Consul (also in Docker) needs to reach the service via Docker DNS
|
||||
host := cfg.GetString("services.auth.host")
|
||||
if host == "" {
|
||||
host = "localhost"
|
||||
if os.Getenv("ENVIRONMENT") == "production" || os.Getenv("DOCKER") == "true" {
|
||||
host = "auth-service" // Docker service name - required for Consul health checks
|
||||
} else if host == "" {
|
||||
host = "localhost" // Local development
|
||||
}
|
||||
port := grpcServer.Port()
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
authzv1 "git.dcentral.systems/toolz/goplt/api/proto/generated/authz/v1"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
"git.dcentral.systems/toolz/goplt/internal/infra/database"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/config"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
"go.uber.org/fx"
|
||||
@@ -24,7 +25,7 @@ import (
|
||||
|
||||
// authzService provides authorization functionality.
|
||||
type authzService struct {
|
||||
client *ent.Client
|
||||
client *database.Client
|
||||
logger logger.Logger
|
||||
}
|
||||
|
||||
@@ -231,7 +232,7 @@ func (s *authzServerImpl) GetUserRoles(ctx context.Context, req *authzv1.GetUser
|
||||
func provideAuthzService() fx.Option {
|
||||
return fx.Options(
|
||||
// Authz service
|
||||
fx.Provide(func(client *ent.Client, log logger.Logger) (*authzService, error) {
|
||||
fx.Provide(func(client *database.Client, log logger.Logger) (*authzService, error) {
|
||||
return &authzService{
|
||||
client: client,
|
||||
logger: log,
|
||||
@@ -270,6 +271,9 @@ func provideAuthzService() fx.Option {
|
||||
// Register health service
|
||||
healthServer := health.NewServer()
|
||||
grpc_health_v1.RegisterHealthServer(grpcServer, healthServer)
|
||||
// Set serving status for the default service (empty string) - this is what Consul checks
|
||||
healthServer.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)
|
||||
// Also set for the specific service name
|
||||
healthServer.SetServingStatus("authz.v1.AuthzService", grpc_health_v1.HealthCheckResponse_SERVING)
|
||||
|
||||
// Register reflection for grpcurl
|
||||
|
||||
@@ -79,10 +79,8 @@ func (s *grpcServerWrapper) Port() int {
|
||||
|
||||
func main() {
|
||||
// Create DI container
|
||||
// Note: CoreModule() is automatically included by NewContainer()
|
||||
container := di.NewContainer(
|
||||
// Core kernel services
|
||||
di.CoreModule(),
|
||||
|
||||
// Database for authz service (authz schema)
|
||||
fx.Provide(func(cfg config.ConfigProvider, log logger.Logger) (*database.Client, error) {
|
||||
dsn := cfg.GetString("database.dsn")
|
||||
@@ -109,11 +107,9 @@ func main() {
|
||||
return client, nil
|
||||
}),
|
||||
|
||||
// Health registry with database checker
|
||||
fx.Provide(func(db *database.Client, log logger.Logger) (*healthpkg.Registry, error) {
|
||||
registry := healthpkg.NewRegistry()
|
||||
// Register database health checker with existing health registry
|
||||
fx.Invoke(func(registry *healthpkg.Registry, db *database.Client) {
|
||||
registry.Register("database", healthpkg.NewDatabaseChecker(db))
|
||||
return registry, nil
|
||||
}),
|
||||
|
||||
// Provide authz service and gRPC server (defined in authz_service_fx.go)
|
||||
@@ -185,9 +181,13 @@ func registerLifecycle(
|
||||
|
||||
// Register with service registry
|
||||
serviceID := fmt.Sprintf("authz-service-%d", time.Now().Unix())
|
||||
// In Docker, always use the Docker service name for health checks
|
||||
// Consul (also in Docker) needs to reach the service via Docker DNS
|
||||
host := cfg.GetString("services.authz.host")
|
||||
if host == "" {
|
||||
host = "localhost"
|
||||
if os.Getenv("ENVIRONMENT") == "production" || os.Getenv("DOCKER") == "true" {
|
||||
host = "authz-service" // Docker service name - required for Consul health checks
|
||||
} else if host == "" {
|
||||
host = "localhost" // Local development
|
||||
}
|
||||
port := grpcServer.Port()
|
||||
|
||||
|
||||
437
cmd/identity-service/identity_service_fx.go
Normal file
437
cmd/identity-service/identity_service_fx.go
Normal file
@@ -0,0 +1,437 @@
|
||||
// Package main provides FX providers for Identity Service.
|
||||
// This file creates the service inline to avoid importing internal packages.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
identityv1 "git.dcentral.systems/toolz/goplt/api/proto/generated/identity/v1"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
"git.dcentral.systems/toolz/goplt/internal/infra/database"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/config"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
"go.uber.org/fx"
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/crypto/argon2"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/health"
|
||||
"google.golang.org/grpc/health/grpc_health_v1"
|
||||
"google.golang.org/grpc/reflection"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// userService provides user management functionality.
|
||||
type userService struct {
|
||||
client *database.Client
|
||||
logger logger.Logger
|
||||
}
|
||||
|
||||
// generateToken generates a random token.
|
||||
func generateToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("failed to generate token: %w", err)
|
||||
}
|
||||
return fmt.Sprintf("%x", b), nil
|
||||
}
|
||||
|
||||
// hashPassword hashes a password using argon2id.
|
||||
func hashPassword(password string) (string, error) {
|
||||
salt := make([]byte, 16)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("failed to generate salt: %w", err)
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, 3, 64*1024, 4, 32)
|
||||
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
|
||||
b64Hash := base64.RawStdEncoding.EncodeToString(hash)
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, 64*1024, 3, 4, b64Salt, b64Hash), nil
|
||||
}
|
||||
|
||||
// verifyPassword verifies a password against a hash.
|
||||
func verifyPassword(password, hash string) (bool, error) {
|
||||
// Simplified verification - in production use proper parsing
|
||||
parts := strings.Split(hash, "$")
|
||||
if len(parts) != 6 {
|
||||
return false, fmt.Errorf("invalid hash format")
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
expectedHash, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
actualHash := argon2.IDKey([]byte(password), salt, 3, 64*1024, 4, uint32(len(expectedHash)))
|
||||
return subtle.ConstantTimeCompare(expectedHash, actualHash) == 1, nil
|
||||
}
|
||||
|
||||
// createUser creates a new user.
|
||||
func (s *userService) createUser(ctx context.Context, email, username, pwd, firstName, lastName string) (*ent.User, error) {
|
||||
exists, err := s.client.User.Query().Where(user.Email(email)).Exist(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to check email: %w", err)
|
||||
}
|
||||
if exists {
|
||||
return nil, fmt.Errorf("email already exists")
|
||||
}
|
||||
|
||||
passwordHash, err := hashPassword(pwd)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to hash password: %w", err)
|
||||
}
|
||||
|
||||
verificationToken, err := generateToken()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate token: %w", err)
|
||||
}
|
||||
|
||||
create := s.client.User.Create().
|
||||
SetID(fmt.Sprintf("%d", time.Now().UnixNano())).
|
||||
SetEmail(email).
|
||||
SetPasswordHash(passwordHash).
|
||||
SetVerified(false).
|
||||
SetEmailVerificationToken(verificationToken)
|
||||
|
||||
if username != "" {
|
||||
create = create.SetUsername(username)
|
||||
}
|
||||
if firstName != "" {
|
||||
create = create.SetFirstName(firstName)
|
||||
}
|
||||
if lastName != "" {
|
||||
create = create.SetLastName(lastName)
|
||||
}
|
||||
|
||||
u, err := create.Save(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create user: %w", err)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// getUser retrieves a user by ID.
|
||||
func (s *userService) getUser(ctx context.Context, id string) (*ent.User, error) {
|
||||
u, err := s.client.User.Get(ctx, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get user: %w", err)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// getUserByEmail retrieves a user by email.
|
||||
func (s *userService) getUserByEmail(ctx context.Context, email string) (*ent.User, error) {
|
||||
u, err := s.client.User.Query().Where(user.Email(email)).Only(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get user: %w", err)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// updateUser updates a user.
|
||||
func (s *userService) updateUser(ctx context.Context, id string, email, username, firstName, lastName *string) (*ent.User, error) {
|
||||
update := s.client.User.UpdateOneID(id)
|
||||
if email != nil {
|
||||
exists, err := s.client.User.Query().
|
||||
Where(user.Email(*email), user.IDNEQ(id)).
|
||||
Exist(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to check email: %w", err)
|
||||
}
|
||||
if exists {
|
||||
return nil, fmt.Errorf("email already taken")
|
||||
}
|
||||
update = update.SetEmail(*email)
|
||||
}
|
||||
if username != nil {
|
||||
update = update.SetUsername(*username)
|
||||
}
|
||||
if firstName != nil {
|
||||
update = update.SetFirstName(*firstName)
|
||||
}
|
||||
if lastName != nil {
|
||||
update = update.SetLastName(*lastName)
|
||||
}
|
||||
return update.Save(ctx)
|
||||
}
|
||||
|
||||
// deleteUser deletes a user.
|
||||
func (s *userService) deleteUser(ctx context.Context, id string) error {
|
||||
return s.client.User.DeleteOneID(id).Exec(ctx)
|
||||
}
|
||||
|
||||
// verifyEmail verifies a user's email.
|
||||
func (s *userService) verifyEmail(ctx context.Context, token string) error {
|
||||
u, err := s.client.User.Query().Where(user.EmailVerificationToken(token)).Only(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid token")
|
||||
}
|
||||
_, err = s.client.User.UpdateOneID(u.ID).
|
||||
SetVerified(true).
|
||||
ClearEmailVerificationToken().
|
||||
Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// requestPasswordReset requests a password reset.
|
||||
func (s *userService) requestPasswordReset(ctx context.Context, email string) (string, error) {
|
||||
u, err := s.getUserByEmail(ctx, email)
|
||||
if err != nil {
|
||||
return "", nil // Don't reveal if user exists
|
||||
}
|
||||
token, err := generateToken()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
expiresAt := time.Now().Add(24 * time.Hour)
|
||||
_, err = s.client.User.UpdateOneID(u.ID).
|
||||
SetPasswordResetToken(token).
|
||||
SetPasswordResetExpiresAt(expiresAt).
|
||||
Save(ctx)
|
||||
return token, err
|
||||
}
|
||||
|
||||
// resetPassword resets a password.
|
||||
func (s *userService) resetPassword(ctx context.Context, token, newPassword string) error {
|
||||
u, err := s.client.User.Query().Where(user.PasswordResetToken(token)).Only(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid token")
|
||||
}
|
||||
if !u.PasswordResetExpiresAt.IsZero() && u.PasswordResetExpiresAt.Before(time.Now()) {
|
||||
return fmt.Errorf("token expired")
|
||||
}
|
||||
passwordHash, err := hashPassword(newPassword)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.client.User.UpdateOneID(u.ID).
|
||||
SetPasswordHash(passwordHash).
|
||||
ClearPasswordResetToken().
|
||||
ClearPasswordResetExpiresAt().
|
||||
Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// verifyPassword verifies a password.
|
||||
func (s *userService) verifyPassword(ctx context.Context, email, pwd string) (*ent.User, error) {
|
||||
u, err := s.getUserByEmail(ctx, email)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
valid, err := verifyPassword(pwd, u.PasswordHash)
|
||||
if err != nil || !valid {
|
||||
return nil, fmt.Errorf("invalid password")
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// identityServerImpl implements the IdentityService gRPC server.
|
||||
type identityServerImpl struct {
|
||||
identityv1.UnimplementedIdentityServiceServer
|
||||
service *userService
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// GetUser retrieves a user by ID.
|
||||
func (s *identityServerImpl) GetUser(ctx context.Context, req *identityv1.GetUserRequest) (*identityv1.GetUserResponse, error) {
|
||||
u, err := s.service.getUser(ctx, req.Id)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.NotFound, "user not found: %v", err)
|
||||
}
|
||||
return &identityv1.GetUserResponse{
|
||||
User: &identityv1.User{
|
||||
Id: u.ID,
|
||||
Email: u.Email,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
LastName: u.LastName,
|
||||
EmailVerified: u.Verified,
|
||||
CreatedAt: u.CreatedAt.Unix(),
|
||||
UpdatedAt: u.UpdatedAt.Unix(),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetUserByEmail retrieves a user by email.
|
||||
func (s *identityServerImpl) GetUserByEmail(ctx context.Context, req *identityv1.GetUserByEmailRequest) (*identityv1.GetUserByEmailResponse, error) {
|
||||
u, err := s.service.getUserByEmail(ctx, req.Email)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.NotFound, "user not found: %v", err)
|
||||
}
|
||||
return &identityv1.GetUserByEmailResponse{
|
||||
User: &identityv1.User{
|
||||
Id: u.ID,
|
||||
Email: u.Email,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
LastName: u.LastName,
|
||||
EmailVerified: u.Verified,
|
||||
CreatedAt: u.CreatedAt.Unix(),
|
||||
UpdatedAt: u.UpdatedAt.Unix(),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreateUser creates a new user.
|
||||
func (s *identityServerImpl) CreateUser(ctx context.Context, req *identityv1.CreateUserRequest) (*identityv1.CreateUserResponse, error) {
|
||||
u, err := s.service.createUser(ctx, req.Email, req.Username, req.Password, req.FirstName, req.LastName)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to create user: %v", err)
|
||||
}
|
||||
return &identityv1.CreateUserResponse{
|
||||
User: &identityv1.User{
|
||||
Id: u.ID,
|
||||
Email: u.Email,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
LastName: u.LastName,
|
||||
EmailVerified: u.Verified,
|
||||
CreatedAt: u.CreatedAt.Unix(),
|
||||
UpdatedAt: u.UpdatedAt.Unix(),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateUser updates a user.
|
||||
func (s *identityServerImpl) UpdateUser(ctx context.Context, req *identityv1.UpdateUserRequest) (*identityv1.UpdateUserResponse, error) {
|
||||
u, err := s.service.updateUser(ctx, req.Id, req.Email, req.Username, req.FirstName, req.LastName)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to update user: %v", err)
|
||||
}
|
||||
return &identityv1.UpdateUserResponse{
|
||||
User: &identityv1.User{
|
||||
Id: u.ID,
|
||||
Email: u.Email,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
LastName: u.LastName,
|
||||
EmailVerified: u.Verified,
|
||||
CreatedAt: u.CreatedAt.Unix(),
|
||||
UpdatedAt: u.UpdatedAt.Unix(),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// DeleteUser deletes a user.
|
||||
func (s *identityServerImpl) DeleteUser(ctx context.Context, req *identityv1.DeleteUserRequest) (*identityv1.DeleteUserResponse, error) {
|
||||
if err := s.service.deleteUser(ctx, req.Id); err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to delete user: %v", err)
|
||||
}
|
||||
return &identityv1.DeleteUserResponse{Success: true}, nil
|
||||
}
|
||||
|
||||
// VerifyEmail verifies a user's email.
|
||||
func (s *identityServerImpl) VerifyEmail(ctx context.Context, req *identityv1.VerifyEmailRequest) (*identityv1.VerifyEmailResponse, error) {
|
||||
if err := s.service.verifyEmail(ctx, req.Token); err != nil {
|
||||
return nil, status.Errorf(codes.InvalidArgument, "failed to verify email: %v", err)
|
||||
}
|
||||
return &identityv1.VerifyEmailResponse{Success: true}, nil
|
||||
}
|
||||
|
||||
// RequestPasswordReset requests a password reset.
|
||||
func (s *identityServerImpl) RequestPasswordReset(ctx context.Context, req *identityv1.RequestPasswordResetRequest) (*identityv1.RequestPasswordResetResponse, error) {
|
||||
_, err := s.service.requestPasswordReset(ctx, req.Email)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "failed to request password reset: %v", err)
|
||||
}
|
||||
return &identityv1.RequestPasswordResetResponse{Success: true}, nil
|
||||
}
|
||||
|
||||
// ResetPassword resets a password.
|
||||
func (s *identityServerImpl) ResetPassword(ctx context.Context, req *identityv1.ResetPasswordRequest) (*identityv1.ResetPasswordResponse, error) {
|
||||
if err := s.service.resetPassword(ctx, req.Token, req.NewPassword); err != nil {
|
||||
return nil, status.Errorf(codes.InvalidArgument, "failed to reset password: %v", err)
|
||||
}
|
||||
return &identityv1.ResetPasswordResponse{Success: true}, nil
|
||||
}
|
||||
|
||||
// VerifyPassword verifies a user's password.
|
||||
func (s *identityServerImpl) VerifyPassword(ctx context.Context, req *identityv1.VerifyPasswordRequest) (*identityv1.VerifyPasswordResponse, error) {
|
||||
u, err := s.service.verifyPassword(ctx, req.Email, req.Password)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Unauthenticated, "invalid credentials: %v", err)
|
||||
}
|
||||
return &identityv1.VerifyPasswordResponse{
|
||||
User: &identityv1.User{
|
||||
Id: u.ID,
|
||||
Email: u.Email,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
LastName: u.LastName,
|
||||
EmailVerified: u.Verified,
|
||||
CreatedAt: u.CreatedAt.Unix(),
|
||||
UpdatedAt: u.UpdatedAt.Unix(),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// provideIdentityService creates the identity service and gRPC server.
|
||||
func provideIdentityService() fx.Option {
|
||||
return fx.Options(
|
||||
// User service
|
||||
fx.Provide(func(client *database.Client, log logger.Logger) (*userService, error) {
|
||||
return &userService{
|
||||
client: client,
|
||||
logger: log,
|
||||
}, nil
|
||||
}),
|
||||
|
||||
// gRPC server implementation
|
||||
fx.Provide(func(userService *userService, log logger.Logger) (*identityServerImpl, error) {
|
||||
zapLogger, _ := zap.NewProduction()
|
||||
return &identityServerImpl{
|
||||
service: userService,
|
||||
logger: zapLogger,
|
||||
}, nil
|
||||
}),
|
||||
|
||||
// gRPC server wrapper
|
||||
fx.Provide(func(
|
||||
serverImpl *identityServerImpl,
|
||||
cfg config.ConfigProvider,
|
||||
log logger.Logger,
|
||||
) (*grpcServerWrapper, error) {
|
||||
port := cfg.GetInt("services.identity.port")
|
||||
if port == 0 {
|
||||
port = 8082
|
||||
}
|
||||
|
||||
addr := fmt.Sprintf("0.0.0.0:%d", port)
|
||||
listener, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to listen on %s: %w", addr, err)
|
||||
}
|
||||
|
||||
grpcServer := grpc.NewServer()
|
||||
identityv1.RegisterIdentityServiceServer(grpcServer, serverImpl)
|
||||
|
||||
// Register health service
|
||||
healthServer := health.NewServer()
|
||||
grpc_health_v1.RegisterHealthServer(grpcServer, healthServer)
|
||||
// Set serving status for the default service (empty string) - this is what Consul checks
|
||||
healthServer.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)
|
||||
// Also set for the specific service name
|
||||
healthServer.SetServingStatus("identity.v1.IdentityService", grpc_health_v1.HealthCheckResponse_SERVING)
|
||||
|
||||
// Register reflection for grpcurl
|
||||
reflection.Register(grpcServer)
|
||||
|
||||
return &grpcServerWrapper{
|
||||
server: grpcServer,
|
||||
listener: listener,
|
||||
port: port,
|
||||
logger: log,
|
||||
}, nil
|
||||
}),
|
||||
)
|
||||
}
|
||||
228
cmd/identity-service/main.go
Normal file
228
cmd/identity-service/main.go
Normal file
@@ -0,0 +1,228 @@
|
||||
// Package main provides the entry point for the Identity Service.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/internal/di"
|
||||
healthpkg "git.dcentral.systems/toolz/goplt/internal/health"
|
||||
"git.dcentral.systems/toolz/goplt/internal/infra/database"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/config"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/registry"
|
||||
"go.uber.org/fx"
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// grpcServerWrapper wraps the gRPC server for lifecycle management.
|
||||
type grpcServerWrapper struct {
|
||||
server *grpc.Server
|
||||
listener net.Listener
|
||||
port int
|
||||
logger logger.Logger
|
||||
}
|
||||
|
||||
func (s *grpcServerWrapper) Start() error {
|
||||
s.logger.Info("Starting Identity Service gRPC server",
|
||||
zap.Int("port", s.port),
|
||||
zap.String("addr", s.listener.Addr().String()),
|
||||
)
|
||||
|
||||
errChan := make(chan error, 1)
|
||||
go func() {
|
||||
if err := s.server.Serve(s.listener); err != nil {
|
||||
errChan <- err
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-errChan:
|
||||
return fmt.Errorf("gRPC server failed to start: %w", err)
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
s.logger.Info("Identity Service gRPC server started successfully",
|
||||
zap.Int("port", s.port),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *grpcServerWrapper) Stop(ctx context.Context) error {
|
||||
s.logger.Info("Stopping Identity Service gRPC server")
|
||||
|
||||
stopped := make(chan struct{})
|
||||
go func() {
|
||||
s.server.GracefulStop()
|
||||
close(stopped)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-stopped:
|
||||
s.logger.Info("Identity Service gRPC server stopped gracefully")
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
s.logger.Warn("Identity Service gRPC server stop timeout, forcing stop")
|
||||
s.server.Stop()
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *grpcServerWrapper) Port() int {
|
||||
return s.port
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Create DI container
|
||||
// Note: CoreModule() is automatically included by NewContainer()
|
||||
container := di.NewContainer(
|
||||
// Database for identity service (identity schema)
|
||||
fx.Provide(func(cfg config.ConfigProvider, log logger.Logger) (*database.Client, error) {
|
||||
dsn := cfg.GetString("database.dsn")
|
||||
if dsn == "" {
|
||||
return nil, fmt.Errorf("database.dsn is required")
|
||||
}
|
||||
client, err := database.NewClientWithSchema(dsn, "identity")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Run migrations
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := client.Migrate(ctx); err != nil {
|
||||
log.Warn("Failed to run migrations",
|
||||
zap.Error(err),
|
||||
)
|
||||
} else {
|
||||
log.Info("Database migrations completed for identity service")
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}),
|
||||
|
||||
// Register database health checker with existing health registry
|
||||
fx.Invoke(func(registry *healthpkg.Registry, db *database.Client) {
|
||||
registry.Register("database", healthpkg.NewDatabaseChecker(db))
|
||||
}),
|
||||
|
||||
// Provide identity service and gRPC server (defined in identity_service_fx.go)
|
||||
provideIdentityService(),
|
||||
|
||||
// Lifecycle hooks
|
||||
fx.Invoke(registerLifecycle),
|
||||
)
|
||||
|
||||
// Create root context
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
// Handle signals
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
|
||||
|
||||
// Start the application
|
||||
if err := container.Start(ctx); err != nil {
|
||||
log := logger.GetGlobalLogger()
|
||||
if log != nil {
|
||||
log.Error("Failed to start Identity Service",
|
||||
logger.Error(err),
|
||||
)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Failed to start Identity Service: %v\n", err)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Wait for interrupt signal
|
||||
<-sigChan
|
||||
fmt.Println("\nShutting down Identity Service...")
|
||||
|
||||
// Create shutdown context with timeout
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer shutdownCancel()
|
||||
|
||||
// Stop the application
|
||||
if err := container.Stop(shutdownCtx); err != nil {
|
||||
log := logger.GetGlobalLogger()
|
||||
if log != nil {
|
||||
log.Error("Error during Identity Service shutdown",
|
||||
logger.Error(err),
|
||||
)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "Error during shutdown: %v\n", err)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Println("Identity Service stopped successfully")
|
||||
}
|
||||
|
||||
// registerLifecycle registers lifecycle hooks for the service.
|
||||
func registerLifecycle(
|
||||
lc fx.Lifecycle,
|
||||
grpcServer *grpcServerWrapper,
|
||||
serviceRegistry registry.ServiceRegistry,
|
||||
cfg config.ConfigProvider,
|
||||
log logger.Logger,
|
||||
) {
|
||||
lc.Append(fx.Hook{
|
||||
OnStart: func(ctx context.Context) error {
|
||||
// Start gRPC server
|
||||
if err := grpcServer.Start(); err != nil {
|
||||
return fmt.Errorf("failed to start gRPC server: %w", err)
|
||||
}
|
||||
|
||||
// Register with service registry
|
||||
serviceID := fmt.Sprintf("identity-service-%d", time.Now().Unix())
|
||||
// In Docker, always use the Docker service name for health checks
|
||||
// Consul (also in Docker) needs to reach the service via Docker DNS
|
||||
host := cfg.GetString("services.identity.host")
|
||||
if os.Getenv("ENVIRONMENT") == "production" || os.Getenv("DOCKER") == "true" {
|
||||
host = "identity-service" // Docker service name - required for Consul health checks
|
||||
} else if host == "" {
|
||||
host = "localhost" // Local development
|
||||
}
|
||||
port := grpcServer.Port()
|
||||
|
||||
instance := ®istry.ServiceInstance{
|
||||
ID: serviceID,
|
||||
Name: "identity-service",
|
||||
Address: host,
|
||||
Port: port,
|
||||
Tags: []string{"grpc", "identity"},
|
||||
Metadata: map[string]string{
|
||||
"version": "1.0.0",
|
||||
"protocol": "grpc",
|
||||
},
|
||||
}
|
||||
|
||||
if err := serviceRegistry.Register(ctx, instance); err != nil {
|
||||
log.Warn("Failed to register with service registry",
|
||||
zap.Error(err),
|
||||
)
|
||||
} else {
|
||||
log.Info("Registered Identity Service with service registry",
|
||||
zap.String("service_id", serviceID),
|
||||
zap.String("name", instance.Name),
|
||||
zap.Int("port", port),
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
OnStop: func(ctx context.Context) error {
|
||||
// Stop gRPC server
|
||||
if err := grpcServer.Stop(ctx); err != nil {
|
||||
return fmt.Errorf("failed to stop gRPC server: %w", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -36,6 +36,8 @@ registry:
|
||||
timeout: "3s"
|
||||
deregister_after: "30s"
|
||||
http: "/healthz"
|
||||
grpc: "grpc.health.v1.Health"
|
||||
use_grpc: true
|
||||
|
||||
services:
|
||||
audit:
|
||||
|
||||
@@ -22,7 +22,7 @@ services:
|
||||
- goplt-network
|
||||
|
||||
consul:
|
||||
image: consul:latest
|
||||
image: consul:1.15.4
|
||||
container_name: goplt-consul
|
||||
command: consul agent -dev -client=0.0.0.0
|
||||
ports:
|
||||
@@ -121,6 +121,34 @@ services:
|
||||
- goplt-network
|
||||
restart: unless-stopped
|
||||
|
||||
api-gateway:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: cmd/api-gateway/Dockerfile
|
||||
container_name: goplt-api-gateway
|
||||
environment:
|
||||
ENVIRONMENT: production
|
||||
REGISTRY_TYPE: consul
|
||||
REGISTRY_CONSUL_ADDRESS: "consul:8500"
|
||||
GATEWAY_PORT: "8080"
|
||||
GATEWAY_HOST: "0.0.0.0"
|
||||
ports:
|
||||
- "8080:8080"
|
||||
depends_on:
|
||||
consul:
|
||||
condition: service_healthy
|
||||
auth-service:
|
||||
condition: service_started
|
||||
identity-service:
|
||||
condition: service_started
|
||||
authz-service:
|
||||
condition: service_started
|
||||
audit-service:
|
||||
condition: service_started
|
||||
networks:
|
||||
- goplt-network
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
driver: local
|
||||
|
||||
@@ -196,16 +196,16 @@ Then start services locally:
|
||||
|
||||
```bash
|
||||
# Terminal 1: Auth Service
|
||||
go run ./cmd/auth-service/main.go
|
||||
go run ./cmd/auth-service/*.go
|
||||
|
||||
# Terminal 2: Identity Service
|
||||
go run ./cmd/identity-service/main.go
|
||||
go run ./cmd/identity-service/*.go
|
||||
|
||||
# Terminal 3: Authz Service
|
||||
go run ./cmd/authz-service/main.go
|
||||
go run ./cmd/authz-service/*.go
|
||||
|
||||
# Terminal 4: Audit Service
|
||||
go run ./cmd/audit-service/main.go
|
||||
go run ./cmd/audit-service/*.go
|
||||
```
|
||||
|
||||
### Option 2: Full Docker Compose (All Services in Docker)
|
||||
@@ -230,6 +230,7 @@ This will start:
|
||||
- Identity Service (port 8082)
|
||||
- Authz Service (port 8083)
|
||||
- Audit Service (port 8084)
|
||||
- API Gateway (port 8080)
|
||||
|
||||
### Infrastructure Services
|
||||
|
||||
@@ -423,9 +424,12 @@ goplt/
|
||||
│ │ ├── main.go
|
||||
│ │ ├── authz_service_fx.go
|
||||
│ │ └── Dockerfile
|
||||
│ └── audit-service/
|
||||
│ ├── audit-service/
|
||||
│ │ ├── main.go
|
||||
│ │ ├── audit_service_fx.go
|
||||
│ │ └── Dockerfile
|
||||
│ └── api-gateway/
|
||||
│ ├── main.go
|
||||
│ ├── audit_service_fx.go
|
||||
│ └── Dockerfile
|
||||
├── docker-compose.yml
|
||||
├── docker-compose.dev.yml
|
||||
@@ -473,6 +477,7 @@ docker build -f cmd/auth-service/Dockerfile -t goplt-auth-service:latest .
|
||||
docker build -f cmd/identity-service/Dockerfile -t goplt-identity-service:latest .
|
||||
docker build -f cmd/authz-service/Dockerfile -t goplt-authz-service:latest .
|
||||
docker build -f cmd/audit-service/Dockerfile -t goplt-audit-service:latest .
|
||||
docker build -f cmd/api-gateway/Dockerfile -t goplt-api-gateway:latest .
|
||||
```
|
||||
|
||||
### Docker Compose Files
|
||||
|
||||
@@ -196,6 +196,23 @@ func (c *IdentityClient) ResetPassword(ctx context.Context, token, newPassword s
|
||||
return nil
|
||||
}
|
||||
|
||||
// VerifyPassword verifies a user's password and returns the user if valid.
|
||||
func (c *IdentityClient) VerifyPassword(ctx context.Context, email, password string) (*services.User, error) {
|
||||
if err := c.connect(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := c.client.VerifyPassword(ctx, &identityv1.VerifyPasswordRequest{
|
||||
Email: email,
|
||||
Password: password,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("verify password failed: %w", err)
|
||||
}
|
||||
|
||||
return protoUserToServiceUser(resp.User), nil
|
||||
}
|
||||
|
||||
// protoUserToServiceUser converts a proto User to a service User.
|
||||
func protoUserToServiceUser(u *identityv1.User) *services.User {
|
||||
if u == nil {
|
||||
|
||||
@@ -3,6 +3,7 @@ package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/pkg/config"
|
||||
@@ -95,9 +96,13 @@ func LoadConfig(env string) (config.ConfigProvider, error) {
|
||||
|
||||
// Enable environment variable support
|
||||
v.AutomaticEnv()
|
||||
// Environment variables can be set in UPPER_SNAKE_CASE format
|
||||
// and will automatically map to nested keys (e.g., SERVER_PORT -> server.port)
|
||||
// Viper handles this automatically with AutomaticEnv()
|
||||
// Set env key replacer to convert UPPER_SNAKE_CASE to nested keys
|
||||
// e.g., DATABASE_DSN -> database.dsn, SERVER_PORT -> server.port
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
// Bind specific environment variables to config keys
|
||||
v.BindEnv("database.dsn", "DATABASE_DSN")
|
||||
v.BindEnv("registry.consul.address", "REGISTRY_CONSUL_ADDRESS")
|
||||
v.BindEnv("registry.type", "REGISTRY_TYPE")
|
||||
|
||||
return NewViperConfig(v), nil
|
||||
}
|
||||
|
||||
@@ -218,8 +218,14 @@ func ProvideServiceRegistry() fx.Option {
|
||||
healthCheckDeregisterAfter = 30 * time.Second
|
||||
}
|
||||
healthCheckHTTP := cfg.GetString("registry.consul.health_check.http")
|
||||
if healthCheckHTTP == "" {
|
||||
healthCheckHTTP = "/healthz"
|
||||
healthCheckGRPC := cfg.GetString("registry.consul.health_check.grpc")
|
||||
useGRPC := cfg.GetBool("registry.consul.health_check.use_grpc")
|
||||
// Default to gRPC if not explicitly set (services are gRPC by default)
|
||||
if !cfg.IsSet("registry.consul.health_check.use_grpc") {
|
||||
useGRPC = true
|
||||
}
|
||||
if healthCheckGRPC == "" {
|
||||
healthCheckGRPC = "grpc.health.v1.Health"
|
||||
}
|
||||
|
||||
consulCfg.HealthCheck = consul.HealthCheckConfig{
|
||||
@@ -227,6 +233,8 @@ func ProvideServiceRegistry() fx.Option {
|
||||
Timeout: healthCheckTimeout,
|
||||
DeregisterAfter: healthCheckDeregisterAfter,
|
||||
HTTP: healthCheckHTTP,
|
||||
GRPC: healthCheckGRPC,
|
||||
UseGRPC: useGRPC,
|
||||
}
|
||||
|
||||
return consul.NewRegistry(consulCfg)
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/auditlog"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
@@ -32,6 +33,8 @@ type Client struct {
|
||||
AuditLog *AuditLogClient
|
||||
// Permission is the client for interacting with the Permission builders.
|
||||
Permission *PermissionClient
|
||||
// RefreshToken is the client for interacting with the RefreshToken builders.
|
||||
RefreshToken *RefreshTokenClient
|
||||
// Role is the client for interacting with the Role builders.
|
||||
Role *RoleClient
|
||||
// RolePermission is the client for interacting with the RolePermission builders.
|
||||
@@ -53,6 +56,7 @@ func (c *Client) init() {
|
||||
c.Schema = migrate.NewSchema(c.driver)
|
||||
c.AuditLog = NewAuditLogClient(c.config)
|
||||
c.Permission = NewPermissionClient(c.config)
|
||||
c.RefreshToken = NewRefreshTokenClient(c.config)
|
||||
c.Role = NewRoleClient(c.config)
|
||||
c.RolePermission = NewRolePermissionClient(c.config)
|
||||
c.User = NewUserClient(c.config)
|
||||
@@ -151,6 +155,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
|
||||
config: cfg,
|
||||
AuditLog: NewAuditLogClient(cfg),
|
||||
Permission: NewPermissionClient(cfg),
|
||||
RefreshToken: NewRefreshTokenClient(cfg),
|
||||
Role: NewRoleClient(cfg),
|
||||
RolePermission: NewRolePermissionClient(cfg),
|
||||
User: NewUserClient(cfg),
|
||||
@@ -176,6 +181,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
|
||||
config: cfg,
|
||||
AuditLog: NewAuditLogClient(cfg),
|
||||
Permission: NewPermissionClient(cfg),
|
||||
RefreshToken: NewRefreshTokenClient(cfg),
|
||||
Role: NewRoleClient(cfg),
|
||||
RolePermission: NewRolePermissionClient(cfg),
|
||||
User: NewUserClient(cfg),
|
||||
@@ -209,7 +215,8 @@ func (c *Client) Close() error {
|
||||
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
|
||||
func (c *Client) Use(hooks ...Hook) {
|
||||
for _, n := range []interface{ Use(...Hook) }{
|
||||
c.AuditLog, c.Permission, c.Role, c.RolePermission, c.User, c.UserRole,
|
||||
c.AuditLog, c.Permission, c.RefreshToken, c.Role, c.RolePermission, c.User,
|
||||
c.UserRole,
|
||||
} {
|
||||
n.Use(hooks...)
|
||||
}
|
||||
@@ -219,7 +226,8 @@ func (c *Client) Use(hooks ...Hook) {
|
||||
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
|
||||
func (c *Client) Intercept(interceptors ...Interceptor) {
|
||||
for _, n := range []interface{ Intercept(...Interceptor) }{
|
||||
c.AuditLog, c.Permission, c.Role, c.RolePermission, c.User, c.UserRole,
|
||||
c.AuditLog, c.Permission, c.RefreshToken, c.Role, c.RolePermission, c.User,
|
||||
c.UserRole,
|
||||
} {
|
||||
n.Intercept(interceptors...)
|
||||
}
|
||||
@@ -232,6 +240,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
|
||||
return c.AuditLog.mutate(ctx, m)
|
||||
case *PermissionMutation:
|
||||
return c.Permission.mutate(ctx, m)
|
||||
case *RefreshTokenMutation:
|
||||
return c.RefreshToken.mutate(ctx, m)
|
||||
case *RoleMutation:
|
||||
return c.Role.mutate(ctx, m)
|
||||
case *RolePermissionMutation:
|
||||
@@ -527,6 +537,139 @@ func (c *PermissionClient) mutate(ctx context.Context, m *PermissionMutation) (V
|
||||
}
|
||||
}
|
||||
|
||||
// RefreshTokenClient is a client for the RefreshToken schema.
|
||||
type RefreshTokenClient struct {
|
||||
config
|
||||
}
|
||||
|
||||
// NewRefreshTokenClient returns a client for the RefreshToken from the given config.
|
||||
func NewRefreshTokenClient(c config) *RefreshTokenClient {
|
||||
return &RefreshTokenClient{config: c}
|
||||
}
|
||||
|
||||
// Use adds a list of mutation hooks to the hooks stack.
|
||||
// A call to `Use(f, g, h)` equals to `refreshtoken.Hooks(f(g(h())))`.
|
||||
func (c *RefreshTokenClient) Use(hooks ...Hook) {
|
||||
c.hooks.RefreshToken = append(c.hooks.RefreshToken, hooks...)
|
||||
}
|
||||
|
||||
// Intercept adds a list of query interceptors to the interceptors stack.
|
||||
// A call to `Intercept(f, g, h)` equals to `refreshtoken.Intercept(f(g(h())))`.
|
||||
func (c *RefreshTokenClient) Intercept(interceptors ...Interceptor) {
|
||||
c.inters.RefreshToken = append(c.inters.RefreshToken, interceptors...)
|
||||
}
|
||||
|
||||
// Create returns a builder for creating a RefreshToken entity.
|
||||
func (c *RefreshTokenClient) Create() *RefreshTokenCreate {
|
||||
mutation := newRefreshTokenMutation(c.config, OpCreate)
|
||||
return &RefreshTokenCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// CreateBulk returns a builder for creating a bulk of RefreshToken entities.
|
||||
func (c *RefreshTokenClient) CreateBulk(builders ...*RefreshTokenCreate) *RefreshTokenCreateBulk {
|
||||
return &RefreshTokenCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
|
||||
// a builder and applies setFunc on it.
|
||||
func (c *RefreshTokenClient) MapCreateBulk(slice any, setFunc func(*RefreshTokenCreate, int)) *RefreshTokenCreateBulk {
|
||||
rv := reflect.ValueOf(slice)
|
||||
if rv.Kind() != reflect.Slice {
|
||||
return &RefreshTokenCreateBulk{err: fmt.Errorf("calling to RefreshTokenClient.MapCreateBulk with wrong type %T, need slice", slice)}
|
||||
}
|
||||
builders := make([]*RefreshTokenCreate, rv.Len())
|
||||
for i := 0; i < rv.Len(); i++ {
|
||||
builders[i] = c.Create()
|
||||
setFunc(builders[i], i)
|
||||
}
|
||||
return &RefreshTokenCreateBulk{config: c.config, builders: builders}
|
||||
}
|
||||
|
||||
// Update returns an update builder for RefreshToken.
|
||||
func (c *RefreshTokenClient) Update() *RefreshTokenUpdate {
|
||||
mutation := newRefreshTokenMutation(c.config, OpUpdate)
|
||||
return &RefreshTokenUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOne returns an update builder for the given entity.
|
||||
func (c *RefreshTokenClient) UpdateOne(_m *RefreshToken) *RefreshTokenUpdateOne {
|
||||
mutation := newRefreshTokenMutation(c.config, OpUpdateOne, withRefreshToken(_m))
|
||||
return &RefreshTokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// UpdateOneID returns an update builder for the given id.
|
||||
func (c *RefreshTokenClient) UpdateOneID(id string) *RefreshTokenUpdateOne {
|
||||
mutation := newRefreshTokenMutation(c.config, OpUpdateOne, withRefreshTokenID(id))
|
||||
return &RefreshTokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// Delete returns a delete builder for RefreshToken.
|
||||
func (c *RefreshTokenClient) Delete() *RefreshTokenDelete {
|
||||
mutation := newRefreshTokenMutation(c.config, OpDelete)
|
||||
return &RefreshTokenDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
|
||||
}
|
||||
|
||||
// DeleteOne returns a builder for deleting the given entity.
|
||||
func (c *RefreshTokenClient) DeleteOne(_m *RefreshToken) *RefreshTokenDeleteOne {
|
||||
return c.DeleteOneID(_m.ID)
|
||||
}
|
||||
|
||||
// DeleteOneID returns a builder for deleting the given entity by its id.
|
||||
func (c *RefreshTokenClient) DeleteOneID(id string) *RefreshTokenDeleteOne {
|
||||
builder := c.Delete().Where(refreshtoken.ID(id))
|
||||
builder.mutation.id = &id
|
||||
builder.mutation.op = OpDeleteOne
|
||||
return &RefreshTokenDeleteOne{builder}
|
||||
}
|
||||
|
||||
// Query returns a query builder for RefreshToken.
|
||||
func (c *RefreshTokenClient) Query() *RefreshTokenQuery {
|
||||
return &RefreshTokenQuery{
|
||||
config: c.config,
|
||||
ctx: &QueryContext{Type: TypeRefreshToken},
|
||||
inters: c.Interceptors(),
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns a RefreshToken entity by its id.
|
||||
func (c *RefreshTokenClient) Get(ctx context.Context, id string) (*RefreshToken, error) {
|
||||
return c.Query().Where(refreshtoken.ID(id)).Only(ctx)
|
||||
}
|
||||
|
||||
// GetX is like Get, but panics if an error occurs.
|
||||
func (c *RefreshTokenClient) GetX(ctx context.Context, id string) *RefreshToken {
|
||||
obj, err := c.Get(ctx, id)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
// Hooks returns the client hooks.
|
||||
func (c *RefreshTokenClient) Hooks() []Hook {
|
||||
return c.hooks.RefreshToken
|
||||
}
|
||||
|
||||
// Interceptors returns the client interceptors.
|
||||
func (c *RefreshTokenClient) Interceptors() []Interceptor {
|
||||
return c.inters.RefreshToken
|
||||
}
|
||||
|
||||
func (c *RefreshTokenClient) mutate(ctx context.Context, m *RefreshTokenMutation) (Value, error) {
|
||||
switch m.Op() {
|
||||
case OpCreate:
|
||||
return (&RefreshTokenCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdate:
|
||||
return (&RefreshTokenUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpUpdateOne:
|
||||
return (&RefreshTokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
|
||||
case OpDelete, OpDeleteOne:
|
||||
return (&RefreshTokenDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("ent: unknown RefreshToken mutation op: %q", m.Op())
|
||||
}
|
||||
}
|
||||
|
||||
// RoleClient is a client for the Role schema.
|
||||
type RoleClient struct {
|
||||
config
|
||||
@@ -1174,9 +1317,11 @@ func (c *UserRoleClient) mutate(ctx context.Context, m *UserRoleMutation) (Value
|
||||
// hooks and interceptors per client, for fast access.
|
||||
type (
|
||||
hooks struct {
|
||||
AuditLog, Permission, Role, RolePermission, User, UserRole []ent.Hook
|
||||
AuditLog, Permission, RefreshToken, Role, RolePermission, User,
|
||||
UserRole []ent.Hook
|
||||
}
|
||||
inters struct {
|
||||
AuditLog, Permission, Role, RolePermission, User, UserRole []ent.Interceptor
|
||||
AuditLog, Permission, RefreshToken, Role, RolePermission, User,
|
||||
UserRole []ent.Interceptor
|
||||
}
|
||||
)
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/auditlog"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
@@ -80,6 +81,7 @@ func checkColumn(t, c string) error {
|
||||
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
|
||||
auditlog.Table: auditlog.ValidColumn,
|
||||
permission.Table: permission.ValidColumn,
|
||||
refreshtoken.Table: refreshtoken.ValidColumn,
|
||||
role.Table: role.ValidColumn,
|
||||
rolepermission.Table: rolepermission.ValidColumn,
|
||||
user.Table: user.ValidColumn,
|
||||
|
||||
@@ -33,6 +33,18 @@ func (f PermissionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value,
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PermissionMutation", m)
|
||||
}
|
||||
|
||||
// The RefreshTokenFunc type is an adapter to allow the use of ordinary
|
||||
// function as RefreshToken mutator.
|
||||
type RefreshTokenFunc func(context.Context, *ent.RefreshTokenMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f RefreshTokenFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if mv, ok := m.(*ent.RefreshTokenMutation); ok {
|
||||
return f(ctx, mv)
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.RefreshTokenMutation", m)
|
||||
}
|
||||
|
||||
// The RoleFunc type is an adapter to allow the use of ordinary
|
||||
// function as Role mutator.
|
||||
type RoleFunc func(context.Context, *ent.RoleMutation) (ent.Value, error)
|
||||
|
||||
@@ -64,6 +64,37 @@ var (
|
||||
Columns: PermissionsColumns,
|
||||
PrimaryKey: []*schema.Column{PermissionsColumns[0]},
|
||||
}
|
||||
// RefreshTokensColumns holds the columns for the "refresh_tokens" table.
|
||||
RefreshTokensColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeString, Unique: true},
|
||||
{Name: "user_id", Type: field.TypeString},
|
||||
{Name: "token_hash", Type: field.TypeString},
|
||||
{Name: "expires_at", Type: field.TypeTime},
|
||||
{Name: "created_at", Type: field.TypeTime},
|
||||
}
|
||||
// RefreshTokensTable holds the schema information for the "refresh_tokens" table.
|
||||
RefreshTokensTable = &schema.Table{
|
||||
Name: "refresh_tokens",
|
||||
Columns: RefreshTokensColumns,
|
||||
PrimaryKey: []*schema.Column{RefreshTokensColumns[0]},
|
||||
Indexes: []*schema.Index{
|
||||
{
|
||||
Name: "refreshtoken_user_id",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{RefreshTokensColumns[1]},
|
||||
},
|
||||
{
|
||||
Name: "refreshtoken_token_hash",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{RefreshTokensColumns[2]},
|
||||
},
|
||||
{
|
||||
Name: "refreshtoken_expires_at",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{RefreshTokensColumns[3]},
|
||||
},
|
||||
},
|
||||
}
|
||||
// RolesColumns holds the columns for the "roles" table.
|
||||
RolesColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeString, Unique: true},
|
||||
@@ -182,6 +213,7 @@ var (
|
||||
Tables = []*schema.Table{
|
||||
AuditLogsTable,
|
||||
PermissionsTable,
|
||||
RefreshTokensTable,
|
||||
RolesTable,
|
||||
RolePermissionsTable,
|
||||
UsersTable,
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/auditlog"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
@@ -31,6 +32,7 @@ const (
|
||||
// Node types.
|
||||
TypeAuditLog = "AuditLog"
|
||||
TypePermission = "Permission"
|
||||
TypeRefreshToken = "RefreshToken"
|
||||
TypeRole = "Role"
|
||||
TypeRolePermission = "RolePermission"
|
||||
TypeUser = "User"
|
||||
@@ -1270,6 +1272,500 @@ func (m *PermissionMutation) ResetEdge(name string) error {
|
||||
return fmt.Errorf("unknown Permission edge %s", name)
|
||||
}
|
||||
|
||||
// RefreshTokenMutation represents an operation that mutates the RefreshToken nodes in the graph.
|
||||
type RefreshTokenMutation struct {
|
||||
config
|
||||
op Op
|
||||
typ string
|
||||
id *string
|
||||
user_id *string
|
||||
token_hash *string
|
||||
expires_at *time.Time
|
||||
created_at *time.Time
|
||||
clearedFields map[string]struct{}
|
||||
done bool
|
||||
oldValue func(context.Context) (*RefreshToken, error)
|
||||
predicates []predicate.RefreshToken
|
||||
}
|
||||
|
||||
var _ ent.Mutation = (*RefreshTokenMutation)(nil)
|
||||
|
||||
// refreshtokenOption allows management of the mutation configuration using functional options.
|
||||
type refreshtokenOption func(*RefreshTokenMutation)
|
||||
|
||||
// newRefreshTokenMutation creates new mutation for the RefreshToken entity.
|
||||
func newRefreshTokenMutation(c config, op Op, opts ...refreshtokenOption) *RefreshTokenMutation {
|
||||
m := &RefreshTokenMutation{
|
||||
config: c,
|
||||
op: op,
|
||||
typ: TypeRefreshToken,
|
||||
clearedFields: make(map[string]struct{}),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(m)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// withRefreshTokenID sets the ID field of the mutation.
|
||||
func withRefreshTokenID(id string) refreshtokenOption {
|
||||
return func(m *RefreshTokenMutation) {
|
||||
var (
|
||||
err error
|
||||
once sync.Once
|
||||
value *RefreshToken
|
||||
)
|
||||
m.oldValue = func(ctx context.Context) (*RefreshToken, error) {
|
||||
once.Do(func() {
|
||||
if m.done {
|
||||
err = errors.New("querying old values post mutation is not allowed")
|
||||
} else {
|
||||
value, err = m.Client().RefreshToken.Get(ctx, id)
|
||||
}
|
||||
})
|
||||
return value, err
|
||||
}
|
||||
m.id = &id
|
||||
}
|
||||
}
|
||||
|
||||
// withRefreshToken sets the old RefreshToken of the mutation.
|
||||
func withRefreshToken(node *RefreshToken) refreshtokenOption {
|
||||
return func(m *RefreshTokenMutation) {
|
||||
m.oldValue = func(context.Context) (*RefreshToken, error) {
|
||||
return node, nil
|
||||
}
|
||||
m.id = &node.ID
|
||||
}
|
||||
}
|
||||
|
||||
// Client returns a new `ent.Client` from the mutation. If the mutation was
|
||||
// executed in a transaction (ent.Tx), a transactional client is returned.
|
||||
func (m RefreshTokenMutation) Client() *Client {
|
||||
client := &Client{config: m.config}
|
||||
client.init()
|
||||
return client
|
||||
}
|
||||
|
||||
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
|
||||
// it returns an error otherwise.
|
||||
func (m RefreshTokenMutation) Tx() (*Tx, error) {
|
||||
if _, ok := m.driver.(*txDriver); !ok {
|
||||
return nil, errors.New("ent: mutation is not running in a transaction")
|
||||
}
|
||||
tx := &Tx{config: m.config}
|
||||
tx.init()
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
// SetID sets the value of the id field. Note that this
|
||||
// operation is only accepted on creation of RefreshToken entities.
|
||||
func (m *RefreshTokenMutation) SetID(id string) {
|
||||
m.id = &id
|
||||
}
|
||||
|
||||
// ID returns the ID value in the mutation. Note that the ID is only available
|
||||
// if it was provided to the builder or after it was returned from the database.
|
||||
func (m *RefreshTokenMutation) ID() (id string, exists bool) {
|
||||
if m.id == nil {
|
||||
return
|
||||
}
|
||||
return *m.id, true
|
||||
}
|
||||
|
||||
// IDs queries the database and returns the entity ids that match the mutation's predicate.
|
||||
// That means, if the mutation is applied within a transaction with an isolation level such
|
||||
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
|
||||
// or updated by the mutation.
|
||||
func (m *RefreshTokenMutation) IDs(ctx context.Context) ([]string, error) {
|
||||
switch {
|
||||
case m.op.Is(OpUpdateOne | OpDeleteOne):
|
||||
id, exists := m.ID()
|
||||
if exists {
|
||||
return []string{id}, nil
|
||||
}
|
||||
fallthrough
|
||||
case m.op.Is(OpUpdate | OpDelete):
|
||||
return m.Client().RefreshToken.Query().Where(m.predicates...).IDs(ctx)
|
||||
default:
|
||||
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
|
||||
}
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (m *RefreshTokenMutation) SetUserID(s string) {
|
||||
m.user_id = &s
|
||||
}
|
||||
|
||||
// UserID returns the value of the "user_id" field in the mutation.
|
||||
func (m *RefreshTokenMutation) UserID() (r string, exists bool) {
|
||||
v := m.user_id
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldUserID returns the old "user_id" field's value of the RefreshToken entity.
|
||||
// If the RefreshToken object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *RefreshTokenMutation) OldUserID(ctx context.Context) (v string, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldUserID is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldUserID requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldUserID: %w", err)
|
||||
}
|
||||
return oldValue.UserID, nil
|
||||
}
|
||||
|
||||
// ResetUserID resets all changes to the "user_id" field.
|
||||
func (m *RefreshTokenMutation) ResetUserID() {
|
||||
m.user_id = nil
|
||||
}
|
||||
|
||||
// SetTokenHash sets the "token_hash" field.
|
||||
func (m *RefreshTokenMutation) SetTokenHash(s string) {
|
||||
m.token_hash = &s
|
||||
}
|
||||
|
||||
// TokenHash returns the value of the "token_hash" field in the mutation.
|
||||
func (m *RefreshTokenMutation) TokenHash() (r string, exists bool) {
|
||||
v := m.token_hash
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldTokenHash returns the old "token_hash" field's value of the RefreshToken entity.
|
||||
// If the RefreshToken object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *RefreshTokenMutation) OldTokenHash(ctx context.Context) (v string, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldTokenHash is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldTokenHash requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldTokenHash: %w", err)
|
||||
}
|
||||
return oldValue.TokenHash, nil
|
||||
}
|
||||
|
||||
// ResetTokenHash resets all changes to the "token_hash" field.
|
||||
func (m *RefreshTokenMutation) ResetTokenHash() {
|
||||
m.token_hash = nil
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (m *RefreshTokenMutation) SetExpiresAt(t time.Time) {
|
||||
m.expires_at = &t
|
||||
}
|
||||
|
||||
// ExpiresAt returns the value of the "expires_at" field in the mutation.
|
||||
func (m *RefreshTokenMutation) ExpiresAt() (r time.Time, exists bool) {
|
||||
v := m.expires_at
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldExpiresAt returns the old "expires_at" field's value of the RefreshToken entity.
|
||||
// If the RefreshToken object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *RefreshTokenMutation) OldExpiresAt(ctx context.Context) (v time.Time, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldExpiresAt is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldExpiresAt requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldExpiresAt: %w", err)
|
||||
}
|
||||
return oldValue.ExpiresAt, nil
|
||||
}
|
||||
|
||||
// ResetExpiresAt resets all changes to the "expires_at" field.
|
||||
func (m *RefreshTokenMutation) ResetExpiresAt() {
|
||||
m.expires_at = nil
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (m *RefreshTokenMutation) SetCreatedAt(t time.Time) {
|
||||
m.created_at = &t
|
||||
}
|
||||
|
||||
// CreatedAt returns the value of the "created_at" field in the mutation.
|
||||
func (m *RefreshTokenMutation) CreatedAt() (r time.Time, exists bool) {
|
||||
v := m.created_at
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldCreatedAt returns the old "created_at" field's value of the RefreshToken entity.
|
||||
// If the RefreshToken object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *RefreshTokenMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldCreatedAt requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)
|
||||
}
|
||||
return oldValue.CreatedAt, nil
|
||||
}
|
||||
|
||||
// ResetCreatedAt resets all changes to the "created_at" field.
|
||||
func (m *RefreshTokenMutation) ResetCreatedAt() {
|
||||
m.created_at = nil
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RefreshTokenMutation builder.
|
||||
func (m *RefreshTokenMutation) Where(ps ...predicate.RefreshToken) {
|
||||
m.predicates = append(m.predicates, ps...)
|
||||
}
|
||||
|
||||
// WhereP appends storage-level predicates to the RefreshTokenMutation builder. Using this method,
|
||||
// users can use type-assertion to append predicates that do not depend on any generated package.
|
||||
func (m *RefreshTokenMutation) WhereP(ps ...func(*sql.Selector)) {
|
||||
p := make([]predicate.RefreshToken, len(ps))
|
||||
for i := range ps {
|
||||
p[i] = ps[i]
|
||||
}
|
||||
m.Where(p...)
|
||||
}
|
||||
|
||||
// Op returns the operation name.
|
||||
func (m *RefreshTokenMutation) Op() Op {
|
||||
return m.op
|
||||
}
|
||||
|
||||
// SetOp allows setting the mutation operation.
|
||||
func (m *RefreshTokenMutation) SetOp(op Op) {
|
||||
m.op = op
|
||||
}
|
||||
|
||||
// Type returns the node type of this mutation (RefreshToken).
|
||||
func (m *RefreshTokenMutation) Type() string {
|
||||
return m.typ
|
||||
}
|
||||
|
||||
// Fields returns all fields that were changed during this mutation. Note that in
|
||||
// order to get all numeric fields that were incremented/decremented, call
|
||||
// AddedFields().
|
||||
func (m *RefreshTokenMutation) Fields() []string {
|
||||
fields := make([]string, 0, 4)
|
||||
if m.user_id != nil {
|
||||
fields = append(fields, refreshtoken.FieldUserID)
|
||||
}
|
||||
if m.token_hash != nil {
|
||||
fields = append(fields, refreshtoken.FieldTokenHash)
|
||||
}
|
||||
if m.expires_at != nil {
|
||||
fields = append(fields, refreshtoken.FieldExpiresAt)
|
||||
}
|
||||
if m.created_at != nil {
|
||||
fields = append(fields, refreshtoken.FieldCreatedAt)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// Field returns the value of a field with the given name. The second boolean
|
||||
// return value indicates that this field was not set, or was not defined in the
|
||||
// schema.
|
||||
func (m *RefreshTokenMutation) Field(name string) (ent.Value, bool) {
|
||||
switch name {
|
||||
case refreshtoken.FieldUserID:
|
||||
return m.UserID()
|
||||
case refreshtoken.FieldTokenHash:
|
||||
return m.TokenHash()
|
||||
case refreshtoken.FieldExpiresAt:
|
||||
return m.ExpiresAt()
|
||||
case refreshtoken.FieldCreatedAt:
|
||||
return m.CreatedAt()
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// OldField returns the old value of the field from the database. An error is
|
||||
// returned if the mutation operation is not UpdateOne, or the query to the
|
||||
// database failed.
|
||||
func (m *RefreshTokenMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
|
||||
switch name {
|
||||
case refreshtoken.FieldUserID:
|
||||
return m.OldUserID(ctx)
|
||||
case refreshtoken.FieldTokenHash:
|
||||
return m.OldTokenHash(ctx)
|
||||
case refreshtoken.FieldExpiresAt:
|
||||
return m.OldExpiresAt(ctx)
|
||||
case refreshtoken.FieldCreatedAt:
|
||||
return m.OldCreatedAt(ctx)
|
||||
}
|
||||
return nil, fmt.Errorf("unknown RefreshToken field %s", name)
|
||||
}
|
||||
|
||||
// SetField sets the value of a field with the given name. It returns an error if
|
||||
// the field is not defined in the schema, or if the type mismatched the field
|
||||
// type.
|
||||
func (m *RefreshTokenMutation) SetField(name string, value ent.Value) error {
|
||||
switch name {
|
||||
case refreshtoken.FieldUserID:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetUserID(v)
|
||||
return nil
|
||||
case refreshtoken.FieldTokenHash:
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetTokenHash(v)
|
||||
return nil
|
||||
case refreshtoken.FieldExpiresAt:
|
||||
v, ok := value.(time.Time)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetExpiresAt(v)
|
||||
return nil
|
||||
case refreshtoken.FieldCreatedAt:
|
||||
v, ok := value.(time.Time)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetCreatedAt(v)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown RefreshToken field %s", name)
|
||||
}
|
||||
|
||||
// AddedFields returns all numeric fields that were incremented/decremented during
|
||||
// this mutation.
|
||||
func (m *RefreshTokenMutation) AddedFields() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddedField returns the numeric value that was incremented/decremented on a field
|
||||
// with the given name. The second boolean return value indicates that this field
|
||||
// was not set, or was not defined in the schema.
|
||||
func (m *RefreshTokenMutation) AddedField(name string) (ent.Value, bool) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// AddField adds the value to the field with the given name. It returns an error if
|
||||
// the field is not defined in the schema, or if the type mismatched the field
|
||||
// type.
|
||||
func (m *RefreshTokenMutation) AddField(name string, value ent.Value) error {
|
||||
switch name {
|
||||
}
|
||||
return fmt.Errorf("unknown RefreshToken numeric field %s", name)
|
||||
}
|
||||
|
||||
// ClearedFields returns all nullable fields that were cleared during this
|
||||
// mutation.
|
||||
func (m *RefreshTokenMutation) ClearedFields() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
// FieldCleared returns a boolean indicating if a field with the given name was
|
||||
// cleared in this mutation.
|
||||
func (m *RefreshTokenMutation) FieldCleared(name string) bool {
|
||||
_, ok := m.clearedFields[name]
|
||||
return ok
|
||||
}
|
||||
|
||||
// ClearField clears the value of the field with the given name. It returns an
|
||||
// error if the field is not defined in the schema.
|
||||
func (m *RefreshTokenMutation) ClearField(name string) error {
|
||||
return fmt.Errorf("unknown RefreshToken nullable field %s", name)
|
||||
}
|
||||
|
||||
// ResetField resets all changes in the mutation for the field with the given name.
|
||||
// It returns an error if the field is not defined in the schema.
|
||||
func (m *RefreshTokenMutation) ResetField(name string) error {
|
||||
switch name {
|
||||
case refreshtoken.FieldUserID:
|
||||
m.ResetUserID()
|
||||
return nil
|
||||
case refreshtoken.FieldTokenHash:
|
||||
m.ResetTokenHash()
|
||||
return nil
|
||||
case refreshtoken.FieldExpiresAt:
|
||||
m.ResetExpiresAt()
|
||||
return nil
|
||||
case refreshtoken.FieldCreatedAt:
|
||||
m.ResetCreatedAt()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unknown RefreshToken field %s", name)
|
||||
}
|
||||
|
||||
// AddedEdges returns all edge names that were set/added in this mutation.
|
||||
func (m *RefreshTokenMutation) AddedEdges() []string {
|
||||
edges := make([]string, 0, 0)
|
||||
return edges
|
||||
}
|
||||
|
||||
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
|
||||
// name in this mutation.
|
||||
func (m *RefreshTokenMutation) AddedIDs(name string) []ent.Value {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemovedEdges returns all edge names that were removed in this mutation.
|
||||
func (m *RefreshTokenMutation) RemovedEdges() []string {
|
||||
edges := make([]string, 0, 0)
|
||||
return edges
|
||||
}
|
||||
|
||||
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
|
||||
// the given name in this mutation.
|
||||
func (m *RefreshTokenMutation) RemovedIDs(name string) []ent.Value {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearedEdges returns all edge names that were cleared in this mutation.
|
||||
func (m *RefreshTokenMutation) ClearedEdges() []string {
|
||||
edges := make([]string, 0, 0)
|
||||
return edges
|
||||
}
|
||||
|
||||
// EdgeCleared returns a boolean which indicates if the edge with the given name
|
||||
// was cleared in this mutation.
|
||||
func (m *RefreshTokenMutation) EdgeCleared(name string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// ClearEdge clears the value of the edge with the given name. It returns an error
|
||||
// if that edge is not defined in the schema.
|
||||
func (m *RefreshTokenMutation) ClearEdge(name string) error {
|
||||
return fmt.Errorf("unknown RefreshToken unique edge %s", name)
|
||||
}
|
||||
|
||||
// ResetEdge resets all changes to the edge with the given name in this mutation.
|
||||
// It returns an error if the edge is not defined in the schema.
|
||||
func (m *RefreshTokenMutation) ResetEdge(name string) error {
|
||||
return fmt.Errorf("unknown RefreshToken edge %s", name)
|
||||
}
|
||||
|
||||
// RoleMutation represents an operation that mutates the Role nodes in the graph.
|
||||
type RoleMutation struct {
|
||||
config
|
||||
|
||||
@@ -12,6 +12,9 @@ type AuditLog func(*sql.Selector)
|
||||
// Permission is the predicate function for permission builders.
|
||||
type Permission func(*sql.Selector)
|
||||
|
||||
// RefreshToken is the predicate function for refreshtoken builders.
|
||||
type RefreshToken func(*sql.Selector)
|
||||
|
||||
// Role is the predicate function for role builders.
|
||||
type Role func(*sql.Selector)
|
||||
|
||||
|
||||
136
internal/ent/refreshtoken.go
Normal file
136
internal/ent/refreshtoken.go
Normal file
@@ -0,0 +1,136 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken"
|
||||
)
|
||||
|
||||
// RefreshToken is the model entity for the RefreshToken schema.
|
||||
type RefreshToken struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID string `json:"id,omitempty"`
|
||||
// ID of the user who owns this refresh token
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
// SHA256 hash of the refresh token
|
||||
TokenHash string `json:"-"`
|
||||
// When the refresh token expires
|
||||
ExpiresAt time.Time `json:"expires_at,omitempty"`
|
||||
// CreatedAt holds the value of the "created_at" field.
|
||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*RefreshToken) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case refreshtoken.FieldID, refreshtoken.FieldUserID, refreshtoken.FieldTokenHash:
|
||||
values[i] = new(sql.NullString)
|
||||
case refreshtoken.FieldExpiresAt, refreshtoken.FieldCreatedAt:
|
||||
values[i] = new(sql.NullTime)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the RefreshToken fields.
|
||||
func (_m *RefreshToken) assignValues(columns []string, values []any) error {
|
||||
if m, n := len(values), len(columns); m < n {
|
||||
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
|
||||
}
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case refreshtoken.FieldID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ID = value.String
|
||||
}
|
||||
case refreshtoken.FieldUserID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field user_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.UserID = value.String
|
||||
}
|
||||
case refreshtoken.FieldTokenHash:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field token_hash", values[i])
|
||||
} else if value.Valid {
|
||||
_m.TokenHash = value.String
|
||||
}
|
||||
case refreshtoken.FieldExpiresAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field expires_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ExpiresAt = value.Time
|
||||
}
|
||||
case refreshtoken.FieldCreatedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field created_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.CreatedAt = value.Time
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the RefreshToken.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *RefreshToken) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this RefreshToken.
|
||||
// Note that you need to call RefreshToken.Unwrap() before calling this method if this RefreshToken
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *RefreshToken) Update() *RefreshTokenUpdateOne {
|
||||
return NewRefreshTokenClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the RefreshToken entity that was returned from a transaction after it was closed,
|
||||
// so that all future queries will be executed through the driver which created the transaction.
|
||||
func (_m *RefreshToken) Unwrap() *RefreshToken {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: RefreshToken is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *RefreshToken) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("RefreshToken(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("user_id=")
|
||||
builder.WriteString(_m.UserID)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("token_hash=<sensitive>")
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("expires_at=")
|
||||
builder.WriteString(_m.ExpiresAt.Format(time.ANSIC))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("created_at=")
|
||||
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// RefreshTokens is a parsable slice of RefreshToken.
|
||||
type RefreshTokens []*RefreshToken
|
||||
82
internal/ent/refreshtoken/refreshtoken.go
Normal file
82
internal/ent/refreshtoken/refreshtoken.go
Normal file
@@ -0,0 +1,82 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package refreshtoken
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the refreshtoken type in the database.
|
||||
Label = "refresh_token"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldUserID holds the string denoting the user_id field in the database.
|
||||
FieldUserID = "user_id"
|
||||
// FieldTokenHash holds the string denoting the token_hash field in the database.
|
||||
FieldTokenHash = "token_hash"
|
||||
// FieldExpiresAt holds the string denoting the expires_at field in the database.
|
||||
FieldExpiresAt = "expires_at"
|
||||
// FieldCreatedAt holds the string denoting the created_at field in the database.
|
||||
FieldCreatedAt = "created_at"
|
||||
// Table holds the table name of the refreshtoken in the database.
|
||||
Table = "refresh_tokens"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for refreshtoken fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldUserID,
|
||||
FieldTokenHash,
|
||||
FieldExpiresAt,
|
||||
FieldCreatedAt,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// UserIDValidator is a validator for the "user_id" field. It is called by the builders before save.
|
||||
UserIDValidator func(string) error
|
||||
// TokenHashValidator is a validator for the "token_hash" field. It is called by the builders before save.
|
||||
TokenHashValidator func(string) error
|
||||
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
|
||||
DefaultCreatedAt func() time.Time
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the RefreshToken queries.
|
||||
type OrderOption func(*sql.Selector)
|
||||
|
||||
// ByID orders the results by the id field.
|
||||
func ByID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUserID orders the results by the user_id field.
|
||||
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUserID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByTokenHash orders the results by the token_hash field.
|
||||
func ByTokenHash(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldTokenHash, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByExpiresAt orders the results by the expires_at field.
|
||||
func ByExpiresAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldExpiresAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreatedAt orders the results by the created_at field.
|
||||
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
|
||||
}
|
||||
310
internal/ent/refreshtoken/where.go
Normal file
310
internal/ent/refreshtoken/where.go
Normal file
@@ -0,0 +1,310 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package refreshtoken
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEqualFold applies the EqualFold predicate on the ID field.
|
||||
func IDEqualFold(id string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEqualFold(FieldID, id))
|
||||
}
|
||||
|
||||
// IDContainsFold applies the ContainsFold predicate on the ID field.
|
||||
func IDContainsFold(id string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldContainsFold(FieldID, id))
|
||||
}
|
||||
|
||||
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
|
||||
func UserID(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEQ(FieldUserID, v))
|
||||
}
|
||||
|
||||
// TokenHash applies equality check predicate on the "token_hash" field. It's identical to TokenHashEQ.
|
||||
func TokenHash(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEQ(FieldTokenHash, v))
|
||||
}
|
||||
|
||||
// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.
|
||||
func ExpiresAt(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEQ(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// UserIDEQ applies the EQ predicate on the "user_id" field.
|
||||
func UserIDEQ(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEQ(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
|
||||
func UserIDNEQ(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldNEQ(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDIn applies the In predicate on the "user_id" field.
|
||||
func UserIDIn(vs ...string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldIn(FieldUserID, vs...))
|
||||
}
|
||||
|
||||
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
|
||||
func UserIDNotIn(vs ...string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldNotIn(FieldUserID, vs...))
|
||||
}
|
||||
|
||||
// UserIDGT applies the GT predicate on the "user_id" field.
|
||||
func UserIDGT(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldGT(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDGTE applies the GTE predicate on the "user_id" field.
|
||||
func UserIDGTE(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldGTE(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDLT applies the LT predicate on the "user_id" field.
|
||||
func UserIDLT(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldLT(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDLTE applies the LTE predicate on the "user_id" field.
|
||||
func UserIDLTE(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldLTE(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDContains applies the Contains predicate on the "user_id" field.
|
||||
func UserIDContains(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldContains(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field.
|
||||
func UserIDHasPrefix(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldHasPrefix(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field.
|
||||
func UserIDHasSuffix(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldHasSuffix(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDEqualFold applies the EqualFold predicate on the "user_id" field.
|
||||
func UserIDEqualFold(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEqualFold(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field.
|
||||
func UserIDContainsFold(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldContainsFold(FieldUserID, v))
|
||||
}
|
||||
|
||||
// TokenHashEQ applies the EQ predicate on the "token_hash" field.
|
||||
func TokenHashEQ(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEQ(FieldTokenHash, v))
|
||||
}
|
||||
|
||||
// TokenHashNEQ applies the NEQ predicate on the "token_hash" field.
|
||||
func TokenHashNEQ(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldNEQ(FieldTokenHash, v))
|
||||
}
|
||||
|
||||
// TokenHashIn applies the In predicate on the "token_hash" field.
|
||||
func TokenHashIn(vs ...string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldIn(FieldTokenHash, vs...))
|
||||
}
|
||||
|
||||
// TokenHashNotIn applies the NotIn predicate on the "token_hash" field.
|
||||
func TokenHashNotIn(vs ...string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldNotIn(FieldTokenHash, vs...))
|
||||
}
|
||||
|
||||
// TokenHashGT applies the GT predicate on the "token_hash" field.
|
||||
func TokenHashGT(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldGT(FieldTokenHash, v))
|
||||
}
|
||||
|
||||
// TokenHashGTE applies the GTE predicate on the "token_hash" field.
|
||||
func TokenHashGTE(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldGTE(FieldTokenHash, v))
|
||||
}
|
||||
|
||||
// TokenHashLT applies the LT predicate on the "token_hash" field.
|
||||
func TokenHashLT(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldLT(FieldTokenHash, v))
|
||||
}
|
||||
|
||||
// TokenHashLTE applies the LTE predicate on the "token_hash" field.
|
||||
func TokenHashLTE(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldLTE(FieldTokenHash, v))
|
||||
}
|
||||
|
||||
// TokenHashContains applies the Contains predicate on the "token_hash" field.
|
||||
func TokenHashContains(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldContains(FieldTokenHash, v))
|
||||
}
|
||||
|
||||
// TokenHashHasPrefix applies the HasPrefix predicate on the "token_hash" field.
|
||||
func TokenHashHasPrefix(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldHasPrefix(FieldTokenHash, v))
|
||||
}
|
||||
|
||||
// TokenHashHasSuffix applies the HasSuffix predicate on the "token_hash" field.
|
||||
func TokenHashHasSuffix(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldHasSuffix(FieldTokenHash, v))
|
||||
}
|
||||
|
||||
// TokenHashEqualFold applies the EqualFold predicate on the "token_hash" field.
|
||||
func TokenHashEqualFold(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEqualFold(FieldTokenHash, v))
|
||||
}
|
||||
|
||||
// TokenHashContainsFold applies the ContainsFold predicate on the "token_hash" field.
|
||||
func TokenHashContainsFold(v string) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldContainsFold(FieldTokenHash, v))
|
||||
}
|
||||
|
||||
// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
|
||||
func ExpiresAtEQ(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEQ(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
|
||||
func ExpiresAtNEQ(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldNEQ(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtIn applies the In predicate on the "expires_at" field.
|
||||
func ExpiresAtIn(vs ...time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldIn(FieldExpiresAt, vs...))
|
||||
}
|
||||
|
||||
// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
|
||||
func ExpiresAtNotIn(vs ...time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldNotIn(FieldExpiresAt, vs...))
|
||||
}
|
||||
|
||||
// ExpiresAtGT applies the GT predicate on the "expires_at" field.
|
||||
func ExpiresAtGT(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldGT(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
|
||||
func ExpiresAtGTE(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldGTE(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtLT applies the LT predicate on the "expires_at" field.
|
||||
func ExpiresAtLT(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldLT(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
|
||||
func ExpiresAtLTE(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldLTE(FieldExpiresAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldGT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldGTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldLT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.FieldLTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// And groups predicates with the AND operator between them.
|
||||
func And(predicates ...predicate.RefreshToken) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.RefreshToken) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.RefreshToken) predicate.RefreshToken {
|
||||
return predicate.RefreshToken(sql.NotPredicates(p))
|
||||
}
|
||||
262
internal/ent/refreshtoken_create.go
Normal file
262
internal/ent/refreshtoken_create.go
Normal file
@@ -0,0 +1,262 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken"
|
||||
)
|
||||
|
||||
// RefreshTokenCreate is the builder for creating a RefreshToken entity.
|
||||
type RefreshTokenCreate struct {
|
||||
config
|
||||
mutation *RefreshTokenMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (_c *RefreshTokenCreate) SetUserID(v string) *RefreshTokenCreate {
|
||||
_c.mutation.SetUserID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetTokenHash sets the "token_hash" field.
|
||||
func (_c *RefreshTokenCreate) SetTokenHash(v string) *RefreshTokenCreate {
|
||||
_c.mutation.SetTokenHash(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (_c *RefreshTokenCreate) SetExpiresAt(v time.Time) *RefreshTokenCreate {
|
||||
_c.mutation.SetExpiresAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (_c *RefreshTokenCreate) SetCreatedAt(v time.Time) *RefreshTokenCreate {
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
|
||||
func (_c *RefreshTokenCreate) SetNillableCreatedAt(v *time.Time) *RefreshTokenCreate {
|
||||
if v != nil {
|
||||
_c.SetCreatedAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetID sets the "id" field.
|
||||
func (_c *RefreshTokenCreate) SetID(v string) *RefreshTokenCreate {
|
||||
_c.mutation.SetID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Mutation returns the RefreshTokenMutation object of the builder.
|
||||
func (_c *RefreshTokenCreate) Mutation() *RefreshTokenMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the RefreshToken in the database.
|
||||
func (_c *RefreshTokenCreate) Save(ctx context.Context) (*RefreshToken, error) {
|
||||
_c.defaults()
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *RefreshTokenCreate) SaveX(ctx context.Context) *RefreshToken {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *RefreshTokenCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *RefreshTokenCreate) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (_c *RefreshTokenCreate) defaults() {
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
v := refreshtoken.DefaultCreatedAt()
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *RefreshTokenCreate) check() error {
|
||||
if _, ok := _c.mutation.UserID(); !ok {
|
||||
return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "RefreshToken.user_id"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.UserID(); ok {
|
||||
if err := refreshtoken.UserIDValidator(v); err != nil {
|
||||
return &ValidationError{Name: "user_id", err: fmt.Errorf(`ent: validator failed for field "RefreshToken.user_id": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.TokenHash(); !ok {
|
||||
return &ValidationError{Name: "token_hash", err: errors.New(`ent: missing required field "RefreshToken.token_hash"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.TokenHash(); ok {
|
||||
if err := refreshtoken.TokenHashValidator(v); err != nil {
|
||||
return &ValidationError{Name: "token_hash", err: fmt.Errorf(`ent: validator failed for field "RefreshToken.token_hash": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.ExpiresAt(); !ok {
|
||||
return &ValidationError{Name: "expires_at", err: errors.New(`ent: missing required field "RefreshToken.expires_at"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "RefreshToken.created_at"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *RefreshTokenCreate) sqlSave(ctx context.Context) (*RefreshToken, error) {
|
||||
if err := _c.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := _c.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if _spec.ID.Value != nil {
|
||||
if id, ok := _spec.ID.Value.(string); ok {
|
||||
_node.ID = id
|
||||
} else {
|
||||
return nil, fmt.Errorf("unexpected RefreshToken.ID type: %T", _spec.ID.Value)
|
||||
}
|
||||
}
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *RefreshTokenCreate) createSpec() (*RefreshToken, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &RefreshToken{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(refreshtoken.Table, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString))
|
||||
)
|
||||
if id, ok := _c.mutation.ID(); ok {
|
||||
_node.ID = id
|
||||
_spec.ID.Value = id
|
||||
}
|
||||
if value, ok := _c.mutation.UserID(); ok {
|
||||
_spec.SetField(refreshtoken.FieldUserID, field.TypeString, value)
|
||||
_node.UserID = value
|
||||
}
|
||||
if value, ok := _c.mutation.TokenHash(); ok {
|
||||
_spec.SetField(refreshtoken.FieldTokenHash, field.TypeString, value)
|
||||
_node.TokenHash = value
|
||||
}
|
||||
if value, ok := _c.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(refreshtoken.FieldExpiresAt, field.TypeTime, value)
|
||||
_node.ExpiresAt = value
|
||||
}
|
||||
if value, ok := _c.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(refreshtoken.FieldCreatedAt, field.TypeTime, value)
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// RefreshTokenCreateBulk is the builder for creating many RefreshToken entities in bulk.
|
||||
type RefreshTokenCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*RefreshTokenCreate
|
||||
}
|
||||
|
||||
// Save creates the RefreshToken entities in the database.
|
||||
func (_c *RefreshTokenCreateBulk) Save(ctx context.Context) ([]*RefreshToken, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*RefreshToken, len(_c.builders))
|
||||
mutators := make([]Mutator, len(_c.builders))
|
||||
for i := range _c.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := _c.builders[i]
|
||||
builder.defaults()
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*RefreshTokenMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
var err error
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
|
||||
} else {
|
||||
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
mutation.done = true
|
||||
return nodes[i], nil
|
||||
})
|
||||
for i := len(builder.hooks) - 1; i >= 0; i-- {
|
||||
mut = builder.hooks[i](mut)
|
||||
}
|
||||
mutators[i] = mut
|
||||
}(i, ctx)
|
||||
}
|
||||
if len(mutators) > 0 {
|
||||
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_c *RefreshTokenCreateBulk) SaveX(ctx context.Context) []*RefreshToken {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *RefreshTokenCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *RefreshTokenCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
88
internal/ent/refreshtoken_delete.go
Normal file
88
internal/ent/refreshtoken_delete.go
Normal file
@@ -0,0 +1,88 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken"
|
||||
)
|
||||
|
||||
// RefreshTokenDelete is the builder for deleting a RefreshToken entity.
|
||||
type RefreshTokenDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *RefreshTokenMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RefreshTokenDelete builder.
|
||||
func (_d *RefreshTokenDelete) Where(ps ...predicate.RefreshToken) *RefreshTokenDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *RefreshTokenDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *RefreshTokenDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *RefreshTokenDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(refreshtoken.Table, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString))
|
||||
if ps := _d.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
_d.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// RefreshTokenDeleteOne is the builder for deleting a single RefreshToken entity.
|
||||
type RefreshTokenDeleteOne struct {
|
||||
_d *RefreshTokenDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RefreshTokenDelete builder.
|
||||
func (_d *RefreshTokenDeleteOne) Where(ps ...predicate.RefreshToken) *RefreshTokenDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *RefreshTokenDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{refreshtoken.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *RefreshTokenDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
527
internal/ent/refreshtoken_query.go
Normal file
527
internal/ent/refreshtoken_query.go
Normal file
@@ -0,0 +1,527 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken"
|
||||
)
|
||||
|
||||
// RefreshTokenQuery is the builder for querying RefreshToken entities.
|
||||
type RefreshTokenQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []refreshtoken.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.RefreshToken
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the RefreshTokenQuery builder.
|
||||
func (_q *RefreshTokenQuery) Where(ps ...predicate.RefreshToken) *RefreshTokenQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *RefreshTokenQuery) Limit(limit int) *RefreshTokenQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *RefreshTokenQuery) Offset(offset int) *RefreshTokenQuery {
|
||||
_q.ctx.Offset = &offset
|
||||
return _q
|
||||
}
|
||||
|
||||
// Unique configures the query builder to filter duplicate records on query.
|
||||
// By default, unique is set to true, and can be disabled using this method.
|
||||
func (_q *RefreshTokenQuery) Unique(unique bool) *RefreshTokenQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *RefreshTokenQuery) Order(o ...refreshtoken.OrderOption) *RefreshTokenQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// First returns the first RefreshToken entity from the query.
|
||||
// Returns a *NotFoundError when no RefreshToken was found.
|
||||
func (_q *RefreshTokenQuery) First(ctx context.Context) (*RefreshToken, error) {
|
||||
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, &NotFoundError{refreshtoken.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *RefreshTokenQuery) FirstX(ctx context.Context) *RefreshToken {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first RefreshToken ID from the query.
|
||||
// Returns a *NotFoundError when no RefreshToken ID was found.
|
||||
func (_q *RefreshTokenQuery) FirstID(ctx context.Context) (id string, err error) {
|
||||
var ids []string
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{refreshtoken.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *RefreshTokenQuery) FirstIDX(ctx context.Context) string {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single RefreshToken entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one RefreshToken entity is found.
|
||||
// Returns a *NotFoundError when no RefreshToken entities are found.
|
||||
func (_q *RefreshTokenQuery) Only(ctx context.Context) (*RefreshToken, error) {
|
||||
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(nodes) {
|
||||
case 1:
|
||||
return nodes[0], nil
|
||||
case 0:
|
||||
return nil, &NotFoundError{refreshtoken.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{refreshtoken.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *RefreshTokenQuery) OnlyX(ctx context.Context) *RefreshToken {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only RefreshToken ID in the query.
|
||||
// Returns a *NotSingularError when more than one RefreshToken ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *RefreshTokenQuery) OnlyID(ctx context.Context) (id string, err error) {
|
||||
var ids []string
|
||||
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &NotFoundError{refreshtoken.Label}
|
||||
default:
|
||||
err = &NotSingularError{refreshtoken.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *RefreshTokenQuery) OnlyIDX(ctx context.Context) string {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of RefreshTokens.
|
||||
func (_q *RefreshTokenQuery) All(ctx context.Context) ([]*RefreshToken, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*RefreshToken, *RefreshTokenQuery]()
|
||||
return withInterceptors[[]*RefreshToken](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *RefreshTokenQuery) AllX(ctx context.Context) []*RefreshToken {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of RefreshToken IDs.
|
||||
func (_q *RefreshTokenQuery) IDs(ctx context.Context) (ids []string, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(refreshtoken.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *RefreshTokenQuery) IDsX(ctx context.Context) []string {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *RefreshTokenQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, _q, querierCount[*RefreshTokenQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *RefreshTokenQuery) CountX(ctx context.Context) int {
|
||||
count, err := _q.Count(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (_q *RefreshTokenQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
|
||||
switch _, err := _q.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (_q *RefreshTokenQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the RefreshTokenQuery builder, including all associated steps. It can be
|
||||
// used to prepare common query builders and use them differently after the clone is made.
|
||||
func (_q *RefreshTokenQuery) Clone() *RefreshTokenQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &RefreshTokenQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]refreshtoken.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.RefreshToken{}, _q.predicates...),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// GroupBy is used to group vertices by one or more fields/columns.
|
||||
// It is often used with aggregate functions, like: count, max, mean, min, sum.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// UserID string `json:"user_id,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.RefreshToken.Query().
|
||||
// GroupBy(refreshtoken.FieldUserID).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *RefreshTokenQuery) GroupBy(field string, fields ...string) *RefreshTokenGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &RefreshTokenGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = refreshtoken.Label
|
||||
grbuild.scan = grbuild.Scan
|
||||
return grbuild
|
||||
}
|
||||
|
||||
// Select allows the selection one or more fields/columns for the given query,
|
||||
// instead of selecting all fields in the entity.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// UserID string `json:"user_id,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.RefreshToken.Query().
|
||||
// Select(refreshtoken.FieldUserID).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *RefreshTokenQuery) Select(fields ...string) *RefreshTokenSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &RefreshTokenSelect{RefreshTokenQuery: _q}
|
||||
sbuild.label = refreshtoken.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a RefreshTokenSelect configured with the given aggregations.
|
||||
func (_q *RefreshTokenQuery) Aggregate(fns ...AggregateFunc) *RefreshTokenSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *RefreshTokenQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range _q.inters {
|
||||
if inter == nil {
|
||||
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
|
||||
}
|
||||
if trv, ok := inter.(Traverser); ok {
|
||||
if err := trv.Traverse(ctx, _q); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range _q.ctx.Fields {
|
||||
if !refreshtoken.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
}
|
||||
if _q.path != nil {
|
||||
prev, err := _q.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_q.sql = prev
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *RefreshTokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*RefreshToken, error) {
|
||||
var (
|
||||
nodes = []*RefreshToken{}
|
||||
_spec = _q.querySpec()
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*RefreshToken).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &RefreshToken{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
for i := range hooks {
|
||||
hooks[i](ctx, _spec)
|
||||
}
|
||||
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nodes, nil
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *RefreshTokenQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
_spec.Node.Columns = _q.ctx.Fields
|
||||
if len(_q.ctx.Fields) > 0 {
|
||||
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
|
||||
}
|
||||
|
||||
func (_q *RefreshTokenQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(refreshtoken.Table, refreshtoken.Columns, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString))
|
||||
_spec.From = _q.sql
|
||||
if unique := _q.ctx.Unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
} else if _q.path != nil {
|
||||
_spec.Unique = true
|
||||
}
|
||||
if fields := _q.ctx.Fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, refreshtoken.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != refreshtoken.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _q.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := _q.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (_q *RefreshTokenQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(refreshtoken.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = refreshtoken.Columns
|
||||
}
|
||||
selector := builder.Select(t1.Columns(columns...)...).From(t1)
|
||||
if _q.sql != nil {
|
||||
selector = _q.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if _q.ctx.Unique != nil && *_q.ctx.Unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range _q.predicates {
|
||||
p(selector)
|
||||
}
|
||||
for _, p := range _q.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
// limit is mandatory for offset clause. We start
|
||||
// with default value, and override it below if needed.
|
||||
selector.Offset(*offset).Limit(math.MaxInt32)
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
}
|
||||
|
||||
// RefreshTokenGroupBy is the group-by builder for RefreshToken entities.
|
||||
type RefreshTokenGroupBy struct {
|
||||
selector
|
||||
build *RefreshTokenQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *RefreshTokenGroupBy) Aggregate(fns ...AggregateFunc) *RefreshTokenGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *RefreshTokenGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
|
||||
if err := _g.build.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*RefreshTokenQuery, *RefreshTokenGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *RefreshTokenGroupBy) sqlScan(ctx context.Context, root *RefreshTokenQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(_g.fns))
|
||||
for _, fn := range _g.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
|
||||
for _, f := range *_g.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*_g.flds...)...)
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
// RefreshTokenSelect is the builder for selecting fields of RefreshToken entities.
|
||||
type RefreshTokenSelect struct {
|
||||
*RefreshTokenQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *RefreshTokenSelect) Aggregate(fns ...AggregateFunc) *RefreshTokenSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *RefreshTokenSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
|
||||
if err := _s.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*RefreshTokenQuery, *RefreshTokenSelect](ctx, _s.RefreshTokenQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *RefreshTokenSelect) sqlScan(ctx context.Context, root *RefreshTokenQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(_s.fns))
|
||||
for _, fn := range _s.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*_s.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
314
internal/ent/refreshtoken_update.go
Normal file
314
internal/ent/refreshtoken_update.go
Normal file
@@ -0,0 +1,314 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken"
|
||||
)
|
||||
|
||||
// RefreshTokenUpdate is the builder for updating RefreshToken entities.
|
||||
type RefreshTokenUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *RefreshTokenMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RefreshTokenUpdate builder.
|
||||
func (_u *RefreshTokenUpdate) Where(ps ...predicate.RefreshToken) *RefreshTokenUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (_u *RefreshTokenUpdate) SetUserID(v string) *RefreshTokenUpdate {
|
||||
_u.mutation.SetUserID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableUserID sets the "user_id" field if the given value is not nil.
|
||||
func (_u *RefreshTokenUpdate) SetNillableUserID(v *string) *RefreshTokenUpdate {
|
||||
if v != nil {
|
||||
_u.SetUserID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetTokenHash sets the "token_hash" field.
|
||||
func (_u *RefreshTokenUpdate) SetTokenHash(v string) *RefreshTokenUpdate {
|
||||
_u.mutation.SetTokenHash(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableTokenHash sets the "token_hash" field if the given value is not nil.
|
||||
func (_u *RefreshTokenUpdate) SetNillableTokenHash(v *string) *RefreshTokenUpdate {
|
||||
if v != nil {
|
||||
_u.SetTokenHash(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (_u *RefreshTokenUpdate) SetExpiresAt(v time.Time) *RefreshTokenUpdate {
|
||||
_u.mutation.SetExpiresAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
|
||||
func (_u *RefreshTokenUpdate) SetNillableExpiresAt(v *time.Time) *RefreshTokenUpdate {
|
||||
if v != nil {
|
||||
_u.SetExpiresAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// Mutation returns the RefreshTokenMutation object of the builder.
|
||||
func (_u *RefreshTokenUpdate) Mutation() *RefreshTokenMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *RefreshTokenUpdate) Save(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *RefreshTokenUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *RefreshTokenUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *RefreshTokenUpdate) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *RefreshTokenUpdate) check() error {
|
||||
if v, ok := _u.mutation.UserID(); ok {
|
||||
if err := refreshtoken.UserIDValidator(v); err != nil {
|
||||
return &ValidationError{Name: "user_id", err: fmt.Errorf(`ent: validator failed for field "RefreshToken.user_id": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.TokenHash(); ok {
|
||||
if err := refreshtoken.TokenHashValidator(v); err != nil {
|
||||
return &ValidationError{Name: "token_hash", err: fmt.Errorf(`ent: validator failed for field "RefreshToken.token_hash": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *RefreshTokenUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(refreshtoken.Table, refreshtoken.Columns, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString))
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.UserID(); ok {
|
||||
_spec.SetField(refreshtoken.FieldUserID, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.TokenHash(); ok {
|
||||
_spec.SetField(refreshtoken.FieldTokenHash, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(refreshtoken.FieldExpiresAt, field.TypeTime, value)
|
||||
}
|
||||
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{refreshtoken.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// RefreshTokenUpdateOne is the builder for updating a single RefreshToken entity.
|
||||
type RefreshTokenUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *RefreshTokenMutation
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (_u *RefreshTokenUpdateOne) SetUserID(v string) *RefreshTokenUpdateOne {
|
||||
_u.mutation.SetUserID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableUserID sets the "user_id" field if the given value is not nil.
|
||||
func (_u *RefreshTokenUpdateOne) SetNillableUserID(v *string) *RefreshTokenUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetUserID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetTokenHash sets the "token_hash" field.
|
||||
func (_u *RefreshTokenUpdateOne) SetTokenHash(v string) *RefreshTokenUpdateOne {
|
||||
_u.mutation.SetTokenHash(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableTokenHash sets the "token_hash" field if the given value is not nil.
|
||||
func (_u *RefreshTokenUpdateOne) SetNillableTokenHash(v *string) *RefreshTokenUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetTokenHash(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetExpiresAt sets the "expires_at" field.
|
||||
func (_u *RefreshTokenUpdateOne) SetExpiresAt(v time.Time) *RefreshTokenUpdateOne {
|
||||
_u.mutation.SetExpiresAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
|
||||
func (_u *RefreshTokenUpdateOne) SetNillableExpiresAt(v *time.Time) *RefreshTokenUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetExpiresAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// Mutation returns the RefreshTokenMutation object of the builder.
|
||||
func (_u *RefreshTokenUpdateOne) Mutation() *RefreshTokenMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RefreshTokenUpdate builder.
|
||||
func (_u *RefreshTokenUpdateOne) Where(ps ...predicate.RefreshToken) *RefreshTokenUpdateOne {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Select allows selecting one or more fields (columns) of the returned entity.
|
||||
// The default is selecting all fields defined in the entity schema.
|
||||
func (_u *RefreshTokenUpdateOne) Select(field string, fields ...string) *RefreshTokenUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated RefreshToken entity.
|
||||
func (_u *RefreshTokenUpdateOne) Save(ctx context.Context) (*RefreshToken, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *RefreshTokenUpdateOne) SaveX(ctx context.Context) *RefreshToken {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *RefreshTokenUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *RefreshTokenUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *RefreshTokenUpdateOne) check() error {
|
||||
if v, ok := _u.mutation.UserID(); ok {
|
||||
if err := refreshtoken.UserIDValidator(v); err != nil {
|
||||
return &ValidationError{Name: "user_id", err: fmt.Errorf(`ent: validator failed for field "RefreshToken.user_id": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.TokenHash(); ok {
|
||||
if err := refreshtoken.TokenHashValidator(v); err != nil {
|
||||
return &ValidationError{Name: "token_hash", err: fmt.Errorf(`ent: validator failed for field "RefreshToken.token_hash": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *RefreshTokenUpdateOne) sqlSave(ctx context.Context) (_node *RefreshToken, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(refreshtoken.Table, refreshtoken.Columns, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "RefreshToken.id" for update`)}
|
||||
}
|
||||
_spec.Node.ID.Value = id
|
||||
if fields := _u.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, refreshtoken.FieldID)
|
||||
for _, f := range fields {
|
||||
if !refreshtoken.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != refreshtoken.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.UserID(); ok {
|
||||
_spec.SetField(refreshtoken.FieldUserID, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.TokenHash(); ok {
|
||||
_spec.SetField(refreshtoken.FieldTokenHash, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ExpiresAt(); ok {
|
||||
_spec.SetField(refreshtoken.FieldExpiresAt, field.TypeTime, value)
|
||||
}
|
||||
_node = &RefreshToken{config: _u.config}
|
||||
_spec.Assign = _node.assignValues
|
||||
_spec.ScanValues = _node.scanValues
|
||||
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{refreshtoken.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/auditlog"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/schema"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
@@ -36,6 +37,20 @@ func init() {
|
||||
permissionDescName := permissionFields[1].Descriptor()
|
||||
// permission.NameValidator is a validator for the "name" field. It is called by the builders before save.
|
||||
permission.NameValidator = permissionDescName.Validators[0].(func(string) error)
|
||||
refreshtokenFields := schema.RefreshToken{}.Fields()
|
||||
_ = refreshtokenFields
|
||||
// refreshtokenDescUserID is the schema descriptor for user_id field.
|
||||
refreshtokenDescUserID := refreshtokenFields[1].Descriptor()
|
||||
// refreshtoken.UserIDValidator is a validator for the "user_id" field. It is called by the builders before save.
|
||||
refreshtoken.UserIDValidator = refreshtokenDescUserID.Validators[0].(func(string) error)
|
||||
// refreshtokenDescTokenHash is the schema descriptor for token_hash field.
|
||||
refreshtokenDescTokenHash := refreshtokenFields[2].Descriptor()
|
||||
// refreshtoken.TokenHashValidator is a validator for the "token_hash" field. It is called by the builders before save.
|
||||
refreshtoken.TokenHashValidator = refreshtokenDescTokenHash.Validators[0].(func(string) error)
|
||||
// refreshtokenDescCreatedAt is the schema descriptor for created_at field.
|
||||
refreshtokenDescCreatedAt := refreshtokenFields[4].Descriptor()
|
||||
// refreshtoken.DefaultCreatedAt holds the default value on creation for the created_at field.
|
||||
refreshtoken.DefaultCreatedAt = refreshtokenDescCreatedAt.Default.(func() time.Time)
|
||||
roleFields := schema.Role{}.Fields()
|
||||
_ = roleFields
|
||||
// roleDescName is the schema descriptor for name field.
|
||||
|
||||
@@ -16,6 +16,8 @@ type Tx struct {
|
||||
AuditLog *AuditLogClient
|
||||
// Permission is the client for interacting with the Permission builders.
|
||||
Permission *PermissionClient
|
||||
// RefreshToken is the client for interacting with the RefreshToken builders.
|
||||
RefreshToken *RefreshTokenClient
|
||||
// Role is the client for interacting with the Role builders.
|
||||
Role *RoleClient
|
||||
// RolePermission is the client for interacting with the RolePermission builders.
|
||||
@@ -157,6 +159,7 @@ func (tx *Tx) Client() *Client {
|
||||
func (tx *Tx) init() {
|
||||
tx.AuditLog = NewAuditLogClient(tx.config)
|
||||
tx.Permission = NewPermissionClient(tx.config)
|
||||
tx.RefreshToken = NewRefreshTokenClient(tx.config)
|
||||
tx.Role = NewRoleClient(tx.config)
|
||||
tx.RolePermission = NewRolePermissionClient(tx.config)
|
||||
tx.User = NewUserClient(tx.config)
|
||||
|
||||
@@ -29,7 +29,9 @@ type HealthCheckConfig struct {
|
||||
Interval time.Duration // Health check interval
|
||||
Timeout time.Duration // Health check timeout
|
||||
DeregisterAfter time.Duration // Time to wait before deregistering unhealthy service
|
||||
HTTP string // HTTP health check endpoint (e.g., "/healthz")
|
||||
HTTP string // HTTP health check endpoint (e.g., "/healthz") - for HTTP services
|
||||
GRPC string // gRPC health check service name (e.g., "grpc.health.v1.Health") - for gRPC services
|
||||
UseGRPC bool // Whether to use gRPC health checks instead of HTTP
|
||||
}
|
||||
|
||||
// NewRegistry creates a new Consul-based service registry.
|
||||
@@ -67,8 +69,52 @@ func (r *ConsulRegistry) Register(ctx context.Context, service *registry.Service
|
||||
Meta: service.Metadata,
|
||||
}
|
||||
|
||||
// Determine health check type based on service metadata/tags or config
|
||||
// Check if service is HTTP (has "http" tag or protocol metadata)
|
||||
isHTTP := false
|
||||
for _, tag := range service.Tags {
|
||||
if tag == "http" {
|
||||
isHTTP = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isHTTP && service.Metadata != nil {
|
||||
if protocol, ok := service.Metadata["protocol"]; ok && protocol == "http" {
|
||||
isHTTP = true
|
||||
}
|
||||
}
|
||||
|
||||
// Add health check if configured
|
||||
if r.config.HealthCheck.HTTP != "" {
|
||||
if isHTTP && r.config.HealthCheck.HTTP != "" {
|
||||
// Use HTTP health check for HTTP services (e.g., API Gateway)
|
||||
healthCheckURL := fmt.Sprintf("http://%s:%d%s", service.Address, service.Port, r.config.HealthCheck.HTTP)
|
||||
registration.Check = &consulapi.AgentServiceCheck{
|
||||
HTTP: healthCheckURL,
|
||||
Interval: r.config.HealthCheck.Interval.String(),
|
||||
Timeout: r.config.HealthCheck.Timeout.String(),
|
||||
DeregisterCriticalServiceAfter: r.config.HealthCheck.DeregisterAfter.String(),
|
||||
}
|
||||
} else if !isHTTP && r.config.HealthCheck.UseGRPC {
|
||||
// Use gRPC health check for gRPC services
|
||||
// Format: host:port (checks default service with empty string name)
|
||||
// Or: host:port/service (checks specific service name)
|
||||
// We use host:port to check the default service (empty string)
|
||||
grpcAddr := fmt.Sprintf("%s:%d", service.Address, service.Port)
|
||||
// If a specific service name is provided, append it
|
||||
// Otherwise, check the default service (empty string) which we set in each service
|
||||
if r.config.HealthCheck.GRPC != "" && r.config.HealthCheck.GRPC != "grpc.health.v1.Health" {
|
||||
// Only append if it's not the default health service name
|
||||
// The GRPC field in Consul expects the application service name, not the proto service name
|
||||
grpcAddr = fmt.Sprintf("%s:%d/%s", service.Address, service.Port, r.config.HealthCheck.GRPC)
|
||||
}
|
||||
registration.Check = &consulapi.AgentServiceCheck{
|
||||
GRPC: grpcAddr,
|
||||
Interval: r.config.HealthCheck.Interval.String(),
|
||||
Timeout: r.config.HealthCheck.Timeout.String(),
|
||||
DeregisterCriticalServiceAfter: r.config.HealthCheck.DeregisterAfter.String(),
|
||||
}
|
||||
} else if r.config.HealthCheck.HTTP != "" {
|
||||
// Fallback to HTTP if HTTP endpoint is configured and service is not explicitly gRPC
|
||||
healthCheckURL := fmt.Sprintf("http://%s:%d%s", service.Address, service.Port, r.config.HealthCheck.HTTP)
|
||||
registration.Check = &consulapi.AgentServiceCheck{
|
||||
HTTP: healthCheckURL,
|
||||
|
||||
@@ -30,6 +30,9 @@ type IdentityServiceClient interface {
|
||||
|
||||
// ResetPassword resets a user's password using a reset token.
|
||||
ResetPassword(ctx context.Context, token, newPassword string) error
|
||||
|
||||
// VerifyPassword verifies a user's password and returns the user if valid.
|
||||
VerifyPassword(ctx context.Context, email, password string) (*User, error)
|
||||
}
|
||||
|
||||
// User represents a user in the system.
|
||||
|
||||
@@ -2,10 +2,8 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/internal/client"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/config"
|
||||
@@ -51,10 +49,50 @@ func NewGateway(
|
||||
|
||||
// SetupRoutes configures routes on the Gin router.
|
||||
func (g *Gateway) SetupRoutes(router *gin.Engine) {
|
||||
// Setup route handlers
|
||||
// Register routes with wildcard support
|
||||
// Gin uses /*path for wildcards, so we convert /** to /*path
|
||||
for _, route := range g.routes {
|
||||
route := route // Capture for closure
|
||||
router.Any(route.Path, g.handleRoute(route))
|
||||
|
||||
// Convert /** wildcard to Gin's /*path format
|
||||
ginPath := route.Path
|
||||
hasWildcard := strings.HasSuffix(ginPath, "/**")
|
||||
if hasWildcard {
|
||||
ginPath = strings.TrimSuffix(ginPath, "/**") + "/*path"
|
||||
}
|
||||
|
||||
// Register all HTTP methods for this route
|
||||
router.Any(ginPath, func(c *gin.Context) {
|
||||
// Extract the remaining path
|
||||
var remainingPath string
|
||||
if hasWildcard {
|
||||
// Extract from Gin's path parameter
|
||||
pathParam := c.Param("path")
|
||||
if pathParam != "" {
|
||||
remainingPath = "/" + pathParam
|
||||
} else {
|
||||
remainingPath = "/"
|
||||
}
|
||||
} else {
|
||||
// Exact match - no remaining path
|
||||
remainingPath = "/"
|
||||
}
|
||||
|
||||
// Route to appropriate service handler
|
||||
switch route.Service {
|
||||
case "auth-service":
|
||||
g.handleAuthService(c, route, remainingPath)
|
||||
case "identity-service":
|
||||
g.handleIdentityService(c, route, remainingPath)
|
||||
default:
|
||||
g.log.Warn("Unknown service",
|
||||
logger.String("service", route.Service),
|
||||
)
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"error": "Service not found",
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Default handler for unmatched routes
|
||||
@@ -66,62 +104,108 @@ func (g *Gateway) SetupRoutes(router *gin.Engine) {
|
||||
})
|
||||
}
|
||||
|
||||
// handleRoute returns a handler function for a route.
|
||||
func (g *Gateway) handleRoute(route RouteConfig) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// TODO: Add authentication middleware if auth_required is true
|
||||
// TODO: Add rate limiting middleware
|
||||
// TODO: Add CORS middleware
|
||||
|
||||
// Discover service instances
|
||||
ctx := c.Request.Context()
|
||||
instances, err := g.registry.Discover(ctx, route.Service)
|
||||
if err != nil {
|
||||
g.log.Error("Failed to discover service",
|
||||
logger.String("service", route.Service),
|
||||
logger.Error(err),
|
||||
)
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{
|
||||
"error": "Service unavailable",
|
||||
})
|
||||
return
|
||||
// matchRoute finds the matching route configuration for a given path.
|
||||
func (g *Gateway) matchRoute(path string) *RouteConfig {
|
||||
for _, route := range g.routes {
|
||||
if g.pathMatches(path, route.Path) {
|
||||
return &route
|
||||
}
|
||||
|
||||
if len(instances) == 0 {
|
||||
g.log.Warn("No instances found for service",
|
||||
logger.String("service", route.Service),
|
||||
)
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{
|
||||
"error": "Service unavailable",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Use first healthy instance (load balancing can be added later)
|
||||
instance := instances[0]
|
||||
targetURL := fmt.Sprintf("http://%s:%d", instance.Address, instance.Port)
|
||||
|
||||
// Create reverse proxy
|
||||
target, err := url.Parse(targetURL)
|
||||
if err != nil {
|
||||
g.log.Error("Failed to parse target URL",
|
||||
logger.String("url", targetURL),
|
||||
logger.Error(err),
|
||||
)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Internal server error",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
proxy := httputil.NewSingleHostReverseProxy(target)
|
||||
proxy.ServeHTTP(c.Writer, c.Request)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// pathMatches checks if a request path matches a route pattern.
|
||||
// Supports wildcard matching: "/api/v1/auth/**" matches "/api/v1/auth/login", etc.
|
||||
func (g *Gateway) pathMatches(requestPath, routePath string) bool {
|
||||
// Remove trailing slashes for comparison
|
||||
requestPath = strings.TrimSuffix(requestPath, "/")
|
||||
routePath = strings.TrimSuffix(routePath, "/")
|
||||
|
||||
// Exact match
|
||||
if requestPath == routePath {
|
||||
return true
|
||||
}
|
||||
|
||||
// Wildcard match: routePath ends with "/**"
|
||||
if strings.HasSuffix(routePath, "/**") {
|
||||
prefix := strings.TrimSuffix(routePath, "/**")
|
||||
return strings.HasPrefix(requestPath, prefix+"/") || requestPath == prefix
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// extractRemainingPath extracts the path segment after the route prefix.
|
||||
// Example: path="/api/v1/auth/login", route="/api/v1/auth/**" -> returns "/login"
|
||||
func (g *Gateway) extractRemainingPath(requestPath, routePath string) string {
|
||||
// Remove trailing slashes
|
||||
requestPath = strings.TrimSuffix(requestPath, "/")
|
||||
routePath = strings.TrimSuffix(routePath, "/")
|
||||
|
||||
// Handle wildcard routes
|
||||
if strings.HasSuffix(routePath, "/**") {
|
||||
prefix := strings.TrimSuffix(routePath, "/**")
|
||||
if strings.HasPrefix(requestPath, prefix) {
|
||||
remaining := strings.TrimPrefix(requestPath, prefix)
|
||||
if remaining == "" {
|
||||
return "/"
|
||||
}
|
||||
return remaining
|
||||
}
|
||||
}
|
||||
|
||||
// Exact match - no remaining path
|
||||
if requestPath == routePath {
|
||||
return "/"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// loadRoutes loads route configurations from config.
|
||||
func loadRoutes(cfg config.ConfigProvider) []RouteConfig {
|
||||
// For now, return empty routes - will be loaded from config in future
|
||||
// This is a placeholder implementation
|
||||
return []RouteConfig{}
|
||||
if cfg == nil {
|
||||
return []RouteConfig{}
|
||||
}
|
||||
|
||||
// Get routes from config
|
||||
routesInterface := cfg.Get("gateway.routes")
|
||||
if routesInterface == nil {
|
||||
return []RouteConfig{}
|
||||
}
|
||||
|
||||
// Convert to slice of RouteConfig
|
||||
routesSlice, ok := routesInterface.([]interface{})
|
||||
if !ok {
|
||||
return []RouteConfig{}
|
||||
}
|
||||
|
||||
routes := make([]RouteConfig, 0, len(routesSlice))
|
||||
for _, routeInterface := range routesSlice {
|
||||
routeMap, ok := routeInterface.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
route := RouteConfig{}
|
||||
|
||||
if path, ok := routeMap["path"].(string); ok {
|
||||
route.Path = path
|
||||
}
|
||||
|
||||
if service, ok := routeMap["service"].(string); ok {
|
||||
route.Service = service
|
||||
}
|
||||
|
||||
if authRequired, ok := routeMap["auth_required"].(bool); ok {
|
||||
route.AuthRequired = authRequired
|
||||
}
|
||||
|
||||
// Only add route if it has required fields
|
||||
if route.Path != "" && route.Service != "" {
|
||||
routes = append(routes, route)
|
||||
}
|
||||
}
|
||||
|
||||
return routes
|
||||
}
|
||||
|
||||
406
services/gateway/handlers.go
Normal file
406
services/gateway/handlers.go
Normal file
@@ -0,0 +1,406 @@
|
||||
// Package gateway provides API Gateway implementation.
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// handleAuthService handles requests for auth-service routes.
|
||||
func (g *Gateway) handleAuthService(c *gin.Context, route RouteConfig, remainingPath string) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get auth client
|
||||
authClient, err := g.clientFactory.GetAuthClient()
|
||||
if err != nil {
|
||||
g.log.Error("Failed to get auth client",
|
||||
logger.String("error", err.Error()),
|
||||
)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Internal server error",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Route based on path and method
|
||||
switch {
|
||||
case c.Request.Method == http.MethodPost && remainingPath == "/login":
|
||||
g.handleLogin(ctx, c, authClient)
|
||||
case c.Request.Method == http.MethodPost && remainingPath == "/refresh":
|
||||
g.handleRefreshToken(ctx, c, authClient)
|
||||
case c.Request.Method == http.MethodPost && remainingPath == "/validate":
|
||||
g.handleValidateToken(ctx, c, authClient)
|
||||
case c.Request.Method == http.MethodPost && remainingPath == "/logout":
|
||||
g.handleLogout(ctx, c, authClient)
|
||||
default:
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"error": "Endpoint not found",
|
||||
"path": remainingPath,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// handleIdentityService handles requests for identity-service routes.
|
||||
func (g *Gateway) handleIdentityService(c *gin.Context, route RouteConfig, remainingPath string) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get identity client
|
||||
identityClient, err := g.clientFactory.GetIdentityClient()
|
||||
if err != nil {
|
||||
g.log.Error("Failed to get identity client",
|
||||
logger.String("error", err.Error()),
|
||||
)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Internal server error",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Route based on path and method
|
||||
pathParts := strings.Split(strings.Trim(remainingPath, "/"), "/")
|
||||
|
||||
switch {
|
||||
// GET /api/v1/users/:id
|
||||
case c.Request.Method == http.MethodGet && len(pathParts) == 1 && pathParts[0] != "":
|
||||
userID := pathParts[0]
|
||||
g.handleGetUser(ctx, c, identityClient, userID)
|
||||
|
||||
// GET /api/v1/users?email=...
|
||||
case c.Request.Method == http.MethodGet && remainingPath == "" && c.Query("email") != "":
|
||||
email := c.Query("email")
|
||||
g.handleGetUserByEmail(ctx, c, identityClient, email)
|
||||
|
||||
// POST /api/v1/users
|
||||
case c.Request.Method == http.MethodPost && remainingPath == "":
|
||||
g.handleCreateUser(ctx, c, identityClient)
|
||||
|
||||
// PUT /api/v1/users/:id
|
||||
case c.Request.Method == http.MethodPut && len(pathParts) == 1 && pathParts[0] != "":
|
||||
userID := pathParts[0]
|
||||
g.handleUpdateUser(ctx, c, identityClient, userID)
|
||||
|
||||
// DELETE /api/v1/users/:id
|
||||
case c.Request.Method == http.MethodDelete && len(pathParts) == 1 && pathParts[0] != "":
|
||||
userID := pathParts[0]
|
||||
g.handleDeleteUser(ctx, c, identityClient, userID)
|
||||
|
||||
// POST /api/v1/users/verify-email
|
||||
case c.Request.Method == http.MethodPost && remainingPath == "/verify-email":
|
||||
g.handleVerifyEmail(ctx, c, identityClient)
|
||||
|
||||
// POST /api/v1/users/request-password-reset
|
||||
case c.Request.Method == http.MethodPost && remainingPath == "/request-password-reset":
|
||||
g.handleRequestPasswordReset(ctx, c, identityClient)
|
||||
|
||||
// POST /api/v1/users/reset-password
|
||||
case c.Request.Method == http.MethodPost && remainingPath == "/reset-password":
|
||||
g.handleResetPassword(ctx, c, identityClient)
|
||||
|
||||
default:
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"error": "Endpoint not found",
|
||||
"path": remainingPath,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Auth Service Handlers
|
||||
|
||||
func (g *Gateway) handleLogin(ctx context.Context, c *gin.Context, client services.AuthServiceClient) {
|
||||
var req struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Invalid request",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
tokenResp, err := client.Login(ctx, req.Email, req.Password)
|
||||
if err != nil {
|
||||
g.handleGRPCError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, tokenResp)
|
||||
}
|
||||
|
||||
func (g *Gateway) handleRefreshToken(ctx context.Context, c *gin.Context, client services.AuthServiceClient) {
|
||||
var req struct {
|
||||
RefreshToken string `json:"refresh_token" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Invalid request",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
tokenResp, err := client.RefreshToken(ctx, req.RefreshToken)
|
||||
if err != nil {
|
||||
g.handleGRPCError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, tokenResp)
|
||||
}
|
||||
|
||||
func (g *Gateway) handleValidateToken(ctx context.Context, c *gin.Context, client services.AuthServiceClient) {
|
||||
var req struct {
|
||||
Token string `json:"token" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Invalid request",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := client.ValidateToken(ctx, req.Token)
|
||||
if err != nil {
|
||||
g.handleGRPCError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, claims)
|
||||
}
|
||||
|
||||
func (g *Gateway) handleLogout(ctx context.Context, c *gin.Context, client services.AuthServiceClient) {
|
||||
var req struct {
|
||||
RefreshToken string `json:"refresh_token" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Invalid request",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
err := client.Logout(ctx, req.RefreshToken)
|
||||
if err != nil {
|
||||
g.handleGRPCError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
})
|
||||
}
|
||||
|
||||
// Identity Service Handlers
|
||||
|
||||
func (g *Gateway) handleGetUser(ctx context.Context, c *gin.Context, client services.IdentityServiceClient, userID string) {
|
||||
user, err := client.GetUser(ctx, userID)
|
||||
if err != nil {
|
||||
g.handleGRPCError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
func (g *Gateway) handleGetUserByEmail(ctx context.Context, c *gin.Context, client services.IdentityServiceClient, email string) {
|
||||
user, err := client.GetUserByEmail(ctx, email)
|
||||
if err != nil {
|
||||
g.handleGRPCError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
func (g *Gateway) handleCreateUser(ctx context.Context, c *gin.Context, client services.IdentityServiceClient) {
|
||||
var req services.CreateUserRequest
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Invalid request",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := client.CreateUser(ctx, &req)
|
||||
if err != nil {
|
||||
g.handleGRPCError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, user)
|
||||
}
|
||||
|
||||
func (g *Gateway) handleUpdateUser(ctx context.Context, c *gin.Context, client services.IdentityServiceClient, userID string) {
|
||||
var req services.UpdateUserRequest
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Invalid request",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := client.UpdateUser(ctx, userID, &req)
|
||||
if err != nil {
|
||||
g.handleGRPCError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
func (g *Gateway) handleDeleteUser(ctx context.Context, c *gin.Context, client services.IdentityServiceClient, userID string) {
|
||||
err := client.DeleteUser(ctx, userID)
|
||||
if err != nil {
|
||||
g.handleGRPCError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (g *Gateway) handleVerifyEmail(ctx context.Context, c *gin.Context, client services.IdentityServiceClient) {
|
||||
var req struct {
|
||||
Token string `json:"token" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Invalid request",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
err := client.VerifyEmail(ctx, req.Token)
|
||||
if err != nil {
|
||||
g.handleGRPCError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (g *Gateway) handleRequestPasswordReset(ctx context.Context, c *gin.Context, client services.IdentityServiceClient) {
|
||||
var req struct {
|
||||
Email string `json:"email" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Invalid request",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
err := client.RequestPasswordReset(ctx, req.Email)
|
||||
if err != nil {
|
||||
g.handleGRPCError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (g *Gateway) handleResetPassword(ctx context.Context, c *gin.Context, client services.IdentityServiceClient) {
|
||||
var req struct {
|
||||
Token string `json:"token" binding:"required"`
|
||||
NewPassword string `json:"new_password" binding:"required"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Invalid request",
|
||||
"details": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
err := client.ResetPassword(ctx, req.Token, req.NewPassword)
|
||||
if err != nil {
|
||||
g.handleGRPCError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
})
|
||||
}
|
||||
|
||||
// handleGRPCError converts gRPC errors to HTTP status codes and responses.
|
||||
func (g *Gateway) handleGRPCError(c *gin.Context, err error) {
|
||||
st, ok := status.FromError(err)
|
||||
if !ok {
|
||||
g.log.Error("Non-gRPC error from service",
|
||||
logger.String("error", err.Error()),
|
||||
)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Internal server error",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var httpStatus int
|
||||
var errorMsg string
|
||||
|
||||
switch st.Code() {
|
||||
case codes.Unauthenticated:
|
||||
httpStatus = http.StatusUnauthorized
|
||||
errorMsg = "Unauthorized"
|
||||
case codes.PermissionDenied:
|
||||
httpStatus = http.StatusForbidden
|
||||
errorMsg = "Forbidden"
|
||||
case codes.NotFound:
|
||||
httpStatus = http.StatusNotFound
|
||||
errorMsg = "Not found"
|
||||
case codes.InvalidArgument:
|
||||
httpStatus = http.StatusBadRequest
|
||||
errorMsg = "Invalid request"
|
||||
case codes.AlreadyExists:
|
||||
httpStatus = http.StatusConflict
|
||||
errorMsg = "Resource already exists"
|
||||
case codes.Internal:
|
||||
httpStatus = http.StatusInternalServerError
|
||||
errorMsg = "Internal server error"
|
||||
case codes.Unavailable:
|
||||
httpStatus = http.StatusServiceUnavailable
|
||||
errorMsg = "Service unavailable"
|
||||
default:
|
||||
httpStatus = http.StatusInternalServerError
|
||||
errorMsg = "Internal server error"
|
||||
}
|
||||
|
||||
// Include gRPC error message if available
|
||||
response := gin.H{
|
||||
"error": errorMsg,
|
||||
}
|
||||
if st.Message() != "" {
|
||||
response["details"] = st.Message()
|
||||
}
|
||||
|
||||
c.JSON(httpStatus, response)
|
||||
}
|
||||
Reference in New Issue
Block a user