-
Notifications
You must be signed in to change notification settings - Fork 8
/
oauth.js
65 lines (58 loc) · 2.21 KB
/
oauth.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
var oauth2orize = require('oauth2orize')
, passport = require('passport')
, db = require('./db').db()
, crypto = require('crypto')
, utils = require("./utils")
, bcrypt = require('bcrypt')
// create OAuth 2.0 server
var server = oauth2orize.createServer();
//(De-)Serialization for clients
server.serializeClient(function(client, done) {
return done(null, client.clientId)
})
server.deserializeClient(function(id, done) {
db.collection('clients').find({clientId: id}, function(err, client) {
if (err) return done(err)
//mongojs db.find returns and array - we need just the matching client doc so get the
return done(null, client[0])
})
})
//Implicit grant
server.grant(oauth2orize.grant.token(function (client, user, ares, done) {
var token = utils.uid(256)
var tokenHash = crypto.createHash('sha1').update(token).digest('hex')
var expirationDate = new Date(new Date().getTime() + (3600 * 1000))
//typo - client-clienId shoudl be client.clientId
db.collection('accessTokens').save({token: tokenHash, expirationDate: expirationDate, userId: user.username, clientId: client.clientId}, function(err) {
if (err) return done(err)
return done(null, token, {expires_in: expirationDate.toISOString()})
})
}))
// user authorization endpoint
exports.authorization = [
function(req, res, next) {
if (req.user) next()
else res.redirect('/oauth/authorization')
},
server.authorization(function(clientId, redirectURI, done) {
db.collection('clients').findOne({clientId: clientId}, function(err, client) {
if (err) return done(err)
// WARNING: For security purposes, it is highly advisable to check that
// redirectURI provided by the client matches one registered with
// the server. For simplicity, this example does not. You have
// been warned.
return done(null, client, redirectURI)
})
}),
function(req, res) {
res.render('decision', { transactionID: req.oauth2.transactionID, user: req.user, client: req.oauth2.client });
}
]
// user decision endpoint
exports.decision = [
function(req, res, next) {
if (req.user) next()
else res.redirect('/oauth/authorization')
},
server.decision()
]