Skip to content

Commit

Permalink
feat: 登录接口增加返回用户id和token时间信息
Browse files Browse the repository at this point in the history
  • Loading branch information
jorben committed Jul 3, 2024
1 parent 8bdcdfa commit be33edf
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
2 changes: 1 addition & 1 deletion router/api/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func AuthCallback(ctx *gin.Context) {
return
}

c.CJSON(errs.Success, gin.H{"token": token})
c.CJSON(errs.Success, token)
}

// AuthRenew 续期JWT
Expand Down
29 changes: 22 additions & 7 deletions service/authservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ type AuthService struct {
signKey []byte
}

type AuthToken struct {
Token string `json:"token"`
UserId string `json:"user_id"`
ExpiresAt int64 `json:"expires_at"`
NotBefore int64 `json:"not_before"`
}

// NewAuthService 新建AuthService实例
func NewAuthService(ctx *gin.Context) *AuthService {

Expand All @@ -31,23 +38,23 @@ func NewAuthService(ctx *gin.Context) *AuthService {
}

// LoginBySource 从第三方登陆
func (a *AuthService) LoginBySource(info *model.UserSocialInfo) (string, error) {
func (a *AuthService) LoginBySource(info *model.UserSocialInfo) (*AuthToken, error) {
// 检查是否已存在该用户
user := a.UserDal.GetUserBySource(info.Source, info.OpenId)
if user == nil {
// 不存在则插入用户
id, err := a.UserDal.SignUpBySource(info)
if err != nil {
log.Errorf(a.Ctx, "UserDal.SignUpBySource failed, err: %s", err.Error())
return "", err
return nil, err
}
return a.SignJwtString(id)
} else {
// 存在则更新信息
_, err := a.UserDal.UpdateBySource(info)
if err != nil {
log.Errorf(a.Ctx, "UserDal.UpdateBySource failed, err: %s", err.Error())
return "", nil
return nil, err
}
return a.SignJwtString(user.BindUserId)
}
Expand All @@ -67,21 +74,29 @@ func (a *AuthService) IsAllow(userId string, path string, method string) bool {
}

// SignJwtString 签发JWT
func (a *AuthService) SignJwtString(id uint) (string, error) {
func (a *AuthService) SignJwtString(id uint) (*AuthToken, error) {
now := time.Now()
expiresAt := now.Add(2 * time.Hour)
notBefore := now.Add(-5 * time.Minute)
claims := jwt.RegisteredClaims{
Issuer: "league",
ExpiresAt: jwt.NewNumericDate(now.Add(2 * time.Hour)),
NotBefore: jwt.NewNumericDate(now.Add(-1 * time.Minute)),
ExpiresAt: jwt.NewNumericDate(expiresAt),
NotBefore: jwt.NewNumericDate(notBefore),
IssuedAt: jwt.NewNumericDate(now),
ID: fmt.Sprintf("%d", id),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS384, claims)
sign, err := token.SignedString(a.signKey)
if err != nil {
log.Errorf(a.Ctx, "Jwt SignedString failed, err: %s", err.Error())
return nil, err
}
return sign, err
return &AuthToken{
Token: sign,
UserId: fmt.Sprintf("%d", id),
ExpiresAt: expiresAt.Unix(),
NotBefore: notBefore.Unix(),
}, nil
}

// VerifyJwtString 校验JWT
Expand Down

0 comments on commit be33edf

Please sign in to comment.