Skip to content

πŸ“š The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.

11.2 KB
Raw Blame
package services

import (
	"alexandrie/models"
	"alexandrie/permissions"
	"alexandrie/pkg/logger"
	"alexandrie/pkg/snowflake"
	"alexandrie/repositories"
	"alexandrie/types"
	"alexandrie/utils"
	"bytes"
	"context"
	"crypto/rand"
	"errors"
	"fmt"
	"html/template"
	"os"
	"regexp"
	"slices"
	"strconv"
	"strings"
	"time"

	"github.com/golang-jwt/jwt/v5"
	"github.com/wneessen/go-mail"
	"golang.org/x/crypto/bcrypt"
)

type UserService interface {
	GetAllUsers() ([]*models.User, error)
	GetUserById(ctx context.Context, id types.Snowflake) (*models.User, error)
	GetUserByUsername(username string) (*models.User, error)
	SearchPublicUsers(query string) ([]*models.User, error)
	CreateUser(username string, firstname, lastname, avatar, email string, user_type int, password string, totp_forced bool) (*models.User, error)
	UpdateUser(ctx context.Context, id types.Snowflake, firstname, lastname, avatar, email *string, user_type int, totp_forced bool) (*models.User, error)
	UpdatePassword(ctx context.Context, id types.Snowflake, currentPassword string, newPassword string) error
	DeleteUser(ctx context.Context, id types.Snowflake, minioService MinioService) error
	GenerateUniqueUsername(givenName *string, userID types.Snowflake) string
	LoadAppAdmins()
}

type userService struct {
	userRepo   repositories.UserRepository
	logRepo    repositories.LogRepository
	snowflake  *snowflake.Snowflake
	access     permissions.AccessGuard
	mailClient *mail.Client
}

func NewUserService(userRepo repositories.UserRepository, logRepo repositories.LogRepository, snowflake *snowflake.Snowflake, access permissions.AccessGuard, mailClient *mail.Client) UserService {
	userService := &userService{
		userRepo:   userRepo,
		logRepo:    logRepo,
		snowflake:  snowflake,
		access:     access,
		mailClient: mailClient,
	}
	userService.LoadAppAdmins() // On startup, ensure admin users are loaded and updated
	return userService
}

func (s *userService) GetAllUsers() ([]*models.User, error) {
	return s.userRepo.GetAll()
}

func (s *userService) GetUserById(ctx context.Context, id types.Snowflake) (*models.User, error) {
	actor, err := actorFromContext(ctx)
	if err != nil {
		return nil, err
	}
	if err := s.access.RequireUserAccess(actor, id); err != nil {
		return nil, err
	}

	user, err := s.userRepo.GetByID(id, false)
	if err != nil {
		return nil, err
	}
	if user == nil {
		return nil, permissions.ErrNotFound
	}

	return user, nil
}

func (s *userService) GetUserByUsername(username string) (*models.User, error) {
	return s.userRepo.GetByUsername(username)
}

func (s *userService) SearchPublicUsers(query string) ([]*models.User, error) {
	return s.userRepo.SearchPublic(query)
}

func (s *userService) CreateUser(username, firstname, lastname, avatar, email string, user_type int, password string, totp_forced bool) (*models.User, error) {
	exists, err := s.userRepo.CheckUsernameExists(username)
	if err != nil {
		return nil, err
	}
	if exists {
		return nil, errors.New("username already exists")
	}

	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return nil, errors.New("failed to hash password")
	}
	hashStr := string(hash)

	user := &models.User{
		Id:               s.snowflake.Generate(),
		Username:         username,
		Firstname:        &firstname,
		Lastname:         &lastname,
		Type:             user_type,
		Avatar:           &avatar,
		Role:             1,
		Email:            &email,
		Password:         &hashStr,
		CreatedTimestamp: time.Now().UnixMilli(),
		UpdatedTimestamp: time.Now().UnixMilli(),
		TOTPForced:       totp_forced,
	}

	if password == "" {

		if user.Email == nil || *user.Email == "" {
			return nil, errors.New("no email provided") // No email to send to
		}

		if s.mailClient == nil {
			return nil, errors.New("mail client is not initialized")
		}

		resetToken := signSetToken(user.Id)
		err = sendPasswordCreatedEmail(s.mailClient, user, resetToken)
		if err != nil {
			return nil, err
		}
	}

	createdUser, err := s.userRepo.Create(user)
	if err != nil {
		return nil, err
	}

	createdUser.Password = nil
	return createdUser, nil
}

