equipment documentation

main
alex 2023-08-20 18:34:26 +00:00
parent 1f7e4f4f87
commit 94af0cf35d
49 changed files with 780 additions and 167 deletions

View File

@ -4,9 +4,9 @@ FROM golang:latest AS go_builder
WORKDIR /app
COPY ./backend/main /app/main
COPY ./backend/grouptasks_lang_log_messages.json /app/
COPY ./backend/system_lang_log_messages.json /app/
COPY ./backend/public/swagger/ /app/swagger
#COPY ./backend/grouptasks_lang_log_messages.json /app/
#COPY ./backend/system_lang_log_messages.json /app/
#COPY ./backend/public/swagger/ /app/swagger
# Assuming you build your Go binary using "go build -o main"
#RUN go build -o main

3
README.md Normal file
View File

@ -0,0 +1,3 @@
#### Requesting a Token
{INVEX_URL}/api/user/token/

2
go.mod
View File

@ -1,4 +1,4 @@
module janex/admin-dashboard-backend
module jannex/admin-dashboard-backend
go 1.20

View File

@ -0,0 +1 @@
numpy==1.24.3

View File

@ -167,5 +167,44 @@
"message": "Installation der Python Pakete für %groupId% von %category% abgeschlossen. Log: %log%"
}
]
},
{
"id": 13,
"languages": [
{
"lang": "en",
"message": "%userId% has requested installing the global python packages"
},
{
"lang": "de",
"message": "%userId% hat die Installation der globalen Python Pakete angefordert"
}
]
},
{
"id": 14,
"languages": [
{
"lang": "en",
"message": "Installing the global python packages failed. Error %error%"
},
{
"lang": "de",
"message": "Installation der globalen Python Pakete fehlgeschlagen. Fehler: %error%"
}
]
},
{
"id": 15,
"languages": [
{
"lang": "en",
"message": "Installation of the global python packages finished. Log %log%"
},
{
"lang": "de",
"message": "Installation der globalen Python Pakete abgeschlossen. Log: %log%"
}
]
}
]

20
main.go
View File

