diff --git a/Components/UI/CopyButton/CopyButton.js b/Components/UI/CopyButton/CopyButton.js index 0079d35..b9eb0b2 100644 --- a/Components/UI/CopyButton/CopyButton.js +++ b/Components/UI/CopyButton/CopyButton.js @@ -1,7 +1,7 @@ //Lib import classes from './CopyButton.module.css'; import { useState } from 'react'; -import { IconCopy } from '@tabler/icons-react'; +import { IconChecks, IconCopy } from '@tabler/icons-react'; export default function CopyButton(props) { //State @@ -29,11 +29,26 @@ export default function CopyButton(props) { className={classes.copyButton} onClick={() => handleCopy(props.dataToCopy)} > - + {props.children} + {isCopied && props.displayIconConfirmation ? ( + + ) : ( + + )} - {isCopied ? ( - Copied ! - ) : null} + {isCopied + ? !props.displayIconConfirmation && ( + Copied ! + ) + : null} ); } diff --git a/Components/UI/CopyButton/CopyButton.module.css b/Components/UI/CopyButton/CopyButton.module.css index ab59788..c9ad029 100644 --- a/Components/UI/CopyButton/CopyButton.module.css +++ b/Components/UI/CopyButton/CopyButton.module.css @@ -4,6 +4,15 @@ border: none; background-color: transparent; cursor: pointer; + display: flex; + align-items: center; +} + +.copyButton span { + font-size: 0.95rem; + color: #6d4aff; + margin-right: 5px; + user-select: text; } .copyValid { diff --git a/Components/UI/Info/Info.js b/Components/UI/Info/Info.js index e06c0bd..a818253 100644 --- a/Components/UI/Info/Info.js +++ b/Components/UI/Info/Info.js @@ -2,5 +2,13 @@ import classes from './Info.module.css'; export default function Info(props) { - return
{props.message}
; + return ( +
+ {props.message} + {props.children} +
+ ); } diff --git a/Containers/UserSettings/Integrations/Integrations.js b/Containers/UserSettings/Integrations/Integrations.js new file mode 100644 index 0000000..7945b8d --- /dev/null +++ b/Containers/UserSettings/Integrations/Integrations.js @@ -0,0 +1,362 @@ +//Lib +import { toast } from 'react-toastify'; +import 'react-toastify/dist/ReactToastify.css'; +import classes from '../UserSettings.module.css'; +import { useEffect, useState } from 'react'; +import { useForm } from 'react-hook-form'; +import { SpinnerDotted } from 'spinners-react'; +import { v4 as uuidv4 } from 'uuid'; +import timestampConverter from '../../../helpers/functions/timestampConverter'; +import { IconTrash } from '@tabler/icons-react'; + +//Components +import Error from '../../../Components/UI/Error/Error'; +import CopyButton from '../../../Components/UI/CopyButton/CopyButton'; +import Info from '../../../Components/UI/Info/Info'; + +export default function Integrations() { + //Var + const toastOptions = { + position: 'top-right', + autoClose: 5000, + hideProgressBar: false, + closeOnClick: true, + pauseOnHover: true, + draggable: true, + progress: undefined, + }; + + const { + register, + handleSubmit, + reset, + formState: { errors, isSubmitting, isValid }, + } = useForm({ mode: 'onChange', defaultValues: { authorization: 'read' } }); + + ////State + const [isLoading, setIsLoading] = useState(false); + const [tokenList, setTokenList] = useState([]); + const [error, setError] = useState(); + const [lastGeneratedToken, setLastGeneratedToken] = useState(); + const [deletingToken, setDeletingToken] = useState(null); + + const fetchTokenList = async () => { + try { + const response = await fetch('/api/account/token-manager', { + method: 'GET', + headers: { + 'Content-type': 'application/json', + }, + }); + const tokensArray = await response.json(); + setTokenList(tokensArray); + } catch (error) { + console.log('Fetching token list failed.'); + } + }; + + ////LifeCycle + useEffect(() => { + fetchTokenList(); + }, []); + + //Form submit Handler for ADD a repo + const formSubmitHandler = async (data) => { + //Remove old error + setError(); + //Loading button on submit to avoid multiple send. + setIsLoading(true); + console.log(data); + //Generate a UUIDv4 + const token = uuidv4(); + setLastGeneratedToken({ name: data.tokenName, value: token }); + + // Post API to send the new token integration + try { + const response = await fetch('/api/account/token-manager', { + method: 'POST', + headers: { + 'Content-type': 'application/json', + }, + body: JSON.stringify({ + name: data.tokenName, + token: token, + creation: Math.floor(Date.now() / 1000), + expirition: null, + permissions: { + read: true, + write: data.authorization === 'write' ? true : false, + }, + }), + }); + const result = await response.json(); + + if (!response.ok) { + setIsLoading(false); + reset(); + toast.error(result.message, toastOptions); + setTimeout(() => setError(), 4000); + } else { + reset(); + fetchTokenList(); + setIsLoading(false); + toast.success('🔑 Token generated !', toastOptions); + } + } catch (error) { + reset(); + setIsLoading(false); + console.log(error); + toast.error( + "Can't generate your token. Contact your administrator.", + toastOptions + ); + setTimeout(() => setError(), 4000); + } + }; + + //Delete token + const deleteTokenHandler = async (tokenName) => { + try { + const response = await fetch('/api/account/token-manager', { + method: 'DELETE', + headers: { + 'Content-type': 'application/json', + }, + body: JSON.stringify({ + name: tokenName, + }), + }); + const result = await response.json(); + + if (!response.ok) { + toast.error(result.message, toastOptions); + setTimeout(() => setError(), 4000); + } else { + fetchTokenList(); + toast.success('🗑️ Token deleted !', toastOptions); + } + } catch (error) { + setIsLoading(false); + toast.error( + "Can't delete your token. Contact your administrator.", + toastOptions + ); + setTimeout(() => setError(), 4000); + } finally { + setDeletingToken(null); + } + }; + + return ( + <> +
+
+

