Merge branch 'dev' into cockroach-db

pull/1579/head
Sammy-T 2022-11-01 13:29:04 -04:00
commit f40a20f7e3
63 changed files with 2194 additions and 1132 deletions

View File

@ -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: '',
@ -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." />,
);
}
};

View File

@ -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' },
];

View File

@ -78,7 +78,7 @@ export default function WebsiteEditForm({ values, onSave, onClose }) {
const [message, setMessage] = useState();
const handleSubmit = async values => {
const { id: websiteId } = values;
const { websiteUuid: websiteId } = values;
const { ok, data } = await post(websiteId ? `/websites/${websiteId}` : '/websites', values);

View File

@ -17,7 +17,7 @@ import styles from './Header.module.css';
export default function Header() {
const { user } = useUser();
const { pathname } = useRouter();
const { updatesDisabled } = useConfig();
const { updatesDisabled, adminDisabled } = useConfig();
const isSharePage = pathname.includes('/share/');
const allowUpdate = user?.isAdmin && !updatesDisabled && !isSharePage;
@ -30,7 +30,7 @@ export default function Header() {
<Link href={isSharePage ? HOMEPAGE_URL : '/'}>umami</Link>
</div>
<HamburgerButton />
{user && (
{user && !adminDisabled && (
<div className={styles.links}>
<Link href="/dashboard">
<FormattedMessage id="label.dashboard" defaultMessage="Dashboard" />
@ -38,11 +38,9 @@ export default function Header() {
<Link href="/realtime">
<FormattedMessage id="label.realtime" defaultMessage="Realtime" />
</Link>
{!process.env.isCloudMode && (
<Link href="/settings">
<FormattedMessage id="label.settings" defaultMessage="Settings" />
</Link>
)}
<Link href="/settings">
<FormattedMessage id="label.settings" defaultMessage="Settings" />
</Link>
</div>
)}
<div className={styles.buttons}>

View File

@ -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,
})),
);

View File

@ -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';
@ -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);

View File

@ -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],
);
@ -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() {
@ -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}

View File

