Moved code into src folder. Added build for component library.

This commit is contained in:
Mike Cao 2023-08-21 02:06:09 -07:00
parent 7a7233ead4
commit ede658771e
490 changed files with 749 additions and 442 deletions

View file

@ -0,0 +1,108 @@
import { canDeleteUser, canUpdateUser, canViewUser } from 'lib/auth';
import { useAuth, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, Role, User } from 'lib/types';
import { NextApiResponse } from 'next';
import { badRequest, hashPassword, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { deleteUser, getUserById, getUserByUsername, updateUser } from 'queries';
import * as yup from 'yup';
export interface UserRequestQuery {
id: string;
}
export interface UserRequestBody {
username: string;
password: string;
role: Role;
}
const schema = {
GET: yup.object().shape({
id: yup.string().uuid().required(),
}),
POST: yup.object().shape({
id: yup.string().uuid().required(),
username: yup.string().max(255),
password: yup.string(),
role: yup.string().matches(/admin|user|view-only/i),
}),
};
export default async (
req: NextApiRequestQueryBody<UserRequestQuery, UserRequestBody>,
res: NextApiResponse<User>,
) => {
await useAuth(req, res);
req.yup = schema;
await useValidate(req, res);
const {
user: { id: userId, isAdmin },
} = req.auth;
const { id } = req.query;
if (req.method === 'GET') {
if (!(await canViewUser(req.auth, id))) {
return unauthorized(res);
}
const user = await getUserById(id);
return ok(res, user);
}
if (req.method === 'POST') {
if (!(await canUpdateUser(req.auth, id))) {
return unauthorized(res);
}
const { username, password, role } = req.body;
const user = await getUserById(id);
const data: any = {};
if (password) {
data.password = hashPassword(password);
}
// Only admin can change these fields
if (role && isAdmin) {
data.role = role;
}
if (username && isAdmin) {
data.username = username;
}
// Check when username changes
if (data.username && user.username !== data.username) {
const user = await getUserByUsername(username);
if (user) {
return badRequest(res, 'User already exists');
}
}
const updated = await updateUser(data, { id });
return ok(res, updated);
}
if (req.method === 'DELETE') {
if (!(await canDeleteUser(req.auth))) {
return unauthorized(res);
}
if (id === userId) {
return badRequest(res, 'You cannot delete yourself.');
}
await deleteUser(id);
return ok(res);
}
return methodNotAllowed(res);
};

View file

@ -0,0 +1,55 @@
import { useAuth, useCors, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, SearchFilter, TeamSearchFilterType } from 'lib/types';
import { getFilterValidation } from 'lib/yup';
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getTeamsByUserId } from 'queries';
import * as yup from 'yup';
export interface UserTeamsRequestQuery extends SearchFilter<TeamSearchFilterType> {
id: string;
}
export interface UserTeamsRequestBody {
name: string;
domain: string;
shareId: string;
}
const schema = {
GET: yup.object().shape({
id: yup.string().uuid().required(),
...getFilterValidation('/All|Name|Owner/i'),
}),
};
export default async (
req: NextApiRequestQueryBody<any, UserTeamsRequestBody>,
res: NextApiResponse,
) => {
await useCors(req, res);
await useAuth(req, res);
req.yup = schema;
await useValidate(req, res);
const { user } = req.auth;
const { id: userId } = req.query;
if (req.method === 'GET') {
if (!user.isAdmin && user.id !== userId) {
return unauthorized(res);
}
const { page, filter, pageSize } = req.query;
const teams = await getTeamsByUserId(userId, {
page,
filter,
pageSize: +pageSize || null,
});
return ok(res, teams);
}
return methodNotAllowed(res);
};

View file

