diff --git a/README.md b/README.md
index 5fe9dd96..70576b8c 100644
--- a/README.md
+++ b/README.md
@@ -36,6 +36,7 @@ DATABASE_URL=connection-url
```
The connection url is in the following format:
+
```
postgresql://username:mypassword@localhost:5432/mydb
@@ -48,7 +49,7 @@ mysql://username:mypassword@localhost:3306/mydb
yarn build
```
-The build step will also create tables in your database if you ae installing for the first time. It will also create a login account with username **admin** and password **umami**.
+The build step will also create tables in your database if you ae installing for the first time. It will also create a login user with username **admin** and password **umami**.
### Start the application
@@ -69,11 +70,13 @@ docker compose up
```
Alternatively, to pull just the Umami Docker image with PostgreSQL support:
+
```bash
docker pull docker.umami.is/umami-software/umami:postgresql-latest
```
Or with MySQL support:
+
```bash
docker pull docker.umami.is/umami-software/umami:mysql-latest
```
diff --git a/components/forms/ChangePasswordForm.js b/components/forms/ChangePasswordForm.js
index dcad6f17..8942ecf6 100644
--- a/components/forms/ChangePasswordForm.js
+++ b/components/forms/ChangePasswordForm.js
@@ -43,7 +43,7 @@ export default function ChangePasswordForm({ values, onSave, onClose }) {
const { user } = useUser();
const handleSubmit = async values => {
- const { ok, error } = await post(`/accounts/${user.accountUuid}/password`, values);
+ const { ok, error } = await post(`/users/${user.id}/password`, values);
if (ok) {
onSave();
diff --git a/components/forms/TrackingCodeForm.js b/components/forms/TrackingCodeForm.js
index 52df3bde..5a098b8d 100644
--- a/components/forms/TrackingCodeForm.js
+++ b/components/forms/TrackingCodeForm.js
@@ -26,7 +26,7 @@ export default function TrackingCodeForm({ values, onClose }) {
rows={3}
cols={60}
spellCheck={false}
- defaultValue={``}
readOnly
diff --git a/components/forms/AccountEditForm.js b/components/forms/UserEditForm.js
similarity index 93%
rename from components/forms/AccountEditForm.js
rename to components/forms/UserEditForm.js
index 70125656..0d7e392f 100644
--- a/components/forms/AccountEditForm.js
+++ b/components/forms/UserEditForm.js
@@ -28,13 +28,13 @@ const validate = ({ id, username, password }) => {
return errors;
};
-export default function AccountEditForm({ values, onSave, onClose }) {
+export default function UserEditForm({ values, onSave, onClose }) {
const { post } = useApi();
const [message, setMessage] = useState();
const handleSubmit = async values => {
const { id } = values;
- const { ok, data } = await post(id ? `/accounts/${id}` : '/accounts', values);
+ const { ok, data } = await post(id ? `/users/${id}` : '/users', values);
if (ok) {
onSave();
diff --git a/components/forms/WebsiteEditForm.js b/components/forms/WebsiteEditForm.js
index f13d0aa0..491a8bfe 100644
--- a/components/forms/WebsiteEditForm.js
+++ b/components/forms/WebsiteEditForm.js
@@ -37,7 +37,7 @@ const validate = ({ name, domain }) => {
return errors;
};
-const OwnerDropDown = ({ user, accounts }) => {
+const OwnerDropDown = ({ user, users }) => {
const { setFieldValue, values } = useFormikContext();
useEffect(() => {
@@ -46,7 +46,7 @@ const OwnerDropDown = ({ user, accounts }) => {
} else if (user?.id && values.owner === '') {
setFieldValue('owner', user.id.toString());
}
- }, [accounts, setFieldValue, user, values]);
+ }, [users, setFieldValue, user, values]);
if (user?.isAdmin) {
return (
@@ -56,7 +56,7 @@ const OwnerDropDown = ({ user, accounts }) => {
- {accounts?.map(acc => (
+ {users?.map(acc => (
@@ -73,14 +73,14 @@ const OwnerDropDown = ({ user, accounts }) => {
export default function WebsiteEditForm({ values, onSave, onClose }) {
const { post } = useApi();
- const { data: accounts } = useFetch(`/accounts`);
+ const { data: users } = useFetch(`/users`);
const { user } = useUser();
const [message, setMessage] = useState();
const handleSubmit = async values => {
- const { websiteUuid: websiteId } = values;
+ const { id } = values;
- const { ok, data } = await post(websiteId ? `/websites/${websiteId}` : '/websites', values);
+ const { ok, data } = await post(id ? `/websites/${id}` : '/websites', values);
if (ok) {
onSave();
@@ -125,7 +125,7 @@ export default function WebsiteEditForm({ values, onSave, onClose }) {
-
+
diff --git a/components/metrics/RealtimeHeader.js b/components/metrics/RealtimeHeader.js
index 1b93cd2f..d3c43dde 100644
--- a/components/metrics/RealtimeHeader.js
+++ b/components/metrics/RealtimeHeader.js
@@ -14,9 +14,9 @@ export default function RealtimeHeader({ websites, data, websiteId, onSelect })
value: null,
},
].concat(
- websites.map(({ name, websiteUuid }, index) => ({
+ websites.map(({ name, id }, index) => ({
label: name,
- value: websiteUuid,
+ value: id,
divider: index === 0,
})),
);
diff --git a/components/pages/DashboardEdit.js b/components/pages/DashboardEdit.js
index 0cc6d4e7..6af1644a 100644
--- a/components/pages/DashboardEdit.js
+++ b/components/pages/DashboardEdit.js
@@ -24,7 +24,7 @@ export default function DashboardEdit({ websites }) {
const ordered = useMemo(
() =>
websites
- .map(website => ({ ...website, order: order.indexOf(website.websiteUuid) }))
+ .map(website => ({ ...website, order: order.indexOf(website.id) }))
.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?.websiteUuid || 0));
+ setOrder(orderedWebsites.map(website => website?.id || 0));
}
function handleSave() {
@@ -76,12 +76,8 @@ export default function DashboardEdit({ websites }) {
ref={provided.innerRef}
style={{ marginBottom: snapshot.isDraggingOver ? 260 : null }}
>
- {ordered.map(({ websiteUuid, name, domain }, index) => (
-
+ {ordered.map(({ id, name, domain }, index) => (
+
{(provided, snapshot) => (
n.websiteUuid === websiteUuid);
+ if (websiteId) {
+ const { id } = init.websites.find(n => n.id === websiteId);
return {
pageviews: filterWebsite(pageviews, id),
sessions: filterWebsite(sessions, id),
@@ -61,7 +61,7 @@ export default function RealtimeDashboard() {
}
return data;
- }, [data, websiteUuid]);
+ }, [data, websiteId]);
const countries = useMemo(() => {
if (realtimeData?.sessions) {
@@ -118,9 +118,9 @@ export default function RealtimeDashboard() {
@@ -128,10 +128,10 @@ export default function RealtimeDashboard() {
-
+
-
+
diff --git a/components/pages/Settings.js b/components/pages/Settings.js
index 87b4ec9c..bc5022b9 100644
--- a/components/pages/Settings.js
+++ b/components/pages/Settings.js
@@ -4,12 +4,12 @@ import { useRouter } from 'next/router';
import Page from 'components/layout/Page';
import MenuLayout from 'components/layout/MenuLayout';
import WebsiteSettings from 'components/settings/WebsiteSettings';
-import AccountSettings from 'components/settings/AccountSettings';
+import UserSettings from 'components/settings/UserSettings';
import ProfileSettings from 'components/settings/ProfileSettings';
import useUser from 'hooks/useUser';
const WEBSITES = '/settings';
-const ACCOUNTS = '/settings/accounts';
+const ACCOUNTS = '/settings/users';
const PROFILE = '/settings/profile';
export default function Settings() {
@@ -28,7 +28,7 @@ export default function Settings() {
value: WEBSITES,
},
{
- label: ,
+ label: ,
value: ACCOUNTS,
hidden: !user?.isAdmin,
},
@@ -42,7 +42,7 @@ export default function Settings() {
{pathname === WEBSITES && }
- {pathname === ACCOUNTS && }
+ {pathname === ACCOUNTS && }
{pathname === PROFILE && }
diff --git a/components/pages/TestConsole.js b/components/pages/TestConsole.js
index 6200f7e5..70b0e504 100644
--- a/components/pages/TestConsole.js
+++ b/components/pages/TestConsole.js
@@ -24,9 +24,9 @@ export default function TestConsole() {
return null;
}
- const options = data.map(({ name, websiteUuid }) => ({ label: name, value: websiteUuid }));
- const website = data.find(({ websiteUuid }) => websiteId === websiteUuid);
- const selectedValue = options.find(({ value }) => value === website?.websiteUuid)?.value;
+ const options = data.map(({ name, id }) => ({ label: name, value: id }));
+ const website = data.find(({ id }) => websiteId === id);
+ const selectedValue = options.find(({ value }) => value === website?.id)?.value;
function handleSelect(value) {
router.push(`/console/${value}`);
@@ -46,7 +46,7 @@ export default function TestConsole() {
@@ -104,13 +104,13 @@ export default function TestConsole() {
>
diff --git a/components/pages/WebsiteList.js b/components/pages/WebsiteList.js
index 24ac8bec..dfd041a1 100644
--- a/components/pages/WebsiteList.js
+++ b/components/pages/WebsiteList.js
@@ -27,7 +27,7 @@ export default function WebsiteList({ websites, showCharts, limit }) {
const ordered = useMemo(
() =>
websites
- .map(website => ({ ...website, order: websiteOrder.indexOf(website.websiteUuid) || 0 }))
+ .map(website => ({ ...website, order: websiteOrder.indexOf(website.id) || 0 }))
.sort(firstBy('order')),
[websites, websiteOrder],
);
@@ -46,11 +46,11 @@ export default function WebsiteList({ websites, showCharts, limit }) {
return (
- {ordered.map(({ websiteUuid, name, domain }, index) =>
+ {ordered.map(({ id, name, domain }, index) =>
index < limit ? (
-
+
(isAdmin ? } size="medium" /> : null);
const DashboardLink = row => {
return (
-
+
} />
@@ -41,11 +41,11 @@ export default function AccountSettings() {
const Buttons = row => (
- } size="small" onClick={() => setEditAccount(row)}>
+ } size="small" onClick={() => setEditUser(row)}>
{!row.isAdmin && (
- } size="small" onClick={() => setDeleteAccount(row)}>
+ } size="small" onClick={() => setDeleteUser(row)}>
)}
@@ -84,9 +84,9 @@ export default function AccountSettings() {
}
function handleClose() {
- setEditAccount(null);
- setAddAccount(null);
- setDeleteAccount(null);
+ setEditUser(null);
+ setAddUser(null);
+ setDeleteUser(null);
}
if (!data) {
@@ -97,33 +97,31 @@ export default function AccountSettings() {
<>
-
+
- } size="small" onClick={() => setAddAccount(true)}>
-
+ } size="small" onClick={() => setAddUser(true)}>
+
- {editAccount && (
- }>
- }>
+
)}
- {addAccount && (
- }>
-
+ {addUser && (
+ }>
+
)}
- {deleteAccount && (
- }
- >
+ {deleteUser && (
+ }>
diff --git a/components/settings/AccountSettings.module.css b/components/settings/UserSettings.module.css
similarity index 100%
rename from components/settings/AccountSettings.module.css
rename to components/settings/UserSettings.module.css
diff --git a/components/settings/WebsiteSettings.js b/components/settings/WebsiteSettings.js
index 80bd1f60..0b428527 100644
--- a/components/settings/WebsiteSettings.js
+++ b/components/settings/WebsiteSettings.js
@@ -46,7 +46,7 @@ export default function WebsiteSettings() {
icon={}
size="small"
tooltip={}
- tooltipId={`button-share-${row.websiteUuid}`}
+ tooltipId={`button-share-${row.id}`}
onClick={() => setShowUrl(row)}
/>
)}
@@ -56,46 +56,42 @@ export default function WebsiteSettings() {
tooltip={
}
- tooltipId={`button-code-${row.websiteUuid}`}
+ tooltipId={`button-code-${row.id}`}
onClick={() => setShowCode(row)}
/>
}
size="small"
tooltip={}
- tooltipId={`button-edit-${row.websiteUuid}`}
+ tooltipId={`button-edit-${row.id}`}
onClick={() => setEditWebsite(row)}
/>
}
size="small"
tooltip={}
- tooltipId={`button-reset-${row.websiteUuid}`}
+ tooltipId={`button-reset-${row.id}`}
onClick={() => setResetWebsite(row)}
/>
}
size="small"
tooltip={}
- tooltipId={`button-delete-${row.websiteUuid}`}
+ tooltipId={`button-delete-${row.id}`}
onClick={() => setDeleteWebsite(row)}
/>
);
- const DetailsLink = ({ websiteUuid, name, domain }) => (
-
+ const DetailsLink = ({ id, name, domain }) => (
+
- {name}
+ {name}
);
- const Domain = ({ domain, websiteUuid }) => (
- {domain}
+ const Domain = ({ domain, id }) => (
+ {domain}
);
const adminColumns = [
@@ -112,7 +108,7 @@ export default function WebsiteSettings() {
render: Domain,
},
{
- key: 'account',
+ key: 'user',
label: ,
className: 'col-12 col-lg-4 col-xl-1',
},
@@ -203,7 +199,7 @@ export default function WebsiteSettings() {
title={}
>
@@ -214,7 +210,7 @@ export default function WebsiteSettings() {
title={}
>
diff --git a/db/postgresql/migrations/01_init/migration.sql b/db/postgresql/migrations/01_init/migration.sql
deleted file mode 100644
index cdabcd17..00000000
--- a/db/postgresql/migrations/01_init/migration.sql
+++ /dev/null
@@ -1,132 +0,0 @@
--- CreateTable
-CREATE TABLE "account" (
- "user_id" SERIAL NOT NULL,
- "username" VARCHAR(255) NOT NULL,
- "password" VARCHAR(60) NOT NULL,
- "is_admin" BOOLEAN NOT NULL DEFAULT false,
- "created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
- "updated_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
-
- PRIMARY KEY ("user_id")
-);
-
--- CreateTable
-CREATE TABLE "event" (
- "event_id" SERIAL NOT NULL,
- "website_id" INTEGER NOT NULL,
- "session_id" INTEGER NOT NULL,
- "created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
- "url" VARCHAR(500) NOT NULL,
- "event_type" VARCHAR(50) NOT NULL,
- "event_value" VARCHAR(50) NOT NULL,
-
- PRIMARY KEY ("event_id")
-);
-
--- CreateTable
-CREATE TABLE "pageview" (
- "view_id" SERIAL NOT NULL,
- "website_id" INTEGER NOT NULL,
- "session_id" INTEGER NOT NULL,
- "created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
- "url" VARCHAR(500) NOT NULL,
- "referrer" VARCHAR(500),
-
- PRIMARY KEY ("view_id")
-);
-
--- CreateTable
-CREATE TABLE "session" (
- "session_id" SERIAL NOT NULL,
- "session_uuid" UUID NOT NULL,
- "website_id" INTEGER NOT NULL,
- "created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
- "hostname" VARCHAR(100),
- "browser" VARCHAR(20),
- "os" VARCHAR(20),
- "device" VARCHAR(20),
- "screen" VARCHAR(11),
- "language" VARCHAR(35),
- "country" CHAR(2),
-
- PRIMARY KEY ("session_id")
-);
-
--- CreateTable
-CREATE TABLE "website" (
- "website_id" SERIAL NOT NULL,
- "website_uuid" UUID NOT NULL,
- "user_id" INTEGER NOT NULL,
- "name" VARCHAR(100) NOT NULL,
- "domain" VARCHAR(500),
- "share_id" VARCHAR(64),
- "created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
-
- PRIMARY KEY ("website_id")
-);
-
--- CreateIndex
-CREATE UNIQUE INDEX "account.username_unique" ON "account"("username");
-
--- CreateIndex
-CREATE INDEX "event_created_at_idx" ON "event"("created_at");
-
--- CreateIndex
-CREATE INDEX "event_session_id_idx" ON "event"("session_id");
-
--- CreateIndex
-CREATE INDEX "event_website_id_idx" ON "event"("website_id");
-
--- CreateIndex
-CREATE INDEX "pageview_created_at_idx" ON "pageview"("created_at");
-
--- CreateIndex
-CREATE INDEX "pageview_session_id_idx" ON "pageview"("session_id");
-
--- CreateIndex
-CREATE INDEX "pageview_website_id_created_at_idx" ON "pageview"("website_id", "created_at");
-
--- CreateIndex
-CREATE INDEX "pageview_website_id_idx" ON "pageview"("website_id");
-
--- CreateIndex
-CREATE INDEX "pageview_website_id_session_id_created_at_idx" ON "pageview"("website_id", "session_id", "created_at");
-
--- CreateIndex
-CREATE UNIQUE INDEX "session.session_uuid_unique" ON "session"("session_uuid");
-
--- CreateIndex
-CREATE INDEX "session_created_at_idx" ON "session"("created_at");
-
--- CreateIndex
-CREATE INDEX "session_website_id_idx" ON "session"("website_id");
-
--- CreateIndex
-CREATE UNIQUE INDEX "website.website_uuid_unique" ON "website"("website_uuid");
-
--- CreateIndex
-CREATE UNIQUE INDEX "website.share_id_unique" ON "website"("share_id");
-
--- CreateIndex
-CREATE INDEX "website_user_id_idx" ON "website"("user_id");
-
--- AddForeignKey
-ALTER TABLE "event" ADD FOREIGN KEY ("session_id") REFERENCES "session"("session_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "event" ADD FOREIGN KEY ("website_id") REFERENCES "website"("website_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "pageview" ADD FOREIGN KEY ("session_id") REFERENCES "session"("session_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "pageview" ADD FOREIGN KEY ("website_id") REFERENCES "website"("website_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "session" ADD FOREIGN KEY ("website_id") REFERENCES "website"("website_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "website" ADD FOREIGN KEY ("user_id") REFERENCES "account"("user_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- CreateAdminUser
-INSERT INTO account (username, password, is_admin) values ('admin', '$2b$10$BUli0c.muyCW1ErNJc3jL.vFRFtFJWrT8/GcR4A.sUdCznaXiqFXa', true);
diff --git a/db/postgresql/migrations/02_add_event_data/migration.sql b/db/postgresql/migrations/02_add_event_data/migration.sql
deleted file mode 100644
index 24c22e35..00000000
--- a/db/postgresql/migrations/02_add_event_data/migration.sql
+++ /dev/null
@@ -1,66 +0,0 @@
--- DropForeignKey
-ALTER TABLE "event" DROP CONSTRAINT "event_session_id_fkey";
-ALTER TABLE "event" DROP CONSTRAINT "event_website_id_fkey";
-
--- RenameIndex
-ALTER INDEX "event_pkey" RENAME TO "event_old_pkey";
-ALTER INDEX "event_created_at_idx" RENAME TO "event_old_created_at_idx";
-ALTER INDEX "event_session_id_idx" RENAME TO "event_old_session_id_idx";
-ALTER INDEX "event_website_id_idx" RENAME TO "event_old_website_id_idx";
-
--- RenameTable
-ALTER TABLE "event" RENAME TO "_event_old";
-
--- CreateTable
-CREATE TABLE "event" (
- "event_id" SERIAL NOT NULL,
- "website_id" INTEGER NOT NULL,
- "session_id" INTEGER NOT NULL,
- "created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
- "url" VARCHAR(500) NOT NULL,
- "event_name" VARCHAR(50) NOT NULL,
-
- PRIMARY KEY ("event_id")
-);
-
--- CreateIndex
-CREATE INDEX "event_created_at_idx" ON "event"("created_at");
-
--- CreateIndex
-CREATE INDEX "event_session_id_idx" ON "event"("session_id");
-
--- CreateIndex
-CREATE INDEX "event_website_id_idx" ON "event"("website_id");
-
--- AddForeignKey
-ALTER TABLE "event" ADD CONSTRAINT "event_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "session"("session_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "event" ADD CONSTRAINT "event_website_id_fkey" FOREIGN KEY ("website_id") REFERENCES "website"("website_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- CreateTable
-CREATE TABLE "event_data" (
- "event_data_id" SERIAL NOT NULL,
- "event_id" INTEGER NOT NULL,
- "event_data" JSONB NOT NULL,
-
- CONSTRAINT "event_data_pkey" PRIMARY KEY ("event_data_id")
-);
-
--- CreateIndex
-CREATE UNIQUE INDEX "event_data_event_id_key" ON "event_data"("event_id");
-
--- AddForeignKey
-ALTER TABLE "event_data" ADD CONSTRAINT "event_data_event_id_fkey" FOREIGN KEY ("event_id") REFERENCES "event"("event_id") ON DELETE RESTRICT ON UPDATE CASCADE;
-
--- RenameIndex
-ALTER INDEX IF EXISTS "account.username_unique" RENAME TO "account_username_key";
-
--- RenameIndex
-ALTER INDEX IF EXISTS "session.session_uuid_unique" RENAME TO "session_session_uuid_key";
-
--- RenameIndex
-ALTER INDEX IF EXISTS "website.share_id_unique" RENAME TO "website_share_id_key";
-
--- RenameIndex
-ALTER INDEX IF EXISTS "website.website_uuid_unique" RENAME TO "website_website_uuid_key";
\ No newline at end of file
diff --git a/db/postgresql/migrations/03_remove_casade_delete/migration.sql b/db/postgresql/migrations/03_remove_casade_delete/migration.sql
deleted file mode 100644
index aa1f7805..00000000
--- a/db/postgresql/migrations/03_remove_casade_delete/migration.sql
+++ /dev/null
@@ -1,35 +0,0 @@
--- DropForeignKey
-ALTER TABLE "event" DROP CONSTRAINT IF EXISTS "event_session_id_fkey";
-
--- DropForeignKey
-ALTER TABLE "event" DROP CONSTRAINT IF EXISTS "event_website_id_fkey";
-
--- DropForeignKey
-ALTER TABLE "pageview" DROP CONSTRAINT IF EXISTS "pageview_session_id_fkey";
-
--- DropForeignKey
-ALTER TABLE "pageview" DROP CONSTRAINT IF EXISTS "pageview_website_id_fkey";
-
--- DropForeignKey
-ALTER TABLE "session" DROP CONSTRAINT IF EXISTS "session_website_id_fkey";
-
--- DropForeignKey
-ALTER TABLE "website" DROP CONSTRAINT IF EXISTS "website_user_id_fkey";
-
--- AddForeignKey
-ALTER TABLE "event" ADD CONSTRAINT "event_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "session"("session_id") ON DELETE RESTRICT ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "event" ADD CONSTRAINT "event_website_id_fkey" FOREIGN KEY ("website_id") REFERENCES "website"("website_id") ON DELETE RESTRICT ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "pageview" ADD CONSTRAINT "pageview_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "session"("session_id") ON DELETE RESTRICT ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "pageview" ADD CONSTRAINT "pageview_website_id_fkey" FOREIGN KEY ("website_id") REFERENCES "website"("website_id") ON DELETE RESTRICT ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "session" ADD CONSTRAINT "session_website_id_fkey" FOREIGN KEY ("website_id") REFERENCES "website"("website_id") ON DELETE RESTRICT ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "website" ADD CONSTRAINT "website_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "account"("user_id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/db/postgresql/migrations/04_add_uuid/migration.sql b/db/postgresql/migrations/04_add_uuid/migration.sql
deleted file mode 100644
index 749cef6b..00000000
--- a/db/postgresql/migrations/04_add_uuid/migration.sql
+++ /dev/null
@@ -1,38 +0,0 @@
--- CreateExtension
-CREATE EXTENSION IF NOT EXISTS pgcrypto;
-
--- AlterTable
-ALTER TABLE "account" ADD COLUMN "account_uuid" UUID NULL;
-
--- Backfill UUID
-UPDATE "account" SET account_uuid = gen_random_uuid();
-
--- AlterTable
-ALTER TABLE "account" ALTER COLUMN "account_uuid" SET NOT NULL;
-
--- CreateIndex
-CREATE UNIQUE INDEX "account_account_uuid_key" ON "account"("account_uuid");
-
--- AlterTable
-ALTER TABLE "event" ADD COLUMN "event_uuid" UUID NULL;
-
--- Backfill UUID
-UPDATE "event" SET event_uuid = gen_random_uuid();
-
--- AlterTable
-ALTER TABLE "event" ALTER COLUMN "event_uuid" SET NOT NULL;
-
--- CreateIndex
-CREATE UNIQUE INDEX "event_event_uuid_key" ON "event"("event_uuid");
-
--- CreateIndex
-CREATE INDEX "account_account_uuid_idx" ON "account"("account_uuid");
-
--- CreateIndex
-CREATE INDEX "session_session_uuid_idx" ON "session"("session_uuid");
-
--- CreateIndex
-CREATE INDEX "website_website_uuid_idx" ON "website"("website_uuid");
-
--- CreateIndex
-CREATE INDEX "event_event_uuid_idx" ON "event"("event_uuid");
\ No newline at end of file
diff --git a/db/postgresql/migrations/migration_lock.toml b/db/postgresql/migrations/migration_lock.toml
deleted file mode 100644
index fbffa92c..00000000
--- a/db/postgresql/migrations/migration_lock.toml
+++ /dev/null
@@ -1,3 +0,0 @@
-# Please do not edit this file manually
-# It should be added in your version-control system (i.e. Git)
-provider = "postgresql"
\ No newline at end of file
diff --git a/db/postgresql/schema.prisma b/db/postgresql/schema.prisma
index ad1c7595..06c46a7d 100644
--- a/db/postgresql/schema.prisma
+++ b/db/postgresql/schema.prisma
@@ -7,55 +7,54 @@ datasource db {
url = env("DATABASE_URL")
}
-model account {
- id Int @id @default(autoincrement()) @map("user_id")
- username String @unique @db.VarChar(255)
- password String @db.VarChar(60)
- isAdmin Boolean @default(false) @map("is_admin")
- createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
- updatedAt DateTime? @default(now()) @map("updated_at") @db.Timestamptz(6)
- accountUuid String @unique @map("account_uuid") @db.Uuid
- website website[]
+model user {
+ id String @id @unique @map("user_id") @db.Uuid
+ username String @unique @db.VarChar(255)
+ password String @db.VarChar(60)
+ isAdmin Boolean @default(false) @map("is_admin")
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
- @@index([accountUuid])
+ groupRole groupRole[]
+ groupUser groupUser[]
+ userRole userRole[]
+ teamWebsite teamWebsite[]
+ teamUser teamUser[]
+ userWebsite userWebsite[]
+ website website[]
}
model event {
- id Int @id() @default(autoincrement()) @map("event_id")
- websiteId Int @map("website_id")
- sessionId Int @map("session_id")
- createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
- url String @db.VarChar(500)
- eventName String @map("event_name") @db.VarChar(50)
- eventUuid String @unique @map("event_uuid") @db.Uuid
- session session @relation(fields: [sessionId], references: [id])
- website website @relation(fields: [websiteId], references: [id])
+ id String @id() @map("event_id") @db.Uuid
+ websiteId String @map("website_id") @db.Uuid
+ sessionId String @map("session_id") @db.Uuid
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
+ url String @db.VarChar(500)
+ eventName String @map("event_name") @db.VarChar(50)
+
eventData eventData?
@@index([createdAt])
@@index([sessionId])
@@index([websiteId])
- @@index([eventUuid])
}
model eventData {
- id Int @id @default(autoincrement()) @map("event_data_id")
- eventId Int @unique @map("event_id")
- eventData Json @map("event_data")
- event event @relation(fields: [eventId], references: [id])
+ id String @id @unique @map("event_data_id") @db.Uuid
+ eventId String @unique @map("event_id") @db.Uuid
+ eventData Json @map("event_data")
+
+ event event @relation(fields: [eventId], references: [id])
@@map("event_data")
}
model pageview {
- id Int @id @default(autoincrement()) @map("view_id")
- websiteId Int @map("website_id")
- sessionId Int @map("session_id")
+ id String @id @unique @map("view_id") @db.Uuid
+ websiteId String @map("website_id") @db.Uuid
+ sessionId String @map("session_id") @db.Uuid
createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
url String @db.VarChar(500)
referrer String? @db.VarChar(500)
- session session @relation(fields: [sessionId], references: [id])
- website website @relation(fields: [websiteId], references: [id])
@@index([createdAt])
@@index([sessionId])
@@ -65,39 +64,154 @@ model pageview {
}
model session {
- id Int @id @default(autoincrement()) @map("session_id")
- sessionUuid String @unique @map("session_uuid") @db.Uuid
- websiteId Int @map("website_id")
- createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
- hostname String? @db.VarChar(100)
- browser String? @db.VarChar(20)
- os String? @db.VarChar(20)
- device String? @db.VarChar(20)
- screen String? @db.VarChar(11)
- language String? @db.VarChar(35)
- country String? @db.Char(2)
- website website? @relation(fields: [websiteId], references: [id])
- events event[]
- pageview pageview[]
+ id String @id @unique @map("session_id") @db.Uuid
+ websiteId String @map("website_id") @db.Uuid
+ hostname String? @db.VarChar(100)
+ browser String? @db.VarChar(20)
+ os String? @db.VarChar(20)
+ device String? @db.VarChar(20)
+ screen String? @db.VarChar(11)
+ language String? @db.VarChar(35)
+ country String? @db.Char(2)
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
@@index([createdAt])
@@index([websiteId])
- @@index([sessionUuid])
}
model website {
- id Int @id @default(autoincrement()) @map("website_id")
- websiteUuid String @unique @map("website_uuid") @db.Uuid
- userId Int @map("user_id")
- name String @db.VarChar(100)
- domain String? @db.VarChar(500)
- shareId String? @unique @map("share_id") @db.VarChar(64)
- createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
- account account @relation(fields: [userId], references: [id])
- event event[]
- pageview pageview[]
- session session[]
+ id String @id @unique @map("website_id") @db.Uuid
+ userId String @map("user_id") @db.Uuid
+ name String @db.VarChar(100)
+ domain String? @db.VarChar(500)
+ shareId String? @unique @map("share_id") @db.VarChar(64)
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
+
+ user user @relation(fields: [userId], references: [id])
+ teamWebsite teamWebsite[]
+ userWebsite userWebsite[]
@@index([userId])
- @@index([websiteUuid])
+}
+
+model group {
+ id String @id() @unique() @map("group_id") @db.Uuid
+ name String @unique() @db.VarChar(255)
+ description String? @db.VarChar(255)
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
+ isDeleted Boolean @default(false) @map("is_deleted")
+
+ groupRoles groupRole[]
+ groupUsers groupUser[]
+}
+
+model groupRole {
+ id String @id() @unique() @map("group_role_id") @db.Uuid
+ groupId String @map("group_id") @db.Uuid
+ roleId String @map("role_id") @db.Uuid
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
+ isDeleted Boolean @default(false) @map("is_deleted")
+
+ group group @relation(fields: [groupId], references: [id])
+ role role @relation(fields: [roleId], references: [id])
+ user user? @relation(fields: [userId], references: [id])
+ userId String? @db.Uuid
+
+ @@map("group_role")
+}
+
+model groupUser {
+ id String @id() @unique() @map("group_user_id") @db.Uuid
+ groupId String @map("group_id") @db.Uuid
+ userId String @map("user_id") @db.Uuid
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
+ isDeleted Boolean @default(false) @map("is_deleted")
+
+ group group @relation(fields: [groupId], references: [id])
+ user user @relation(fields: [userId], references: [id])
+
+ @@map("group_user")
+}
+
+model permission {
+ id String @id() @unique() @map("permission_id") @db.Uuid
+ name String @unique() @db.VarChar(255)
+ description String? @db.VarChar(255)
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
+ isDeleted Boolean @default(false) @map("is_deleted")
+}
+
+model role {
+ id String @id() @unique() @map("role_id") @db.Uuid
+ name String @unique() @db.VarChar(255)
+ description String? @db.VarChar(255)
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
+ isDeleted Boolean @default(false) @map("is_deleted")
+
+ groupRoles groupRole[]
+ userRoles userRole[]
+}
+
+model userRole {
+ id String @id() @unique() @map("user_role_id") @db.Uuid
+ roleId String @map("role_id") @db.Uuid
+ userId String @map("user_id") @db.Uuid
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
+ isDeleted Boolean @default(false) @map("is_deleted")
+
+ role role @relation(fields: [roleId], references: [id])
+ user user @relation(fields: [userId], references: [id])
+
+ @@map("user_role")
+}
+
+model team {
+ id String @id() @unique() @map("team_id") @db.Uuid
+ name String @unique() @db.VarChar(50)
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
+ isDeleted Boolean @default(false) @map("is_deleted")
+
+ teamWebsites teamWebsite[]
+ teamUsers teamUser[]
+}
+
+model teamWebsite {
+ id String @id() @unique() @map("team_website_id") @db.Uuid
+ teamId String @map("team_id") @db.Uuid
+ websiteId String @map("website_id") @db.Uuid
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
+ isDeleted Boolean @default(false) @map("is_deleted")
+
+ website website @relation(fields: [websiteId], references: [id])
+ team team @relation(fields: [teamId], references: [id])
+ user user? @relation(fields: [userId], references: [id])
+ userId String? @db.Uuid
+
+ @@map("team_website")
+}
+
+model teamUser {
+ id String @id() @unique() @map("team_user_id") @db.Uuid
+ teamId String @map("team_id") @db.Uuid
+ userId String @map("user_id") @db.Uuid
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
+ isDeleted Boolean @default(false) @map("is_deleted")
+
+ team team @relation(fields: [teamId], references: [id])
+ user user @relation(fields: [userId], references: [id])
+
+ @@map("team_user")
+}
+
+model userWebsite {
+ id String @id() @unique() @map("user_website_id") @db.Uuid
+ userId String @map("user_id") @db.Uuid
+ websiteId String @map("website_id") @db.Uuid
+ createdAt DateTime? @default(now()) @map("created_at") @db.Timestamptz(6)
+ isDeleted Boolean @default(false) @map("is_deleted")
+
+ website website @relation(fields: [websiteId], references: [id])
+ user user @relation(fields: [userId], references: [id])
+
+ @@map("user_website")
}
diff --git a/interface/auth.d.ts b/interface/auth.d.ts
new file mode 100644
index 00000000..36d3041e
--- /dev/null
+++ b/interface/auth.d.ts
@@ -0,0 +1,5 @@
+export interface Auth {
+ id: number;
+ email?: string;
+ teams?: string[];
+}
diff --git a/interface/base.d.ts b/interface/base.d.ts
new file mode 100644
index 00000000..5d498ebf
--- /dev/null
+++ b/interface/base.d.ts
@@ -0,0 +1,22 @@
+import { NextApiRequest } from 'next';
+import { Auth } from './auth';
+
+export interface NextApiRequestQueryBody extends NextApiRequest {
+ auth: Auth;
+ query: TQuery;
+ body: TBody;
+}
+
+export interface NextApiRequestQuery extends NextApiRequest {
+ auth: Auth;
+ query: TQuery;
+}
+
+export interface NextApiRequestBody extends NextApiRequest {
+ auth: Auth;
+ body: TBody;
+}
+
+export interface ObjectAny {
+ [key: string]: any;
+}
diff --git a/interface/index.d.ts b/interface/index.d.ts
new file mode 100644
index 00000000..5d498ebf
--- /dev/null
+++ b/interface/index.d.ts
@@ -0,0 +1,22 @@
+import { NextApiRequest } from 'next';
+import { Auth } from './auth';
+
+export interface NextApiRequestQueryBody extends NextApiRequest {
+ auth: Auth;
+ query: TQuery;
+ body: TBody;
+}
+
+export interface NextApiRequestQuery extends NextApiRequest {
+ auth: Auth;
+ query: TQuery;
+}
+
+export interface NextApiRequestBody extends NextApiRequest {
+ auth: Auth;
+ body: TBody;
+}
+
+export interface ObjectAny {
+ [key: string]: any;
+}
diff --git a/lib/auth.js b/lib/auth.js
index 93027544..1b063b5a 100644
--- a/lib/auth.js
+++ b/lib/auth.js
@@ -1,5 +1,5 @@
import { parseSecureToken, parseToken } from 'next-basics';
-import { getAccount, getWebsite } from 'queries';
+import { getUser, getWebsite } from 'queries';
import { SHARE_TOKEN_HEADER, TYPE_ACCOUNT, TYPE_WEBSITE } from 'lib/constants';
import { secret } from 'lib/crypto';
@@ -50,13 +50,13 @@ export async function allowQuery(req, type) {
if (userId) {
if (type === TYPE_WEBSITE) {
- const website = await getWebsite({ websiteUuid: id });
+ const website = await getWebsite({ id });
return website && website.userId === userId;
} else if (type === TYPE_ACCOUNT) {
- const account = await getAccount({ accountUuid: id });
+ const user = await getUser({ id });
- return account && account.accountUuid === id;
+ return user && user.id === id;
}
}
diff --git a/lib/constants.js b/lib/constants.js
index 8b3ee8d0..7a791a50 100644
--- a/lib/constants.js
+++ b/lib/constants.js
@@ -22,7 +22,7 @@ export const REALTIME_RANGE = 30;
export const REALTIME_INTERVAL = 3000;
export const TYPE_WEBSITE = 'website';
-export const TYPE_ACCOUNT = 'account';
+export const TYPE_ACCOUNT = 'user';
export const THEME_COLORS = {
light: {
diff --git a/lib/redis.js b/lib/redis.js
index 85752c54..16cfce19 100644
--- a/lib/redis.js
+++ b/lib/redis.js
@@ -1,11 +1,8 @@
-import Redis from 'ioredis';
-import { startOfMonth } from 'date-fns';
import debug from 'debug';
-import { getSessions, getAllWebsites } from 'queries';
+import Redis from 'ioredis';
import { REDIS } from 'lib/db';
const log = debug('umami:redis');
-const INITIALIZED = 'redis:initialized';
export const DELETED = 'deleted';
let redis;
@@ -32,30 +29,6 @@ function getClient() {
return redis;
}
-async function stageData() {
- const sessions = await getSessions([], startOfMonth(new Date()));
- const websites = await getAllWebsites();
-
- const sessionUuids = sessions.map(a => {
- return { key: `session:${a.sessionUuid}`, value: 1 };
- });
- const websiteIds = websites.map(a => {
- return { key: `website:${a.websiteUuid}`, value: Number(a.websiteId) };
- });
-
- await addSet(sessionUuids);
- await addSet(websiteIds);
-
- await redis.set(INITIALIZED, 1);
-}
-
-async function addSet(ids) {
- for (let i = 0; i < ids.length; i++) {
- const { key, value } = ids[i];
- await redis.set(key, value);
- }
-}
-
async function get(key) {
await connect();
@@ -76,4 +49,4 @@ async function connect() {
return redis;
}
-export default { enabled, client: redis, log, connect, get, set, stageData };
+export default { enabled, client: redis, log, connect, get, set };
diff --git a/lib/session.js b/lib/session.js
index d1a88768..4186f402 100644
--- a/lib/session.js
+++ b/lib/session.js
@@ -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, getWebsite } from 'queries';
+import { createSession, getSession as getSessionPrisma, getWebsite } from 'queries';
export async function getSession(req) {
const { payload } = getJsonBody(req);
@@ -23,51 +23,51 @@ export async function getSession(req) {
}
}
- const { website: websiteUuid, hostname, screen, language } = payload;
+ const { website: websiteId, hostname, screen, language } = payload;
- if (!validate(websiteUuid)) {
+ if (!validate(websiteId)) {
return null;
}
- let websiteId = null;
+ let isValidWebsite = null;
// Check if website exists
if (redis.enabled) {
- websiteId = Number(await redis.get(`website:${websiteUuid}`));
+ isValidWebsite = await redis.get(`website:${websiteId}`);
}
// Check database if does not exists in Redis
- if (!websiteId) {
- const website = await getWebsite({ websiteUuid });
- websiteId = website ? website.id : null;
+ if (!isValidWebsite) {
+ const website = await getWebsite({ id: websiteId });
+ isValidWebsite = !!website;
}
- if (!websiteId || websiteId === DELETED) {
- throw new Error(`Website not found: ${websiteUuid}`);
+ if (!isValidWebsite || isValidWebsite === DELETED) {
+ throw new Error(`Website not found: ${websiteId}`);
}
const { userAgent, browser, os, ip, country, device } = await getClientInfo(req, payload);
- const sessionUuid = uuid(websiteUuid, hostname, ip, userAgent);
+ const sessionId = uuid(websiteId, hostname, ip, userAgent);
- let sessionId = null;
+ let isValidSession = null;
let session = null;
if (!clickhouse.enabled) {
// Check if session exists
if (redis.enabled) {
- sessionId = Number(await redis.get(`session:${sessionUuid}`));
+ isValidSession = await redis.get(`session:${sessionId}`);
}
// Check database if does not exists in Redis
- if (!sessionId) {
- session = await getSessionByUuid(sessionUuid);
- sessionId = session ? session.id : null;
+ if (!isValidSession) {
+ session = await getSessionPrisma({ id: sessionId });
+ isValidSession = !!session;
}
- if (!sessionId) {
+ if (!isValidSession) {
try {
session = await createSession(websiteId, {
- sessionUuid,
+ id: sessionId,
hostname,
browser,
os,
@@ -84,8 +84,7 @@ export async function getSession(req) {
}
} else {
session = {
- sessionId,
- sessionUuid,
+ id: sessionId,
hostname,
browser,
os,
@@ -97,10 +96,7 @@ export async function getSession(req) {
}
return {
- website: {
- websiteId,
- websiteUuid,
- },
+ websiteId,
session,
};
}
diff --git a/next-env.d.ts b/next-env.d.ts
new file mode 100644
index 00000000..62b8a52d
--- /dev/null
+++ b/next-env.d.ts
@@ -0,0 +1,5 @@
+///
+///
+
+// NOTE: This file should not be edited
+// see https://nextjs.org/docs/basic-features/typescript for more information.
diff --git a/pages/api/auth/login.js b/pages/api/auth/login.js
index aa4803d8..fb9b5a1b 100644
--- a/pages/api/auth/login.js
+++ b/pages/api/auth/login.js
@@ -1,5 +1,5 @@
import { ok, unauthorized, badRequest, checkPassword, createSecureToken } from 'next-basics';
-import { getAccount } from 'queries';
+import { getUser } from 'queries';
import { secret } from 'lib/crypto';
export default async (req, res) => {
@@ -9,12 +9,11 @@ export default async (req, res) => {
return badRequest(res);
}
- const account = await getAccount({ username });
+ const user = await getUser({ username });
- if (account && checkPassword(password, account.password)) {
- const { id, username, isAdmin, accountUuid } = account;
- const user = { userId: id, username, isAdmin, accountUuid };
- const token = createSecureToken(user, secret());
+ if (user && checkPassword(password, user.password)) {
+ const { id: userId, username, isAdmin } = user;
+ const token = createSecureToken({ userId, username, isAdmin }, secret());
return ok(res, { token, user });
}
diff --git a/pages/api/collect.js b/pages/api/collect.js
index 5a4411d5..8ed03ed3 100644
--- a/pages/api/collect.js
+++ b/pages/api/collect.js
@@ -58,7 +58,7 @@ export default async (req, res) => {
await useSession(req, res);
- const { website, session } = req.session;
+ const { websiteId, session } = req.session;
const { type, payload } = getJsonBody(req);
@@ -68,14 +68,12 @@ export default async (req, res) => {
url = url.replace(/\/$/, '');
}
- const eventUuid = uuid();
-
if (type === 'pageview') {
- await savePageView(website, { session, url, referrer });
+ await savePageView(websiteId, { pageViewId: uuid(), session, url, referrer });
} else if (type === 'event') {
- await saveEvent(website, {
+ await saveEvent(websiteId, {
+ eventId: uuid(),
session,
- eventUuid,
url,
eventName,
eventData,
@@ -86,7 +84,7 @@ export default async (req, res) => {
const token = createToken(
{
- website,
+ websiteId,
session,
},
secret(),
diff --git a/pages/api/realtime/init.js b/pages/api/realtime/init.js
index 9a9a4297..6b980a0d 100644
--- a/pages/api/realtime/init.js
+++ b/pages/api/realtime/init.js
@@ -11,7 +11,7 @@ export default async (req, res) => {
const { userId } = req.auth;
const websites = await getUserWebsites({ userId });
- const ids = websites.map(({ websiteUuid }) => websiteUuid);
+ const ids = websites.map(({ id }) => id);
const token = createToken({ websites: ids }, secret());
const data = await getRealtimeData(ids, subMinutes(new Date(), 30));
diff --git a/pages/api/share/[id].js b/pages/api/share/[id].js
index 4ff6b81c..6fb19739 100644
--- a/pages/api/share/[id].js
+++ b/pages/api/share/[id].js
@@ -3,14 +3,14 @@ import { ok, notFound, methodNotAllowed, createToken } from 'next-basics';
import { secret } from 'lib/crypto';
export default async (req, res) => {
- const { id } = req.query;
+ const { id: shareId } = req.query;
if (req.method === 'GET') {
- const website = await getWebsite({ shareId: id });
+ const website = await getWebsite({ shareId });
if (website) {
- const { websiteUuid } = website;
- const data = { id: websiteUuid };
+ const { id } = website;
+ const data = { id };
const token = createToken(data, secret());
return ok(res, { ...data, token });
diff --git a/pages/api/accounts/[id]/index.js b/pages/api/users/[id]/index.js
similarity index 65%
rename from pages/api/accounts/[id]/index.js
rename to pages/api/users/[id]/index.js
index ae5fc434..3329869a 100644
--- a/pages/api/accounts/[id]/index.js
+++ b/pages/api/users/[id]/index.js
@@ -1,5 +1,5 @@
import { badRequest, hashPassword, methodNotAllowed, ok, unauthorized } from 'next-basics';
-import { getAccount, deleteAccount, updateAccount } from 'queries';
+import { getUser, deleteUser, updateUser } from 'queries';
import { useAuth } from 'lib/middleware';
export default async (req, res) => {
@@ -13,9 +13,9 @@ export default async (req, res) => {
return unauthorized(res);
}
- const account = await getAccount({ id: +id });
+ const user = await getUser({ id });
- return ok(res, account);
+ return ok(res, user);
}
if (req.method === 'POST') {
@@ -25,7 +25,7 @@ export default async (req, res) => {
return unauthorized(res);
}
- const account = await getAccount({ id: +id });
+ const user = await getUser({ id });
const data = {};
@@ -39,15 +39,15 @@ export default async (req, res) => {
}
// Check when username changes
- if (data.username && account.username !== data.username) {
- const accountByUsername = await getAccount({ username });
+ if (data.username && user.username !== data.username) {
+ const userByUsername = await getUser({ username });
- if (accountByUsername) {
- return badRequest(res, 'Account already exists');
+ if (userByUsername) {
+ return badRequest(res, 'User already exists');
}
}
- const updated = await updateAccount(data, { id: +id });
+ const updated = await updateUser(data, { id });
return ok(res, updated);
}
@@ -57,7 +57,7 @@ export default async (req, res) => {
return unauthorized(res);
}
- await deleteAccount(userId);
+ await deleteUser(id);
return ok(res);
}
diff --git a/pages/api/accounts/[id]/password.js b/pages/api/users/[id]/password.js
similarity index 70%
rename from pages/api/accounts/[id]/password.js
rename to pages/api/users/[id]/password.js
index 89649c20..fcb39df8 100644
--- a/pages/api/accounts/[id]/password.js
+++ b/pages/api/users/[id]/password.js
@@ -1,4 +1,4 @@
-import { getAccount, updateAccount } from 'queries';
+import { getUser, updateUser } from 'queries';
import { useAuth } from 'lib/middleware';
import {
badRequest,
@@ -15,22 +15,22 @@ export default async (req, res) => {
await useAuth(req, res);
const { current_password, new_password } = req.body;
- const { id: accountUuid } = req.query;
+ const { id } = req.query;
if (!(await allowQuery(req, TYPE_ACCOUNT))) {
return unauthorized(res);
}
if (req.method === 'POST') {
- const account = await getAccount({ accountUuid });
+ const user = await getUser({ id });
- if (!checkPassword(current_password, account.password)) {
+ if (!checkPassword(current_password, user.password)) {
return badRequest(res, 'Current password is incorrect');
}
const password = hashPassword(new_password);
- const updated = await updateAccount({ password }, { accountUuid });
+ const updated = await updateUser({ password }, { id });
return ok(res, updated);
}
diff --git a/pages/api/accounts/index.js b/pages/api/users/index.js
similarity index 56%
rename from pages/api/accounts/index.js
rename to pages/api/users/index.js
index 22248ed4..92b29204 100644
--- a/pages/api/accounts/index.js
+++ b/pages/api/users/index.js
@@ -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, getAccount, getAccounts } from 'queries';
+import { createUser, getUser, getUsers } from 'queries';
export default async (req, res) => {
await useAuth(req, res);
@@ -13,24 +13,24 @@ export default async (req, res) => {
}
if (req.method === 'GET') {
- const accounts = await getAccounts();
+ const users = await getUsers();
- return ok(res, accounts);
+ return ok(res, users);
}
if (req.method === 'POST') {
- const { username, password, account_uuid } = req.body;
+ const { username, password } = req.body;
- const account = await getAccount({ username });
+ const user = await getUser({ username });
- if (account) {
- return badRequest(res, 'Account already exists');
+ if (user) {
+ return badRequest(res, 'User already exists');
}
- const created = await createAccount({
+ const created = await createUser({
+ id: uuid(),
username,
password: hashPassword(password),
- accountUuid: account_uuid || uuid(),
});
return ok(res, created);
diff --git a/pages/api/websites/[id]/index.js b/pages/api/websites/[id]/index.js
index 539a3288..81ccfc29 100644
--- a/pages/api/websites/[id]/index.js
+++ b/pages/api/websites/[id]/index.js
@@ -1,39 +1,39 @@
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 { deleteWebsite, getUser, 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: websiteUuid } = req.query;
+ const { id } = req.query;
if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res);
}
if (req.method === 'GET') {
- const website = await getWebsite({ websiteUuid });
+ const website = await getWebsite({ id });
return ok(res, website);
}
if (req.method === 'POST') {
const { name, domain, owner, enableShareUrl, shareId } = req.body;
- const { accountUuid } = req.auth;
- let account;
+ const { userId } = req.auth;
+ let user;
- if (accountUuid) {
- account = await getAccount({ accountUuid });
+ if (userId) {
+ user = await getUser({ id: userId });
- if (!account) {
- return serverError(res, 'Account does not exist.');
+ if (!user) {
+ return serverError(res, 'User does not exist.');
}
}
- const website = await getWebsite({ websiteUuid });
+ const website = await getWebsite({ id });
const newShareId = enableShareUrl ? website.shareId || getRandomChars(8) : null;
@@ -43,9 +43,9 @@ export default async (req, res) => {
name,
domain,
shareId: shareId ? shareId : newShareId,
- userId: account ? account.id : +owner || undefined,
+ userId: +owner || user.id,
},
- { websiteUuid },
+ { id },
);
} catch (e) {
if (e.message.includes('Unique constraint') && e.message.includes('share_id')) {
@@ -61,7 +61,7 @@ export default async (req, res) => {
return unauthorized(res);
}
- await deleteWebsite(websiteUuid);
+ await deleteWebsite(id);
return ok(res);
}
diff --git a/pages/api/websites/[id]/metrics.js b/pages/api/websites/[id]/metrics.js
index 0aafe7d3..97216273 100644
--- a/pages/api/websites/[id]/metrics.js
+++ b/pages/api/websites/[id]/metrics.js
@@ -94,7 +94,7 @@ export default async (req, res) => {
let domain;
if (type === 'referrer') {
- const website = await getWebsite({ websiteUuid: websiteId });
+ const website = await getWebsite({ id: websiteId });
if (!website) {
return badRequest(res);
diff --git a/pages/api/websites/index.js b/pages/api/websites/index.js
index daecac88..2121cbf8 100644
--- a/pages/api/websites/index.js
+++ b/pages/api/websites/index.js
@@ -1,4 +1,4 @@
-import { createWebsite, getAccount, getAllWebsites, getUserWebsites } from 'queries';
+import { createWebsite, getUser, getAllWebsites, getUserWebsites } from 'queries';
import { ok, methodNotAllowed, unauthorized, getRandomChars } from 'next-basics';
import { useAuth } from 'lib/middleware';
import { uuid } from 'lib/crypto';
@@ -8,14 +8,14 @@ export default async (req, res) => {
const { user_id, include_all } = req.query;
const { userId: currentUserId, isAdmin } = req.auth;
- const accountUuid = user_id || req.auth.accountUuid;
- let account;
+ const id = user_id || currentUserId;
+ let user;
- if (accountUuid) {
- account = await getAccount({ accountUuid });
+ if (id) {
+ user = await getUser({ id });
}
- const userId = account ? account.id : user_id;
+ const userId = user ? user.id : user_id;
if (req.method === 'GET') {
if (userId && userId !== currentUserId && !isAdmin) {
@@ -23,9 +23,7 @@ export default async (req, res) => {
}
const websites =
- isAdmin && include_all
- ? await getAllWebsites()
- : await getUserWebsites({ userId: account?.id });
+ isAdmin && include_all ? await getAllWebsites() : await getUserWebsites({ userId });
return ok(res, websites);
}
@@ -33,15 +31,14 @@ export default async (req, res) => {
if (req.method === 'POST') {
const { name, domain, owner, enableShareUrl } = req.body;
- const website_owner = account ? account.id : +owner;
+ const website_owner = user ? userId : +owner;
if (website_owner !== currentUserId && !isAdmin) {
return unauthorized(res);
}
- const websiteUuid = uuid();
const shareId = enableShareUrl ? getRandomChars(8) : null;
- const website = await createWebsite(website_owner, { websiteUuid, name, domain, shareId });
+ const website = await createWebsite(website_owner, { id: uuid(), name, domain, shareId });
return ok(res, website);
}
diff --git a/pages/settings/accounts.js b/pages/settings/users.js
similarity index 100%
rename from pages/settings/accounts.js
rename to pages/settings/users.js
diff --git a/queries/admin/account/createAccount.js b/queries/admin/account/createAccount.js
deleted file mode 100644
index 2c4e1a40..00000000
--- a/queries/admin/account/createAccount.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import prisma from 'lib/prisma';
-
-export async function createAccount(data) {
- return prisma.client.account.create({
- data,
- });
-}
diff --git a/queries/admin/account/getAccount.js b/queries/admin/account/getAccount.js
deleted file mode 100644
index c414f56d..00000000
--- a/queries/admin/account/getAccount.js
+++ /dev/null
@@ -1,7 +0,0 @@
-import prisma from 'lib/prisma';
-
-export async function getAccount(where) {
- return prisma.client.account.findUnique({
- where,
- });
-}
diff --git a/queries/admin/account/updateAccount.js b/queries/admin/account/updateAccount.js
deleted file mode 100644
index 3a1cadca..00000000
--- a/queries/admin/account/updateAccount.js
+++ /dev/null
@@ -1,8 +0,0 @@
-import prisma from 'lib/prisma';
-
-export async function updateAccount(data, where) {
- return prisma.client.account.update({
- where,
- data,
- });
-}
diff --git a/queries/admin/user/createUser.js b/queries/admin/user/createUser.js
new file mode 100644
index 00000000..54e008fe
--- /dev/null
+++ b/queries/admin/user/createUser.js
@@ -0,0 +1,7 @@
+import prisma from 'lib/prisma';
+
+export async function createUser(data) {
+ return prisma.client.user.create({
+ data,
+ });
+}
diff --git a/queries/admin/account/deleteAccount.js b/queries/admin/user/deleteUser.js
similarity index 73%
rename from queries/admin/account/deleteAccount.js
rename to queries/admin/user/deleteUser.js
index 9f6dd636..81ade1a0 100644
--- a/queries/admin/account/deleteAccount.js
+++ b/queries/admin/user/deleteUser.js
@@ -1,18 +1,17 @@
import prisma from 'lib/prisma';
import redis, { DELETED } from 'lib/redis';
-export async function deleteAccount(userId) {
+export async function deleteUser(userId) {
const { client } = prisma;
const websites = await client.website.findMany({
where: { userId },
- select: { websiteUuid: true },
});
- let websiteUuids = [];
+ let websiteIds = [];
if (websites.length > 0) {
- websiteUuids = websites.map(a => a.websiteUuid);
+ websiteIds = websites.map(a => a.id);
}
return client
@@ -32,7 +31,7 @@ export async function deleteAccount(userId) {
client.website.deleteMany({
where: { userId },
}),
- client.account.delete({
+ client.user.delete({
where: {
id: userId,
},
@@ -40,8 +39,8 @@ export async function deleteAccount(userId) {
])
.then(async res => {
if (redis.enabled) {
- for (let i = 0; i < websiteUuids.length; i++) {
- await redis.set(`website:${websiteUuids[i]}`, DELETED);
+ for (let i = 0; i < websiteIds.length; i++) {
+ await redis.set(`website:${websiteIds[i]}`, DELETED);
}
}
diff --git a/queries/admin/user/getUser.js b/queries/admin/user/getUser.js
new file mode 100644
index 00000000..6c9ebd88
--- /dev/null
+++ b/queries/admin/user/getUser.js
@@ -0,0 +1,7 @@
+import prisma from 'lib/prisma';
+
+export async function getUser(where) {
+ return prisma.client.user.findUnique({
+ where,
+ });
+}
diff --git a/queries/admin/account/getAccounts.js b/queries/admin/user/getUsers.js
similarity index 64%
rename from queries/admin/account/getAccounts.js
rename to queries/admin/user/getUsers.js
index ceca2582..2fc473cb 100644
--- a/queries/admin/account/getAccounts.js
+++ b/queries/admin/user/getUsers.js
@@ -1,7 +1,7 @@
import prisma from 'lib/prisma';
-export async function getAccounts() {
- return prisma.client.account.findMany({
+export async function getUsers() {
+ return prisma.client.user.findMany({
orderBy: [
{ isAdmin: 'desc' },
{
@@ -13,8 +13,6 @@ export async function getAccounts() {
username: true,
isAdmin: true,
createdAt: true,
- updatedAt: true,
- accountUuid: true,
},
});
}
diff --git a/queries/admin/user/updateUser.js b/queries/admin/user/updateUser.js
new file mode 100644
index 00000000..ea80cf43
--- /dev/null
+++ b/queries/admin/user/updateUser.js
@@ -0,0 +1,8 @@
+import prisma from 'lib/prisma';
+
+export async function updateUser(data, where) {
+ return prisma.client.user.update({
+ where,
+ data,
+ });
+}
diff --git a/queries/admin/website/createWebsite.js b/queries/admin/website/createWebsite.js
index 22ac50c6..f9cb94be 100644
--- a/queries/admin/website/createWebsite.js
+++ b/queries/admin/website/createWebsite.js
@@ -5,7 +5,7 @@ export async function createWebsite(userId, data) {
return prisma.client.website
.create({
data: {
- account: {
+ user: {
connect: {
id: userId,
},
@@ -15,7 +15,7 @@ export async function createWebsite(userId, data) {
})
.then(async res => {
if (redis.enabled && res) {
- await redis.set(`website:${res.websiteUuid}`, res.id);
+ await redis.set(`website:${res.id}`, 1);
}
return res;
diff --git a/queries/admin/website/deleteWebsite.js b/queries/admin/website/deleteWebsite.js
index 4eb4d97b..429e4fe2 100644
--- a/queries/admin/website/deleteWebsite.js
+++ b/queries/admin/website/deleteWebsite.js
@@ -1,28 +1,28 @@
import prisma from 'lib/prisma';
import redis, { DELETED } from 'lib/redis';
-export async function deleteWebsite(websiteUuid) {
+export async function deleteWebsite(id) {
const { client, transaction } = prisma;
return transaction([
client.pageview.deleteMany({
- where: { session: { website: { websiteUuid } } },
+ where: { session: { website: { id } } },
}),
client.eventData.deleteMany({
- where: { event: { session: { website: { websiteUuid } } } },
+ where: { event: { session: { website: { id } } } },
}),
client.event.deleteMany({
- where: { session: { website: { websiteUuid } } },
+ where: { session: { website: { id } } },
}),
client.session.deleteMany({
- where: { website: { websiteUuid } },
+ where: { website: { id } },
}),
client.website.delete({
- where: { websiteUuid },
+ where: { id },
}),
]).then(async res => {
if (redis.enabled) {
- await redis.set(`website:${websiteUuid}`, DELETED);
+ await redis.set(`website:${id}`, DELETED);
}
return res;
diff --git a/queries/admin/website/getAllWebsites.js b/queries/admin/website/getAllWebsites.js
index 2c2c1bee..f9ad262c 100644
--- a/queries/admin/website/getAllWebsites.js
+++ b/queries/admin/website/getAllWebsites.js
@@ -11,7 +11,7 @@ export async function getAllWebsites() {
},
],
include: {
- account: {
+ user: {
select: {
username: true,
},
@@ -19,5 +19,5 @@ export async function getAllWebsites() {
},
});
- return data.map(i => ({ ...i, account: i.account.username }));
+ return data.map(i => ({ ...i, user: i.user.username }));
}
diff --git a/queries/admin/website/getWebsite.js b/queries/admin/website/getWebsite.js
index 6c109ff7..b7a468d2 100644
--- a/queries/admin/website/getWebsite.js
+++ b/queries/admin/website/getWebsite.js
@@ -8,7 +8,7 @@ export async function getWebsite(where) {
})
.then(async data => {
if (redis.enabled && data) {
- await redis.set(`website:${data.websiteUuid}`, data.id);
+ await redis.set(`website:${data.id}`, 1);
}
return data;
diff --git a/queries/admin/website/resetWebsite.js b/queries/admin/website/resetWebsite.js
index d969b0d0..68cae61e 100644
--- a/queries/admin/website/resetWebsite.js
+++ b/queries/admin/website/resetWebsite.js
@@ -1,20 +1,20 @@
import prisma from 'lib/prisma';
-export async function resetWebsite(websiteId) {
+export async function resetWebsite(id) {
const { client, transaction } = prisma;
return transaction([
client.pageview.deleteMany({
- where: { session: { website: { websiteUuid: websiteId } } },
+ where: { session: { website: { id } } },
}),
client.eventData.deleteMany({
- where: { event: { session: { website: { websiteUuid: websiteId } } } },
+ where: { event: { session: { website: { id } } } },
}),
client.event.deleteMany({
- where: { session: { website: { websiteUuid: websiteId } } },
+ where: { session: { website: { id } } },
}),
client.session.deleteMany({
- where: { website: { websiteUuid: websiteId } },
+ where: { website: { id } },
}),
]);
}
diff --git a/queries/analytics/event/getEventData.js b/queries/analytics/event/getEventData.js
index 91302d30..72857af4 100644
--- a/queries/analytics/event/getEventData.js
+++ b/queries/analytics/event/getEventData.js
@@ -21,7 +21,7 @@ async function relationalQuery(websiteId, { startDate, endDate, event_name, colu
on event.website_id = website.website_id
join event_data
on event.event_id = event_data.event_id
- where website_uuid='${websiteId}'
+ where website.website_id='${websiteId}'
and event.created_at between $1 and $2
${event_name ? `and event_name = ${event_name}` : ''}
${
diff --git a/queries/analytics/event/getEventMetrics.js b/queries/analytics/event/getEventMetrics.js
index 605bb688..9dcf6d55 100644
--- a/queries/analytics/event/getEventMetrics.js
+++ b/queries/analytics/event/getEventMetrics.js
@@ -28,7 +28,7 @@ async function relationalQuery(
from event
join website
on event.website_id = website.website_id
- where website_uuid='${websiteId}'
+ where website.website_id='${websiteId}'
and event.created_at between $1 and $2
${getFilterQuery('event', filters, params)}
group by 1, 2
diff --git a/queries/analytics/event/getEvents.js b/queries/analytics/event/getEvents.js
index ef2ee4e4..dde19992 100644
--- a/queries/analytics/event/getEvents.js
+++ b/queries/analytics/event/getEvents.js
@@ -13,7 +13,7 @@ function relationalQuery(websites, start_at) {
return prisma.client.event.findMany({
where: {
website: {
- websiteUuid: {
+ id: {
in: websites,
},
},
diff --git a/queries/analytics/event/saveEvent.js b/queries/analytics/event/saveEvent.js
index de7a1cae..a6bbe2fa 100644
--- a/queries/analytics/event/saveEvent.js
+++ b/queries/analytics/event/saveEvent.js
@@ -2,6 +2,7 @@ import { EVENT_NAME_LENGTH, URL_LENGTH } from 'lib/constants';
import { CLICKHOUSE, PRISMA, runQuery } from 'lib/db';
import kafka from 'lib/kafka';
import prisma from 'lib/prisma';
+import { uuid } from 'lib/crypto';
export async function saveEvent(...args) {
return runQuery({
@@ -11,10 +12,11 @@ export async function saveEvent(...args) {
}
async function relationalQuery(
- { websiteId },
- { session: { id: sessionId }, eventUuid, url, eventName, eventData },
+ websiteId,
+ { eventId, session: { id: sessionId }, eventUuid, url, eventName, eventData },
) {
const data = {
+ id: eventId,
websiteId,
sessionId,
url: url?.substring(0, URL_LENGTH),
@@ -26,6 +28,7 @@ async function relationalQuery(
data.eventData = {
create: {
eventData: eventData,
+ id: uuid(),
},
};
}
@@ -36,7 +39,7 @@ async function relationalQuery(
}
async function clickhouseQuery(
- { websiteUuid: websiteId },
+ websiteId,
{ session: { country, sessionUuid, ...sessionArgs }, eventUuid, url, eventName, eventData },
) {
const { getDateFormat, sendMessage } = kafka;
diff --git a/queries/analytics/pageview/getPageviewMetrics.js b/queries/analytics/pageview/getPageviewMetrics.js
index 69607d00..3acfdefb 100644
--- a/queries/analytics/pageview/getPageviewMetrics.js
+++ b/queries/analytics/pageview/getPageviewMetrics.js
@@ -24,7 +24,7 @@ async function relationalQuery(websiteId, { startDate, endDate, column, table, f
from ${table}
${` join website on ${table}.website_id = website.website_id`}
${joinSession}
- where website.website_uuid='${websiteId}'
+ where website.website_id='${websiteId}'
and ${table}.created_at between $1 and $2
${pageviewQuery}
${joinSession && sessionQuery}
diff --git a/queries/analytics/pageview/getPageviewParams.js b/queries/analytics/pageview/getPageviewParams.js
index 5cdabfa3..ce96c25b 100644
--- a/queries/analytics/pageview/getPageviewParams.js
+++ b/queries/analytics/pageview/getPageviewParams.js
@@ -24,7 +24,7 @@ async function relationalQuery(websiteId, start_at, end_at, column, table, filte
from ${table}
${` join website on ${table}.website_id = website.website_id`}
${joinSession}
- where website.website_uuid='${websiteId}'
+ where website.website_id='${websiteId}'
and ${table}.created_at between $1 and $2
and ${table}.url like '%?%'
${pageviewQuery}
diff --git a/queries/analytics/pageview/getPageviewStats.js b/queries/analytics/pageview/getPageviewStats.js
index 5ec8339f..57ff27f3 100644
--- a/queries/analytics/pageview/getPageviewStats.js
+++ b/queries/analytics/pageview/getPageviewStats.js
@@ -37,7 +37,7 @@ async function relationalQuery(
join website
on pageview.website_id = website.website_id
${joinSession}
- where website.website_uuid='${websiteId}'
+ where website.website_id='${websiteId}'
and pageview.created_at between $1 and $2
${pageviewQuery}
${sessionQuery}
diff --git a/queries/analytics/pageview/getPageviews.js b/queries/analytics/pageview/getPageviews.js
index 923317c0..e3b5cbc4 100644
--- a/queries/analytics/pageview/getPageviews.js
+++ b/queries/analytics/pageview/getPageviews.js
@@ -13,7 +13,7 @@ async function relationalQuery(websites, start_at) {
return prisma.client.pageview.findMany({
where: {
website: {
- websiteUuid: {
+ id: {
in: websites,
},
},
diff --git a/queries/analytics/pageview/savePageView.js b/queries/analytics/pageview/savePageView.js
index 65f04331..c035bfdf 100644
--- a/queries/analytics/pageview/savePageView.js
+++ b/queries/analytics/pageview/savePageView.js
@@ -10,9 +10,13 @@ export async function savePageView(...args) {
});
}
-async function relationalQuery({ websiteId }, { session: { id: sessionId }, url, referrer }) {
+async function relationalQuery(
+ websiteId,
+ { pageViewId, session: { id: sessionId }, url, referrer },
+) {
return prisma.client.pageview.create({
data: {
+ id: pageViewId,
websiteId,
sessionId,
url: url?.substring(0, URL_LENGTH),
@@ -22,12 +26,12 @@ async function relationalQuery({ websiteId }, { session: { id: sessionId }, url,
}
async function clickhouseQuery(
- { websiteUuid: websiteId },
- { session: { country, sessionUuid, ...sessionArgs }, url, referrer },
+ websiteId,
+ { session: { country, id: sessionId, ...sessionArgs }, url, referrer },
) {
const { getDateFormat, sendMessage } = kafka;
const params = {
- session_uuid: sessionUuid,
+ session_id: sessionId,
website_id: websiteId,
created_at: getDateFormat(new Date()),
url: url?.substring(0, URL_LENGTH),
diff --git a/queries/analytics/session/createSession.js b/queries/analytics/session/createSession.js
index 824ed252..b121ef7c 100644
--- a/queries/analytics/session/createSession.js
+++ b/queries/analytics/session/createSession.js
@@ -19,7 +19,6 @@ async function relationalQuery(websiteId, data) {
},
select: {
id: true,
- sessionUuid: true,
hostname: true,
browser: true,
os: true,
@@ -31,7 +30,7 @@ async function relationalQuery(websiteId, data) {
})
.then(async res => {
if (redis.enabled && res) {
- await redis.set(`session:${res.sessionUuid}`, 1);
+ await redis.set(`session:${res.id}`, 1);
}
return res;
@@ -40,12 +39,12 @@ async function relationalQuery(websiteId, data) {
async function clickhouseQuery(
websiteId,
- { sessionUuid, hostname, browser, os, screen, language, country, device },
+ { sessionId, hostname, browser, os, screen, language, country, device },
) {
const { getDateFormat, sendMessage } = kafka;
const params = {
- session_uuid: sessionUuid,
+ sessionId,
website_id: websiteId,
created_at: getDateFormat(new Date()),
hostname,
@@ -60,6 +59,6 @@ async function clickhouseQuery(
await sendMessage(params, 'event');
if (redis.enabled) {
- await redis.set(`session:${sessionUuid}`, 1);
+ await redis.set(`session:${sessionId}`, 1);
}
}
diff --git a/queries/analytics/session/getSessionByUuid.js b/queries/analytics/session/getSession.js
similarity index 83%
rename from queries/analytics/session/getSessionByUuid.js
rename to queries/analytics/session/getSession.js
index 2bb29c01..6bb4e445 100644
--- a/queries/analytics/session/getSessionByUuid.js
+++ b/queries/analytics/session/getSession.js
@@ -3,19 +3,17 @@ import { CLICKHOUSE, PRISMA, runQuery } from 'lib/db';
import prisma from 'lib/prisma';
import redis from 'lib/redis';
-export async function getSessionByUuid(...args) {
+export async function getSession(...args) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
-async function relationalQuery(sessionUuid) {
+async function relationalQuery(where) {
return prisma.client.session
.findUnique({
- where: {
- sessionUuid,
- },
+ where,
})
.then(async res => {
if (redis.enabled && res) {
@@ -49,7 +47,7 @@ async function clickhouseQuery(sessionUuid) {
.then(result => findFirst(result))
.then(async res => {
if (redis.enabled && res) {
- await redis.set(`session:${res.session_uuid}`, 1);
+ await redis.set(`session:${res.id}`, 1);
}
return res;
diff --git a/queries/analytics/session/getSessionMetrics.js b/queries/analytics/session/getSessionMetrics.js
index 020bddfb..e4e389d0 100644
--- a/queries/analytics/session/getSessionMetrics.js
+++ b/queries/analytics/session/getSessionMetrics.js
@@ -23,7 +23,7 @@ async function relationalQuery(websiteId, { startDate, endDate, field, filters =
join website
on pageview.website_id = website.website_id
${joinSession}
- where website.website_uuid='${websiteId}'
+ where website.website_id='${websiteId}'
and pageview.created_at between $1 and $2
${pageviewQuery}
${sessionQuery}
diff --git a/queries/analytics/session/getSessions.js b/queries/analytics/session/getSessions.js
index 85e33248..a806c16d 100644
--- a/queries/analytics/session/getSessions.js
+++ b/queries/analytics/session/getSessions.js
@@ -15,7 +15,7 @@ async function relationalQuery(websites, start_at) {
...(websites && websites.length > 0
? {
website: {
- websiteUuid: {
+ id: {
in: websites,
},
},
diff --git a/queries/analytics/stats/getActiveVisitors.js b/queries/analytics/stats/getActiveVisitors.js
index 3a898d94..c7592e5b 100644
--- a/queries/analytics/stats/getActiveVisitors.js
+++ b/queries/analytics/stats/getActiveVisitors.js
@@ -19,7 +19,7 @@ async function relationalQuery(websiteId) {
from pageview
join website
on pageview.website_id = website.website_id
- where website.website_uuid = '${websiteId}'
+ where website.website_id = '${websiteId}'
and pageview.created_at >= $1`,
params,
);
diff --git a/queries/analytics/stats/getWebsiteStats.js b/queries/analytics/stats/getWebsiteStats.js
index 134e1c3e..c6e37cd4 100644
--- a/queries/analytics/stats/getWebsiteStats.js
+++ b/queries/analytics/stats/getWebsiteStats.js
@@ -33,7 +33,7 @@ async function relationalQuery(websiteId, { start_at, end_at, filters = {} }) {
join website
on pageview.website_id = website.website_id
${joinSession}
- where website.website_uuid='${websiteId}'
+ where website.website_id='${websiteId}'
and pageview.created_at between $1 and $2
${pageviewQuery}
${sessionQuery}
diff --git a/queries/index.js b/queries/index.js
index a570af65..4cdcedd9 100644
--- a/queries/index.js
+++ b/queries/index.js
@@ -1,8 +1,8 @@
-export * from './admin/account/createAccount';
-export * from './admin/account/deleteAccount';
-export * from './admin/account/getAccount';
-export * from './admin/account/getAccounts';
-export * from './admin/account/updateAccount';
+export * from './admin/user/createUser';
+export * from './admin/user/deleteUser';
+export * from './admin/user/getUser';
+export * from './admin/user/getUsers';
+export * from './admin/user/updateUser';
export * from './admin/website/createWebsite';
export * from './admin/website/deleteWebsite';
export * from './admin/website/getAllWebsites';
@@ -20,7 +20,7 @@ export * from './analytics/pageview/getPageviews';
export * from './analytics/pageview/getPageviewStats';
export * from './analytics/pageview/savePageView';
export * from './analytics/session/createSession';
-export * from './analytics/session/getSessionByUuid';
+export * from './analytics/session/getSession';
export * from './analytics/session/getSessionMetrics';
export * from './analytics/session/getSessions';
export * from './analytics/stats/getActiveVisitors';
diff --git a/scripts/change-password.js b/scripts/change-password.js
index a9b63c12..b12373a9 100644
--- a/scripts/change-password.js
+++ b/scripts/change-password.js
@@ -13,9 +13,9 @@ const runQuery = async query => {
});
};
-const updateAccountByUsername = (username, data) => {
+const updateUserByUsername = (username, data) => {
return runQuery(
- prisma.account.update({
+ prisma.user.update({
where: {
username,
},
@@ -26,7 +26,7 @@ const updateAccountByUsername = (username, data) => {
const changePassword = async (username, newPassword) => {
const password = hashPassword(newPassword);
- return updateAccountByUsername(username, { password });
+ return updateUserByUsername(username, { password });
};
const getUsernameAndPassword = async () => {
@@ -40,7 +40,7 @@ const getUsernameAndPassword = async () => {
questions.push({
type: 'text',
name: 'username',
- message: 'Enter account to change password',
+ message: 'Enter user to change password',
});
}
if (!password) {
@@ -84,7 +84,7 @@ const getUsernameAndPassword = async () => {
console.log('Password changed for user', chalk.greenBright(username));
} catch (error) {
if (error.meta.cause.includes('Record to update not found')) {
- console.log('Account not found:', chalk.redBright(username));
+ console.log('User not found:', chalk.redBright(username));
} else {
throw error;
}
diff --git a/scripts/check-db.js b/scripts/check-db.js
index d5cc2a64..9b5a47a8 100644
--- a/scripts/check-db.js
+++ b/scripts/check-db.js
@@ -40,7 +40,7 @@ async function checkConnection() {
async function checkTables() {
try {
- await prisma.$queryRaw`select * from account limit 1`;
+ await prisma.$queryRaw`select * from user limit 1`;
success('Database tables found.');
} catch (e) {
diff --git a/sql/schema.mysql.sql b/sql/schema.mysql.sql
deleted file mode 100644
index 0ae7775a..00000000
--- a/sql/schema.mysql.sql
+++ /dev/null
@@ -1,102 +0,0 @@
--- CreateTable
-CREATE TABLE `account` (
- `user_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
- `username` VARCHAR(255) NOT NULL,
- `password` VARCHAR(60) NOT NULL,
- `is_admin` BOOLEAN NOT NULL DEFAULT false,
- `created_at` TIMESTAMP(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
- `updated_at` TIMESTAMP(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
-
- UNIQUE INDEX `username`(`username`),
- PRIMARY KEY (`user_id`)
-) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-
--- CreateTable
-CREATE TABLE `event` (
- `event_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
- `website_id` INTEGER UNSIGNED NOT NULL,
- `session_id` INTEGER UNSIGNED NOT NULL,
- `created_at` TIMESTAMP(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
- `url` VARCHAR(500) NOT NULL,
- `event_type` VARCHAR(50) NOT NULL,
- `event_value` VARCHAR(50) NOT NULL,
-
- INDEX `event_created_at_idx`(`created_at`),
- INDEX `event_session_id_idx`(`session_id`),
- INDEX `event_website_id_idx`(`website_id`),
- PRIMARY KEY (`event_id`)
-) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-
--- CreateTable
-CREATE TABLE `pageview` (
- `view_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
- `website_id` INTEGER UNSIGNED NOT NULL,
- `session_id` INTEGER UNSIGNED NOT NULL,
- `created_at` TIMESTAMP(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
- `url` VARCHAR(500) NOT NULL,
- `referrer` VARCHAR(500) NULL,
-
- INDEX `pageview_created_at_idx`(`created_at`),
- INDEX `pageview_session_id_idx`(`session_id`),
- INDEX `pageview_website_id_created_at_idx`(`website_id`, `created_at`),
- INDEX `pageview_website_id_idx`(`website_id`),
- INDEX `pageview_website_id_session_id_created_at_idx`(`website_id`, `session_id`, `created_at`),
- PRIMARY KEY (`view_id`)
-) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-
--- CreateTable
-CREATE TABLE `session` (
- `session_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
- `session_uuid` VARCHAR(36) NOT NULL,
- `website_id` INTEGER UNSIGNED NOT NULL,
- `created_at` TIMESTAMP(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
- `hostname` VARCHAR(100) NULL,
- `browser` VARCHAR(20) NULL,
- `os` VARCHAR(20) NULL,
- `device` VARCHAR(20) NULL,
- `screen` VARCHAR(11) NULL,
- `language` VARCHAR(35) NULL,
- `country` CHAR(2) NULL,
-
- UNIQUE INDEX `session_uuid`(`session_uuid`),
- INDEX `session_created_at_idx`(`created_at`),
- INDEX `session_website_id_idx`(`website_id`),
- PRIMARY KEY (`session_id`)
-) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-
--- CreateTable
-CREATE TABLE `website` (
- `website_id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
- `website_uuid` VARCHAR(36) NOT NULL,
- `user_id` INTEGER UNSIGNED NOT NULL,
- `name` VARCHAR(100) NOT NULL,
- `domain` VARCHAR(500) NULL,
- `share_id` VARCHAR(64) NULL,
- `created_at` TIMESTAMP(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
-
- UNIQUE INDEX `website_uuid`(`website_uuid`),
- UNIQUE INDEX `share_id`(`share_id`),
- INDEX `website_user_id_idx`(`user_id`),
- PRIMARY KEY (`website_id`)
-) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-
--- AddForeignKey
-ALTER TABLE `event` ADD CONSTRAINT `event_ibfk_2` FOREIGN KEY (`session_id`) REFERENCES `session`(`session_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
-
--- AddForeignKey
-ALTER TABLE `event` ADD CONSTRAINT `event_ibfk_1` FOREIGN KEY (`website_id`) REFERENCES `website`(`website_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
-
--- AddForeignKey
-ALTER TABLE `pageview` ADD CONSTRAINT `pageview_ibfk_2` FOREIGN KEY (`session_id`) REFERENCES `session`(`session_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
-
--- AddForeignKey
-ALTER TABLE `pageview` ADD CONSTRAINT `pageview_ibfk_1` FOREIGN KEY (`website_id`) REFERENCES `website`(`website_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
-
--- AddForeignKey
-ALTER TABLE `session` ADD CONSTRAINT `session_ibfk_1` FOREIGN KEY (`website_id`) REFERENCES `website`(`website_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
-
--- AddForeignKey
-ALTER TABLE `website` ADD CONSTRAINT `website_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `account`(`user_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
-
--- CreateAdminUser
-INSERT INTO account (username, password, is_admin) values ('admin', '$2b$10$BUli0c.muyCW1ErNJc3jL.vFRFtFJWrT8/GcR4A.sUdCznaXiqFXa', true);
diff --git a/sql/schema.postgresql.sql b/sql/schema.postgresql.sql
deleted file mode 100644
index cdabcd17..00000000
--- a/sql/schema.postgresql.sql
+++ /dev/null
@@ -1,132 +0,0 @@
--- CreateTable
-CREATE TABLE "account" (
- "user_id" SERIAL NOT NULL,
- "username" VARCHAR(255) NOT NULL,
- "password" VARCHAR(60) NOT NULL,
- "is_admin" BOOLEAN NOT NULL DEFAULT false,
- "created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
- "updated_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
-
- PRIMARY KEY ("user_id")
-);
-
--- CreateTable
-CREATE TABLE "event" (
- "event_id" SERIAL NOT NULL,
- "website_id" INTEGER NOT NULL,
- "session_id" INTEGER NOT NULL,
- "created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
- "url" VARCHAR(500) NOT NULL,
- "event_type" VARCHAR(50) NOT NULL,
- "event_value" VARCHAR(50) NOT NULL,
-
- PRIMARY KEY ("event_id")
-);
-
--- CreateTable
-CREATE TABLE "pageview" (
- "view_id" SERIAL NOT NULL,
- "website_id" INTEGER NOT NULL,
- "session_id" INTEGER NOT NULL,
- "created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
- "url" VARCHAR(500) NOT NULL,
- "referrer" VARCHAR(500),
-
- PRIMARY KEY ("view_id")
-);
-
--- CreateTable
-CREATE TABLE "session" (
- "session_id" SERIAL NOT NULL,
- "session_uuid" UUID NOT NULL,
- "website_id" INTEGER NOT NULL,
- "created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
- "hostname" VARCHAR(100),
- "browser" VARCHAR(20),
- "os" VARCHAR(20),
- "device" VARCHAR(20),
- "screen" VARCHAR(11),
- "language" VARCHAR(35),
- "country" CHAR(2),
-
- PRIMARY KEY ("session_id")
-);
-
--- CreateTable
-CREATE TABLE "website" (
- "website_id" SERIAL NOT NULL,
- "website_uuid" UUID NOT NULL,
- "user_id" INTEGER NOT NULL,
- "name" VARCHAR(100) NOT NULL,
- "domain" VARCHAR(500),
- "share_id" VARCHAR(64),
- "created_at" TIMESTAMPTZ(6) DEFAULT CURRENT_TIMESTAMP,
-
- PRIMARY KEY ("website_id")
-);
-
--- CreateIndex
-CREATE UNIQUE INDEX "account.username_unique" ON "account"("username");
-
--- CreateIndex
-CREATE INDEX "event_created_at_idx" ON "event"("created_at");
-
--- CreateIndex
-CREATE INDEX "event_session_id_idx" ON "event"("session_id");
-
--- CreateIndex
-CREATE INDEX "event_website_id_idx" ON "event"("website_id");
-
--- CreateIndex
-CREATE INDEX "pageview_created_at_idx" ON "pageview"("created_at");
-
--- CreateIndex
-CREATE INDEX "pageview_session_id_idx" ON "pageview"("session_id");
-
--- CreateIndex
-CREATE INDEX "pageview_website_id_created_at_idx" ON "pageview"("website_id", "created_at");
-
--- CreateIndex
-CREATE INDEX "pageview_website_id_idx" ON "pageview"("website_id");
-
--- CreateIndex
-CREATE INDEX "pageview_website_id_session_id_created_at_idx" ON "pageview"("website_id", "session_id", "created_at");
-
--- CreateIndex
-CREATE UNIQUE INDEX "session.session_uuid_unique" ON "session"("session_uuid");
-
--- CreateIndex
-CREATE INDEX "session_created_at_idx" ON "session"("created_at");
-
--- CreateIndex
-CREATE INDEX "session_website_id_idx" ON "session"("website_id");
-
--- CreateIndex
-CREATE UNIQUE INDEX "website.website_uuid_unique" ON "website"("website_uuid");
-
--- CreateIndex
-CREATE UNIQUE INDEX "website.share_id_unique" ON "website"("share_id");
-
--- CreateIndex
-CREATE INDEX "website_user_id_idx" ON "website"("user_id");
-
--- AddForeignKey
-ALTER TABLE "event" ADD FOREIGN KEY ("session_id") REFERENCES "session"("session_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "event" ADD FOREIGN KEY ("website_id") REFERENCES "website"("website_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "pageview" ADD FOREIGN KEY ("session_id") REFERENCES "session"("session_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "pageview" ADD FOREIGN KEY ("website_id") REFERENCES "website"("website_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "session" ADD FOREIGN KEY ("website_id") REFERENCES "website"("website_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "website" ADD FOREIGN KEY ("user_id") REFERENCES "account"("user_id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- CreateAdminUser
-INSERT INTO account (username, password, is_admin) values ('admin', '$2b$10$BUli0c.muyCW1ErNJc3jL.vFRFtFJWrT8/GcR4A.sUdCznaXiqFXa', true);
diff --git a/tracker/index.js b/tracker/index.js
index 3edca438..a9e11d0d 100644
--- a/tracker/index.js
+++ b/tracker/index.js
@@ -92,21 +92,21 @@
.then(text => (cache = text));
};
- const trackView = (url = currentUrl, referrer = currentRef, websiteUuid = website) =>
+ const trackView = (url = currentUrl, referrer = currentRef, websiteId = website) =>
collect(
'pageview',
assign(getPayload(), {
- website: websiteUuid,
+ website: websiteId,
url,
referrer,
}),
);
- const trackEvent = (eventName, eventData, url = currentUrl, websiteUuid = website) =>
+ const trackEvent = (eventName, eventData, url = currentUrl, websiteId = website) =>
collect(
'event',
assign(getPayload(), {
- website: websiteUuid,
+ website: websiteId,
url,
event_name: eventName,
event_data: eventData,