-
Notifications
You must be signed in to change notification settings - Fork 0
/
accounts.js
77 lines (59 loc) · 2.05 KB
/
accounts.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
var Firebase = require('firebase');
var crypto = require('crypto');
var firebase = new Firebase('https://wikieasy-89192.firebaseio.com/');
var users = firebase.child('users');
function hash (password) {
return crypto.createHash('sha512').update(password).digest('hex');
}
var router = require('express').Router();
router.use(require('body-parser').json());
router.use(require('cookie-parser')());
router.use(require('express-session')({
resave: false,
saveUninitialized: true,
secret: 'secretsecretsecret'
}));
router.post('/api/signup', function (req, res) {
var username = req.body.username,
password = req.body.password;
if (!username || !password)
return res.json({ signedIn: false, message: 'no username or password' });
users.child(username).once('value', function (snapshot) {
if (snapshot.exists())
return res.json({ signedIn: false, message: 'username already in use' });
var userObj = {
username: username,
passwordHash: hash(password)
};
users.child(username).set(userObj);
req.session.user = userObj;
res.json({
signedIn: true,
user: userObj
});
});
});
router.post('/api/signin', function (req, res) {
var username = req.body.username,
password = req.body.password;
if (!username || !password)
return res.json({ signedIn: false, message: 'no username or password' });
users.child(username).once('value', function (snapshot) {
if (!snapshot.exists() || snapshot.child('passwordHash').val() !== hash(password))
return res.json({ signedIn: false, message: 'wrong username or password' });
var user = snapshot.exportVal();
req.session.user = user;
res.json({
signedIn: true,
user: user
});
});
});
router.post('/api/signout', function (req, res) {
delete req.session.user;
res.json({
signedIn: false,
message: 'You have been signed out'
});
});
module.exports = router;