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,4 +1,4 @@
import { getRandomChars, parseSecureToken, parseToken } from 'next-basics'; import { parseSecureToken, parseToken } from 'next-basics';
import { getUser, getWebsite } from 'queries'; import { getUser, getWebsite } from 'queries';
import debug from 'debug'; import debug from 'debug';
import { SHARE_TOKEN_HEADER, TYPE_USER, TYPE_WEBSITE } from 'lib/constants'; import { SHARE_TOKEN_HEADER, TYPE_USER, TYPE_WEBSITE } from 'lib/constants';
@ -6,10 +6,6 @@ import { secret } from 'lib/crypto';
const log = debug('umami:auth'); const log = debug('umami:auth');
export function generateAuthToken() {
return `auth:${getRandomChars(32)}`;
}
export function getAuthToken(req) { export function getAuthToken(req) {
const token = req.headers.authorization; const token = req.headers.authorization;

View File

@ -1,9 +1,9 @@
import { createMiddleware, unauthorized, badRequest } from 'next-basics'; import { createMiddleware, unauthorized, badRequest, parseSecureToken } from 'next-basics';
import debug from 'debug'; import debug from 'debug';
import cors from 'cors'; import cors from 'cors';
import { findSession } from 'lib/session'; import { findSession } from 'lib/session';
import { parseAuthToken, parseShareToken, getAuthToken } from 'lib/auth'; import { parseShareToken, getAuthToken } from 'lib/auth';
import redis from 'lib/redis'; import { secret } from './crypto';
const log = debug('umami:middleware'); const log = debug('umami:middleware');
@ -22,7 +22,8 @@ export const useSession = createMiddleware(async (req, res, next) => {
}); });
export const useAuth = createMiddleware(async (req, res, next) => { export const useAuth = createMiddleware(async (req, res, next) => {
const token = redis.enabled ? await redis.get(getAuthToken(req)) : await parseAuthToken(req); const token = getAuthToken(req);
const payload = parseSecureToken(token, secret());
const shareToken = await parseShareToken(req); const shareToken = await parseShareToken(req);
if (!token && !shareToken) { if (!token && !shareToken) {
@ -30,6 +31,6 @@ export const useAuth = createMiddleware(async (req, res, next) => {
return unauthorized(res); return unauthorized(res);
} }
req.auth = { ...token, shareToken }; req.auth = { ...payload, shareToken };
next(); next();
}); });

View File

@ -9,7 +9,7 @@ let redis;
const enabled = Boolean(process.env.REDIS_URL); const enabled = Boolean(process.env.REDIS_URL);
function getClient() { function getClient() {
if (!process.env.REDIS_URL) { if (!enabled) {
return null; return null;
} }
@ -32,7 +32,11 @@ function getClient() {
async function get(key) { async function get(key) {
await connect(); await connect();
return JSON.parse(await redis.get(key)); try {
return JSON.parse(await redis.get(key));
} catch {
return null;
}
} }
async function set(key, value) { async function set(key, value) {
@ -48,8 +52,8 @@ async function del(key) {
} }
async function connect() { async function connect() {
if (!redis) { if (!redis && enabled) {
redis = process.env.REDIS_URL && (global[REDIS] || getClient()); redis = global[REDIS] || getClient();
} }
return redis; return redis;

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 { getUser } from 'queries';
import { secret } from 'lib/crypto'; import { secret } from 'lib/crypto';
import redis from 'lib/redis'; import redis from 'lib/redis';
import { generateAuthToken } from 'lib/auth';
export default async (req, res) => { export default async (req, res) => {
const { username, password } = req.body; if (req.method === 'POST') {
const { username, password } = req.body;
if (!username || !password) { if (!username || !password) {
return badRequest(res); return badRequest(res);
} }
const user = await getUser({ username }); const user = await getUser({ username });
if (user && checkPassword(password, user.password)) { if (user && checkPassword(password, user.password)) {
if (redis.enabled) { if (redis.enabled) {
const token = generateAuthToken(); 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 }); return ok(res, { token, user });
} }
const { id: userId, username, isAdmin } = user; return unauthorized(res, 'Incorrect username and/or password.');
const token = createSecureToken({ userId, username, isAdmin }, secret());
return ok(res, { token, user });
} }
return unauthorized(res); return methodNotAllowed(res);
}; };

View File

@ -8,7 +8,7 @@ export default async (req, res) => {
if (req.method === 'POST') { if (req.method === 'POST') {
if (redis.enabled) { if (redis.enabled) {
await redis.del(`auth:${getAuthToken(req)}`); await redis.del(getAuthToken(req));
} }
return ok(res); return ok(res);

View File

@ -1,22 +1,8 @@
import { useAuth } from 'lib/middleware'; import { useAuth } from 'lib/middleware';
import { ok, unauthorized } from 'next-basics'; import { ok } from 'next-basics';
import redis from 'lib/redis';
import { secret } from 'lib/crypto';
import { getAuthToken } from 'lib/auth';
export default async (req, res) => { export default async (req, res) => {
if (redis.enabled) { await useAuth(req, res);
const token = await getAuthToken(req, secret());
const user = await redis.get(token);
return ok(res, user); return ok(res, req.auth);
} else {
await useAuth(req, res);
if (req.auth) {
return ok(res, req.auth);
}
}
return unauthorized(res);
}; };

View File

@ -1,38 +1,19 @@
import { useEffect } from 'react'; import { useEffect } from 'react';
import debug from 'debug';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import { setItem } from 'next-basics'; import { setItem } from 'next-basics';
import { AUTH_TOKEN } from 'lib/constants'; import { AUTH_TOKEN } from 'lib/constants';
import useApi from 'hooks/useApi';
import { setUser } from 'store/app';
const log = debug('umami:sso');
export default function SingleSignOnPage() { export default function SingleSignOnPage() {
const router = useRouter(); const router = useRouter();
const { get } = useApi();
const { token, url } = router.query; const { token, url } = router.query;
useEffect(() => { useEffect(() => {
async function verify() { if (url && token) {
setItem(AUTH_TOKEN, token); setItem(AUTH_TOKEN, token);
const { ok, data } = await get('/auth/verify'); router.push(url);
if (ok) {
log(data);
setUser(data);
if (url) {
await router.push(url);
}
}
} }
}, [url, token]);
if (token) {
verify();
}
}, [token]);
return null; return null;
} }