-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathauth.js
47 lines (40 loc) · 1.44 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
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const Admin = require('./models/admin.model');
const logger = require('./logger');
const errorCodes = require('./constants/errorCodes');
const baseURL = require('./constants/apiURL');
module.exports = (passport) => {
const { OAUTH_CLIENT_ID, CLIENT_SECRET } = process.env;
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
passport.use(new GoogleStrategy({
clientID: OAUTH_CLIENT_ID,
clientSecret: CLIENT_SECRET,
callbackURL: `${baseURL}/auth/redirect`
},
async (token, refreshToken, profile, done) => {
let email;
if (profile.emails && profile.emails.length) {
email = profile.emails[0].value;
}
try {
if (!email) {
throw new Error();
}
const admin = await Admin.findOne({ email });
if (!admin) {
throw new Error();
}
return done(null, { _id: admin._id, email });
} catch (error) {
logger.error(`Admin access denied, email was: ${email}`, error);
const err = new Error();
err.code = errorCodes[0];
return done(err, null);
}
}));
};