-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.js
More file actions
206 lines (179 loc) · 6.68 KB
/
Copy pathauth.js
File metadata and controls
206 lines (179 loc) · 6.68 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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
const passport = require('passport');
const GitHubStrategy = require('passport-github').Strategy;
const LocalStrategy = require('passport-local').Strategy;
const FacebookStrategy = require('passport-facebook').Strategy;
const session = require('express-session');
const cookieParser = require('cookie-parser');
const models = require('./models');
const bcrypt = require('bcrypt');
require('dotenv').config()
const setupAuth = (app) => {
app.use(cookieParser());
app.use(session({
secret: 'whatever',
resave: true,
saveUninitialized: true
}));
passport.use(new GitHubStrategy({
clientID: process.env.client_id,
clientSecret: process.env.client_secret,
callbackURL: process.env.callbackURL
}, (accessToken, refreshToken, profile, done) => {
models.user.findOrCreate({
where: {
githubid: profile.id,
}
}).then(result => {
models.user.update({
username: profile.username,
imgUrl: profile.photos[0].value
}, {
where: {
githubid: profile.id
}
})
return done(null, result[0]);
})
.catch(done)
}));
passport.use(new FacebookStrategy({
clientID: process.env.fb_client_id,
clientSecret: process.env.fb_client_secret,
callbackURL: process.env.fb_callbackURL
}, (accessToken, refreshToken, profile, done) => {
models.user.findOrCreate({
where: {
fbid: profile.id,
}
})
.then(result => {
models.user.update({
username: profile.id,
// imgUrl: profile.photos[0].value
}, {
where: {
fbid: profile.id
}
})
return done(null, result[0]);
})
.catch(done)
}));
passport.use(new LocalStrategy({
// options: https://github.com/jaredhanson/passport-local#parameters
// change these if you want a different field name for username or password
// usernameField: 'username',
// passwordField: 'password',
}, (username, password, done) => {
// check if there is a user with the username given
models.user.findOne({
where: {
'username': username
}
})
.then((currentUser) => {
// if there isn't a current User
if (!currentUser) {
// return an error
return done(null, false, { message: 'Incorrect username' })
}
// If the password doesn't match
if (!bcrypt.compareSync(password, currentUser.password)) {
// return an error
return done(null, false, { message: 'Incorrect password' })
}
// otherwise, return the user object
return done(null, currentUser)
})
.catch(done);
}));
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
done(null, id);
});
app.use(passport.initialize());
app.use(passport.session());
// this is a simple API to check if there is a user
app.get('/api/user', (req, res, next) => {
if (req.user) {
return res.json({ user: req.user })
} else {
return res.json({ user: null })
}
})
app.post('/auth/signup', (req, res) => {
// destructure username and password off req.body into new constants
const { username, password } = req.body;
// Check if there is a user with the given username
models.user.findOne({
where: {
'username': username
}
})
.then((currentUser) => {
// if there is a user already
if (currentUser) {
// return an error
return res.json({
error: `Sorry, already a username '${username}' is already taken`
});
}
// otherwise, create a new user and encrypt the password
models.user.create({
'username': username,
'password': bcrypt.hashSync(password, 10)
})
.then((newUser) => {
// we don't want to return everything, so put all the fields into a new object
const data = {
...newUser.get()
};
// and then delete the password off that object
delete data.password;
// return the cleaned object
return res.json(data);
})
.catch((err) => {
// if there's an error, return that
return res.json(err);
});
})
})
app.post('/auth/login',
passport.authenticate('local'),
(req, res) => {
// req.user will have been deserialized at this point, so we need
// to get the values and remove any sensitive ones
const cleanUser = { ...req.user.get() };
if (cleanUser.password) {
console.log(`Removing password from user:`, cleanUser.username);
delete cleanUser.password
}
res.json({ user: cleanUser });
}
)
// adding a session destroy on request line to fix github cache issue
app.get('/github/login', passport.authenticate('github'));
app.get('/github/auth',
passport.authenticate('github', { failureRedirect: '/github/login' }),
(req, res) => {
res.redirect('/');
});
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { successRedirect: '/', failureRedirect: '/login' }));
app.get('/logout', function (req, res, next) {
req.session.destroy();
res.json({ loggedIn: false });
});
};
const ensureAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
}
module.exports = setupAuth;
module.exports.ensureAuthenticated = ensureAuthenticated;