-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathoidc.strategy.ts
More file actions
153 lines (145 loc) · 4.82 KB
/
oidc.strategy.ts
File metadata and controls
153 lines (145 loc) · 4.82 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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import {Injectable, UnauthorizedException} from '@nestjs/common';
import {PassportStrategy} from '@nestjs/passport';
import {Strategy} from '@govtechsg/passport-openidconnect';
import {HttpsProxyAgent} from 'https-proxy-agent';
import winston from 'winston';
import {ConfigService} from '../config/config.service';
import {GroupsService} from '../groups/groups.service';
import {AuthnService} from './authn.service';
import {Request} from 'express';
import 'express-session';
declare module 'express-session' {
interface SessionData {
redirectLogin?: string;
}
}
interface OIDCProfile {
id: string;
displayName: string;
name: {familyName: string; givenName: string};
emails: [{value: string}];
_raw: string;
_json: {
given_name: string;
family_name: string;
email: string;
email_verified: boolean;
groups: string[];
};
}
@Injectable()
export class OidcStrategy extends PassportStrategy(Strategy, 'oidc') {
authenticate(req: Request, options: Record<string, unknown> = {}) {
const redirect =
typeof req.query?.redirect === 'string' &&
req.query.redirect.startsWith('/')
? req.query.redirect
: undefined;
if (redirect) {
super.authenticate(req, {
...options,
state: encodeURIComponent(redirect)
});
return;
}
super.authenticate(req);
}
private readonly line = '_______________________________________________\n';
public loggingTimeFormat = 'MMM-DD-YYYY HH:mm:ss Z';
public logger = winston.createLogger({
transports: [new winston.transports.Console()],
format: winston.format.combine(
winston.format.timestamp({
format: this.loggingTimeFormat
}),
winston.format.printf(
(info) =>
`${this.line}[${[info.timestamp]}] (Authn Service): ${info.message}`
)
)
});
constructor(
private readonly authnService: AuthnService,
private readonly configService: ConfigService,
private readonly groupsService: GroupsService
) {
super(
{
issuer: configService.get('OIDC_ISSUER') || 'disabled',
authorizationURL:
configService.get('OIDC_AUTHORIZATION_URL') || 'disabled',
tokenURL: configService.get('OIDC_TOKEN_URL') || 'disabled',
userInfoURL: configService.get('OIDC_USER_INFO_URL') || 'disabled',
clientID: configService.get('OIDC_CLIENTID') || 'disabled',
clientSecret: configService.get('OIDC_CLIENT_SECRET') || 'disabled',
callbackURL: `${configService.get('EXTERNAL_URL')}/authn/oidc_callback`,
pkce:
configService.get('OIDC_USES_PKCE_S256') === 'true'
? 'S256'
: configService.get('OIDC_USES_PKCE_PLAIN') === 'true'
? 'plain'
: undefined,
scope: ['openid', 'email', 'profile'],
skipUserProfile: false,
proxy:
configService.get('OIDC_USE_HTTPS_PROXY') === 'true'
? true
: undefined,
agent:
configService.get('OIDC_USE_HTTPS_PROXY') === 'true'
? new HttpsProxyAgent(configService.get('HTTPS_PROXY') ?? '')
: undefined
},
// using the 9-arity function so that we can access the underlying JSON response and extract the 'email_verified' attribute
async (
req: Request,
_issuer: string,
uiProfile: OIDCProfile,
_idProfile: object,
_context: object,
_idToken: string,
_accessToken: string,
_refreshToken: string,
_params: object,
//eslint-disable-next-line @typescript-eslint/no-explicit-any
done: any
) => {
const redirectLogin =
typeof req.query?.state === 'string'
? decodeURIComponent(req.query.state as string)
: undefined;
if (redirectLogin?.startsWith('/')) {
req.session.redirectLogin = redirectLogin;
}
this.logger.debug('in oidc strategy file');
this.logger.debug(JSON.stringify(uiProfile, null, 2));
const userData = uiProfile._json;
const {given_name, family_name, email, email_verified, groups} =
userData;
if (
configService.get('OIDC_USES_VERIFIED_EMAIL') === 'false' ||
email_verified
) {
const user = await authnService.validateOrCreateUser(
email,
given_name,
family_name,
'oidc'
);
if (
configService.get('OIDC_EXTERNAL_GROUPS') === 'true' &&
groups !== undefined
) {
await groupsService.syncUserGroups(user, groups);
}
return done(null, user);
}
return done(
new UnauthorizedException(
'Please verify your name and email with your identity provider before logging into Heimdall.'
)
);
}
);
}
}