mirror of
https://github.com/Ravinou/borgwarehouse
synced 2026-03-14 22:35:46 +01:00
feat: ✨ generate and manage access tokens in account settings
This commit is contained in:
parent
202e7dcef9
commit
e4d9484759
10 changed files with 879 additions and 12 deletions
|
|
@ -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)}
|
||||
>
|
||||
<IconCopy color='#65748b' stroke={1.25} size={props.size} />
|
||||
{props.children}
|
||||
{isCopied && props.displayIconConfirmation ? (
|
||||
<IconChecks
|
||||
color='#07bc0c'
|
||||
stroke={props.stroke || 1.25}
|
||||
size={props.size}
|
||||
/>
|
||||
) : (
|
||||
<IconCopy
|
||||
color='#65748b'
|
||||
stroke={props.stroke || 1.25}
|
||||
size={props.size}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
{isCopied ? (
|
||||
<span className={classes.copyValid}>Copied !</span>
|
||||
) : null}
|
||||
{isCopied
|
||||
? !props.displayIconConfirmation && (
|
||||
<span className={classes.copyValid}>Copied !</span>
|
||||
)
|
||||
: null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -2,5 +2,13 @@
|
|||
import classes from './Info.module.css';
|
||||
|
||||
export default function Info(props) {
|
||||
return <div className={classes.infoMessage}>{props.message}</div>;
|
||||
return (
|
||||
<div
|
||||
className={classes.infoMessage}
|
||||
style={{ backgroundColor: props.color }}
|
||||
>
|
||||
{props.message}
|
||||
{props.children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
362
Containers/UserSettings/Integrations/Integrations.js
Normal file
362
Containers/UserSettings/Integrations/Integrations.js
Normal file
|
|
@ -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 (
|
||||
<>
|
||||
<div className={classes.containerSetting}>
|
||||
<div className={classes.settingCategory}>
|
||||
<h2>Generate token</h2>
|
||||
</div>
|
||||
<div className={classes.setting}>
|
||||
<form
|
||||
onSubmit={handleSubmit(formSubmitHandler)}
|
||||
className={[classes.bwForm, classes.tokenGen].join(' ')}
|
||||
>
|
||||
<input
|
||||
type='text'
|
||||
placeholder='Token name'
|
||||
{...register('tokenName', {
|
||||
required: true,
|
||||
pattern: /^[a-zA-Z0-9_-]*$/,
|
||||
maxLength: 25,
|
||||
})}
|
||||
/>
|
||||
|
||||
<div className='radio-group'>
|
||||
<label style={{ marginRight: '10px' }}>
|
||||
<div style={{ display: 'flex' }}>
|
||||
<input
|
||||
{...register('authorization')}
|
||||
type='radio'
|
||||
value='read'
|
||||
/>
|
||||
<span>Read</span>
|
||||
</div>
|
||||
</label>
|
||||
<label>
|
||||
<div style={{ display: 'flex' }}>
|
||||
<input
|
||||
{...register('authorization')}
|
||||
type='radio'
|
||||
value='write'
|
||||
/>
|
||||
<span>Write</span>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button
|
||||
className={classes.AccountSettingsButton}
|
||||
disabled={!isValid || isSubmitting}
|
||||
>
|
||||
{isLoading ? (
|
||||
<SpinnerDotted
|
||||
size={20}
|
||||
thickness={150}
|
||||
speed={100}
|
||||
color='#fff'
|
||||
/>
|
||||
) : (
|
||||
'Generate'
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
{errors.tokenName &&
|
||||
errors.tokenName.type === 'maxLength' && (
|
||||
<small className={classes.errorMessage}>
|
||||
25 characters max.
|
||||
</small>
|
||||
)}
|
||||
{errors.tokenName &&
|
||||
errors.tokenName.type === 'pattern' && (
|
||||
<small className={classes.errorMessage}>
|
||||
Only alphanumeric characters, dashes, and
|
||||
underscores are allowed (no spaces).
|
||||
</small>
|
||||
)}
|
||||
{error && <Error message={error} />}
|
||||
</div>
|
||||
</div>
|
||||
{tokenList && tokenList.length > 0 && (
|
||||
<div className={classes.containerSetting}>
|
||||
<div className={classes.settingCategory}>
|
||||
<h2>API Tokens</h2>
|
||||
</div>
|
||||
<div className={classes.tokenCardList}>
|
||||
{tokenList
|
||||
.slice()
|
||||
.sort((a, b) => b.creation - a.creation)
|
||||
.map((token, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={classes.tokenCardWrapper}
|
||||
>
|
||||
<div
|
||||
className={`${classes.tokenCard} ${
|
||||
lastGeneratedToken &&
|
||||
lastGeneratedToken.name ===
|
||||
token.name
|
||||
? classes.tokenCardHighlight
|
||||
: ''
|
||||
} ${
|
||||
deletingToken &&
|
||||
deletingToken.name === token.name
|
||||
? classes.tokenCardBlurred
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
<div
|
||||
className={classes.tokenCardHeader}
|
||||
>
|
||||
{token.name}
|
||||
</div>
|
||||
<div className={classes.tokenCardBody}>
|
||||
<p>
|
||||
<strong>Created at:</strong>
|
||||
{timestampConverter(
|
||||
token.creation
|
||||
)}
|
||||
</p>
|
||||
<p>
|
||||
<strong>Permission:</strong>
|
||||
<div
|
||||
className={
|
||||
classes.permissionBadge
|
||||
}
|
||||
>
|
||||
{token.permissions.write
|
||||
? 'Write'
|
||||
: 'Read'}
|
||||
</div>
|
||||
</p>
|
||||
{lastGeneratedToken &&
|
||||
lastGeneratedToken.name ===
|
||||
token.name && (
|
||||
<>
|
||||
<p>
|
||||
<strong>
|
||||
Token:
|
||||
</strong>
|
||||
<CopyButton
|
||||
size={22}
|
||||
displayIconConfirmation={
|
||||
true
|
||||
}
|
||||
dataToCopy={
|
||||
lastGeneratedToken.value
|
||||
}
|
||||
>
|
||||
<span>
|
||||
{
|
||||
lastGeneratedToken.value
|
||||
}
|
||||
</span>
|
||||
</CopyButton>
|
||||
</p>
|
||||
<Info color='#3498db'>
|
||||
This token will not
|
||||
be shown again.
|
||||
Please save it.
|
||||
</Info>
|
||||
</>
|
||||
)}
|
||||
{deletingToken &&
|
||||
deletingToken.name ===
|
||||
token.name && (
|
||||
<div
|
||||
className={
|
||||
classes.deleteConfirmationButtons
|
||||
}
|
||||
>
|
||||
<button
|
||||
className={
|
||||
classes.confirmButton
|
||||
}
|
||||
onClick={() =>
|
||||
deleteTokenHandler(
|
||||
token.name
|
||||
)
|
||||
}
|
||||
>
|
||||
Confirm
|
||||
</button>
|
||||
<button
|
||||
className={
|
||||
classes.cancelButton
|
||||
}
|
||||
onClick={() =>
|
||||
setDeletingToken(
|
||||
null
|
||||
)
|
||||
}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className={classes.deleteToken}>
|
||||
<IconTrash
|
||||
cursor={'pointer'}
|
||||
color='#ea1313'
|
||||
strokeWidth={2}
|
||||
onClick={() =>
|
||||
setDeletingToken(token)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<div className={classes.containerSettings}>
|
||||
|
|
@ -48,6 +50,16 @@ export default function UserSettings(props) {
|
|||
>
|
||||
Notifications
|
||||
</button>
|
||||
<button
|
||||
className={
|
||||
tab == 'Integrations'
|
||||
? classes.tabListButtonActive
|
||||
: classes.tabListButton
|
||||
}
|
||||
onClick={() => setTab('Integrations')}
|
||||
>
|
||||
Integrations
|
||||
</button>
|
||||
</div>
|
||||
{tab == 'General' && (
|
||||
<>
|
||||
|
|
@ -62,6 +74,11 @@ export default function UserSettings(props) {
|
|||
<AppriseAlertSettings />
|
||||
</>
|
||||
)}
|
||||
{tab == 'Integrations' && (
|
||||
<>
|
||||
<Integrations />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
21
package-lock.json
generated
21
package-lock.json
generated
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
256
pages/api/account/token-manager.js
Normal file
256
pages/api/account/token-manager.js
Normal file
|
|
@ -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' });
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue