-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
94 lines (72 loc) · 2.1 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
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package goadmin
import (
"encoding/hex"
"net/http"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
"github.com/xxtea/xxtea-go/xxtea"
)
func auth(ctx *AppContext) (result User, err error) {
login := ctx.FormValue("login")
password := ctx.FormValue("password")
result.Login = login
result.Password = password
user, err := ctx.UserCase().SearchByLogin(ctx.Ctx(), login)
if err != nil {
return result, err
}
ok, err := ctx.UserCase().ComparePassword(user, password)
if err != nil {
return result, err
}
if !ok {
return result, ErrWrongPassword
}
token, err := ctx.UserCase().CreateAuthToken(ctx.Ctx(), user)
if err != nil {
return result, errors.Wrap(err, "creating auth token failed")
}
err = ctx.UserCase().SetLastLogged(ctx.Ctx(), user)
if err != nil {
return result, errors.Wrap(err, "updating user failed")
}
key := ctx.RealIP() + ctx.Request().UserAgent()
tokenValue := xxtea.Encrypt([]byte(token.Token), []byte(key))
http.SetCookie(ctx.Response(), &http.Cookie{
Name: AccessCookieName,
Value: hex.EncodeToString(tokenValue),
Expires: token.DTExpired,
Path: "/",
HttpOnly: true,
})
return result, nil
}
func authByCookie(ctx *AppContext) (*User, error) {
t, err := ctx.Cookie(AccessCookieName)
if err != nil {
return nil, echo.NewHTTPError(http.StatusBadRequest, err)
}
value, err := hex.DecodeString(t.Value)
if err != nil {
return nil, errors.Wrap(err, "decoding cookie value failed")
}
key := ctx.RealIP() + ctx.Request().UserAgent()
tokenValue := xxtea.Decrypt(value, []byte(key))
c := ctx.Request().Context()
token, err := ctx.UserCase().SearchToken(c, string(tokenValue))
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError).SetInternal(err)
}
if token.Type != AuthToken {
return nil, echo.NewHTTPError(http.StatusForbidden)
}
if token.IsExpired() {
return nil, echo.NewHTTPError(http.StatusNotFound)
}
err = ctx.UserCase().SetLastLogged(c, token.User)
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError).SetInternal(err)
}
token.User.Current = true
return token.User, nil
}