-
-
Notifications
You must be signed in to change notification settings - Fork 161
/
auth.js
108 lines (100 loc) · 3.24 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
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
BasicStrategy = require('passport-http').BasicStrategy,
ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy,
BearerStrategy = require('passport-http-bearer').Strategy,
OAuth2Client = require('./models/oauth2client'),
OAuth2Token = require('./models/oauth2token'),
User = require('./models/user');
// Local authentication strategy for passportjs, used for web logins
passport.use(new LocalStrategy({
usernameField: 'username'
},
function (username, password, done) {
User.authenticate(username, password, function (err, user, params) {
return done(err, user, params);
});
}));
// standard basic authentication strategy, used for REST based logins
passport.use(new BasicStrategy(
function (username, password, done) {
User.authenticate(username, password, function (err, user, params) {
return done(err, user, params);
});
}
));
// authentication strategy used by oauth clients, usess a custom name 'oAuthBasic'
passport.use('oAuthBasic' , new BasicStrategy(
function (username, password, done) {
OAuth2Client.findOne({
clientId: username
}, function (error, client) {
if (error) {
return done(error);
}
if (!client) {
return done(null, false);
}
if (client.clientSecret !== password) {
return done(null, false);
}
return done(null, client);
});
}
));
// A client-password strategy for authorizing requests for tokens
passport.use(new ClientPasswordStrategy(
function (clientId, clientSecret, done) {
OAuth2Client.findOne({
clientId: clientId
}, function (error, client) {
if (error) {
return done(error);
}
if (!client) {
return done(null, false);
}
if (client.clientSecret !== clientSecret) {
return done(null, false);
}
return done(null, client);
});
}
));
// A bearer strategy to authorize API requests by oauth2code
passport.use(new BearerStrategy(
function (accessToken, done) {
OAuth2Token.findOne({
token: accessToken
}, function (error, oauth2token) {
if (error) {
return done(error);
}
if (!oauth2token) {
return done(null, false);
}
User.findOne({
_id: oauth2token.user
}, function (error, openhabUser) {
if (error) {
return done(error);
}
if (!openhabUser) {
return done(null, false);
}
var info = {
scope: oauth2token.scope
};
done(null, openhabUser, info);
});
});
}
));
passport.serializeUser(function (user, done) {
done(null, user._id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});