/
loginlogic.go
70 lines (61 loc) · 1.55 KB
/
loginlogic.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
package logic
import (
"context"
"errors"
"time"
"github.com/golang-jwt/jwt"
"github.com/zeromicro/cds/cmd/galaxy/internal/svc"
"github.com/zeromicro/cds/cmd/galaxy/internal/types"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type LoginLogic struct {
ctx context.Context
logx.Logger
svcCtx *svc.ServiceContext
}
func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) LoginLogic {
return LoginLogic{
ctx: ctx,
Logger: logx.WithContext(ctx),
svcCtx: svcCtx,
}
// TODO need set model here from svc
}
func (l *LoginLogic) Login(req types.UserLoginRequest) (*types.TokenResponse, error) {
u, e := l.svcCtx.UserModel.FindByEmail(req.Email)
if e != nil {
if e == sqlx.ErrNotFound {
return nil, errors.New("账户未找到")
}
logx.Error(e)
return nil, e
}
if u.Password != req.Password {
return nil, errors.New("密码错误")
}
info := map[string]interface{}{
"name": u.Name,
"email": u.Email,
"id": u.ID,
"perm": u.GroupID,
}
auth, err := genToken(l.svcCtx.Config.Auth.AccessSecret, info, 24*3600)
if err != nil {
logx.Error(err)
return nil, err
}
return &types.TokenResponse{Auth: auth}, nil
}
func genToken(secretKey string, payloads map[string]interface{}, seconds int64) (string, error) {
now := time.Now().Unix()
claims := make(jwt.MapClaims)
claims["exp"] = now + seconds
claims["iat"] = now
for k, v := range payloads {
claims[k] = v
}
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(secretKey))
}