Skip to content

Commit

Permalink
Merge pull request #31 from uwblueprint/S24/jerry/revert-roles-table
Browse files Browse the repository at this point in the history
S24/jerry/revert roles table
  • Loading branch information
jerry-cheng5 authored Sep 12, 2024
2 parents 685107b + 2a2cbcf commit 434e6f4
Show file tree
Hide file tree
Showing 15 changed files with 163 additions and 103 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// TODO: DEPRECATED, LEAVING FOR FUTURE REFERENCE

import { DataType } from "sequelize-typescript";

import { Migration } from "../umzug";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// TODO: DEPRECATED, LEAVING FOR FUTURE REFERENCE

import { DataType } from "sequelize-typescript";
import { Migration } from "../umzug";

Expand All @@ -16,6 +18,7 @@ export const up: Migration = async ({ context: sequelize }) => {
});

await queryInterface.removeColumn("users", "role");
await sequelize.query(`DROP TYPE IF EXISTS enum_users_role;`);
};

export const down: Migration = async ({ context: sequelize }) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { DataType } from "sequelize-typescript";

import { Migration } from "../umzug";

export const up: Migration = async ({ context: sequelize }) => {
await sequelize.getQueryInterface().removeColumn("users", "role_id");
await sequelize.getQueryInterface().addColumn("users", "role", {
type: DataType.ENUM(
"Administrator",
"Animal Behaviourist",
"Staff",
"Volunteer",
),
allowNull: false,
});

await sequelize.getQueryInterface().dropTable("roles");
};

