-
Notifications
You must be signed in to change notification settings - Fork 0
/
authentication_service.go
64 lines (51 loc) · 1.79 KB
/
authentication_service.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package authentication
import (
"context"
"time"
"github.com/manumura/go-auth-rbac-starter/db"
"github.com/rs/zerolog/log"
)
type AuthenticationService interface {
CreateAuthentication(ctx context.Context, req AuthenticationRequest) (db.AuthenticationToken, error)
GetByAccessToken(ctx context.Context, token string) (db.AuthenticationToken, error)
}
type AuthenticationServiceImpl struct {
datastore db.DataStore
}
func NewAuthenticationService(datastore db.DataStore) AuthenticationService {
return &AuthenticationServiceImpl{
datastore: datastore,
}
}
func (service *AuthenticationServiceImpl) CreateAuthentication(ctx context.Context, req AuthenticationRequest) (db.AuthenticationToken, error) {
var t db.AuthenticationToken
err := service.datastore.ExecTx(ctx, func(q *db.Queries) error {
var err error
log.Info().Msg("deleting existing authentication token")
err = q.DeleteAuthenticationToken(ctx, req.UserID)
if err != nil {
return err
}
log.Info().Msg("creating new authentication token")
now := time.Now().UTC()
r := db.CreateAuthenticationTokenParams{
UserID: req.UserID,
AccessToken: req.AccessToken,
AccessTokenExpiresAt: req.AccessTokenExpiresAt.Format(time.DateTime),
RefreshToken: req.RefreshToken,
RefreshTokenExpiresAt: req.RefreshTokenExpiresAt.Format(time.DateTime),
CreatedAt: now.Format(time.DateTime),
}
t, err = q.CreateAuthenticationToken(ctx, r)
if err != nil {
return err
}
log.Info().Msg("new authentication token created")
return nil
})
return t, err
}
func (service *AuthenticationServiceImpl) GetByAccessToken(ctx context.Context, token string) (db.AuthenticationToken, error) {
t, err := service.datastore.GetAuthenticationTokenByAccessToken(ctx, token)
return t, err
}