Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
🚧 Update some user rests
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Apr 1, 2020
1 parent d280a6c commit d389775
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 85 deletions.
38 changes: 19 additions & 19 deletions src/crud/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
tableName
} from "../helpers/mysql";
import { KeyValue } from "../interfaces/general";
import { prisma } from "../helpers/prisma";
import { usersDelegate } from "@prisma/client";

/*
* Get pagination data
Expand All @@ -19,7 +21,19 @@ export const getPaginatedData = async <T>({
search,
sort = "asc"
}: {
table: string;
table:
| "access_tokens"
| "api_keys"
| "approved_locations"
| "backup_codes"
| "domains"
| "emails"
| "identities"
| "memberships"
| "organizations"
| "sessions"
| "users"
| "webhooks";
conditions?: KeyValue;
start?: number;
itemsPerPage?: number;
Expand All @@ -28,24 +42,10 @@ export const getPaginatedData = async <T>({
search?: string;
sort?: string;
}) => {
const data = (await query(
`SELECT * FROM ${tableName(table)} WHERE ${primaryKey} ${
sort === "asc" ? ">" : "<"
} ? ${
conditions
? `AND ${Object.keys(conditions)
.map(condition => `${condition} = ?`)
.join(" AND ")}`
: ""
}${
q && search ? ` AND \`${search}\` LIKE "%?%"` : ""
} ORDER BY ${primaryKey} ${sort.toUpperCase()} LIMIT ${itemsPerPage}`,
[
sort === "desc" && start == 0 ? 99999999999 : start,
...(conditions ? Object.values(conditions) : []),
q
]
)) as Array<T>;
const data = await (prisma[table] as usersDelegate).findMany({
where: conditions,
after: { id: start }
});
return {
data,
hasMore: data.length == itemsPerPage,
Expand Down
103 changes: 37 additions & 66 deletions src/rest/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,73 +3,46 @@ import {
INSUFFICIENT_PERMISSION,
INVALID_2FA_TOKEN,
MISSING_PASSWORD,
NOT_ENABLED_2FA
NOT_ENABLED_2FA,
USER_NOT_FOUND
} from "@staart/errors";
import { compare } from "@staart/text";
import { authenticator } from "otplib";
import { toDataURL } from "qrcode";
import { SERVICE_2FA } from "../config";
import { getPaginatedData } from "../crud/data";
import {
deleteAllUserEmails,
getUserEmails,
getUserPrimaryEmail,
getUserBestEmail
} from "../crud/email";
import {
addOrganizationToMemberships,
deleteAllUserMemberships,
getUserMembershipsDetailed
} from "../crud/membership";
import {
createAccessToken,
createBackupCodes,
createIdentityConnect,
createIdentityGetOAuthLink,
deleteAccessToken,
deleteAllUserApprovedLocations,
deleteIdentity,
deleteSession,
deleteUser,
deleteUserBackupCodes,
getAccessToken,
getIdentity,
getSession,
getUser,
getUserAccessTokens,
getUserApprovedLocations,
getUserBackupCodes,
getUserIdentities,
getUserSessions,
updateAccessToken,
updateUser,
getUserIdFromUsername
} from "../crud/user";
import { can } from "../helpers/authorization";
import { trackEvent } from "../helpers/tracking";
import { EventType, UserScopes, Templates } from "../interfaces/enum";
import { KeyValue, Locals } from "../interfaces/general";
import { Event } from "../interfaces/tables/events";
import { Membership } from "../interfaces/tables/memberships";
import { User } from "../interfaces/tables/user";
import { mail } from "../helpers/mail";
import { couponCodeJwt } from "../helpers/jwt";
import { prisma } from "../helpers/prisma";
import { users, memberships } from "@prisma/client";

export const getUserFromId = async (userId: string, tokenUserId: string) => {
if (await can(tokenUserId, UserScopes.READ_USER, "user", userId))
return getUser(userId);
if (await can(tokenUserId, UserScopes.READ_USER, "user", userId)) {
const user = await prisma.users.findOne({
where: { id: parseInt(userId) }
});
if (user) return user;
throw new Error(USER_NOT_FOUND);
}
throw new Error(INSUFFICIENT_PERMISSION);
};

export const updateUserForUser = async (
tokenUserId: string,
updateUserId: string,
data: User,
data: users,
locals: Locals
) => {
delete data.password;
if (await can(tokenUserId, UserScopes.UPDATE_USER, "user", updateUserId)) {
await updateUser(updateUserId, data);
const user = await prisma.users.update({
data,
where: { id: parseInt(updateUserId) }
});
trackEvent(
{
userId: tokenUserId,
Expand All @@ -78,7 +51,7 @@ export const updateUserForUser = async (
},
locals
);
return;
return user;
}
throw new Error(INSUFFICIENT_PERMISSION);
};
Expand All @@ -93,11 +66,17 @@ export const updatePasswordForUser = async (
if (
await can(tokenUserId, UserScopes.CHANGE_PASSWORD, "user", updateUserId)
) {
const user = await getUser(updateUserId, true);
const user = await prisma.users.findOne({
where: { id: parseInt(updateUserId) }
});
if (!user) throw new Error(USER_NOT_FOUND);
if (!user.password) throw new Error(MISSING_PASSWORD);
const correctPassword = await compare(oldPassword, user.password);
if (!correctPassword) throw new Error(INCORRECT_PASSWORD);
await updateUser(updateUserId, { password: newPassword });
const result = await prisma.users.update({
data: { password: newPassword },
where: { id: parseInt(updateUserId) }
});
trackEvent(
{
userId: tokenUserId,
Expand All @@ -106,7 +85,7 @@ export const updatePasswordForUser = async (
},
locals
);
return;
return result;
}
throw new Error(INSUFFICIENT_PERMISSION);
};
Expand All @@ -117,10 +96,16 @@ export const deleteUserForUser = async (
locals: Locals
) => {
if (await can(tokenUserId, UserScopes.DELETE_USER, "user", updateUserId)) {
await deleteAllUserEmails(updateUserId);
await deleteAllUserMemberships(updateUserId);
await deleteAllUserApprovedLocations(updateUserId);
await deleteUser(updateUserId);
await prisma.emails.deleteMany({
where: { userId: parseInt(updateUserId) }
});
await prisma.memberships.deleteMany({
where: { userId: parseInt(updateUserId) }
});
await prisma.approved_locations.deleteMany({
where: { userId: parseInt(updateUserId) }
});
await prisma.users.deleteMany({ where: { id: parseInt(updateUserId) } });
trackEvent(
{
userId: tokenUserId,
Expand All @@ -134,20 +119,6 @@ export const deleteUserForUser = async (
throw new Error(INSUFFICIENT_PERMISSION);
};

export const getRecentEventsForUser = async (
tokenUserId: string,
dataUserId: string,
query: KeyValue
) => {
if (await can(tokenUserId, UserScopes.READ_USER, "user", dataUserId))
return await getPaginatedData<Event>({
table: "events",
conditions: { userId: dataUserId },
...query
});
throw new Error(INSUFFICIENT_PERMISSION);
};

export const getMembershipsForUser = async (
tokenUserId: string,
dataUserId: string,
Expand All @@ -156,7 +127,7 @@ export const getMembershipsForUser = async (
if (
await can(tokenUserId, UserScopes.READ_USER_MEMBERSHIPS, "user", dataUserId)
) {
const memberships = await getPaginatedData<Membership>({
const memberships = await getPaginatedData<memberships>({
table: "memberships",
conditions: { userId: dataUserId },
...query
Expand Down

0 comments on commit d389775

Please sign in to comment.