export const down: Migration = async ({ context: sequelize }) => {
await sequelize.getQueryInterface().createTable("roles", {
id: {
type: DataType.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
role_name: {
type: DataType.STRING,
allowNull: false,
},
});

await sequelize
.getQueryInterface()
.bulkInsert("roles", [
{ role_name: "Administrator" },
{ role_name: "Animal Behaviourist" },
{ role_name: "Staff" },
{ role_name: "Volunteer" },
]);

await sequelize.getQueryInterface().addColumn("users", "role_id", {
type: DataType.INTEGER,
allowNull: true,
references: {
model: "roles",
key: "id",
},
onUpdate: "CASCADE",
onDelete: "SET NULL",
});

await sequelize.getQueryInterface().removeColumn("users", "role");
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { DataType } from "sequelize-typescript";
import { Migration } from "../umzug";

export const up: Migration = async ({ context: sequelize }) => {
await sequelize.getQueryInterface().addColumn("users", "status", {
type: DataType.ENUM("Active", "Invited", "Inactive"),
allowNull: false,
});
};

export const down: Migration = async ({ context: sequelize }) => {
await sequelize.getQueryInterface().removeColumn("users", "status");
await sequelize.query(`DROP TYPE IF EXISTS enum_users_status;`);
};
15 changes: 7 additions & 8 deletions backend/typescript/models/user.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ import {
DataType,
Model,
Table,
ForeignKey,
BelongsTo,
AllowNull,
} from "sequelize-typescript";
import Role from "./role.model";
import { Role, UserStatus } from "../types";

@Table({ tableName: "users" })
export default class User extends Model {
Expand All @@ -19,11 +18,8 @@ export default class User extends Model {
@Column({ type: DataType.STRING, allowNull: false })
auth_id!: string;

@ForeignKey(() => Role)
@Column({ type: DataType.INTEGER })
role_id!: number;

@BelongsTo(() => Role)
@AllowNull(false)
@Column({ type: DataType.ENUM(...Object.values(Role)), allowNull: false })
role!: Role;

@Column({ type: DataType.STRING, allowNull: false })
Expand All @@ -40,4 +36,7 @@ export default class User extends Model {

@Column({ type: DataType.STRING })
phone_number?: string | null;

@Column({ type: DataType.ENUM("Active", "Inactive"), allowNull: false })
status!: UserStatus;
}
6 changes: 4 additions & 2 deletions backend/typescript/rest/authRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import IAuthService from "../services/interfaces/authService";
import IEmailService from "../services/interfaces/emailService";
import IUserService from "../services/interfaces/userService";
import { getErrorMessage } from "../utilities/errorUtils";
import { Role, UserStatus } from "../types";

const authRouter: Router = Router();
const userService: IUserService = new UserService();
Expand Down Expand Up @@ -51,7 +52,8 @@ authRouter.post("/register", registerRequestValidator, async (req, res) => {
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
role: req.body.role,
role: req.body.role ?? Role.VOLUNTEER,
status: req.body.status ?? UserStatus.ACTIVE, // TODO: make this default to inactive once user registration flow is done
skillLevel: req.body.skillLevel ?? null,
canSeeAllLogs: req.body.canSeeAllLogs ?? null,
canAssignUsersToTasks: req.body.canAssignUsersToTasks ?? null,
Expand All @@ -65,7 +67,7 @@ authRouter.post("/register", registerRequestValidator, async (req, res) => {
);
const { refreshToken, ...rest } = authDTO;

await authService.sendEmailVerificationLink(req.body.email);
// await authService.sendEmailVerificationLink(req.body.email); // TODO: Uncomment once email service is ready

res
.cookie("refreshToken", refreshToken, cookieOptions)
Expand Down
4 changes: 2 additions & 2 deletions backend/typescript/rest/entityRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ import {
} from "../services/interfaces/IEntityService";
import { getErrorMessage } from "../utilities/errorUtils";
import { sendResponseByMimeType } from "../utilities/responseUtil";
import { RoleEnum } from "../types";
import { Role } from "../types";

const upload = multer({ dest: "uploads/" });

const entityRouter: Router = Router();
entityRouter.use(isAuthorizedByRole(new Set(Object.values(RoleEnum))));
entityRouter.use(isAuthorizedByRole(new Set(Object.values(Role))));

const defaultBucket = process.env.FIREBASE_STORAGE_DEFAULT_BUCKET || "";
const fileStorageService: IFileStorageService = new FileStorageService(
Expand Down
4 changes: 2 additions & 2 deletions backend/typescript/rest/simpleEntityRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import {
} from "../services/interfaces/simpleEntityService";
import { getErrorMessage } from "../utilities/errorUtils";
import { sendResponseByMimeType } from "../utilities/responseUtil";
import { RoleEnum } from "../types";
import { Role } from "../types";

const simpleEntityRouter: Router = Router();
simpleEntityRouter.use(isAuthorizedByRole(new Set(Object.values(RoleEnum))));
simpleEntityRouter.use(isAuthorizedByRole(new Set(Object.values(Role))));

const simpleEntityService: ISimpleEntityService = new SimpleEntityService();

Expand Down
10 changes: 6 additions & 4 deletions backend/typescript/rest/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import UserService from "../services/implementations/userService";
import IAuthService from "../services/interfaces/authService";
import IEmailService from "../services/interfaces/emailService";
import IUserService from "../services/interfaces/userService";
import { UserDTO } from "../types";
import { Role, UserDTO, UserStatus } from "../types";
import {
getErrorMessage,
NotFoundError,
Expand All @@ -22,7 +22,7 @@ import { sendResponseByMimeType } from "../utilities/responseUtil";

const userRouter: Router = Router();
userRouter.use(
isAuthorizedByRole(new Set(["Administrator", "Animal Behaviourist"])),
isAuthorizedByRole(new Set([Role.ADMINISTRATOR, Role.ANIMAL_BEHAVIOURIST])),
);

const userService: IUserService = new UserService();
Expand Down Expand Up @@ -100,15 +100,16 @@ userRouter.post("/", createUserDtoValidator, async (req, res) => {
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
role: req.body.role,
role: req.body.role ?? Role.VOLUNTEER,
status: req.body.status ?? UserStatus.ACTIVE, // TODO: make this default to inactive once user registration flow is done
skillLevel: req.body.skillLevel ?? null,
canSeeAllLogs: req.body.canSeeAllLogs ?? null,
canAssignUsersToTasks: req.body.canSeeAllUsers ?? null,
phoneNumber: req.body.phoneNumber ?? null,
password: req.body.password,
});

await authService.sendEmailVerificationLink(req.body.email);
// await authService.sendEmailVerificationLink(req.body.email); // TODO: Uncomment once email service is ready

res.status(201).json(newUser);
} catch (error: unknown) {
Expand All @@ -129,6 +130,7 @@ userRouter.put("/:userId", updateUserDtoValidator, async (req, res) => {
lastName: req.body.lastName,
email: req.body.email,
role: req.body.role,
status: req.body.status,
skillLevel: req.body.skillLevel ?? null,
canSeeAllLogs: req.body.canSeeAllLogs ?? null,
canAssignUsersToTasks: req.body.canSeeAllUsers ?? null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { snakeCase } from "lodash";
import UserModel from "../../../models/user.model";
import UserService from "../userService";

import { RoleEnum, UserDTO, DTOTypes } from "../../../types";
import { UserDTO, Role, UserStatus } from "../../../types";

import { testSql } from "../../../testUtils/testDb";

Expand All @@ -12,13 +12,15 @@ const testUsers = [
firstName: "Peter",
lastName: "Pan",
authId: "123",
role: RoleEnum.Administrator,
role: Role.ADMINISTRATOR,
status: UserStatus.ACTIVE,
},
{
firstName: "Wendy",
lastName: "Darling",
authId: "321",
role: RoleEnum.Staff,
role: Role.STAFF,
status: UserStatus.ACTIVE,
},
];

Expand All @@ -44,7 +46,7 @@ describe("pg userService", () => {

it("getUsers", async () => {
const users = testUsers.map((user) => {
const userSnakeCase: DTOTypes = {};
const userSnakeCase: Record<string, string> = {};
Object.entries(user).forEach(([key, value]) => {
userSnakeCase[snakeCase(key)] = value;
});
Expand Down
14 changes: 9 additions & 5 deletions backend/typescript/services/implementations/authService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import * as firebaseAdmin from "firebase-admin";
import IAuthService from "../interfaces/authService";
import IEmailService from "../interfaces/emailService";
import IUserService from "../interfaces/userService";
import { AuthDTO, Role, RoleEnum, Token } from "../../types";
import { AuthDTO, Role, Token, UserStatus } from "../../types";
import { getErrorMessage } from "../../utilities/errorUtils";
import FirebaseRestClient from "../../utilities/firebaseRestClient";
import logger from "../../utilities/logger";
Expand Down Expand Up @@ -63,7 +63,8 @@ class AuthService implements IAuthService {
firstName: googleUser.firstName,
lastName: googleUser.lastName,
email: googleUser.email,
role: RoleEnum.Staff,
role: Role.STAFF,
status: UserStatus.ACTIVE,
password: "",
},
googleUser.localId,
Expand Down Expand Up @@ -179,7 +180,8 @@ class AuthService implements IAuthService {
.auth()
.getUser(decodedIdToken.uid);

return firebaseUser.emailVerified && roles.has(userRole);
// return firebaseUser.emailVerified && roles.has(userRole); // TODO: Uncomment once email service is ready
return roles.has(userRole);
} catch (error) {
return false;
}
Expand All @@ -202,7 +204,8 @@ class AuthService implements IAuthService {
.getUser(decodedIdToken.uid);

return (
firebaseUser.emailVerified && String(tokenUserId) === requestedUserId
// firebaseUser.emailVerified && String(tokenUserId) === requestedUserId // TODO: Uncomment once email service is ready
String(tokenUserId) === requestedUserId
);
} catch (error) {
return false;
Expand All @@ -223,7 +226,8 @@ class AuthService implements IAuthService {
.getUser(decodedIdToken.uid);

return (
firebaseUser.emailVerified && decodedIdToken.email === requestedEmail
// firebaseUser.emailVerified && decodedIdToken.email === requestedEmail // TODO: Uncomment once email service is ready
decodedIdToken.email === requestedEmail
);
} catch (error) {
return false;
Expand Down
Loading

0 comments on commit 434e6f4

Please sign in to comment.