Generate token

+
+
+
+ + +
+ + +
+ + +
+ {errors.tokenName && + errors.tokenName.type === 'maxLength' && ( + + 25 characters max. + + )} + {errors.tokenName && + errors.tokenName.type === 'pattern' && ( + + Only alphanumeric characters, dashes, and + underscores are allowed (no spaces). + + )} + {error && } +
+
+ {tokenList && tokenList.length > 0 && ( +
+
+

API Tokens

+
+
+ {tokenList + .slice() + .sort((a, b) => b.creation - a.creation) + .map((token, index) => ( +
+
+
+ {token.name} +
+
+

+ Created at: + {timestampConverter( + token.creation + )} +

+

+ Permission: +

+ {token.permissions.write + ? 'Write' + : 'Read'} +
+

+ {lastGeneratedToken && + lastGeneratedToken.name === + token.name && ( + <> +

+ + Token: + + + + { + lastGeneratedToken.value + } + + +

+ + This token will not + be shown again. + Please save it. + + + )} + {deletingToken && + deletingToken.name === + token.name && ( +
+ + +
+ )} +
+
+
+ + setDeletingToken(token) + } + /> +
+
+ ))} +
+
+ )} + + ); +} diff --git a/Containers/UserSettings/PasswordSettings/PasswordSettings.js b/Containers/UserSettings/PasswordSettings/PasswordSettings.js index 0e684ea..2efb260 100644 --- a/Containers/UserSettings/PasswordSettings/PasswordSettings.js +++ b/Containers/UserSettings/PasswordSettings/PasswordSettings.js @@ -36,7 +36,6 @@ export default function PasswordSettings(props) { //Form submit Handler for ADD a repo const formSubmitHandler = async (data) => { console.log(data); - //Remove old error setError(); //Loading button on submit to avoid multiple send. diff --git a/Containers/UserSettings/UserSettings.js b/Containers/UserSettings/UserSettings.js index d83d761..817bc8d 100644 --- a/Containers/UserSettings/UserSettings.js +++ b/Containers/UserSettings/UserSettings.js @@ -9,10 +9,12 @@ import PasswordSettings from './PasswordSettings/PasswordSettings'; import UsernameSettings from './UsernameSettings/UsernameSettings'; import EmailAlertSettings from './EmailAlertSettings/EmailAlertSettings'; import AppriseAlertSettings from './AppriseAlertSettings/AppriseAlertSettings'; +import Integrations from './Integrations/Integrations'; export default function UserSettings(props) { //States const [tab, setTab] = useState('General'); + const [displayDeleteDialog, setDisplayDeleteDialog] = useState(false); return (
@@ -48,6 +50,16 @@ export default function UserSettings(props) { > Notifications +
{tab == 'General' && ( <> @@ -62,6 +74,11 @@ export default function UserSettings(props) { )} + {tab == 'Integrations' && ( + <> + + + )} ); } diff --git a/Containers/UserSettings/UserSettings.module.css b/Containers/UserSettings/UserSettings.module.css index 6f9b393..a624377 100644 --- a/Containers/UserSettings/UserSettings.module.css +++ b/Containers/UserSettings/UserSettings.module.css @@ -47,6 +47,189 @@ width: 100%; } +/* Tokens generation */ + +.tokenGen { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + box-sizing: border-box; +} + +.tokenGen input { + flex: 1; + margin-right: 10px; +} + +.newTokenWrapper { + display: flex; + align-items: center; + background-color: #f5f5f5; + border-radius: 5px; + color: #494b7a; + outline: 1px solid #6d4aff; + box-shadow: 0 0 10px 3px rgba(110, 74, 255, 0.605); + animation: entrance ease-in 0.3s 1 normal none; + padding: 10px; + font-family: ( + --pure-material-font, + 'Roboto', + 'Segoe UI', + BlinkMacSystemFont, + system-ui + ); +} + +.tokenCardList { + min-width: 50%; +} + +.tokenCardWrapper { + display: flex; + flex-direction: row; + align-items: center; + gap: 10px; + justify-content: space-between; + margin-bottom: 20px; +} + +.tokenCard { + width: 100%; + border: 1px solid #ccc; + border-radius: 5px; + padding: 20px; + box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); +} + +.tokenCardHeader { + font-size: 1.2em; + margin-bottom: 10px; + border-bottom: 1px solid #eee; + padding-bottom: 5px; + color: #494b7a; +} + +.tokenCardBody { + font-size: 0.9em; +} + +.tokenCardBody p { + display: flex; + align-items: center; + gap: 5px; + margin: 10px 0; + color: #494b7a; +} + +.tokenCardHighlight { + animation: highlightEffect 1s ease-out forwards; +} + +@keyframes highlightEffect { + 0% { + outline: 1px solid #6d4aff; + box-shadow: 0 0 0 rgba(110, 74, 255, 0.5); /* Pas d'ombre au début */ + } + 50% { + outline: 1px solid #6d4aff; + box-shadow: 0 0 15px rgba(110, 74, 255, 0.6); /* Ombre qui s'agrandit */ + } + 100% { + outline: 1px solid transparent; /* Bordure devient transparente */ + box-shadow: 0; + } +} + +.cancelButton { + border: 0; + padding: 10px 15px; + background-color: #c1c1c1; + color: white; + margin: 5px; + border-radius: 4px; + cursor: pointer; + text-decoration: none; + font-weight: bold; + font-size: 1em; +} + +.cancelButton:hover { + border: 0; + padding: 10px 15px; + background-color: #9a9a9a; + color: white; + margin: 5px; + border-radius: 4px; + cursor: pointer; + text-decoration: none; + font-weight: bold; + font-size: 1em; +} + +.cancelButton:active { + border: 0; + padding: 10px 15px; + background-color: #9a9a9a; + color: white; + margin: 5px; + border-radius: 4px; + cursor: pointer; + text-decoration: none; + font-weight: bold; + font-size: 1em; + transform: scale(0.9); +} + +.confirmButton { + border: 0; + padding: 10px 15px; + background-color: #ff0000; + color: white; + margin: 5px; + border-radius: 4px; + cursor: pointer; + text-decoration: none; + font-weight: bold; + font-size: 1em; +} + +.confirmButton:hover { + border: 0; + padding: 10px 15px; + background-color: #ff4b4b; + color: white; + margin: 5px; + border-radius: 4px; + cursor: pointer; + text-decoration: none; + font-weight: bold; + font-size: 1em; +} + +.confirmButton:active { + border: 0; + padding: 10px 15px; + background-color: #ff4b4b; + color: white; + margin: 5px; + border-radius: 4px; + cursor: pointer; + text-decoration: none; + font-weight: bold; + font-size: 1em; + transform: scale(0.9); +} + +.permissionBadge { + border-radius: 5px; + border: 1px solid #6d4aff; + color: #6d4aff; + font-size: 0.9em; + padding: 2px 5px; + margin-right: 8px; +} + /* Forms */ .bwForm { @@ -83,6 +266,10 @@ color: #494b7a; } +.bwForm.tokenGen label { + margin-bottom: 0px; +} + .bwForm input, .bwForm textarea, .bwForm select { diff --git a/package-lock.json b/package-lock.json index 77d8510..96abd2c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,7 +21,8 @@ "react-select": "^5.8.0", "react-toastify": "^10.0.5", "spinners-react": "^1.0.7", - "swr": "^2.2.5" + "swr": "^2.2.5", + "uuid": "^10.0.0" }, "devDependencies": { "@commitlint/cli": "^19.4.0", @@ -4374,6 +4375,14 @@ } } }, + "node_modules/next-auth/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/nodemailer": { "version": "6.9.14", "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.9.14.tgz", @@ -5880,9 +5889,13 @@ } }, "node_modules/uuid": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], "bin": { "uuid": "dist/bin/uuid" } diff --git a/package.json b/package.json index 7df17fa..363f7f1 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,8 @@ "react-select": "^5.8.0", "react-toastify": "^10.0.5", "spinners-react": "^1.0.7", - "swr": "^2.2.5" + "swr": "^2.2.5", + "uuid": "^10.0.0" }, "devDependencies": { "@commitlint/cli": "^19.4.0", diff --git a/pages/api/account/token-manager.js b/pages/api/account/token-manager.js new file mode 100644 index 0000000..9b4f009 --- /dev/null +++ b/pages/api/account/token-manager.js @@ -0,0 +1,256 @@ +//Lib +import { promises as fs } from 'fs'; +import path from 'path'; +import { authOptions } from '../auth/[...nextauth]'; +import { getServerSession } from 'next-auth/next'; + +export default async function handler(req, res) { + if (req.method == 'POST') { + //Verify that the user is logged in. + const session = await getServerSession(req, res, authOptions); + if (!session) { + res.status(401).json({ message: 'You must be logged in.' }); + return; + } + + //The data we expect to receive + let { name, token, creation, expiration, permissions } = req.body; + + //Read the users file + //Find the absolute path of the json directory + const jsonDirectory = path.join(process.cwd(), '/config'); + let usersList = await fs.readFile( + jsonDirectory + '/users.json', + 'utf8' + ); + //Parse the usersList + usersList = JSON.parse(usersList); + + //1 : We check that we receive data for each variable. + if (!name || !token || !creation || !permissions) { + res.status(400).json({ message: 'A field is missing.' }); + return; + } + + //Control the data + const nameRegex = new RegExp('^[a-zA-Z0-9_-]{1,25}$'); + if (!nameRegex.test(name)) { + res.status(400).json({ message: 'Your name is not valid' }); + return; + } + + //2 : Verify that the user of the session exists + const userIndex = usersList + .map((user) => user.username) + .indexOf(session.user.name); + if (userIndex === -1) { + res.status(400).json({ message: 'User is incorrect.' }); + return; + } + const user = usersList[userIndex]; + + //3 : Check that the tokenName or tokenValue already exists + const tokenExists = + user.tokens && + user.tokens.some((existingToken) => existingToken.name === name); + if (tokenExists) { + res.status(400).json({ + message: 'A token with this name already exists.', + }); + return; + } + + //4 : Add the new token + try { + let newUsersList = usersList.map((user) => + user.username == session.user.name + ? { + ...user, + tokens: [ + ...(user.tokens || []), + { + name, + token, + creation, + expiration, + permissions, + }, + ], + } + : user + ); + //Stringify the new users list + newUsersList = JSON.stringify(newUsersList); + //Write the new JSON + await fs.writeFile( + jsonDirectory + '/users.json', + newUsersList, + (err) => { + if (err) console.log(err); + } + ); + res.status(200).json({ message: 'Successful API send' }); + } catch (error) { + //Log for backend + console.log(error); + //Log for frontend + if (error.code == 'ENOENT') { + res.status(500).json({ + status: 500, + message: 'No such file or directory', + }); + } else { + res.status(500).json({ + status: 500, + message: 'API error, contact the administrator', + }); + } + return; + } + } else if (req.method == 'GET') { + //Verify that the user is logged in. + const session = await getServerSession(req, res, authOptions); + if (!session) { + res.status(401).json({ message: 'You must be logged in.' }); + return; + } + try { + //Read the users file + //Find the absolute path of the json directory + const jsonDirectory = path.join(process.cwd(), '/config'); + let usersList = await fs.readFile( + jsonDirectory + '/users.json', + 'utf8' + ); + //Parse the usersList + usersList = JSON.parse(usersList); + + //Verify that the user of the session exists + const userIndex = usersList + .map((user) => user.username) + .indexOf(session.user.name); + if (userIndex === -1) { + res.status(400).json({ + message: + 'User is incorrect. Please, logout to update your session.', + }); + return; + } else { + //Send the token list without tokens + res.status(200).json([ + ...usersList[userIndex].tokens.map((token) => ({ + name: token.name, + creation: token.creation, + expiration: token.expiration, + permissions: token.permissions, + })), + ]); + return; + } + } catch (error) { + //Log for backend + console.log(error); + //Log for frontend + if (error.code == 'ENOENT') { + res.status(500).json({ + status: 500, + message: 'No such file or directory', + }); + } else { + res.status(500).json({ + status: 500, + message: 'API error, contact the administrator', + }); + } + return; + } + } else if (req.method == 'DELETE') { + //Verify that the user is logged in. + const session = await getServerSession(req, res, authOptions); + if (!session) { + res.status(401).json({ message: 'You must be logged in.' }); + return; + } + + //The data we expect to receive + let { name } = req.body; + + //Read the users file + //Find the absolute path of the json directory + const jsonDirectory = path.join(process.cwd(), '/config'); + let usersList = await fs.readFile( + jsonDirectory + '/users.json', + 'utf8' + ); + //Parse the usersList + usersList = JSON.parse(usersList); + + //1 : We check that we receive data for each variable. + if (!name) { + res.status(400).json({ message: 'A field is missing.' }); + return; + } + + //2 : Verify that the user of the session exists + const userIndex = usersList + .map((user) => user.username) + .indexOf(session.user.name); + if (userIndex === -1) { + res.status(400).json({ message: 'User is incorrect.' }); + return; + } + const user = usersList[userIndex]; + + //Control the data + const tokenExists = user.tokens.some( + (existingToken) => existingToken.name === name + ); + if (!tokenExists) { + res.status(400).json({ message: 'Token not found.' }); + return; + } + + //3 : Delete the token object if it exists + try { + let newUsersList = usersList.map((user) => + user.username == session.user.name + ? { + ...user, + tokens: user.tokens.filter( + (token) => token.name != name + ), + } + : user + ); + //Stringify the new users list + newUsersList = JSON.stringify(newUsersList); + //Write the new JSON + await fs.writeFile( + jsonDirectory + '/users.json', + newUsersList, + (err) => { + if (err) console.log(err); + } + ); + res.status(200).json({ message: 'Successful API send' }); + } catch (error) { + //Log for backend + console.log(error); + //Log for frontend + if (error.code == 'ENOENT') { + res.status(500).json({ + status: 500, + message: 'No such file or directory', + }); + } else { + res.status(500).json({ + status: 500, + message: 'API error, contact the administrator', + }); + } + return; + } + } else { + res.status(405).json({ message: 'Bad request on API' }); + } +}