用户注册,用户登陆模块完善
This commit is contained in:
parent
79250bc0db
commit
ab93bd397a
|
@ -15,8 +15,10 @@ type IHelloV1 interface {
|
|||
|
||||
type IAuthV1 interface {
|
||||
AuthRegister(ctx context.Context, req *request.RegisterReq) (res *request.RegisterRes, err error)
|
||||
AuthLogin(ctx context.Context, req *request.LoginReq) (res *request.LoginRes, err error)
|
||||
}
|
||||
|
||||
type ITokenV1 interface {
|
||||
TokenCreate(ctx context.Context, req *request.TokenCreateReq) (res *request.TokenCreateRes, err error)
|
||||
TokenVerify(ctx context.Context, req *request.TokenVerifyReq) (res *request.TokenVerifyRes, err error)
|
||||
}
|
||||
|
|
|
@ -5,16 +5,11 @@ import (
|
|||
)
|
||||
|
||||
type RegisterReq struct {
|
||||
g.Meta `path:"/register" tags:"注册" method:"get" summary:"注册账号"`
|
||||
|
||||
Username string `json:"username"`
|
||||
g.Meta `path:"/register" tags:"注册" method:"post" summary:"注册账号"`
|
||||
}
|
||||
type LoginReq struct {
|
||||
g.Meta `path:"/login" tags:"登录" method:"get" summary:"登录账号"`
|
||||
}
|
||||
|
||||
type RegisterRes struct {
|
||||
g.Meta `mime:"application/json" example:"string"`
|
||||
|
||||
Output string `json:"output"`
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data any `json:"data"`
|
||||
}
|
||||
type RegisterRes struct{}
|
||||
type LoginRes struct{}
|
||||
|
|
|
@ -3,11 +3,11 @@ package request
|
|||
import "github.com/gogf/gf/v2/frame/g"
|
||||
|
||||
type TokenCreateReq struct {
|
||||
g.Meta `path:"/create" tags:"创建" method:"get" summary:"创建 Token"`
|
||||
g.Meta `path:"/create" tags:"创建" method:"get" summary:"创建 TokenServiceImpl"`
|
||||
}
|
||||
type TokenCreateRes struct{}
|
||||
|
||||
type TokenVerifyReq struct {
|
||||
g.Meta `path:"/verify" tags:"验证" method:"get" summary:"验证 Token"`
|
||||
g.Meta `path:"/verify" tags:"验证" method:"get" summary:"验证 TokenServiceImpl"`
|
||||
}
|
||||
type TokenVerifyRes struct{}
|
||||
|
|
1
go.mod
1
go.mod
|
@ -25,6 +25,7 @@ require (
|
|||
go.opentelemetry.io/otel/metric v1.21.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.21.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.21.0 // indirect
|
||||
golang.org/x/crypto v0.17.0 // indirect
|
||||
golang.org/x/net v0.19.0 // indirect
|
||||
golang.org/x/sys v0.15.0 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
|
|
2
go.sum
2
go.sum
|
@ -70,6 +70,8 @@ go.opentelemetry.io/otel/trace v1.14.0 h1:wp2Mmvj41tDsyAJXiWDWpfNsOiIyd38fy85pyK
|
|||
go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8=
|
||||
go.opentelemetry.io/otel/trace v1.21.0 h1:WD9i5gzvoUPuXIXH24ZNBudiarZDKuekPqi/E8fpfLc=
|
||||
go.opentelemetry.io/otel/trace v1.21.0/go.mod h1:LGbsEB0f9LGjN+OZaQQ26sohbOmiMR+BaslueVtS/qQ=
|
||||
golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
|
||||
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
||||
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
|
||||
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
||||
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
|
||||
|
|
|
@ -21,8 +21,8 @@ var (
|
|||
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
|
||||
s := g.Server()
|
||||
s.Group("/api", func(group *ghttp.RouterGroup) {
|
||||
group.Middleware(middleware.TimestampMiddleware)
|
||||
group.Middleware(middleware.JsonResponseMiddleware)
|
||||
group.Middleware(middleware.TimestampMiddleware)
|
||||
|
||||
group.Group("/", func(group *ghttp.RouterGroup) {
|
||||
group.Bind(
|
||||
|
@ -31,6 +31,7 @@ var (
|
|||
})
|
||||
group.Group("/auth", func(group *ghttp.RouterGroup) {
|
||||
group.Group("/user", func(group *ghttp.RouterGroup) {
|
||||
group.Middleware(middleware.VerifyTokenMiddleware)
|
||||
group.Bind(
|
||||
user.NewAuthV1(),
|
||||
)
|
||||
|
|
|
@ -3,7 +3,7 @@ package token
|
|||
import (
|
||||
"PersonalMain/api/request"
|
||||
"PersonalMain/internal/model/do"
|
||||
"PersonalMain/internal/service"
|
||||
"PersonalMain/internal/service/TokenService"
|
||||
"PersonalMain/utility/ErrorCode"
|
||||
"PersonalMain/utility/ResultUtil"
|
||||
"context"
|
||||
|
@ -13,46 +13,46 @@ import (
|
|||
|
||||
// TokenCreate
|
||||
//
|
||||
// 生成 Token
|
||||
// 生成 TokenServiceImpl
|
||||
func (_ *ControllerV1) TokenCreate(ctx context.Context, _ *request.TokenCreateReq) (res *request.TokenCreateRes, err error) {
|
||||
// 获取 Cookie 是否存在
|
||||
req := ghttp.RequestFromCtx(ctx)
|
||||
hasCookie := req.Cookie.Contains("token")
|
||||
tokenService := service.NewTokenService()
|
||||
tokenService := TokenService.NewTokenService()
|
||||
var token *do.TokenDO
|
||||
if hasCookie {
|
||||
// 检查 Session 是否有效
|
||||
token = tokenService.GetToken(req)
|
||||
if tokenService.VerifyToken(token) {
|
||||
// 有效则输出Token依然有效
|
||||
ResultUtil.Success(req, "Token 依然有效", nil)
|
||||
ResultUtil.Success(req, "TokenServiceImpl 依然有效", nil)
|
||||
} else {
|
||||
// 生成新的 Session
|
||||
token = tokenService.CreateToken()
|
||||
ResultUtil.Success(req, "Token 已重新生成", g.Map{"token": token.Token})
|
||||
ResultUtil.Success(req, "TokenServiceImpl 已重新生成", g.Map{"token": token.Token})
|
||||
}
|
||||
} else {
|
||||
// 生成新的 Session
|
||||
token = tokenService.CreateToken()
|
||||
ResultUtil.Success(req, "Token 已生成", g.Map{"token": token.Token})
|
||||
ResultUtil.Success(req, "TokenServiceImpl 已生成", g.Map{"token": token.Token})
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
// TokenVerify
|
||||
//
|
||||
// 验证 Token
|
||||
// 验证 TokenServiceImpl
|
||||
func (_ *ControllerV1) TokenVerify(ctx context.Context, _ *request.TokenVerifyReq) (res *request.TokenVerifyRes, err error) {
|
||||
// 获取 Cookie 是否存在
|
||||
req := ghttp.RequestFromCtx(ctx)
|
||||
hasCookie := req.Cookie.Contains("token")
|
||||
tokenService := service.NewTokenService()
|
||||
tokenService := TokenService.NewTokenService()
|
||||
var token *do.TokenDO
|
||||
if hasCookie {
|
||||
// 检查 Session 是否有效
|
||||
token = tokenService.GetToken(req)
|
||||
if tokenService.VerifyToken(token) {
|
||||
ResultUtil.SuccessNoData(req, "Token 有效")
|
||||
ResultUtil.SuccessNoData(req, "TokenServiceImpl 有效")
|
||||
} else {
|
||||
ResultUtil.ErrorNoData(req, ErrorCode.TokenVerifyFailed)
|
||||
}
|
||||
|
|
|
@ -2,15 +2,54 @@ package user
|
|||
|
||||
import (
|
||||
"PersonalMain/api/request"
|
||||
"PersonalMain/internal/model/entity"
|
||||
"PersonalMain/internal/service/UserService"
|
||||
"PersonalMain/utility/ErrorCode"
|
||||
"PersonalMain/utility/ResultUtil"
|
||||
"context"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
)
|
||||
|
||||
func (c *ControllerV1) AuthRegister(_ context.Context, req *request.RegisterReq) (res *request.RegisterRes, err error) {
|
||||
res = &request.RegisterRes{
|
||||
Output: "Success",
|
||||
Code: 200,
|
||||
Message: "Success",
|
||||
Data: req,
|
||||
// AuthRegister
|
||||
//
|
||||
// 用户注册
|
||||
func (_ *ControllerV1) AuthRegister(ctx context.Context, _ *request.RegisterReq) (res *request.RegisterRes, err error) {
|
||||
userRegister := entity.UserRegisterVO{}
|
||||
req := ghttp.RequestFromCtx(ctx)
|
||||
// 获取 model 表单信息
|
||||
errStruct := req.GetRequestStruct(&userRegister)
|
||||
if errStruct == nil {
|
||||
errStruct := g.Validator().Data(userRegister).Run(ctx)
|
||||
if errStruct == nil {
|
||||
// 进行用户注册
|
||||
userService := UserService.NewUserService()
|
||||
userService.UserRegister(req, &userRegister)
|
||||
} else {
|
||||
ResultUtil.Error(req, ErrorCode.RequestBodyMismatching, errStruct.Map())
|
||||
}
|
||||
} else {
|
||||
ResultUtil.Error(req, ErrorCode.RequestBodyError, errStruct.Error())
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (_ *ControllerV1) AuthLogin(ctx context.Context, _ *request.LoginReq) (res *request.LoginRes, err error) {
|
||||
userLogin := entity.UserLoginVO{}
|
||||
req := ghttp.RequestFromCtx(ctx)
|
||||
// 获取 model 表单信息
|
||||
errStruct := req.GetRequestStruct(&userLogin)
|
||||
if errStruct == nil {
|
||||
errStruct := g.Validator().Data(userLogin).Run(ctx)
|
||||
if errStruct == nil {
|
||||
// 进行用户注册
|
||||
userService := UserService.NewUserService()
|
||||
userService.UserLogin(req, &userLogin)
|
||||
} else {
|
||||
ResultUtil.Error(req, ErrorCode.RequestBodyMismatching, errStruct.Map())
|
||||
}
|
||||
} else {
|
||||
ResultUtil.Error(req, ErrorCode.RequestBodyError, errStruct.Error())
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
|
|
@ -2,6 +2,7 @@ package tokenDAO
|
|||
|
||||
import (
|
||||
"PersonalMain/internal/model/do"
|
||||
"PersonalMain/utility/CustomError"
|
||||
"PersonalMain/utility/Processing"
|
||||
"context"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
|
@ -21,10 +22,10 @@ func CreateToken() do.TokenDO {
|
|||
}
|
||||
_, err := g.Model("xf_token").Data(token).OmitEmpty().Insert()
|
||||
if err == nil {
|
||||
g.Log().Cat("Database").Cat("Token").Notice(context.TODO(), "Token", token.Token, "创建成功")
|
||||
g.Log().Cat("Database").Cat("Token").Notice(context.Background(), "Token", token.Token, "创建成功")
|
||||
return token
|
||||
} else {
|
||||
g.Log().Cat("Database").Cat("Token").Error(context.TODO(), err.Error())
|
||||
g.Log().Cat("Database").Cat("Token").Error(context.Background(), err.Error())
|
||||
return do.TokenDO{}
|
||||
}
|
||||
}
|
||||
|
@ -40,18 +41,18 @@ func GetToken(token string) *do.TokenDO {
|
|||
if !result.IsEmpty() {
|
||||
err := result.Struct(&tokenDO)
|
||||
if err != nil {
|
||||
g.Log().Cat("Database").Cat("Token").Error(context.TODO(), err.Error())
|
||||
g.Log().Cat("Database").Cat("Token").Error(context.Background(), err.Error())
|
||||
return nil
|
||||
} else {
|
||||
g.Log().Cat("Database").Cat("Token").Notice(context.TODO(), "Token", tokenDO.Token, "获取成功")
|
||||
g.Log().Cat("Database").Cat("Token").Notice(context.Background(), "Token", tokenDO.Token, "获取成功")
|
||||
return &tokenDO
|
||||
}
|
||||
} else {
|
||||
g.Log().Cat("Database").Cat("Token").Notice(context.TODO(), "xf_token 数据表为空")
|
||||
g.Log().Cat("Database").Cat("Token").Notice(context.Background(), "Token", token, "获取失败,原因:Token不存在")
|
||||
return nil
|
||||
}
|
||||
} else {
|
||||
g.Log().Cat("Database").Cat("Token").Error(context.TODO(), err.Error())
|
||||
g.Log().Cat("Database").Cat("Token").Error(context.Background(), err.Error())
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
@ -59,11 +60,48 @@ func GetToken(token string) *do.TokenDO {
|
|||
// DeleteToken
|
||||
//
|
||||
// 删除Token业务
|
||||
func DeleteToken(token string) {
|
||||
func DeleteToken(token string) bool {
|
||||
_, err := g.Model("xf_token").Where("token = ?", token).Delete()
|
||||
if err != nil {
|
||||
g.Log().Cat("Database").Cat("Token").Error(context.TODO(), err.Error())
|
||||
g.Log().Cat("Database").Cat("Token").Error(context.Background(), err.Error())
|
||||
return false
|
||||
} else {
|
||||
g.Log().Cat("Database").Cat("Token").Notice(context.TODO(), "Token", token, "删除成功")
|
||||
g.Log().Cat("Database").Cat("Token").Notice(context.Background(), "Token", token, "删除成功")
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateToken
|
||||
//
|
||||
// 更新Token业务
|
||||
func UpdateToken(token string, userId *int64) (*do.TokenDO, error) {
|
||||
// 查找 token
|
||||
getTokenDO := GetToken(token)
|
||||
if getTokenDO != nil {
|
||||
if getTokenDO.UserId == nil {
|
||||
newTokenDO := do.TokenDO{
|
||||
Id: nil,
|
||||
UserId: userId,
|
||||
Token: (*getTokenDO).Token,
|
||||
ExpiredAt: time.Now().Add(time.Hour * 24),
|
||||
CreatedAt: (*getTokenDO).CreatedAt,
|
||||
}
|
||||
_, err := g.Model("xf_token").Data(newTokenDO).Where("token = ?", getTokenDO.Token).Update()
|
||||
if err != nil {
|
||||
g.Log().Cat("Database").Cat("Token").Error(context.Background(), err.Error())
|
||||
errorData := &CustomError.CustomError{Message: "DatabaseError"}
|
||||
return nil, errorData
|
||||
} else {
|
||||
g.Log().Cat("Database").Cat("Token").Notice(context.Background(), "Token", getTokenDO.Token, "更新成功")
|
||||
return &newTokenDO, nil
|
||||
}
|
||||
} else {
|
||||
g.Log().Cat("Database").Cat("Token").Notice(context.Background(), "Token", getTokenDO.Token, "更新失败,原因:该Token已登陆")
|
||||
errorData := &CustomError.CustomError{Message: "AlreadyLogin"}
|
||||
return nil, errorData
|
||||
}
|
||||
} else {
|
||||
errorData := &CustomError.CustomError{Message: "TokenNotFound"}
|
||||
return nil, errorData
|
||||
}
|
||||
}
|
||||
|
|
59
internal/dao/userDAO/userDAO.go
Normal file
59
internal/dao/userDAO/userDAO.go
Normal file
|
@ -0,0 +1,59 @@
|
|||
package userDAO
|
||||
|
||||
import (
|
||||
"PersonalMain/internal/model/do"
|
||||
"context"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
)
|
||||
|
||||
// InsertUser
|
||||
//
|
||||
// 插入用户
|
||||
func InsertUser(userDO do.UserDO) string {
|
||||
// 检查数据库是否存在用户
|
||||
result, err := g.Model("xf_user").Where("user_name = ? or email = ?", userDO.UserName, userDO.Email).One()
|
||||
if err == nil {
|
||||
if result.IsEmpty() {
|
||||
_, err := g.Model("xf_user").Data(userDO).Insert()
|
||||
if err != nil {
|
||||
g.Log().Cat("Database").Cat("User").Error(context.Background(), err.Error())
|
||||
return "DatabaseError"
|
||||
} else {
|
||||
g.Log().Cat("Database").Cat("User").Notice(context.Background(), "User", userDO.UserName, "创建成功")
|
||||
return "Success"
|
||||
}
|
||||
} else {
|
||||
g.Log().Cat("Database").Cat("User").Notice(context.Background(), "无法创建", userDO.UserName, "用户。原因:已存在此用户")
|
||||
return "UserExist"
|
||||
}
|
||||
} else {
|
||||
g.Log().Cat("Database").Cat("User").Error(context.Background(), err.Error())
|
||||
return "DatabaseError"
|
||||
}
|
||||
}
|
||||
|
||||
// GetUser
|
||||
//
|
||||
// 获取用户信息
|
||||
func GetUser(user string) *do.UserDO {
|
||||
userDO := do.UserDO{}
|
||||
result, err := g.Model("xf_user").Where("user_name = ? or email = ?", user, user).One()
|
||||
if err == nil {
|
||||
if result.IsEmpty() {
|
||||
g.Log().Cat("Database").Cat("User").Notice(context.Background(), "无法获取", user, "用户。原因:不存在此用户")
|
||||
return nil
|
||||
} else {
|
||||
err := result.Struct(&userDO)
|
||||
if err != nil {
|
||||
g.Log().Cat("Database").Cat("User").Error(context.Background(), err.Error())
|
||||
return nil
|
||||
} else {
|
||||
g.Log().Cat("Database").Cat("User").Notice(context.Background(), "获取", user, "用户成功")
|
||||
return &userDO
|
||||
}
|
||||
}
|
||||
} else {
|
||||
g.Log().Cat("Database").Cat("User").Error(context.Background(), err.Error())
|
||||
return nil
|
||||
}
|
||||
}
|
|
@ -1,8 +1,10 @@
|
|||
package logic
|
||||
package TokenServiceImpl
|
||||
|
||||
import (
|
||||
"PersonalMain/internal/dao/tokenDAO"
|
||||
"PersonalMain/internal/model/do"
|
||||
"PersonalMain/utility/ErrorCode"
|
||||
"PersonalMain/utility/ResultUtil"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
"time"
|
||||
)
|
||||
|
@ -52,3 +54,26 @@ func (_ DefaultTokenImpl) VerifyToken(token *do.TokenDO) bool {
|
|||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// LoginToken
|
||||
//
|
||||
// 登录Token业务
|
||||
func (_ DefaultTokenImpl) LoginToken(req *ghttp.Request, userDO do.UserDO) *do.TokenDO {
|
||||
// 更新数据库
|
||||
newTokenDO, err := tokenDAO.UpdateToken(req.Cookie.Get("token").String(), userDO.Id)
|
||||
if err == nil {
|
||||
if newTokenDO != nil {
|
||||
return newTokenDO
|
||||
}
|
||||
} else {
|
||||
switch err.Error() {
|
||||
case "DatabaseError":
|
||||
ResultUtil.ErrorNoData(req, ErrorCode.ServerDatabaseInteriorError)
|
||||
case "AlreadyLogin":
|
||||
ResultUtil.ErrorNoData(req, ErrorCode.AlreadyLogin)
|
||||
case "TokenNotFound":
|
||||
ResultUtil.ErrorNoData(req, ErrorCode.TokenNotFound)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
89
internal/logic/UserServiceImpl/userServiceImpl.go
Normal file
89
internal/logic/UserServiceImpl/userServiceImpl.go
Normal file
|
@ -0,0 +1,89 @@
|
|||
package UserServiceImpl
|
||||
|
||||
import (
|
||||
"PersonalMain/internal/dao/userDAO"
|
||||
"PersonalMain/internal/logic/TokenServiceImpl"
|
||||
"PersonalMain/internal/model/do"
|
||||
"PersonalMain/internal/model/entity"
|
||||
"PersonalMain/internal/service/TokenService"
|
||||
"PersonalMain/utility/ErrorCode"
|
||||
"PersonalMain/utility/ResultUtil"
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DefaultUserImpl struct{}
|
||||
|
||||
func tokenService() TokenService.TokenService {
|
||||
return &TokenServiceImpl.DefaultTokenImpl{}
|
||||
}
|
||||
|
||||
// UserRegister
|
||||
//
|
||||
// 用户注册
|
||||
func (_ *DefaultUserImpl) UserRegister(req *ghttp.Request, userVO *entity.UserRegisterVO) {
|
||||
// 密码加密
|
||||
enPassword, err := bcrypt.GenerateFromPassword([]byte(userVO.Password), bcrypt.DefaultCost)
|
||||
if err == nil {
|
||||
// 注册用户
|
||||
newUserDO := do.UserDO{
|
||||
Id: nil,
|
||||
UserName: userVO.Username,
|
||||
DisplayName: nil,
|
||||
Email: userVO.Email,
|
||||
Qq: nil,
|
||||
Password: string(enPassword),
|
||||
OldPassword: nil,
|
||||
EmailVerify: false,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: nil,
|
||||
}
|
||||
// 注入注册
|
||||
switch userDAO.InsertUser(newUserDO) {
|
||||
case "Success":
|
||||
userVO.Password = ""
|
||||
userVO.RePassword = ""
|
||||
ResultUtil.Success(req, "注册成功", userVO)
|
||||
break
|
||||
case "UserExist":
|
||||
ResultUtil.ErrorNoData(req, ErrorCode.UserExist)
|
||||
case "DatabaseError":
|
||||
ResultUtil.ErrorNoData(req, ErrorCode.ServerDatabaseInteriorError)
|
||||
default:
|
||||
ResultUtil.ErrorNoData(req, ErrorCode.ServerUnknownError)
|
||||
}
|
||||
} else {
|
||||
ResultUtil.ErrorNoData(req, ErrorCode.PasswordEncodeError)
|
||||
}
|
||||
}
|
||||
|
||||
// UserLogin
|
||||
//
|
||||
// 用户登录
|
||||
func (_ *DefaultUserImpl) UserLogin(req *ghttp.Request, userVO *entity.UserLoginVO) {
|
||||
// 获取数据库中用户信息
|
||||
getUserDO := userDAO.GetUser(userVO.User)
|
||||
if getUserDO != nil {
|
||||
// 比对密码-=
|
||||
err := bcrypt.CompareHashAndPassword([]byte(getUserDO.Password), []byte(userVO.Password))
|
||||
if err == nil {
|
||||
// TokenServiceImpl 注册更新
|
||||
getTokenDO := tokenService().LoginToken(req, *getUserDO)
|
||||
if getTokenDO != nil {
|
||||
getUserDO.Password = ""
|
||||
getUserDO.OldPassword = nil
|
||||
ResultUtil.Success(req, "登录成功", g.Map{"user": getUserDO, "token": getTokenDO})
|
||||
}
|
||||
} else {
|
||||
ResultUtil.ErrorNoData(req, ErrorCode.PasswordNotMatch)
|
||||
}
|
||||
} else {
|
||||
ResultUtil.ErrorNoData(req, ErrorCode.UserNotExist)
|
||||
}
|
||||
}
|
||||
|
||||
func (_ *DefaultUserImpl) CheckLogin(req *ghttp.Request) {
|
||||
|
||||
}
|
|
@ -1,6 +1,7 @@
|
|||
package middleware
|
||||
|
||||
import (
|
||||
"PersonalMain/internal/service/TokenService"
|
||||
"PersonalMain/utility/ErrorCode"
|
||||
"PersonalMain/utility/ResultUtil"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
@ -13,6 +14,7 @@ import (
|
|||
|
||||
// DefaultHandlerResponse is the default implementation of HandlerResponse.
|
||||
type DefaultHandlerResponse struct {
|
||||
Output string `json:"output" dc:"Output data for certain request according API definition"`
|
||||
Code int `json:"code" dc:"Error code"`
|
||||
Message string `json:"message" dc:"Error message"`
|
||||
Data interface{} `json:"data" dc:"Result data for certain request according API definition"`
|
||||
|
@ -40,6 +42,25 @@ func TimestampMiddleware(r *ghttp.Request) {
|
|||
}
|
||||
}
|
||||
|
||||
// VerifyTokenMiddleware
|
||||
//
|
||||
// 校验 TokenServiceImpl 是否有效
|
||||
func VerifyTokenMiddleware(r *ghttp.Request) {
|
||||
// 校验 token
|
||||
tokenService := TokenService.NewTokenService()
|
||||
getToken := tokenService.GetToken(r)
|
||||
if getToken != nil {
|
||||
// 检查 TokenServiceImpl 是否有效
|
||||
if tokenService.VerifyToken(getToken) {
|
||||
r.Middleware.Next()
|
||||
} else {
|
||||
ResultUtil.ErrorNoData(r, ErrorCode.TokenExpired)
|
||||
}
|
||||
} else {
|
||||
ResultUtil.ErrorNoData(r, ErrorCode.TokenNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func JsonResponseMiddleware(r *ghttp.Request) {
|
||||
r.Middleware.Next()
|
||||
|
||||
|
@ -49,6 +70,7 @@ func JsonResponseMiddleware(r *ghttp.Request) {
|
|||
}
|
||||
|
||||
var (
|
||||
output = r.GetRequest("output").String()
|
||||
msg = r.GetRequest("message").String()
|
||||
err = r.GetError()
|
||||
res = r.GetHandlerResponse()
|
||||
|
@ -74,14 +96,16 @@ func JsonResponseMiddleware(r *ghttp.Request) {
|
|||
err = gerror.New(r.GetRequest("message").String())
|
||||
r.SetError(err)
|
||||
} else {
|
||||
code = 200
|
||||
code = ErrorCode.ServerUnknownError.Code()
|
||||
if msg == "" {
|
||||
msg = "success"
|
||||
msg = ErrorCode.ServerUnknownError.Message()
|
||||
output = ErrorCode.ServerUnknownError.Output()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
r.Response.WriteJson(DefaultHandlerResponse{
|
||||
Output: output,
|
||||
Code: code,
|
||||
Message: msg,
|
||||
Data: res,
|
||||
|
|
16
internal/model/do/userDO.go
Normal file
16
internal/model/do/userDO.go
Normal file
|
@ -0,0 +1,16 @@
|
|||
package do
|
||||
|
||||
import "time"
|
||||
|
||||
type UserDO struct {
|
||||
Id *int64 `json:"id"`
|
||||
UserName string `json:"username"`
|
||||
DisplayName *string `json:"display_name"`
|
||||
Email string `json:"email"`
|
||||
Qq *string `json:"qq"`
|
||||
Password string `json:"password"`
|
||||
OldPassword *string `json:"old_password"`
|
||||
EmailVerify bool `json:"email_verify"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
}
|
6
internal/model/entity/userLoginVO.go
Normal file
6
internal/model/entity/userLoginVO.go
Normal file
|
@ -0,0 +1,6 @@
|
|||
package entity
|
||||
|
||||
type UserLoginVO struct {
|
||||
User string `p:"user" v:"required|length:6,100#请输入用户名或邮箱"`
|
||||
Password string `p:"password" v:"required|length:6,30#请输入密码|密码长度为:6-30位"`
|
||||
}
|
8
internal/model/entity/userRegisterVO.go
Normal file
8
internal/model/entity/userRegisterVO.go
Normal file
|
@ -0,0 +1,8 @@
|
|||
package entity
|
||||
|
||||
type UserRegisterVO struct {
|
||||
Username string `json:"username" v:"required|regex:^[0-9A-Za-z-_]+$|length:6,30#请输入用户名|用户名只允许 0-9, A-Z, a-z, -, _|用户名长度为:6-30位"`
|
||||
Email string `json:"email" v:"required|email#请输入邮箱|邮箱格式错误"`
|
||||
Password string `json:"password" v:"required|length:6,30#请输入密码|密码长度为:6-30位"`
|
||||
RePassword string `json:"rePassword" v:"required|same:Password#请输入确认密码|两次密码不一致"`
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
package packed
|
21
internal/service/TokenService/tokenService.go
Normal file
21
internal/service/TokenService/tokenService.go
Normal file
|
@ -0,0 +1,21 @@
|
|||
package TokenService
|
||||
|
||||
import (
|
||||
"PersonalMain/internal/logic/TokenServiceImpl"
|
||||
"PersonalMain/internal/model/do"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
)
|
||||
|
||||
func NewTokenService() TokenService {
|
||||
return &TokenServiceImpl.DefaultTokenImpl{}
|
||||
}
|
||||
|
||||
// TokenService
|
||||
//
|
||||
// TokenServiceImpl 服务接口
|
||||
type TokenService interface {
|
||||
CreateToken() *do.TokenDO
|
||||
GetToken(*ghttp.Request) *do.TokenDO
|
||||
VerifyToken(*do.TokenDO) bool
|
||||
LoginToken(*ghttp.Request, do.UserDO) *do.TokenDO
|
||||
}
|
17
internal/service/UserService/userService.go
Normal file
17
internal/service/UserService/userService.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package UserService
|
||||
|
||||
import (
|
||||
"PersonalMain/internal/logic/UserServiceImpl"
|
||||
"PersonalMain/internal/model/entity"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
)
|
||||
|
||||
func NewUserService() UserService {
|
||||
return &UserServiceImpl.DefaultUserImpl{}
|
||||
}
|
||||
|
||||
type UserService interface {
|
||||
UserRegister(*ghttp.Request, *entity.UserRegisterVO)
|
||||
UserLogin(*ghttp.Request, *entity.UserLoginVO)
|
||||
CheckLogin(*ghttp.Request)
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"PersonalMain/internal/logic"
|
||||
"PersonalMain/internal/model/do"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
)
|
||||
|
||||
func NewTokenService() TokenService {
|
||||
return &logic.DefaultTokenImpl{}
|
||||
}
|
||||
|
||||
// TokenService
|
||||
//
|
||||
// Token 服务接口
|
||||
type TokenService interface {
|
||||
CreateToken() *do.TokenDO
|
||||
GetToken(req *ghttp.Request) *do.TokenDO
|
||||
VerifyToken(token *do.TokenDO) bool
|
||||
}
|
1
main.go
1
main.go
|
@ -1,7 +1,6 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
_ "PersonalMain/internal/packed"
|
||||
_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gctx"
|
||||
|
|
9
utility/CustomError/CustomError.go
Normal file
9
utility/CustomError/CustomError.go
Normal file
|
@ -0,0 +1,9 @@
|
|||
package CustomError
|
||||
|
||||
type CustomError struct {
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *CustomError) Error() string {
|
||||
return e.Message
|
||||
}
|
|
@ -15,8 +15,18 @@ type Errors interface {
|
|||
var (
|
||||
TimestampVerifyFailed = ErrorCode{output: "TimestampVerifyFailed", code: 40010, message: "时间戳格式错误"}
|
||||
TimestampExpired = ErrorCode{output: "TimestampExpired", code: 40011, message: "时间戳过期"}
|
||||
PasswordEncodeError = ErrorCode{output: "PasswordEncodeError", code: 40012, message: "密码加密失败"}
|
||||
TokenExpired = ErrorCode{output: "TokenExpired", code: 40100, message: "Token 已过期"}
|
||||
TokenVerifyFailed = ErrorCode{output: "TokenVerifyFailed", code: 40101, message: "Token 验证失败"}
|
||||
TokenNotFound = ErrorCode{output: "TokenNotFound", code: 40102, message: "Token 不存在"}
|
||||
PasswordNotMatch = ErrorCode{output: "PasswordNotMatch", code: 40103, message: "密码错误"}
|
||||
AlreadyLogin = ErrorCode{output: "AlreadyLogin", code: 40104, message: "已经登录"}
|
||||
RequestBodyMismatching = ErrorCode{output: "RequestBodyMismatching", code: 40200, message: "请求体不匹配"}
|
||||
RequestBodyError = ErrorCode{output: "RequestBodyError", code: 40201, message: "请求体错误"}
|
||||
UserExist = ErrorCode{output: "UserExists", code: 40300, message: "用户已存在"}
|
||||
UserNotExist = ErrorCode{output: "UserNotExist", code: 40301, message: "用户不存在"}
|
||||
ServerUnknownError = ErrorCode{output: "ServerUnknownError", code: 50000, message: "服务器未知错误"}
|
||||
ServerDatabaseInteriorError = ErrorCode{output: "ServerDatabaseInteriorError", code: 50001, message: "服务器数据库内部错误"}
|
||||
)
|
||||
|
||||
func (e ErrorCode) Output() string {
|
||||
|
|
Loading…
Reference in New Issue
Block a user