Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework invitations backend #185

Merged
merged 1 commit into from
Oct 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 21 additions & 21 deletions server/src/api/invitations/invitations.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,20 @@ import Invitation from './invitations.model';
import User from '../users/users.model';
import uuid from 'uuid';
import { sendEmail } from '../../utils/sendEmail';
import { daysAgo } from '../../utils/date';

// should FRONTEND_BASE_URL and CORS_ORIGIN be same variable?
const BASE_URL = process.env.FRONTEND_BASE_URL!;

export const addInvitations: RouteHandlerFnc = async (ctx) => {
export const getInvitations: RouteHandlerFnc = async (ctx) => {
ctx.body = await Invitation.query()
.where({
roadmapId: Number(ctx.params.roadmapId),
})
.where('updatedAt', '>=', daysAgo(30));
};

export const postInvitation: RouteHandlerFnc = async (ctx) => {
const { type, email, ...others } = ctx.request.body;
if (Object.keys(others).length) return void (ctx.status = 400);

Expand All @@ -20,24 +29,15 @@ export const addInvitations: RouteHandlerFnc = async (ctx) => {

if (existingRole) throw new Error('Invitee is already a team member');

const previousInvitation = await Invitation.query()
.where({ email, roadmapId })
.first();

if (previousInvitation) {
const updated = await Invitation.query().patchAndFetchById(
previousInvitation.id,
{ type },
);
return void (ctx.body = updated);
}

const created = await Invitation.query().insertAndFetch({
id: uuid.v4(),
roadmapId,
type,
email,
});
const created = await Invitation.query()
.insertAndFetch({
id: uuid.v4(),
roadmapId,
type,
email,
})
.onConflict(['roadmapId', 'email'])
.merge();
await sendEmail(
email,
'Invitation to roadmap',
Expand All @@ -46,7 +46,7 @@ export const addInvitations: RouteHandlerFnc = async (ctx) => {
return void (ctx.body = created);
};

export const patchInvitations: RouteHandlerFnc = async (ctx) => {
export const patchInvitation: RouteHandlerFnc = async (ctx) => {
const { id, type, email, roadmapId, ...others } = ctx.request.body;
if (Object.keys(others).length) return void (ctx.status = 400);

Expand All @@ -62,7 +62,7 @@ export const patchInvitations: RouteHandlerFnc = async (ctx) => {
}
};

export const deleteInvitations: RouteHandlerFnc = async (ctx) => {
export const deleteInvitation: RouteHandlerFnc = async (ctx) => {
const numDeleted = await Invitation.query()
.where({
id: ctx.params.invitationId,
Expand Down
20 changes: 19 additions & 1 deletion server/src/api/invitations/invitations.model.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { Model } from 'objection';
import { Model, Pojo } from 'objection';
import { RoleType } from '../../../../shared/types/customTypes';
import { daysAgo } from '../../utils/date';

export default class Invitation extends Model {
id!: string;
roadmapId!: number;
type!: RoleType;
email!: string;
updatedAt!: Date;

valid?: boolean;

static tableName = 'invitations';

Expand All @@ -18,4 +22,18 @@ export default class Invitation extends Model {
email: { type: 'string', format: 'email', minLength: 1, maxLength: 255 },
},
};

$beforeInsert() {
this.updatedAt = new Date();
}
$beforeUpdate() {
this.updatedAt = new Date();
}
$parseDatabaseJson(json: Pojo) {
json = super.$parseDatabaseJson(json);
json.updatedAt = json.updatedAt && new Date(json.updatedAt);

json.valid = json.updatedAt >= daysAgo(2);
return json;
}
}
19 changes: 13 additions & 6 deletions server/src/api/invitations/invitations.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,36 @@ import { Context } from 'koa';
import { IKoaState } from '../../types/customTypes';
import { Permission } from '../../../../shared/types/customTypes';
import {
addInvitations,
patchInvitations,
deleteInvitations,
getInvitations,
postInvitation,
patchInvitation,
deleteInvitation,
} from './invitations.controller';

const invitationsRouter = new KoaRouter<IKoaState, Context>();

invitationsRouter.get(
'/invitations',
requirePermission(Permission.RoadmapInvite),
getInvitations,
);

invitationsRouter.post(
'/invitations',
requirePermission(Permission.RoadmapInvite),
addInvitations,
postInvitation,
);

invitationsRouter.patch(
'/invitations/:invitationId',
requirePermission(Permission.RoadmapInvite),
patchInvitations,
patchInvitation,
);

invitationsRouter.delete(
'/invitations/:invitationId',
requirePermission(Permission.RoadmapInvite),
deleteInvitations,
deleteInvitation,
);

export default invitationsRouter;
4 changes: 3 additions & 1 deletion server/src/api/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,11 @@ export const getUserRoles: RouteHandlerFnc = async (ctx) => {
export const joinRoadmap: RouteHandlerFnc = async (ctx) => {
if (!ctx.state.user) throw new Error('User is required');
const { ...others } = ctx.request.body;

const invitation = await Invitation.query().findById(ctx.params.invitationId);

if (Object.keys(others).length || !invitation) return void (ctx.status = 400);
if (Object.keys(others).length || !invitation || !invitation.valid)
return void (ctx.status = 400);
if (invitation.email !== ctx.state.user.email) return void (ctx.status = 403);

const role = await Invitation.transaction(async (trx) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as Knex from 'knex';

export async function up(knex: Knex): Promise<void> {
return knex.schema.alterTable('invitations', (table) => {
table.timestamp('updatedAt');
table.unique(['roadmapId', 'email']);
});
}

export async function down(knex: Knex): Promise<void> {
return knex.schema.alterTable('invitations', (table) => {
table.dropColumn('updatedAt');
table.dropUnique(['roadmapId', 'email']);
});
}
5 changes: 5 additions & 0 deletions server/src/utils/date.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const daysAgo = (days: number) => {
const dateNow = new Date();
dateNow.setDate(dateNow.getDate() - days);
return dateNow;
};