PersonalMain-Golang/internal/controller/auth/token/tokenController.go

71 lines
2.0 KiB
Go
Raw Normal View History

2023-12-25 02:15:59 +08:00
package token
import (
2023-12-27 01:48:24 +08:00
"PersonalMain/api"
2023-12-25 02:15:59 +08:00
"PersonalMain/api/request"
"PersonalMain/internal/model/do"
"PersonalMain/internal/service/TokenService"
2023-12-25 02:28:28 +08:00
"PersonalMain/utility/ErrorCode"
"PersonalMain/utility/ResultUtil"
2023-12-25 02:15:59 +08:00
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
2023-12-27 01:48:24 +08:00
type ControllerV1 struct{}
func NewTokenV1() api.ITokenV1 {
return &ControllerV1{}
}
2023-12-25 02:28:28 +08:00
// TokenCreate
//
// 生成 TokenServiceImpl
2023-12-26 17:14:09 +08:00
func (*ControllerV1) TokenCreate(ctx context.Context, _ *request.TokenCreateReq) (res *request.TokenCreateRes, err error) {
2023-12-25 02:15:59 +08:00
// 获取 Cookie 是否存在
req := ghttp.RequestFromCtx(ctx)
hasCookie := req.Cookie.Contains("token")
tokenService := TokenService.NewTokenService()
2023-12-25 02:15:59 +08:00
var token *do.TokenDO
if hasCookie {
// 检查 Session 是否有效
token = tokenService.GetToken(req)
if tokenService.VerifyToken(token) {
// 有效则输出Token依然有效
ResultUtil.Success(req, "TokenServiceImpl 依然有效", nil)
2023-12-25 02:15:59 +08:00
} else {
// 生成新的 Session
token = tokenService.CreateToken()
ResultUtil.Success(req, "TokenServiceImpl 已重新生成", g.Map{"token": token.Token})
2023-12-25 02:15:59 +08:00
}
} else {
// 生成新的 Session
token = tokenService.CreateToken()
ResultUtil.Success(req, "TokenServiceImpl 已生成", g.Map{"token": token.Token})
2023-12-25 02:28:28 +08:00
}
return res, err
}
// TokenVerify
//
// 验证 TokenServiceImpl
2023-12-26 17:14:09 +08:00
func (*ControllerV1) TokenVerify(ctx context.Context, _ *request.TokenVerifyReq) (res *request.TokenVerifyRes, err error) {
2023-12-25 02:28:28 +08:00
// 获取 Cookie 是否存在
req := ghttp.RequestFromCtx(ctx)
hasCookie := req.Cookie.Contains("token")
tokenService := TokenService.NewTokenService()
2023-12-25 02:28:28 +08:00
var token *do.TokenDO
if hasCookie {
// 检查 Session 是否有效
token = tokenService.GetToken(req)
if tokenService.VerifyToken(token) {
ResultUtil.SuccessNoData(req, "TokenServiceImpl 有效")
2023-12-25 02:28:28 +08:00
} else {
ResultUtil.ErrorNoData(req, ErrorCode.TokenVerifyFailed)
}
} else {
ResultUtil.ErrorNoData(req, ErrorCode.TokenExpired)
2023-12-25 02:15:59 +08:00
}
return res, err
}