@ -1,4 +1,4 @@
// Package classification Janex API Documentation.
// Package classification Jannex API Documentation.
//
// Schemes: https
// Host: janex
@ -18,15 +18,15 @@ import (
"encoding/json"
"fmt"
"io"
"janex/admin-dashboard-backend/modules/config"
"janex/admin-dashboard-backend/modules/database"
"janex/admin-dashboard-backend/modules/grouptasks"
"janex/admin-dashboard-backend/modules/logger"
"janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/systempermissions"
"janex/admin-dashboard-backend/modules/utils"
"janex/admin-dashboard-backend/routers/router"
"janex/admin-dashboard-backend/socketserver"
"jannex/admin-dashboard-backend/modules/config"
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/grouptasks"
"jannex/admin-dashboard-backend/modules/logger"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/systempermissions"
"jannex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/routers/router"
"jannex/admin-dashboard-backend/socketserver"
"os"
"path/filepath"
"time"

View File

@ -1,7 +1,7 @@
package cache
import (
"janex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/structs"
"sort"
"sync"
)

View File

@ -1,8 +1,8 @@
package cache
import (
"janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils"
"sync"
)

View File

@ -1,8 +1,8 @@
package cache
import (
"janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils"
"sync"
"time"
)

View File

@ -1,7 +1,7 @@
package cache
import (
"janex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/structs"
"sync"
"github.com/gofiber/websocket/v2"

View File

@ -2,21 +2,32 @@ package database
import (
"fmt"
"janex/admin-dashboard-backend/modules/config"
"janex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/config"
"jannex/admin-dashboard-backend/modules/structs"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var DB *gorm.DB
func InitDatabase() {
cfg := config.Cfg.MariaDB
cfg := config.Cfg
var logMode logger.LogLevel
if cfg.Debug {
logMode = logger.Error
} else {
logMode = logger.Silent
}
db, err := gorm.Open(mysql.Open(
fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", cfg.Username, cfg.Password, cfg.Hostname, cfg.Port, cfg.DatabaseName)),
&gorm.Config{})
fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", cfg.MariaDB.Username, cfg.MariaDB.Password, cfg.MariaDB.Hostname, cfg.MariaDB.Port, cfg.MariaDB.DatabaseName)),
&gorm.Config{
Logger: logger.Default.LogMode(logMode),
})
if err != nil {
panic(err)
@ -32,4 +43,6 @@ func InitDatabase() {
db.AutoMigrate(&structs.Role{})
db.AutoMigrate(&structs.RolePermission{})
db.AutoMigrate(&structs.UserApiKey{})
db.AutoMigrate(&structs.Equipment{})
db.AutoMigrate(&structs.EquipmentDocumentation{})
}

View File

@ -0,0 +1,99 @@
package equipment
import (
"encoding/json"
"errors"
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/structs"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log"
"gorm.io/gorm"
)
const Base = "https://inv.ex.umbach.dev"
const apiBase = Base + "/api"
const ApiToken = "1367f15d21935e4eb540f897946fb5cd98485c3f"
func GetEquipmentDocumentation(stockItemId string, c *fiber.Ctx) error {
equipment := structs.Equipment{Id: stockItemId}
if err := database.DB.Where("id = ?", stockItemId).First(&equipment).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
log.Info().Msgf("a %s", err)
log.Error().Msgf("Failed to get equipment, err: %s", err)
return c.JSON([]structs.EquipmentDocumentation{})
}
// if equipment already exists, return the documentation
if equipment.Name != "" {
var equipmentDocumentations []structs.EquipmentDocumentation
database.DB.Where("equipment_id = ?", stockItemId).Find(&equipmentDocumentations)
return c.JSON(equipmentDocumentations)
}
// create new equipment
a := fiber.AcquireAgent()
a.Add("Authorization", "Token "+ApiToken)
req := a.Request()
req.Header.SetMethod(fiber.MethodGet)
req.SetRequestURI(apiBase + "/stock/" + stockItemId + "/")
if err := a.Parse(); err != nil {
log.Error().Msgf("Failed to parse request, err: %s", err)
return c.SendStatus(fiber.StatusInternalServerError)
}
code, body, _ := a.Bytes()
if code == 401 {
log.Error().Msgf("invex not authorized, code: %d", code)
return c.SendStatus(fiber.StatusInternalServerError)
}
if code == 404 {
log.Error().Msgf("Inven stock item not found, code: %d", code)
return c.SendStatus(fiber.StatusNotFound)
}
// parse body as json
var data map[string]interface{}
if err := json.Unmarshal(body, &data); err != nil {
log.Error().Msgf("Failed to unmarshal json, err: %s", err)
return c.SendStatus(fiber.StatusInternalServerError)
}
partDetail := data["part_detail"].(map[string]interface{})
database.DB.Create(&structs.Equipment{
Id: stockItemId,
Name: partDetail["name"].(string),
Thumbnail: partDetail["thumbnail"].(string),
})
return c.JSON([]structs.EquipmentDocumentation{})
}
func GetEquipment() []structs.Equipment {
var equipments []structs.Equipment
database.DB.Find(&equipments)
return equipments
}
/*
// return whether the scanned equipment is existing in the database
func IsEquipmentExisting(stockItemId string) bool {
var equipment structs.Equipment
database.DB.Where("id = ?", stockItemId).FirstOrCreate(&equipment)
return equipment.Id != ""
} */

View File

@ -5,14 +5,14 @@ import (
"errors"
"fmt"
"io/ioutil"
"janex/admin-dashboard-backend/modules/cache"
"janex/admin-dashboard-backend/modules/config"
"janex/admin-dashboard-backend/modules/database"
"janex/admin-dashboard-backend/modules/logger"
"janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/systempermissions"
"janex/admin-dashboard-backend/modules/utils"
"janex/admin-dashboard-backend/socketclients"
"jannex/admin-dashboard-backend/modules/cache"
"jannex/admin-dashboard-backend/modules/config"
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/logger"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/systempermissions"
"jannex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/socketclients"
"os"
"os/exec"
"path/filepath"
@ -932,7 +932,77 @@ func StartGroupTask(userId string, groupTask structs.GroupTasks) {
})
}
func InstallPythonDependencies(userId string, category, groupId string) {
func InstallGlobalPythonPackages(userId string) {
logger.AddGroupTasksLog(structs.LogMessage{
Id: 13,
Type: utils.LogTypeInfo,
Messages: []structs.LogData{
{Type: "userId", Value: userId},
},
})
socketclients.BroadcastMessageToUsersWithPermission(
utils.PermissionGroupTasksInstallGlobalPythonPackages,
structs.SendSocketMessage{
Cmd: utils.SentCmdInstallingGlobalPythonPackages,
})
// check if requirements.txt exists
if _, err := os.Stat(config.Cfg.FolderPaths.GroupTasksGroups + "requirements.txt"); errors.Is(err, os.ErrNotExist) {
logger.AddGroupTasksLog(structs.LogMessage{
Id: 14,
Type: utils.LogTypeInfo,
Messages: []structs.LogData{
{Type: "error", Value: "requirements.txt not found"},
},
})
socketclients.BroadcastMessageToUsersWithPermission(
utils.PermissionGroupTasksInstallGlobalPythonPackages,
structs.SendSocketMessage{
Cmd: utils.SentCmdInstallingGlobalPythonPackagesFailed,
})
return
}
// install python dependencies
cmd := exec.Command("pip3", "install", "-r", config.Cfg.FolderPaths.GroupTasksGroups+"requirements.txt")
out, err := cmd.CombinedOutput()
if err != nil {
logger.AddGroupTasksLog(structs.LogMessage{
Id: 14,
Type: utils.LogTypeInfo,
Messages: []structs.LogData{
{Type: "error", Value: err.Error()},
},
})
socketclients.BroadcastMessageToUsersWithPermission(
utils.PermissionGroupTasksInstallGlobalPythonPackages,
structs.SendSocketMessage{
Cmd: utils.SentCmdInstallingGlobalPythonPackagesFailed,
})
return
}
logger.AddGroupTasksLog(structs.LogMessage{
Id: 15,
Type: utils.LogTypeInfo,
Messages: []structs.LogData{
{Type: "log", Value: string(out)},
},
})
socketclients.BroadcastMessageToUsersWithPermission(
utils.PermissionGroupTasksInstallGlobalPythonPackages,
structs.SendSocketMessage{
Cmd: utils.SentCmdInstallingGlobalPythonPackagesFinished,
})
}
func InstallPythonPackages(userId string, category, groupId string) {
logger.AddGroupTasksLog(structs.LogMessage{
Id: 10,
Type: utils.LogTypeInfo,
@ -951,10 +1021,12 @@ func InstallPythonDependencies(userId string, category, groupId string) {
GroupId: groupId,
}
convertedXYPermission := systempermissions.ConvertXYPermission(utils.PermissionGroupTasksOverviewXYInstallPythonPackages, category)
socketclients.BroadcastMessageToUsersWithPermission(
systempermissions.ConvertXYPermission(utils.PermissionGroupTasksOverviewXYInstallPythonDependencies, category),
convertedXYPermission,
structs.SendSocketMessage{
Cmd: utils.SentCmdInstallingPythonDependencies,
Cmd: utils.SentCmdInstallingPythonPackages,
Body: messageBody,
})
@ -971,9 +1043,9 @@ func InstallPythonDependencies(userId string, category, groupId string) {
})
socketclients.BroadcastMessageToUsersWithPermission(
systempermissions.ConvertXYPermission(utils.PermissionGroupTasksOverviewXYInstallPythonDependencies, category),
convertedXYPermission,
structs.SendSocketMessage{
Cmd: utils.SentCmdInstallingPythonDependenciesFailed,
Cmd: utils.SentCmdInstallingPythonPackagesFailed,
Body: messageBody,
})
return
@ -995,9 +1067,9 @@ func InstallPythonDependencies(userId string, category, groupId string) {
})
socketclients.BroadcastMessageToUsersWithPermission(
systempermissions.ConvertXYPermission(utils.PermissionGroupTasksOverviewXYInstallPythonDependencies, category),
convertedXYPermission,
structs.SendSocketMessage{
Cmd: utils.SentCmdInstallingPythonDependenciesFailed,
Cmd: utils.SentCmdInstallingPythonPackages,
Body: messageBody,
})
return
@ -1014,9 +1086,9 @@ func InstallPythonDependencies(userId string, category, groupId string) {
})
socketclients.BroadcastMessageToUsersWithPermission(
systempermissions.ConvertXYPermission(utils.PermissionGroupTasksOverviewXYInstallPythonDependencies, category),
convertedXYPermission,
structs.SendSocketMessage{
Cmd: utils.SentCmdInstallingPythonDependenciesFinished,
Cmd: utils.SentCmdInstallingPythonPackagesFinished,
Body: messageBody,
})
}

View File

@ -5,9 +5,9 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"janex/admin-dashboard-backend/modules/config"
"janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/modules/config"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils"
"os"
"sort"
"strconv"

View File

@ -0,0 +1,22 @@
package structs
import "time"
type Equipment struct {
Id string // stock item id of invex system
Name string
Thumbnail string // url provided by invex system
CreatedAt time.Time
UpdatedAt time.Time
}
type EquipmentDocumentation struct {
Id string // stock item id of invex system
Content string
CreatedAt time.Time
UpdatedAt time.Time
}
type ApiEquipmentParamsRequest struct {
StockItemId string `json:"stockItemId"`
}

View File

@ -1,10 +1,10 @@
package systempermissions
import (
"janex/admin-dashboard-backend/modules/cache"
"janex/admin-dashboard-backend/modules/database"
"janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/modules/cache"
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils"
"strings"
"time"

View File

@ -73,9 +73,12 @@ const (
SentCmdNewUserApiKeyCreated = 30
SentCmdDeletedUserApiKey = 31
SentCmdNewApiKeyUsageCount = 32
SentCmdInstallingPythonDependencies = 33
SentCmdInstallingPythonDependenciesFailed = 34
SentCmdInstallingPythonDependenciesFinished = 35
SentCmdInstallingPythonPackages = 33
SentCmdInstallingPythonPackagesFailed = 34
SentCmdInstallingPythonPackagesFinished = 35
SentCmdInstallingGlobalPythonPackages = 36
SentCmdInstallingGlobalPythonPackagesFailed = 37
SentCmdInstallingGlobalPythonPackagesFinished = 38
)
// commands received from web clients
@ -100,7 +103,8 @@ const (
ReceivedCmdHandleUserActionTaskStep = 18
ReceivedCmdCreateNewUserApiKey = 19
ReceivedCmdDeleteUserApiKey = 20
ReceivedCmdGroupTasksInstallPythonDependencies = 21
ReceivedCmdGroupTasksInstallPythonPackages = 21
ReceivedCmdGroupTasksInstallGlobalPythonPackages = 22
)
const (
@ -127,17 +131,23 @@ var (
"Description": "required",
"GlobalInputs": "required",
}
equipmentRules = map[string]string{
"StockItemId": "required",
}
)
const (
_equipmentDocumentation = "equipment_documentation."
PermissionEquipmentDocumentationView = _equipmentDocumentation + "view"
_groupTasks = "group_tasks."
PermissionGroupTasksOverviewXYNewTask = _groupTasks + "overview.XY.new_task"
PermissionGroupTasksOverviewXYReloadGroupConfig = _groupTasks + "overview.XY.reload_group_config"
PermissionGroupTasksOverviewXYInstallPythonDependencies = _groupTasks + "overview.XY.install_python_dependencies"
PermissionGroupTasksOverviewXYInstallPythonPackages = _groupTasks + "overview.XY.install_python_packages"
PermissionGroupTasksOverviewXYView = _groupTasks + "overview.XY.view"
PermissionGroupTasksHistory = _groupTasks + "history"
PermissionGroupTasksInstallGlobalPythonPackages = _groupTasks + "install_global_python_packages"
PermissionGroupTasksCheckingForCategoryGroupChanges = _groupTasks + "checking_for_category_group_changes"
PermissionAllUsersCreateNewUser = "all_users.create_new_user"
PermissionAllUsersActionChangeRole = "all_users.action.change_role"
PermissionAllUsersActionDeleteUser = "all_users.action.delete_user"
@ -156,7 +166,9 @@ const (
)
var SystemPermissions = []string{
PermissionEquipmentDocumentationView,
PermissionGroupTasksHistory,
PermissionGroupTasksInstallGlobalPythonPackages,
PermissionGroupTasksCheckingForCategoryGroupChanges,
PermissionAllUsersActionChangeRole,
PermissionAllUsersActionDeleteUser,
@ -174,6 +186,6 @@ var SystemPermissions = []string{
var DynamicGroupTasksPermissions = []string{
PermissionGroupTasksOverviewXYNewTask,
PermissionGroupTasksOverviewXYReloadGroupConfig,
PermissionGroupTasksOverviewXYInstallPythonDependencies,
PermissionGroupTasksOverviewXYInstallPythonPackages,
PermissionGroupTasksOverviewXYView,
}

View File

@ -1,7 +1,7 @@
package utils
import (
"janex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/structs"
"github.com/go-playground/validator/v10"
)
@ -37,4 +37,6 @@ func ValidatorInit() {
Validate.RegisterStructValidationMapRules(groupTaskRules,
structs.ApiGroupTaskRequest{})
Validate.RegisterStructValidationMapRules(equipmentRules, structs.ApiEquipmentParamsRequest{})
}

Binary file not shown.

BIN
public/swagger/favicon-16x16.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 665 B

BIN
public/swagger/favicon-32x32.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 628 B

59
public/swagger/index.css Executable file
View File

@ -0,0 +1,59 @@
html {
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 0;
background: #fafafa;
}
/* Position the navbar container inside the image */
.container {
position: absolute;
width: auto;
font-family: Arial, Helvetica, sans-serif;
margin: 65px 5px;
}
#container-versions {
margin: 110px 5px;
}
/* The navbar */
.topnav {
overflow: hidden;
background-color: #333;
border-radius: 10px;
}
.topnav:first-child {
margin-bottom: 10px;
}
/* Navbar links */
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 10px 12px;
text-decoration: none;
font-size: 14px;
}
.topnav a:hover {
opacity: 0.7;
border-bottom: 5px solid #62a03f;
}
.topnav a.active {
color: #999494;
border-bottom: 5px solid #62a03f;
}

19
public/swagger/index.html Executable file
View File

@ -0,0 +1,19 @@
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" />
<link rel="stylesheet" type="text/css" href="index.css" />
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="./swagger-ui-bundle.js" charset="UTF-8"> </script>
<script src="./swagger-ui-standalone-preset.js" charset="UTF-8"> </script>
<script src="./swagger-initializer.js" charset="UTF-8"> </script>
</body>
</html>

View File

@ -0,0 +1,79 @@
<!doctype html>
<html lang="en-US">
<head>
<title>Swagger UI: OAuth2 Redirect</title>
</head>
<body>
<script>
'use strict';
function run () {
var oauth2 = window.opener.swaggerUIRedirectOauth2;
var sentState = oauth2.state;
var redirectUrl = oauth2.redirectUrl;
var isValid, qp, arr;
if (/code|token|error/.test(window.location.hash)) {
qp = window.location.hash.substring(1).replace('?', '&');
} else {
qp = location.search.substring(1);
}
arr = qp.split("&");
arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';});
qp = qp ? JSON.parse('{' + arr.join() + '}',
function (key, value) {
return key === "" ? value : decodeURIComponent(value);
}
) : {};
isValid = qp.state === sentState;
if ((
oauth2.auth.schema.get("flow") === "accessCode" ||
oauth2.auth.schema.get("flow") === "authorizationCode" ||
oauth2.auth.schema.get("flow") === "authorization_code"
) && !oauth2.auth.code) {
if (!isValid) {
oauth2.errCb({
authId: oauth2.auth.name,
source: "auth",
level: "warning",
message: "Authorization may be unsafe, passed state was changed in server. The passed state wasn't returned from auth server."
});
}
if (qp.code) {
delete oauth2.state;
oauth2.auth.code = qp.code;
oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
} else {
let oauthErrorMsg;
if (qp.error) {
oauthErrorMsg = "["+qp.error+"]: " +
(qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
(qp.error_uri ? "More info: "+qp.error_uri : "");
}
oauth2.errCb({
authId: oauth2.auth.name,
source: "auth",
level: "error",
message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server."
});
}
} else {
oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
}
window.close();
}
if (document.readyState !== 'loading') {
run();
} else {
document.addEventListener('DOMContentLoaded', function () {
run();
});
}
</script>
</body>
</html>

View File

@ -0,0 +1,11 @@
window.onload = function() {
window.ui = SwaggerUIBundle({
url: 'swagger.json',
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
layout: "StandaloneLayout",
});
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

3
public/swagger/swagger-ui.css Executable file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

2
public/swagger/swagger-ui.js Executable file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,61 @@
{
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0",
"info": {
"title": "Janex API Documentation.",
"version": "0.0.1"
},
"host": "janex",
"basePath": "/v1",
"paths": {
"/grouptasks/start": {
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"grouptasks"
],
"summary": "Start a new group task",
"operationId": "grouptasksStart",
"parameters": [
{
"description": "You can create a new api key in your user profile",
"name": "X-Api-Key",
"in": "header"
},
{
"description": "JSON -\u003e Category str, GroupId str, Description str, GlobalInputs [{key, value}, {...}]",
"name": "body",
"in": "body"
}
],
"responses": {
"200": {
"description": "New group task created successfully"
},
"400": {
"description": "Invalid request body"
},
"401": {
"description": "No permissions"
},
"422": {
"description": "No group tasks in this category or provided global inputs incomplete"
}
}
}
}
}
}

View File

@ -0,0 +1,63 @@
package equipment
import (
"jannex/admin-dashboard-backend/modules/equipment"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log"
)
func GetEquipment(c *fiber.Ctx) error {
return c.JSON(equipment.GetEquipment())
}
func GetEquipmentDocumentation(c *fiber.Ctx) error {
var body structs.ApiEquipmentParamsRequest
if err := c.ParamsParser(&body); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(err)
}
if errValidation := utils.ValidateStruct(body); errValidation != nil {
log.Error().Msgf("Failed to validate body, err: %v", errValidation)
return c.Status(fiber.StatusBadRequest).JSON(errValidation)
}
return equipment.GetEquipmentDocumentation(body.StockItemId, c)
}
// fetching the thumbnail from the invex server and sending it back to the client
func GetEquipmentThumbnail(c *fiber.Ctx) error {
//resp, err := http.Get(equipment.Base + "/media/part_images/part_152_image.thumbnail.png")
a := fiber.AcquireAgent()
a.Add("Authorization", "Token "+equipment.ApiToken)
req := a.Request()
req.Header.SetMethod(fiber.MethodGet)
req.SetRequestURI(equipment.Base + "/media/part_images/" + c.Params("stockItemThumbnail"))
if err := a.Parse(); err != nil {
log.Error().Msgf("Failed to parse request, err: %s", err)
return c.SendStatus(fiber.StatusInternalServerError)
}
code, body, errs := a.Bytes()
log.Info().Msgf("code %d %s", code, errs)
/*
resp := fiber.AcquireResponse()
a.SetResponse(resp)
fiber.ReleaseResponse(resp)
*/
c.Set("Content-Type", "image/png")
return c.Send(body)
}

View File

@ -2,11 +2,11 @@ package grouptask
import (
"encoding/json"
"janex/admin-dashboard-backend/modules/cache"
"janex/admin-dashboard-backend/modules/grouptasks"
"janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/utils"
"janex/admin-dashboard-backend/socketclients"
"jannex/admin-dashboard-backend/modules/cache"
"jannex/admin-dashboard-backend/modules/grouptasks"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/socketclients"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log"

View File

@ -1,11 +1,11 @@
package jxscanner
import (
"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"
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/logger"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/socketclients"
"time"
"github.com/gofiber/fiber/v2"

View File

@ -1,10 +1,10 @@
package logger
import (
"janex/admin-dashboard-backend/modules/logger"
"janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/utils"
"janex/admin-dashboard-backend/socketclients"
"jannex/admin-dashboard-backend/modules/logger"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/socketclients"
"github.com/gofiber/fiber/v2"
)

View File

@ -2,11 +2,11 @@ package user
import (
"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"
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/logger"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/socketclients"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log"

View File

@ -2,12 +2,12 @@ package user
import (
"fmt"
"janex/admin-dashboard-backend/modules/config"
"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"
"jannex/admin-dashboard-backend/modules/config"
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/logger"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/socketclients"
"os"
"strings"

View File

@ -1,11 +1,11 @@
package user
import (
"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"
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/logger"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/socketclients"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log"

View File

@ -1,16 +1,16 @@
package router
import (
"janex/admin-dashboard-backend/modules/config"
"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/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"
"janex/admin-dashboard-backend/socketclients"
"jannex/admin-dashboard-backend/modules/config"
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/logger"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/routers/router/api/v1/equipment"
"jannex/admin-dashboard-backend/routers/router/api/v1/grouptask"
log "jannex/admin-dashboard-backend/routers/router/api/v1/logger"
"jannex/admin-dashboard-backend/routers/router/api/v1/user"
"jannex/admin-dashboard-backend/socketclients"
"time"
"github.com/gofiber/fiber/v2"
@ -22,24 +22,50 @@ func SetupRoutes(app *fiber.App) {
u := v1.Group("/user")
u.Post("/auth/login", user.UserLogin)
u.Delete("/auth/logout", userSessionValidation, user.UserLogout)
u.Delete("/session/:idForDeletion", userSessionValidation, user.SignOutSession)
u.Post("/avatar", userSessionValidation, user.UpdateAvatar)
u.Delete("/auth/logout", requestAccessValidation, user.UserLogout)
u.Delete("/session/:idForDeletion", requestAccessValidation, user.SignOutSession)
u.Post("/avatar", requestAccessValidation, user.UpdateAvatar)
s := v1.Group("/scanner")
s.Post("/", jxscanner.AddScanner)
s.Post("/scan", scannerSessionValidation, jxscanner.ScanResult)
s.Delete("/", scannerSessionValidation, jxscanner.DeleteScanner)
//s := v1.Group("/scanner")
//s.Post("/", jxscanner.AddScanner)
//s.Post("/scan", scannerSessionValidation, jxscanner.ScanResult)
//s.Delete("/", scannerSessionValidation, jxscanner.DeleteScanner)
l := v1.Group("/log")
l.Get("/", userSessionValidation, log.GetSystemLog)
l.Get("/", requestAccessValidation, log.GetSystemLog)
g := v1.Group("/grouptasks")
g.Post("/start", userApikeyTokenValidation, grouptask.StartGroupTask)
g.Post("/start", requestAccessValidation, grouptask.StartGroupTask)
e := v1.Group("/equipment")
// TODO: add user session validation
//e.Get("/scanned/:stockItemId", requestAccessValidation, equipment.EquipmentScanned)
e.Get("/", requestAccessValidation, equipment.GetEquipment)
e.Get("/documentation/:stockItemId", requestAccessValidation, equipment.GetEquipmentDocumentation)
// access validation here implented as it would require to implement authorization on web client side on Avatar Component
e.Get("/thumbnail/media/part_images/:stockItemThumbnail", equipment.GetEquipmentThumbnail)
app.Static("/", config.Cfg.FolderPaths.PublicStatic)
}
func requestAccessValidation(c *fiber.Ctx) error {
// user session
xAuthorization := utils.GetXAuhorizationHeader(c)
if len(xAuthorization) == utils.LenHeaderXAuthorization {
return userSessionValidation(c)
}
// api key
xApiKey := utils.GetXApiKeyHeader(c)
if len(xApiKey) == utils.LenHeaderXApiKey {
return userApikeyTokenValidation(c)
}
return c.SendStatus(fiber.StatusUnauthorized)
}
func userApikeyTokenValidation(c *fiber.Ctx) error {
xApikey := utils.GetXApiKeyHeader(c)
@ -108,6 +134,7 @@ func userSessionValidation(c *fiber.Ctx) error {
return c.Next()
}
/*
func scannerSessionValidation(c *fiber.Ctx) error {
xAuthorization := utils.GetXAuhorizationHeader(c)
@ -128,3 +155,4 @@ func scannerSessionValidation(c *fiber.Ctx) error {
return c.Next()
}
*/

View File

@ -2,12 +2,12 @@ package socketclients
import (
"encoding/base64"
"janex/admin-dashboard-backend/modules/cache"
"janex/admin-dashboard-backend/modules/database"
"janex/admin-dashboard-backend/modules/logger"
"janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/systempermissions"
"janex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/modules/cache"
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/logger"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/systempermissions"
"jannex/admin-dashboard-backend/modules/utils"
"os"
"strconv"
"time"

View File

@ -3,14 +3,14 @@ package socketserver
import (
"encoding/json"
"fmt"
"janex/admin-dashboard-backend/modules/cache"
"janex/admin-dashboard-backend/modules/database"
"janex/admin-dashboard-backend/modules/grouptasks"
"janex/admin-dashboard-backend/modules/logger"
"janex/admin-dashboard-backend/modules/structs"
"janex/admin-dashboard-backend/modules/systempermissions"
"janex/admin-dashboard-backend/modules/utils"
"janex/admin-dashboard-backend/socketclients"
"jannex/admin-dashboard-backend/modules/cache"
"jannex/admin-dashboard-backend/modules/database"
"jannex/admin-dashboard-backend/modules/grouptasks"
"jannex/admin-dashboard-backend/modules/logger"
"jannex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/systempermissions"
"jannex/admin-dashboard-backend/modules/utils"
"jannex/admin-dashboard-backend/socketclients"
"time"
"github.com/gofiber/websocket/v2"
@ -397,15 +397,22 @@ func RunHub() {
case utils.ReceivedCmdDeleteUserApiKey:
socketclients.DeleteUserApiKey(data.Conn.Locals("userId").(string), receivedMessage.Body["Id"].(string))
break
case utils.ReceivedCmdGroupTasksInstallPythonDependencies:
if !socketclients.HasXYPermission(data.Conn.Locals("userId").(string), utils.PermissionGroupTasksOverviewXYInstallPythonDependencies, receivedMessage.Body["category"].(string)) {
case utils.ReceivedCmdGroupTasksInstallPythonPackages:
if !socketclients.HasXYPermission(data.Conn.Locals("userId").(string), utils.PermissionGroupTasksOverviewXYInstallPythonPackages, receivedMessage.Body["category"].(string)) {
socketclients.SendErrorMessageNoPermissions(data.Conn.Locals("sessionId").(string))
break
}
grouptasks.InstallPythonDependencies(data.Conn.Locals("userId").(string), receivedMessage.Body["category"].(string), receivedMessage.Body["groupId"].(string))
grouptasks.InstallPythonPackages(data.Conn.Locals("userId").(string), receivedMessage.Body["category"].(string), receivedMessage.Body["groupId"].(string))
break
case utils.ReceivedCmdGroupTasksInstallGlobalPythonPackages:
if !socketclients.HasPermission(data.Conn.Locals("userId").(string), utils.PermissionGroupTasksInstallGlobalPythonPackages) {
socketclients.SendErrorMessageNoPermissions(data.Conn.Locals("sessionId").(string))
break
}
grouptasks.InstallGlobalPythonPackages(data.Conn.Locals("userId").(string))
break
default:
log.Error().Msgf("Received unknown message: %v", receivedMessage)
break

View File

@ -1,7 +1,7 @@
package socketserver
import (
"janex/admin-dashboard-backend/modules/structs"
"jannex/admin-dashboard-backend/modules/structs"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"