homebox/backend/internal/services/service_user.go

195 lines
5.2 KiB
Go
Raw Normal View History

2022-08-30 02:30:36 +00:00
package services
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/internal/repo"
"github.com/hay-kot/homebox/backend/pkgs/hasher"
"github.com/rs/zerolog/log"
2022-08-30 02:30:36 +00:00
)
var (
oneWeek = time.Hour * 24 * 7
ErrorInvalidLogin = errors.New("invalid username or password")
ErrorInvalidToken = errors.New("invalid token")
ErrorTokenIdMismatch = errors.New("token id mismatch")
)
type UserService struct {
repos *repo.AllRepos
}
type (
UserRegistration struct {
GroupToken string `json:"token"`
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
GroupName string `json:"groupName"`
}
UserAuthTokenDetail struct {
Raw string `json:"raw"`
ExpiresAt time.Time `json:"expiresAt"`
}
LoginForm struct {
Username string `json:"username"`
Password string `json:"password"`
}
)
2022-09-04 06:19:13 +00:00
// RegisterUser creates a new user and group in the data with the provided data. It also bootstraps the user's group
// with default Labels and Locations.
func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration) (repo.UserOut, error) {
log.Debug().
Str("name", data.Name).
Str("email", data.Email).
Str("groupName", data.GroupName).
Str("groupToken", data.GroupToken).
Msg("Registering new user")
var (
err error
group repo.Group
token repo.GroupInvitation
)
if data.GroupToken == "" {
group, err = svc.repos.Groups.GroupCreate(ctx, data.GroupName)
if err != nil {
log.Err(err).Msg("Failed to create group")
return repo.UserOut{}, err
}
} else {
token, err = svc.repos.Groups.InvitationGet(ctx, hasher.HashToken(data.GroupToken))
if err != nil {
log.Err(err).Msg("Failed to get invitation token")
return repo.UserOut{}, err
}
group = token.Group
2022-08-30 18:05:11 +00:00
}
hashed, _ := hasher.HashPassword(data.Password)
usrCreate := repo.UserCreate{
Name: data.Name,
Email: data.Email,
2022-08-30 18:05:11 +00:00
Password: hashed,
IsSuperuser: false,
GroupID: group.ID,
}
2022-09-04 06:19:13 +00:00
usr, err := svc.repos.Users.Create(ctx, usrCreate)
if err != nil {
return repo.UserOut{}, err
2022-09-04 06:19:13 +00:00
}
for _, label := range defaultLabels() {
_, err := svc.repos.Labels.Create(ctx, group.ID, label)
if err != nil {
return repo.UserOut{}, err
2022-09-04 06:19:13 +00:00
}
}
for _, location := range defaultLocations() {
_, err := svc.repos.Locations.Create(ctx, group.ID, location)
if err != nil {
return repo.UserOut{}, err
2022-09-04 06:19:13 +00:00
}
}
// Decrement the invitation token if it was used
if token.ID != uuid.Nil {
err = svc.repos.Groups.InvitationUpdate(ctx, token.ID, token.Uses-1)
if err != nil {
log.Err(err).Msg("Failed to update invitation token")
return repo.UserOut{}, err
}
}
return usr, nil
2022-08-30 18:05:11 +00:00
}
2022-08-30 02:30:36 +00:00
// GetSelf returns the user that is currently logged in based of the token provided within
func (svc *UserService) GetSelf(ctx context.Context, requestToken string) (repo.UserOut, error) {
2022-08-30 02:30:36 +00:00
hash := hasher.HashToken(requestToken)
return svc.repos.AuthTokens.GetUserFromToken(ctx, hash)
2022-08-30 02:30:36 +00:00
}
func (svc *UserService) UpdateSelf(ctx context.Context, ID uuid.UUID, data repo.UserUpdate) (repo.UserOut, error) {
2022-08-30 02:30:36 +00:00
err := svc.repos.Users.Update(ctx, ID, data)
if err != nil {
return repo.UserOut{}, err
2022-08-30 02:30:36 +00:00
}
return svc.repos.Users.GetOneId(ctx, ID)
2022-08-30 02:30:36 +00:00
}
// ============================================================================
// User Authentication
func (svc *UserService) createToken(ctx context.Context, userId uuid.UUID) (UserAuthTokenDetail, error) {
2022-08-30 02:30:36 +00:00
newToken := hasher.GenerateToken()
created, err := svc.repos.AuthTokens.CreateToken(ctx, repo.UserAuthTokenCreate{
2022-08-30 02:30:36 +00:00
UserID: userId,
TokenHash: newToken.Hash,
ExpiresAt: time.Now().Add(oneWeek),
})
return UserAuthTokenDetail{Raw: newToken.Raw, ExpiresAt: created.ExpiresAt}, err
2022-08-30 02:30:36 +00:00
}
func (svc *UserService) Login(ctx context.Context, username, password string) (UserAuthTokenDetail, error) {
2022-08-30 02:30:36 +00:00
usr, err := svc.repos.Users.GetOneEmail(ctx, username)
if err != nil || !hasher.CheckPasswordHash(password, usr.PasswordHash) {
return UserAuthTokenDetail{}, ErrorInvalidLogin
2022-08-30 02:30:36 +00:00
}
return svc.createToken(ctx, usr.ID)
}
func (svc *UserService) Logout(ctx context.Context, token string) error {
hash := hasher.HashToken(token)
err := svc.repos.AuthTokens.DeleteToken(ctx, hash)
return err
}
func (svc *UserService) RenewToken(ctx context.Context, token string) (UserAuthTokenDetail, error) {
2022-08-30 02:30:36 +00:00
hash := hasher.HashToken(token)
dbToken, err := svc.repos.AuthTokens.GetUserFromToken(ctx, hash)
if err != nil {
return UserAuthTokenDetail{}, ErrorInvalidToken
2022-08-30 02:30:36 +00:00
}
newToken, _ := svc.createToken(ctx, dbToken.ID)
return newToken, nil
}
2022-09-04 02:42:03 +00:00
// DeleteSelf deletes the user that is currently logged based of the provided UUID
// There is _NO_ protection against deleting the wrong user, as such this should only
// be used when the identify of the user has been confirmed.
func (svc *UserService) DeleteSelf(ctx context.Context, ID uuid.UUID) error {
return svc.repos.Users.Delete(ctx, ID)
}
func (svc *UserService) NewInvitation(ctx Context, uses int, expiresAt time.Time) (string, error) {
token := hasher.GenerateToken()
_, err := svc.repos.Groups.InvitationCreate(ctx, ctx.GID, repo.GroupInvitationCreate{
Token: token.Hash,
Uses: uses,
ExpiresAt: expiresAt,
})
if err != nil {
return "", err
}
return token.Raw, nil
}