Skip to content

Fully autonomous AI Agents system capable of performing complex penetration testing tasks

feat(webui): replace Change Password with My Profile (email and password updates)

Akalanka133782bca05ac362
diff --git a/backend/go.mod b/backend/go.mod
index 4a31f836..5e4ec29b 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -128,6 +128,7 @@ require (
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/gabriel-vasile/mimetype v1.4.9 // indirect
github.com/gage-technologies/mistral-go v1.1.0 // indirect
+ github.com/ghodss/yaml v1.0.0 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
github.com/go-logr/logr v1.4.3 // indirect
@@ -232,6 +233,7 @@ require (
google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect
google.golang.org/protobuf v1.36.10 // indirect
+ gopkg.in/yaml.v2 v2.4.0 // indirect
gotest.tools/v3 v3.5.1 // indirect
nhooyr.io/websocket v1.8.7 // indirect
)
diff --git a/backend/go.sum b/backend/go.sum
index ee265fa3..4dbc2979 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -220,6 +220,7 @@ github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBv
github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok=
github.com/gage-technologies/mistral-go v1.1.0 h1:POv1wM9jA/9OBXGV2YdPi9Y/h09+MjCbUF+9hRYlVUI=
github.com/gage-technologies/mistral-go v1.1.0/go.mod h1:tF++Xt7U975GcLlzhrjSQb8l/x+PrriO9QEdsgm9l28=
+github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw=
github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E=
diff --git a/backend/pkg/server/docs/docs.go b/backend/pkg/server/docs/docs.go
index b1561c30..69a00d2a 100644
--- a/backend/pkg/server/docs/docs.go
+++ b/backend/pkg/server/docs/docs.go
@@ -7087,6 +7087,69 @@ const docTemplate = `{
}
}
},
+ "/user/email": {
+ "put": {
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Users"
+ ],
+ "summary": "Update email for current user (account)",
+ "parameters": [
+ {
+ "description": "container to validate and update account email",
+ "name": "json",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/models.EmailChange"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "account email updated successful",
+ "schema": {
+ "$ref": "#/definitions/SuccessResponse"
+ }
+ },
+ "400": {
+ "description": "invalid account email form data",
+ "schema": {
+ "$ref": "#/definitions/ErrorResponse"
+ }
+ },
+ "403": {
+ "description": "updating account email not permitted",
+ "schema": {
+ "$ref": "#/definitions/ErrorResponse"
+ }
+ },
+ "404": {
+ "description": "current user not found",
+ "schema": {
+ "$ref": "#/definitions/ErrorResponse"
+ }
+ },
+ "409": {
+ "description": "email already exists",
+ "schema": {
+ "$ref": "#/definitions/ErrorResponse"
+ }
+ },
+ "500": {
+ "description": "internal error on updating account email",
+ "schema": {
+ "$ref": "#/definitions/ErrorResponse"
+ }
+ }
+ }
+ }
+ },
"/user/password": {
"put": {
"consumes": [
@@ -8426,6 +8489,24 @@ const docTemplate = `{
}
}
},
+ "models.EmailChange": {
+ "type": "object",
+ "required": [
+ "current_password",
+ "mail"
+ ],
+ "properties": {
+ "current_password": {
+ "type": "string",
+ "maxLength": 100,
+ "minLength": 5
+ },
+ "mail": {
+ "type": "string",
+ "maxLength": 50
+ }
+ }
+ },
"models.Flow": {
"type": "object",
"required": [
diff --git a/backend/pkg/server/docs/swagger.json b/backend/pkg/server/docs/swagger.json
index 803e56ac..43e9a260 100644
--- a/backend/pkg/server/docs/swagger.json
+++ b/backend/pkg/server/docs/swagger.json
@@ -7079,6 +7079,69 @@
}
}
},
+ "/user/email": {
+ "put": {
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "Users"
+ ],
+ "summary": "Update email for current user (account)",
+ "parameters": [
+ {
+ "description": "container to validate and update account email",
+ "name": "json",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/models.EmailChange"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "account email updated successful",
+ "schema": {
+ "$ref": "#/definitions/SuccessResponse"
+ }
+ },
+ "400": {
+ "description": "invalid account email form data",
+ "schema": {
+ "$ref": "#/definitions/ErrorResponse"
+ }
+ },
+ "403": {
+ "description": "updating account email not permitted",
+ "schema": {
+ "$ref": "#/definitions/ErrorResponse"
+ }
+ },
+ "404": {
+ "description": "current user not found",
+ "schema": {
+ "$ref": "#/definitions/ErrorResponse"
+ }
+ },
+ "409": {
+ "description": "email already exists",
+ "schema": {
+ "$ref": "#/definitions/ErrorResponse"
+ }
+ },
+ "500": {
+ "description": "internal error on updating account email",
+ "schema": {
+ "$ref": "#/definitions/ErrorResponse"
+ }
+ }
+ }
+ }
+ },
"/user/password": {
"put": {
"consumes": [
@@ -8418,6 +8481,24 @@
}
}
},
+ "models.EmailChange": {
+ "type": "object",
+ "required": [
+ "current_password",
+ "mail"
+ ],
+ "properties": {
+ "current_password": {
+ "type": "string",
+ "maxLength": 100,
+ "minLength": 5
+ },
+ "mail": {
+ "type": "string",
+ "maxLength": 50
+ }
+ }
+ },
"models.Flow": {
"type": "object",
"required": [
diff --git a/backend/pkg/server/docs/swagger.yaml b/backend/pkg/server/docs/swagger.yaml
index ef648a1a..66cbeb70 100644
--- a/backend/pkg/server/docs/swagger.yaml
+++ b/backend/pkg/server/docs/swagger.yaml
@@ -588,6 +588,19 @@ definitions:
- date
- stats
type: object
+ models.EmailChange:
+ properties:
+ current_password:
+ maxLength: 100
+ minLength: 5
+ type: string
+ mail:
+ maxLength: 50
+ type: string
+ required:
+ - current_password
+ - mail
+ type: object
models.Flow:
properties:
created_at:
@@ -6712,6 +6725,47 @@ paths:
summary: Retrieve current user information
tags:
- Users
+ /user/email:
+ put:
+ consumes:
+ - application/json
+ parameters:
+ - description: container to validate and update account email
+ in: body
+ name: json
+ required: true
+ schema:
+ $ref: '#/definitions/models.EmailChange'
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: account email updated successful
+ schema:
+ $ref: '#/definitions/SuccessResponse'
+ "400":
+ description: invalid account email form data
+ schema:
+ $ref: '#/definitions/ErrorResponse'
+ "403":
+ description: updating account email not permitted
+ schema:
+ $ref: '#/definitions/ErrorResponse'
+ "404":
+ description: current user not found
+ schema:
+ $ref: '#/definitions/ErrorResponse'
+ "409":
+ description: email already exists
+ schema:
+ $ref: '#/definitions/ErrorResponse'
+ "500":
+ description: internal error on updating account email
+ schema:
+ $ref: '#/definitions/ErrorResponse'
+ summary: Update email for current user (account)
+ tags:
+ - Users
/user/password:
put:
consumes:
diff --git a/backend/pkg/server/models/init.go b/backend/pkg/server/models/init.go
index 7919853e..e19a595d 100644
--- a/backend/pkg/server/models/init.go
+++ b/backend/pkg/server/models/init.go
@@ -222,6 +222,7 @@ func init() {
_, _ = reflect.ValueOf(User{}).Interface().(IValid)
_, _ = reflect.ValueOf(Password{}).Interface().(IValid)
+ _, _ = reflect.ValueOf(EmailChange{}).Interface().(IValid)
_, _ = reflect.ValueOf(Role{}).Interface().(IValid)
_, _ = reflect.ValueOf(Prompt{}).Interface().(IValid)
diff --git a/backend/pkg/server/models/users.go b/backend/pkg/server/models/users.go
index 859334e4..f6165a89 100644
--- a/backend/pkg/server/models/users.go
+++ b/backend/pkg/server/models/users.go
@@ -302,3 +302,27 @@ type UserWithPreferences struct {
User User
Preferences UserPreferences
}
+
+// EmailChange is model to contain user email to change it
+type EmailChange struct {
+ CurrentPassword string `form:"current_password" json:"current_password" validate:"min=5,max=100,required" gorm:"-"`
+ Mail string `form:"mail" json:"mail" validate:"max=50,vmail,required" gorm:"type:TEXT"`
+}
+
+// TableName returns the table name string to guaranty use correct table
+func (ec *EmailChange) TableName() string {
+ return "users"
+}
+
+// Valid is function to control input/output data
+func (ec EmailChange) Valid() error {
+ return validate.Struct(ec)
+}
+
+// Validate is function to use callback to control input/output data
+func (ec EmailChange) Validate(db *gorm.DB) {
+ if err := ec.Valid(); err != nil {
+ db.AddError(err)
+ }
+}
+
diff --git a/backend/pkg/server/response/errors.go b/backend/pkg/server/response/errors.go
index 8db4e89c..338141c9 100644
--- a/backend/pkg/server/response/errors.go
+++ b/backend/pkg/server/response/errors.go
@@ -44,6 +44,9 @@ var ErrUsersInvalidRequest = NewHttpError(400, "Users.InvalidRequest", "invalid
var ErrChangePasswordCurrentUserInvalidPassword = NewHttpError(400, "Users.ChangePasswordCurrentUser.InvalidPassword", "failed to validate user password")
var ErrChangePasswordCurrentUserInvalidCurrentPassword = NewHttpError(403, "Users.ChangePasswordCurrentUser.InvalidCurrentPassword", "invalid current password")
var ErrChangePasswordCurrentUserInvalidNewPassword = NewHttpError(400, "Users.ChangePasswordCurrentUser.InvalidNewPassword", "invalid new password form data")
+var ErrChangeEmailCurrentUserInvalidEmail = NewHttpError(400, "Users.ChangeEmailCurrentUser.InvalidEmail", "failed to validate user email")
+var ErrChangeEmailCurrentUserInvalidCurrentPassword = NewHttpError(403, "Users.ChangeEmailCurrentUser.InvalidCurrentPassword", "invalid current password")
+var ErrChangeEmailCurrentUserEmailAlreadyExists = NewHttpError(409, "Users.ChangeEmailCurrentUser.EmailAlreadyExists", "email already exists")
var ErrGetUserModelsNotFound = NewHttpError(404, "Users.GetUser.ModelsNotFound", "user linked models not found")
var ErrCreateUserInvalidUser = NewHttpError(400, "Users.CreateUser.InvalidUser", "failed to validate user")
var ErrPatchUserModelsNotFound = NewHttpError(404, "Users.PatchUser.ModelsNotFound", "user linked models not found")
diff --git a/backend/pkg/server/response/http_test.go b/backend/pkg/server/response/http_test.go
index f36cc804..495fa9a0 100644
--- a/backend/pkg/server/response/http_test.go
+++ b/backend/pkg/server/response/http_test.go
@@ -91,6 +91,9 @@ func TestPredefinedErrors(t *testing.T) {
{"ErrChangePasswordCurrentUserInvalidPassword", ErrChangePasswordCurrentUserInvalidPassword, 400, "Users.ChangePasswordCurrentUser.InvalidPassword"},
{"ErrChangePasswordCurrentUserInvalidCurrentPassword", ErrChangePasswordCurrentUserInvalidCurrentPassword, 403, "Users.ChangePasswordCurrentUser.InvalidCurrentPassword"},
{"ErrChangePasswordCurrentUserInvalidNewPassword", ErrChangePasswordCurrentUserInvalidNewPassword, 400, "Users.ChangePasswordCurrentUser.InvalidNewPassword"},
+ {"ErrChangeEmailCurrentUserInvalidEmail", ErrChangeEmailCurrentUserInvalidEmail, 400, "Users.ChangeEmailCurrentUser.InvalidEmail"},
+ {"ErrChangeEmailCurrentUserInvalidCurrentPassword", ErrChangeEmailCurrentUserInvalidCurrentPassword, 403, "Users.ChangeEmailCurrentUser.InvalidCurrentPassword"},
+ {"ErrChangeEmailCurrentUserEmailAlreadyExists", ErrChangeEmailCurrentUserEmailAlreadyExists, 409, "Users.ChangeEmailCurrentUser.EmailAlreadyExists"},
{"ErrGetUserModelsNotFound", ErrGetUserModelsNotFound, 404, "Users.GetUser.ModelsNotFound"},
{"ErrCreateUserInvalidUser", ErrCreateUserInvalidUser, 400, "Users.CreateUser.InvalidUser"},
{"ErrPatchUserModelsNotFound", ErrPatchUserModelsNotFound, 404, "Users.PatchUser.ModelsNotFound"},
diff --git a/backend/pkg/server/router.go b/backend/pkg/server/router.go
index 5404e35d..97243713 100644
--- a/backend/pkg/server/router.go
+++ b/backend/pkg/server/router.go
@@ -249,6 +249,7 @@ func NewRouter(
changePasswordGroup.Use(authMiddleware.AuthUserRequired)
changePasswordGroup.Use(localUserRequired())
changePasswordGroup.PUT("/password", userService.ChangePasswordCurrentUser)
+ changePasswordGroup.PUT("/email", userService.ChangeEmailCurrentUser)
publicGroup := api.Group("/")
publicGroup.Use(authMiddleware.TryAuth)
diff --git a/backend/pkg/server/services/users.go b/backend/pkg/server/services/users.go
index 7ebfa722..dabf201c 100644
--- a/backend/pkg/server/services/users.go
+++ b/backend/pkg/server/services/users.go
@@ -181,6 +181,89 @@ func (s *UserService) ChangePasswordCurrentUser(c *gin.Context) {
response.Success(c, http.StatusOK, struct{}{})
}
+// ChangeEmailCurrentUser is a function to update account email
+// @Summary Update email for current user (account)
+// @Tags Users
+// @Accept json
+// @Produce json
+// @Param json body models.EmailChange true "container to validate and update account email"
+// @Success 200 {object} response.successResp "account email updated successful"
+// @Failure 400 {object} response.errorResp "invalid account email form data"
+// @Failure 403 {object} response.errorResp "updating account email not permitted"
+// @Failure 404 {object} response.errorResp "current user not found"
+// @Failure 409 {object} response.errorResp "email already exists"
+// @Failure 500 {object} response.errorResp "internal error on updating account email"
+// @Router /user/email [put]
+func (s *UserService) ChangeEmailCurrentUser(c *gin.Context) {
+ var (
+ err error
+ form models.EmailChange
+ user models.UserPassword
+ )
+
+ if err = c.ShouldBindJSON(&form); err != nil || form.Valid() != nil {
+ if err == nil {
+ err = form.Valid()
+ }
+ logger.FromContext(c).WithError(err).Errorf("error binding JSON")
+ response.Error(c, response.ErrChangeEmailCurrentUserInvalidEmail, err)
+ return
+ }
+
+ uid := c.GetUint64("uid")
+ scope := func(db *gorm.DB) *gorm.DB {
+ return db.Where("id = ?", uid)
+ }
+
+ if err = s.db.Scopes(scope).Take(&user).Error; err != nil {
+ logger.FromContext(c).WithError(err).Errorf("error finding current user")
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ response.Error(c, response.ErrUsersNotFound, err)
+ } else {
+ response.Error(c, response.ErrInternal, err)
+ }
+ return
+ } else if err = user.Valid(); err != nil {
+ logger.FromContext(c).WithError(err).Errorf("error validating user data '%s'", user.Hash)
+ response.Error(c, response.ErrUsersInvalidData, err)
+ return
+ }
+
+ if err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(form.CurrentPassword)); err != nil {
+ logger.FromContext(c).WithError(err).Errorf("error checking password for current user")
+ response.Error(c, response.ErrChangeEmailCurrentUserInvalidCurrentPassword, err)
+ return
+ }
+
+ // Check if another user already has the new email
+ var count int
+ if err = s.db.Model(&models.User{}).Where("mail = ? AND id != ?", form.Mail, uid).Count(&count).Error; err != nil {
+ logger.FromContext(c).WithError(err).Errorf("error checking email duplicate")
+ response.Error(c, response.ErrInternal, err)
+ return
+ }
+ if count > 0 {
+ logger.FromContext(c).Errorf("email already exists: %s", form.Mail)
+ response.Error(c, response.ErrChangeEmailCurrentUserEmailAlreadyExists, errors.New("email already exists"))
+ return
+ }
+
+ updates := map[string]any{
+ "mail": form.Mail,
+ }
+
+ if err = s.db.Model(&user).Scopes(scope).Updates(updates).Error; err != nil {
+ logger.FromContext(c).WithError(err).Errorf("error updating email for current user")
+ response.Error(c, response.ErrInternal, err)
+ return
+ }
+
+ s.userCache.Invalidate(uid)
+
+ response.Success(c, http.StatusOK, struct{}{})
+}
+
+
// GetUsers returns users list
// @Summary Retrieve users list by filters
// @Tags Users
diff --git a/backend/pkg/server/services/users_test.go b/backend/pkg/server/services/users_test.go
index db2d38cd..19c6427b 100644
--- a/backend/pkg/server/services/users_test.go
+++ b/backend/pkg/server/services/users_test.go
@@ -15,6 +15,7 @@ import (
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
+ "golang.org/x/crypto/bcrypt"
)
func TestCreateUser_CreatesUserPreferences(t *testing.T) {
@@ -352,3 +353,92 @@ func TestCreateUser_DuplicateEmail(t *testing.T) {
db.Model(&models.User{}).Where("mail = ?", "[email protected]").Count(&count)
assert.Equal(t, 1, count, "Should have only one user with this email")
}
+
+func TestChangeEmailCurrentUser(t *testing.T) {
+ db := setupTestDB(t)
+ defer db.Close()
+
+ // Hash password for user 1
+ hashedPassword, err := bcrypt.GenerateFromPassword([]byte("SecurePass123!"), bcrypt.DefaultCost)
+ require.NoError(t, err)
+ err = db.Model(&models.User{}).Where("id = 1").Updates(map[string]interface{}{
+ "password": string(hashedPassword),
+ "hash": "11111111111111111111111111111111",
+ }).Error
+ require.NoError(t, err)
+
+ userCache := auth.NewUserCache(db)
+ service := NewUserService(db, userCache)
+
+ testCases := []struct {
+ name string
+ requestBody string
+ uid uint64
+ expectedCode int
+ checkResult func(t *testing.T, db *gorm.DB)
+ errorContains string
+ }{
+ {
+ name: "successful email change",
+ requestBody: `{"current_password": "SecurePass123!", "mail": "[email protected]"}`,
+ uid: 1,
+ expectedCode: http.StatusOK,
+ checkResult: func(t *testing.T, db *gorm.DB) {
+ var user models.User
+ err := db.Where("id = 1").First(&user).Error
+ require.NoError(t, err)
+ assert.Equal(t, "[email protected]", user.Mail)
+ },
+ },
+ {
+ name: "invalid password",
+ requestBody: `{"current_password": "WrongPassword!", "mail": "[email protected]"}`,
+ uid: 1,
+ expectedCode: http.StatusForbidden,
+ errorContains: "invalid current password",
+ },
+ {
+ name: "email already exists",
+ requestBody: `{"current_password": "SecurePass123!", "mail": "[email protected]"}`,
+ uid: 1,
+ expectedCode: http.StatusConflict,
+ errorContains: "email already exists",
+ },
+ {
+ name: "invalid email format",
+ requestBody: `{"current_password": "SecurePass123!", "mail": "invalid-email"}`,
+ uid: 1,
+ expectedCode: http.StatusBadRequest,
+ errorContains: "failed to validate user email",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+
+ c.Set("uid", tc.uid)
+ c.Set("rid", uint64(2))
+ c.Set("uhash", "11111111111111111111111111111111")
+ c.Set("prm", []string{})
+
+ c.Request, _ = http.NewRequest("PUT", "/user/email", bytes.NewBufferString(tc.requestBody))
+ c.Request.Header.Set("Content-Type", "application/json")
+
+ service.ChangeEmailCurrentUser(c)
+
+ assert.Equal(t, tc.expectedCode, w.Code)
+
+ if tc.checkResult != nil {
+ tc.checkResult(t, db)
+ }
+
+ if tc.errorContains != "" {
+ assert.Contains(t, w.Body.String(), tc.errorContains)
+ }
+ })
+ }
+}
+
diff --git a/frontend/src/components/layouts/main-sidebar.tsx b/frontend/src/components/layouts/main-sidebar.tsx
index 56041c6a..b4051f5b 100644
--- a/frontend/src/components/layouts/main-sidebar.tsx
+++ b/frontend/src/components/layouts/main-sidebar.tsx
@@ -5,7 +5,6 @@ import {
FileText,
Folder,
GitFork,
- KeyRound,
LayoutDashboard,
LibraryBig,
LogOut,
@@ -49,7 +48,7 @@ import {
SidebarRail,
} from '@/components/ui/sidebar';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
-import { PasswordChangeForm } from '@/features/authentication/password-change-form';
+import { ProfileDialog } from '@/features/authentication/profile-dialog';
import { useResourcesUpload } from '@/features/resources/use-resources-upload';
import { useTheme } from '@/hooks/use-theme';
import { useFavorites } from '@/providers/favorites-provider';
@@ -64,7 +63,7 @@ interface FlowMenuItemProps {
}
export function MainSidebar() {
- const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(false);
+ const [isProfileModalOpen, setIsProfileModalOpen] = useState(false);
const isDashboardActive = useMatch('/dashboard');
const isFlowsActive = useMatch('/flows/*');
const isTemplatesActive = useMatch('/templates/*');
@@ -359,9 +358,9 @@ export function MainSidebar() {
{user?.type === 'local' && (
<>
<DropdownMenuSeparator />
- <DropdownMenuItem onClick={() => setIsPasswordModalOpen(true)}>
- <KeyRound className="mr-2 size-4" />
- Change Password
+ <DropdownMenuItem onClick={() => setIsProfileModalOpen(true)}>
+ <UserIcon className="mr-2 size-4" />
+ My Profile
</DropdownMenuItem>
</>
)}
@@ -389,16 +388,16 @@ export function MainSidebar() {
/>
<Dialog
- onOpenChange={setIsPasswordModalOpen}
- open={isPasswordModalOpen}
+ onOpenChange={setIsProfileModalOpen}
+ open={isProfileModalOpen}
>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
- <DialogTitle>Change Password</DialogTitle>
+ <DialogTitle>My Profile</DialogTitle>
</DialogHeader>
- <PasswordChangeForm
- onCancel={() => setIsPasswordModalOpen(false)}
- onSuccess={() => setIsPasswordModalOpen(false)}
+ <ProfileDialog
+ onCancel={() => setIsProfileModalOpen(false)}
+ onSuccess={() => setIsProfileModalOpen(false)}
/>
</DialogContent>
</Dialog>
diff --git a/frontend/src/features/authentication/email-change-form.tsx b/frontend/src/features/authentication/email-change-form.tsx
new file mode 100644
index 00000000..17dca164
--- /dev/null
+++ b/frontend/src/features/authentication/email-change-form.tsx
@@ -0,0 +1,189 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { Eye, EyeOff } from 'lucide-react';
+import { useState } from 'react';
+import { useForm } from 'react-hook-form';
+import { toast } from 'sonner';
+import * as z from 'zod';
+
+import { Button } from '@/components/ui/button';
+import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
+import { FormSubmitButton } from '@/components/ui/form-submit-button';
+import { Input } from '@/components/ui/input';
+import { api, type ApiErrorResponse, type ApiHttpError } from '@/lib/axios';
+import { useUser } from '@/providers/user-provider';
+
+const emailChangeSchema = z.object({
+ currentPassword: z.string().min(1, { message: 'Current password is required' }),
+ newEmail: z
+ .string()
+ .min(1, { message: 'Email is required' })
+ .email({ message: 'Invalid email address' })
+ .max(50, { message: 'Email must not exceed 50 characters' }),
+});
+
+interface EmailChangeFormProps {
+ isModal?: boolean;
+ onCancel?: () => void;
+ onSuccess?: () => void;
+}
+
+type EmailChangeFormValues = z.infer<typeof emailChangeSchema>;
+
+export function EmailChangeForm({ isModal = true, onCancel, onSuccess }: EmailChangeFormProps) {
+ const [error, setError] = useState<null | string>(null);
+ const [showPassword, setShowPassword] = useState(false);
+ const { authInfo, refreshAuthInfo } = useUser();
+ const currentEmail = authInfo?.user?.mail || '';
+
+ const form = useForm<EmailChangeFormValues>({
+ defaultValues: {
+ currentPassword: '',
+ newEmail: '',
+ },
+ resolver: zodResolver(emailChangeSchema),
+ });
+
+ const handleSubmit = async (values: EmailChangeFormValues) => {
+ setError(null);
+
+ try {
+ await api.put('/user/email', {
+ current_password: values.currentPassword,
+ mail: values.newEmail,
+ });
+
+ form.reset();
+ setShowPassword(false);
+
+ toast.success('Email successfully updated');
+
+ // Refresh user info to update local state/display
+ await refreshAuthInfo();
+
+ if (onSuccess) {
+ onSuccess();
+ }
+ } catch (err: unknown) {
+ const error = err as ApiHttpError;
+ const responseData = error.response?.data as ApiErrorResponse | undefined;
+
+ let errorMessage = 'Failed to update email';
+
+ if (responseData?.msg) {
+ errorMessage = responseData.msg;
+ } else if (responseData?.code) {
+ switch (responseData.code) {
+ case 'AuthRequired':
+ errorMessage = 'Authentication required';
+ break;
+ case 'Users.ChangeEmailCurrentUser.EmailAlreadyExists':
+ errorMessage = 'Email address is already in use';
+ break;
+ case 'Users.ChangeEmailCurrentUser.InvalidCurrentPassword':
+ errorMessage = 'Current password is incorrect';
+ break;
+ case 'Users.ChangeEmailCurrentUser.InvalidEmail':
+ errorMessage = 'New email does not meet requirements';
+ break;
+ case 'Users.NotFound':
+ errorMessage = 'User not found';
+ break;
+ default:
+ errorMessage = responseData.msg || error.message || 'Failed to update email';
+ }
+ } else if (error.message) {
+ errorMessage = error.message;
+ }
+
+ setError(errorMessage);
+ }
+ };
+
+ return (
+ <Form {...form}>
+ <form
+ className="flex flex-col gap-4"
+ onSubmit={form.handleSubmit(handleSubmit)}
+ >
+ <div className="space-y-2">
+ <label className="text-sm leading-none font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
+ Current Email
+ </label>
+ <Input
+ disabled
+ value={currentEmail}
+ />
+ </div>
+
+ <FormField
+ control={form.control}
+ name="newEmail"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>New Email</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ placeholder="Enter new email address"
+ type="email"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="currentPassword"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Current Password</FormLabel>
+ <FormControl>
+ <div className="relative">
+ <Input
+ {...field}
+ placeholder="Enter your current password to confirm"
+ type={showPassword ? 'text' : 'password'}
+ />
+ <Button
+ className="absolute top-0 right-0 h-full px-3 py-2 hover:bg-transparent"
+ onClick={() => setShowPassword(!showPassword)}
+ size="sm"
+ tabIndex={-1}
+ type="button"
+ variant="ghost"
+ >
+ {showPassword ? (
+ <EyeOff className="text-muted-foreground size-4" />
+ ) : (
+ <Eye className="text-muted-foreground size-4" />
+ )}
+ </Button>
+ </div>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {error && <div className="text-destructive text-sm">{error}</div>}
+
+ <div className="flex justify-end gap-2 pt-2">
+ {isModal && (
+ <Button
+ onClick={onCancel}
+ type="button"
+ variant="outline"
+ >
+ Cancel
+ </Button>
+ )}
+ <FormSubmitButton>
+ <span>Update Email</span>
+ </FormSubmitButton>
+ </div>
+ </form>
+ </Form>
+ );
+}
diff --git a/frontend/src/features/authentication/profile-dialog.tsx b/frontend/src/features/authentication/profile-dialog.tsx
new file mode 100644
index 00000000..7507cf01
--- /dev/null
+++ b/frontend/src/features/authentication/profile-dialog.tsx
@@ -0,0 +1,39 @@
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
+
+import { EmailChangeForm } from './email-change-form';
+import { PasswordChangeForm } from './password-change-form';
+
+interface ProfileDialogProps {
+ onCancel: () => void;
+ onSuccess: () => void;
+}
+
+export function ProfileDialog({ onCancel, onSuccess }: ProfileDialogProps) {
+ return (
+ <Tabs
+ className="w-full"
+ defaultValue="email"
+ >
+ <TabsList className="grid w-full grid-cols-2">
+ <TabsTrigger value="email">Update Email</TabsTrigger>
+ <TabsTrigger value="password">Change Password</TabsTrigger>
+ </TabsList>
+ <TabsContent value="email">
+ <div className="pt-2">
+ <EmailChangeForm
+ onCancel={onCancel}
+ onSuccess={onSuccess}
+ />
+ </div>
+ </TabsContent>
+ <TabsContent value="password">
+ <div className="pt-2">
+ <PasswordChangeForm
+ onCancel={onCancel}
+ onSuccess={onSuccess}
+ />
+ </div>
+ </TabsContent>
+ </Tabs>
+ );
+}