ms-auth/internal/sessions/delivery/grpc/handlers.go
Vyacheslav1557 93eaf89d78 refactor:
2024-10-09 22:07:38 +05:00

90 lines
2.5 KiB
Go

package grpc
import (
"context"
"git.sch9.ru/new_gate/ms-auth/internal/models"
"git.sch9.ru/new_gate/ms-auth/internal/sessions"
"git.sch9.ru/new_gate/ms-auth/internal/users"
sessionv1 "git.sch9.ru/new_gate/ms-auth/pkg/go/gen/proto/session/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 sessionHandlers struct {
sessionv1.UnimplementedSessionServiceServer
sessionUC sessions.UseCase
userUC users.UseCase
}
func NewSessionHandlers(gserver *grpc.Server, sessionUC sessions.UseCase, userUC users.UseCase) {
handlers := &sessionHandlers{
sessionUC: sessionUC,
userUC: userUC,
}
sessionv1.RegisterSessionServiceServer(gserver, handlers)
}
func (s *sessionHandlers) Create(ctx context.Context, req *sessionv1.CreateSessionRequest) (*sessionv1.CreateSessionResponse, error) {
var (
err error
user *models.User
)
handle := req.GetHandle()
password := req.GetPassword()
if utils.ValidUsername(handle) == nil {
user, err = s.userUC.ReadUserByUsername(ctx, req.GetHandle())
} else if utils.ValidEmail(handle) == nil {
user, err = s.userUC.ReadUserByEmail(ctx, handle)
} else {
return nil, utils.ErrBadHandleOrPassword
}
if err != nil {
return nil, err
}
err = user.ComparePassword(password)
if err != nil {
return nil, err
}
token, err := s.sessionUC.Create(ctx, *user.Id)
if err != nil {
return nil, status.Errorf(codes.Unknown, err.Error()) // FIXME
}
return &sessionv1.CreateSessionResponse{
Token: *token,
}, nil
}
func (s *sessionHandlers) Read(ctx context.Context, req *sessionv1.ReadSessionRequest) (*sessionv1.ReadSessionResponse, error) {
id, err := s.sessionUC.Read(ctx, req.GetToken())
if err != nil {
return nil, status.Errorf(codes.Unknown, err.Error()) // FIXME
}
return &sessionv1.ReadSessionResponse{
UserId: *id,
}, nil
}
func (s *sessionHandlers) Update(ctx context.Context, req *sessionv1.UpdateSessionRequest) (*emptypb.Empty, error) {
err := s.sessionUC.Update(ctx, req.GetToken())
if err != nil {
return nil, status.Errorf(codes.Unknown, err.Error()) // FIXME
}
return &emptypb.Empty{}, nil
}
func (s *sessionHandlers) Delete(ctx context.Context, req *sessionv1.DeleteSessionRequest) (*emptypb.Empty, error) {
err := s.sessionUC.Delete(ctx, req.GetToken())
if err != nil {
return nil, status.Errorf(codes.Unknown, err.Error()) // FIXME
}
return &emptypb.Empty{}, nil
}