-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
42 lines (37 loc) · 1.29 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package handler
import (
"context"
"github.com/ScoreTrak/ScoreTrak/pkg/auth"
authpb "github.com/ScoreTrak/ScoreTrak/pkg/proto/auth/v1"
"github.com/ScoreTrak/ScoreTrak/pkg/user/userservice"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type AuthController struct {
svc userservice.Serv
jwtManager *auth.Manager
authpb.UnimplementedAuthServiceServer
}
func NewAuthController(svc userservice.Serv, jwtManager *auth.Manager) *AuthController {
return &AuthController{svc: svc, jwtManager: jwtManager}
}
func (a AuthController) Login(ctx context.Context, request *authpb.LoginRequest) (*authpb.LoginResponse, error) {
if request.GetUsername() == "" || request.GetPassword() == "" {
return nil, status.Errorf(
codes.InvalidArgument,
"Username and password should not be empty",
)
}
usr, err := a.svc.GetByUsername(ctx, request.GetUsername())
if err != nil {
return nil, status.Errorf(codes.Internal, "cannot retrieve user: %v", err)
}
if usr == nil || !usr.IsCorrectPassword(request.GetPassword()) {
return nil, status.Errorf(codes.NotFound, "incorrect username/password")
}
token, err := a.jwtManager.Generate(usr)
if err != nil {
return nil, status.Errorf(codes.Internal, "cannot generate access token")
}
return &authpb.LoginResponse{AccessToken: token}, nil
}