-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.js
75 lines (63 loc) · 1.62 KB
/
index.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
import passport from 'koa-passport';
import compose from 'koa-compose';
import jwt from 'jsonwebtoken';
import User from '../models/User';
import { auth as config } from './config';
// Strategies
import jwtStrategy from './strategies/jwt';
import emailStrategy from './strategies/email';
passport.use('jwt', jwtStrategy);
passport.use('email', emailStrategy);
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((id, done) => {
(async () => {
try {
const user = await User.findById(id);
done(null, user);
} catch (error) {
done(error);
}
})();
});
export default function auth() {
return compose([
passport.initialize(),
]);
}
export function isAuthenticated() {
return passport.authenticate('jwt');
}
export function authEmail() {
return passport.authenticate('email');
}
// After autentication using one of the strategies, generate a JWT token
export function generateToken() {
return async ctx => {
const { user } = ctx.passport;
if (user === false) {
ctx.status = 401;
} else {
const jwtToken = jwt.sign({ id: user }, config.secret);
const token = `JWT ${jwtToken}`;
const currentUser = await User.findOne({ _id: user });
ctx.status = 200;
ctx.body = {
token,
user: currentUser,
};
}
};
}
// Web Facebook Authentication
export function isFacebookAuthenticated() {
return passport.authenticate('facebook', {
scope: ['email'],
});
}
export function isFacebookAuthenticatedCallback() {
return passport.authenticate('facebook', {
failureRedirect: '/login',
});
}