添加后台用户表直接分离

This commit is contained in:
eson
2023-06-25 18:30:39 +08:00
parent a5ea734eb0
commit 96c43325c0
72 changed files with 1678 additions and 77 deletions

View File

@@ -0,0 +1,13 @@
package config
import (
"fusenapi/server/backend/internal/types"
"github.com/zeromicro/go-zero/rest"
)
type Config struct {
rest.RestConf
SourceMysql string
Auth types.Auth
}

View File

@@ -0,0 +1,49 @@
package handler
import (
"errors"
"fmt"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/utils/basic"
"fusenapi/server/backend/internal/logic"
"fusenapi/server/backend/internal/svc"
"fusenapi/server/backend/internal/types"
)
func BackendUserLoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.RequestUserLogin
// 如果端点有请求结构体则使用httpx.Parse方法从HTTP请求体中解析请求数据
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
Code: 510,
Message: "parameter error",
})
logx.Info(err)
return
}
// 创建一个业务逻辑层实例
l := logic.NewBackendUserLoginLogic(r.Context(), svcCtx)
resp, token := l.BackendUserLogin(&req)
if resp.Code == basic.CodeOK.Code {
w.Header().Add("Authorization", fmt.Sprintf("Bearer %s", token))
}
// 如果响应不为nil则使用httpx.OkJsonCtx方法返回JSON响应;
// 否则发送500内部服务器错误的JSON响应并记录错误消息logx.Error。
if resp != nil {
httpx.OkJsonCtx(r.Context(), w, resp)
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
}
}

View File

@@ -0,0 +1,73 @@
package handler
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"fusenapi/server/backend/internal/logic"
"fusenapi/server/backend/internal/svc"
"fusenapi/server/backend/internal/types"
)
func QuotationDetailHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
// 定义错误变量
err error
// 定义用户信息变量
userinfo *auth.BackendUserInfo
)
// 解析JWT token,并对空用户进行判断
claims, err := svcCtx.ParseJwtToken(r)
// 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息
if err != nil || claims == nil {
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
Code: 401, // 返回401状态码,表示未授权
Message: "unauthorized", // 返回未授权信息
})
logx.Info("unauthorized:", err.Error()) // 记录错误日志
return
}
// 从token中获取对应的用户信息
userinfo, err = auth.GetBackendUserInfoFormMapClaims(claims)
// 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息
if err != nil {
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
Code: 401,
Message: "unauthorized",
})
logx.Info("unauthorized:", err.Error())
return
}
var req types.Request
// 如果端点有请求结构体则使用httpx.Parse方法从HTTP请求体中解析请求数据
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
Code: 510,
Message: "parameter error",
})
logx.Info(err)
return
}
// 创建一个业务逻辑层实例
l := logic.NewQuotationDetailLogic(r.Context(), svcCtx)
resp := l.QuotationDetail(&req, userinfo)
// 如果响应不为nil则使用httpx.OkJsonCtx方法返回JSON响应;
if resp != nil {
httpx.OkJsonCtx(r.Context(), w, resp)
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
}
}

View File

@@ -0,0 +1,27 @@
// Code generated by goctl. DO NOT EDIT.
package handler
import (
"net/http"
"fusenapi/server/backend/internal/svc"
"github.com/zeromicro/go-zero/rest"
)
func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodGet,
Path: "/quotation/detail",
Handler: QuotationDetailHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/backend-user/login",
Handler: BackendUserLoginHandler(serverCtx),
},
},
)
}

View File

@@ -0,0 +1,70 @@
package logic
import (
"errors"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"time"
"context"
"fusenapi/server/backend/internal/svc"
"fusenapi/server/backend/internal/types"
"github.com/zeromicro/go-zero/core/logx"
"gorm.io/gorm"
)
type BackendUserLoginLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewBackendUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendUserLoginLogic {
return &BackendUserLoginLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *BackendUserLoginLogic) BackendUserLogin(req *types.RequestUserLogin) (resp *basic.Response, jwtToken string) {
// 创建一个 FsUserModel 对象 m 并实例化之,该对象用于操作 MySQL 数据库中的用户数据表。
m := l.svcCtx.AllModels.FsBackendUser
// 在用户数据表中根据登录名(email)查找用户记录,并返回 UserModel 类型的结构体对象 userModel。
user, err := m.FindUserByEmail(l.ctx, req.Name)
if errors.Is(err, gorm.ErrRecordNotFound) {
return resp.SetStatus(basic.CodeEmailNotFoundErr), ""
}
// 如果在用户数据表中找到了登录名匹配的用户记录,则判断密码是否匹配。
if *user.PasswordHash != req.Password {
logx.Info("密码错误")
return resp.SetStatus(basic.CodePasswordErr), jwtToken
}
// 如果密码匹配,则生成 JWT Token。
nowSec := time.Now().Unix()
jwtToken, err = auth.GenerateBackendJwtToken(&l.svcCtx.Config.Auth.AccessSecret, l.svcCtx.Config.Auth.AccessExpire, nowSec, user.Id, 0)
// 如果生成 JWT Token 失败,则抛出错误并返回未认证的状态码。
if err != nil {
logx.Error(err)
return resp.SetStatus(basic.CodeUnAuth), jwtToken
}
// 如果更新 VerificationToken 字段失败,则返回未认证的状态码。
if err != nil {
return resp.SetStatus(basic.CodeUnAuth), jwtToken
}
// 构造 DataUserLogin 类型的数据对象 data 并设置其属性值为生成的 JWT Token。
data := &types.DataUserLogin{
Token: jwtToken,
}
// 返回认证成功的状态码以及数据对象 data 和 JWT Token。
return resp.SetStatus(basic.CodeOK, data), jwtToken
}

View File

@@ -0,0 +1,34 @@
package logic
import (
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"context"
"fusenapi/server/backend/internal/svc"
"fusenapi/server/backend/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type QuotationDetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewQuotationDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QuotationDetailLogic {
return &QuotationDetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *QuotationDetailLogic) QuotationDetail(req *types.Request, userinfo *auth.BackendUserInfo) (resp *basic.Response) {
// 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data)
// userinfo 传入值时, 一定不为null
return resp.SetStatus(basic.CodeOK)
}

View File

@@ -0,0 +1,57 @@
package svc
import (
"errors"
"fmt"
"fusenapi/server/backend/internal/config"
"net/http"
"fusenapi/initalize"
"fusenapi/model/gmodel"
"github.com/golang-jwt/jwt"
"gorm.io/gorm"
)
type ServiceContext struct {
Config config.Config
MysqlConn *gorm.DB
AllModels *gmodel.AllModelsGen
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
MysqlConn: initalize.InitMysql(c.SourceMysql),
AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)),
}
}
func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) {
AuthKey := r.Header.Get("Authorization")
if len(AuthKey) <= 50 {
return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey)))
}
token, err := jwt.Parse(AuthKey, func(token *jwt.Token) (interface{}, error) {
// 检查签名方法是否为 HS256
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
// 返回用于验证签名的密钥
return []byte(svcCtx.Config.Auth.AccessSecret), nil
})
if err != nil {
return nil, errors.New(fmt.Sprint("Error parsing token:", err))
}
// 验证成功返回
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return claims, nil
}
return nil, errors.New(fmt.Sprint("Invalid token", err))
}

View File

@@ -0,0 +1,74 @@
// Code generated by goctl. DO NOT EDIT.
package types
import (
"fusenapi/utils/basic"
)
type RequestQuotationId struct {
QuotationId int64 `form:"id"`
}
type RequestUserLogin struct {
Name string `json:"name"`
Password string `json:"pwd"`
}
type DataUserLogin struct {
Token string `json:"token"` // 登录jwt token
}
type Request struct {
}
type Response struct {
Code int `json:"code"`
Message string `json:"msg"`
Data interface{} `json:"data"`
}
type Auth struct {
AccessSecret string `json:"accessSecret"`
AccessExpire int64 `json:"accessExpire"`
RefreshAfter int64 `json:"refreshAfter"`
}
// Set 设置Response的Code和Message值
func (resp *Response) Set(Code int, Message string) *Response {
return &Response{
Code: Code,
Message: Message,
}
}
// Set 设置整个Response
func (resp *Response) SetWithData(Code int, Message string, Data interface{}) *Response {
return &Response{
Code: Code,
Message: Message,
Data: Data,
}
}
// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数
func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) *Response {
newResp := &Response{
Code: sr.Code,
}
if len(data) == 1 {
newResp.Data = data[0]
}
return newResp
}
// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数
func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) *Response {
newResp := &Response{
Code: sr.Code,
Message: msg,
}
if len(data) == 1 {
newResp.Data = data[0]
}
return newResp
}