📚 The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.
Vue dockergolangkanbanknowledge-baseknowledge-managementmarkdownnote-takingnotesnotes-appnotionnuxtnuxtjsoffline-firstoidcpwaselfhostedssovuevuejswiki
feat: new user management system & forced 2FA option (#669)
Smaugec4ec3719209
diff --git a/backend/app/app.go b/backend/app/app.goindex 5b09fb6e..b436751f 100644--- a/backend/app/app.go+++ b/backend/app/app.go@@ -66,7 +66,7 @@ func InitApp(config Config) *App {SupportedTypes: config.Cdn.SupportedTypes,SupportedTypesImages: config.Cdn.SupportedTypesImages,}- serviceManager, err := services.NewServiceManager(repoManager, app.Snowflake, app.MinioClient, resourceConfig)+ serviceManager, err := services.NewServiceManager(repoManager, app.Snowflake, app.MinioClient, app.MailClient, resourceConfig)if err != nil {log.Fatalf("Failed to initialize service manager: %v", err)}diff --git a/backend/app/migrations/000020_users.up.sql b/backend/app/migrations/000020_users.up.sqlnew file mode 100644index 00000000..5edc3278--- /dev/null+++ b/backend/app/migrations/000020_users.up.sql@@ -0,0 +1,2 @@+ALTER TABLE users ADD COLUMN totp_forced BOOLEAN DEFAULT FALSE AFTER totp_enabled;+ALTER TABLE users ADD COLUMN `type` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '0: Regular user, 1: Supervised account' AFTER `role`;diff --git a/backend/controllers/authentication.controller.go b/backend/controllers/authentication.controller.goindex ab987c64..b4c15619 100644--- a/backend/controllers/authentication.controller.go+++ b/backend/controllers/authentication.controller.go@@ -8,6 +8,7 @@ import ("os""github.com/gin-gonic/gin"+ "github.com/gin-gonic/gin/binding")type AuthController interface {@@ -81,6 +82,15 @@ func (ctr *Controller) Login(c *gin.Context) (int, any) {if err != nil {return http.StatusUnauthorized, err}++ if user.TOTPForced && !user.TotpEnabled {+ return http.StatusAccepted, gin.H{+ "message": "2FA_TO_ENABLE",+ "pre_auth_token": preAuthToken,+ "user_id": user.Id,+ }+ }+if user.TotpEnabled && session == nil {return http.StatusAccepted, gin.H{"message": "2FA_REQUIRED",@@ -219,13 +229,31 @@ func (ctr *Controller) LogoutAllDevices(c *gin.Context) (int, any) {// @Security Session validation// @Success 200 {object} Success// @Failure 400 {object} Error+type PreAuthClaims struct {+ PreAuthToken string `json:"pre_auth_token"`+}+func (ctr *Controller) RequestTOTPActivation(c *gin.Context) (int, any) {++ // Two ways to get the user ID:+ // 1. From the session (if the user is logged in)+ // 2. From the preauth token (if the user is in the process of logging in and needs to enable 2FA)userId, err := utils.GetUserIdCtx(c)if err != nil {- return http.StatusBadRequest, err+ var claims PreAuthClaims+ if err := c.BindJSON(&claims); err != nil {+ return http.StatusBadRequest, err+ }+ if claims.PreAuthToken == "" {+ return http.StatusBadRequest, errors.New("pre_auth_token is required")+ }+ userId, err = ctr.app.Services.Auth.VerifyPreAuth(claims.PreAuthToken)+ if err != nil {+ return http.StatusUnauthorized, err+ }}- user, err := ctr.app.Services.User.GetUserById(c.Request.Context(), userId)+ user, err := ctr.app.Repos.User.GetByID(userId, false)if err != nil || user == nil {return http.StatusBadRequest, errors.New("user not found")}@@ -251,16 +279,30 @@ func (ctr *Controller) RequestTOTPActivation(c *gin.Context) (int, any) {// @Success 200 {object} Success(string)// @Failure 400 {object} Errorfunc (ctr *Controller) ConfirmTOTPActivation(c *gin.Context) (int, any) {++ // Two ways to get the user ID:+ // 1. From the session (if the user is logged in)+ // 2. From the preauth token (if the user is in the process of logging in and needs to enable 2FA)userId, err := utils.GetUserIdCtx(c)if err != nil {- return http.StatusBadRequest, err+ var claims PreAuthClaims+ if err := c.ShouldBindBodyWith(&claims, binding.JSON); err != nil {+ return http.StatusBadRequest, err+ }+ if claims.PreAuthToken == "" {+ return http.StatusBadRequest, errors.New("pre_auth_token is required")+ }+ userId, err = ctr.app.Services.Auth.VerifyPreAuth(claims.PreAuthToken)+ if err != nil {+ return http.StatusUnauthorized, err+ }}var data struct {Secret string `json:"secret" binding:"required"`Code string `json:"code" binding:"required"`}- if err := c.ShouldBindJSON(&data); err != nil {+ if err := c.ShouldBindBodyWith(&data, binding.JSON); err != nil {return http.StatusBadRequest, err}diff --git a/backend/controllers/users.controller.go b/backend/controllers/users.controller.goindex 69bba398..ef283a54 100644--- a/backend/controllers/users.controller.go+++ b/backend/controllers/users.controller.go@@ -116,8 +116,11 @@ func (ctr *Controller) CreateUser(c *gin.Context) (int, any) {lastname := utils.StringValue(user.Lastname)avatar := utils.StringValue(user.Avatar)email := utils.StringValue(user.Email)+ password := utils.StringValue(user.Password)+ user_type := user.Type+ totp_forced := user.TOTPForced- createdUser, err := ctr.app.Services.User.CreateUser(user.Username, firstname, lastname, avatar, email, user.Password)+ createdUser, err := ctr.app.Services.User.CreateUser(user.Username, firstname, lastname, avatar, email, user_type, password, totp_forced)if err != nil {return http.StatusBadRequest, err}@@ -150,7 +153,7 @@ func (ctr *Controller) UpdateUser(c *gin.Context) (int, any) {return http.StatusBadRequest, err}- updatedUser, err := ctr.app.Services.User.UpdateUser(c.Request.Context(), targetUserId, user.Firstname, user.Lastname, user.Avatar, user.Email)+ updatedUser, err := ctr.app.Services.User.UpdateUser(c.Request.Context(), targetUserId, user.Firstname, user.Lastname, user.Avatar, user.Email, user.Type, user.TOTPForced)if err != nil {return statusFromAccessError(err), err}diff --git a/backend/emails/account-create.html b/backend/emails/account-create.htmlnew file mode 100644index 00000000..34870bc1--- /dev/null+++ b/backend/emails/account-create.html@@ -0,0 +1,181 @@+<!doctype html>+<html lang="en">++<head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Set your Alexandrie password</title>+</head>++<body style="+ margin: 0;+ padding: 0;+ background-color: #f4f4f5;+ font-family: Arial, Helvetica, sans-serif;+ color: #18181b;+">+ <table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color: #f4f4f5; padding: 40px 20px">+ <tr>+ <td align="center">++ <!-- Main container -->+ <table width="100%" cellpadding="0" cellspacing="0" border="0" style="+ max-width: 600px;+ background-color: #ffffff;+ border-radius: 12px;+ overflow: hidden;+ ">+ <!-- Header -->+ <tr>+ <td align="center" style="padding: 32px 40px; background-color: #18181b">+ <div style="+ font-size: 28px;+ font-weight: bold;+ color: #ffffff;+ ">+ Alexandrie+ </div>+ <img src="{{ .FrontendURL }}/Logo/Alexandrie-logo-dark-crop.png" alt="Alexandrie Logo" style="+ margin-top: 16px;+ width: 48px;+ height: 48px;+ " />+ </td>+ </tr>++ <!-- Content -->+ <tr>+ <td style="padding: 40px">++ <h1 style="+ margin: 0 0 20px;+ font-size: 24px;+ color: #18181b;+ ">+ Set your password+ </h1>++ <p style="+ margin: 0 0 16px;+ font-size: 16px;+ line-height: 1.6;+ color: #52525b;+ ">+ An app administrator has created an account for you on+ Alexandrie.+ </p>++ <p style="+ margin: 0 0 28px;+ font-size: 16px;+ line-height: 1.6;+ color: #52525b;+ ">+ Click the button below to set your password and access your+ account.+ </p>++ <!-- Button -->+ <table cellpadding="0" cellspacing="0" border="0">+ <tr>+ <td align="center" style="+ border-radius: 8px;+ background-color: #6366f1;+ ">+ <a href="{{ .ResetURL }}" style="+ display: inline-block;+ padding: 14px 24px;+ font-size: 16px;+ font-weight: bold;+ color: #ffffff;+ text-decoration: none;+ ">+ Set my password+ </a>+ </td>+ </tr>+ </table>++ <!-- Username -->+ <div style="+ margin-top: 32px;+ padding: 16px;+ background-color: #f4f4f5;+ border-radius: 8px;+ ">+ <p style="+ margin: 0;+ font-size: 14px;+ color: #71717a;+ ">+ Your username+ </p>++ <p style="+ margin: 6px 0 0;+ font-size: 16px;+ font-weight: bold;+ color: #18181b;+ ">+ {{ .Username }}+ </p>+ </div>++ <!-- Fallback link -->+ <p style="+ margin: 32px 0 0;+ font-size: 13px;+ line-height: 1.5;+ color: #71717a;+ ">+ If the button doesn't work, copy and paste this link into your+ browser:+ </p>++ <p style="+ margin: 8px 0 0;+ font-size: 13px;+ word-break: break-all;+ ">+ <a href="{{ .ResetURL }}" style="color: #6366f1">+ {{ .ResetURL }}+ </a>+ </p>++ </td>+ </tr>++ <!-- Footer -->+ <tr>+ <td align="center" style="+ padding: 24px 40px;+ background-color: #fafafa;+ border-top: 1px solid #e4e4e7;+ ">+ <p style="+ margin: 0;+ font-size: 13px;+ line-height: 1.5;+ color: #71717a;+ ">+ If you did not expect this email, you can safely ignore it.+ </p>++ <p style="+ margin: 12px 0 0;+ font-size: 12px;+ color: #a1a1aa;+ ">+ © Alexandrie+ </p>+ </td>+ </tr>++ </table>++ </td>+ </tr>+ </table>+</body>++</html>\ No newline at end of filediff --git a/backend/emails/password-reset.html b/backend/emails/password-reset.htmlnew file mode 100644index 00000000..a8054f5b--- /dev/null+++ b/backend/emails/password-reset.html@@ -0,0 +1,154 @@+<!doctype html>+<html lang="en">++<head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Reset your Alexandrie password</title>+</head>++<body style="+ margin: 0;+ padding: 0;+ background-color: #f4f4f5;+ font-family: Arial, Helvetica, sans-serif;+ color: #18181b;+">+ <table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color: #f4f4f5; padding: 40px 20px">+ <tr>+ <td align="center">++ <!-- Main container -->+ <table width="100%" cellpadding="0" cellspacing="0" border="0" style="+ max-width: 600px;+ background-color: #ffffff;+ border-radius: 12px;+ overflow: hidden;+ ">+ <!-- Header -->+ <tr>+ <td align="center" style="padding: 32px 40px; background-color: #18181b">+ <div style="+ font-size: 28px;+ font-weight: bold;+ color: #ffffff;+ ">+ Alexandrie+ </div>+ <img src="{{ .FrontendURL }}/Logo/Alexandrie-logo-dark-crop.png" alt="Alexandrie Logo" style="+ margin-top: 16px;+ width: 48px;+ " />+ </td>+ </tr>++ <!-- Content -->+ <tr>+ <td style="padding: 40px">++ <h1 style="+ margin: 0 0 20px;+ font-size: 24px;+ color: #18181b;+ ">+ Reset your password+ </h1>++ <p style="+ margin: 0 0 16px;+ font-size: 16px;+ line-height: 1.6;+ color: #52525b;+ ">+ You recently requested to reset your password.+ </p>++ <p style="+ margin: 0 0 28px;+ font-size: 16px;+ line-height: 1.6;+ color: #52525b;+ ">+ Click the button below to set a new password and access your+ account.+ </p>++ <!-- Button -->+ <table cellpadding="0" cellspacing="0" border="0">+ <tr>+ <td align="center" style="+ border-radius: 8px;+ background-color: #6366f1;+ ">+ <a href="{{ .ResetURL }}" style="+ display: inline-block;+ padding: 14px 24px;+ font-size: 16px;+ font-weight: bold;+ color: #ffffff;+ text-decoration: none;+ ">+ Reset my password+ </a>+ </td>+ </tr>+ </table>++ <!-- Fallback link -->+ <p style="+ margin: 32px 0 0;+ font-size: 13px;+ line-height: 1.5;+ color: #71717a;+ ">+ If the button doesn't work, copy and paste this link into your+ browser:+ </p>++ <p style="+ margin: 8px 0 0;+ font-size: 13px;+ word-break: break-all;+ ">+ <a href="{{ .ResetURL }}" style="color: #6366f1">+ {{ .ResetURL }}+ </a>+ </p>++ </td>+ </tr>++ <!-- Footer -->+ <tr>+ <td align="center" style="+ padding: 24px 40px;+ background-color: #fafafa;+ border-top: 1px solid #e4e4e7;+ ">+ <p style="+ margin: 0;+ font-size: 13px;+ line-height: 1.5;+ color: #71717a;+ ">+ If you did not expect this email, you can safely ignore it.+ </p>++ <p style="+ margin: 12px 0 0;+ font-size: 12px;+ color: #a1a1aa;+ ">+ © Alexandrie+ </p>+ </td>+ </tr>++ </table>++ </td>+ </tr>+ </table>+</body>++</html>\ No newline at end of filediff --git a/backend/middlewares/authentification.go b/backend/middlewares/authentification.goindex 6665c616..191dcfbe 100644--- a/backend/middlewares/authentification.go+++ b/backend/middlewares/authentification.go@@ -17,10 +17,18 @@ type AuthClaims struct {jwt.RegisteredClaims}-func Auth() gin.HandlerFunc {+func Auth(allowNoAuthorization ...bool) gin.HandlerFunc {+ allowNoToken := false+ if len(allowNoAuthorization) > 0 {+ allowNoToken = allowNoAuthorization[0]+ }return func(c *gin.Context) {tokenString, err := c.Cookie("Authorization")if err != nil {+ if allowNoToken {+ c.Next()+ return+ }c.JSON(http.StatusUnauthorized, utils.Error("Bad access token."))c.Abort()returndiff --git a/backend/models/user.model.go b/backend/models/user.model.goindex bd4821d0..b436943f 100644--- a/backend/models/user.model.go+++ b/backend/models/user.model.go@@ -8,11 +8,13 @@ type User struct {Firstname *string `json:"firstname" form:"firstname" binding:"omitempty" db:"firstname"`Lastname *string `json:"lastname" form:"lastname" binding:"omitempty" db:"lastname"`Role int `json:"role" form:"role" binding:"omitempty" db:"role"` // 1: user, 2: admin+ Type int `json:"type" form:"type" binding:"omitempty" db:"type"` // 0: Regular user, 1: Supervised accountAvatar *string `json:"avatar" form:"avatar" binding:"omitempty" db:"avatar"`Email *string `json:"email" form:"email" binding:"omitempty,email" db:"email"`Password *string `json:"password,omitempty" form:"password" binding:"omitempty,min=4,max=50" db:"password"`TotpSecret *string `json:"-" db:"totp_secret"`TotpEnabled bool `json:"totp_enabled" db:"totp_enabled"`+ TOTPForced bool `json:"totp_forced" db:"totp_forced"`CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty" db:"created_timestamp"`UpdatedTimestamp int64 `json:"updated_timestamp" form:"updated_timestamp" binding:"omitempty" db:"updated_timestamp"`}diff --git a/backend/repositories/user.repository.go b/backend/repositories/user.repository.goindex e0adbf2f..cf91c292 100644--- a/backend/repositories/user.repository.go+++ b/backend/repositories/user.repository.go@@ -37,7 +37,7 @@ func NewUserRepository(db *sqlx.DB) UserRepository {func (r *UserRepositoryImpl) GetAll() ([]*models.User, error) {var users []*models.Usererr := r.db.Select(&users, `- SELECT id, username, firstname, lastname, role, avatar, email, totp_enabled, created_timestamp, updated_timestamp+ SELECT id, type, username, firstname, lastname, role, avatar, email, totp_enabled, totp_forced, created_timestamp, updated_timestampFROM usersORDER BY created_timestamp DESC`)if err != nil {@@ -51,12 +51,12 @@ func (r *UserRepositoryImpl) GetByID(id types.Snowflake, secrets bool) (*models.var err errorif secrets {err = r.db.Get(&user, `- SELECT id, username, firstname, lastname, role, avatar, email, password, totp_secret, totp_enabled, created_timestamp, updated_timestamp+ SELECT id, username, firstname, lastname, role, avatar, email, password, totp_secret, totp_enabled, totp_forced, created_timestamp, updated_timestampFROM usersWHERE id = ?`, id)} else {err = r.db.Get(&user, `- SELECT id, username, firstname, lastname, role, avatar, email, totp_enabled, created_timestamp, updated_timestamp+ SELECT id, username, firstname, lastname, role, avatar, email, totp_enabled, totp_forced, created_timestamp, updated_timestampFROM usersWHERE id = ?`, id)}@@ -72,7 +72,7 @@ func (r *UserRepositoryImpl) GetByID(id types.Snowflake, secrets bool) (*models.func (r *UserRepositoryImpl) GetByUsername(username string) (*models.User, error) {var user models.Usererr := r.db.Get(&user, `- SELECT id, username, firstname, lastname, role, avatar, email, password, totp_enabled, created_timestamp, updated_timestamp+ SELECT id, username, firstname, lastname, role, avatar, email, password, totp_enabled, created_timestamp, updated_timestamp, totp_forcedFROM usersWHERE username = ?`, username)if err == sql.ErrNoRows {@@ -153,8 +153,8 @@ func (r *UserRepositoryImpl) CheckUsernameExists(username string) (bool, error)func (r *UserRepositoryImpl) Create(user *models.User) (*models.User, error) {_, err := r.db.NamedExec(`- INSERT INTO users (id, username, firstname, lastname, role, avatar, email, password, created_timestamp, updated_timestamp)- VALUES (:id, :username, :firstname, :lastname, :role, :avatar, :email, :password, :created_timestamp, :updated_timestamp)`,+ INSERT INTO users (id, username, firstname, lastname, role, type, avatar, email, password, created_timestamp, updated_timestamp, totp_forced)+ VALUES (:id, :username, :firstname, :lastname, :role, :type, :avatar, :email, :password, :created_timestamp, :updated_timestamp, :totp_forced)`,user)if err != nil {return nil, fmt.Errorf("failed to create user: %w", err)@@ -165,9 +165,9 @@ func (r *UserRepositoryImpl) Create(user *models.User) (*models.User, error) {func (r *UserRepositoryImpl) Update(id types.Snowflake, user *models.User) (*models.User, error) {_, err := r.db.Exec(`UPDATE users- SET username=?, firstname=?, lastname=?, avatar=?, email=?, updated_timestamp=?+ SET username=?, firstname=?, lastname=?, type=?, avatar=?, email=?, updated_timestamp=?, totp_forced=?WHERE id=?`,- user.Username, user.Firstname, user.Lastname, user.Avatar, user.Email, user.UpdatedTimestamp, id)+ user.Username, user.Firstname, user.Lastname, user.Type, user.Avatar, user.Email, user.UpdatedTimestamp, user.TOTPForced, id)if err != nil {return nil, fmt.Errorf("failed to update user: %w", err)}diff --git a/backend/router/routes/auth.go b/backend/router/routes/auth.goindex 2b9dafb7..82d8b3b0 100644--- a/backend/router/routes/auth.go+++ b/backend/router/routes/auth.go@@ -20,8 +20,8 @@ func Auth(app *app.App, router *gin.RouterGroup) {auth.POST("/logout", utils.WP(authCtrl.Logout))auth.POST("/logout/all", middlewares.Auth(), utils.WP(authCtrl.LogoutAllDevices))- auth.POST("/2fa/request", middlewares.Auth(), utils.WP(authCtrl.RequestTOTPActivation))- auth.POST("/2fa/confirm", middlewares.Auth(), utils.WP(authCtrl.ConfirmTOTPActivation))+ auth.POST("/2fa/request", middlewares.Auth(true), utils.WP(authCtrl.RequestTOTPActivation))+ auth.POST("/2fa/confirm", middlewares.Auth(true), utils.WP(authCtrl.ConfirmTOTPActivation))auth.POST("/2fa/verify", utils.WP(authCtrl.VerifyTOTP))auth.POST("/2fa/disable", middlewares.Auth(), utils.WP(authCtrl.DisableTOTP))diff --git a/backend/services/auth.service.go b/backend/services/auth.service.goindex 04f70a9a..cf0a64a0 100644--- a/backend/services/auth.service.go+++ b/backend/services/auth.service.go@@ -6,9 +6,11 @@ import ("alexandrie/repositories""alexandrie/types""alexandrie/utils"+ "bytes""crypto/rand""errors""fmt"+ "html/template""math/big""os""strconv"@@ -32,6 +34,7 @@ type AuthService interface {RequestPasswordReset(username string, mailClient *mail.Client) errorResetPassword(token, newPassword string) error+ VerifyPreAuth(preAuthToken string) (types.Snowflake, error)VerifyTOTPAndLogin(preAuthToken, code, ip, userAgent string) (*models.User, *models.Session, error)GenerateTOTPSecret(user *models.User) (string, string, error)EnableTOTP(userId types.Snowflake, secret, code string) ([]string, error)@@ -76,7 +79,7 @@ func (s *authService) Login(username, password, ip, userAgent string) (*models.Uif err := bcrypt.CompareHashAndPassword([]byte(*user.Password), []byte(password)); err != nil {return nil, nil, "", errors.New("invalid credentials")}- if user.TotpEnabled {+ if user.TotpEnabled || (user.TOTPForced && !user.TotpEnabled) {user.Password = nilpreAuthToken, err := signPreAuthToken(user.Id)if err != nil {@@ -179,20 +182,63 @@ func (s *authService) RequestPasswordReset(username string, mailClient *mail.Clireturn nil // Don't reveal errors}+ err = sendPasswordResetEmail(mailClient, user, resetToken)+ if err != nil {+ return errors.New("failed to send password reset email")+ }+ return nil+}++type PasswordResetEmailData struct {+ ResetURL string+ FrontendURL string+}++func sendPasswordResetEmail(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/password-reset.html")+ if err != nil {+ return err+ }++ var htmlBody bytes.Buffer++ data := PasswordResetEmailData{+ ResetURL: resetURL,+ 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: Password Reset")- message.SetBodyString(mail.TypeTextPlain, fmt.Sprintf("Your password reset link is: %s", os.Getenv("FRONTEND_URL")+"/login/reset?token="+resetToken))+ message.Subject("Alexandrie: Reset your password")++ message.SetBodyString(+ mail.TypeTextPlain,+ "Your password reset link is: "+resetURL+"\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 nil // Don't reveal errors+ return errors.New("failed to send password reset email")}+return nil}@@ -226,27 +272,35 @@ func (s *authService) ResetPassword(token, newPassword string) error {return s.userRepo.UpdatePassword(user.Id, string(hash))}-func (s *authService) VerifyTOTPAndLogin(preAuthToken, code, ip, userAgent string) (*models.User, *models.Session, error) {-- token, err := jwt.Parse(preAuthToken, func(token *jwt.Token) (interface{}, error) {+func (s *authService) VerifyPreAuth(preAuthToken string) (types.Snowflake, error) {+ token, err := jwt.Parse(preAuthToken, func(token *jwt.Token) (any, error) {return []byte(os.Getenv("JWT_SECRET")), nil})if err != nil || !token.Valid {- return nil, nil, errors.New("invalid or expired pre-authentication token")+ return types.Snowflake(0), errors.New("invalid or expired pre-authentication token")}claims, ok := token.Claims.(jwt.MapClaims)if !ok || claims["pre_auth"] != true {- return nil, nil, errors.New("invalid token type")+ return types.Snowflake(0), errors.New("invalid token type")}- // 2. Extraire le User ID du tokenuserIdStr, _ := claims["sub"].(string)userIdUint, err := strconv.ParseUint(userIdStr, 10, 64)if err != nil {- return nil, nil, errors.New("invalid user ID")+ return types.Snowflake(0), errors.New("invalid user ID")}userId := types.Snowflake(userIdUint)+ return userId, nil+}++func (s *authService) VerifyTOTPAndLogin(preAuthToken, code, ip, userAgent string) (*models.User, *models.Session, error) {++ userId, err := s.VerifyPreAuth(preAuthToken)++ if err != nil {+ return nil, nil, err+ }user, err := s.userRepo.GetByID(userId, true)if user == nil || err != nil {@@ -295,7 +349,6 @@ func (s *authService) GenerateTOTPSecret(user *models.User) (string, string, errfunc generateBackupCodes() ([]string, error) {codes := make([]string, 8)for i := range 8 {- // Génère un nombre aléatoire entre 10000000 et 99999999nBig, err := rand.Int(rand.Reader, big.NewInt(90000000))if err != nil {return nil, err@@ -381,9 +434,9 @@ func signPreAuthToken(userId types.Snowflake) (string, error) {claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{"sub": strconv.FormatUint(uint64(userId), 10),"iss": "alexandrie",- "exp": time.Now().Add(3 * time.Minute).Unix(), // Valide seulement 3 minutes+ "exp": time.Now().Add(3 * time.Minute).Unix(),"iat": time.Now().Unix(),- "pre_auth": true, // Flag crucial pour identifier qu'il ne s'agit pas d'une session finale+ "pre_auth": true,})return claims.SignedString([]byte(os.Getenv("JWT_SECRET")))}diff --git a/backend/services/manager.go b/backend/services/manager.goindex 08bfe448..906bc981 100644--- a/backend/services/manager.go+++ b/backend/services/manager.go@@ -8,6 +8,7 @@ import ("fmt""github.com/minio/minio-go/v7"+ "github.com/wneessen/go-mail")type ServiceManager struct {@@ -26,10 +27,10 @@ type ServiceManager struct {initialized bool}-func NewServiceManager(repos *repositories.RepositoryManager, snowflake *snowflake.Snowflake, minioClient *minio.Client, resourceConfig ResourceConfig) (*ServiceManager, error) {+func NewServiceManager(repos *repositories.RepositoryManager, snowflake *snowflake.Snowflake, minioClient *minio.Client, mailClient *mail.Client, resourceConfig ResourceConfig) (*ServiceManager, error) {sm := &ServiceManager{}- if err := sm.initializeServices(repos, snowflake, minioClient, resourceConfig); err != nil {+ if err := sm.initializeServices(repos, snowflake, minioClient, mailClient, resourceConfig); err != nil {return nil, fmt.Errorf("failed to initialize services: %w", err)}@@ -38,10 +39,10 @@ func NewServiceManager(repos *repositories.RepositoryManager, snowflake *snowflareturn sm, nil}-func (sm *ServiceManager) initializeServices(repos *repositories.RepositoryManager, snowflake *snowflake.Snowflake, minioClient *minio.Client, resourceConfig ResourceConfig) error {+func (sm *ServiceManager) initializeServices(repos *repositories.RepositoryManager, snowflake *snowflake.Snowflake, minioClient *minio.Client, mailClient *mail.Client, resourceConfig ResourceConfig) error {sm.Access = permissions.NewAccessGuard(repos.Node, repos.Permission)sm.Auth = NewAuthService(repos.User, repos.Session, repos.BackupCodes, repos.Log, snowflake)- sm.User = NewUserService(repos.User, repos.Log, snowflake, sm.Access)+ sm.User = NewUserService(repos.User, repos.Log, snowflake, sm.Access, mailClient)sm.Stats = NewStatsService(repos.Stats)sm.Minio = NewMinioService(minioClient)sm.Node = NewNodeService(repos.Node, repos.Permission, sm.Minio, snowflake, sm.Access)diff --git a/backend/services/user.service.go b/backend/services/user.service.goindex c740dc95..0646f0cf 100644--- a/backend/services/user.service.go+++ b/backend/services/user.service.go@@ -8,15 +8,21 @@ import ("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")@@ -25,8 +31,8 @@ type UserService interface {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, password *string) (*models.User, error)- UpdateUser(ctx context.Context, id types.Snowflake, firstname, lastname, avatar, email *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) errorDeleteUser(ctx context.Context, id types.Snowflake, minioService MinioService) errorGenerateUniqueUsername(givenName *string, userID types.Snowflake) string@@ -34,18 +40,20 @@ type UserService interface {}type userService struct {- userRepo repositories.UserRepository- logRepo repositories.LogRepository- snowflake *snowflake.Snowflake- access permissions.AccessGuard+ 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) UserService {+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,+ userRepo: userRepo,+ logRepo: logRepo,+ snowflake: snowflake,+ access: access,+ mailClient: mailClient,}userService.LoadAppAdmins() // On startup, ensure admin users are loaded and updatedreturn userService@@ -83,7 +91,7 @@ func (s *userService) SearchPublicUsers(query string) ([]*models.User, error) {return s.userRepo.SearchPublic(query)}-func (s *userService) CreateUser(username, firstname, lastname, avatar, email string, password *string) (*models.User, error) {+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@@ -92,38 +100,123 @@ func (s *userService) CreateUser(username, firstname, lastname, avatar, email streturn nil, errors.New("username already exists")}- if password == nil || len(*password) == 0 {- return nil, errors.New("password is required")- }-- hash, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost)+ 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 = nilreturn createdUser, nil}-func (s *userService) UpdateUser(ctx context.Context, id types.Snowflake, firstname, lastname, avatar, email *string) (*models.User, error) {+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@@ -137,11 +230,21 @@ func (s *userService) UpdateUser(ctx context.Context, id types.Snowflake, firstnreturn 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,diff --git a/frontend/app/components/AppToggle.vue b/frontend/app/components/AppToggle.vueindex a1b93fe6..3e79e225 100644--- a/frontend/app/components/AppToggle.vue+++ b/frontend/app/components/AppToggle.vue@@ -18,6 +18,15 @@ const toggle = () => {emit('update:modelValue', active.value);emit('toggle');};++watch(+ () => props.modelValue,+ newValue => {+ if (newValue !== undefined) {+ active.value = newValue;+ }+ },+);</script><style scoped lang="scss">diff --git a/frontend/app/pages/dashboard/import/_components/ImportProgress.vue b/frontend/app/components/ImportJob/Status.vuesimilarity index 80%rename from frontend/app/pages/dashboard/import/_components/ImportProgress.vuerename to frontend/app/components/ImportJob/Status.vueindex 4d5cc942..2d53b58c 100644--- a/frontend/app/pages/dashboard/import/_components/ImportProgress.vue+++ b/frontend/app/components/ImportJob/Status.vue@@ -12,20 +12,23 @@<div class="progress-bar" :style="{ width: progress + '%' }"></div></div>- <small v-if="importJob.status === 'failed'">{{ importJob.error_message }} ({{ importJob.failures }} {{ t('common.status.failed') }})</small>+ <!-- eslint-disable-next-line vue/no-v-html -->+ <small v-if="displayErr" v-html="`${importJob.error_message}`"></small>+ <small v-if="importJob.failures > 0">{{ importJob.failures }} {{ t('common.status.failed') }}</small>+ <small v-if="importJob.created.length > 0">{{ importJob.created.length }} {{ t('common.status.completed') }}</small></div></template><script setup lang="ts">import type { ImportJob } from '~/helpers/backups/Importer';-const props = defineProps<{ importJob: ImportJob }>();+const props = defineProps<{ importJob: ImportJob<object, object | null> }>();const { t } = useI18nT();const progress = computed(() =>Math.floor(- ((props.importJob.created.length + props.importJob.updated.length) * 100) /+ ((props.importJob.created.length + props.importJob.updated.length + props.importJob.failures) * 100) /((props.importJob.toCreate.length || 0) + (props.importJob.toUpdate.length || 0)),),);@@ -43,6 +46,8 @@ const statusLabel = computed(() => {return t('common.status.unknown');}});++const displayErr = computed(() => props.importJob.status === 'failed' || props.importJob.error_message);</script><style scoped lang="scss">diff --git a/frontend/app/helpers/backups/Importer.ts b/frontend/app/helpers/backups/Importer.tsindex f73b1562..6fa45815 100644--- a/frontend/app/helpers/backups/Importer.ts+++ b/frontend/app/helpers/backups/Importer.ts@@ -2,15 +2,15 @@ import compile from '~/helpers/markdown';import { extractMetadataFromMarkdown } from '~/helpers/node';import type { DB_Node } from '~/stores';-export interface ImportJob {+export interface ImportJob<T = DB_Node, O = ImportOptions> {status: 'pending' | 'in_progress' | 'completed' | 'failed';- toCreate: DB_Node[];+ toCreate: T[];created: string[];- toUpdate: DB_Node[];+ toUpdate: T[];updated: string[];failures: number;error_message?: string;- options: ImportOptions;+ options: O;}interface ImportOptions {diff --git a/frontend/app/pages/(public)/login/_components/Login2FA.vue b/frontend/app/pages/(public)/login/_components/Login2FA.vuenew file mode 100644index 00000000..17da9f2b--- /dev/null+++ b/frontend/app/pages/(public)/login/_components/Login2FA.vue@@ -0,0 +1,90 @@+<template>+ <div class="ctn">+ <h1>{{ t('public.login.OTP_2FA.title') }}</h1>+ <p class="section-description">{{ t('public.login.OTP_2FA.description') }}</p>+ <form @submit.prevent="handleVerify2FA">+ <div class="form-group">+ <label for="totpCode">{{ t('public.login.OTP_2FA.code') }}</label>+ <input+ id="totpCode"+ v-model="totpCode"+ type="text"+ :placeholder="t('public.login.OTP_2FA.placeholder')"+ maxlength="8"+ pattern="[0-9]*"+ inputmode="numeric"+ autocomplete="one-time-code"+ />+ </div>+ <tag v-if="error" red class="error">{{ error }}</tag>+ <button class="btn" type="submit">{{ t('public.login.OTP_2FA.submit') }}</button>+ </form>+ </div>+</template>++<script setup lang="ts">+const props = defineProps<{+ preAuthToken: string;+}>();++const userStore = useUserStore();++const router = useRouter();+const { t } = useI18nT();++const totpCode = ref('');++const error = ref('');++async function handleVerify2FA() {+ const res = await userStore.verify2FA(props.preAuthToken, totpCode.value);+ if (res.success) router.push('/dashboard');+ else error.value = (res.error as string) || 'Invalid 2FA code';+}+</script>++<style scoped lang="scss">+h1 {+ font-size: 2.5em;+}++.ctn {+ display: flex;+ flex-direction: column;+ justify-content: center;+ align-items: center;+ width: 100%;+}++.btn {+ width: 100%;+ margin-top: 1rem;+ padding: 0.9rem;+ border: none;+ border-radius: var(--radius-lg);+ font-size: 1.1rem;+ font-weight: 600;+ color: white;+ background-color: var(--primary);+ cursor: pointer;+ transition:+ background-color $transition-fast ease,+ transform $transition-fast ease;++ &:hover {+ background: var(--primary-dark);+ transform: translateY(-1px);+ }+}++form {+ width: 100%;+}++.error {+ margin-top: 0.4rem;+ padding: 0.5rem;+ font-size: 0.8rem;+ text-align: center;+}+</style>diff --git a/frontend/app/pages/(public)/login/_components/Login2FAEnable.vue b/frontend/app/pages/(public)/login/_components/Login2FAEnable.vuenew file mode 100644index 00000000..4290f179--- /dev/null+++ b/frontend/app/pages/(public)/login/_components/Login2FAEnable.vue@@ -0,0 +1,118 @@+<template>+ <div class="ctn">+ <h1>{{ t('settings.security.totp.enable') }}</h1>+ <p class="reason">{{ t('settings.security.totp.forced') }}</p>+ <p>{{ t('settings.security.totp.enableStep1') }}</p>++ <div class="qr-container">+ <QrcodeVue :value="totpData.qr_code_url" :size="200" level="H" />+ <code class="secret-text">Secret Key: {{ totpData.secret }}</code>+ </div>++ <p>{{ t('settings.security.totp.enableStep2') }}</p>+ <input v-model="setupCode" type="text" :placeholder="t('public.login.OTP_2FA.placeholder')" maxlength="6" />++ <div class="footer">+ <AppButton type="primary" @click="confirm2FA">{{ t('common.actions.confirm') }}</AppButton>+ </div>++ <tag v-if="setupError" red class="error">{{ setupError }}</tag>+ </div>+</template>++<script setup lang="ts">+import BackupCodes2FA from '~/pages/dashboard/settings/_views/_components/BackupCodes2FA.vue';+import QrcodeVue from 'qrcode.vue';++const props = defineProps<{+ preAuthToken: string;+}>();++const emit = defineEmits<{ (e: '2fa-enabled'): void }>();++const userStore = useUserStore();+const { t } = useI18nT();++const totpData = ref({ secret: '', qr_code_url: '' });+const setupCode = ref('');+const setupError = ref('');++definePageMeta({+ layout: 'public',+});++const modals = useModal();++async function confirm2FA() {+ setupError.value = '';+ try {+ const backupCodes = await userStore.confirm2FA(totpData.value.secret, setupCode.value, props.preAuthToken);+ setupCode.value = '';+ modals.add(new Modal(shallowRef(BackupCodes2FA), { size: 'small', props: { backupCodes }, onClose: () => emit('2fa-enabled') }));+ } catch (err) {+ setupError.value = (err as string) || 'Invalid code. Activation failed.';+ }+}++onMounted(async () => {+ try {+ const data = await userStore.request2FA(props.preAuthToken);+ totpData.value = data!;+ } catch (err) {+ setupError.value = (err as string) || 'An error occurred while initiating 2FA setup.';+ }+});+</script>+<style scoped lang="scss">+h1 {+ font-size: 2.5em;+}++.ctn {+ display: flex;+ flex-direction: column;+ justify-content: center;+ align-items: center;+ width: 100%;+}++p.reason {+ font-size: 0.9rem;+ color: var(--text-muted);+}++.qr-container {+ display: flex;+ flex-direction: column;+ justify-content: center;+ align-items: center;+ gap: 1rem;+ width: fit-content;+ padding: 1.5rem;+ border-radius: var(--radius-md);+ background: white;++ .secret-text {+ padding: 0.4rem 0.75rem;+ border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ font-family: var(--font-mono, monospace);+ font-size: 0.85rem;+ color: #333;+ text-align: center;+ word-break: break-all;+ background: var(--surface-background);+ }+}++.footer {+ margin-top: 1rem;+}++.error {+ margin-top: 0.4rem;+ padding: 0.5rem;+ font-size: 0.8rem;+ text-align: center;+}+</style>diff --git a/frontend/app/pages/(public)/login/_components/LoginBase.vue b/frontend/app/pages/(public)/login/_components/LoginBase.vuenew file mode 100644index 00000000..4e262a47--- /dev/null+++ b/frontend/app/pages/(public)/login/_components/LoginBase.vue@@ -0,0 +1,226 @@+<template>+ <div class="ctn">+ <h1>{{ t('public.login.title') }}</h1>+ <form @submit.prevent="login">+ <div v-if="!hideLoginForm" class="form-group">+ <label for="username">{{ t('public.login.form.username') }}</label>+ <input id="username" v-model="username" type="username" :class="{ 'is-invalid': errors.username }" :disabled="loginDisabled" />+ <p v-if="errors.username" class="invalid-feedback">{{ errors.username }}</p>+ </div>+ <div v-if="!hideLoginForm" class="form-group">+ <label for="password">{{ t('public.login.form.password') }}</label>+ <div class="password-input">+ <input+ id="password"+ :key="`password-${showPassword}`"+ v-model="password"+ :type="showPassword ? 'text' : 'password'"+ :class="{ 'is-invalid': errors.password }"+ :disabled="loginDisabled"+ />+ <button type="button" class="password-toggle" @click="togglePassword">+ <div class="eye-icon" :class="{ show: showPassword }">+ <Icon v-if="showPassword" name="eye" />+ <Icon v-else name="eye_off" />+ </div>+ </button>+ </div>+ <p v-if="errors.password" class="invalid-feedback">{{ errors.password }}</p>+ </div>+ <NuxtLinkLocale to="/signup" class="signup-link">{{ t('public.login.needAccount') }}</NuxtLinkLocale>+ <button v-if="!hideLoginForm" class="btn" :disabled="loginDisabled">{{ t('public.login.form.submit') }}</button>+ <p v-if="loginDisabled" class="disabled">{{ t('public.login.disabled') }}</p>+ <OIDCProviders />++ <p class="forgot-password-link">+ {{ t('public.login.forgotPassword') }} <NuxtLinkLocale to="/login/request-reset">{{ t('public.login.clickHere') }}</NuxtLinkLocale>+ </p>+ </form>+ </div>+</template>++<script setup lang="ts">+const { t } = useI18nT();++const username = ref('');+const password = ref('');++const emit = defineEmits<{ (e: 'login', payload: { username: string; password: string }): void }>();++const config = useRuntimeConfig();+const loginDisabled = config.public.configDisableNativeLogin;+const hideLoginForm = config.public.configHideLoginForm;++const errors = ref({ username: '', password: '', general: '' });+const { showPassword, togglePassword } = usePasswordField();++function login() {+ errors.value.username = !username.value ? 'Username is required' : '';+ errors.value.password = !password.value ? 'Password is required' : '';++ if (username.value && password.value) emit('login', { username: username.value, password: password.value });+}++watch([username, password], () => {+ errors.value.username = '';+ errors.value.password = '';+});+</script>+<style scoped lang="scss">+h1 {+ font-size: 2.5em;+}++.ctn {+ display: flex;+ flex-direction: column;+ justify-content: center;+ align-items: center;+ width: 100%;+}++form {+ width: 100%;+}++.form-group {+ margin-bottom: 0.8rem;+}++input {+ padding: 0.6rem;++ &:disabled {+ background: var(--surface-transparent);+ cursor: not-allowed;+ }+}++/* ===== Password ===== */+.password-input {+ position: relative;+}++.password-toggle {+ position: absolute;+ top: 50%;+ right: 8px;+ display: flex;+ justify-content: center;+ align-items: center;+ padding: 8px;+ border: none;+ border-radius: 50%;+ background: transparent;+ cursor: pointer;+ transition:+ background-color $transition-fast ease,+ transform $transition-fast ease;+ transform: translateY(-50%);++ &:hover {+ background: var(--surface-transparent);+ }++ &:active {+ transform: translateY(-50%) scale(0.95);+ }+}++.disabled {+ margin-top: 0.5rem;+ font-size: 0.9rem;+ color: var(--text-muted);+ text-align: center;+}++.eye-icon {+ display: flex;+ justify-content: center;+ align-items: center;+ width: 20px;+ height: 20px;+ transition: transform $transition-medium ease;++ &.show {+ transform: scale(1.1);+ }+}++/* ===== Links ===== */+.signup-link {+ display: block;+ margin-bottom: 1rem;+ font-weight: 500;+ color: var(--primary);+ text-align: center;+ text-decoration: none;+ transition: color $transition-fast ease;++ &:hover {+ color: var(--primary-dark);+ text-decoration: underline;+ }+}++.forgot-password-link {+ margin-top: 1rem;+ font-size: 16px;+ font-weight: 500;+ text-align: center;++ a {+ font-weight: 600;+ color: var(--primary);+ transition: color $transition-fast ease;++ &:hover {+ color: var(--primary-dark);+ text-decoration: underline;+ }+ }+}++/* ===== Buttons ===== */+.btn {+ width: 100%;+ margin-top: 1rem;+ padding: 0.9rem;+ border: none;+ border-radius: var(--radius-lg);+ font-size: 1.1rem;+ font-weight: 600;+ color: white;+ background-color: var(--primary);+ cursor: pointer;+ transition:+ background-color $transition-fast ease,+ transform $transition-fast ease;++ &:hover {+ background: var(--primary-dark);+ transform: translateY(-1px);+ }++ &:active {+ transform: translateY(0);+ }++ &:disabled {+ cursor: not-allowed;+ transform: none;+ }+}++/* ===== States and messages ===== */+.is-invalid {+ border-color: var(--red) !important;+}++.invalid-feedback {+ margin: 0;+ font-size: 0.8rem;+ color: var(--red);+ text-align: center;+}+</style>diff --git a/frontend/app/pages/(public)/login/index.vue b/frontend/app/pages/(public)/login/index.vueindex 6051c85d..d2b5d9f2 100644--- a/frontend/app/pages/(public)/login/index.vue+++ b/frontend/app/pages/(public)/login/index.vue@@ -2,82 +2,26 @@<div class="body-container"><IconApp style="width: 120px" />- <template v-if="!step2FA">- <h1>{{ t('public.login.title') }}</h1>- <form @submit.prevent="login">- <div v-if="!hideLoginForm" class="form-group">- <label for="username">{{ t('public.login.form.username') }}</label>- <input id="username" v-model="username" type="username" :class="{ 'is-invalid': errors.username }" :disabled="loginDisabled" />- <p v-if="errors.username" class="invalid-feedback">{{ errors.username }}</p>- </div>- <div v-if="!hideLoginForm" class="form-group">- <label for="password">{{ t('public.login.form.password') }}</label>- <div class="password-input">- <input- id="password"- :key="`password-${showPassword}`"- v-model="password"- :type="showPassword ? 'text' : 'password'"- :class="{ 'is-invalid': errors.password }"- :disabled="loginDisabled"- />- <button type="button" class="password-toggle" @click="togglePassword">- <div class="eye-icon" :class="{ show: showPassword }">- <Icon v-if="showPassword" name="eye" />- <Icon v-else name="eye_off" />- </div>- </button>- </div>- <p v-if="errors.password" class="invalid-feedback">{{ errors.password }}</p>- </div>- <NuxtLinkLocale to="/signup" class="signup-link">{{ t('public.login.needAccount') }}</NuxtLinkLocale>- <button v-if="!hideLoginForm" class="btn" :disabled="loginDisabled">{{ t('public.login.form.submit') }}</button>- <p v-if="loginDisabled" class="disabled">{{ t('public.login.disabled') }}</p>- <OIDCProviders />+ <LoginBase v-if="step === 0" @login="connect" />- <p v-if="errors.general" class="invalid-feedback general">{{ errors.general }}</p>- <p class="forgot-password-link">- {{ t('public.login.forgotPassword') }} <NuxtLinkLocale to="/login/request-reset">{{ t('public.login.clickHere') }}</NuxtLinkLocale>- </p>- </form>- </template>+ <Login2FA v-else-if="step === 1" :pre-auth-token="pendingPreAuthToken" />- <template v-else>- <h1>{{ t('public.login.OTP_2FA.title') }}</h1>- <p class="section-description">{{ t('public.login.OTP_2FA.description') }}</p>- <form @submit.prevent="handleVerify2FA">- <div class="form-group">- <label for="totpCode">{{ t('public.login.OTP_2FA.code') }}</label>- <input- id="totpCode"- v-model="totpCode"- type="text"- placeholder="000000 or 8-digit backup code"- maxlength="8"- pattern="[0-9]*"- inputmode="numeric"- autocomplete="one-time-code"- :disabled="loginDisabled"- />- </div>- <p v-if="errors.general" class="invalid-feedback">{{ errors.general }}</p>- <button class="btn" :disabled="loginDisabled" type="submit">{{ t('public.login.OTP_2FA.submit') }}</button>- <button class="btn-secondary" type="button" @click="step2FA = false">{{ t('public.login.OTP_2FA.back') }}</button>- </form>- </template>+ <Login2FAEnable v-else-if="step === 2" :pre-auth-token="pendingPreAuthToken" @2fa-enabled="() => (step = 0)" />++ <tag v-if="error" red class="error">{{ error }}</tag></div></template><script setup lang="ts">+import LoginBase from './_components/LoginBase.vue';+import Login2FA from './_components/Login2FA.vue';+import Login2FAEnable from './_components/Login2FAEnable.vue';+const userStore = useUserStore();const router = useRouter();-const { t } = useI18nT();-const username = ref('');-const password = ref('');-const totpCode = ref('');+const step = ref(0); // 0 = login, 1 = 2FA, 2 = enable 2FA-const step2FA = ref(false);const pendingPreAuthToken = ref('');definePageMeta({@@ -85,18 +29,14 @@ definePageMeta({});const route = useRoute();-const config = useRuntimeConfig();-const loginDisabled = config.public.configDisableNativeLogin;-const hideLoginForm = config.public.configHideLoginForm;-const errors = ref({ username: '', password: '', general: '' });-const { showPassword, togglePassword } = usePasswordField();+const error = ref('');// Check for OIDC error redirectonMounted(() => {const errorParam = route.query.error as string | undefined;if (errorParam) {- errors.value.general = formatOIDCError(errorParam);+ error.value = formatOIDCError(errorParam);}});@@ -115,43 +55,25 @@ function formatOIDCError(error: string): string {return errorMessages[error] || `Error: ${error}`;}-function login() {- errors.value.username = !username.value ? 'Username is required' : '';- errors.value.password = !password.value ? 'Password is required' : '';-- if (username.value && password.value) {- connect();+async function connect(payload: { username: string; password: string }) {+ error.value = '';+ const res = await userStore.login(payload.username, payload.password);+ if (!res.success) {+ error.value = (res.error as string) || 'Invalid credentials';+ return;}-}--watch([username, password, totpCode], () => {- errors.value.general = '';- errors.value.username = '';- errors.value.password = '';-});--async function connect() {- const res = await userStore.login(username.value, password.value);- if (res.success) {- if (res.require2FA) {- pendingPreAuthToken.value = res.preAuthToken!;- step2FA.value = true;- } else {- router.push('/dashboard');- }+ if (res.require2FA) {+ pendingPreAuthToken.value = res.preAuthToken!;+ step.value = 1;+ } else if (res.require2FAEnable) {+ step.value = 2;+ pendingPreAuthToken.value = res.preAuthToken!;} else {- errors.value.general = (res.error as string) || 'Invalid credentials';- }-}--async function handleVerify2FA() {- const res = await userStore.verify2FA(pendingPreAuthToken.value, totpCode.value);- if (res.success) {router.push('/dashboard');- } else {- errors.value.general = (res.error as string) || 'Invalid 2FA code';}}++watch(step, () => (error.value = ''));</script><style scoped lang="scss">.body-container {@@ -164,158 +86,11 @@ async function handleVerify2FA() {margin: 0 auto;}-h1 {- font-size: 2.5em;-}--/* ===== Form ===== */-form {+.error {width: 100%;-}--.form-group {- margin-bottom: 0.8rem;-}--input {- padding: 0.6rem;-- &:disabled {- background: var(--surface-transparent);- cursor: not-allowed;- }-}--/* ===== Password ===== */-.password-input {- position: relative;-}--.password-toggle {- position: absolute;- top: 50%;- right: 8px;- display: flex;- justify-content: center;- align-items: center;- padding: 8px;- border: none;- border-radius: 50%;- background: transparent;- cursor: pointer;- transition:- background-color $transition-fast ease,- transform $transition-fast ease;- transform: translateY(-50%);-- &:hover {- background: var(--surface-transparent);- }-- &:active {- transform: translateY(-50%) scale(0.95);- }-}--.disabled {- margin-top: 0.5rem;- font-size: 0.9rem;- color: var(--text-muted);- text-align: center;-}--.eye-icon {- display: flex;- justify-content: center;- align-items: center;- width: 20px;- height: 20px;- transition: transform $transition-medium ease;-- &.show {- transform: scale(1.1);- }-}--/* ===== Links ===== */-.signup-link {- display: block;- margin-bottom: 1rem;- font-weight: 500;- color: var(--primary);- text-align: center;- text-decoration: none;- transition: color $transition-fast ease;-- &:hover {- color: var(--primary-dark);- text-decoration: underline;- }-}--.forgot-password-link {- margin-top: 1rem;- font-size: 16px;- font-weight: 500;- text-align: center;-- a {- font-weight: 600;- color: var(--primary);- transition: color $transition-fast ease;-- &:hover {- color: var(--primary-dark);- text-decoration: underline;- }- }-}--/* ===== Buttons ===== */-.btn {- width: 100%;- margin-top: 1rem;- padding: 0.9rem;- border: none;- border-radius: var(--radius-lg);- font-size: 1.1rem;- font-weight: 600;- color: white;- background-color: var(--primary);- cursor: pointer;- transition:- background-color $transition-fast ease,- transform $transition-fast ease;-- &:hover {- background: var(--primary-dark);- transform: translateY(-1px);- }-- &:active {- transform: translateY(0);- }-- &:disabled {- cursor: not-allowed;- transform: none;- }-}--/* ===== States and messages ===== */-.is-invalid {- border-color: var(--red) !important;-}--.invalid-feedback {- margin: 0;+ margin-top: 0.4rem;+ padding: 0.5rem;font-size: 0.8rem;- color: var(--red);text-align: center;-- &.general {- margin-top: 1rem;- font-size: 0.9rem;- }}</style>diff --git a/frontend/app/pages/(public)/signup.vue b/frontend/app/pages/(public)/signup.vueindex a2449a6f..d3c614ef 100644--- a/frontend/app/pages/(public)/signup.vue+++ b/frontend/app/pages/(public)/signup.vue@@ -107,7 +107,7 @@ watch([username, email, password, confirmPassword], () => {async function createAccount(username: string, email: string, password: string) {userStore- .register({ username, email: email || undefined, password, role: 1, totp_enabled: false })+ .register({ username, email: email || undefined, password, totp_forced: false, type: 0 }).then(() => {router.push('/login');})diff --git a/frontend/app/pages/dashboard/admin.vue b/frontend/app/pages/dashboard/admin.vueindex 72e2c921..e9bb7eb6 100644--- a/frontend/app/pages/dashboard/admin.vue+++ b/frontend/app/pages/dashboard/admin.vue@@ -4,4 +4,7 @@<script setup lang="ts">definePageMeta({ breadcrumb: { i18n: 'admin.dashboard.title' } });++const store = useAdminStore();+void store.fetchAll();</script>diff --git a/frontend/app/pages/dashboard/admin/_modals/UserCreation.vue b/frontend/app/pages/dashboard/admin/_modals/UserCreation.vuenew file mode 100644index 00000000..a3cc60ff--- /dev/null+++ b/frontend/app/pages/dashboard/admin/_modals/UserCreation.vue@@ -0,0 +1,288 @@+<template>+ <div class="modal-content">+ <header>+ <div>+ <h2>Create users</h2>+ <p>Add people one at a time or import a CSV file, then review the same import list before creating accounts.</p>+ </div>+ </header>++ <form class="manual-form" @submit.prevent>+ <h3>Add a user</h3>+ <div class="fields">+ <div class="field">+ <label>Username <span class="required">*</span></label>+ <input v-model.trim="manualUser.username" autocomplete="off" placeholder="jdoe" />+ </div>+ <div class="field">+ <label>Email <span class="required">*</span></label>+ <input v-model.trim="manualUser.email" type="email" autocomplete="email" placeholder="[email protected]" />+ </div>+ <div class="field">+ <label>First name</label>+ <input v-model.trim="manualUser.firstname" autocomplete="given-name" placeholder="Jane" />+ </div>+ <div class="field">+ <label>Last name</label>+ <input v-model.trim="manualUser.lastname" autocomplete="family-name" placeholder="Doe" />+ </div>+ </div>+ <div class="manual-actions">+ <div class="actions-row">+ <AppToggle v-model="manualUser.totp_forced" />+ <label class="toggle-row">+ <span><strong>Require two-factor authentication</strong><small>The user will need to set up TOTP.</small></span>+ </label>+ </div>+ <AppButton type="secondary" @click="addManualUser"><Icon name="plus" /> Add to import list</AppButton>+ </div>+ <tag v-if="manuelUserError" red>{{ manuelUserError }}</tag>+ </form>++ <section class="import-section" aria-labelledby="csv-title">+ <div class="section-heading">+ <div>+ <h3 id="csv-title">Import list</h3>+ <p>Upload a CSV file or edit the list directly. The first row must contain the column names.</p>+ </div>+ <label class="upload-button"><Icon name="import" /> Import CSV<input type="file" accept=".csv,text/csv" @change="importCsvFile" /></label>+ </div>+ <p class="csv-format"><code>username,email,firstname,lastname,totp_forced</code></p>+ <textarea v-model="csvContent" aria-label="Users CSV import list" spellcheck="false" />+ <tag v-if="parseErrors.length" red>{{ parseErrors[0] }}</tag>+ <p v-else class="queue-count">{{ parsedUsers.length }} {{ parsedUsers.length === 1 ? 'user' : 'users' }} ready to import</p>+ </section>+ <div class="progress">+ <ImportJobStatus :import-job="job" />+ </div>+ <footer>+ <AppButton type="primary" :disabled="!parsedUsers.length || parseErrors.length > 0" @click="importAll">Import All ({{ parsedUsers.length }})</AppButton>+ </footer>+ </div>+</template>++<script setup lang="ts">+import type { ImportJob } from '~/helpers/backups/Importer';+import type { UserToCreateBulk } from '~/stores';++const users = useUserStore();++const CSV_HEADERS = ['username', 'email', 'firstname', 'lastname', 'totp_forced'] as const;+const csvContent = ref(CSV_HEADERS.join(','));+const manualUser = reactive<UserToCreateBulk>({ username: '', email: '', firstname: '', lastname: '', totp_forced: false, type: 1 });+const manuelUserError = ref('');+const parsedResult = computed(() => parseUsersCsv(csvContent.value));+const parsedUsers = computed(() => parsedResult.value.users);+const parseErrors = computed(() => parsedResult.value.errors);++const job: ImportJob<UserToCreateBulk, null> = reactive({+ status: 'pending',+ toCreate: [],+ toUpdate: [],+ created: [],+ updated: [],+ failures: 0,+ error_message: '',+ options: null,+});++function addManualUser() {+ manuelUserError.value = '';+ if (!manualUser.username) return (manuelUserError.value = 'Username is required.');+ if (!manualUser.email) return (manuelUserError.value = 'Email is required.');+ const row = [manualUser.username, manualUser.email, manualUser.firstname, manualUser.lastname, String(Boolean(manualUser.totp_forced))]+ .map(value => escapeCsvValue(value ?? ''))+ .join(',');+ csvContent.value = `${csvContent.value.trimEnd()}\n${row}`;+ Object.assign(manualUser, { username: '', email: '', firstname: '', lastname: '', totp_forced: manualUser.totp_forced });+}++async function importCsvFile(event: Event) {+ const input = event.target as HTMLInputElement;+ const file = input.files?.[0];+ if (!file) return;+ csvContent.value = await file.text();+ input.value = '';+}++async function importAll() {+ job.toCreate = parsedUsers.value;+ await users.bulkRegister(job);+}++function parseUsersCsv(content: string): { users: UserToCreateBulk[]; errors: string[] } {+ const rows = parseCsv(content);+ if (!rows.length) return { users: [], errors: [] };+ const headers = rows[0]!.map(header => header.trim().toLowerCase());+ const missingHeaders = CSV_HEADERS.filter(header => !headers.includes(header));+ if (missingHeaders.length) return { users: [], errors: [`Missing CSV column${missingHeaders.length > 1 ? 's' : ''}: ${missingHeaders.join(', ')}.`] };++ const positions = Object.fromEntries(CSV_HEADERS.map(header => [header, headers.indexOf(header)])) as Record<(typeof CSV_HEADERS)[number], number>;+ const users: UserToCreateBulk[] = [];+ const errors: string[] = [];+ rows.slice(1).forEach((row, index) => {+ if (row.every(value => !value.trim())) return;+ const username = row[positions.username]?.trim();+ const rawTotp = row[positions.totp_forced]?.trim().toLowerCase();+ if (!username) return void errors.push(`Line ${index + 2}: username is required.`);+ if (rawTotp && !['true', 'false', '1', '0', 'yes', 'no'].includes(rawTotp))+ return void errors.push(`Line ${index + 2}: totp_forced must be true or false.`);+ users.push({+ username,+ email: optionalValue(row[positions.email]),+ firstname: optionalValue(row[positions.firstname]),+ lastname: optionalValue(row[positions.lastname]),+ totp_forced: ['true', '1', 'yes'].includes(rawTotp || ''),+ type: 1,+ });+ });+ return { users, errors };+}++function optionalValue(value?: string): string | undefined {+ const trimmed = value?.trim();+ return trimmed || undefined;+}++function escapeCsvValue(value: string): string {+ return /[",\n]/.test(value) ? `"${value.replaceAll('"', '""')}"` : value;+}++function parseCsv(content: string): string[][] {+ const rows: string[][] = [];+ let row: string[] = [];+ let value = '';+ let quoted = false;+ for (let index = 0; index < content.length; index += 1) {+ const character = content[index];+ if (character === '"') {+ if (quoted && content[index + 1] === '"') {+ value += '"';+ index += 1;+ } else quoted = !quoted;+ } else if (character === ',' && !quoted) {+ row.push(value);+ value = '';+ } else if ((character === '\n' || character === '\r') && !quoted) {+ if (character === '\r' && content[index + 1] === '\n') index += 1;+ row.push(value);+ rows.push(row);+ row = [];+ value = '';+ } else value += character;+ }+ if (value || row.length) rows.push([...row, value]);+ return rows;+}+</script>++<style scoped lang="scss">+.modal-content {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+ font-family: $font-ui;+}++header p,+.section-heading p,+.queue-count,+.toggle-row small {+ font-size: 0.88rem;+ color: var(--text-muted);+}++.manual-form,+.import-section {+ display: flex;+ flex-direction: column;+ gap: 0.8rem;+ padding: 1rem;+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+}++.fields {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 0.75rem;+}++.required {+ color: var(--red);+}++.manual-actions,+.section-heading,+footer {+ display: flex;+ justify-content: space-between;+ align-items: center;+ gap: 1rem;+}++.toggle-row {+ flex-direction: row;+ align-items: center;+}++.toggle-row span {+ display: flex;+ flex-direction: column;+}++.upload-button {+ display: flex;+ flex-direction: row;+ align-items: center;+ gap: 0.5rem;+ padding: 8px;+ border: 1px solid var(--primary);+ border-radius: var(--radius-sm);+ cursor: pointer;+}++.upload-button input {+ display: none;+}++.csv-format {+ margin: 0;+}++textarea {+ box-sizing: border-box;+ min-height: 150px;+ padding: 0.65rem;+ font-family: monospace;+ font-size: 0.82rem;+ line-height: 1.45;+ resize: vertical;+}++.queue-count {+ min-height: 1.25rem;+}++footer {+ justify-content: flex-end;+}++.progress {+ padding: 0.75rem 1rem;+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+}++@media screen and (width <= 560px) {+ .fields {+ grid-template-columns: 1fr;+ }++ .manual-actions,+ .section-heading {+ flex-direction: column;+ align-items: flex-start;+ }+}+</style>diff --git a/frontend/app/pages/dashboard/admin/index.vue b/frontend/app/pages/dashboard/admin/index.vueindex f12e076f..c145a365 100644--- a/frontend/app/pages/dashboard/admin/index.vue+++ b/frontend/app/pages/dashboard/admin/index.vue@@ -5,7 +5,6 @@<h1>{{ t('admin.dashboard.title') }}</h1><p>{{ t('admin.dashboard.description') }}</p></div>- <AppButton type="primary" @click="router.push('/dashboard/admin/users')">{{ t('admin.dashboard.manageUsers') }}</AppButton></header><div v-if="store.loadingStats" class="stats-loading">@@ -53,6 +52,17 @@</article></section>+ <section class="actions">+ <article class="action-card">+ <h2>{{ t('admin.dashboard.manageUsers') }}</h2>++ <div class="actions-row">+ <AppButton type="primary" @click="router.push('/dashboard/admin/users')">{{ t('admin.dashboard.manageUsers') }}</AppButton>+ <AppButton type="secondary" @click="openCreateModal">Create Users</AppButton>+ </div>+ </article>+ </section>+<section class="top-grid"><article class="top-card"><h2>{{ t('admin.dashboard.top.byNodes') }}</h2>@@ -104,14 +114,15 @@<script setup lang="ts">import { readableFileSize } from '~/helpers/resources';+import UserCreation from './_modals/UserCreation.vue';import type { MonthlyCount } from '~/stores';const router = useRouter();const { t } = useI18nT();const store = useAdminStore();+const modals = useModal();-void store.fetchAll();void store.fetchStats().catch(() => undefined);const usersPoints = computed(() => toPolyline(store.stats.users.growth_last_12_months));@@ -140,6 +151,14 @@ function toPolyline(series: MonthlyCount[]): string {}).join(' ');}++const openCreateModal = () => {+ modals.add(+ new Modal(shallowRef(UserCreation), {+ size: 'medium',+ }),+ );+};</script><style scoped lang="scss">@@ -208,6 +227,19 @@ a:hover {font-weight: 700;}+.actions {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: 1rem;+}++.action-card {+ padding: 1rem;+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+ background: radial-gradient(circle at top right, color-mix(in srgb, var(--primary) 11%, transparent), transparent 54%), var(--background-100);+}+.sparkline {width: 100%;height: 120px;diff --git a/frontend/app/pages/dashboard/admin/users/[id]/index.vue b/frontend/app/pages/dashboard/admin/users/[id]/index.vueindex 82c2f026..87589eb3 100644--- a/frontend/app/pages/dashboard/admin/users/[id]/index.vue+++ b/frontend/app/pages/dashboard/admin/users/[id]/index.vue@@ -26,6 +26,19 @@<option :value="2">Admin</option></select></div>+ <div class="user-detail">+ <label for="role">Account Type</label>+ <select id="role" v-model="user.type">+ <option :value="0">Normal</option>+ <option :value="1">Supervised</option>+ </select>+ </div>+ <div class="actions-row">+ <label class="toggle-row">+ <span><strong>Require two-factor authentication</strong><small>The user will need to set up TOTP.</small></span>+ </label>+ <AppToggle v-model="user.totp_forced" />+ </div><div class="container"><div class="user-detail"><label>Created At</label>@@ -95,13 +108,19 @@ const saveChanges = async () => {width: 100%;}+.toggle-row {+ flex-direction: row;+ align-items: center;+}++.toggle-row span {+ display: flex;+ flex-direction: column;+}+.avatar {width: 40px;height: 40px;border-radius: 50%;}--label {- font-weight: bold;-}</style>diff --git a/frontend/app/pages/dashboard/admin/users/index.vue b/frontend/app/pages/dashboard/admin/users/index.vueindex 68273510..7eaa0480 100644--- a/frontend/app/pages/dashboard/admin/users/index.vue+++ b/frontend/app/pages/dashboard/admin/users/index.vue@@ -4,6 +4,7 @@<h1>{{ t('admin.users.title') }}</h1></header><DataTable v-if="rows?.length" :headers="headers" :rows="rows || []">+ <template #username="{ cell }"> <UserAvatar :user="cell?.data as User" /> {{ (cell?.data as User).username }} </template><template #action="{ cell }"><NuxtLink :to="`/dashboard/admin/users/${(cell?.data as User).id}`"><Icon name="view" /></NuxtLink></template>@@ -18,7 +19,6 @@ import type { User } from '~/stores';const adminStore = useAdminStore();const { t } = useI18nT();-const { avatarURL } = useApi();const { numericDate } = useDateFormatters();const headers = computed(() => [@@ -35,8 +35,8 @@ const rows = computed(() =>adminStore.users?.map(u => {return {username: {- content: `<img style="border-radius:50%;width:25px;height:25px;" src="${avatarURL(u)}"/> ${u.username}`,- type: 'html' as const,+ type: 'slot' as const,+ data: u,},firstname: { content: u.firstname, type: 'text' as const },lastname: { content: u.lastname, type: 'text' as const },diff --git a/frontend/app/pages/dashboard/import/_components/ImportSummary.vue b/frontend/app/pages/dashboard/import/_components/ImportSummary.vueindex 8cb4eaa8..64a8e873 100644--- a/frontend/app/pages/dashboard/import/_components/ImportSummary.vue+++ b/frontend/app/pages/dashboard/import/_components/ImportSummary.vue@@ -19,13 +19,12 @@</div></div><div class="progess">- <ImportProgress :import-job="importJob" />+ <ImportJobStatus :import-job="importJob" /></div></div></template><script setup lang="ts">-import ImportProgress from './ImportProgress.vue';import type { ImportJob } from '~/helpers/backups/Importer';defineProps<{diff --git a/frontend/app/pages/dashboard/import/advanced.vue b/frontend/app/pages/dashboard/import/advanced.vueindex aebb53dc..3415056d 100644--- a/frontend/app/pages/dashboard/import/advanced.vue+++ b/frontend/app/pages/dashboard/import/advanced.vue@@ -66,7 +66,7 @@<AppSelect id="default-theme" v-model="importJob.options.defaultValues!.defaultTheme" :items="DOCUMENT_THEMES" /></div><h3>{{ t('import.progress.title') }}</h3>- <ImportProgress :import-job="importJob" />+ <ImportJobStatus :import-job="importJob" /><section v-if="nodes.length" class="panel"><div class="panel-head"><h3>{{ t('import.files.toImport') }} ({{ totalItemsToImport }})</h3>@@ -102,7 +102,6 @@</div></template><script setup lang="ts">-import ImportProgress from './_components/ImportProgress.vue';import { Importer, type ResourceImportTask, type ImportJob } from '~/helpers/backups/Importer';import { DOCUMENT_THEMES } from '~/helpers/constants';import type { DB_Node } from '~/stores';diff --git a/frontend/app/pages/dashboard/import/files.vue b/frontend/app/pages/dashboard/import/files.vueindex f6fdf178..49847301 100644--- a/frontend/app/pages/dashboard/import/files.vue+++ b/frontend/app/pages/dashboard/import/files.vue@@ -20,7 +20,7 @@</AppButton></div></div>- <ImportProgress :import-job="importJob" />+ <ImportJobStatus :import-job="importJob" /><div class="list"><NodeImportPreviewv-for="node in nodes"@@ -37,7 +37,6 @@</template><script setup lang="ts">-import ImportProgress from './_components/ImportProgress.vue';import { Importer, type ImportJob } from '~/helpers/backups/Importer';import type { DB_Node } from '~/stores';diff --git a/frontend/app/pages/dashboard/settings/_views/_components/BackupCodes2FA.vue b/frontend/app/pages/dashboard/settings/_views/_components/BackupCodes2FA.vueindex a306cbd6..7d266b44 100644--- a/frontend/app/pages/dashboard/settings/_views/_components/BackupCodes2FA.vue+++ b/frontend/app/pages/dashboard/settings/_views/_components/BackupCodes2FA.vue@@ -1,11 +1,11 @@<template><div class="modal">- <h2>Backup Recovery Codes</h2>+ <h2>{{ t('settings.security.totp.backupCodes.title') }}</h2><div class="warning-box"><p>- <strong>Keep these codes safe!</strong>- If you lose your 2FA device, these codes are the only way to recover your account. Each code can only be used once.+ <strong>{{ t('settings.security.totp.backupCodes.warn') }}</strong>+ {{ t('settings.security.totp.backupCodes.description') }}</p></div>@@ -19,27 +19,22 @@<button class="btn-copy" type="button" @click="copyAllCodes"><Icon :name="copied ? 'check' : 'copy'" display="sm" />- <span>{{ copied ? 'Codes copied!' : 'Copy all codes' }}</span>+ <span>{{ copied ? t('settings.security.totp.backupCodes.copied') : t('settings.security.totp.backupCodes.copy') }}</span></button></div><div class="footer">- <AppButton type="secondary" @click="downloadCodes"> Download text file </AppButton>- <AppButton type="primary" @click="emit('close')"> I have saved these codes </AppButton>+ <AppButton type="secondary" @click="downloadCodes"> {{ t('settings.security.totp.backupCodes.download') }} </AppButton>+ <AppButton type="primary" @click="emit('close')"> {{ t('settings.security.totp.backupCodes.seen') }} </AppButton></div></div></template><script setup lang="ts">-import { ref } from 'vue';+const props = defineProps<{ backupCodes: string[] }>();+const emit = defineEmits<{ (event: 'close'): void }>();-const props = defineProps<{- backupCodes: string[];-}>();--const emit = defineEmits<{- (event: 'close'): void;-}>();+const { t } = useI18nT();const copied = ref(false);diff --git a/frontend/app/pages/dashboard/settings/_views/_components/SecuritySection2FA.vue b/frontend/app/pages/dashboard/settings/_views/_components/SecuritySection2FA.vueindex 7aad80d2..bf1bfe76 100644--- a/frontend/app/pages/dashboard/settings/_views/_components/SecuritySection2FA.vue+++ b/frontend/app/pages/dashboard/settings/_views/_components/SecuritySection2FA.vue@@ -2,34 +2,36 @@<section><header><div>- <h3>Two-Factor Authentication (2FA)<tag blue>New</tag></h3>- <p class="section-description">Secure your account by requiring a 6-digit code during login.</p>+ <h3>+ {{ t('settings.security.totp.title') }} <tag blue>{{ t('common.actions.new') }}</tag>+ </h3>+ <p class="section-description">{{ t('settings.security.totp.description') }}</p></div><div v-if="userStore.user?.totp_enabled">- <AppButton type="danger" @click="disable2FA"> Disable 2FA </AppButton>+ <AppButton type="danger" @click="disable2FA"> {{ t('settings.security.totp.disable') }} </AppButton></div><div v-else-if="!setupMode">- <AppButton type="primary" @click="start2FASetup">Enable 2FA</AppButton>+ <AppButton type="primary" @click="start2FASetup"> {{ t('settings.security.totp.enable') }} </AppButton></div></header>- <p v-if="userStore.user?.totp_enabled" class="enabled">2FA is currently <strong>enabled</strong> on your account.</p>+ <p v-if="userStore.user?.totp_enabled" class="enabled">{{ t('settings.security.totp.stateEnabled') }}</p><div v-if="setupMode" class="setup-wizard">- <p>1. Scan this QR code with your Authenticator application (Google Authenticator, Bitwarden, etc.) :</p>+ <p>{{ t('settings.security.totp.enableStep1') }}</p><div class="qr-container"><QrcodeVue :value="totpData.qr_code_url" :size="200" level="H" /><code class="secret-text">Secret Key: {{ totpData.secret }}</code></div>- <p>2. Enter the verification code generated by your app to finalize activation :</p>- <input v-model="setupCode" type="text" placeholder="000000" maxlength="6" />+ <p>{{ t('settings.security.totp.enableStep2') }}</p>+ <input v-model="setupCode" type="text" :placeholder="t('public.login.OTP_2FA.placeholder')" maxlength="6" /><div class="footer">- <AppButton type="secondary" @click="setupMode = false">Cancel</AppButton>- <AppButton type="primary" @click="confirm2FA">Confirm Activation</AppButton>+ <AppButton type="secondary" @click="setupMode = false">{{ t('common.actions.cancel') }}</AppButton>+ <AppButton type="primary" @click="confirm2FA">{{ t('common.actions.confirm') }}</AppButton></div><p v-if="setupError" class="error">{{ setupError }}</p>@@ -45,6 +47,7 @@ import BackupCodes2FA from './BackupCodes2FA.vue';const userStore = useUserStore();const modals = useModal();+const { t } = useI18nT();const setupMode = ref(false);const setupCode = ref('');@@ -58,7 +61,7 @@ async function start2FASetup() {totpData.value = data!;setupMode.value = true;} catch (err) {- setupError.value = (err as string) || "Impossible d'initier la configuration 2FA";+ setupError.value = (err as string) || 'Failed to initiate 2FA setup';}}@@ -70,7 +73,7 @@ async function confirm2FA() {setupCode.value = '';modals.add(new Modal(shallowRef(BackupCodes2FA), { size: 'small', props: { backupCodes } }));} catch (err) {- setupError.value = (err as string) || "Code invalide. L'activation a échoué.";+ setupError.value = (err as string) || 'Invalid code. Activation failed.';}}@@ -142,7 +145,7 @@ h3 {border-radius: var(--radius-sm);font-family: var(--font-mono, monospace);font-size: 0.85rem;- color: #333; /* Lisible sur fond blanc */+ color: #333;text-align: center;word-break: break-all;background: var(--surface-background);diff --git a/frontend/app/stores/db_structures.d.ts b/frontend/app/stores/db_structures.d.tsindex c1d89ba4..8261d7f5 100644--- a/frontend/app/stores/db_structures.d.ts+++ b/frontend/app/stores/db_structures.d.ts@@ -61,6 +61,7 @@ export interface Node extends DB_Node {export interface User {id: string;+ type: number; // 0: Normal; 1 Supervisedusername: string;firstname?: string;lastname?: string;@@ -69,6 +70,7 @@ export interface User {password?: string;email?: string;totp_enabled: boolean;+ totp_forced?: boolean;created_timestamp: number;updated_timestamp: number;}@@ -81,6 +83,9 @@ export interface PublicUser {updated_timestamp: number;}+export type UserToCreate = Pick<User, 'username' | 'password' | 'email' | 'firstname' | 'lastname' | 'totp_forced' | 'type'>;+export type UserToCreateBulk = Pick<User, 'username' | 'email' | 'firstname' | 'lastname' | 'totp_forced' | 'type'>;+export interface NodeSearchResult {id: string;user_id: string;diff --git a/frontend/app/stores/user.store.ts b/frontend/app/stores/user.store.tsindex db445636..cef1c891 100644--- a/frontend/app/stores/user.store.ts+++ b/frontend/app/stores/user.store.ts@@ -1,5 +1,6 @@import localForage from 'localforage';-import type { User, PublicUser, Session } from './db_structures';+import type { User, PublicUser, UserToCreate, Session, UserToCreateBulk } from './db_structures';+import type { ImportJob } from '~/helpers/backups/Importer';export const useUserStore = defineStore('user', {state: () => ({@@ -21,6 +22,7 @@ export const useUserStore = defineStore('user', {const response = await makeRequest<{ auth: boolean; pre_auth_token?: string; message?: string; user?: User }>('auth', 'POST', { username, password });if (response.status === 'success') {+ if (response.result?.message === '2FA_TO_ENABLE') return { success: true, require2FAEnable: true, preAuthToken: response.result?.pre_auth_token };if (response.result?.message === '2FA_REQUIRED') return { success: true, require2FA: true, preAuthToken: response.result?.pre_auth_token };if (import.meta.client) localForage.setItem('isLoggedIn', true);return { success: true, require2FA: false };@@ -32,16 +34,20 @@ export const useUserStore = defineStore('user', {}},- async request2FA() {- const response = await makeRequest<{ secret: string; qr_code_url: string }>('auth/2fa/request', 'POST', {});+ async request2FA(preAuthToken?: string) {+ const response = await makeRequest<{ secret: string; qr_code_url: string }>('auth/2fa/request', 'POST', { pre_auth_token: preAuthToken });if (response.status === 'success') {return response.result;}throw response.message;},- async confirm2FA(secret: string, code: string): Promise<string[]> {- const response = await makeRequest<{ message: string; backup_codes: string[] }>('auth/2fa/confirm', 'POST', { secret, code });+ async confirm2FA(secret: string, code: string, preAuthToken?: string): Promise<string[]> {+ const response = await makeRequest<{ message: string; backup_codes: string[] }>('auth/2fa/confirm', 'POST', {+ secret,+ code,+ pre_auth_token: preAuthToken,+ });if (response.status === 'success') {if (this.user) this.user.totp_enabled = true;return response.result?.backup_codes || [];@@ -71,12 +77,35 @@ export const useUserStore = defineStore('user', {throw response.message;},- async register(user: Omit<User, 'created_timestamp' | 'id' | 'updated_timestamp'>): Promise<boolean> {+ async register(user: UserToCreate): Promise<boolean> {const request = await makeRequest('users', 'POST', user);if (request.status === 'success') return true;throw request.message;},+ async bulkRegister(job: ImportJob<UserToCreateBulk, null>) {+ job.status = 'in_progress';+ job.failures = 0;+ job.error_message = '';+ for (const user of job.toCreate) {+ user.type = 1; // Set type to 1 (Supervised) for all users created via bulk registration+ try {+ await new Promise(resolve => setTimeout(resolve, 75));+ const request = await makeRequest('users', 'POST', user);+ if (request.status === 'success') job.created.push((request.result as User).id);+ else throw request.message;+ } catch (e) {+ job.failures++;+ job.error_message += `Failed to register user ${user.username}: ${e}<br>`;+ }+ }+ if (job.failures > 0) {+ job.status = 'failed';+ } else {+ job.status = 'completed';+ }+ },+async fetch(): Promise<undefined | User> {if (this.user) return this.user;const response = await makeRequest<User>(`users/@me`, 'GET', {});diff --git a/frontend/i18n/locales/de/public.ts b/frontend/i18n/locales/de/public.tsindex a78ea8e8..b67d9978 100644--- a/frontend/i18n/locales/de/public.ts+++ b/frontend/i18n/locales/de/public.ts@@ -19,6 +19,7 @@ export default {OTP_2FA: {title: 'Zwei-Faktor-Authentisierung',description: 'Bitte geben Sie den 6-stelligen Code aus Ihrer Authentifikator-App ein.',+ placeholder: '000000 oder 8-stelliger Backup-Code',code: 'Authentifizierungscode',submit: 'Verifizieren',back: 'Zurück',diff --git a/frontend/i18n/locales/de/settings.ts b/frontend/i18n/locales/de/settings.tsindex 89f931c2..76f076c1 100644--- a/frontend/i18n/locales/de/settings.ts+++ b/frontend/i18n/locales/de/settings.ts@@ -270,6 +270,26 @@ export default {passwordNotMatch: 'Passwörter stimmen nicht überein!',subtitle: 'Verwalte deine Sicherheitseinstellungen und überwache die Kontoaktivität.',title: 'Sicherheit',+ totp: {+ title: 'Zwei-Faktor-Authentisierung (2FA)',+ description: 'Sichere dein Konto, indem du einen 6-stelligen Code während des Logins verlangst.',+ enable: '2FA aktivieren',+ disable: '2FA deaktivieren',+ stateEnabled: '2FA ist derzeit auf deinem Konto aktiviert.',+ forced: '2FA ist für dein Konto erforderlich. Bitte aktiviere es, um die App weiterhin zu verwenden.',+ enableStep1: '1. Scanne diesen QR-Code mit deiner Authenticator-Anwendung (Google Authenticator, Bitwarden, etc.)',+ enableStep2: '2. Gib den 6-stelligen Code ein, der von deiner Authenticator-App generiert wurde, um die 2FA zu verifizieren und zu aktivieren.',+ backupCodes: {+ title: 'Sicherungscodes',+ warn: 'Sichere diese Codes!',+ description:+ 'Wenn du dein 2FA-Gerät verlierst, sind diese Codes die einzige Möglichkeit, dein Konto wiederherzustellen. Jeder Code kann nur einmal verwendet werden.',+ download: 'Sicherungscodes herunterladen',+ seen: 'Ich habe die Sicherungscodes gesehen und gespeichert',+ copied: 'Alle Codes kopiert',+ copy: 'Alle Codes kopieren',+ },+ },unlink: 'Trennen',unrecognizedSession: 'Nicht erkannte Sitzung?',unrecognizedSessionDesc:diff --git a/frontend/i18n/locales/en/public.ts b/frontend/i18n/locales/en/public.tsindex 2ff01568..bce75fca 100644--- a/frontend/i18n/locales/en/public.ts+++ b/frontend/i18n/locales/en/public.ts@@ -19,6 +19,7 @@ export default {OTP_2FA: {title: 'Two-Factor Authentication',description: 'Please enter the 6-digit code from your authenticator app.',+ placeholder: '000000 or 8-digit backup code',code: 'Authentication code',submit: 'Verify',back: 'Back',diff --git a/frontend/i18n/locales/en/settings.ts b/frontend/i18n/locales/en/settings.tsindex 0bcb0f35..e8aa7294 100644--- a/frontend/i18n/locales/en/settings.ts+++ b/frontend/i18n/locales/en/settings.ts@@ -268,6 +268,25 @@ export default {passwordNotMatch: 'Passwords do not match!',subtitle: 'Manage your security settings and monitor account activity.',title: 'Security',+ totp: {+ title: 'Two-Factor Authentication (2FA)',+ description: 'Secure your account by requiring a 6-digit code during login.',+ enable: 'Enable 2FA',+ disable: 'Disable 2FA',+ stateEnabled: '2FA is currently enabled on your account.',+ forced: '2FA is required for your account. Please enable it to continue using the app.',+ enableStep1: '1. Scan this QR code with your Authenticator application (Google Authenticator, Bitwarden, etc.)',+ enableStep2: '2. Enter the 6-digit code generated by your Authenticator app below to verify and enable 2FA.',+ backupCodes: {+ title: 'Backup codes',+ warn: 'Keep these codes safe!',+ description: 'If you lose your 2FA device, these codes are the only way to recover your account. Each code can only be used once.',+ download: 'Download backup codes',+ seen: 'I have saved these codes',+ copied: 'Codes copied!',+ copy: 'Copy all codes',+ },+ },unlink: 'Unlink',unrecognizedSession: 'Unrecognized session?',unrecognizedSessionDesc: 'If you see a session you do not recognize, change your password immediately and click "Sign out from all devices" below.',diff --git a/frontend/i18n/locales/fr/public.ts b/frontend/i18n/locales/fr/public.tsindex d98e7aed..1f41c51e 100644--- a/frontend/i18n/locales/fr/public.ts+++ b/frontend/i18n/locales/fr/public.ts@@ -19,6 +19,7 @@ export default {OTP_2FA: {title: 'Authentification à deux facteurs',description: "Veuillez saisir le code à 6 chiffres de votre application d'authentification.",+ placeholder: '000000 ou code de secours à 8 chiffres',code: "Code d'authentification",submit: 'Vérifier',back: 'Retour',diff --git a/frontend/i18n/locales/fr/settings.ts b/frontend/i18n/locales/fr/settings.tsindex 28ec80a1..db1644f1 100644--- a/frontend/i18n/locales/fr/settings.ts+++ b/frontend/i18n/locales/fr/settings.ts@@ -270,6 +270,27 @@ export default {passwordNotMatch: 'Les mots de passe ne correspondent pas !',subtitle: "Gérez vos paramètres de sécurité et surveillez l'activité de votre compte.",title: 'Sécurité',+ totp: {+ title: 'Authentification à deux facteurs (2FA)',+ description: 'écurisez votre compte en exigeant un code à 6 chiffres lors de la connexion.',+ enable: 'Activer 2FA',+ disable: 'Désactiver 2FA',+ stateEnabled: '2FA est actuellement activé sur votre compte.',+ forced: "2FA est requis pour votre compte. Veuillez l'activer pour continuer à utiliser l'application.",+ enableStep1:+ "1. Scannez le code QR ci-dessous avec votre application d'authentification (Google Authenticator, Authy, etc.) ou entrez la clé manuellement.",+ enableStep2: "2. Entrez le code à 6 chiffres généré par votre application d'authentification ci-dessous pour vérifier et activer le 2FA.",+ backupCodes: {+ title: 'Codes de récupération',+ warn: 'Gardez ces codes en sécurité !',+ description:+ "Si vous perdez votre appareil 2FA, ces codes sont le seul moyen de récupérer votre compte. Chaque code ne peut être utilisé qu'une seule fois.",+ download: 'Télécharger les codes de récupération',+ seen: "J'ai sauvegardé ces codes",+ copied: 'Codes copiés !',+ copy: 'Copier tous les codes',+ },+ },unlink: 'Délier',unrecognizedSession: 'Session non reconnue ?',unrecognizedSessionDesc:diff --git a/frontend/i18n/locales/it/public.ts b/frontend/i18n/locales/it/public.tsindex 492efb76..f9dda3aa 100644--- a/frontend/i18n/locales/it/public.ts+++ b/frontend/i18n/locales/it/public.ts@@ -19,6 +19,7 @@ export default {OTP_2FA: {title: 'Autenticazione a due fattori',description: 'Inserisci il codice a 6 cifre della tua app di autenticazione.',+ placeholder: '000000 o codice di backup a 8 cifre',code: 'Codice di autenticazione',submit: 'Verifica',back: 'Indietro',diff --git a/frontend/i18n/locales/it/settings.ts b/frontend/i18n/locales/it/settings.tsindex f057e4c6..3645c93c 100644--- a/frontend/i18n/locales/it/settings.ts+++ b/frontend/i18n/locales/it/settings.ts@@ -270,6 +270,26 @@ export default {passwordNotMatch: 'Le password non corrispondono!',subtitle: "Gestisci le tue impostazioni di sicurezza e monitora l'attività dell'account.",title: 'Sicurezza',+ totp: {+ title: 'Autenticazione a due fattori (2FA)',+ description: 'Proteggi il tuo account richiedendo un codice di 6 cifre durante il login.',+ enable: 'Abilita 2FA',+ disable: 'Disabilita 2FA',+ stateEnabled: '2FA è attualmente abilitato sul tuo account.',+ forced: "2FA è richiesto per il tuo account. Abilitalo per continuare a usare l'app.",+ enableStep1: '1. Scansiona il codice QR con la tua app di autenticazione (come Google Authenticator o Authy) o inserisci manualmente la chiave segreta.',+ enableStep2: '2. Inserisci il codice di 6 cifre generato dalla tua app di autenticazione qui sotto per verificare e abilitare il 2FA.',+ backupCodes: {+ title: 'Codes di backup',+ warn: 'Tieni questi codici al sicuro!',+ description:+ "Se perdi il tuo dispositivo 2FA, questi codici sono l'unico modo per recuperare il tuo account. Ogni codice può essere utilizzato solo una volta.",+ download: 'Scarica i codici di backup',+ seen: 'Ho salvato questi codici',+ copied: 'Codici copiati negli appunti',+ copy: 'Copia tutti i codici',+ },+ },unlink: 'Scollega',unrecognizedSession: 'Sessione non riconosciuta?',unrecognizedSessionDesc:diff --git a/frontend/i18n/locales/ko/public.ts b/frontend/i18n/locales/ko/public.tsindex 1d18e6c3..1092bbe1 100644--- a/frontend/i18n/locales/ko/public.ts+++ b/frontend/i18n/locales/ko/public.ts@@ -19,6 +19,7 @@ export default {OTP_2FA: {title: '2단계 인증',description: '인증 앱의 6자리 코드를 입력해 주세요.',+ placeholder: '000000 또는 8자리 백업 코드',code: '인증 코드',submit: '확인',back: '뒤로 가기',diff --git a/frontend/i18n/locales/ko/settings.ts b/frontend/i18n/locales/ko/settings.tsindex 9d041d77..ffcbabfb 100644--- a/frontend/i18n/locales/ko/settings.ts+++ b/frontend/i18n/locales/ko/settings.ts@@ -267,6 +267,25 @@ export default {passwordNotMatch: '비밀번호가 일치하지 않습니다!',subtitle: '보안 설정을 관리하고 계정 활동을 모니터링합니다.',title: '보안',+ totp: {+ title: '2단계 인증 (2FA)',+ description: '로그인 시 6자리 코드를 요구하여 계정을 보호합니다.',+ enable: '2FA 사용',+ disable: '2FA 비활성화',+ stateEnabled: '2FA는 현재 귀하의 계정에서 활성화되어 있습니다.',+ forced: '2FA는 귀하의 계정에 필수적입니다. 앱을 계속 사용하려면 활성화해 주세요.',+ enableStep1: '1. 인증 애플리케이션 (Google Authenticator, Bitwarden 등)으로 이 QR 코드를 스캔하세요.',+ enableStep2: '2. 인증 애플리케이션에서 생성된 6자리 코드를 입력하고 "활성화"를 클릭하세요.',+ backupCodes: {+ title: '백업 코드',+ warn: '이 코드를 안전하게 보관하세요!',+ description: '2FA 기기를 분실하면 이 코드만으로 계정을 복구할 수 있습니다. 각 코드는 한 번만 사용할 수 있습니다.',+ download: '백업 코드 다운로드',+ seen: '이 코드들을 저장했습니다',+ copied: '코드가 복사되었습니다!',+ copy: '모든 코드 복사',+ },+ },unlink: '연결 해제',unrecognizedSession: '알 수 없는 세션이 있나요?',unrecognizedSessionDesc: '인식되지 않는 세션이 있다면 즉시 비밀번호를 변경하고 아래의 "모든 기기에서 로그아웃"을 클릭하세요.',diff --git a/frontend/i18n/locales/uk/public.ts b/frontend/i18n/locales/uk/public.tsindex cc6e794e..a822736f 100644--- a/frontend/i18n/locales/uk/public.ts+++ b/frontend/i18n/locales/uk/public.ts@@ -19,6 +19,7 @@ export default {OTP_2FA: {title: 'Двофакторна автентифікація',description: 'Будь ласка, введіть 6-значний код із вашого додатку для автентифікації.',+ placeholder: '000000 або 8-значний резервний код',code: 'Код автентифікації',submit: 'Підтвердити',back: 'Назад',diff --git a/frontend/i18n/locales/uk/settings.ts b/frontend/i18n/locales/uk/settings.tsindex 050006ef..ad4f6676 100644--- a/frontend/i18n/locales/uk/settings.ts+++ b/frontend/i18n/locales/uk/settings.ts@@ -268,6 +268,25 @@ export default {passwordNotMatch: 'Паролі не збігаються!',subtitle: 'Керуйте налаштуваннями безпеки та відстежуйте активність облікового запису.',title: 'Безпека',+ totp: {+ title: 'Двофакторна автентифікація (2FA)',+ description: 'Захистіть свій обліковий запис, вимагаючи 6-значного коду під час входу.',+ enable: 'Увімкнути 2FA',+ disable: 'Вимкнути 2FA',+ stateEnabled: '2FA наразі увімкнено на вашому обліковому записі.',+ forced: "2FA обов'язковий для вашого облікового запису. Будь ласка, увімкніть його, щоб продовжити використання застосунку.",+ enableStep1: '1. Скануйте цей QR-код за допомогою програми автентифікації (Google Authenticator, Bitwarden тощо)',+ enableStep2: '2. Введіть 6-значний код, згенерований вашою програмою автентифікації нижче, щоб перевірити та увімкнути 2FA.',+ backupCodes: {+ title: 'Коди резервного копіювання',+ warn: 'Зберігайте ці коди в безпеці!',+ description: 'Якщо ви втратите пристрій 2FA, ці коди єдиний спосіб відновити ваш обліковий запис. Кожен код можна використовувати лише один раз.',+ download: 'Завантажити коди резервного копіювання',+ seen: 'Я зберегла ці коди',+ copied: 'Коди скопійовано!',+ copy: 'Копіювати всі коди',+ },+ },unlink: "Від'єднати",unrecognizedSession: 'Сесія не розпізнана?',unrecognizedSessionDesc: 'Якщо ви бачите сесію, яку не впізнаєте, негайно змініть пароль і натисніть «Вийти з усіх пристроїв» нижче.',