Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
* Fixed issue with realtime page rendering.

* fix auth, add pg extension (umami-software#1596)

* Fixed change password issue. API refactoring. Closes umami-software#1592.

* Fixed account lookup.

* Fixed issue with accessing user dashboards. Closes umami-software#1590

* fix sort on dashboard (umami-software#1600)

Co-authored-by: Brian Cao <[email protected]>
  • Loading branch information
mikecao and briancao authored Oct 25, 2022
1 parent 94dc915 commit aceb904
Show file tree
Hide file tree
Showing 38 changed files with 145 additions and 169 deletions.
6 changes: 3 additions & 3 deletions components/forms/ChangePasswordForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import FormLayout, {
FormRow,
} from 'components/layout/FormLayout';
import useApi from 'hooks/useApi';
import useUser from '../../hooks/useUser';
import useUser from 'hooks/useUser';

const initialValues = {
current_password: '',
Expand Down Expand Up @@ -43,13 +43,13 @@ export default function ChangePasswordForm({ values, onSave, onClose }) {
const { user } = useUser();

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) {
onSave();
} else {
setMessage(
data || <FormattedMessage id="message.failure" defaultMessage="Something went wrong." />,
error || <FormattedMessage id="message.failure" defaultMessage="Something went wrong." />,
);
}
};
Expand Down
2 changes: 1 addition & 1 deletion components/forms/EventDataForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const filterOptions = [
{ label: 'Count', value: 'count' },
{ label: 'Average', value: 'avg' },
{ label: 'Minimum', value: 'min' },
{ label: 'Maxmimum', value: 'max' },
{ label: 'Maximum', value: 'max' },
{ label: 'Sum', value: 'sum' },
];

Expand Down
9 changes: 6 additions & 3 deletions components/metrics/RealtimeHeader.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@ import styles from './RealtimeHeader.module.css';

export default function RealtimeHeader({ websites, data, websiteId, onSelect }) {
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(
websites.map(({ name, id }, index) => ({
websites.map(({ name, websiteUuid }, index) => ({
label: name,
value: id,
value: websiteUuid,
divider: index === 0,
})),
);
Expand Down
6 changes: 1 addition & 5 deletions components/pages/Dashboard.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useState } from 'react';
import { defineMessages, useIntl } from 'react-intl';
import { useRouter } from 'next/router';
import Page from 'components/layout/Page';
import PageHeader from 'components/layout/PageHeader';
import WebsiteList from 'components/pages/WebsiteList';
Expand All @@ -16,10 +15,7 @@ const messages = defineMessages({
more: { id: 'label.more', defaultMessage: 'More' },
});

export default function Dashboard() {
const router = useRouter();
const { id } = router.query;
const userId = id?.[0];
export default function Dashboard({ userId }) {
const dashboard = useDashboard();
const { showCharts, limit, editing } = dashboard;
const [max, setMax] = useState(limit);
Expand Down
12 changes: 8 additions & 4 deletions components/pages/DashboardEdit.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default function DashboardEdit({ websites }) {
const ordered = useMemo(
() =>
websites
.map(website => ({ ...website, order: order.indexOf(website.websiteId) }))
.map(website => ({ ...website, order: order.indexOf(website.websiteUuid) }))
.sort(firstBy('order')),
[websites, order],
);
Expand All @@ -36,7 +36,7 @@ export default function DashboardEdit({ websites }) {
const [removed] = orderedWebsites.splice(source.index, 1);
orderedWebsites.splice(destination.index, 0, removed);

setOrder(orderedWebsites.map(website => website?.websiteId || 0));
setOrder(orderedWebsites.map(website => website?.websiteUuid || 0));
}

function handleSave() {
Expand Down Expand Up @@ -76,8 +76,12 @@ export default function DashboardEdit({ websites }) {
ref={provided.innerRef}
style={{ marginBottom: snapshot.isDraggingOver ? 260 : null }}
>
{ordered.map(({ websiteId, name, domain }, index) => (
<Draggable key={websiteId} draggableId={`${dragId}-${websiteId}`} index={index}>
{ordered.map(({ websiteUuid, name, domain }, index) => (
<Draggable
key={websiteUuid}
draggableId={`${dragId}-${websiteUuid}`}
index={index}
>
{(provided, snapshot) => (
<div
ref={provided.innerRef}
Expand Down
28 changes: 12 additions & 16 deletions components/pages/RealtimeDashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default function RealtimeDashboard() {
const { locale } = useLocale();
const countryNames = useCountryNames(locale);
const [data, setData] = useState();
const [websiteId, setWebsiteId] = useState(0);
const [websiteUuid, setWebsiteUuid] = useState(null);
const { data: init, loading } = useFetch('/realtime/init');
const { data: updates } = useFetch('/realtime/update', {
params: { start_at: data?.timestamp },
Expand All @@ -50,17 +50,18 @@ export default function RealtimeDashboard() {
if (data) {
const { pageviews, sessions, events } = data;

if (websiteId) {
if (websiteUuid) {
const { id } = init.websites.find(n => n.websiteUuid === websiteUuid);
return {
pageviews: filterWebsite(pageviews, websiteId),
sessions: filterWebsite(sessions, websiteId),
events: filterWebsite(events, websiteId),
pageviews: filterWebsite(pageviews, id),
sessions: filterWebsite(sessions, id),
events: filterWebsite(events, id),
};
}
}

return data;
}, [data, websiteId]);
}, [data, websiteUuid]);

const countries = useMemo(() => {
if (realtimeData?.sessions) {
Expand Down Expand Up @@ -117,25 +118,20 @@ export default function RealtimeDashboard() {
<Page>
<RealtimeHeader
websites={websites}
websiteId={websiteId}
websiteId={websiteUuid}
data={{ ...realtimeData, countries }}
onSelect={setWebsiteId}
onSelect={setWebsiteUuid}
/>
<div className={styles.chart}>
<RealtimeChart
websiteId={websiteId}
data={realtimeData}
unit="minute"
records={REALTIME_RANGE}
/>
<RealtimeChart data={realtimeData} unit="minute" records={REALTIME_RANGE} />
</div>
<GridLayout>
<GridRow>
<GridColumn xs={12} lg={4}>
<RealtimeViews websiteId={websiteId} data={realtimeData} websites={websites} />
<RealtimeViews websiteId={websiteUuid} data={realtimeData} websites={websites} />
</GridColumn>
<GridColumn xs={12} lg={8}>
<RealtimeLog websiteId={websiteId} data={realtimeData} websites={websites} />
<RealtimeLog websiteId={websiteUuid} data={realtimeData} websites={websites} />
</GridColumn>
</GridRow>
<GridRow>
Expand Down
16 changes: 9 additions & 7 deletions components/settings/AccountSettings.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@ export default function AccountSettings() {

const Checkmark = ({ isAdmin }) => (isAdmin ? <Icon icon={<Check />} size="medium" /> : null);

const DashboardLink = row => (
<Link href={`/dashboard/${row.userId}/${row.username}`}>
<a>
<Icon icon={<LinkIcon />} />
</a>
</Link>
);
const DashboardLink = row => {
return (
<Link href={`/dashboard/${row.accountUuid}/${row.username}`}>
<a>
<Icon icon={<LinkIcon />} />
</a>
</Link>
);
};

const Buttons = row => (
<ButtonLayout align="right">
Expand Down
2 changes: 2 additions & 0 deletions db/postgresql/migrations/04_add_uuid/migration.sql
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
-- CreateExtension
CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- AlterTable
ALTER TABLE "account" ADD COLUMN "account_uuid" UUID NULL;
Expand Down
16 changes: 11 additions & 5 deletions lib/auth.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { parseSecureToken, parseToken } from 'next-basics';
import { getWebsite } from 'queries';
import { SHARE_TOKEN_HEADER } from 'lib/constants';
import { getAccount, getWebsite } from 'queries';
import { SHARE_TOKEN_HEADER, TYPE_ACCOUNT, TYPE_WEBSITE } from 'lib/constants';
import { secret } from 'lib/crypto';

export function getAuthToken(req) {
Expand Down Expand Up @@ -35,7 +35,7 @@ export function isValidToken(token, validation) {
return false;
}

export async function allowQuery(req) {
export async function allowQuery(req, type) {
const { id } = req.query;

const { userId, isAdmin, shareToken } = req.auth ?? {};
Expand All @@ -49,9 +49,15 @@ export async function allowQuery(req) {
}

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;
Expand Down
3 changes: 3 additions & 0 deletions lib/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ export const DEFAULT_WEBSITE_LIMIT = 10;
export const REALTIME_RANGE = 30;
export const REALTIME_INTERVAL = 3000;

export const TYPE_WEBSITE = 'website';
export const TYPE_ACCOUNT = 'account';

export const THEME_COLORS = {
light: {
primary: '#2680eb',
Expand Down
4 changes: 2 additions & 2 deletions lib/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { secret, uuid } from 'lib/crypto';
import redis, { DELETED } from 'lib/redis';
import clickhouse from 'lib/clickhouse';
import { getClientInfo, getJsonBody } from 'lib/request';
import { createSession, getSessionByUuid, getWebsiteByUuid } from 'queries';
import { createSession, getSessionByUuid, getWebsite } from 'queries';

export async function getSession(req) {
const { payload } = getJsonBody(req);
Expand Down Expand Up @@ -38,7 +38,7 @@ export async function getSession(req) {

// Check database if does not exists in Redis
if (!websiteId) {
const website = await getWebsiteByUuid(websiteUuid);
const website = await getWebsite({ websiteUuid });
websiteId = website ? website.id : null;
}

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "umami",
"version": "1.39.1",
"version": "1.39.2",
"description": "A simple, fast, privacy-focused alternative to Google Analytics.",
"author": "Mike Cao <[email protected]>",
"license": "MIT",
Expand Down
14 changes: 7 additions & 7 deletions pages/api/accounts/[id]/password.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getAccountById, updateAccount } from 'queries';
import { getAccount, updateAccount } from 'queries';
import { useAuth } from 'lib/middleware';
import {
badRequest,
Expand All @@ -8,29 +8,29 @@ import {
checkPassword,
hashPassword,
} from 'next-basics';
import { allowQuery } from 'lib/auth';
import { TYPE_ACCOUNT } from 'lib/constants';

export default async (req, res) => {
await useAuth(req, res);

const { userId: currentUserId, isAdmin: currentUserIsAdmin } = req.auth;
const { current_password, new_password } = req.body;
const { id } = req.query;
const userId = +id;
const { id: accountUuid } = req.query;

if (!currentUserIsAdmin && userId !== currentUserId) {
if (!(await allowQuery(req, TYPE_ACCOUNT))) {
return unauthorized(res);
}

if (req.method === 'POST') {
const account = await getAccountById(userId);
const account = await getAccount({ accountUuid });

if (!checkPassword(current_password, account.password)) {
return badRequest(res, 'Current password is incorrect');
}

const password = hashPassword(new_password);

const updated = await updateAccount(userId, { password });
const updated = await updateAccount({ password }, { accountUuid });

return ok(res, updated);
}
Expand Down
6 changes: 3 additions & 3 deletions pages/api/accounts/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ok, unauthorized, methodNotAllowed, badRequest, hashPassword } from 'next-basics';
import { useAuth } from 'lib/middleware';
import { uuid } from 'lib/crypto';
import { createAccount, getAccountByUsername, getAccounts } from 'queries';
import { createAccount, getAccount, getAccounts } from 'queries';

export default async (req, res) => {
await useAuth(req, res);
Expand All @@ -21,9 +21,9 @@ export default async (req, res) => {
if (req.method === 'POST') {
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');
}

Expand Down
4 changes: 2 additions & 2 deletions pages/api/auth/login.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
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';

export default async (req, res) => {
Expand All @@ -9,7 +9,7 @@ export default async (req, res) => {
return badRequest(res);
}

const account = await getAccountByUsername(username);
const account = await getAccount({ username });

if (account && checkPassword(password, account.password)) {
const { id, username, isAdmin, accountUuid } = account;
Expand Down
2 changes: 1 addition & 1 deletion pages/api/realtime/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default async (req, res) => {
if (req.method === 'GET') {
const { userId } = req.auth;

const websites = await getUserWebsites(userId);
const websites = await getUserWebsites({ userId });
const ids = websites.map(({ websiteUuid }) => websiteUuid);
const token = createToken({ websites: ids }, secret());
const data = await getRealtimeData(ids, subMinutes(new Date(), 30));
Expand Down
4 changes: 2 additions & 2 deletions pages/api/share/[id].js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { getWebsiteByShareId } from 'queries';
import { getWebsite } from 'queries';
import { ok, notFound, methodNotAllowed, createToken } from 'next-basics';
import { secret } from 'lib/crypto';

export default async (req, res) => {
const { id } = req.query;

if (req.method === 'GET') {
const website = await getWebsiteByShareId(id);
const website = await getWebsite({ shareId: id });

if (website) {
const { websiteUuid } = website;
Expand Down
3 changes: 2 additions & 1 deletion pages/api/websites/[id]/active.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
import { getActiveVisitors } from 'queries';
import { TYPE_WEBSITE } from 'lib/constants';

export default async (req, res) => {
await useCors(req, res);
await useAuth(req, res);

if (req.method === 'GET') {
if (!(await allowQuery(req))) {
if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res);
}

Expand Down
Loading

0 comments on commit aceb904

Please sign in to comment.