用户注册,用户登陆模块完善
This commit is contained in:
parent
79250bc0db
commit
ab93bd397a
|
@ -15,8 +15,10 @@ type IHelloV1 interface {
|
||||||
|
|
||||||
type IAuthV1 interface {
|
type IAuthV1 interface {
|
||||||
AuthRegister(ctx context.Context, req *request.RegisterReq) (res *request.RegisterRes, err error)
|
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 {
|
type ITokenV1 interface {
|
||||||
TokenCreate(ctx context.Context, req *request.TokenCreateReq) (res *request.TokenCreateRes, err error)
|
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 {
|
type RegisterReq struct {
|
||||||
g.Meta `path:"/register" tags:"注册" method:"get" summary:"注册账号"`
|
g.Meta `path:"/register" tags:"注册" method:"post" summary:"注册账号"`
|
||||||
|
}
|
||||||
Username string `json:"username"`
|
type LoginReq struct {
|
||||||
|
g.Meta `path:"/login" tags:"登录" method:"get" summary:"登录账号"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type RegisterRes struct {
|
type RegisterRes struct{}
|
||||||
g.Meta `mime:"application/json" example:"string"`
|
type LoginRes struct{}
|
||||||
|
|
||||||
Output string `json:"output"`
|
|
||||||
Code int `json:"code"`
|
|
||||||
Message string `json:"message"`
|
|
||||||
Data any `json:"data"`
|
|
||||||
}
|
|
||||||
|
|
|
@ -3,11 +3,11 @@ package request
|
||||||
import "github.com/gogf/gf/v2/frame/g"
|
import "github.com/gogf/gf/v2/frame/g"
|
||||||
|
|
||||||
type TokenCreateReq struct {
|
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 TokenCreateRes struct{}
|
||||||
|
|
||||||
type TokenVerifyReq 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{}
|
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/metric v1.21.0 // indirect
|
||||||
go.opentelemetry.io/otel/sdk v1.21.0 // indirect
|
go.opentelemetry.io/otel/sdk v1.21.0 // indirect
|
||||||
go.opentelemetry.io/otel/trace 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/net v0.19.0 // indirect
|
||||||
golang.org/x/sys v0.15.0 // indirect
|
golang.org/x/sys v0.15.0 // indirect
|
||||||
golang.org/x/text v0.14.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.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 h1:WD9i5gzvoUPuXIXH24ZNBudiarZDKuekPqi/E8fpfLc=
|
||||||
go.opentelemetry.io/otel/trace v1.21.0/go.mod h1:LGbsEB0f9LGjN+OZaQQ26sohbOmiMR+BaslueVtS/qQ=
|
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 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
|
||||||
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
||||||
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
|
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) {
|
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
|
||||||
s := g.Server()
|
s := g.Server()
|
||||||
s.Group("/api", func(group *ghttp.RouterGroup) {
|
s.Group("/api", func(group *ghttp.RouterGroup) {
|
||||||
group.Middleware(middleware.TimestampMiddleware)
|
|
||||||
group.Middleware(middleware.JsonResponseMiddleware)
|
group.Middleware(middleware.JsonResponseMiddleware)
|
||||||
|
group.Middleware(middleware.TimestampMiddleware)
|
||||||
|
|
||||||
group.Group("/", func(group *ghttp.RouterGroup) {
|
group.Group("/", func(group *ghttp.RouterGroup) {
|
||||||
group.Bind(
|
group.Bind(
|
||||||
|
@ -31,6 +31,7 @@ var (
|
||||||
})
|
})
|
||||||
group.Group("/auth", func(group *ghttp.RouterGroup) {
|
group.Group("/auth", func(group *ghttp.RouterGroup) {
|
||||||
group.Group("/user", func(group *ghttp.RouterGroup) {
|
group.Group("/user", func(group *ghttp.RouterGroup) {
|
||||||
|
group.Middleware(middleware.VerifyTokenMiddleware)
|
||||||
group.Bind(
|
group.Bind(
|
||||||
user.NewAuthV1(),
|
user.NewAuthV1(),
|
||||||
)
|
)
|
||||||
|
|
|
@ -3,7 +3,7 @@ package token
|
||||||
import (
|
import (
|
||||||
"PersonalMain/api/request"
|
"PersonalMain/api/request"
|
||||||
"PersonalMain/internal/model/do"
|
"PersonalMain/internal/model/do"
|
||||||
"PersonalMain/internal/service"
|
"PersonalMain/internal/service/TokenService"
|
||||||
"PersonalMain/utility/ErrorCode"
|
"PersonalMain/utility/ErrorCode"
|
||||||
"PersonalMain/utility/ResultUtil"
|
"PersonalMain/utility/ResultUtil"
|
||||||
"context"
|
"context"
|
||||||
|
@ -13,46 +13,46 @@ import (
|
||||||
|
|
||||||
// TokenCreate
|
// TokenCreate
|
||||||
//
|
//
|
||||||
// 生成 Token
|
// 生成 TokenServiceImpl
|
||||||
func (_ *ControllerV1) TokenCreate(ctx context.Context, _ *request.TokenCreateReq) (res *request.TokenCreateRes, err error) {
|
func (_ *ControllerV1) TokenCreate(ctx context.Context, _ *request.TokenCreateReq) (res *request.TokenCreateRes, err error) {
|
||||||
// 获取 Cookie 是否存在
|
// 获取 Cookie 是否存在
|
||||||
req := ghttp.RequestFromCtx(ctx)
|
req := ghttp.RequestFromCtx(ctx)
|
||||||
hasCookie := req.Cookie.Contains("token")
|
hasCookie := req.Cookie.Contains("token")
|
||||||
tokenService := service.NewTokenService()
|
tokenService := TokenService.NewTokenService()
|
||||||
var token *do.TokenDO
|
var token *do.TokenDO
|
||||||
if hasCookie {
|
if hasCookie {
|
||||||
// 检查 Session 是否有效
|
// 检查 Session 是否有效
|
||||||
token = tokenService.GetToken(req)
|
token = tokenService.GetToken(req)
|
||||||
if tokenService.VerifyToken(token) {
|
if tokenService.VerifyToken(token) {
|
||||||
// 有效则输出Token依然有效
|
// 有效则输出Token依然有效
|
||||||
ResultUtil.Success(req, "Token 依然有效", nil)
|
ResultUtil.Success(req, "TokenServiceImpl 依然有效", nil)
|
||||||
} else {
|
} else {
|
||||||
// 生成新的 Session
|
// 生成新的 Session
|
||||||
token = tokenService.CreateToken()
|
token = tokenService.CreateToken()
|
||||||
ResultUtil.Success(req, "Token 已重新生成", g.Map{"token": token.Token})
|
ResultUtil.Success(req, "TokenServiceImpl 已重新生成", g.Map{"token": token.Token})
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 生成新的 Session
|
// 生成新的 Session
|
||||||
token = tokenService.CreateToken()
|
token = tokenService.CreateToken()
|
||||||
ResultUtil.Success(req, "Token 已生成", g.Map{"token": token.Token})
|
ResultUtil.Success(req, "TokenServiceImpl 已生成", g.Map{"token": token.Token})
|
||||||
}
|
}
|
||||||
return res, err
|
return res, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// TokenVerify
|
// TokenVerify
|
||||||
//
|
//
|
||||||
// 验证 Token
|
// 验证 TokenServiceImpl
|
||||||
func (_ *ControllerV1) TokenVerify(ctx context.Context, _ *request.TokenVerifyReq) (res *request.TokenVerifyRes, err error) {
|
func (_ *ControllerV1) TokenVerify(ctx context.Context, _ *request.TokenVerifyReq) (res *request.TokenVerifyRes, err error) {
|
||||||
// 获取 Cookie 是否存在
|
// 获取 Cookie 是否存在
|
||||||
req := ghttp.RequestFromCtx(ctx)
|
req := ghttp.RequestFromCtx(ctx)
|
||||||
hasCookie := req.Cookie.Contains("token")
|
hasCookie := req.Cookie.Contains("token")
|
||||||
tokenService := service.NewTokenService()
|
tokenService := TokenService.NewTokenService()
|
||||||
var token *do.TokenDO
|
var token *do.TokenDO
|
||||||
if hasCookie {
|
if hasCookie {
|
||||||
// 检查 Session 是否有效
|
// 检查 Session 是否有效
|
||||||
token = tokenService.GetToken(req)
|
token = tokenService.GetToken(req)
|
||||||
if tokenService.VerifyToken(token) {
|
if tokenService.VerifyToken(token) {
|
||||||
ResultUtil.SuccessNoData(req, "Token 有效")
|
ResultUtil.SuccessNoData(req, "TokenServiceImpl 有效")
|
||||||
} else {
|
} else {
|
||||||
ResultUtil.ErrorNoData(req, ErrorCode.TokenVerifyFailed)
|
ResultUtil.ErrorNoData(req, ErrorCode.TokenVerifyFailed)
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,15 +2,54 @@ package user
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"PersonalMain/api/request"
|
"PersonalMain/api/request"
|
||||||
|
"PersonalMain/internal/model/entity"
|
||||||
|
"PersonalMain/internal/service/UserService"
|
||||||
|
"PersonalMain/utility/ErrorCode"
|
||||||
|
"PersonalMain/utility/ResultUtil"
|
||||||
"context"
|
"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) {
|
// AuthRegister
|
||||||
res = &request.RegisterRes{
|
//
|
||||||
Output: "Success",
|
// 用户注册
|
||||||
Code: 200,
|
func (_ *ControllerV1) AuthRegister(ctx context.Context, _ *request.RegisterReq) (res *request.RegisterRes, err error) {
|
||||||
Message: "Success",
|
userRegister := entity.UserRegisterVO{}
|
||||||
Data: req,
|
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
|
return res, err
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,6 +2,7 @@ package tokenDAO
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"PersonalMain/internal/model/do"
|
"PersonalMain/internal/model/do"
|
||||||
|
"PersonalMain/utility/CustomError"
|
||||||
"PersonalMain/utility/Processing"
|
"PersonalMain/utility/Processing"
|
||||||
"context"
|
"context"
|
||||||
"github.com/gogf/gf/v2/frame/g"
|
"github.com/gogf/gf/v2/frame/g"
|
||||||
|
@ -21,10 +22,10 @@ func CreateToken() do.TokenDO {
|
||||||
}
|
}
|
||||||
_, err := g.Model("xf_token").Data(token).OmitEmpty().Insert()
|
_, err := g.Model("xf_token").Data(token).OmitEmpty().Insert()
|
||||||
if err == nil {
|
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
|
return token
|
||||||
} else {
|
} 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{}
|
return do.TokenDO{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -40,18 +41,18 @@ func GetToken(token string) *do.TokenDO {
|
||||||
if !result.IsEmpty() {
|
if !result.IsEmpty() {
|
||||||
err := result.Struct(&tokenDO)
|
err := result.Struct(&tokenDO)
|
||||||
if err != nil {
|
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
|
return nil
|
||||||
} else {
|
} 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
|
return &tokenDO
|
||||||
}
|
}
|
||||||
} else {
|
} 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
|
return nil
|
||||||
}
|
}
|
||||||
} else {
|
} 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
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -59,11 +60,48 @@ func GetToken(token string) *do.TokenDO {
|
||||||
// DeleteToken
|
// DeleteToken
|
||||||
//
|
//
|
||||||
// 删除Token业务
|
// 删除Token业务
|
||||||
func DeleteToken(token string) {
|
func DeleteToken(token string) bool {
|
||||||
_, err := g.Model("xf_token").Where("token = ?", token).Delete()
|
_, err := g.Model("xf_token").Where("token = ?", token).Delete()
|
||||||
if err != nil {
|
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 {
|
} 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 (
|
import (
|
||||||
"PersonalMain/internal/dao/tokenDAO"
|
"PersonalMain/internal/dao/tokenDAO"
|
||||||
"PersonalMain/internal/model/do"
|
"PersonalMain/internal/model/do"
|
||||||
|
"PersonalMain/utility/ErrorCode"
|
||||||
|
"PersonalMain/utility/ResultUtil"
|
||||||
"github.com/gogf/gf/v2/net/ghttp"
|
"github.com/gogf/gf/v2/net/ghttp"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
@ -52,3 +54,26 @@ func (_ DefaultTokenImpl) VerifyToken(token *do.TokenDO) bool {
|
||||||
return false
|
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
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"PersonalMain/internal/service/TokenService"
|
||||||
"PersonalMain/utility/ErrorCode"
|
"PersonalMain/utility/ErrorCode"
|
||||||
"PersonalMain/utility/ResultUtil"
|
"PersonalMain/utility/ResultUtil"
|
||||||
"github.com/gogf/gf/v2/errors/gerror"
|
"github.com/gogf/gf/v2/errors/gerror"
|
||||||
|
@ -13,6 +14,7 @@ import (
|
||||||
|
|
||||||
// DefaultHandlerResponse is the default implementation of HandlerResponse.
|
// DefaultHandlerResponse is the default implementation of HandlerResponse.
|
||||||
type DefaultHandlerResponse struct {
|
type DefaultHandlerResponse struct {
|
||||||
|
Output string `json:"output" dc:"Output data for certain request according API definition"`
|
||||||
Code int `json:"code" dc:"Error code"`
|
Code int `json:"code" dc:"Error code"`
|
||||||
Message string `json:"message" dc:"Error message"`
|
Message string `json:"message" dc:"Error message"`
|
||||||
Data interface{} `json:"data" dc:"Result data for certain request according API definition"`
|
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) {
|
func JsonResponseMiddleware(r *ghttp.Request) {
|
||||||
r.Middleware.Next()
|
r.Middleware.Next()
|
||||||
|
|
||||||
|
@ -49,10 +70,11 @@ func JsonResponseMiddleware(r *ghttp.Request) {
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
msg = r.GetRequest("message").String()
|
output = r.GetRequest("output").String()
|
||||||
err = r.GetError()
|
msg = r.GetRequest("message").String()
|
||||||
res = r.GetHandlerResponse()
|
err = r.GetError()
|
||||||
code int
|
res = r.GetHandlerResponse()
|
||||||
|
code int
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if r.GetRequest("code") == nil {
|
if r.GetRequest("code") == nil {
|
||||||
|
@ -74,14 +96,16 @@ func JsonResponseMiddleware(r *ghttp.Request) {
|
||||||
err = gerror.New(r.GetRequest("message").String())
|
err = gerror.New(r.GetRequest("message").String())
|
||||||
r.SetError(err)
|
r.SetError(err)
|
||||||
} else {
|
} else {
|
||||||
code = 200
|
code = ErrorCode.ServerUnknownError.Code()
|
||||||
if msg == "" {
|
if msg == "" {
|
||||||
msg = "success"
|
msg = ErrorCode.ServerUnknownError.Message()
|
||||||
|
output = ErrorCode.ServerUnknownError.Output()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
r.Response.WriteJson(DefaultHandlerResponse{
|
r.Response.WriteJson(DefaultHandlerResponse{
|
||||||
|
Output: output,
|
||||||
Code: code,
|
Code: code,
|
||||||
Message: msg,
|
Message: msg,
|
||||||
Data: res,
|
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
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
_ "PersonalMain/internal/packed"
|
|
||||||
_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
|
_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
|
||||||
|
|
||||||
"github.com/gogf/gf/v2/os/gctx"
|
"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
|
||||||
|
}
|
|
@ -13,10 +13,20 @@ type Errors interface {
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
TimestampVerifyFailed = ErrorCode{output: "TimestampVerifyFailed", code: 40010, message: "时间戳格式错误"}
|
TimestampVerifyFailed = ErrorCode{output: "TimestampVerifyFailed", code: 40010, message: "时间戳格式错误"}
|
||||||
TimestampExpired = ErrorCode{output: "TimestampExpired", code: 40011, message: "时间戳过期"}
|
TimestampExpired = ErrorCode{output: "TimestampExpired", code: 40011, message: "时间戳过期"}
|
||||||
TokenExpired = ErrorCode{output: "TokenExpired", code: 40100, message: "Token 已过期"}
|
PasswordEncodeError = ErrorCode{output: "PasswordEncodeError", code: 40012, message: "密码加密失败"}
|
||||||
TokenVerifyFailed = ErrorCode{output: "TokenVerifyFailed", code: 40101, message: "Token 验证失败"}
|
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 {
|
func (e ErrorCode) Output() string {
|
||||||
|
|
Loading…
Reference in New Issue
Block a user