Skip to content

Commit

Permalink
updated setConfig validations
Browse files Browse the repository at this point in the history
  • Loading branch information
d02ev committed Dec 14, 2024
1 parent 6247039 commit df26b0c
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 35 deletions.
36 changes: 9 additions & 27 deletions backend/src/controllers/team.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ const TeamService = require("../service/team.service");
const { internalServerError } = require("../utils/errors.helper");
const { MAX_ORG_NAME_LENGTH, ORG_NAME_REGEX, VALID_URL_REGEX } = require('../utils/constants.helper');
const db = require("../models");
const { encryptApiKey, decryptApiKey, validateServerUrl } = require("../utils/team.helper");
const { decryptApiKey, encryptApiKey } = require("../utils/team.helper");
const { validationResult } = require("express-validator");

const Team = db.Team;
const teamService = new TeamService();
Expand Down Expand Up @@ -121,35 +122,16 @@ const updateTeamDetails = async (req, res) => {
};

const setConfig = async (req, res) => {
let { serverUrl, apiKey } = req.body;
if (!apiKey || typeof apiKey !== "string" || apiKey.trim().length === 0) {
return res.status(400).json({ message: 'API Key is required and should be a non-empty string' });
}

serverUrl = serverUrl && serverUrl !== "" ? serverUrl.trim() : serverUrl;
apiKey = apiKey.trim();
const encryptedApiKey = encryptApiKey(apiKey);

if (serverUrl) {
const result = validateServerUrl(serverUrl);

if (!result.valid) {
return res.status(400).json({ message: result.errors });
}
}
const validationErrors = validationResult(req);

if (serverUrl && serverUrl !== "") {
try {
const url = new URL(serverUrl);
if (url.username || url.password) {
throw new Error('URL cannot contain credentials');
}
} catch (err) {
return res.status(400).json({ message: 'Invalid server URL format.' });
}
if (!validationErrors.isEmpty()) {
return res.status(400).json({ errors: validationErrors.array() });
}

try {
const { serverUrl, apiKey } = req.body;
const encryptedApiKey = encryptApiKey(apiKey);

await teamService.addServerUrlAndApiKey(serverUrl, encryptedApiKey);
return res.status(200).json({ message: "Server URL and API Key Set Successfully" });
} catch (err) {
Expand Down Expand Up @@ -190,4 +172,4 @@ const changeRole = async (req, res) => {
}
}

module.exports = { setOrganisation, getTeamDetails, getServerUrlAndApiKey, updateTeamDetails, removeMember, changeRole, getTeamCount, setConfig };
module.exports = { setOrganisation, getTeamDetails, getServerUrlAndApiKey, updateTeamDetails, removeMember, changeRole, getTeamCount, setConfig, teamService };
3 changes: 2 additions & 1 deletion backend/src/routes/team.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const {
const authenticateJWT = require("../middleware/auth.middleware");
const accessGuard = require("../middleware/accessGuard.middleware");
const settings = require("../../config/settings");
const { validateSetConfig } = require("../utils/team.helper");

const router = express.Router();
const teamPermissions = settings.team.permissions;
Expand All @@ -28,7 +29,7 @@ router.post("/set-organisation", authenticateJWT, accessGuard(teamPermissions.se
router.post("/invite", authenticateJWT, accessGuard(teamPermissions.invite), sendTeamInvite);
router.put("/update", authenticateJWT, accessGuard(teamPermissions.update), updateTeamDetails);
router.put("/change-role", authenticateJWT, accessGuard(teamPermissions.changeRole), changeRole);
router.put('/set-config', authenticateJWT, accessGuard(teamPermissions.serverUrlAndApiKey), setConfig);
router.put('/set-config', authenticateJWT, accessGuard(teamPermissions.serverUrlAndApiKey), validateSetConfig, setConfig);

router.delete("/remove/:memberId", authenticateJWT, accessGuard(teamPermissions.removeUser), removeMember);
router.get('/get-all-invites', authenticateJWT, accessGuard(teamPermissions.removeUser), getAllInvites);
Expand Down
2 changes: 0 additions & 2 deletions backend/src/utils/constants.helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,5 @@ module.exports = Object.freeze({
ORG_NAME_REGEX: /^[a-zA-Z0-9\s\-_&.]+$/,
URL_PROTOCOL_REGEX: /^(https?:\/\/)/,
URL_DOMAIN_REGEX: /^https?:\/\/([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/,
URL_PORT_REGEX: /^https?:\/\/[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:[0-9]{1,5})?/,
URL_PATH_REGEX: /^https?:\/\/[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:[0-9]{1,5})?(\/[^\s]*)?$/
});

27 changes: 22 additions & 5 deletions backend/src/utils/team.helper.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const jwt = require('jsonwebtoken');
const { URL_PROTOCOL_REGEX, URL_DOMAIN_REGEX } = require('./constants.helper');
const { check } = require('express-validator');

require('dotenv').config();

Expand All @@ -18,10 +19,6 @@ const decryptApiKey = (apiKey) => {
const validateServerUrl = url => {
const errors = [];

if (url === "") {
return { valid: true, error: null }
}

if (!URL_PROTOCOL_REGEX.test(url)) {
errors.push("Invalid or missing protocol (must be 'http://' or 'https://').")
}
Expand All @@ -43,4 +40,24 @@ const validateServerUrl = url => {
return { valid: false, errors }
};

module.exports = { encryptApiKey, decryptApiKey, validateServerUrl };
const validateSetConfig = [
check('apiKey')
.exists().withMessage('API Key is required')
.isString().withMessage('API Key must be a string')
.trim()
.notEmpty().withMessage('API Key cannot be empty'),

check('serverUrl')
.optional()
.isString().withMessage('Server URL must be a string')
.trim()
.custom(value => {
const result = validateServerUrl(value);
if (result.valid) {
return true;
}
throw new Error(result.errors);
})
];

module.exports = { encryptApiKey, decryptApiKey, validateSetConfig };

0 comments on commit df26b0c

Please sign in to comment.