move: 后端

This commit is contained in:
Leon
2025-12-25 22:40:20 +08:00
parent 99951ec3dc
commit 9ba916643e
31 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
package account
type Account struct {
ID uint `gorm:"primaryKey" json:"id"`
Username string `gorm:"unique" json:"username"`
Password string `json:"-"`
Token string `json:"-"`
}
type CreateAccountRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type RenameRequest struct {
NewUsername string `json:"new_username"`
}
type FindByIDRequest struct {
ID uint `json:"id"`
}
type FindByIDResponse struct {
ID uint `json:"id"`
Username string `json:"username"`
}
type FindByUsernameRequest struct {
Username string `json:"username"`
}
type FindByUsernameResponse struct {
ID uint `json:"id"`
Username string `json:"username"`
}
type ChangePasswordRequest struct {
Username string `json:"username"`
OldPassword string `json:"old_password"`
NewPassword string `json:"new_password"`
}
type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}

View File

@@ -0,0 +1,142 @@
package account
import (
"errors"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
type AccountHandler struct {
accountService *AccountService
}
func NewAccountHandler(accountService *AccountService) *AccountHandler {
return &AccountHandler{accountService: accountService}
}
func (h *AccountHandler) CreateAccount(c *gin.Context) {
var req CreateAccountRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if err := h.accountService.CreateAccount(c.Request.Context(), &Account{
Username: req.Username,
Password: req.Password,
}); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{"message": "account created"})
}
func (h *AccountHandler) Rename(c *gin.Context) {
var req RenameRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
accountID, err := getAccountID(c)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
token, err := h.accountService.Rename(c.Request.Context(), accountID, req.NewUsername)
if err != nil {
if errors.Is(err, ErrNewUsernameRequired) {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if errors.Is(err, ErrUsernameTaken) {
c.JSON(409, gin.H{"error": err.Error()})
return
}
if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(404, gin.H{"error": "account not found"})
return
}
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{"token": token})
}
func (h *AccountHandler) ChangePassword(c *gin.Context) {
var req ChangePasswordRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if err := h.accountService.ChangePassword(c.Request.Context(), req.Username, req.OldPassword, req.NewPassword); err != nil {
c.JSON(400, gin.H{"error": "unsuccessfully password changed"})
return
}
c.JSON(200, gin.H{"message": "successfully password changed"})
}
func (h *AccountHandler) FindByID(c *gin.Context) {
var req FindByIDRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if account, err := h.accountService.FindByID(c.Request.Context(), req.ID); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
} else {
c.JSON(200, account)
}
}
func (h *AccountHandler) FindByUsername(c *gin.Context) {
var req FindByUsernameRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if account, err := h.accountService.FindByUsername(c.Request.Context(), req.Username); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
} else {
c.JSON(200, account)
}
}
func (h *AccountHandler) Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if token, err := h.accountService.Login(c.Request.Context(), req.Username, req.Password); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
} else {
c.JSON(200, gin.H{"token": token})
}
}
func (h *AccountHandler) Logout(c *gin.Context) {
accountID, err := getAccountID(c)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if err := h.accountService.Logout(c.Request.Context(), accountID); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{"message": "account logged out"})
}
func getAccountID(c *gin.Context) (uint, error) {
value, exists := c.Get("accountID")
if !exists {
return 0, errors.New("accountID not found")
}
id, ok := value.(uint)
if !ok {
return 0, errors.New("accountID has invalid type")
}
return id, nil
}

View File

@@ -0,0 +1,86 @@
package account
import (
"context"
"gorm.io/gorm"
)
type AccountRepository struct {
db *gorm.DB
}
func NewAccountRepository(db *gorm.DB) *AccountRepository {
return &AccountRepository{db: db}
}
func (ar *AccountRepository) CreateAccount(ctx context.Context, account *Account) error {
if err := ar.db.WithContext(ctx).Create(account).Error; err != nil {
return err
}
return nil
}
func (ar *AccountRepository) Rename(ctx context.Context, id uint, newUsername string) error {
result := ar.db.WithContext(ctx).Model(&Account{}).Where("id = ?", id).Update("username", newUsername)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
}
func (ar *AccountRepository) RenameWithToken(ctx context.Context, id uint, newUsername string, token string) error {
return ar.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
result := tx.Model(&Account{}).Where("id = ?", id).Update("username", newUsername)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
if err := tx.Model(&Account{}).Where("id = ?", id).Update("token", token).Error; err != nil {
return err
}
return nil
})
}
func (ar *AccountRepository) ChangePassword(ctx context.Context, id uint, newPassword string) error {
if err := ar.db.WithContext(ctx).Model(&Account{}).Where("id = ?", id).Update("password", newPassword).Error; err != nil {
return err
}
return nil
}
func (ar *AccountRepository) FindByID(ctx context.Context, id uint) (*Account, error) {
var account Account
if err := ar.db.WithContext(ctx).First(&account, id).Error; err != nil {
return nil, err
}
return &account, nil
}
func (ar *AccountRepository) FindByUsername(ctx context.Context, username string) (*Account, error) {
var account Account
if err := ar.db.WithContext(ctx).Where("username = ?", username).First(&account).Error; err != nil {
return nil, err
}
return &account, nil
}
func (ar *AccountRepository) Login(ctx context.Context, id uint, token string) error {
if err := ar.db.WithContext(ctx).Model(&Account{}).Where("id = ?", id).Update("token", token).Error; err != nil {
return err
}
return nil
}
func (ar *AccountRepository) Logout(ctx context.Context, id uint) error {
if err := ar.db.WithContext(ctx).Model(&Account{}).Where("id = ?", id).Update("token", "").Error; err != nil {
return err
}
return nil
}

