Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.
TypeScript analyticsaudience-segmentationchartscohort-analysisgoogle-analyticsproduct-analyticsstatisticsuser-journeyweb-analytics
Refactor API authentication.
Mike Cao5a4fc96ebcd9
diff --git a/components/forms/AccountEditForm.js b/components/forms/AccountEditForm.jsindex 3f54b2f5c..70125656d 100644--- a/components/forms/AccountEditForm.js+++ b/components/forms/AccountEditForm.js@@ -15,13 +15,13 @@ const initialValues = {password: '',};-const validate = ({ userId, username, password }) => {+const validate = ({ id, username, password }) => {const errors = {};if (!username) {errors.username = <FormattedMessage id="label.required" defaultMessage="Required" />;}- if (!userId && !password) {+ if (!id && !password) {errors.password = <FormattedMessage id="label.required" defaultMessage="Required" />;}@@ -33,8 +33,8 @@ export default function AccountEditForm({ values, onSave, onClose }) {const [message, setMessage] = useState();const handleSubmit = async values => {- const { userId } = values;- const { ok, data } = await post(userId ? `/accounts/${userId}` : '/accounts', values);+ const { id } = values;+ const { ok, data } = await post(id ? `/accounts/${id}` : '/accounts', values);if (ok) {onSave();diff --git a/components/forms/WebsiteEditForm.js b/components/forms/WebsiteEditForm.jsindex 00cba5401..b56e21c17 100644--- a/components/forms/WebsiteEditForm.js+++ b/components/forms/WebsiteEditForm.js@@ -94,7 +94,7 @@ export default function WebsiteEditForm({ values, onSave, onClose }) {return (<FormLayout><Formik- initialValues={{ ...initialValues, ...values, enable_share_url: !!values?.shareId }}+ initialValues={{ ...initialValues, ...values, enableShareUrl: !!values?.shareId }}validate={validate}onSubmit={handleSubmit}>@@ -128,7 +128,7 @@ export default function WebsiteEditForm({ values, onSave, onClose }) {<OwnerDropDown accounts={accounts} user={user} /><FormRow><label />- <Field name="enable_share_url">+ <Field name="enableShareUrl">{({ field }) => (<Checkbox{...field}diff --git a/lib/auth.js b/lib/auth.jsindex c84f22e81..48d0b6fe9 100644--- a/lib/auth.js+++ b/lib/auth.js@@ -1,4 +1,3 @@-import { validate } from 'uuid';import { parseSecureToken, parseToken } from 'next-basics';import { getWebsite } from 'queries';import { SHARE_TOKEN_HEADER } from 'lib/constants';@@ -38,24 +37,23 @@ export function isValidToken(token, validation) {return false;}-export async function allowQuery(req, skipToken) {- const { id } = req.query;- const token = req.headers[SHARE_TOKEN_HEADER];+export async function allowQuery(req) {+ const { id: websiteId } = req.query;- const website = await getWebsite(validate(id) ? { websiteUuid: id } : { id: +id });+ const { userId, isAdmin, shareToken } = req.auth ?? {};- if (website) {- if (token && token !== 'undefined' && !skipToken) {- return isValidToken(token, { websiteId: website.id });- }+ if (isAdmin) {+ return true;+ }- const authToken = await getAuthToken(req);+ if (shareToken) {+ return isValidToken(shareToken, { websiteUuid: websiteId });+ }- if (authToken) {- const { userId, isAdmin } = authToken;+ if (userId) {+ const website = await getWebsite({ websiteUuid: websiteId });- return isAdmin || website.userId === userId;- }+ return website && website.userId === userId;}return false;diff --git a/pages/api/accounts/[id]/index.js b/pages/api/accounts/[id]/index.jsindex 716ffef76..ae5fc4344 100644--- a/pages/api/accounts/[id]/index.js+++ b/pages/api/accounts/[id]/index.js@@ -1,32 +1,31 @@import { badRequest, hashPassword, methodNotAllowed, ok, unauthorized } from 'next-basics';-import { getAccountById, deleteAccount, getAccountByUsername, updateAccount } from 'queries';+import { getAccount, deleteAccount, updateAccount } from 'queries';import { useAuth } from 'lib/middleware';export default async (req, res) => {await useAuth(req, res);- const { is_admin: currentUserIsAdmin, user_id: currentUserId } = req.auth;+ const { isAdmin, userId } = req.auth;const { id } = req.query;- const userId = +id;if (req.method === 'GET') {- if (userId !== currentUserId && !currentUserIsAdmin) {+ if (id !== userId && !isAdmin) {return unauthorized(res);}- const account = await getAccountById(userId);+ const account = await getAccount({ id: +id });return ok(res, account);}if (req.method === 'POST') {- const { username, password, is_admin } = req.body;+ const { username, password } = req.body;- if (userId !== currentUserId && !currentUserIsAdmin) {+ if (id !== userId && !isAdmin) {return unauthorized(res);}- const account = await getAccountById(userId);+ const account = await getAccount({ id: +id });const data = {};@@ -35,27 +34,26 @@ export default async (req, res) => {}// Only admin can change these fields- if (currentUserIsAdmin) {+ if (isAdmin) {data.username = username;- data.isAdmin = is_admin;}// Check when username changesif (data.username && account.username !== data.username) {- const accountByUsername = await getAccountByUsername(username);+ const accountByUsername = await getAccount({ username });if (accountByUsername) {return badRequest(res, 'Account already exists');}}- const updated = await updateAccount(userId, data);+ const updated = await updateAccount(data, { id: +id });return ok(res, updated);}if (req.method === 'DELETE') {- if (!currentUserIsAdmin) {+ if (!isAdmin) {return unauthorized(res);}diff --git a/pages/api/websites/[id]/active.js b/pages/api/websites/[id]/active.jsindex c29f97016..10e73ea85 100644--- a/pages/api/websites/[id]/active.js+++ b/pages/api/websites/[id]/active.js@@ -1,12 +1,13 @@import { methodNotAllowed, ok, unauthorized } from 'next-basics';import { allowQuery } from 'lib/auth';-import { useCors } from 'lib/middleware';+import { useAuth, useCors } from 'lib/middleware';import { getActiveVisitors } from 'queries';export default async (req, res) => {- if (req.method === 'GET') {- await useCors(req, res);+ await useCors(req, res);+ await useAuth(req, res);+ if (req.method === 'GET') {if (!(await allowQuery(req))) {return unauthorized(res);}diff --git a/pages/api/websites/[id]/events.js b/pages/api/websites/[id]/events.jsindex c1f96b2e7..192e284a5 100644--- a/pages/api/websites/[id]/events.js+++ b/pages/api/websites/[id]/events.js@@ -2,14 +2,15 @@ import moment from 'moment-timezone';import { getEventMetrics } from 'queries';import { ok, badRequest, methodNotAllowed, unauthorized } from 'next-basics';import { allowQuery } from 'lib/auth';-import { useCors } from 'lib/middleware';+import { useAuth, useCors } from 'lib/middleware';const unitTypes = ['year', 'month', 'hour', 'day'];export default async (req, res) => {- if (req.method === 'GET') {- await useCors(req, res);+ await useCors(req, res);+ await useAuth(req, res);+ if (req.method === 'GET') {if (!(await allowQuery(req))) {return unauthorized(res);}diff --git a/pages/api/websites/[id]/index.js b/pages/api/websites/[id]/index.jsindex ad55a2967..cf8d836b0 100644--- a/pages/api/websites/[id]/index.js+++ b/pages/api/websites/[id]/index.js@@ -1,47 +1,42 @@import { allowQuery } from 'lib/auth';import { useAuth, useCors } from 'lib/middleware';import { getRandomChars, methodNotAllowed, ok, unauthorized } from 'next-basics';-import { deleteWebsite, getAccount, getWebsite, getWebsiteByUuid, updateWebsite } from 'queries';+import { deleteWebsite, getAccount, getWebsite, updateWebsite } from 'queries';export default async (req, res) => {- const { id: websiteId } = req.query;+ await useCors(req, res);+ await useAuth(req, res);- if (req.method === 'GET') {- await useCors(req, res);+ const { id: websiteId } = req.query;- if (!(await allowQuery(req))) {- return unauthorized(res);- }+ if (!(await allowQuery(req))) {+ return unauthorized(res);+ }- const website = await getWebsiteByUuid(websiteId);+ if (req.method === 'GET') {+ const website = await getWebsite({ websiteUuid: websiteId });return ok(res, website);}if (req.method === 'POST') {- await useAuth(req, res);-- const { isAdmin: currentUserIsAdmin, userId: currentUserId, accountUuid } = req.auth;- const { name, domain, owner, enable_share_url } = req.body;+ const { name, domain, owner, enableShareUrl, shareId } = req.body;+ const { accountUuid } = req.auth;let account;if (accountUuid) {account = await getAccount({ accountUuid });}- const website = await getWebsite(websiteId);-- const shareId = enable_share_url ? website.shareId || getRandomChars(8) : null;+ const website = await getWebsite({ websiteUuid: websiteId });- if (website.userId !== currentUserId && !currentUserIsAdmin) {- return unauthorized(res);- }+ const newShareId = enableShareUrl ? website.shareId || getRandomChars(8) : null;await updateWebsite({name,domain,- shareId: shareId,+ shareId: shareId ? shareId : newShareId,userId: account ? account.id : +owner,},{ websiteUuid: websiteId },diff --git a/pages/api/websites/[id]/metrics.js b/pages/api/websites/[id]/metrics.jsindex 29bfdc779..e0eab028d 100644--- a/pages/api/websites/[id]/metrics.js+++ b/pages/api/websites/[id]/metrics.js@@ -1,6 +1,6 @@import { allowQuery } from 'lib/auth';import { FILTER_IGNORED } from 'lib/constants';-import { useCors } from 'lib/middleware';+import { useAuth, useCors } from 'lib/middleware';import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';import { getPageviewMetrics, getSessionMetrics, getWebsiteByUuid } from 'queries';@@ -34,9 +34,10 @@ function getColumn(type) {}export default async (req, res) => {- if (req.method === 'GET') {- await useCors(req, res);+ await useCors(req, res);+ await useAuth(req, res);+ if (req.method === 'GET') {if (!(await allowQuery(req))) {return unauthorized(res);}diff --git a/pages/api/websites/[id]/pageviews.js b/pages/api/websites/[id]/pageviews.jsindex acf7f11bc..9e05417b8 100644--- a/pages/api/websites/[id]/pageviews.js+++ b/pages/api/websites/[id]/pageviews.js@@ -2,14 +2,15 @@ import moment from 'moment-timezone';import { getPageviewStats } from 'queries';import { ok, badRequest, methodNotAllowed, unauthorized } from 'next-basics';import { allowQuery } from 'lib/auth';-import { useCors } from 'lib/middleware';+import { useAuth, useCors } from 'lib/middleware';const unitTypes = ['year', 'month', 'hour', 'day'];export default async (req, res) => {- if (req.method === 'GET') {- await useCors(req, res);+ await useCors(req, res);+ await useAuth(req, res);+ if (req.method === 'GET') {if (!(await allowQuery(req))) {return unauthorized(res);}diff --git a/pages/api/websites/[id]/reset.js b/pages/api/websites/[id]/reset.jsindex acfc9b0e3..fe527ad41 100644--- a/pages/api/websites/[id]/reset.js+++ b/pages/api/websites/[id]/reset.js@@ -1,8 +1,12 @@import { resetWebsite } from 'queries';import { methodNotAllowed, ok, unauthorized } from 'next-basics';import { allowQuery } from 'lib/auth';+import { useAuth, useCors } from 'lib/middleware';export default async (req, res) => {+ await useCors(req, res);+ await useAuth(req, res);+const { id: websiteId } = req.query;if (req.method === 'POST') {diff --git a/pages/api/websites/[id]/stats.js b/pages/api/websites/[id]/stats.jsindex c127eb0fd..596ebc90f 100644--- a/pages/api/websites/[id]/stats.js+++ b/pages/api/websites/[id]/stats.js@@ -1,12 +1,13 @@import { getWebsiteStats } from 'queries';import { methodNotAllowed, ok, unauthorized } from 'next-basics';import { allowQuery } from 'lib/auth';-import { useCors } from 'lib/middleware';+import { useAuth, useCors } from 'lib/middleware';export default async (req, res) => {- if (req.method === 'GET') {- await useCors(req, res);+ await useCors(req, res);+ await useAuth(req, res);+ if (req.method === 'GET') {if (!(await allowQuery(req))) {return unauthorized(res);}diff --git a/pages/api/websites/index.js b/pages/api/websites/index.jsindex 00385f370..9fade8c23 100644--- a/pages/api/websites/index.js+++ b/pages/api/websites/index.js@@ -30,7 +30,7 @@ export default async (req, res) => {}if (req.method === 'POST') {- const { name, domain, owner, enable_share_url } = req.body;+ const { name, domain, owner, enableShareUrl } = req.body;const website_owner = account ? account.id : +owner;@@ -39,7 +39,7 @@ export default async (req, res) => {}const websiteUuid = uuid();- const shareId = enable_share_url ? getRandomChars(8) : null;+ const shareId = enableShareUrl ? getRandomChars(8) : null;const website = await createWebsite(website_owner, { websiteUuid, name, domain, shareId });return ok(res, website);diff --git a/queries/admin/account/updateAccount.js b/queries/admin/account/updateAccount.jsindex d78485f9d..3a1cadca0 100644--- a/queries/admin/account/updateAccount.js+++ b/queries/admin/account/updateAccount.js@@ -1,10 +1,8 @@import prisma from 'lib/prisma';-export async function updateAccount(userId, data) {+export async function updateAccount(data, where) {return prisma.client.account.update({- where: {- id: userId,- },+ where,data,});}