Fetch user inside useAuth.

This commit is contained in:
Mike Cao 2022-11-09 06:40:36 -08:00
parent 1bce4f2174
commit 3b705e6cb4
2 changed files with 17 additions and 4 deletions

View File

@ -48,7 +48,11 @@ export function isValidToken(token, validation) {
export async function allowQuery(req, type) {
const { id } = req.query;
const { userId, isAdmin, shareToken } = req.auth ?? {};
const {
user: { id: userId },
isAdmin,
shareToken,
} = req.auth ?? {};
if (isAdmin) {
return true;

View File

@ -4,6 +4,8 @@ import cors from 'cors';
import { findSession } from 'lib/session';
import { parseShareToken, getAuthToken } from 'lib/auth';
import { secret } from './crypto';
import redis from 'lib/redis';
import { getUser } from '../queries';
const log = debug('umami:middleware');
@ -23,14 +25,21 @@ export const useSession = createMiddleware(async (req, res, next) => {
export const useAuth = createMiddleware(async (req, res, next) => {
const token = getAuthToken(req);
const payload = parseSecureToken(token, secret());
const key = parseSecureToken(token, secret());
const shareToken = await parseShareToken(req);
if (!token && !shareToken) {
let user;
if (redis.enabled) {
user = await redis.get(key);
} else {
user = await getUser({ id: key });
}
if (!user && !shareToken) {
log('useAuth:user-not-authorized');
return unauthorized(res);
}
req.auth = { ...payload, shareToken };
req.auth = { user, token, shareToken, key };
next();
});