-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
69 lines (62 loc) · 1.8 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
const passport = require("koa-passport");
const { Strategy, ExtractJwt } = require("passport-jwt");
const crypto = require("crypto");
const jwt = require("jsonwebtoken");
const { AuthError } = require("@salsita/errors");
const defaultAlgorithm = "HS384";
const defaultExpiresIn = "6h";
const defaultVersion = 1;
module.exports = ({
key = crypto.randomBytes(30).toString("base64"),
algorithm = defaultAlgorithm,
expiresIn = defaultExpiresIn,
version = defaultVersion,
createSession,
getUserForSession,
}) => {
const resignPayload = (payload) => {
delete payload.exp; // eslint-disable-line no-param-reassign
return jwt.sign(payload, key, { algorithm, expiresIn });
};
const createSessionToken = async (...args) => {
const payload = await createSession(...args);
return resignPayload({ payload, version });
};
const isSessionValid = (session) => session && session.version === version;
passport.use(
new Strategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: key,
algorithms: [algorithm],
},
async (jwtPayload, done) => {
if (!isSessionValid(jwtPayload)) {
return done(null, false);
}
try {
const user = await getUserForSession(jwtPayload.payload);
done(null, user || false);
} catch (err) {
done(err);
}
return null;
}
)
);
return {
createSessionToken,
middleware: async (ctx, next) => {
await passport.authenticate("jwt", { session: false }, async (authErr, user) => {
if (authErr) {
throw authErr;
}
if (!user) {
throw new AuthError("Unauthorized");
}
return ctx.logIn(user, { session: false });
})(ctx);
return next();
},
};
};