View File

@@ -0,0 +1,156 @@
package account
import (
"context"
"errors"
"feedsystem_video_go/internal/auth"
"fmt"
"log"
"time"
rediscache "feedsystem_video_go/internal/redis"
"github.com/go-sql-driver/mysql"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type AccountService struct {
accountRepository *AccountRepository
cache *rediscache.Client
}
var (
ErrUsernameTaken = errors.New("username already exists")
ErrNewUsernameRequired = errors.New("new_username is required")
)
func NewAccountService(accountRepository *AccountRepository, cache *rediscache.Client) *AccountService {
return &AccountService{accountRepository: accountRepository, cache: cache}
}
func (as *AccountService) CreateAccount(ctx context.Context, account *Account) error {
passwordHash, err := bcrypt.GenerateFromPassword([]byte(account.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
account.Password = string(passwordHash)
if err := as.accountRepository.CreateAccount(ctx, account); err != nil {
return err
}
return nil
}
func (as *AccountService) Rename(ctx context.Context, accountID uint, newUsername string) (string, error) {
if newUsername == "" {
return "", ErrNewUsernameRequired
}
token, err := auth.GenerateToken(accountID, newUsername)
if err != nil {
return "", err
}
if err := as.accountRepository.RenameWithToken(ctx, accountID, newUsername, token); err != nil {
var mysqlErr *mysql.MySQLError
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
return "", ErrUsernameTaken
}
if errors.Is(err, gorm.ErrRecordNotFound) {
return "", err
}
return "", err
}
if as.cache != nil {
cacheCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
if err := as.cache.SetBytes(cacheCtx, fmt.Sprintf("account:%d", accountID), []byte(token), 24*time.Hour); err != nil {
log.Printf("failed to set cache: %v", err)
}
}
return token, nil
}
func (as *AccountService) ChangePassword(ctx context.Context, username, oldPassword, newPassword string) error {
account, err := as.FindByUsername(ctx, username)
if err != nil {
return err
}
if err := bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(oldPassword)); err != nil {
return err
}
passwordHash, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
if err != nil {
return err
}
if err := as.accountRepository.ChangePassword(ctx, account.ID, string(passwordHash)); err != nil {
return err
}
if err := as.Logout(ctx, account.ID); err != nil {
return err
}
return nil
}
func (as *AccountService) FindByID(ctx context.Context, id uint) (*Account, error) {
if account, err := as.accountRepository.FindByID(ctx, id); err != nil {
return nil, err
} else {
return account, nil
}
}
func (as *AccountService) FindByUsername(ctx context.Context, username string) (*Account, error) {
if account, err := as.accountRepository.FindByUsername(ctx, username); err != nil {
return nil, err
} else {
return account, nil
}
}
func (as *AccountService) Login(ctx context.Context, username, password string) (string, error) {
account, err := as.FindByUsername(ctx, username)
if err != nil {
return "", err
}
if err := bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(password)); err != nil {
return "", err
}
// generate token
token, err := auth.GenerateToken(account.ID, account.Username)
if err != nil {
return "", err
}
if err := as.accountRepository.Login(ctx, account.ID, token); err != nil {
return "", err
}
if as.cache != nil {
cacheCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
if err := as.cache.SetBytes(cacheCtx, fmt.Sprintf("account:%d", account.ID), []byte(token), 24*time.Hour); err != nil {
log.Printf("failed to set cache: %v", err)
}
}
return token, nil
}
func (as *AccountService) Logout(ctx context.Context, accountID uint) error {
account, err := as.FindByID(ctx, accountID)
if err != nil {
return err
}
if account.Token == "" {
return nil
}
if as.cache != nil {
cacheCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
if err := as.cache.Del(cacheCtx, fmt.Sprintf("account:%d", account.ID)); err != nil {
log.Printf("failed to del cache: %v", err)
}
}
return as.accountRepository.Logout(ctx, account.ID)
}