-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.js
82 lines (71 loc) · 2.2 KB
/
auth.js
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
const cds = require('@sap/cds');
const DEBUG = cds.debug('cds-azure-ad');
const passport = require('passport');
const config = require('./config');
var OIDCBearerStrategy = require('passport-azure-ad').BearerStrategy;
const AzureADUser = class extends cds.User {
is(role) {
DEBUG && DEBUG('Requested role: ' + role);
return this._roles[role];
}
};
module.exports = async (req, res, next) => {
var options = {
// The URL of the metadata document for your app. We will put the keys for token validation from the URL found in the jwks_uri tag of the in the metadata.
identityMetadata: config.creds.identityMetadata,
clientID: config.creds.clientID,
validateIssuer: config.creds.validateIssuer,
issuer: config.creds.issuer,
passReqToCallback: config.creds.passReqToCallback,
audience: config.creds.audience,
loggingLevel: config.creds.loggingLevel,
loggingNoPII: true
};
passport.initialize();
passport.use(
new OIDCBearerStrategy(options, function (token, done) {
DEBUG && DEBUG('verifying the user');
DEBUG && DEBUG(token, 'was the token retreived');
var user = token.oid;
return done(null, user, token);
})
);
passport.authenticate('oauth-bearer', async function (err, user, token) {
var capUser = {
id: '',
email: '',
firstName: '',
lastName: '',
role: '',
_roles: []
};
if (err) {
DEBUG && DEBUG('err');
DEBUG && DEBUG(err);
return next(err);
}
if (!user) {
DEBUG && DEBUG('No user');
//return next(Error(token));
} else {
let email = token.preferred_username.toLowerCase(); // Contains email address
const { Persons } = cds.entities;
const person = await SELECT.one(Persons).where({ email: email });
if (person) {
capUser = {
id: person.ID,
email: email,
firstname: person.firstname,
lastname: person.lastname,
role: person.role,
unit_ID: person.unit_ID,
_roles: ['authenticated-user']
};
capUser._roles.push(person.role);
}
}
DEBUG && DEBUG(capUser);
req.user = new AzureADUser(capUser);
next();
})(req, res, next);
};