feat(login):基本完成用户登录,待测。

This commit is contained in:
徐涛
2022-08-12 06:32:25 +08:00
parent 8f4e0320fd
commit 1c5bcf033b
8 changed files with 265 additions and 0 deletions

94
service/user.go Normal file
View File

@@ -0,0 +1,94 @@
package service
import (
"crypto/sha512"
"electricity_bill_calc/cache"
"electricity_bill_calc/config"
"electricity_bill_calc/exceptions"
"electricity_bill_calc/model"
"electricity_bill_calc/repository"
"fmt"
"time"
"github.com/google/uuid"
)
type _UserService struct{}
var UserService _UserService
func (_UserService) ProcessEnterpriseUserLogin(username, password string) (*model.Session, error) {
user, err := repository.UserRepo.FindUserByUsername(username)
if err != nil {
return nil, err
}
if user == nil {
return nil, exceptions.NewAuthenticationError(404, "用户不存在。")
}
if user.Type != 0 {
return nil, exceptions.NewAuthenticationError(401, "用户类型不正确。")
}
hash := sha512.New512_256()
hash.Write([]byte(password))
hashedPassword := fmt.Sprintf("%x", hash.Sum(nil))
if hashedPassword != user.Password {
return nil, exceptions.NewAuthenticationError(401, "用户凭据不正确。")
}
if user.ResetNeeded {
authErr := exceptions.NewAuthenticationError(401, "用户凭据已失效。")
authErr.NeedReset = true
return nil, authErr
}
session := &model.Session{
Token: uuid.New().String(),
Uid: user.Id,
Type: user.Type,
Name: user.Username,
ExpiresAt: time.Now().Add(config.ServiceSettings.MaxSessionLife),
}
userDetial, _ := repository.UserRepo.RetreiveUserDetail(user.Id)
if userDetial != nil {
session.Name = *userDetial.Name
}
cache.CacheSession(session)
return session, nil
}
func (_UserService) ProcessManagementUserLogin(username, password string) (*model.Session, error) {
user, err := repository.UserRepo.FindUserByUsername(username)
if err != nil {
return nil, err
}
if user == nil {
return nil, exceptions.NewAuthenticationError(404, "用户不存在。")
}
if user.Type != 1 && user.Type != 2 {
return nil, exceptions.NewAuthenticationError(401, "用户类型不正确。")
}
hash := sha512.New512_256()
hash.Write([]byte(password))
hashedPassword := fmt.Sprintf("%x", hash.Sum(nil))
if hashedPassword != user.Password {
return nil, exceptions.NewAuthenticationError(401, "用户凭据不正确。")
}
if user.ResetNeeded {
authErr := exceptions.NewAuthenticationError(401, "用户凭据已失效。")
authErr.NeedReset = true
return nil, authErr
}
session := &model.Session{
Token: uuid.New().String(),
Uid: user.Id,
Type: user.Type,
Name: user.Username,
ExpiresAt: time.Now().Add(config.ServiceSettings.MaxSessionLife),
}
userDetial, _ := repository.UserRepo.RetreiveUserDetail(user.Id)
if userDetial != nil {
session.Name = *userDetial.Name
}
cache.CacheSession(session)
return session, nil
}