electricity_bill_calc_service/service/user.go

95 lines
2.6 KiB
Go

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
}