package grpc import ( "context" "git.sch9.ru/new_gate/ms-auth/internal/models" "git.sch9.ru/new_gate/ms-auth/internal/users" userv1 "git.sch9.ru/new_gate/ms-auth/pkg/go/gen/proto/user/v1" "git.sch9.ru/new_gate/ms-auth/pkg/utils" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/emptypb" ) type userHandlers struct { userv1.UnimplementedUserServiceServer userUC users.UseCase } func NewUserHandlers(gserver *grpc.Server, userUC users.UseCase) { handlers := &userHandlers{ userUC: userUC, } userv1.RegisterUserServiceServer(gserver, handlers) } func (h *userHandlers) CreateUser(ctx context.Context, req *userv1.CreateUserRequest) (*userv1.CreateUserResponse, error) { user := req.GetUser() if user == nil { return nil, status.Errorf(codes.Unknown, "") // FIXME } id, err := h.userUC.CreateUser( ctx, &models.User{ Username: utils.AsStringP(user.GetUsername()), Password: utils.AsStringP(user.GetPassword()), Email: nil, ExpiresAt: utils.TimeP(user.ExpiresAt), Role: AsMRoleP(user.GetRole()), }, ) if err != nil { return nil, status.Errorf(codes.Unknown, err.Error()) // FIXME } return &userv1.CreateUserResponse{ Id: id, }, nil } func (h *userHandlers) ReadUser(ctx context.Context, req *userv1.ReadUserRequest) (*userv1.ReadUserResponse, error) { user, err := h.userUC.ReadUser( ctx, req.GetId(), ) if err != nil { return nil, status.Errorf(codes.Unknown, err.Error()) // FIXME } return &userv1.ReadUserResponse{ User: &userv1.ReadUserResponse_User{ Id: *user.Id, Username: *user.Username, ExpiresAt: utils.TimestampP(user.ExpiresAt), CreatedAt: utils.TimestampP(user.CreatedAt), Role: *AsRoleP(user.Role), }, }, nil } func (h *userHandlers) UpdateUser(ctx context.Context, req *userv1.UpdateUserRequest) (*emptypb.Empty, error) { user := req.GetUser() if user == nil { return nil, status.Errorf(codes.Unknown, "") // FIXME } err := h.userUC.UpdateUser( ctx, &models.User{ Id: utils.AsInt32P(user.GetId()), Username: utils.AsStringP(user.GetUsername()), Password: utils.AsStringP(user.GetPassword()), Email: nil, ExpiresAt: utils.TimeP(user.ExpiresAt), Role: AsMRoleP(user.GetRole()), }, ) if err != nil { return nil, status.Errorf(codes.Unknown, err.Error()) // FIXME } return &emptypb.Empty{}, nil } func (h *userHandlers) DeleteUser(ctx context.Context, req *userv1.DeleteUserRequest) (*emptypb.Empty, error) { err := h.userUC.DeleteUser( ctx, req.GetId(), ) if err != nil { return nil, status.Errorf(codes.Unknown, err.Error()) // FIXME } return &emptypb.Empty{}, nil } func AsMRoleP(v userv1.Role) *models.Role { vv := models.Role(v.Number()) return &vv } func AsRoleP(r *models.Role) *userv1.Role { if r == nil { return nil } rr := userv1.Role(*r) return &rr }