From 21154128f88129abf2e518440e2f33bae12b505b Mon Sep 17 00:00:00 2001 From: alex Date: Sun, 2 Jul 2023 22:09:53 +0200 Subject: [PATCH] api keys --- modules/database/database.go | 1 + modules/structs/api.go | 8 +++++ modules/structs/socket.go | 1 + modules/structs/user.go | 10 ++++++ modules/utils/globals.go | 2 ++ modules/utils/utils.go | 25 +++++++++++++++ routers/router/api/v1/grouptask/grouptask.go | 20 ++++++++++++ routers/router/api/v1/jxscanner/scanner.go | 4 +-- routers/router/api/v1/user/auth.go | 26 +--------------- routers/router/router.go | 4 +++ socketclients/socketclients.go | 32 ++++++++++++++++++++ socketserver/hub.go | 4 +++ 12 files changed, 109 insertions(+), 28 deletions(-) create mode 100644 modules/structs/api.go create mode 100644 routers/router/api/v1/grouptask/grouptask.go diff --git a/modules/database/database.go b/modules/database/database.go index d0d3251..042d99d 100644 --- a/modules/database/database.go +++ b/modules/database/database.go @@ -31,4 +31,5 @@ func InitDatabase() { db.AutoMigrate(&structs.Scanner{}) db.AutoMigrate(&structs.Role{}) db.AutoMigrate(&structs.RolePermission{}) + db.AutoMigrate(&structs.UserApiKey{}) } diff --git a/modules/structs/api.go b/modules/structs/api.go new file mode 100644 index 0000000..6a9c4f0 --- /dev/null +++ b/modules/structs/api.go @@ -0,0 +1,8 @@ +package structs + +type ApiGroupTaskRequest struct { + Category string + GroupId string + Description string + GlobalInputs map[string]string +} diff --git a/modules/structs/socket.go b/modules/structs/socket.go index abc133a..71c6bc3 100644 --- a/modules/structs/socket.go +++ b/modules/structs/socket.go @@ -115,6 +115,7 @@ type UserData struct { Email string Sessions []UserSessionSocket Permissions []string + ApiKeys []UserApiKey } type UserSessionSocket struct { diff --git a/modules/structs/user.go b/modules/structs/user.go index fcc2f10..b1f208e 100644 --- a/modules/structs/user.go +++ b/modules/structs/user.go @@ -43,3 +43,13 @@ type UserResponse struct { type UserSignOutSessionRequest struct { IdForDeletion string } + +type UserApiKey struct { + Id string + Token string + UserId string + Name string + UsageCount uint + CreatedAt time.Time + LastUsed time.Time +} diff --git a/modules/utils/globals.go b/modules/utils/globals.go index 5ae5d59..65a9e29 100644 --- a/modules/utils/globals.go +++ b/modules/utils/globals.go @@ -61,6 +61,7 @@ const ( SentCmdAllUsersUserDeleted = 27 SentCmdAllUsersUserDeactivation = 28 SentCmdGroupTasksCategoryGroupChanges = 29 + SentCmdNewUserApiKeyCreated = 30 ) // commands received from web clients @@ -83,6 +84,7 @@ const ( ReceivedCmdScannersDisconnectScanner = 16 ReceivedCmdGroupTasksCheckingForCategoryGroupChanges = 17 ReceivedCmdHandleUserActionTaskStep = 18 + ReceivedCmdCreateNewUserApiKey = 19 ) const ( diff --git a/modules/utils/utils.go b/modules/utils/utils.go index aec77f6..d8403a0 100644 --- a/modules/utils/utils.go +++ b/modules/utils/utils.go @@ -1,7 +1,9 @@ package utils import ( + "crypto/rand" "encoding/json" + "math/big" "time" "github.com/gofiber/fiber/v2" @@ -37,3 +39,26 @@ func IsPasswordLengthValid(password string) bool { return true } + +func GenerateSession() (string, error) { + var letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + + r := make([]byte, 36) + + for i := 0; i < 36; i++ { + num, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters)))) + + if err != nil { + log.Error().Msgf("Failed to session: %v", err) + return "", err + } + + if i == 8 || i == 13 || i == 18 || i == 23 { + r[i] = 45 + } else { + r[i] = letters[num.Int64()] + } + } + + return string(r), nil +} diff --git a/routers/router/api/v1/grouptask/grouptask.go b/routers/router/api/v1/grouptask/grouptask.go new file mode 100644 index 0000000..7e8478b --- /dev/null +++ b/routers/router/api/v1/grouptask/grouptask.go @@ -0,0 +1,20 @@ +package grouptask + +import ( + "github.com/gofiber/fiber/v2" + "github.com/rs/zerolog/log" +) + +type b struct { +} + +func StartGroupTask(c *fiber.Ctx) error { + var body b + + if err := c.BodyParser(&body); err != nil { + log.Error().Msg("Failed to parse body, err: " + err.Error()) + return c.Status(fiber.StatusBadRequest).JSON(err) + } + + return c.SendStatus(fiber.StatusOK) +} diff --git a/routers/router/api/v1/jxscanner/scanner.go b/routers/router/api/v1/jxscanner/scanner.go index 41cbe64..6911e72 100644 --- a/routers/router/api/v1/jxscanner/scanner.go +++ b/routers/router/api/v1/jxscanner/scanner.go @@ -5,7 +5,6 @@ import ( "janex/admin-dashboard-backend/modules/logger" "janex/admin-dashboard-backend/modules/structs" "janex/admin-dashboard-backend/modules/utils" - "janex/admin-dashboard-backend/routers/router/api/v1/user" "janex/admin-dashboard-backend/socketclients" "time" @@ -28,10 +27,9 @@ func AddScanner(c *fiber.Ctx) error { } id := uuid.V4() - session, err := user.GenerateSession() + session, err := utils.GenerateSession() if err != nil { - log.Error().Msgf("Failed to create session for scanner: %v", err) return c.SendStatus(fiber.StatusInternalServerError) } diff --git a/routers/router/api/v1/user/auth.go b/routers/router/api/v1/user/auth.go index 77e34a4..97149bd 100644 --- a/routers/router/api/v1/user/auth.go +++ b/routers/router/api/v1/user/auth.go @@ -1,14 +1,12 @@ package user import ( - "crypto/rand" "encoding/base64" "janex/admin-dashboard-backend/modules/database" "janex/admin-dashboard-backend/modules/logger" "janex/admin-dashboard-backend/modules/structs" "janex/admin-dashboard-backend/modules/utils" "janex/admin-dashboard-backend/socketclients" - "math/big" "github.com/gofiber/fiber/v2" "github.com/rs/zerolog/log" @@ -58,7 +56,7 @@ func UserLogin(c *fiber.Ctx) error { return c.SendStatus(fiber.StatusUnauthorized) } - session, err := GenerateSession() + session, err := utils.GenerateSession() if err != nil { return c.SendStatus(fiber.StatusInternalServerError) @@ -105,25 +103,3 @@ func UserLogout(c *fiber.Ctx) error { return c.SendStatus(fiber.StatusCreated) } - -func GenerateSession() (string, error) { - var letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - - r := make([]byte, 36) - - for i := 0; i < 36; i++ { - num, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters)))) - - if err != nil { - return "", nil - } - - if i == 8 || i == 13 || i == 18 || i == 23 { - r[i] = 45 - } else { - r[i] = letters[num.Int64()] - } - } - - return string(r), nil -} diff --git a/routers/router/router.go b/routers/router/router.go index b458bf0..03b3257 100644 --- a/routers/router/router.go +++ b/routers/router/router.go @@ -5,6 +5,7 @@ import ( "janex/admin-dashboard-backend/modules/database" "janex/admin-dashboard-backend/modules/structs" "janex/admin-dashboard-backend/modules/utils" + "janex/admin-dashboard-backend/routers/router/api/v1/grouptask" "janex/admin-dashboard-backend/routers/router/api/v1/jxscanner" log "janex/admin-dashboard-backend/routers/router/api/v1/logger" "janex/admin-dashboard-backend/routers/router/api/v1/user" @@ -29,6 +30,9 @@ func SetupRoutes(app *fiber.App) { l := v1.Group("/log") l.Get("/", userSessionValidation, log.GetSystemLog) + g := v1.Group("/grouptasks") + g.Post("/", grouptask.StartGroupTask) + app.Static("/", config.Cfg.FolderPaths.PublicStatic) } diff --git a/socketclients/socketclients.go b/socketclients/socketclients.go index ba90c4a..5d3cdb2 100644 --- a/socketclients/socketclients.go +++ b/socketclients/socketclients.go @@ -931,3 +931,35 @@ func ScannersUpdateScannerUsedByUserId(userId string, scannerId string) { }) } } + +func GetUserApiKeys(userId string) []structs.UserApiKey { + var apiKeys []structs.UserApiKey + + database.DB.Where("user_id = ?", userId).Find(&apiKeys) + + return apiKeys +} + +func CreateNewUserApiKey(userId string, apiName string) { + token, err := utils.GenerateSession() + + if err != nil { + return + } + + newApiKey := structs.UserApiKey{ + Id: uuid.New().String(), + Token: token, + UserId: userId, + Name: apiName, + UsageCount: 0, + CreatedAt: time.Now(), + } + + database.DB.Create(&newApiKey) + + SendMessageToUser(userId, "", structs.SendSocketMessage{ + Cmd: utils.SentCmdNewUserApiKeyCreated, + Body: newApiKey, + }) +} diff --git a/socketserver/hub.go b/socketserver/hub.go index a563f99..55946ea 100644 --- a/socketserver/hub.go +++ b/socketserver/hub.go @@ -72,6 +72,7 @@ func RunHub() { Email: user.Email, Sessions: socketclients.GetUserSessions(userId), Permissions: socketclients.GetPermissionsByRoleId(user.RoleId), + ApiKeys: socketclients.GetUserApiKeys(userId), }, CategoryGroups: cache.GetCategoryGroupsSorted(), GroupTasks: grouptasks.GetAllGroupTasks(), @@ -372,6 +373,9 @@ func RunHub() { case utils.ReceivedCmdHandleUserActionTaskStep: grouptasks.HandleUserActionTaskStep(data.Conn.Locals("userId").(string), receivedMessage.Body) break + case utils.ReceivedCmdCreateNewUserApiKey: + socketclients.CreateNewUserApiKey(data.Conn.Locals("userId").(string), receivedMessage.Body["Name"].(string)) + break default: log.Error().Msgf("Received unknown message: %v", receivedMessage)