Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

长短token 登录 #10

Merged
merged 5 commits into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/dlclark/regexp2 v1.10.0
github.com/gin-gonic/gin v1.9.1
github.com/go-sql-driver/mysql v1.7.1
github.com/golang-jwt/jwt/v5 v5.0.0
github.com/stretchr/testify v1.8.4
go.uber.org/mock v0.2.0
gorm.io/driver/mysql v1.5.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrt
github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE=
github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
Expand Down
103 changes: 98 additions & 5 deletions internal/integration/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,17 @@ import (
"testing"
"time"

"github.com/ecodeclub/webook/internal/repository"
"github.com/ecodeclub/webook/internal/repository/dao"
"github.com/ecodeclub/webook/internal/service"
"github.com/ecodeclub/webook/internal/web"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/mysql"
"gorm.io/gorm"

"github.com/ecodeclub/webook/internal/repository"
"github.com/ecodeclub/webook/internal/repository/dao"
"github.com/ecodeclub/webook/internal/service"
"github.com/ecodeclub/webook/internal/web"
jwt2 "github.com/ecodeclub/webook/internal/web/encryption/jwt"
)

func TestUserHandler_e2e_SignUp(t *testing.T) {
Expand Down Expand Up @@ -171,6 +174,95 @@ func TestUserHandler_e2e_SignUp(t *testing.T) {
}
}

func TestUserHandler_e2e_Login(t *testing.T) {
// server := InitWebServer()
server := gin.Default()
//db := initDB()
var db *gorm.DB
da := dao.NewUserInfoDAO(db)
repo := repository.NewUserInfoRepository(da)
svc := service.NewUserService(repo)

jwt := jwt2.NewJwt()
userHandle := web.NewUserHandler(svc, jwt)
userHandle.RegisterRoutes(server)
now := time.Now()

testCases := []struct {
name string
before func(t *testing.T)
reqBody string
wantCode int
wantBody string
fingerprint string
after func(t *testing.T)
//userId int64 // jwt-token 中携带的信息
}{
{
name: "参数绑定失败",
reqBody: `{"email":"asxxxxxxxxxx163.com","password":"123456","fingerprint":""}`,
wantCode: http.StatusBadRequest,
wantBody: "参数合法性验证失败",
fingerprint: "",
},
{
name: "登陆成功",
reqBody: `{"email":"[email protected]","password":"123456","fingerprint":"long-short-token"}`,
wantCode: http.StatusOK,
wantBody: "登陆成功",
fingerprint: "long-short-token",
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
//构造请求
req, err := http.NewRequest(http.MethodPost, "/users/login", bytes.NewBuffer([]byte(tc.reqBody)))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")

//用于接收resp
resp := httptest.NewRecorder()

server.ServeHTTP(resp, req)

// 判断结果
assert.Equal(t, tc.wantCode, resp.Code)

assert.Equal(t, tc.wantBody, resp.Body.String())
//登录成功才需要判断
if resp.Code == http.StatusOK {
accessToken := resp.Header().Get("x-access-token")
refreshToken := resp.Header().Get("x-refresh-token")
//jwt.Decrypt(accessToken, web.AccessSecret)
acessT, err := jwt.Decrypt(accessToken, web.AccessSecret)
if err != nil {
panic(err)
}
accessTokenClaim := acessT.(*jwt2.TokenClaims)
assert.Equal(t, tc.fingerprint, accessTokenClaim.Fingerprint)
//判断过期时间
if now.Add(time.Minute*29).UnixMilli() > accessTokenClaim.RegisteredClaims.ExpiresAt.Time.UnixMilli() {
panic("过期时间异常")
return
}

refreshT, err := jwt.Decrypt(refreshToken, web.RefreshSecret)
if err != nil {
panic(err)
}
refreshTokenClaim := refreshT.(*jwt2.TokenClaims)
assert.Equal(t, tc.fingerprint, refreshTokenClaim.Fingerprint)
//判断过期时间
if now.Add(time.Hour*168).UnixMilli() < accessTokenClaim.RegisteredClaims.ExpiresAt.Time.UnixMilli() {
panic("过期时间异常")
return
}
}
})
}
}

