package service import ( e "errors" "gold-shop/errors" "gold-shop/global" "gold-shop/model" "gold-shop/utils" "gorm.io/gorm" ) var AdminService = adminService{} type adminService struct { } func (adminService) Login(username string, password string) (string, error) { admin := &model.Admin{} err := global.DB.Where("username", username).First(admin).Error if e.Is(err, gorm.ErrRecordNotFound) { return "", errors.NewBusinessError("账号或密码错误") } if utils.PasswordVerify(password, admin.PasswordHash) { return utils.GenerateToken(admin.ID, "admin") } return "", errors.NewBusinessError("账号或密码错误") } func (adminService) Add(username string, password string) error { admin := &model.Admin{} err := global.DB.Where("username", username).First(admin).Error if err == nil { return errors.NewBusinessError("账号已存在") } admin.Username = username passwordHash, _ := utils.PasswordHash(password) admin.PasswordHash = passwordHash return global.DB.Save(admin).Error } func (adminService) ModifyPassword(password string, oldPassword string, admin *model.Admin) error { if !utils.PasswordVerify(oldPassword, admin.PasswordHash) { return errors.NewBusinessError("旧密码错误") } passwordHash, _ := utils.PasswordHash(password) admin.PasswordHash = passwordHash return global.DB.Save(admin).Error } func (adminService) ResetPassword(adminID int, password string) error { admin := &model.Admin{} err := global.DB.Where("id", adminID).First(admin).Error if e.Is(err, gorm.ErrRecordNotFound) { return errors.NewBusinessError("账号不存在") } passwordHash, _ := utils.PasswordHash(password) admin.PasswordHash = passwordHash return global.DB.Save(admin).Error } func (adminService) GetAdminInfo(adminID int) *model.Admin { admin := &model.Admin{} global.DB.Where("id", adminID).First(admin) return admin }