-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogin.go
More file actions
67 lines (51 loc) · 1.68 KB
/
login.go
File metadata and controls
67 lines (51 loc) · 1.68 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
package endpoints
import (
"fantlab/core/db"
"fantlab/pb"
"net/http"
"time"
"golang.org/x/crypto/bcrypt"
"google.golang.org/protobuf/proto"
)
// Создаёт новый аутентификационный токен для пользователя на основе пары логин/пароль
func (api *API) Login(r *http.Request) (int, proto.Message) {
var params struct {
// логин или почта пользователя
Login string `http:"login,form"`
// пароль
Password string `http:"password,form"`
}
api.bindParams(¶ms, r)
// ищем юзера в базе
userLoginInfo, err := api.services.DB().FetchUserLoginInfo(r.Context(), params.Login)
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(userLoginInfo.OldHash), []byte(params.Password))
if err != nil {
err = bcrypt.CompareHashAndPassword([]byte(userLoginInfo.NewHash), []byte(params.Password))
}
if err != nil {
return http.StatusUnauthorized, &pb.Error_Response{
Status: pb.Error_INVALID_PASSWORD,
}
}
// выпускаем новый токен
response, err := api.makeAuthResponse(r, time.Now(), userLoginInfo.UserId, func(entry *db.AuthTokenEntry) error {
return api.services.DB().InsertAuthToken(r.Context(), entry)
})
if err != nil {
return http.StatusInternalServerError, &pb.Error_Response{
Status: pb.Error_SOMETHING_WENT_WRONG,
}
}
// успех
return http.StatusOK, response
}