91 lines
2 KiB
Go
91 lines
2 KiB
Go
package service
|
|
|
|
import (
|
|
"gitea.qpismont.fr/qpismont/trepa/internal/accounts/domain"
|
|
"gitea.qpismont.fr/qpismont/trepa/internal/core"
|
|
)
|
|
|
|
type Service struct {
|
|
repository domain.AccountRepository
|
|
}
|
|
|
|
func NewService(repository domain.AccountRepository) domain.AccountService {
|
|
return &Service{repository: repository}
|
|
}
|
|
|
|
func (s *Service) GetAccount(id int) (*domain.Account, *core.HTTPError) {
|
|
account, err := s.repository.FetchOneById(id)
|
|
if err != nil {
|
|
return nil, core.NewInternalServerError(err)
|
|
}
|
|
|
|
if account == nil {
|
|
return nil, domain.ErrAccountNotFound
|
|
}
|
|
|
|
return account, nil
|
|
}
|
|
|
|
func (s *Service) Login(login domain.AccountLogin) (*domain.AccountWithToken, *core.HTTPError) {
|
|
account, err := s.repository.FetchOneByUsername(login.Username)
|
|
if err != nil {
|
|
return nil, core.NewInternalServerError(err)
|
|
}
|
|
|
|
if account == nil {
|
|
return nil, domain.ErrAccountNotFound
|
|
}
|
|
|
|
ok, err := core.ComparePassword(login.Password, account.Password)
|
|
if err != nil {
|
|
return nil, core.NewInternalServerError(err)
|
|
}
|
|
|
|
if !ok {
|
|
return nil, domain.ErrBadPassword
|
|
}
|
|
|
|
claims := core.JWTClaims{
|
|
AccountId: account.Id,
|
|
RoleId: account.RoleId,
|
|
}
|
|
|
|
token, err := core.SignJWT(claims)
|
|
if err != nil {
|
|
return nil, core.NewInternalServerError(err)
|
|
}
|
|
|
|
return &domain.AccountWithToken{
|
|
Account: account,
|
|
Token: token,
|
|
}, nil
|
|
}
|
|
|
|
func (s *Service) Register(register domain.AccountRegister) (int, *core.HTTPError) {
|
|
accountExist, err := s.repository.FetchOneByUsername(register.Username)
|
|
if err != nil {
|
|
return 0, core.NewInternalServerError(err)
|
|
}
|
|
|
|
if accountExist != nil {
|
|
return 0, domain.ErrAccountAlreadyExists
|
|
}
|
|
|
|
hashedPassword, err := core.HashPassword(register.Password)
|
|
if err != nil {
|
|
return 0, core.NewInternalServerError(err)
|
|
}
|
|
|
|
account := domain.Account{
|
|
Username: register.Username,
|
|
Password: hashedPassword,
|
|
RoleId: register.RoleId,
|
|
}
|
|
|
|
id, err := s.repository.Insert(account)
|
|
if err != nil {
|
|
return 0, core.NewInternalServerError(err)
|
|
}
|
|
|
|
return id, nil
|
|
}
|