-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
95 lines (81 loc) · 2.91 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
var passport = require("passport");
var bcrypt = require("bcrypt");
var LocalStrategy = require("passport-local").Strategy;
var BasicStrategy = require("passport-http").BasicStrategy;
var ClientPasswordStrategy = require("passport-oauth2-client-password").Strategy;
var BearerStrategy = require("passport-http-bearer").Strategy;
var userRepo = require("./data/user");
var clientRepo = require("./data/client");
var tokenRepo = require("./data/token");
passport.use(new LocalStrategy({
usernameField: "uname",
passwordField: "pass"
}, function (username, password, done) {
userRepo.findUser(username, function (err, user) {
if (err)
return done(err);
if (!user)
return done(null, null);
bcrypt.compare(password, user.passwordHash, function (err, matched) {
if (matched)
done(null, user);
else
done(null, null);
});
});
}));
passport.use(new BasicStrategy(function (username, password, done) {
clientRepo.findClient(username, function (err, client) {
if (err)
return done(err);
if (client.clientSecret === password)
return done(null, client);
return done(null, null);
});
}));
passport.use(new ClientPasswordStrategy(function (clientId, clientSecret, done) {
clientRepo.findClient(clientId, function (err, client) {
if (err)
return done(err);
if (client.clientSecret === clientSecret)
return done(null, client);
return done(null, null);
});
}));
passport.use(new BearerStrategy(function (token, done) {
tokenRepo.find(token, function (err, accessToken) {
if (err)
return done(err);
if (accessToken.username) {
userRepo.findUser(accessToken.username, function (err, user) {
if (err)
return done(err);
if (!user)
return done(null, null);
done(null, user, { scope: "*", isUser: true })
});
} else {
clientRepo.findClient(accessToken.clientId, function (err, client) {
if (err)
return done(err);
if (!client)
return done(null, null);
done(null, client, { scope: "*", isClient: true });
});
}
});
}));
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
exports.authenticate = passport.authenticate("local", { successRedirect: "/", failureRedirect: "/login", session: true });
exports.authenticateClient = passport.authenticate(['basic', 'oauth2-client-password'], { session: false });
exports.isLoggedIn = function (req, res, next) {
if (req.isAuthenticated && req.isAuthenticated())
return next();
else
return res.redirect("/login");
}