Skip to content

Commit

Permalink
feat:完成简单登陆,注册,查找用户逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
xudaqian1 committed Feb 16, 2024
1 parent aa570fa commit c1c34b2
Show file tree
Hide file tree
Showing 13 changed files with 150 additions and 30 deletions.
33 changes: 33 additions & 0 deletions api/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package api

import (
"auth-server/middleware"
"auth-server/model"
"github.com/gin-gonic/gin"
)

type AuthApi struct{}

func (AuthApi) Login(c *gin.Context) {
var param model.LoginUser
if err := c.ShouldBindJSON(&param); err != nil {
middleware.Fail(c, model.ErrParam.AddErr(err))
return
}
token, err := authService.Login(param)
middleware.Auto(c, err, map[string]string{
"token": token,
})
return
}

func (AuthApi) Register(c *gin.Context) {
var param model.User
if err := c.ShouldBindJSON(&param); err != nil {
middleware.Fail(c, model.ErrParam.AddErr(err))
return
}
err := authService.Register(&param)
middleware.Auto(c, err, nil)
return
}
1 change: 1 addition & 0 deletions api/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ import (

var (
userService services.UserService
authService services.AuthService
)
10 changes: 2 additions & 8 deletions api/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,6 @@ type GetUserParam struct {

type UserApi struct{}

func (UserApi) CreateUser(c *gin.Context) {
_, _, param := middleware.Validate[any, any, model.User](c)

errCreate := userService.CreateUser(&param)
middleware.Auto(c, errCreate, nil)
return
}

func (UserApi) GetUser(c *gin.Context) {
params, _, _ := middleware.Validate[GetUserParam, any, any](c)

Expand All @@ -36,7 +28,9 @@ func (UserApi) GetUser(c *gin.Context) {
}

func (UserApi) UpdateUser(gin *gin.Context) {

}

func (UserApi) DeleteUser(gin *gin.Context) {

}
5 changes: 3 additions & 2 deletions middleware/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ func JWT() gin.HandlerFunc {
err = model.ErrParam.AddErr(errors.New("Authorization为空"))
} else {
_, parseErr := common.ParseToken(token, config.JwtSecret)
err = model.ErrAuthCheckTokenFail.AddErr(parseErr)

if parseErr != nil {
err = model.ErrAuthToken.AddErr(parseErr)
}
}
if err.Code != 0 {
Fail(c, err)
Expand Down
3 changes: 3 additions & 0 deletions middleware/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ func Auto(c *gin.Context, err model.ErrorCode, data interface{}) {
if err.Code != 0 {
resp.Code = err.Code
resp.Msg = err.Msg
if err.Err != nil {
resp.Data = err.Err.Error()
}
} else {
resp.Data = data
}
Expand Down
10 changes: 6 additions & 4 deletions model/errorcode.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,14 @@ func responseErrCode(code int, msg string) ErrorCode {
//ERROR_AUTH: "Token错误",

var (
Err = responseErrCode(400, "接口错误") // 通用错误
ErrParam = responseErrCode(10001, "参数有误")

Err = responseErrCode(400, "接口错误") // 通用错误
ErrParam = responseErrCode(10001, "参数有误")
ErrLonginParam = responseErrCode(10001, "用户名或密码错误")
ErrSignParam = responseErrCode(10002, "签名参数有误")
ErrAuthToken = responseErrCode(10003, "token错误")
ErrAuthCheckTokenFail = responseErrCode(10004, "token鉴权失败")
ErrGenToken = responseErrCode(10004, "token生成错误")
ErrRegisterParam = responseErrCode(10005, "用户名已存在")
ErrAuthCheckTokenFail = responseErrCode(10005, "token鉴权失败")
ErrDb = responseErrCode(20003, "数据库错误")

// ......
Expand Down
6 changes: 6 additions & 0 deletions model/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ type UpdateUser struct {
Avatar string `json:"avatar"`
}

// LoginUser 用户登陆参数校验
type LoginUser struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}

type GetUserParams struct {
Id string `uri:"id" validate:"required"`
}
23 changes: 21 additions & 2 deletions proxy/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package proxy

import (
"auth-server/model"
"github.com/pkg/errors"
"gorm.io/gorm"
)

type UserProxy struct{}
Expand All @@ -25,12 +27,29 @@ func (UserProxy) UpdateUser(userId int64, updateUser model.User) (err model.Erro
return
}

func (UserProxy) GetUser(userId int64) (user *model.User, err model.ErrorCode) {
func (UserProxy) GetUserById(userId int64) (user model.User, found bool, err model.ErrorCode) {
db := storageEngine.GetStorageDB()
dbErr := db.First(&user, userId).Error
if dbErr != nil {
if errors.Is(dbErr, gorm.ErrRecordNotFound) {
} else if dbErr != nil {
err = model.ErrDb.AddErr(dbErr)
} else {
found = true
}
return
}

func (UserProxy) GetUserByUsername(userName string) (user model.User, found bool, err model.ErrorCode) {
db := storageEngine.GetStorageDB()
user.Username = userName
dbErr := db.First(&user).Error
if errors.Is(dbErr, gorm.ErrRecordNotFound) {
} else if dbErr != nil {
err = model.ErrDb.AddErr(dbErr)
} else {
found = true
}

return
}

Expand Down
8 changes: 8 additions & 0 deletions router/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package router

import "github.com/gin-gonic/gin"

func authRouter(router *gin.RouterGroup) {
router.POST("/auth/login", apiAuth.Login)
router.POST("/auth/register", apiAuth.Register)
}
5 changes: 4 additions & 1 deletion router/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ var (
func InitRouter() {
engine := gin.New()
engine.Use(gin.Recovery())

// 登陆认证相关路由
authRouterGroup := engine.Group("/api/v1")
authRouter(authRouterGroup)
// 用户登陆
userRouterGroup := engine.Group("/api/v1")
userRouterGroup.Use(middleware.JWT())
userRouter(userRouterGroup)
Expand Down
1 change: 0 additions & 1 deletion router/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
func userRouter(router *gin.RouterGroup) {
// user
router.GET("/users/:id", apiUser.GetUser)
router.POST("/users", apiUser.CreateUser)
router.PATCH("/users/:id", apiUser.UpdateUser)
router.DELETE("/users/:id", apiUser.DeleteUser)
}
61 changes: 61 additions & 0 deletions services/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package services

import (
"auth-server/common"
"auth-server/config"
"auth-server/model"
"github.com/pkg/errors"
)

type AuthService struct{}

var (
UserNotFoundErr = errors.New("user not found")
UserExistErr = errors.New("user exist")
)

func (AuthService) Register(user *model.User) (err model.ErrorCode) {
var found bool
_, found, err = proxyUser.GetUserByUsername(user.Username)
if err.Code != 0 {
return
}
if found {
err = model.ErrRegisterParam.AddErr(UserExistErr)
return
}

// 产生slat
slat := common.GetRandomString(16)
user.Salt = slat
// todo 后续采用加密更强的算法,例如AES
user.Password = common.MD5(slat + user.Password)
err = proxyUser.CreateUser(user)
return
}

func (AuthService) Login(loginUser model.LoginUser) (token string, err model.ErrorCode) {
var user model.User
var found bool
user, found, err = proxyUser.GetUserByUsername(loginUser.Username)
if err.Code != 0 {
return
}
if !found {
err = model.ErrLonginParam.AddErr(UserNotFoundErr)
return
}
slat := user.Salt
enPassword := common.MD5(slat + loginUser.Password)
if enPassword != user.Password {
err = model.ErrLonginParam
return
}
var genTokenErr error
token, genTokenErr = common.GenerateToken(loginUser.Username, config.JwtSecret, config.JwtExpire, config.ServerName)
if genTokenErr != nil {
err = model.ErrGenToken.AddErr(genTokenErr)
return
}
return
}
14 changes: 2 additions & 12 deletions services/user.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,12 @@
package services

import (
"auth-server/common"
"auth-server/model"
)

type UserService struct{}

func (UserService) CreateUser(user *model.User) (err model.ErrorCode) {
// 产生slat
slat := common.GetRandomString(16)
// todo 后续采用加密更强的算法,例如AES
user.Password = common.MD5(slat)
err = proxyUser.CreateUser(user)
return
}

func (UserService) GetUser(userId int64) (user *model.User, err model.ErrorCode) {
user, err = proxyUser.GetUser(userId)
func (UserService) GetUser(userId int64) (user model.User, err model.ErrorCode) {
user, _, err = proxyUser.GetUserById(userId)
return
}

0 comments on commit c1c34b2

Please sign in to comment.