bbs-backend/logic/appservice/user_service.go
2024-11-19 21:08:28 +08:00

121 lines
2.8 KiB
Go

package appservice
import (
"bbs-backend/api/request"
"bbs-backend/common/errcode"
"bbs-backend/dal/model"
"bbs-backend/logic/domainservice"
"github.com/dgrijalva/jwt-go"
"time"
)
var jwtKey = []byte("your_secret_key")
// RegisterUser handles user registration
func RegisterUser(req request.RegisterRequest) (*model.User, error) {
// 转换为数据模型
user := &model.User{
Username: req.Username,
Email: req.Email,
Password: req.Password,
}
err := domainservice.RegisterUserDomainService(user)
if err != nil {
return nil, err
}
return user, nil
}
// LoginUser handles user login and generates a JWT token
func LoginUser(req request.LoginRequest) (string, error) {
user, err := domainservice.LoginUserDomainService(req.Username, req.Password)
if err != nil {
return "", errcode.ErrUnauthorized
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": user.ID,
"exp": time.Now().Add(time.Hour * 24).Unix(),
})
tokenString, err := token.SignedString(jwtKey)
if err != nil {
return "", errcode.ErrInternalServerError
}
return tokenString, nil
}
// GetUserInfo retrieves user information by user ID
func GetUserInfo(userID uint) (*model.User, error) {
user, err := domainservice.GetUserInfoDomainService(userID)
if err != nil {
return nil, errcode.ErrInternalServerError
}
return user, nil
}
// UpdateUserInfo handles user info update
func UpdateUserInfo(userID uint, req request.UpdateUserInfoRequest) error {
user, err := domainservice.GetUserInfoDomainService(userID)
if err != nil {
return errcode.ErrInternalServerError
}
fieldsToUpdate := make([]string, 0)
if req.Email != "" {
user.Email = req.Email
fieldsToUpdate = append(fieldsToUpdate, "Email")
}
if req.Nickname != "" {
user.Nickname = req.Nickname
}
if req.Description != "" {
user.Description = req.Description
}
if req.Password != "" {
user.Password = req.Password
fieldsToUpdate = append(fieldsToUpdate, "Password")
}
err = domainservice.UpdateUserDomainService(user, fieldsToUpdate...)
if err != nil {
return errcode.ErrInternalServerError
}
return nil
}
// UploadAvatar handles avatar upload
func UploadAvatar(userID uint, avatar []byte) error {
user, err := domainservice.GetUserInfoDomainService(userID)
if err != nil {
return errcode.ErrInternalServerError
}
user.Avatar = avatar
user.AvatarURL = ""
err = domainservice.UpdateUserDomainService(user)
if err != nil {
return errcode.ErrInternalServerError
}
return nil
}
// SendVerificationCode sends verification code to email
func SendVerificationCode(email string) error {
// 发送验证码逻辑
return nil
}
// VerifyEmail verifies email and code
func VerifyEmail(userID uint, email, code string) error {
// 验证邮箱和验证码逻辑
return nil
}