main
alex 2023-07-02 22:09:53 +02:00
parent b83c9efcb9
commit 21154128f8
12 changed files with 109 additions and 28 deletions

View File

@ -31,4 +31,5 @@ func InitDatabase() {
db.AutoMigrate(&structs.Scanner{}) db.AutoMigrate(&structs.Scanner{})
db.AutoMigrate(&structs.Role{}) db.AutoMigrate(&structs.Role{})
db.AutoMigrate(&structs.RolePermission{}) db.AutoMigrate(&structs.RolePermission{})
db.AutoMigrate(&structs.UserApiKey{})
} }

8
modules/structs/api.go Normal file
View File

@ -0,0 +1,8 @@
package structs
type ApiGroupTaskRequest struct {
Category string
GroupId string
Description string
GlobalInputs map[string]string
}

View File

@ -115,6 +115,7 @@ type UserData struct {
Email string Email string
Sessions []UserSessionSocket Sessions []UserSessionSocket
Permissions []string Permissions []string
ApiKeys []UserApiKey
} }
type UserSessionSocket struct { type UserSessionSocket struct {

View File

@ -43,3 +43,13 @@ type UserResponse struct {
type UserSignOutSessionRequest struct { type UserSignOutSessionRequest struct {
IdForDeletion string IdForDeletion string
} }
type UserApiKey struct {
Id string
Token string
UserId string
Name string
UsageCount uint
CreatedAt time.Time
LastUsed time.Time
}

View File

@ -61,6 +61,7 @@ const (
SentCmdAllUsersUserDeleted = 27 SentCmdAllUsersUserDeleted = 27
SentCmdAllUsersUserDeactivation = 28 SentCmdAllUsersUserDeactivation = 28
SentCmdGroupTasksCategoryGroupChanges = 29 SentCmdGroupTasksCategoryGroupChanges = 29
SentCmdNewUserApiKeyCreated = 30
) )
// commands received from web clients // commands received from web clients
@ -83,6 +84,7 @@ const (
ReceivedCmdScannersDisconnectScanner = 16 ReceivedCmdScannersDisconnectScanner = 16
ReceivedCmdGroupTasksCheckingForCategoryGroupChanges = 17 ReceivedCmdGroupTasksCheckingForCategoryGroupChanges = 17
ReceivedCmdHandleUserActionTaskStep = 18 ReceivedCmdHandleUserActionTaskStep = 18
ReceivedCmdCreateNewUserApiKey = 19
) )
const ( const (

View File

@ -1,7 +1,9 @@
package utils package utils
import ( import (
"crypto/rand"
"encoding/json" "encoding/json"
"math/big"
"time" "time"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
@ -37,3 +39,26 @@ func IsPasswordLengthValid(password string) bool {
return true 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
}

View File

@ -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)
}

View File

@ -5,7 +5,6 @@ import (
"janex/admin-dashboard-backend/modules/logger" "janex/admin-dashboard-backend/modules/logger"
"janex/admin-dashboard-backend/modules/structs" "janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/utils" "janex/admin-dashboard-backend/modules/utils"
"janex/admin-dashboard-backend/routers/router/api/v1/user"
"janex/admin-dashboard-backend/socketclients" "janex/admin-dashboard-backend/socketclients"
"time" "time"
@ -28,10 +27,9 @@ func AddScanner(c *fiber.Ctx) error {
} }
id := uuid.V4() id := uuid.V4()
session, err := user.GenerateSession() session, err := utils.GenerateSession()
if err != nil { if err != nil {
log.Error().Msgf("Failed to create session for scanner: %v", err)
return c.SendStatus(fiber.StatusInternalServerError) return c.SendStatus(fiber.StatusInternalServerError)
} }

View File

@ -1,14 +1,12 @@
package user package user
import ( import (
"crypto/rand"
"encoding/base64" "encoding/base64"
"janex/admin-dashboard-backend/modules/database" "janex/admin-dashboard-backend/modules/database"
"janex/admin-dashboard-backend/modules/logger" "janex/admin-dashboard-backend/modules/logger"
"janex/admin-dashboard-backend/modules/structs" "janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/utils" "janex/admin-dashboard-backend/modules/utils"
"janex/admin-dashboard-backend/socketclients" "janex/admin-dashboard-backend/socketclients"
"math/big"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
@ -58,7 +56,7 @@ func UserLogin(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusUnauthorized) return c.SendStatus(fiber.StatusUnauthorized)
} }
session, err := GenerateSession() session, err := utils.GenerateSession()
if err != nil { if err != nil {
return c.SendStatus(fiber.StatusInternalServerError) return c.SendStatus(fiber.StatusInternalServerError)
@ -105,25 +103,3 @@ func UserLogout(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusCreated) 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
}

View File

@ -5,6 +5,7 @@ import (
"janex/admin-dashboard-backend/modules/database" "janex/admin-dashboard-backend/modules/database"
"janex/admin-dashboard-backend/modules/structs" "janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/utils" "janex/admin-dashboard-backend/modules/utils"
"janex/admin-dashboard-backend/routers/router/api/v1/grouptask"
"janex/admin-dashboard-backend/routers/router/api/v1/jxscanner" "janex/admin-dashboard-backend/routers/router/api/v1/jxscanner"
log "janex/admin-dashboard-backend/routers/router/api/v1/logger" log "janex/admin-dashboard-backend/routers/router/api/v1/logger"
"janex/admin-dashboard-backend/routers/router/api/v1/user" "janex/admin-dashboard-backend/routers/router/api/v1/user"
@ -29,6 +30,9 @@ func SetupRoutes(app *fiber.App) {
l := v1.Group("/log") l := v1.Group("/log")
l.Get("/", userSessionValidation, log.GetSystemLog) l.Get("/", userSessionValidation, log.GetSystemLog)
g := v1.Group("/grouptasks")
g.Post("/", grouptask.StartGroupTask)
app.Static("/", config.Cfg.FolderPaths.PublicStatic) app.Static("/", config.Cfg.FolderPaths.PublicStatic)
} }

View File

@ -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,
})
}

View File

@ -72,6 +72,7 @@ func RunHub() {
Email: user.Email, Email: user.Email,
Sessions: socketclients.GetUserSessions(userId), Sessions: socketclients.GetUserSessions(userId),
Permissions: socketclients.GetPermissionsByRoleId(user.RoleId), Permissions: socketclients.GetPermissionsByRoleId(user.RoleId),
ApiKeys: socketclients.GetUserApiKeys(userId),
}, },
CategoryGroups: cache.GetCategoryGroupsSorted(), CategoryGroups: cache.GetCategoryGroupsSorted(),
GroupTasks: grouptasks.GetAllGroupTasks(), GroupTasks: grouptasks.GetAllGroupTasks(),
@ -372,6 +373,9 @@ func RunHub() {
case utils.ReceivedCmdHandleUserActionTaskStep: case utils.ReceivedCmdHandleUserActionTaskStep:
grouptasks.HandleUserActionTaskStep(data.Conn.Locals("userId").(string), receivedMessage.Body) grouptasks.HandleUserActionTaskStep(data.Conn.Locals("userId").(string), receivedMessage.Body)
break break
case utils.ReceivedCmdCreateNewUserApiKey:
socketclients.CreateNewUserApiKey(data.Conn.Locals("userId").(string), receivedMessage.Body["Name"].(string))
break
default: default:
log.Error().Msgf("Received unknown message: %v", receivedMessage) log.Error().Msgf("Received unknown message: %v", receivedMessage)