Fix Website auth.

This commit is contained in:
Brian Cao 2022-11-18 18:49:58 -08:00
parent 1af93a17a3
commit e28ee6597a
23 changed files with 108 additions and 105 deletions

View file

@ -1,8 +1,9 @@
import { parseSecureToken, parseToken } from 'next-basics';
import { getUser, getWebsite } from 'queries';
import debug from 'debug';
import { SHARE_TOKEN_HEADER, TYPE_USER, TYPE_WEBSITE } from 'lib/constants';
import { NextApiRequestAuth } from 'interface/api/nextApi';
import { SHARE_TOKEN_HEADER, UmamiApi } from 'lib/constants';
import { secret } from 'lib/crypto';
import { parseSecureToken, parseToken } from 'next-basics';
import { getUser, getUserWebsite } from 'queries';
const log = debug('umami:auth');
@ -47,30 +48,38 @@ export function isValidToken(token, validation) {
return false;
}
export async function allowQuery(req, type) {
const { id } = req.query;
export async function allowQuery(
req: NextApiRequestAuth,
type: UmamiApi.AuthType,
typeId?: string,
) {
const { id } = req.query as { id: string };
const { user, shareToken } = req.auth;
if (user?.isAdmin) {
return true;
}
if (shareToken) {
return isValidToken(shareToken, { id });
}
if (user?.id) {
if (type === TYPE_WEBSITE) {
const website = await getWebsite({ id });
if (type === UmamiApi.AuthType.Website) {
const userWebsite = await getUserWebsite({
userId: user.id,
websiteId: typeId ?? id,
isDeleted: false,
});
return website && website.userId === user.id;
} else if (type === TYPE_USER) {
return userWebsite;
} else if (type === UmamiApi.AuthType.User) {
const user = await getUser({ id });
return user && user.id === id;
}
}
if (user?.isAdmin) {
return true;
}
return false;
}

View file

@ -1,5 +1,6 @@
import { getWebsite, getUser, getSession } from '../queries';
import redis, { DELETED } from 'lib/redis';
import { Role, Team, TeamUser, User, UserRole, UserWebsite, Website } from '@prisma/client';
async function fetchObject(key, query) {
const obj = await redis.get(key);
@ -40,8 +41,14 @@ async function deleteWebsite(id) {
return deleteObject(`website:${id}`);
}
async function fetchUser(id) {
return fetchObject(`user:${id}`, () => getUser({ id }));
async function fetchUser(id): Promise<
User & {
userRole?: (UserRole & { role: Role })[];
teamUser?: (TeamUser & { team: Team })[];
userWebsite?: (UserWebsite & { website: Website })[];
}
> {
return fetchObject(`user:${id}`, () => getUser({ id }, true));
}
async function storeUser(data) {

View file

@ -1,3 +1,15 @@
/* eslint-disable no-unused-vars */
export namespace UmamiApi {
export enum EventType {
Pageview = 1,
Event = 2,
}
export enum AuthType {
Website,
User,
}
}
export const CURRENT_VERSION = process.env.currentVersion;
export const AUTH_TOKEN = 'umami.auth';
export const LOCALE_CONFIG = 'umami.locale';

View file

@ -1,7 +0,0 @@
/* eslint-disable no-unused-vars */
export namespace UmamiApi {
export enum EventType {
Pageview = 1,
Event = 2,
}
}