@ -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 },
@ -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) {
@ -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>

View File

@ -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">

View File

@ -8,10 +8,12 @@ import User from 'assets/user.svg';
import styles from './UserButton.module.css';
import { AUTH_TOKEN } from 'lib/constants';
import useUser from 'hooks/useUser';
import useConfig from 'hooks/useConfig';
export default function UserButton() {
const { user } = useUser();
const router = useRouter();
const { adminDisabled } = useConfig();
const menuOptions = [
{
@ -28,7 +30,7 @@ export default function UserButton() {
{
label: <FormattedMessage id="label.profile" defaultMessage="Profile" />,
value: 'profile',
hidden: process.env.isCloudMode,
hidden: adminDisabled,
},
{ label: <FormattedMessage id="label.logout" defaultMessage="Logout" />, value: 'logout' },
];

View File

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

View File

@ -2,7 +2,7 @@ import { useEffect } from 'react';
import useStore, { setConfig } from 'store/app';
import useApi from 'hooks/useApi';
let fetched = false;
let loading = false;
export default function useConfig() {
const { config } = useStore();
@ -10,12 +10,13 @@ export default function useConfig() {
async function loadConfig() {
const { data } = await get('/config');
loading = false;
setConfig(data);
}
useEffect(() => {
if (!config && !fetched) {
fetched = true;
if (!config && !loading) {
loading = true;
loadConfig();
}
}, []);

View File

@ -1,6 +1,8 @@
{
"label.accounts": "Konta",
"label.add-account": "Dodaj konto",
"label.add-column": "Dodaj kolumnę",
"label.add-filter": "Dodaj filtr",
"label.add-website": "Dodaj witrynę",
"label.administrator": "Administrator",
"label.all": "Wszystkie",
@ -25,6 +27,8 @@
"label.edit-account": "Edytuj konto",
"label.edit-website": "Edytuj witrynę",
"label.enable-share-url": "Włącz udostępnianie adresu URL",
"label.event-data": "Dane zdarzenia",
"label.field-name": "Nazwa pola",
"label.invalid": "Nieprawidłowy",
"label.invalid-domain": "Nieprawidłowa witryna",
"label.language": "Język",
@ -36,7 +40,7 @@
"label.more": "Więcej",
"label.name": "Nazwa",
"label.new-password": "Nowe hasło",
"label.none": "None",
"label.none": "Brak",
"label.owner": "Właściciel",
"label.password": "Hasło",
"label.passwords-dont-match": "Hasła się nie zgadzają",
@ -48,6 +52,7 @@
"label.reset": "Zresetuj",
"label.reset-website": "Zresetuj statystyki",
"label.save": "Zapisz",
"label.search": "Szukaj",
"label.settings": "Ustawienia",
"label.share-url": "Udostępnij adres URL",
"label.single-day": "W tym dniu",
@ -58,16 +63,19 @@
"label.timezone": "Strefa czasowa",
"label.today": "Dzisiaj",
"label.tracking-code": "Kod śledzenia",
"label.type": "Typ",
"label.unknown": "Nieznany",
"label.username": "Nazwa użytkownika",
"label.value": "Wartość",
"label.view-details": "Pokaż szczegóły",
"label.websites": "Witryny",
"label.yesterday": "Wczoraj",
"message.active-users": "{x} aktualnie {x, plural, one {odwiedzający} other {odwiedzających}}",
"message.confirm-delete": "Czy na pewno chcesz usunąć {target}?",
"message.confirm-reset": "Czy na pewno chcesz zresetować statystyki {target}?",
"message.copied": "Skopiowano!",
"message.delete-warning": "Wszystkie powiązane dane również zostaną usunięte.",
"message.edit-dashboard": "Edit dashboard",
"message.edit-dashboard": "Edytuj panel",
"message.failure": "Coś poszło nie tak.",
"message.get-share-url": "Uzyskaj adres URL udostępniania",
"message.get-tracking-code": "Pobierz kod śledzenia",
@ -103,7 +111,7 @@
"metrics.operating-systems": "System operacyjny",
"metrics.page-views": "Wyświetlenia strony",
"metrics.pages": "Strony",
"metrics.query-parameters": "Query parameters",
"metrics.query-parameters": "Parametry query",
"metrics.referrers": "Źródła odsyłające",
"metrics.screens": "Ekrany",
"metrics.unique-visitors": "Unikalni odwiedzający",

View File

@ -1,44 +1,47 @@
import { parseSecureToken, parseToken } from 'next-basics';
import { getWebsite } from 'queries';
import { SHARE_TOKEN_HEADER } from 'lib/constants';
import { getAccount, getWebsite } from 'queries';
import debug from 'debug';
import { SHARE_TOKEN_HEADER, TYPE_ACCOUNT, TYPE_WEBSITE } from 'lib/constants';
import { secret } from 'lib/crypto';
export function getAuthToken(req) {
const log = debug('umami:auth');
export function parseAuthToken(req) {
try {
const token = req.headers.authorization;
return parseSecureToken(token.split(' ')[1], secret());
} catch {
} catch (e) {
log(e);
return null;
}
}
export function getShareToken(req) {
export function parseShareToken(req) {
try {
return parseSecureToken(req.headers[SHARE_TOKEN_HEADER], secret());
} catch {
return parseToken(req.headers[SHARE_TOKEN_HEADER], secret());
} catch (e) {
log(e);
return null;
}
}
export function isValidToken(token, validation) {
try {
const result = parseToken(token, secret());
if (typeof validation === 'object') {
return !Object.keys(validation).find(key => result[key] !== validation[key]);
return !Object.keys(validation).find(key => token[key] !== validation[key]);
} else if (typeof validation === 'function') {
return validation(result);
return validation(token);
}
} catch (e) {
log(e);
return false;
}
return false;
}
export async function allowQuery(req) {
const { id: websiteId } = req.query;
export async function allowQuery(req, type) {
const { id } = req.query;
const { userId, isAdmin, shareToken } = req.auth ?? {};
@ -47,13 +50,19 @@ export async function allowQuery(req) {
}
if (shareToken) {
return isValidToken(shareToken, { websiteUuid: websiteId });
return isValidToken(shareToken, { id });
}
if (userId) {
const website = await getWebsite({ websiteUuid: websiteId });
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;

View File

@ -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',

View File

@ -9,11 +9,11 @@ export function secret() {
export function salt() {
const ROTATING_SALT = hash(startOfMonth(new Date()).toUTCString());
return hash([secret(), ROTATING_SALT]);
return hash(secret(), ROTATING_SALT);
}
export function uuid(...args) {
if (!args.length) return v4();
return v5(hash([...args, salt()]), v5.DNS);
return v5(hash(...args, salt()), v5.DNS);
}

View File

@ -1,7 +1,7 @@
import { createMiddleware, unauthorized, badRequest, serverError } from 'next-basics';
import cors from 'cors';
import { getSession } from './session';
import { getAuthToken, getShareToken } from './auth';
import { parseAuthToken, parseShareToken } from './auth';
export const useCors = createMiddleware(cors());
@ -26,10 +26,10 @@ export const useSession = createMiddleware(async (req, res, next) => {
});
export const useAuth = createMiddleware(async (req, res, next) => {
const token = await getAuthToken(req);
const shareToken = await getShareToken(req);
const token = await parseAuthToken(req);
const shareToken = await parseShareToken(req);
if (!token) {
if (!token && !shareToken) {
return unauthorized(res);
}

View File

@ -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);
@ -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;
}

View File

@ -1,2 +1,5 @@
[functions]
included_files = ["node_modules/.geo/**"]
[[plugins]]
package = "@netlify/plugin-nextjs"

View File

@ -36,7 +36,7 @@ module.exports = {
env: {
currentVersion: pkg.version,
isProduction: process.env.NODE_ENV === 'production',
isCloudMode: process.env.CLOUD_MODE,
uiDisabled: !!process.env.DISABLE_UI,
},
basePath: process.env.BASE_PATH,
output: 'standalone',

View File

@ -1,6 +1,6 @@
{
"name": "umami",
"version": "1.39.0-beta.1",
"version": "2.0.0-beta.1",
"description": "A simple, fast, privacy-focused alternative to Google Analytics.",
"author": "Mike Cao <mike@mikecao.com>",
"license": "MIT",
@ -56,7 +56,7 @@
},
"dependencies": {
"@fontsource/inter": "4.5.7",
"@prisma/client": "4.4.0",
"@prisma/client": "4.5.0",
"chalk": "^4.1.1",
"chart.js": "^2.9.4",
"classnames": "^2.3.1",
@ -83,8 +83,8 @@
"kafkajs": "^2.1.0",
"maxmind": "^4.3.6",
"moment-timezone": "^0.5.35",
"next": "^12.2.5",
"next-basics": "^0.18.0",
"next": "^12.3.1",
"next-basics": "^0.20.0",
"node-fetch": "^3.2.8",
"npm-run-all": "^4.1.5",
"prop-types": "^15.7.2",
@ -106,6 +106,7 @@
},
"devDependencies": {
"@formatjs/cli": "^4.2.29",
"@netlify/plugin-nextjs": "^4.27.3",
"@rollup/plugin-buble": "^0.21.3",
"@rollup/plugin-replace": "^4.0.0",
"@svgr/webpack": "^6.2.1",
@ -125,7 +126,7 @@
"postcss-preset-env": "7.4.3",
"postcss-rtlcss": "^3.6.1",
"prettier": "^2.6.2",
"prisma": "4.4.0",
"prisma": "4.5.0",
"prompts": "2.4.2",
"rollup": "^2.70.1",
"rollup-plugin-terser": "^7.0.2",

View File

@ -2,30 +2,27 @@ import Head from 'next/head';
import { useRouter } from 'next/router';
import { IntlProvider } from 'react-intl';
import useLocale from 'hooks/useLocale';
import useConfig from 'hooks/useConfig';
import 'styles/variables.css';
import 'styles/bootstrap-grid.css';
import 'styles/index.css';
import '@fontsource/inter/400.css';
import '@fontsource/inter/600.css';
const Intl = ({ children }) => {
export default function App({ Component, pageProps }) {
const { locale, messages } = useLocale();
const { basePath } = useRouter();
const { dir } = useLocale();
useConfig();
const Wrapper = ({ children }) => <span className={locale}>{children}</span>;
if (process.env.uiDisabled) {
return null;
}
return (
<IntlProvider locale={locale} messages={messages[locale]} textComponent={Wrapper}>
{children}
</IntlProvider>
);
};
export default function App({ Component, pageProps }) {
const { basePath } = useRouter();
const { dir } = useLocale();
return (
<Intl>
<Head>
<link rel="icon" href={`${basePath}/favicon.ico`} />
<link rel="apple-touch-icon" sizes="180x180" href={`${basePath}/apple-touch-icon.png`} />
@ -41,6 +38,6 @@ export default function App({ Component, pageProps }) {
<div className="container" dir={dir}>
<Component {...pageProps} />
</div>
</Intl>
</IntlProvider>
);
}

View File

@ -43,7 +43,7 @@ export default async (req, res) => {
const accountByUsername = await getAccount({ username });
if (accountByUsername) {
return badRequest(res, 'Account already exists');
return badRequest(res, 'Account already exists.');
}
}
@ -53,11 +53,15 @@ export default async (req, res) => {
}
if (req.method === 'DELETE') {
if (id === userId) {
return badRequest(res, 'You cannot delete your own account.');
}
if (!isAdmin) {
return unauthorized(res);
}
await deleteAccount(userId);
await deleteAccount(+id);
return ok(res);
}

View File

@ -1,4 +1,4 @@
import { getAccountById, updateAccount } from 'queries';
import { getAccount, updateAccount } from 'queries';
import { useAuth } from 'lib/middleware';
import {
badRequest,
@ -8,21 +8,21 @@ 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');
@ -30,7 +30,7 @@ export default async (req, res) => {
const password = hashPassword(new_password);
const updated = await updateAccount(userId, { password });
const updated = await updateAccount({ password }, { accountUuid });
return ok(res, updated);
}

View File

@ -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);
@ -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');
}

View File

@ -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) => {
@ -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;

View File

@ -7,6 +7,7 @@ export default async (req, res) => {
trackerScriptName: process.env.TRACKER_SCRIPT_NAME,
updatesDisabled: !!process.env.DISABLE_UPDATES,
telemetryDisabled: !!process.env.DISABLE_TELEMETRY,
adminDisabled: !!process.env.DISABLE_ADMIN,
});
}

View File

@ -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));

View File

@ -1,4 +1,4 @@
import { getWebsiteByShareId } from 'queries';
import { getWebsite } from 'queries';
import { ok, notFound, methodNotAllowed, createToken } from 'next-basics';
import { secret } from 'lib/crypto';
@ -6,13 +6,14 @@ 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 { websiteId, websiteUuid } = website;
const token = createToken({ websiteId, websiteUuid }, secret());
const { websiteUuid } = website;
const data = { id: websiteUuid };
const token = createToken(data, secret());
return ok(res, { websiteId, websiteUuid, token });
return ok(res, { ...data, token });
}
return notFound(res);

View File

@ -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);
}

View File

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

View File

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

View File

@ -2,19 +2,20 @@ import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
import { getRandomChars, methodNotAllowed, ok, serverError, unauthorized } from 'next-basics';
import { deleteWebsite, getAccount, getWebsite, updateWebsite } from 'queries';
import { TYPE_WEBSITE } from 'lib/constants';
export default async (req, res) => {
await useCors(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);
}
if (req.method === 'GET') {
const website = await getWebsite({ websiteUuid: websiteId });
const website = await getWebsite({ websiteUuid });
return ok(res, website);
}
@ -22,6 +23,7 @@ export default async (req, res) => {
if (req.method === 'POST') {
const { name, domain, owner, enableShareUrl, shareId } = req.body;
const { accountUuid } = req.auth;
let account;
if (accountUuid) {
@ -32,7 +34,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;
@ -42,9 +44,9 @@ export default async (req, res) => {
name,
domain,
shareId: shareId ? shareId : newShareId,
userId: account ? account.id : +owner || undefined,
userId: +owner || account.id,
},
{ websiteUuid: websiteId },
{ websiteUuid },
);
} catch (e) {
if (e.message.includes('Unique constraint') && e.message.includes('share_id')) {
@ -56,11 +58,11 @@ export default async (req, res) => {
}
if (req.method === 'DELETE') {
if (!(await allowQuery(req, true))) {
if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res);
}
await deleteWebsite(websiteId);
await deleteWebsite(websiteUuid);
return ok(res);
}

View File

@ -1,8 +1,8 @@
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 { 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 pageviewColumns = ['url', 'referrer', 'query'];
@ -38,7 +38,7 @@ export default async (req, res) => {
await useAuth(req, res);
if (req.method === 'GET') {
if (!(await allowQuery(req))) {
if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res);
}
@ -94,7 +94,7 @@ export default async (req, res) => {
let domain;
if (type === 'referrer') {
const website = await getWebsiteByUuid(websiteId);
const website = await getWebsite({ websiteUuid: websiteId });
if (!website) {
return badRequest(res);

View File

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

View File

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

View File

@ -2,13 +2,14 @@ import { getWebsiteStats } from 'queries';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
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);
}

View File

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

View File

@ -4,11 +4,11 @@ import TestConsole from 'components/pages/TestConsole';
import useRequireLogin from 'hooks/useRequireLogin';
import useUser from 'hooks/useUser';
export default function ConsolePage({ enabled }) {
export default function ConsolePage({ pageDisabled }) {
const { loading } = useRequireLogin();
const { user } = useUser();
if (loading || !enabled || !user?.isAdmin) {
if (pageDisabled || loading || !user?.isAdmin) {
return null;
}
@ -21,6 +21,8 @@ export default function ConsolePage({ enabled }) {
export async function getServerSideProps() {
return {
props: { enabled: !!process.env.ENABLE_TEST_CONSOLE },
props: {
pageDisabled: !process.env.ENABLE_TEST_CONSOLE,
},
};
}

View File

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

View File

@ -2,8 +2,8 @@ import React from 'react';
import Layout from 'components/layout/Layout';
import LoginForm from 'components/forms/LoginForm';
export default function LoginPage({ loginDisabled }) {
if (loginDisabled) {
export default function LoginPage({ pageDisabled }) {
if (pageDisabled) {
return null;
}
@ -16,6 +16,8 @@ export default function LoginPage({ loginDisabled }) {
export async function getServerSideProps() {
return {
props: { loginDisabled: !!process.env.DISABLE_LOGIN || !!process.env.isCloudMode },
props: {
pageDisabled: !!process.env.DISABLE_LOGIN,
},
};
}

View File

@ -2,11 +2,13 @@ import React from 'react';
import Layout from 'components/layout/Layout';
import Settings from 'components/pages/Settings';
import useRequireLogin from 'hooks/useRequireLogin';
import useConfig from 'hooks/useConfig';
export default function SettingsPage() {
const { loading } = useRequireLogin();
const { adminDisabled } = useConfig();
if (process.env.isCloudMode || loading) {
if (adminDisabled || loading) {
return null;
}

View File

@ -14,11 +14,9 @@ export default function SharePage() {
return null;
}
const { websiteId } = shareToken;
return (
<Layout>
<WebsiteDetails websiteId={websiteId} />
<WebsiteDetails websiteId={shareToken.id} />
</Layout>
);
}

38
pages/sso.js Normal file
View File

@ -0,0 +1,38 @@
import { useEffect } from 'react';
import debug from 'debug';
import { useRouter } from 'next/router';
import { setItem } from 'next-basics';
import { AUTH_TOKEN } from 'lib/constants';
import useApi from 'hooks/useApi';
import { setUser } from 'store/app';
const log = debug('umami:sso');
export default function SingleSignOnPage() {
const router = useRouter();
const { get } = useApi();
const { token, url } = router.query;
useEffect(() => {
async function verify() {
setItem(AUTH_TOKEN, token);
const { ok, data } = await get('/auth/verify');
if (ok) {
log(data);
setUser(data);
if (url) {
await router.push(url);
}
}
}
if (token) {
verify();
}
}, [token]);
return null;
}

View File

@ -11,6 +11,18 @@
"value": "Add account"
}
],
"label.add-column": [
{
"type": 0,
"value": "Add column"
}
],
"label.add-filter": [
{
"type": 0,
"value": "Add filter"
}
],
"label.add-website": [
{
"type": 0,
@ -155,6 +167,18 @@
"value": "Enable share URL"
}
],
"label.event-data": [
{
"type": 0,
"value": "Event Data"
}
],
"label.field-name": [
{
"type": 0,
"value": "Field Name"
}
],
"label.invalid": [
{
"type": 0,
@ -313,6 +337,12 @@
"value": "Save"
}
],
"label.search": [
{
"type": 0,
"value": "Search"
}
],
"label.settings": [
{
"type": 0,
@ -373,6 +403,12 @@
"value": "Tracking code"
}
],
"label.type": [
{
"type": 0,
"value": "Type"
}
],
"label.unknown": [
{
"type": 0,
@ -385,6 +421,12 @@
"value": "Username"
}
],
"label.value": [
{
"type": 0,
"value": "Value"
}
],
"label.view-details": [
{
"type": 0,

View File

@ -11,6 +11,18 @@
"value": "Dodaj konto"
}
],
"label.add-column": [
{
"type": 0,
"value": "Dodaj kolumnę"
}
],
"label.add-filter": [
{
"type": 0,
"value": "Dodaj filtr"
}
],
"label.add-website": [
{
"type": 0,
@ -155,6 +167,18 @@
"value": "Włącz udostępnianie adresu URL"
}
],
"label.event-data": [
{
"type": 0,
"value": "Dane zdarzenia"
}
],
"label.field-name": [
{
"type": 0,
"value": "Nazwa pola"
}
],
"label.invalid": [
{
"type": 0,
@ -244,7 +268,7 @@
"label.none": [
{
"type": 0,
"value": "None"
"value": "Brak"
}
],
"label.owner": [
@ -313,6 +337,12 @@
"value": "Zapisz"
}
],
"label.search": [
{
"type": 0,
"value": "Szukaj"
}
],
"label.settings": [
{
"type": 0,
@ -373,6 +403,12 @@
"value": "Kod śledzenia"
}
],
"label.type": [
{
"type": 0,
"value": "Typ"
}
],
"label.unknown": [
{
"type": 0,
@ -385,6 +421,12 @@
"value": "Nazwa użytkownika"
}
],
"label.value": [
{
"type": 0,
"value": "Wartość"
}
],
"label.view-details": [
{
"type": 0,
@ -397,6 +439,12 @@
"value": "Witryny"
}
],
"label.yesterday": [
{
"type": 0,
"value": "Wczoraj"
}
],
"message.active-users": [
{
"type": 1,
@ -474,7 +522,7 @@
"message.edit-dashboard": [
{
"type": 0,
"value": "Edit dashboard"
"value": "Edytuj panel"
}
],
"message.failure": [
@ -770,7 +818,7 @@
"metrics.query-parameters": [
{
"type": 0,
"value": "Query parameters"
"value": "Parametry query"
}
],
"metrics.referrers": [

View File

@ -39,7 +39,7 @@ export async function deleteAccount(userId) {
}),
])
.then(async res => {
if (redis.client) {
if (redis.enabled) {
for (let i = 0; i < websiteUuids.length; i++) {
await redis.set(`website:${websiteUuids[i]}`, DELETED);
}

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,
createdAt: true,
updatedAt: true,
accountUuid: true,
},
});
}

View File

@ -14,8 +14,8 @@ export async function createWebsite(userId, data) {
},
})
.then(async res => {
if (redis.client && res) {
await redis.client.set(`website:${res.websiteUuid}`, res.id);
if (redis.enabled && res) {
await redis.set(`website:${res.websiteUuid}`, res.id);
}
return res;

View File

@ -1,31 +1,28 @@
import prisma from 'lib/prisma';
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 { websiteUuid } = await getWebsiteByUuid(websiteId);
return transaction([
client.pageview.deleteMany({
where: { session: { website: { websiteUuid: websiteId } } },
where: { session: { website: { websiteUuid } } },
}),
client.eventData.deleteMany({
where: { event: { session: { website: { websiteUuid: websiteId } } } },
where: { event: { session: { website: { websiteUuid } } } },
}),
client.event.deleteMany({
where: { session: { website: { websiteUuid: websiteId } } },
where: { session: { website: { websiteUuid } } },
}),
client.session.deleteMany({
where: { website: { websiteUuid: websiteId } },
where: { website: { websiteUuid } },
}),
client.website.delete({
where: { websiteUuid: websiteId },
where: { websiteUuid },
}),
]).then(async res => {
if (redis.client) {
await redis.client.set(`website:${websiteUuid}`, DELETED);
if (redis.enabled) {
await redis.set(`website:${websiteUuid}`, DELETED);
}
return res;

View File

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

View File

@ -1,7 +1,16 @@
import prisma from 'lib/prisma';
import redis from 'lib/redis';
export async function getWebsite(where) {
return prisma.client.website.findUnique({
where,
});
return prisma.client.website
.findUnique({
where,
})
.then(async data => {
if (redis.enabled && data) {
await redis.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

@ -30,8 +30,8 @@ async function relationalQuery(websiteId, data) {
},
})
.then(async res => {
if (redis.client && res) {
await redis.client.set(`session:${res.sessionUuid}`, 1);
if (redis.enabled && res) {
await redis.set(`session:${res.sessionUuid}`, 1);
}
return res;
@ -59,7 +59,7 @@ async function clickhouseQuery(
await sendMessage(params, 'event');
if (redis.client) {
await redis.client.set(`session:${sessionUuid}`, 1);
if (redis.enabled) {
await redis.set(`session:${sessionUuid}`, 1);
}
}

View File

@ -18,8 +18,8 @@ async function relationalQuery(sessionUuid) {
},
})
.then(async res => {
if (redis.client && res) {
await redis.client.set(`session:${res.sessionUuid}`, 1);
if (redis.enabled && res) {
await redis.set(`session:${res.sessionUuid}`, 1);
}
return res;
@ -48,8 +48,8 @@ async function clickhouseQuery(sessionUuid) {
)
.then(result => findFirst(result))
.then(async res => {
if (redis.client && res) {
await redis.client.set(`session:${res.session_uuid}`, 1);
if (redis.enabled && res) {
await redis.set(`session:${res.session_uuid}`, 1);
}
return res;

View File

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

View File

@ -1,8 +1,6 @@
export * from './admin/account/createAccount';
export * from './admin/account/deleteAccount';
export * from './admin/account/getAccount';
export * from './admin/account/getAccountById';
export * from './admin/account/getAccountByUsername';
export * from './admin/account/getAccounts';
export * from './admin/account/updateAccount';
export * from './admin/website/createWebsite';
@ -10,9 +8,6 @@ export * from './admin/website/deleteWebsite';
export * from './admin/website/getAllWebsites';
export * from './admin/website/getUserWebsites';
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/updateWebsite';
export * from './analytics/event/getEventMetrics';

View File

@ -143,7 +143,10 @@
) {
e.preventDefault();
trackEvent(name).then(() => {
location.href = get('href');
const href = get('href');
if (href) {
location.href = href;
}
});
} else {
trackEvent(name);

2687
yarn.lock

File diff suppressed because it is too large Load Diff