-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrefresh_auth.go
More file actions
73 lines (55 loc) · 1.87 KB
/
refresh_auth.go
File metadata and controls
73 lines (55 loc) · 1.87 KB
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
package endpoints
import (
"fantlab/core/app"
"fantlab/core/config"
"fantlab/core/db"
"fantlab/pb"
"net/http"
"time"
"golang.org/x/crypto/bcrypt"
"google.golang.org/protobuf/proto"
)
// Продлевает сессию с помощью рефреш-токена
func (api *API) RefreshAuth(r *http.Request) (int, proto.Message) {
var params struct {
// рефреш-токен, выданный при логине или предыдущем продлении сессии
RefreshToken string `http:"refresh_token,form"`
}
api.bindParams(¶ms, r)
auth := app.GetUserAuth(r.Context())
// ищем токен в базе
authToken, err := api.services.DB().FetchAuthToken(r.Context(), auth.TokenId)
if db.IsNotFoundError(err) {
return http.StatusNotFound, &pb.Error_Response{
Status: pb.Error_NOT_FOUND,
}
} else if err != nil {
return http.StatusInternalServerError, &pb.Error_Response{
Status: pb.Error_SOMETHING_WENT_WRONG,
}
}
// проверяем рефреш-токен
err = bcrypt.CompareHashAndPassword([]byte(authToken.RefreshHash), []byte(params.RefreshToken))
if err != nil {
return http.StatusUnauthorized, &pb.Error_Response{
Status: pb.Error_INVALID_REFRESH_TOKEN,
}
}
// проверяем валидность рефреш-токена
if time.Until(authToken.IssuedAt.Add(config.RefreshTokenTimeout)) < 0 {
return http.StatusUnauthorized, &pb.Error_Response{
Status: pb.Error_REFRESH_TOKEN_EXPIRED,
}
}
// выпускаем новый токен
response, err := api.makeAuthResponse(r, time.Now(), auth.User.UserId, func(entry *db.AuthTokenEntry) error {
return api.services.DB().ReplaceAuthToken(r.Context(), entry, auth.TokenId)
})
if err != nil {
return http.StatusInternalServerError, &pb.Error_Response{
Status: pb.Error_SOMETHING_WENT_WRONG,
}
}
// успех
return http.StatusOK, response
}