generated from resonatecoop/id-server-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
access_token.go
74 lines (60 loc) · 1.53 KB
/
access_token.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
65
66
67
68
69
70
71
72
73
74
package oauth
import (
"context"
"time"
"github.com/google/uuid"
"github.com/litesolutions/justifay-api/model"
)
// GrantAccessToken deletes old tokens and grants a new access token
func (s *Service) GrantAccessToken(client *model.Client, user *model.User, expiresIn int, scope string) (*model.AccessToken, error) {
// Begin a transaction
tx, err := s.db.Begin()
ctx := context.Background()
//var result Sql.result
if err != nil {
return nil, err
}
accessToken := new(model.AccessToken)
// Delete expired access tokens
if user != nil && user.ID != uuid.Nil {
_, err = tx.NewDelete().
Model(accessToken).
Where("user_id = ?", user.ID).
Where("client_id = ?", client.ID).
Where("expires_at <= ?", time.Now()).
Exec(ctx)
} else {
_, err = tx.NewDelete().
Model(accessToken).
Where("user_id = uuid_nil()").
Where("client_id = ?", client.ID).
Where("expires_at <= ?", time.Now()).
Exec(ctx)
}
if err != nil {
tx.Rollback() // rollback the transaction
return nil, err
}
// Create a new access token
accessToken = model.NewOauthAccessToken(client, user, expiresIn, scope)
_, err = tx.NewInsert().
Model(accessToken).
Exec(ctx)
if err != nil {
tx.Rollback() // rollback the transaction
return nil, err
}
accessToken.ClientID = client.ID
if user == nil {
accessToken.UserID = uuid.Nil
} else {
accessToken.UserID = user.ID
}
// Commit the transaction
err = tx.Commit()
if err != nil {
tx.Rollback() // rollback the transaction
return nil, err
}
return accessToken, nil
}