-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmagicLink.controller.ts
More file actions
138 lines (125 loc) · 4.96 KB
/
magicLink.controller.ts
File metadata and controls
138 lines (125 loc) · 4.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import { StatusCodes } from 'http-status-codes';
import fastifyPassport from '@fastify/passport';
import type { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox';
import type { PassportUser, preHandlerHookHandler } from 'fastify';
import type { RouteShorthandHook } from 'fastify/types/route';
import { ClientManager, Context, DEFAULT_LANG, RecaptchaAction } from '@graasp/sdk';
import { resolveDependency } from '../../../../di/utils';
import { db } from '../../../../drizzle/db';
import { asDefined } from '../../../../utils/assertions';
import { MemberAlreadySignedUp } from '../../../../utils/errors';
import { isMember } from '../../../authentication';
import { InvitationService } from '../../../item/plugins/invitation/invitation.service';
import { MemberService } from '../../../member/member.service';
import { getRedirectionLink } from '../../utils';
import captchaPreHandler from '../captcha/captcha';
import { PassportStrategy } from '../passport/strategies';
import type { PassportInfo } from '../passport/types';
import { auth, login, register, signOut } from './magicLink.schemas';
import { MagicLinkService } from './magicLink.service';
const ERROR_SEARCH_PARAM = 'error';
const plugin: FastifyPluginAsyncTypebox = async (fastify) => {
const memberService = resolveDependency(MemberService);
const magicLinkService = resolveDependency(MagicLinkService);
const invitationService = resolveDependency(InvitationService);
fastify.post(
'/register',
{ schema: register, preHandler: captchaPreHandler(RecaptchaAction.SignUp) },
async (request, reply) => {
const {
body,
query: { lang = DEFAULT_LANG },
} = request;
const { url } = body;
return db.transaction(async (tx) => {
try {
// we use member service to allow post hook for invitation
const member = await memberService.post(tx, body, lang);
await magicLinkService.sendRegisterMail(member.toMemberInfo(), url);
// transform memberships from existing invitations
await invitationService.createToMemberships(tx, member);
reply.status(StatusCodes.NO_CONTENT);
} catch (e) {
if (!(e instanceof MemberAlreadySignedUp)) {
throw e;
}
// send login email
await magicLinkService.login(tx, body, lang);
reply.status(StatusCodes.NO_CONTENT);
}
});
},
);
// login
fastify.post(
'/login',
{
schema: login,
preHandler: captchaPreHandler(RecaptchaAction.SignIn),
},
async (request, reply) => {
const { body } = request;
const { url } = body;
await magicLinkService.login(db, body, url);
reply.status(StatusCodes.NO_CONTENT);
},
);
// authenticate
fastify.get(
'/auth',
{
schema: auth,
preHandler: fastifyPassport.authenticate(
PassportStrategy.WebMagicLink,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
async (request, reply, err, user?: PassportUser, info?: PassportInfo) => {
// This function is called after the strategy has been executed.
// It is necessary, so we match the behavior of the original implementation.
if (!user || err) {
// Authentication failed
const target = ClientManager.getInstance().getURLByContext(Context.Auth);
if (err) {
target.searchParams.set(ERROR_SEARCH_PARAM, err.message);
} else if (!user) {
target.searchParams.set(ERROR_SEARCH_PARAM, 'TOKEN_EXPIRED');
} else {
target.searchParams.set(ERROR_SEARCH_PARAM, 'UNEXPECTED_ERROR');
}
reply.redirect(target.toString(), StatusCodes.SEE_OTHER);
} else {
request.logIn(user, { session: true });
request.authInfo = info;
}
},
) as RouteShorthandHook<preHandlerHookHandler>,
},
async (request, reply) => {
const {
user,
authInfo,
query: { url },
log,
} = request;
const member = asDefined(user?.account);
const redirectionLink = getRedirectionLink(log, url ? decodeURIComponent(url) : undefined);
await db.transaction(async (tx) => {
await memberService.refreshLastAuthenticatedAt(tx, member.id);
// on auth, if the user used the email sign in, its account gets validated
if (authInfo?.emailValidation && isMember(member) && !member.isValidated) {
await memberService.validate(tx, member.id);
}
});
reply.redirect(redirectionLink, StatusCodes.SEE_OTHER);
},
);
// logout
fastify.post('/logout', { schema: signOut }, async (request, reply) => {
// logout user, so subsequent calls can not make use of the current user.
request.logout();
// remove session so the cookie is removed by the browser
request.session.delete();
reply.status(StatusCodes.NO_CONTENT);
});
};
export default plugin;