From 8444724a583c597937de4d97a128c1836b440fca Mon Sep 17 00:00:00 2001 From: alex Date: Mon, 12 Jun 2023 23:17:16 +0200 Subject: [PATCH] update user profile --- modules/utils/globals.go | 37 ++++++------- modules/utils/utils.go | 11 ++++ routers/router/api/v1/user/auth.go | 13 +---- socketclients/socketclients.go | 86 ++++++++++++++++++++++++++++++ socketserver/hub.go | 6 +-- 5 files changed, 120 insertions(+), 33 deletions(-) diff --git a/modules/utils/globals.go b/modules/utils/globals.go index 73bc74b..4f0d357 100644 --- a/modules/utils/globals.go +++ b/modules/utils/globals.go @@ -24,24 +24,24 @@ const ( // commands sent to web clients const ( - SentCmdInitUserSocketConnection = 1 - SentCmdUpdateConnectedUsers = 2 - SentCmdNewGroupTaskStarted = 3 - SentCmdNewGroupTaskStep = 4 - SentCmdUpdateGroupTaskStep = 5 - SentCmdUpdateGroupTask = 6 - SentCmdReloadingGroupTasks = 7 - SentCmdGroupTasksReloaded = 8 - SentCmdUpdateUserSessions = 9 - SentCmdUpdateAllUsersUserAvatar = 10 - SentCmdNewScanner = 11 - SentCmdDeleteScanner = 12 - SentCmdUpdateScannerUsedBy = 13 - SentCmdScanResult = 14 - SentCmdUpdateScannerLastUsed = 15 - SentCmdTaskLocked = 16 - SentCmdTaskUnlocked = 17 - SentCmdUpdateGroupTaskStepUserInputValue = 18 + SentCmdInitUserSocketConnection = 1 + SentCmdUpdateConnectedUsers = 2 + SentCmdNewGroupTaskStarted = 3 + SentCmdNewGroupTaskStep = 4 + SentCmdUpdateGroupTaskStep = 5 + SentCmdUpdateGroupTask = 6 + SentCmdReloadingGroupTasks = 7 + SentCmdGroupTasksReloaded = 8 + SentCmdUpdateUserSessions = 9 + SentCmdUpdateAllUsersUserAvatar = 10 + SentCmdNewScanner = 11 + SentCmdDeleteScanner = 12 + SentCmdUpdateScannerUsedBy = 13 + SentCmdScanResult = 14 + SentCmdUpdateScannerLastUsed = 15 + SentCmdTaskLocked = 16 + SentCmdTaskUnlocked = 17 + SentCmdUserProfileUpdated = 18 ) // commands received from web clients @@ -51,6 +51,7 @@ const ( ReceivedCmdTaskContinueTaskStep = 3 ReceivedCmdReloadGroupTasks = 4 ReceivedCmdTaskLocking = 5 + ReceivedCmdUpdateUserProfile = 6 ) const ( diff --git a/modules/utils/utils.go b/modules/utils/utils.go index 0162b6d..aec77f6 100644 --- a/modules/utils/utils.go +++ b/modules/utils/utils.go @@ -26,3 +26,14 @@ func MarshalJson(v any) string { func GetSessionExpiresAtTime() time.Time { return time.Now().Add(time.Second * SessionExpiresAtTime) } + +func IsPasswordLengthValid(password string) bool { + lenPassword := len(password) + + if lenPassword < MinPassword || lenPassword > MaxPassword { + log.Error().Msg("Password length not valid") + return false + } + + return true +} diff --git a/routers/router/api/v1/user/auth.go b/routers/router/api/v1/user/auth.go index 67f9fc6..0c89a40 100644 --- a/routers/router/api/v1/user/auth.go +++ b/routers/router/api/v1/user/auth.go @@ -35,7 +35,7 @@ func UserLogin(c *fiber.Ctx) error { return c.Status(fiber.StatusBadRequest).JSON(err.Error()) } - if passwordValid := validatePasswordLength(string(decodedPassword)); !passwordValid { + if passwordValid := utils.IsPasswordLengthValid(string(decodedPassword)); !passwordValid { return c.SendStatus(fiber.StatusBadRequest) } @@ -79,17 +79,6 @@ func UserLogout(c *fiber.Ctx) error { return c.SendStatus(fiber.StatusCreated) } -func validatePasswordLength(password string) bool { - lenPassword := len(password) - - if lenPassword < utils.MinPassword || lenPassword > utils.MaxPassword { - log.Error().Msg("Password length not valid") - return false - } - - return true -} - func GenerateSession() (string, error) { var letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" diff --git a/socketclients/socketclients.go b/socketclients/socketclients.go index 061f630..bdb8f59 100644 --- a/socketclients/socketclients.go +++ b/socketclients/socketclients.go @@ -1,11 +1,15 @@ package socketclients import ( + "encoding/base64" "janex/admin-dashboard-backend/modules/cache" "janex/admin-dashboard-backend/modules/database" "janex/admin-dashboard-backend/modules/structs" "janex/admin-dashboard-backend/modules/utils" "time" + + "github.com/rs/zerolog/log" + "golang.org/x/crypto/bcrypt" ) func BroadcastMessage(sendSocketMessage structs.SendSocketMessage) { @@ -149,3 +153,85 @@ func GetAllScanners() []structs.Scanner { return allScanners } + +func isUsernameAvailable(username string) bool { + var user structs.User + database.DB.Select("username").Where("username = ?", username).Find(&user) + + return user.Username == "" +} + +func isEmailAvailable(email string) bool { + var user structs.User + database.DB.Select("email").Where("email = ?", email).Find(&user) + + return user.Email == "" +} + +func UpdateUserProfile(userId string, changes map[string]interface{}) { + log.Debug().Msgf("changes: %v", changes) + + var user structs.User + var updates = make(map[string]interface{}) + + // TODO: validate length of username and email + + if changes["username"] != nil { + username := changes["username"].(string) + + if isUsernameAvailable(username) { + user.Username = username + updates["Username"] = username + } + } + + if changes["email"] != nil { + email := changes["email"].(string) + + if isEmailAvailable(email) { + user.Email = email + updates["Email"] = email + } + } + + if changes["password"] != nil { + log.Debug().Msg("update password") + password := changes["password"].(string) + + decodedPassword, err := base64.StdEncoding.DecodeString(changes["password"].(string)) + + if err != nil { + log.Error().Msg("Failed to decode base64 password, err: " + err.Error()) + } + + if utils.IsPasswordLengthValid(password) { + if err := bcrypt.CompareHashAndPassword([]byte(user.Password), decodedPassword); err != nil { + log.Error().Msg("Incorrect password") + } + } + + // TODO: logout all client user sessions + } + + log.Debug().Msgf("len %v", len(changes)) + + // TODO: dont sent change message if user changed password + if len(changes) > 0 { + // TODO: update user last updated timestamp + database.DB.Model(&structs.User{}).Where("id = ?", userId).Updates(user) + + if changes["username"] != nil || changes["email"] != nil { + BroadcastMessage(structs.SendSocketMessage{ + Cmd: utils.SentCmdUserProfileUpdated, + Body: struct { + UserId string + Changes map[string]interface{} + }{ + UserId: userId, + Changes: updates, + }, + }) + } + } + // TODO: sent feedback back to user for ui notification message +} diff --git a/socketserver/hub.go b/socketserver/hub.go index 07bc6c2..8c2a342 100644 --- a/socketserver/hub.go +++ b/socketserver/hub.go @@ -154,7 +154,6 @@ func RunHub() { TaskStepId: receivedMessage.Body["taskStepId"].(string), TaskInputs: utils.MarshalJson(receivedMessage.Body["taskInputs"]), }) - break case utils.ReceivedCmdReloadGroupTasks: category := receivedMessage.Body["category"].(string) @@ -165,7 +164,6 @@ func RunHub() { }) grouptasks.LoadGroups(category) - break case utils.ReceivedCmdTaskLocking: cache.AddLockedGroupTaskStep(structs.LockedGroupTaskSteps{ @@ -187,7 +185,9 @@ func RunHub() { ParameterName: receivedMessage.Body["parameterName"].(string), Value: receivedMessage.Body["value"], }) - + break + case utils.ReceivedCmdUpdateUserProfile: + socketclients.UpdateUserProfile(data.Conn.Locals("userId").(string), receivedMessage.Body["changes"].(map[string]interface{})) break default: log.Error().Msgf("Received unknown message: %v", receivedMessage)