Refactor authentication and token handling.

This commit is contained in:
Mike Cao 2022-11-08 22:58:52 -08:00
parent 1a8c7c42f4
commit 67732b9b5a
7 changed files with 50 additions and 70 deletions

View file

@ -1,32 +1,44 @@
import { ok, unauthorized, badRequest, checkPassword, createSecureToken } from 'next-basics';
import {
ok,
unauthorized,
badRequest,
checkPassword,
createSecureToken,
methodNotAllowed,
getRandomChars,
} from 'next-basics';
import { getUser } from 'queries';
import { secret } from 'lib/crypto';
import redis from 'lib/redis';
import { generateAuthToken } from 'lib/auth';
export default async (req, res) => {
const { username, password } = req.body;
if (req.method === 'POST') {
const { username, password } = req.body;
if (!username || !password) {
return badRequest(res);
}
if (!username || !password) {
return badRequest(res);
}
const user = await getUser({ username });
const user = await getUser({ username });
if (user && checkPassword(password, user.password)) {
if (redis.enabled) {
const token = generateAuthToken();
if (user && checkPassword(password, user.password)) {
if (redis.enabled) {
const key = `auth:${getRandomChars(32)}`;
await redis.set(token, user);
await redis.set(key, user);
const token = createSecureToken(key, secret());
return ok(res, { token, user });
}
const token = createSecureToken(user.id, secret());
return ok(res, { token, user });
}
const { id: userId, username, isAdmin } = user;
const token = createSecureToken({ userId, username, isAdmin }, secret());
return ok(res, { token, user });
return unauthorized(res, 'Incorrect username and/or password.');
}
return unauthorized(res);
return methodNotAllowed(res);
};