86 lines
2.4 KiB
Go
86 lines
2.4 KiB
Go
|
package models
|
||
|
|
||
|
import (
|
||
|
"MossChat/db"
|
||
|
"MossChat/enums"
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"golang.org/x/crypto/bcrypt"
|
||
|
"gorm.io/gorm"
|
||
|
)
|
||
|
|
||
|
type User struct {
|
||
|
gorm.Model
|
||
|
Username string `json:"username"`
|
||
|
Password string `json:"-"`
|
||
|
Nickname string `json:"nickname"`
|
||
|
Gender enums.GenderType `json:"gender"`
|
||
|
Introduce string `json:"introduce"`
|
||
|
Email string `json:"email"`
|
||
|
Avatar string `json:"avatar"`
|
||
|
IsBanned bool `json:"is_banned"`
|
||
|
Phone string `json:"phone"`
|
||
|
}
|
||
|
|
||
|
func (user *User) UpdatePassword(password string) error {
|
||
|
bcryptHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||
|
if err != nil {
|
||
|
return errors.New("无法加密密码")
|
||
|
}
|
||
|
user.Password = string(bcryptHash)
|
||
|
return nil
|
||
|
}
|
||
|
func (user *User) CheckPassword(password string) error {
|
||
|
return bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
|
||
|
}
|
||
|
func (user *User) Delete() error {
|
||
|
if err := db.DB.Delete(user); err != nil {
|
||
|
return errors.New("无法删除该用户")
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func CreateUser(username string, password string, nickname string, gender enums.GenderType) (User, error) {
|
||
|
user := User{Username: username,
|
||
|
Nickname: nickname,
|
||
|
Gender: gender,
|
||
|
Introduce: "这个人很懒,什么都没留下。",
|
||
|
}
|
||
|
var count int64
|
||
|
if err := db.DB.Model(&User{}).Where("username = ?", username).Count(&count).Error; err != nil {
|
||
|
return User{}, errors.New("数据库查询错误")
|
||
|
}
|
||
|
if count != 0 {
|
||
|
return User{}, errors.New("用户已存在")
|
||
|
}
|
||
|
//加密密码
|
||
|
if err := user.UpdatePassword(password); err != nil {
|
||
|
return User{}, err
|
||
|
}
|
||
|
if err := db.DB.Create(user).Error; err != nil {
|
||
|
return User{}, errors.New("无法创建用户")
|
||
|
}
|
||
|
return user, nil
|
||
|
}
|
||
|
|
||
|
func DeleteUser(username string) error {
|
||
|
if err := db.DB.Model(&User{}).Where("username = ?", username).Delete(&User{}).Error; err != nil {
|
||
|
return errors.New(fmt.Sprintf("无法创建用户:%s", err.Error()))
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
func GetUserByUsername(username string) (User, error) {
|
||
|
var user User
|
||
|
if err := db.DB.Where("username = ?", username).First(&user).Error; err != nil {
|
||
|
return User{}, errors.New("无法找到用户")
|
||
|
}
|
||
|
return user, nil
|
||
|
}
|
||
|
func GetUserByUid(uid uint) (User, error) {
|
||
|
var user User
|
||
|
if err := db.DB.Where("uid = ?", uid).First(&user).Error; err != nil {
|
||
|
return User{}, errors.New("无法找到用户")
|
||
|
}
|
||
|
return user, nil
|
||
|
}
|