| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- package model
- import (
- "crypto/hmac"
- "crypto/sha256"
- "errors"
- "fmt"
- "woord-core-service/global"
- "gorm.io/gorm"
- )
- var (
- ErrUserNotFound = fmt.Errorf("用户不存在")
- ErrUserNameAlreadyExists = fmt.Errorf("用户名已存在")
- ErrWrongUserNameOrPassword = fmt.Errorf("用户名或密码错误")
- )
- // 用户
- type User struct {
- *gorm.Model
- // 用户名
- Name string `gorm:"unique;index"`
- // 用户密码,保存为 HS256 散列值
- Password string
- // 用户所有词库
- Dicts []Dict
- }
- type UserResult struct {
- ID uint `json:"id"`
- Name string `json:"name"`
- }
- // 计算密码的 HS256 散列值
- func hashPassword(password string) string {
- mac := hmac.New(sha256.New, global.SecretKey)
- mac.Write([]byte(password))
- return fmt.Sprintf("%x", mac.Sum(nil))
- }
- // 获取用户
- func GetUser(user *User) (*UserResult, error) {
- result := &UserResult{}
- if err := global.DB.Model(&User{}).Take(result, user, "id").Error; err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, ErrUserNotFound
- }
- return nil, err
- }
- return result, nil
- }
- // 创建用户
- func CreateUser(user *User) (*UserResult, error) {
- if err := global.DB.Model(&User{}).Take(&struct{ ID uint }{}, user, "name").Error; !errors.Is(err, gorm.ErrRecordNotFound) {
- if err != nil {
- return nil, err
- }
- return nil, ErrUserNameAlreadyExists
- }
- user.Password = hashPassword(user.Password)
- if err := global.DB.Select("name", "password").Create(user).Error; err != nil {
- return nil, err
- }
- return &UserResult{
- ID: user.ID,
- Name: user.Name,
- }, nil
- }
- // 认证用户
- func AuthenticateUser(user *User) (*UserResult, error) {
- user.Password = hashPassword(user.Password)
- result := &UserResult{}
- if err := global.DB.Model(&User{}).Take(result, user, "name", "password").Error; err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, ErrWrongUserNameOrPassword
- }
- return nil, err
- }
- return result, nil
- }
|