type PasswordCreatedEmailData struct {
	ResetURL    string
	Username    string
	FrontendURL string
}

func sendPasswordCreatedEmail(mailClient *mail.Client, user *models.User, resetToken string) error {
	mailFrom := os.Getenv("SMTP_MAIL_FROM")
	if mailFrom == "" {
		mailFrom = os.Getenv("SMTP_MAIL")
	}

	resetURL := os.Getenv("FRONTEND_URL") +
		"/login/reset?token=" +
		resetToken

	tmpl, err := template.ParseFiles("emails/account-create.html")
	if err != nil {
		return err
	}

	var htmlBody bytes.Buffer

	data := PasswordCreatedEmailData{
		ResetURL:    resetURL,
		Username:    user.Username,
		FrontendURL: os.Getenv("FRONTEND_URL"),
	}

	if err := tmpl.Execute(&htmlBody, data); err != nil {
		return err
	}

	message := mail.NewMsg()
	message.FromFormat("Alexandrie Team", mailFrom)
	message.To(*user.Email)
	message.Subject("Alexandrie: Set your password")

	message.SetBodyString(
		mail.TypeTextPlain,
		"An app administrator has created an account for you.\n\n"+
			"Set your password: "+resetURL+"\n\n"+
			"Your username: "+user.Username+"\n\n"+
			"If you did not expect this email, please ignore it.",
	)

	message.AddAlternativeString(
		mail.TypeTextHTML,
		htmlBody.String(),
	)

	if err := mailClient.DialAndSend(message); err != nil {
		return errors.New("failed to send password set email")
	}

	return nil
}

func signSetToken(userId types.Snowflake) string {
	claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"sub": strconv.FormatUint(uint64(userId), 10),
	})
	tokenString, err := claims.SignedString([]byte(os.Getenv("JWT_SECRET")))
	if err != nil {
		return ""
	}
	return tokenString
}

func (s *userService) UpdateUser(ctx context.Context, id types.Snowflake, firstname, lastname, avatar, email *string, user_type int, totp_forced bool) (*models.User, error) {
	actor, err := actorFromContext(ctx)
	if err != nil {
		return nil, err
	}
	if err := s.access.RequireUserAccess(actor, id); err != nil {
		return nil, err
	}

	dbUser, err := s.userRepo.GetByID(id, false)
	if err != nil || dbUser == nil {
		return nil, permissions.ErrNotFound
	}

	if s.access.IsAppAdmin(actor.Role) {
		if user_type != 0 && user_type != 1 {
			return nil, errors.New("invalid user type")
		}
	} else {
		user_type = dbUser.Type         // Non-admins cannot change user type
		totp_forced = dbUser.TOTPForced // Non-admins cannot change TOTP forced status
	}

	user := &models.User{
		Id:               id,
		Username:         dbUser.Username,
		Firstname:        utils.IfNotNilPointer(firstname, dbUser.Firstname),
		Lastname:         utils.IfNotNilPointer(lastname, dbUser.Lastname),
		Type:             user_type,
		Avatar:           utils.IfNotNilPointer(avatar, dbUser.Avatar),
		Email:            utils.IfNotNilPointer(email, dbUser.Email),
		CreatedTimestamp: dbUser.CreatedTimestamp,
		UpdatedTimestamp: time.Now().UnixMilli(),
	}

	return s.userRepo.Update(id, user)
}

func (s *userService) UpdatePassword(ctx context.Context, id types.Snowflake, currentPassword string, newPassword string) error {
	actor, err := actorFromContext(ctx)
	if err != nil {
		return err
	}
	if err := s.access.RequireUserAccess(actor, id); err != nil {
		return err
	}

	if newPassword == "" {
		return errors.New("password is required")
	}

	// Only require the current password when users change their own password.
	// App admins resetting another user's password are exempt (e.g. account recovery).
	if actor.UserID == id {
		dbUser, err := s.userRepo.GetByID(id, true)
		if err != nil || dbUser == nil {
			return permissions.ErrNotFound
		}

		// If the user already has a password set, they must confirm it.
		// Users without a password (e.g. OAuth/SSO-only accounts) are setting
		// a password for the first time, so no current-password check applies.
		if dbUser.Password != nil {
			if currentPassword == "" {
				return permissions.ErrInvalidPassword
			}
			if err := bcrypt.CompareHashAndPassword([]byte(*dbUser.Password), []byte(currentPassword)); err != nil {
				return permissions.ErrIncorrectPassword
			}
		}
	}

	hash, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
	if err != nil {
		return errors.New("failed to hash password")
	}

	return s.userRepo.UpdatePassword(id, string(hash))
}

func (s *userService) DeleteUser(ctx context.Context, id types.Snowflake, minioService MinioService) error {
	actor, err := actorFromContext(ctx)
	if err != nil {
		return err
	}
	if err := s.access.RequireUserAccess(actor, id); err != nil {
		return err
	}

	if minioService != nil {
		if err := minioService.DeleteAllFromUser(id); err != nil {
			return err
		}
	}
	return s.userRepo.Delete(id)
}

var usernameAdjectives = []string{
	"Brave", "Clever", "Swift", "Mighty", "Nimble",
	"Wise", "Bold", "Fierce", "Loyal", "Gentle",
	"Bright", "Calm", "Daring", "Epic", "Fast",
}
var reg = regexp.MustCompile(`[^a-zA-Z0-9_-]`)

func sanitizeUsername(name string) string {
	name = strings.ReplaceAll(name, " ", "_")
	name = reg.ReplaceAllString(name, "")
	if len(name) > 20 {
		name = name[:20]
	}
	return name
}

func generateRandomBase() string {
	randBytes := make([]byte, 2)
	rand.Read(randBytes)
	adj := usernameAdjectives[int(randBytes[0])%len(usernameAdjectives)]
	return fmt.Sprintf("Alex-%s", adj)
}

func (s *userService) GenerateUniqueUsername(givenName *string, userID types.Snowflake) string {
	var baseUsername string

	// Determine the base username
	if givenName != nil && strings.TrimSpace(*givenName) != "" {
		baseUsername = sanitizeUsername(strings.TrimSpace(*givenName))
	}

	if baseUsername == "" {
		baseUsername = generateRandomBase()
	}

	idSuffix := fmt.Sprintf("%06d", int64(userID)%1000000)

	return fmt.Sprintf("%s-%s", baseUsername, idSuffix)
}

func (s *userService) LoadAppAdmins() {
	adminIDs := utils.GetEnvAsSlice("ADMIN_ACCOUNTS", ",")

	// Remove admin role from all users not in the current admin list
	existingAdmins, err := s.userRepo.GetAppAdmins()

	if err != nil {
		logger.Warn("app-admins", "Failed to load existing admin users: "+err.Error())
		return
	}

	for _, admin := range existingAdmins {
		if !slices.Contains(adminIDs, admin.Id.String()) {
			err := s.userRepo.UpdateRole(admin.Id, int(permissions.RoleNone))
			if err != nil {
				logger.Error("app-admins", "Failed to update user "+admin.Username+" to regular role: "+err.Error())
			} else {
				logger.Info("app-admins", "User "+admin.Username+" has been set to regular role.")
			}
		}
	}

	// Add new admins from the environment variable
	for _, idStr := range adminIDs {
		id, err := types.SnowflakeFromString(idStr)
		if err != nil {
			logger.Warn("app-admins", "Invalid admin user ID: "+idStr)
			continue
		}
		user, err := s.userRepo.GetByID(*id, false)
		if err != nil || user == nil {
			logger.Warn("app-admins", "Failed to load admin user with ID "+idStr+"\nCheck if the ID is correct and if the user exists.")
			continue
		}
		if user.Role != int(permissions.RoleAdministrator) {
			err := s.userRepo.UpdateRole(user.Id, int(permissions.RoleAdministrator))
			if err != nil {
				logger.Warn("app-admins", "Failed to update user "+user.Username+" to admin role: "+err.Error())
			} else {
				logger.Info("app-admins", "User "+user.Username+" has been granted admin role.")
			}
		} else {
			logger.Info("app-admins", "User "+user.Username+" is already an admin.")
		}
	}

}