feat: add a CLI key for scripts to auth with API

pull/182/head
tycrek 1 year ago
parent eb5578ef9e
commit 182d674a7e
No known key found for this signature in database
GPG Key ID: FF8A54DCE404885A

@ -203,6 +203,13 @@ export const onStart = (authFile = 'auth.json') => new Promise((resolve, reject)
return await createNewUser('ass', nanoid(), true);
}
// Check if the CLI key is set
if (!json.cliKey || json.cliKey.length === 0) {
log.debug('CLI key is not set, generating new key');
json.cliKey = nanoid(32);
fs.writeJsonSync(file, json, { spaces: '\t' });
}
// Add users to the map
return json.users.forEach((user) => users.push(user));
})
@ -224,6 +231,14 @@ export const findFromToken = (token: string) => {
*/
export const verifyValidToken = (req: Request) => {
return req.headers.authorization && findFromToken(req.headers.authorization);
/**
* Verifies that the CLI key in the request matches the one in auth.json
* @since v0.14.0
*/
export const verifyCliKey = (req: Request) => {
const cliKey: string = fs.readJsonSync(path('auth.json')).cliKey;
return req.headers.authorization != null && req.headers.authorization === cliKey;
};
// todo: move inside of onStart (currently broken)

@ -5,7 +5,7 @@
*/
import { Router, Request, Response, NextFunction } from 'express';
import { findFromToken, setUserPassword, users, createNewUser } from '../auth';
import { findFromToken, setUserPassword, users, createNewUser, verifyCliKey } from '../auth';
import { log } from '../utils';
import { data } from '../data';
import { User } from '../types/auth';
@ -21,7 +21,7 @@ const RouterApi = Router();
*/
const adminAuthMiddleware = (req: Request, res: Response, next: NextFunction) => {
const user = findFromToken(req.headers.authorization ?? '');
(user && user.admin) ? next() : res.sendStatus(401);
(verifyCliKey(req) || (user && user.admin)) ? next() : res.sendStatus(401);
};
/**

@ -49,6 +49,11 @@ export interface Users {
*/
migrated?: boolean
/**
* Access key for the CLI
*/
cliKey?: string
/**
* Extra metadata. Frontends can use this to store extra data.
*/

Loading…
Cancel
Save