summaryrefslogtreecommitdiff
path: root/server/auth/index.js
blob: e8fb483f1e1a6404bd0d125e506fcd5f17835733 (plain)
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
/* jshint node: true */

var passport = require('passport'),
	LocalStrategy = require('passport-local').Strategy,
	_ = require('lodash'),
	config = require('../../config.json'),
	User = require('../models/User'),
	crypt = require('./crypt');

var auth = module.exports = {
	
	guestUser: {
		id: "guest",
		username: "guest",
		name: "guest",
		access: 0,
	},

	init: function () { 
		passport.serializeUser(auth.serializeUser);
		passport.deserializeUser(auth.deserializeUser);
		passport.use(new LocalStrategy(auth.verifyLocalUser))
	},

	login: function (req, res, next) {
		if (req.isAuthenticated()) {
			console.log(req.user)
			return User.findAll({ where: { access: 2 }, attributes: ['id','name'] }).success(function(hosts){
				res.json({
					status: "OK",
					user: req.user,
					hosts: hosts
				})
			})
		}
		passport.authenticate("local", function(err, user, info){
			if (err || ! user) {
				return res.json({ error: err || "no user" });
			}
			
			req.logIn(user, function(err) {
				if (err) { return next(err); }
				User.findAll({ where: { access: 2 }, attributes: ['id','name'] }).success(function(hosts){
					return res.json({
						status: "OK",
						user: user,
						hosts: hosts
					})
				})
			});
		})(req, res, next);
	},

	logout: function (req, res) {
		req.logout();
		req.session.destroy()
		res.redirect('/');
	},

	serializeUser: function (user, done) {
		done(null, user.id);
	},

	deserializeUser: function (id, done) {
		if (id == "guest") {
			done(null, auth.guestUser)
		}
		User.find({ id: id }, function (err, user) {
			done(err, user)
		});
	},

	verifyLocalUser: function (username, password, done) {
		if (username == "protocolsnyc" && password == "madhousenyc") {
			return done(null, auth.guestUser)
		}
		User.find({ where: { email: username } }).success(function(user){
			if (! user.password || user.password.length < 2) {
				return done(null, false, { error: { errors: { username: { message: 'No such user.' } }}})
			}
			else if ( crypt(password, user.password) !== user.password) {
				return done(null, false, { error: { errors: { password: { message: 'Incorrect password.' } }}})
			}
			return done(null, user);
		}).error(function(){
			return done(null, false, { error: { errors: { username: { message: 'No such username.' } }}})
		})
	}

}