-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathrequestToken.js
More file actions
48 lines (40 loc) · 1.39 KB
/
requestToken.js
File metadata and controls
48 lines (40 loc) · 1.39 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
'use strict';
const jwt = require('jsonwebtoken');
const { promisify } = require('../utils/promise');
const lookup = require('../utils/lookup');
const requestToken = async (strategy, req, options) => {
// Get address from addressField
const addressField = strategy.deliver.addressField;
const address = options.allowPost
? lookup(req.body, addressField) || lookup(req.query, addressField)
: lookup(req.query, addressField);
if (!address) {
return strategy.fail(
new Error(options.badRequestMessage || `Missing ${addressField}`),
400
);
}
// Verify user
const user = await strategy.verify(address).catch(err => strategy.fail(err));
if (!user) {
return strategy.fail(
new Error(options.authMessage || `No user found`),
400
);
}
// Generate JWT
const createToken = promisify(jwt.sign);
const token = await createToken(
{ user, iat: Math.floor(Date.now() / 1000) },
strategy.secret,
{ expiresIn: strategy.ttl }
).catch(err => strategy.error(err));
// Deliver JWT
await strategy.deliver
.send(user, token, req)
.catch(err => strategy.error(err));
// Pass without making a success or fail decision (No passport user will be set)
// https://github.com/jaredhanson/passport/blob/master/lib/middleware/authenticate.js#L329
return strategy.pass({ message: 'Token succesfully delivered' });
};
module.exports = requestToken;