@ -0,0 +1,86 @@
import { useAuth, useCors, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody } from 'lib/types';
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getEventDataUsage, getEventUsage, getUserWebsites } from 'queries';
import * as yup from 'yup';
export interface UserUsageRequestQuery {
id: string;
startAt: string;
endAt: string;
}
export interface UserUsageRequestResponse {
websiteEventUsage: number;
eventDataUsage: number;
websites: {
websiteEventUsage: number;
eventDataUsage: number;
websiteId: string;
websiteName: string;
}[];
}
const schema = {
GET: yup.object().shape({
id: yup.string().uuid().required(),
startAt: yup.number().integer().required(),
endAt: yup.number().integer().moreThan(yup.ref('startAt')).required(),
}),
};
export default async (
req: NextApiRequestQueryBody<UserUsageRequestQuery>,
res: NextApiResponse<UserUsageRequestResponse>,
) => {
await useCors(req, res);
await useAuth(req, res);
req.yup = schema;
await useValidate(req, res);
const { user } = req.auth;
if (req.method === 'GET') {
if (!user.isAdmin) {
return unauthorized(res);
}
const { id: userId, startAt, endAt } = req.query;
const startDate = new Date(+startAt);
const endDate = new Date(+endAt);
const websites = await getUserWebsites(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,
}));
const usage = websiteUsage.reduce(
(acc, cv) => {
acc.websiteEventUsage += cv.websiteEventUsage;
acc.eventDataUsage += cv.eventDataUsage;
return acc;
},
{ websiteEventUsage: 0, eventDataUsage: 0 },
);
return ok(res, {
...usage,
websites: websiteUsage,
});
}
return methodNotAllowed(res);
};

View file

@ -0,0 +1,54 @@
import { useAuth, useCors, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, SearchFilter, WebsiteSearchFilterType } from 'lib/types';
import { getFilterValidation } from 'lib/yup';
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { getWebsitesByUserId } from 'queries';
import * as yup from 'yup';
export interface UserWebsitesRequestQuery extends SearchFilter<WebsiteSearchFilterType> {
id: string;
includeTeams?: boolean;
onlyTeams?: boolean;
}
const schema = {
GET: yup.object().shape({
id: yup.string().uuid().required(),
includeTeams: yup.boolean(),
onlyTeams: yup.boolean(),
...getFilterValidation(/All|Name|Domain/i),
}),
};
export default async (
req: NextApiRequestQueryBody<UserWebsitesRequestQuery>,
res: NextApiResponse,
) => {
await useCors(req, res);
await useAuth(req, res);
req.yup = schema;
await useValidate(req, res);
const { user } = req.auth;
const { id: userId, page, filter, pageSize, includeTeams, onlyTeams } = req.query;
if (req.method === 'GET') {
if (!user.isAdmin && user.id !== userId) {
return unauthorized(res);
}
const websites = await getWebsitesByUserId(userId, {
page,
filter,
pageSize: +pageSize || null,
includeTeams,
onlyTeams,
});
return ok(res, websites);
}
return methodNotAllowed(res);
};

View file

@ -0,0 +1,80 @@
import { canCreateUser, canViewUsers } from 'lib/auth';
import { ROLES } from 'lib/constants';
import { uuid } from 'lib/crypto';
import { useAuth, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, Role, SearchFilter, User, UserSearchFilterType } from 'lib/types';
import { getFilterValidation } from 'lib/yup';
import { NextApiResponse } from 'next';
import { badRequest, hashPassword, methodNotAllowed, ok, unauthorized } from 'next-basics';
import { createUser, getUserByUsername, getUsers } from 'queries';
export interface UsersRequestQuery extends SearchFilter<UserSearchFilterType> {}
export interface UsersRequestBody {
username: string;
password: string;
id: string;
role?: Role;
}
import * as yup from 'yup';
const schema = {
GET: yup.object().shape({
...getFilterValidation(/All|Username/i),
}),
POST: yup.object().shape({
username: yup.string().max(255).required(),
password: yup.string().required(),
id: yup.string().uuid(),
role: yup
.string()
.matches(/admin|user|view-only/i)
.required(),
}),
};
export default async (
req: NextApiRequestQueryBody<UsersRequestQuery, UsersRequestBody>,
res: NextApiResponse<User[] | User>,
) => {
await useAuth(req, res);
req.yup = schema;
await useValidate(req, res);
if (req.method === 'GET') {
if (!(await canViewUsers(req.auth))) {
return unauthorized(res);
}
const { page, filter, pageSize } = req.query;
const users = await getUsers({ page, filter, pageSize: pageSize ? +pageSize : null });
return ok(res, users);
}
if (req.method === 'POST') {
if (!(await canCreateUser(req.auth))) {
return unauthorized(res);
}
const { username, password, role, id } = req.body;
const existingUser = await getUserByUsername(username, { showDeleted: true });
if (existingUser) {
return badRequest(res, 'User already exists');
}
const created = await createUser({
id: id || uuid(),
username,
password: hashPassword(password),
role: role ?? ROLES.user,
});
return ok(res, created);
}
return methodNotAllowed(res);
};