## 主要功能 - ✅ 用户认证模块 (登录/注册/JWT) - ✅ 照片管理模块 (上传/查询/分页/搜索) - ✅ 分类管理模块 (创建/查询/分页) - ✅ 用户管理模块 (用户列表/分页查询) - ✅ 健康检查接口 ## 技术实现 - 基于 go-zero v1.8.0 标准架构 - Handler → Logic → Model 三层架构 - SQLite/PostgreSQL 数据库支持 - JWT 认证机制 - bcrypt 密码加密 - 统一响应格式 - 自定义模型方法 (分页/搜索) ## API 接口 - POST /api/v1/auth/login - 用户登录 - POST /api/v1/auth/register - 用户注册 - GET /api/v1/health - 健康检查 - GET /api/v1/photos - 照片列表 - POST /api/v1/photos - 上传照片 - GET /api/v1/categories - 分类列表 - POST /api/v1/categories - 创建分类 - GET /api/v1/users - 用户列表 ## 配置完成 - 开发环境配置 (SQLite) - 生产环境支持 (PostgreSQL) - JWT 认证配置 - 文件上传配置 - Makefile 构建脚本 服务已验证可正常构建和启动。
74 lines
1.6 KiB
Go
74 lines
1.6 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"photography-backend/internal/svc"
|
|
"photography-backend/internal/types"
|
|
"photography-backend/pkg/utils/hash"
|
|
"photography-backend/pkg/utils/jwt"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type LoginLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
// 用户登录
|
|
func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
|
|
return &LoginLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *LoginLogic) Login(req *types.LoginRequest) (resp *types.LoginResponse, err error) {
|
|
// 1. 验证用户名和密码
|
|
user, err := l.svcCtx.UserModel.FindOneByUsername(l.ctx, req.Username)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 2. 验证密码
|
|
if !hash.CheckPassword(req.Password, user.Password) {
|
|
return nil, errors.New("用户名或密码错误")
|
|
}
|
|
|
|
// 3. 检查用户状态
|
|
if user.Status == 0 {
|
|
return nil, errors.New("用户已被禁用")
|
|
}
|
|
|
|
// 4. 生成 JWT token
|
|
token, err := jwt.GenerateToken(user.Id, user.Username, l.svcCtx.Config.Auth.AccessSecret, time.Hour*24*7)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 5. 返回登录结果
|
|
return &types.LoginResponse{
|
|
BaseResponse: types.BaseResponse{
|
|
Code: 200,
|
|
Message: "登录成功",
|
|
},
|
|
Data: types.LoginData{
|
|
Token: token,
|
|
User: types.User{
|
|
Id: user.Id,
|
|
Username: user.Username,
|
|
Email: user.Email,
|
|
Avatar: user.Avatar,
|
|
Status: int(user.Status),
|
|
CreatedAt: user.CreatedAt.Unix(),
|
|
UpdatedAt: user.UpdatedAt.Unix(),
|
|
},
|
|
},
|
|
}, nil
|
|
}
|