* Fixed issue with realtime page rendering.

* fix auth, add pg extension (#1596)

* Fixed change password issue. API refactoring. Closes #1592.

* Fixed account lookup.

* Fixed issue with accessing user dashboards. Closes #1590

* fix sort on dashboard (#1600)

Co-authored-by: Brian Cao <brian@umami.is>
This commit is contained in:
Mike Cao 2022-10-25 16:50:12 -07:00 committed by GitHub
parent 94dc915272
commit aceb904398
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 145 additions and 169 deletions

View File

@ -9,7 +9,7 @@ import FormLayout, {
FormRow, FormRow,
} from 'components/layout/FormLayout'; } from 'components/layout/FormLayout';
import useApi from 'hooks/useApi'; import useApi from 'hooks/useApi';
import useUser from '../../hooks/useUser'; import useUser from 'hooks/useUser';
const initialValues = { const initialValues = {
current_password: '', current_password: '',
@ -43,13 +43,13 @@ export default function ChangePasswordForm({ values, onSave, onClose }) {
const { user } = useUser(); const { user } = useUser();
const handleSubmit = async values => { const handleSubmit = async values => {
const { ok, data } = await post(`/accounts/${user.userId}/password`, values); const { ok, error } = await post(`/accounts/${user.accountUuid}/password`, values);
if (ok) { if (ok) {
onSave(); onSave();
} else { } else {
setMessage( setMessage(
data || <FormattedMessage id="message.failure" defaultMessage="Something went wrong." />, error || <FormattedMessage id="message.failure" defaultMessage="Something went wrong." />,
); );
} }
}; };

View File

@ -22,7 +22,7 @@ export const filterOptions = [
{ label: 'Count', value: 'count' }, { label: 'Count', value: 'count' },
{ label: 'Average', value: 'avg' }, { label: 'Average', value: 'avg' },
{ label: 'Minimum', value: 'min' }, { label: 'Minimum', value: 'min' },
{ label: 'Maxmimum', value: 'max' }, { label: 'Maximum', value: 'max' },
{ label: 'Sum', value: 'sum' }, { label: 'Sum', value: 'sum' },
]; ];

View File

@ -9,11 +9,14 @@ import styles from './RealtimeHeader.module.css';
export default function RealtimeHeader({ websites, data, websiteId, onSelect }) { export default function RealtimeHeader({ websites, data, websiteId, onSelect }) {
const options = [ const options = [
{ label: <FormattedMessage id="label.all-websites" defaultMessage="All websites" />, value: 0 }, {
label: <FormattedMessage id="label.all-websites" defaultMessage="All websites" />,
value: null,
},
].concat( ].concat(
websites.map(({ name, id }, index) => ({ websites.map(({ name, websiteUuid }, index) => ({
label: name, label: name,
value: id, value: websiteUuid,
divider: index === 0, divider: index === 0,
})), })),
); );

View File

@ -1,6 +1,5 @@
import { useState } from 'react'; import { useState } from 'react';
import { defineMessages, useIntl } from 'react-intl'; import { defineMessages, useIntl } from 'react-intl';
import { useRouter } from 'next/router';
import Page from 'components/layout/Page'; import Page from 'components/layout/Page';
import PageHeader from 'components/layout/PageHeader'; import PageHeader from 'components/layout/PageHeader';
import WebsiteList from 'components/pages/WebsiteList'; import WebsiteList from 'components/pages/WebsiteList';
@ -16,10 +15,7 @@ const messages = defineMessages({
more: { id: 'label.more', defaultMessage: 'More' }, more: { id: 'label.more', defaultMessage: 'More' },
}); });
export default function Dashboard() { export default function Dashboard({ userId }) {
const router = useRouter();
const { id } = router.query;
const userId = id?.[0];
const dashboard = useDashboard(); const dashboard = useDashboard();
const { showCharts, limit, editing } = dashboard; const { showCharts, limit, editing } = dashboard;
const [max, setMax] = useState(limit); const [max, setMax] = useState(limit);

View File

@ -24,7 +24,7 @@ export default function DashboardEdit({ websites }) {
const ordered = useMemo( const ordered = useMemo(
() => () =>
websites websites
.map(website => ({ ...website, order: order.indexOf(website.websiteId) })) .map(website => ({ ...website, order: order.indexOf(website.websiteUuid) }))
.sort(firstBy('order')), .sort(firstBy('order')),
[websites, order], [websites, order],
); );
@ -36,7 +36,7 @@ export default function DashboardEdit({ websites }) {
const [removed] = orderedWebsites.splice(source.index, 1); const [removed] = orderedWebsites.splice(source.index, 1);
orderedWebsites.splice(destination.index, 0, removed); orderedWebsites.splice(destination.index, 0, removed);
setOrder(orderedWebsites.map(website => website?.websiteId || 0)); setOrder(orderedWebsites.map(website => website?.websiteUuid || 0));
} }
function handleSave() { function handleSave() {
@ -76,8 +76,12 @@ export default function DashboardEdit({ websites }) {
ref={provided.innerRef} ref={provided.innerRef}
style={{ marginBottom: snapshot.isDraggingOver ? 260 : null }} style={{ marginBottom: snapshot.isDraggingOver ? 260 : null }}
> >
{ordered.map(({ websiteId, name, domain }, index) => ( {ordered.map(({ websiteUuid, name, domain }, index) => (
<Draggable key={websiteId} draggableId={`${dragId}-${websiteId}`} index={index}> <Draggable
key={websiteUuid}
draggableId={`${dragId}-${websiteUuid}`}
index={index}
>
{(provided, snapshot) => ( {(provided, snapshot) => (
<div <div
ref={provided.innerRef} ref={provided.innerRef}

View File

@ -32,7 +32,7 @@ export default function RealtimeDashboard() {
const { locale } = useLocale(); const { locale } = useLocale();
const countryNames = useCountryNames(locale); const countryNames = useCountryNames(locale);
const [data, setData] = useState(); const [data, setData] = useState();
const [websiteId, setWebsiteId] = useState(0); const [websiteUuid, setWebsiteUuid] = useState(null);
const { data: init, loading } = useFetch('/realtime/init'); const { data: init, loading } = useFetch('/realtime/init');
const { data: updates } = useFetch('/realtime/update', { const { data: updates } = useFetch('/realtime/update', {
params: { start_at: data?.timestamp }, params: { start_at: data?.timestamp },
@ -50,17 +50,18 @@ export default function RealtimeDashboard() {
if (data) { if (data) {
const { pageviews, sessions, events } = data; const { pageviews, sessions, events } = data;
if (websiteId) { if (websiteUuid) {
const { id } = init.websites.find(n => n.websiteUuid === websiteUuid);
return { return {
pageviews: filterWebsite(pageviews, websiteId), pageviews: filterWebsite(pageviews, id),
sessions: filterWebsite(sessions, websiteId), sessions: filterWebsite(sessions, id),
events: filterWebsite(events, websiteId), events: filterWebsite(events, id),
}; };
} }
} }
return data; return data;
}, [data, websiteId]); }, [data, websiteUuid]);
const countries = useMemo(() => { const countries = useMemo(() => {
if (realtimeData?.sessions) { if (realtimeData?.sessions) {
@ -117,25 +118,20 @@ export default function RealtimeDashboard() {
<Page> <Page>
<RealtimeHeader <RealtimeHeader
websites={websites} websites={websites}
websiteId={websiteId} websiteId={websiteUuid}
data={{ ...realtimeData, countries }} data={{ ...realtimeData, countries }}
onSelect={setWebsiteId} onSelect={setWebsiteUuid}
/> />
<div className={styles.chart}> <div className={styles.chart}>
<RealtimeChart <RealtimeChart data={realtimeData} unit="minute" records={REALTIME_RANGE} />
websiteId={websiteId}
data={realtimeData}
unit="minute"
records={REALTIME_RANGE}
/>
</div> </div>
<GridLayout> <GridLayout>
<GridRow> <GridRow>
<GridColumn xs={12} lg={4}> <GridColumn xs={12} lg={4}>
<RealtimeViews websiteId={websiteId} data={realtimeData} websites={websites} /> <RealtimeViews websiteId={websiteUuid} data={realtimeData} websites={websites} />
</GridColumn> </GridColumn>
<GridColumn xs={12} lg={8}> <GridColumn xs={12} lg={8}>
<RealtimeLog websiteId={websiteId} data={realtimeData} websites={websites} /> <RealtimeLog websiteId={websiteUuid} data={realtimeData} websites={websites} />
</GridColumn> </GridColumn>
</GridRow> </GridRow>
<GridRow> <GridRow>

View File

@ -29,13 +29,15 @@ export default function AccountSettings() {
const Checkmark = ({ isAdmin }) => (isAdmin ? <Icon icon={<Check />} size="medium" /> : null); const Checkmark = ({ isAdmin }) => (isAdmin ? <Icon icon={<Check />} size="medium" /> : null);
const DashboardLink = row => ( const DashboardLink = row => {
<Link href={`/dashboard/${row.userId}/${row.username}`}> return (
<a> <Link href={`/dashboard/${row.accountUuid}/${row.username}`}>
<Icon icon={<LinkIcon />} /> <a>
</a> <Icon icon={<LinkIcon />} />
</Link> </a>
); </Link>
);
};
const Buttons = row => ( const Buttons = row => (
<ButtonLayout align="right"> <ButtonLayout align="right">

View File

@ -1,3 +1,5 @@
-- CreateExtension
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- AlterTable -- AlterTable
ALTER TABLE "account" ADD COLUMN "account_uuid" UUID NULL; ALTER TABLE "account" ADD COLUMN "account_uuid" UUID NULL;

View File

@ -1,6 +1,6 @@
import { parseSecureToken, parseToken } from 'next-basics'; import { parseSecureToken, parseToken } from 'next-basics';
import { getWebsite } from 'queries'; import { getAccount, getWebsite } from 'queries';
import { SHARE_TOKEN_HEADER } from 'lib/constants'; import { SHARE_TOKEN_HEADER, TYPE_ACCOUNT, TYPE_WEBSITE } from 'lib/constants';
import { secret } from 'lib/crypto'; import { secret } from 'lib/crypto';
export function getAuthToken(req) { export function getAuthToken(req) {
@ -35,7 +35,7 @@ export function isValidToken(token, validation) {
return false; return false;
} }
export async function allowQuery(req) { export async function allowQuery(req, type) {
const { id } = req.query; const { id } = req.query;
const { userId, isAdmin, shareToken } = req.auth ?? {}; const { userId, isAdmin, shareToken } = req.auth ?? {};
@ -49,9 +49,15 @@ export async function allowQuery(req) {
} }
if (userId) { if (userId) {
const website = await getWebsite({ id }); if (type === TYPE_WEBSITE) {
const website = await getWebsite({ websiteUuid: id });
return website && website.userId === userId; return website && website.userId === userId;
} else if (type === TYPE_ACCOUNT) {
const account = await getAccount({ accountUuid: id });
return account && account.accountUuid === id;
}
} }
return false; return false;

View File

@ -21,6 +21,9 @@ export const DEFAULT_WEBSITE_LIMIT = 10;
export const REALTIME_RANGE = 30; export const REALTIME_RANGE = 30;
export const REALTIME_INTERVAL = 3000; export const REALTIME_INTERVAL = 3000;
export const TYPE_WEBSITE = 'website';
export const TYPE_ACCOUNT = 'account';
export const THEME_COLORS = { export const THEME_COLORS = {
light: { light: {
primary: '#2680eb', primary: '#2680eb',

View File

@ -4,7 +4,7 @@ import { secret, uuid } from 'lib/crypto';
import redis, { DELETED } from 'lib/redis'; import redis, { DELETED } from 'lib/redis';
import clickhouse from 'lib/clickhouse'; import clickhouse from 'lib/clickhouse';
import { getClientInfo, getJsonBody } from 'lib/request'; import { getClientInfo, getJsonBody } from 'lib/request';
import { createSession, getSessionByUuid, getWebsiteByUuid } from 'queries'; import { createSession, getSessionByUuid, getWebsite } from 'queries';
export async function getSession(req) { export async function getSession(req) {
const { payload } = getJsonBody(req); const { payload } = getJsonBody(req);
@ -38,7 +38,7 @@ export async function getSession(req) {
// Check database if does not exists in Redis // Check database if does not exists in Redis
if (!websiteId) { if (!websiteId) {
const website = await getWebsiteByUuid(websiteUuid); const website = await getWebsite({ websiteUuid });
websiteId = website ? website.id : null; websiteId = website ? website.id : null;
} }

View File

@ -1,6 +1,6 @@
{ {
"name": "umami", "name": "umami",
"version": "1.39.1", "version": "1.39.2",
"description": "A simple, fast, privacy-focused alternative to Google Analytics.", "description": "A simple, fast, privacy-focused alternative to Google Analytics.",
"author": "Mike Cao <mike@mikecao.com>", "author": "Mike Cao <mike@mikecao.com>",
"license": "MIT", "license": "MIT",

View File

@ -1,4 +1,4 @@
import { getAccountById, updateAccount } from 'queries'; import { getAccount, updateAccount } from 'queries';
import { useAuth } from 'lib/middleware'; import { useAuth } from 'lib/middleware';
import { import {
badRequest, badRequest,
@ -8,21 +8,21 @@ import {
checkPassword, checkPassword,
hashPassword, hashPassword,
} from 'next-basics'; } from 'next-basics';
import { allowQuery } from 'lib/auth';
import { TYPE_ACCOUNT } from 'lib/constants';
export default async (req, res) => { export default async (req, res) => {
await useAuth(req, res); await useAuth(req, res);
const { userId: currentUserId, isAdmin: currentUserIsAdmin } = req.auth;
const { current_password, new_password } = req.body; const { current_password, new_password } = req.body;
const { id } = req.query; const { id: accountUuid } = req.query;
const userId = +id;
if (!currentUserIsAdmin && userId !== currentUserId) { if (!(await allowQuery(req, TYPE_ACCOUNT))) {
return unauthorized(res); return unauthorized(res);
} }
if (req.method === 'POST') { if (req.method === 'POST') {
const account = await getAccountById(userId); const account = await getAccount({ accountUuid });
if (!checkPassword(current_password, account.password)) { if (!checkPassword(current_password, account.password)) {
return badRequest(res, 'Current password is incorrect'); return badRequest(res, 'Current password is incorrect');
@ -30,7 +30,7 @@ export default async (req, res) => {
const password = hashPassword(new_password); const password = hashPassword(new_password);
const updated = await updateAccount(userId, { password }); const updated = await updateAccount({ password }, { accountUuid });
return ok(res, updated); return ok(res, updated);
} }

View File

@ -1,7 +1,7 @@
import { ok, unauthorized, methodNotAllowed, badRequest, hashPassword } from 'next-basics'; import { ok, unauthorized, methodNotAllowed, badRequest, hashPassword } from 'next-basics';
import { useAuth } from 'lib/middleware'; import { useAuth } from 'lib/middleware';
import { uuid } from 'lib/crypto'; import { uuid } from 'lib/crypto';
import { createAccount, getAccountByUsername, getAccounts } from 'queries'; import { createAccount, getAccount, getAccounts } from 'queries';
export default async (req, res) => { export default async (req, res) => {
await useAuth(req, res); await useAuth(req, res);
@ -21,9 +21,9 @@ export default async (req, res) => {
if (req.method === 'POST') { if (req.method === 'POST') {
const { username, password, account_uuid } = req.body; const { username, password, account_uuid } = req.body;
const accountByUsername = await getAccountByUsername(username); const account = await getAccount({ username });
if (accountByUsername) { if (account) {
return badRequest(res, 'Account already exists'); return badRequest(res, 'Account already exists');
} }

View File

@ -1,5 +1,5 @@
import { ok, unauthorized, badRequest, checkPassword, createSecureToken } from 'next-basics'; import { ok, unauthorized, badRequest, checkPassword, createSecureToken } from 'next-basics';
import { getAccountByUsername } from 'queries/admin/account/getAccountByUsername'; import { getAccount } from 'queries';
import { secret } from 'lib/crypto'; import { secret } from 'lib/crypto';
export default async (req, res) => { export default async (req, res) => {
@ -9,7 +9,7 @@ export default async (req, res) => {
return badRequest(res); return badRequest(res);
} }
const account = await getAccountByUsername(username); const account = await getAccount({ username });
if (account && checkPassword(password, account.password)) { if (account && checkPassword(password, account.password)) {
const { id, username, isAdmin, accountUuid } = account; const { id, username, isAdmin, accountUuid } = account;

View File

@ -10,7 +10,7 @@ export default async (req, res) => {
if (req.method === 'GET') { if (req.method === 'GET') {
const { userId } = req.auth; const { userId } = req.auth;
const websites = await getUserWebsites(userId); const websites = await getUserWebsites({ userId });
const ids = websites.map(({ websiteUuid }) => websiteUuid); const ids = websites.map(({ websiteUuid }) => websiteUuid);
const token = createToken({ websites: ids }, secret()); const token = createToken({ websites: ids }, secret());
const data = await getRealtimeData(ids, subMinutes(new Date(), 30)); const data = await getRealtimeData(ids, subMinutes(new Date(), 30));

View File

@ -1,4 +1,4 @@
import { getWebsiteByShareId } from 'queries'; import { getWebsite } from 'queries';
import { ok, notFound, methodNotAllowed, createToken } from 'next-basics'; import { ok, notFound, methodNotAllowed, createToken } from 'next-basics';
import { secret } from 'lib/crypto'; import { secret } from 'lib/crypto';
@ -6,7 +6,7 @@ export default async (req, res) => {
const { id } = req.query; const { id } = req.query;
if (req.method === 'GET') { if (req.method === 'GET') {
const website = await getWebsiteByShareId(id); const website = await getWebsite({ shareId: id });
if (website) { if (website) {
const { websiteUuid } = website; const { websiteUuid } = website;

View File

@ -2,13 +2,14 @@ import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth'; import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware'; import { useAuth, useCors } from 'lib/middleware';
import { getActiveVisitors } from 'queries'; import { getActiveVisitors } from 'queries';
import { TYPE_WEBSITE } from 'lib/constants';
export default async (req, res) => { export default async (req, res) => {
await useCors(req, res); await useCors(req, res);
await useAuth(req, res); await useAuth(req, res);
if (req.method === 'GET') { if (req.method === 'GET') {
if (!(await allowQuery(req))) { if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res); return unauthorized(res);
} }

View File

@ -3,13 +3,14 @@ import { getEventData } from 'queries';
import { ok, badRequest, methodNotAllowed, unauthorized } from 'next-basics'; import { ok, badRequest, methodNotAllowed, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth'; import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware'; import { useAuth, useCors } from 'lib/middleware';
import { TYPE_WEBSITE } from 'lib/constants';
export default async (req, res) => { export default async (req, res) => {
await useCors(req, res); await useCors(req, res);
await useAuth(req, res); await useAuth(req, res);
if (req.method === 'POST') { if (req.method === 'POST') {
if (!(await allowQuery(req))) { if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res); return unauthorized(res);
} }

View File

@ -3,6 +3,7 @@ import { getEventMetrics } from 'queries';
import { ok, badRequest, methodNotAllowed, unauthorized } from 'next-basics'; import { ok, badRequest, methodNotAllowed, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth'; import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware'; import { useAuth, useCors } from 'lib/middleware';
import { TYPE_WEBSITE } from 'lib/constants';
const unitTypes = ['year', 'month', 'hour', 'day']; const unitTypes = ['year', 'month', 'hour', 'day'];
@ -11,7 +12,7 @@ export default async (req, res) => {
await useAuth(req, res); await useAuth(req, res);
if (req.method === 'GET') { if (req.method === 'GET') {
if (!(await allowQuery(req))) { if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res); return unauthorized(res);
} }

View File

@ -2,19 +2,20 @@ import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware'; import { useAuth, useCors } from 'lib/middleware';
import { getRandomChars, methodNotAllowed, ok, serverError, unauthorized } from 'next-basics'; import { getRandomChars, methodNotAllowed, ok, serverError, unauthorized } from 'next-basics';
import { deleteWebsite, getAccount, getWebsite, updateWebsite } from 'queries'; import { deleteWebsite, getAccount, getWebsite, updateWebsite } from 'queries';
import { TYPE_WEBSITE } from 'lib/constants';
export default async (req, res) => { export default async (req, res) => {
await useCors(req, res); await useCors(req, res);
await useAuth(req, res); await useAuth(req, res);
const { id: websiteId } = req.query; const { id: websiteUuid } = req.query;
if (!(await allowQuery(req))) { if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res); return unauthorized(res);
} }
if (req.method === 'GET') { if (req.method === 'GET') {
const website = await getWebsite({ websiteUuid: websiteId }); const website = await getWebsite({ websiteUuid });
return ok(res, website); return ok(res, website);
} }
@ -32,7 +33,7 @@ export default async (req, res) => {
} }
} }
const website = await getWebsite({ websiteUuid: websiteId }); const website = await getWebsite({ websiteUuid });
const newShareId = enableShareUrl ? website.shareId || getRandomChars(8) : null; const newShareId = enableShareUrl ? website.shareId || getRandomChars(8) : null;
@ -44,7 +45,7 @@ export default async (req, res) => {
shareId: shareId ? shareId : newShareId, shareId: shareId ? shareId : newShareId,
userId: account ? account.id : +owner || undefined, userId: account ? account.id : +owner || undefined,
}, },
{ websiteUuid: websiteId }, { websiteUuid },
); );
} catch (e) { } catch (e) {
if (e.message.includes('Unique constraint') && e.message.includes('share_id')) { if (e.message.includes('Unique constraint') && e.message.includes('share_id')) {
@ -56,11 +57,11 @@ export default async (req, res) => {
} }
if (req.method === 'DELETE') { if (req.method === 'DELETE') {
if (!(await allowQuery(req, true))) { if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res); return unauthorized(res);
} }
await deleteWebsite(websiteId); await deleteWebsite(websiteUuid);
return ok(res); return ok(res);
} }

View File

@ -1,8 +1,8 @@
import { allowQuery } from 'lib/auth'; import { allowQuery } from 'lib/auth';
import { FILTER_IGNORED } from 'lib/constants'; import { FILTER_IGNORED, TYPE_WEBSITE } from 'lib/constants';
import { useAuth, useCors } from 'lib/middleware'; import { useAuth, useCors } from 'lib/middleware';
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics'; import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getPageviewMetrics, getSessionMetrics, getWebsiteByUuid } from 'queries'; import { getPageviewMetrics, getSessionMetrics, getWebsite } from 'queries';
const sessionColumns = ['browser', 'os', 'device', 'screen', 'country', 'language']; const sessionColumns = ['browser', 'os', 'device', 'screen', 'country', 'language'];
const pageviewColumns = ['url', 'referrer', 'query']; const pageviewColumns = ['url', 'referrer', 'query'];
@ -38,7 +38,7 @@ export default async (req, res) => {
await useAuth(req, res); await useAuth(req, res);
if (req.method === 'GET') { if (req.method === 'GET') {
if (!(await allowQuery(req))) { if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res); return unauthorized(res);
} }
@ -94,7 +94,7 @@ export default async (req, res) => {
let domain; let domain;
if (type === 'referrer') { if (type === 'referrer') {
const website = await getWebsiteByUuid(websiteId); const website = await getWebsite({ websiteUuid: websiteId });
if (!website) { if (!website) {
return badRequest(res); return badRequest(res);

View File

@ -3,6 +3,7 @@ import { getPageviewStats } from 'queries';
import { ok, badRequest, methodNotAllowed, unauthorized } from 'next-basics'; import { ok, badRequest, methodNotAllowed, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth'; import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware'; import { useAuth, useCors } from 'lib/middleware';
import { TYPE_WEBSITE } from 'lib/constants';
const unitTypes = ['year', 'month', 'hour', 'day']; const unitTypes = ['year', 'month', 'hour', 'day'];
@ -11,7 +12,7 @@ export default async (req, res) => {
await useAuth(req, res); await useAuth(req, res);
if (req.method === 'GET') { if (req.method === 'GET') {
if (!(await allowQuery(req))) { if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res); return unauthorized(res);
} }

View File

@ -2,6 +2,7 @@ import { resetWebsite } from 'queries';
import { methodNotAllowed, ok, unauthorized } from 'next-basics'; import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth'; import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware'; import { useAuth, useCors } from 'lib/middleware';
import { TYPE_WEBSITE } from 'lib/constants';
export default async (req, res) => { export default async (req, res) => {
await useCors(req, res); await useCors(req, res);
@ -10,7 +11,7 @@ export default async (req, res) => {
const { id: websiteId } = req.query; const { id: websiteId } = req.query;
if (req.method === 'POST') { if (req.method === 'POST') {
if (!(await allowQuery(req))) { if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res); return unauthorized(res);
} }

View File

@ -2,13 +2,14 @@ import { getWebsiteStats } from 'queries';
import { methodNotAllowed, ok, unauthorized } from 'next-basics'; import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth'; import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware'; import { useAuth, useCors } from 'lib/middleware';
import { TYPE_WEBSITE } from 'lib/constants';
export default async (req, res) => { export default async (req, res) => {
await useCors(req, res); await useCors(req, res);
await useAuth(req, res); await useAuth(req, res);
if (req.method === 'GET') { if (req.method === 'GET') {
if (!(await allowQuery(req))) { if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res); return unauthorized(res);
} }

View File

@ -6,15 +6,16 @@ import { uuid } from 'lib/crypto';
export default async (req, res) => { export default async (req, res) => {
await useAuth(req, res); await useAuth(req, res);
const { userId: currentUserId, isAdmin, accountUuid } = req.auth;
const { user_id, include_all } = req.query; const { user_id, include_all } = req.query;
const { userId: currentUserId, isAdmin } = req.auth;
const accountUuid = user_id || req.auth.accountUuid;
let account; let account;
if (accountUuid) { if (accountUuid) {
account = await getAccount({ accountUuid: accountUuid }); account = await getAccount({ accountUuid });
} }
const userId = account ? account.id : +user_id; const userId = account ? account.id : user_id;
if (req.method === 'GET') { if (req.method === 'GET') {
if (userId && userId !== currentUserId && !isAdmin) { if (userId && userId !== currentUserId && !isAdmin) {
@ -24,7 +25,7 @@ export default async (req, res) => {
const websites = const websites =
isAdmin && include_all isAdmin && include_all
? await getAllWebsites() ? await getAllWebsites()
: await getUserWebsites(userId || currentUserId); : await getUserWebsites({ userId: account.id });
return ok(res, websites); return ok(res, websites);
} }

View File

@ -2,17 +2,27 @@ import React from 'react';
import Layout from 'components/layout/Layout'; import Layout from 'components/layout/Layout';
import Dashboard from 'components/pages/Dashboard'; import Dashboard from 'components/pages/Dashboard';
import useRequireLogin from 'hooks/useRequireLogin'; import useRequireLogin from 'hooks/useRequireLogin';
import { useRouter } from 'next/router';
import useUser from 'hooks/useUser';
export default function DashboardPage() { export default function DashboardPage() {
const {
query: { id },
isReady,
asPath,
} = useRouter();
const { loading } = useRequireLogin(); const { loading } = useRequireLogin();
const user = useUser();
if (loading) { if (!user || !isReady || loading) {
return null; return null;
} }
const userId = id?.[0];
return ( return (
<Layout> <Layout>
<Dashboard /> <Dashboard key={asPath} userId={user.id || userId} />
</Layout> </Layout>
); );
} }

View File

@ -1,9 +0,0 @@
import prisma from 'lib/prisma';
export async function getAccountById(userId) {
return prisma.client.account.findUnique({
where: {
id: userId,
},
});
}

View File

@ -1,9 +0,0 @@
import prisma from 'lib/prisma';
export async function getAccountByUsername(username) {
return prisma.client.account.findUnique({
where: {
username,
},
});
}

View File

@ -14,6 +14,7 @@ export async function getAccounts() {
isAdmin: true, isAdmin: true,
createdAt: true, createdAt: true,
updatedAt: true, updatedAt: true,
accountUuid: true,
}, },
}); });
} }

View File

@ -1,27 +1,24 @@
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
import redis, { DELETED } from 'lib/redis'; import redis, { DELETED } from 'lib/redis';
import { getWebsiteByUuid } from 'queries';
export async function deleteWebsite(websiteId) { export async function deleteWebsite(websiteUuid) {
const { client, transaction } = prisma; const { client, transaction } = prisma;
const { websiteUuid } = await getWebsiteByUuid(websiteId);
return transaction([ return transaction([
client.pageview.deleteMany({ client.pageview.deleteMany({
where: { session: { website: { websiteUuid: websiteId } } }, where: { session: { website: { websiteUuid } } },
}), }),
client.eventData.deleteMany({ client.eventData.deleteMany({
where: { event: { session: { website: { websiteUuid: websiteId } } } }, where: { event: { session: { website: { websiteUuid } } } },
}), }),
client.event.deleteMany({ client.event.deleteMany({
where: { session: { website: { websiteUuid: websiteId } } }, where: { session: { website: { websiteUuid } } },
}), }),
client.session.deleteMany({ client.session.deleteMany({
where: { website: { websiteUuid: websiteId } }, where: { website: { websiteUuid } },
}), }),
client.website.delete({ client.website.delete({
where: { websiteUuid: websiteId }, where: { websiteUuid },
}), }),
]).then(async res => { ]).then(async res => {
if (redis.client) { if (redis.client) {

View File

@ -1,10 +1,8 @@
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
export async function getUserWebsites(userId) { export async function getUserWebsites(where) {
return prisma.client.website.findMany({ return prisma.client.website.findMany({
where: { where,
userId,
},
orderBy: { orderBy: {
name: 'asc', name: 'asc',
}, },

View File

@ -1,7 +1,16 @@
import prisma from 'lib/prisma'; import prisma from 'lib/prisma';
import redis from 'lib/redis';
export async function getWebsite(where) { export async function getWebsite(where) {
return prisma.client.website.findUnique({ return prisma.client.website
where, .findUnique({
}); where,
})
.then(async data => {
if (redis.enabled && data) {
await redis.client.set(`website:${data.websiteUuid}`, data.id);
}
return data;
});
} }

View File

@ -1,9 +0,0 @@
import prisma from 'lib/prisma';
export async function getWebsiteById(websiteId) {
return prisma.client.website.findUnique({
where: {
id: websiteId,
},
});
}

View File

@ -1,9 +0,0 @@
import prisma from 'lib/prisma';
export async function getWebsiteByShareId(shareId) {
return prisma.client.website.findUnique({
where: {
shareId,
},
});
}

View File

@ -1,18 +0,0 @@
import prisma from 'lib/prisma';
import redis from 'lib/redis';
export async function getWebsiteByUuid(websiteUuid) {
return prisma.client.website
.findUnique({
where: {
websiteUuid,
},
})
.then(async res => {
if (redis.client && res) {
await redis.client.set(`website:${res.websiteUuid}`, res.id);
}
return res;
});
}

View File

@ -10,19 +10,19 @@ export async function getRealtimeData(websites, time) {
]); ]);
return { return {
pageviews: pageviews.map(({ pageviewId, ...props }) => ({ pageviews: pageviews.map(({ id, ...props }) => ({
__id: `p${pageviewId}`, __id: `p${id}`,
pageviewId, pageviewId: id,
...props, ...props,
})), })),
sessions: sessions.map(({ sessionId, ...props }) => ({ sessions: sessions.map(({ id, ...props }) => ({
__id: `s${sessionId}`, __id: `s${id}`,
sessionId, sessionId: id,
...props, ...props,
})), })),
events: events.map(({ eventId, ...props }) => ({ events: events.map(({ id, ...props }) => ({
__id: `e${eventId}`, __id: `e${id}`,
eventId, eventId: id,
...props, ...props,
})), })),
timestamp: Date.now(), timestamp: Date.now(),

View File

@ -1,8 +1,6 @@
export * from './admin/account/createAccount'; export * from './admin/account/createAccount';
export * from './admin/account/deleteAccount'; export * from './admin/account/deleteAccount';
export * from './admin/account/getAccount'; export * from './admin/account/getAccount';
export * from './admin/account/getAccountById';
export * from './admin/account/getAccountByUsername';
export * from './admin/account/getAccounts'; export * from './admin/account/getAccounts';
export * from './admin/account/updateAccount'; export * from './admin/account/updateAccount';
export * from './admin/website/createWebsite'; export * from './admin/website/createWebsite';
@ -10,9 +8,6 @@ export * from './admin/website/deleteWebsite';
export * from './admin/website/getAllWebsites'; export * from './admin/website/getAllWebsites';
export * from './admin/website/getUserWebsites'; export * from './admin/website/getUserWebsites';
export * from './admin/website/getWebsite'; export * from './admin/website/getWebsite';
export * from './admin/website/getWebsiteById';
export * from './admin/website/getWebsiteByShareId';
export * from './admin/website/getWebsiteByUuid';
export * from './admin/website/resetWebsite'; export * from './admin/website/resetWebsite';
export * from './admin/website/updateWebsite'; export * from './admin/website/updateWebsite';
export * from './analytics/event/getEventMetrics'; export * from './analytics/event/getEventMetrics';