Skip to content

Commit

Permalink
Convert /api/users.
Browse files Browse the repository at this point in the history
  • Loading branch information
mikecao committed Jan 22, 2025
1 parent 090abcf commit baa3851
Show file tree
Hide file tree
Showing 61 changed files with 1,064 additions and 70 deletions.
2 changes: 1 addition & 1 deletion next-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
/// <reference types="next/navigation-types/compat/navigation" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
11 changes: 11 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const basePath = process.env.BASE_PATH;
const collectApiEndpoint = process.env.COLLECT_API_ENDPOINT;
const cloudMode = process.env.CLOUD_MODE;
const cloudUrl = process.env.CLOUD_URL;
const corsMaxAge = process.env.CORS_MAX_AGE;
const defaultLocale = process.env.DEFAULT_LOCALE;
const disableLogin = process.env.DISABLE_LOGIN;
const disableUI = process.env.DISABLE_UI;
Expand Down Expand Up @@ -59,6 +60,16 @@ const trackerHeaders = [
];

const headers = [
{
source: '/api/:path*',
headers: [
{ key: 'Access-Control-Allow-Credentials', value: 'true' },
{ key: 'Access-Control-Allow-Origin', value: '*' },
{ key: 'Access-Control-Allow-Headers', value: '*' },
{ key: 'Access-Control-Allow-Methods', value: 'GET, DELETE, POST, PUT' },
{ key: 'Access-Control-Max-Age', value: corsMaxAge || '86400' },
],
},
{
source: '/:path*',
headers: defaultHeaders,
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"url": "https://github.com/umami-software/umami.git"
},
"scripts": {
"dev": "next dev -p 3000",
"dev": "next dev -p 3000 --turbo",
"build": "npm-run-all check-env build-db check-db build-tracker build-geo build-app",
"start": "next start",
"build-docker": "npm-run-all build-db build-tracker build-geo build-app",
Expand Down Expand Up @@ -119,6 +119,7 @@
"thenby": "^1.3.4",
"uuid": "^9.0.0",
"yup": "^0.32.11",
"zod": "^3.24.1",
"zustand": "^4.5.5"
},
"devDependencies": {
Expand Down
4 changes: 4 additions & 0 deletions src/app/(main)/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export function App({ children }) {
return null;
}

if (config.uiDisabled) {
return null;
}

return (
<>
{children}
Expand Down
6 changes: 1 addition & 5 deletions src/app/(main)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@ import NavBar from './NavBar';
import Page from 'components/layout/Page';
import styles from './layout.module.css';

export default function ({ children }) {
if (process.env.DISABLE_UI) {
return null;
}

export default async function ({ children }) {
return (
<App>
<main className={styles.layout}>
Expand Down
10 changes: 10 additions & 0 deletions src/app/actions/getConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use server';

export async function getConfig() {
return {
telemetryDisabled: !!process.env.DISABLE_TELEMETRY,
trackerScriptName: process.env.TRACKER_SCRIPT_NAME,
uiDisabled: !!process.env.DISABLE_UI,
updatesDisabled: !!process.env.DISABLE_UPDATES,
};
}
3 changes: 3 additions & 0 deletions src/app/api/heartbeat/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export async function GET() {
return Response.json({ ok: true });
}
72 changes: 72 additions & 0 deletions src/app/api/users/[userId]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { z } from 'zod';
import { canUpdateUser, canViewUser, checkAuth } from 'lib/auth';
import { getUser, getUserByUsername, updateUser } from 'queries';
import { json, unauthorized, badRequest } from 'lib/response';
import { hashPassword } from 'next-basics';
import { checkRequest } from 'lib/request';

export async function GET(request: Request, { params }: { params: Promise<{ userId: string }> }) {
const { userId } = await params;
const auth = await checkAuth(request);

if (!auth || !(await canViewUser(auth, userId))) {
return unauthorized();
}

const user = await getUser(userId);

return json(user);
}

export async function POST(request: Request, { params }: { params: Promise<{ userId: string }> }) {
const schema = z.object({
username: z.string().max(255),
password: z.string().max(255),
role: z.string().regex(/admin|user|view-only/i),
});

const { body, error } = await checkRequest(request, schema);

if (error) {
return badRequest(error);
}

const { userId } = await params;
const auth = await checkAuth(request);

if (!auth || !(await canUpdateUser(auth, userId))) {
return unauthorized();
}

const { username, password, role } = body;

const user = await getUser(userId);

const data: any = {};

if (password) {
data.password = hashPassword(password);
}

// Only admin can change these fields
if (role && auth.user.isAdmin) {
data.role = role;
}

if (username && auth.user.isAdmin) {
data.username = username;
}

// Check when username changes
if (data.username && user.username !== data.username) {
const user = await getUserByUsername(username);

if (user) {
return badRequest('User already exists');
}
}

const updated = await updateUser(userId, data);

return json(updated);
}
30 changes: 30 additions & 0 deletions src/app/api/users/[userId]/teams/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { z } from 'zod';
import { pagingParams } from 'lib/schema';
import { getUserTeams } from 'queries';
import { checkAuth } from 'lib/auth';
import { unauthorized, badRequest, json } from 'lib/response';
import { checkRequest } from 'lib/request';

const schema = z.object({
...pagingParams,
});

export async function GET(request: Request, { params }: { params: Promise<{ userId: string }> }) {
const { userId } = await params;

const { query, error } = await checkRequest(request, schema);

if (error) {
return badRequest(error);
}

const auth = await checkAuth(request);

if (!auth || (!auth.user.isAdmin && (!userId || auth.user.id !== userId))) {
return unauthorized();
}

const teams = await getUserTeams(userId, query);

return json(teams);
}
66 changes: 66 additions & 0 deletions src/app/api/users/[userId]/usage/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { z } from 'zod';
import { json, unauthorized, badRequest } from 'lib/response';
import { getAllUserWebsitesIncludingTeamOwner } from 'queries/prisma/website';
import { getEventUsage } from 'queries/analytics/events/getEventUsage';
import { getEventDataUsage } from 'queries/analytics/events/getEventDataUsage';
import { checkAuth } from 'lib/auth';
import { checkRequest } from 'lib/request';

const schema = z.object({
startAt: z.coerce.number(),
endAt: z.coerce.number(),
});

export async function GET(request: Request, { params }: { params: Promise<{ userId: string }> }) {
const { query, error } = await checkRequest(request, schema);

if (error) {
return badRequest(error);
}

const auth = await checkAuth(request);

if (!auth || !auth.user.isAdmin) {
return unauthorized();
}

const { userId } = await params;
const { startAt, endAt } = query;

const startDate = new Date(+startAt);
const endDate = new Date(+endAt);

const websites = await getAllUserWebsitesIncludingTeamOwner(userId);

const websiteIds = websites.map(a => a.id);

const websiteEventUsage = await getEventUsage(websiteIds, startDate, endDate);
const eventDataUsage = await getEventDataUsage(websiteIds, startDate, endDate);

const websiteUsage = websites.map(a => ({
websiteId: a.id,
websiteName: a.name,
websiteEventUsage: websiteEventUsage.find(b => a.id === b.websiteId)?.count || 0,
eventDataUsage: eventDataUsage.find(b => a.id === b.websiteId)?.count || 0,
deletedAt: a.deletedAt,
}));

const usage = websiteUsage.reduce(
(acc, cv) => {
acc.websiteEventUsage += cv.websiteEventUsage;
acc.eventDataUsage += cv.eventDataUsage;

return acc;
},
{ websiteEventUsage: 0, eventDataUsage: 0 },
);

const filteredWebsiteUsage = websiteUsage.filter(
a => !a.deletedAt && (a.websiteEventUsage > 0 || a.eventDataUsage > 0),
);

return json({
...usage,
websites: filteredWebsiteUsage,
});
}
29 changes: 29 additions & 0 deletions src/app/api/users/[userId]/websites/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { z } from 'zod';
import { unauthorized, json, badRequest } from 'lib/response';
import { getUserWebsites } from 'queries/prisma/website';
import { pagingParams } from 'lib/schema';
import { checkRequest } from 'lib/request';
import { checkAuth } from 'lib/auth';

const schema = z.object({
...pagingParams,
});

export async function GET(request: Request, { params }: { params: Promise<{ userId: string }> }) {
const { query, error } = await checkRequest(request, schema);

if (error) {
return badRequest(error);
}

const { userId } = await params;
const auth = await checkAuth(request);

if (!auth || (!auth.user.isAdmin && auth.user.id !== userId)) {
return unauthorized();
}

const websites = await getUserWebsites(userId, query);

return json(websites);
}
46 changes: 46 additions & 0 deletions src/app/api/users/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { z } from 'zod';
import { hashPassword } from 'next-basics';
import { canCreateUser, checkAuth } from 'lib/auth';
import { ROLES } from 'lib/constants';
import { uuid } from 'lib/crypto';
import { checkRequest } from 'lib/request';
import { unauthorized, json, badRequest } from 'lib/response';
import { createUser, getUserByUsername } from 'queries';

const schema = z.object({
username: z.string().max(255),
password: z.string(),
id: z.string().uuid(),
role: z.string().regex(/admin|user|view-only/i),
});

export async function POST(request: Request) {
const { body, error } = await checkRequest(request, schema);

if (error) {
return badRequest(error);
}

const auth = await checkAuth(request);

if (!auth || !(await canCreateUser(auth))) {
return unauthorized();
}

const { username, password, role, id } = body;

const existingUser = await getUserByUsername(username, { showDeleted: true });

if (existingUser) {
return badRequest('User already exists');
}

const user = await createUser({
id: id || uuid(),
username,
password: hashPassword(password),
role: role ?? ROLES.user,
});

return json(user);
}
6 changes: 6 additions & 0 deletions src/app/api/version/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { json } from 'lib/response';
import { CURRENT_VERSION } from 'lib/constants';

export async function GET() {
return json({ version: CURRENT_VERSION });
}
24 changes: 24 additions & 0 deletions src/app/api/websites/[websiteId]/active/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { canViewWebsite, checkAuth } from 'lib/auth';
import { json, unauthorized } from 'lib/response';
import { getActiveVisitors } from 'queries';

export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const auth = await checkAuth(request);

if (!auth) {
return unauthorized();
}

const { websiteId } = await params;

if (!(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}

const result = await getActiveVisitors(websiteId);

return json(result);
}
19 changes: 19 additions & 0 deletions src/app/api/websites/[websiteId]/daterange/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { canViewWebsite, checkAuth } from 'lib/auth';
import { getWebsiteDateRange } from 'queries';
import { json, unauthorized } from 'lib/response';

export async function GET(
request: Request,
{ params }: { params: Promise<{ websiteId: string }> },
) {
const auth = await checkAuth(request);
const { websiteId } = await params;

if (!auth || !(await canViewWebsite(auth, websiteId))) {
return unauthorized();
}

const result = await getWebsiteDateRange(websiteId);

return json(result);
}
Loading

0 comments on commit baa3851

Please sign in to comment.