func InitTest() *gin.Engine {
r := initWebServer()
db := initDB()
Expand Down Expand Up @@ -216,6 +308,7 @@ func initUser(db *gorm.DB) *web.UserHandler {
da := dao.NewUserInfoDAO(db)
repo := repository.NewUserInfoRepository(da)
svc := service.NewUserService(repo)
u := web.NewUserHandler(svc)
jwt := jwt2.NewJwt()
u := web.NewUserHandler(svc, jwt)
return u
}
63 changes: 63 additions & 0 deletions internal/web/encryption/jwt/jwt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package jwt

import (
"errors"
"time"

"github.com/golang-jwt/jwt/v5"

"github.com/ecodeclub/webook/internal/web/encryption"
)

type TokenClaims struct {
jwt.RegisteredClaims
// 这是一个前端采集了用户的登录环境生成的一个码
Fingerprint string
//用于查找用户信息的一个字段
Id int64
}

type Jwt struct {
//secretCode string
}

func NewJwt() encryption.Handle {
flycash marked this conversation as resolved.
Show resolved Hide resolved
return &Jwt{}
}

func (j *Jwt) Encryption(arg map[string]string, secretCode string, duration time.Duration) (encryptString string, err error) {
now := time.Now()
fingerprint, ok := arg["fingerprint"]
if !ok {
return "", errors.New("参数缺失")
}
claims := TokenClaims{
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(duration)),
},
Fingerprint: fingerprint,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)

encryptString, err = token.SignedString([]byte(secretCode))
if err != nil {
return "", nil
}
return encryptString, nil
}

func (j *Jwt) Decrypt(tokenStr string, secretCode string) (interface{}, error) {
claims := &TokenClaims{}
token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(secretCode), nil
})
if err != nil {
return nil, err
}
if token == nil || !token.Valid {
//解析成功 但是 token 以及 claims 不一定合法
return nil, errors.New("不合法操作")
}

return claims, nil
}
65 changes: 65 additions & 0 deletions internal/web/encryption/jwt/mock/jwt_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions internal/web/encryption/type.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package encryption

import "time"

type Handle interface {
Encryption(map[string]string, string, time.Duration) (encryptString string, err error)
Decrypt(tokenStr string, secretCode string) (interface{}, error)
}
1 change: 1 addition & 0 deletions internal/web/init_web.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ import "github.com/gin-gonic/gin"

func (u *UserHandler) RegisterRoutes(server *gin.Engine) {
server.POST("/users/signup", u.SignUp)
server.POST("/users/login", u.Login)
}
45 changes: 43 additions & 2 deletions internal/web/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,34 @@ package web

import (
"net/http"
"time"

regexp "github.com/dlclark/regexp2"
"github.com/gin-gonic/gin"

"github.com/ecodeclub/webook/internal/domain"
"github.com/ecodeclub/webook/internal/service"
"github.com/gin-gonic/gin"
"github.com/ecodeclub/webook/internal/web/encryption"
)

const (
//密码规则:长度至少 6 位
passwordRegexPattern = `^.{6,}$`
AccessSecret = "95osj3fUD7fo0mlYdDbncXz4VD2igvf0"
RefreshSecret = "95osj3fUD7fo0m123DbncXz4VD2igvf0"
)

type UserHandler struct {
svc service.UserAndService
passwordRegexExp *regexp.Regexp
encryption.Handle
}

func NewUserHandler(svc service.UserAndService) *UserHandler {
func NewUserHandler(svc service.UserAndService, jwt encryption.Handle) *UserHandler {
return &UserHandler{
svc: svc,
passwordRegexExp: regexp.MustCompile(passwordRegexPattern, regexp.None),
Handle: jwt,
}
}

Expand Down Expand Up @@ -69,3 +76,37 @@ func (u *UserHandler) SignUp(ctx *gin.Context) {
}
ctx.String(http.StatusOK, "注册成功!")
}

func (u *UserHandler) Login(ctx *gin.Context) {
type TokenLoginReq struct {
Email string `json:"email" binding:"required,email"`
Password string `json:"password" binding:"required"`
Fingerprint string `json:"fingerprint" binding:"required"` //你可以认为这是一个前端采集了用户的登录环境生成的一个码,你编码进去 EncryptionHandle acccess_token 中。
}
var req TokenLoginReq
err := ctx.ShouldBind(&req)
if err != nil {
ctx.String(http.StatusBadRequest, "参数合法性验证失败")
return
}
//验证登录用户合法性 获取个人信息查找的标识: 例如id
tmpMap := map[string]string{
flycash marked this conversation as resolved.
Show resolved Hide resolved
//"id":id,
"fingerprint": req.Fingerprint,
}
accessToken, err := u.Encryption(tmpMap, AccessSecret, time.Minute*30)
if err != nil {
ctx.String(http.StatusInternalServerError, "系统异常")
return
}
refreshToken, err := u.Encryption(tmpMap, RefreshSecret, time.Hour*24*7)
if err != nil {
ctx.String(http.StatusInternalServerError, "系统异常")
return
}
ctx.Header("x-access-token", accessToken)
ctx.Header("x-refresh-token", refreshToken)
//可以换一种方式保持到redis里面,避免refresh_token 被人拿到之后一直使用
//可以使用MD5 转一下,或者直接截取指定长度的字符串 如: 以key 为 前面获取到的字符串
ctx.String(http.StatusOK, "登陆成功")
}
Loading