mirror of
https://github.com/umami-software/umami.git
synced 2026-02-10 23:57:12 +01:00
Convert /api/users.
This commit is contained in:
parent
090abcff81
commit
baa3851fb4
61 changed files with 1064 additions and 70 deletions
72
src/app/api/users/[userId]/route.ts
Normal file
72
src/app/api/users/[userId]/route.ts
Normal file
|
|
@ -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);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue