aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/controllers/users.js
blob: f3568a4422fc8114b76c983af263bf67de1323b5 (plain) (blame)
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

/**
 * Module dependencies
 */

var mongoose = require('mongoose')
  , User = mongoose.model('User')
  , Project = mongoose.model('Project')
  , Access = mongoose.model('Access')
  , env = process.env.NODE_ENV || 'development'
  , config = require('../config/config')[env]
  , Validator = require('validator').Validator
  , v = new Validator()
  , sanitize = require('validator').sanitize;

// validation error handling. This collects all errors before pushing them out in getErrors()
Validator.prototype.error = function(msg) {
    this._errors.push(msg);
    return this;
}
Validator.prototype.getErrors = function() {
    var returnThis = this._errors;
    this._errors = ''; // need to reset errors between sessions because of object model
    return returnThis;
}


/**
 * Login
 */
exports.login = function(req, res) {
    res.render('login', {
        title: 'Login'
    });

}


/**
 * Logout
 */
exports.logout = function(req, res) {
    req.logout();
    res.redirect('/test');
}


/**
 * Signin
 * This is triggered when the user post to /login
 */
exports.signin = function(req, res) {
    res.redirect('/dashboard');
}


/**
 * Signup
 */
exports.signup = function(req, res) {
        res.render('signup', { title: 'Registrer deg' });
}

/**
 * Create users
 */
exports.create = function(req, res) {
    var user = new User(req.body);
    user.provider = 'local';
    user.save(function(err) {
        if (err) return res.render('signup', { errors: err.errors, user: user });
        req.logIn(user, function(err) {
            if (err) return next(err);
            return res.redirect('/dashboard');
        });
    });
}


/**
 * AuthCallback
 * This is what happends when a user has signed in using facebook/twitter
 */

exports.authCallback = function(req, res, next) {
    res.redirect('/dashboard');
}


/**
 * postProjectParticipants
 * This callback is in this file because it treats users.
 */
exports.postProjectParticipants = function(req, res) {
    Project.loadShort(req.params.short, function(err, project) {
        if (err || !project) return res.status(500).render('error', { title: '500', text: 'En serverfeil oppstod', error: err.stack });

        Access.checkAccess(req.user._id, project._id, 3, function(err, access) {
            if (err || !access) return res.status(403).render('error', { title: '403', text: 'No sir! NO ACCESS FOR YOU', error: err });

            // validate
            var emails = sanitize(req.body.emails).xss();
            v.check(emails, 'You need to enter some emails to invite someone').notEmpty();
            //var emails = sanitize(req.body.emails).xss();
            emails = emails.split('\r\n');
            emails.forEach(function(m) { // m = each mailaddress
                if (m) v.check(m, m + ' is not a valid email').isEmail();
            });

            // error when validation fails
            var errors = v.getErrors();
            if (errors.length !== 0) return res.status(500).render('error', { title: '500', text: 'Det oppstod en valideringsfeil<br>' + errors, error: errors });

            // EMAIL
            // Require dependencies. We require them here so that they're not fetched until they're actually needed.
            var email = require('emailjs')
              , server = email.server.connect(config.email)
              , message = {
                subject:    'You were invited to use Divid',
                text:       'VIL DU BRUK DIVID?',
                from:       'Divid <divid@divid.no>',
            }

           emails.forEach(function(mailAddress) { // loops through all the emails and sets up each user
                User.loadUser(mailAddress, function(err, user) {
                    if (err) return res.status(500).render('error', { title: '500', text: 'En serverfeil oppstod', error: err.stack });
                    if (!user) { //if the user doesn't exist, create one
                        console.log('fant ingen brukere med den eposten. må invitere og stasj');
                        var newUser = new User();
                        newUser.email = mailAddress;
                        newUser.status = 1;
                        newUser.password = newUser.generateRandomToken(32);
                        newUser.save(function(err) {
                            if (err) return res.render('projectParticipants', { title: 'Nytt prosjekt - en feil oppstod', loggedin: true });
                            console.log('made new user ' + newUser._id);
                            var access = new Access();
                            access.user = newUser._id;
                            access.creator = req.user._id;
                            access.project = project._id;
                            access.save(function(err) {
                                if (err) {
                                    console.log(err.errors);
                                    return res.render('projectParticipants', { title: 'Nytt prosjekt - en feil oppstod', loggedin: true });
                                }
                                console.log('made new access for user ' + newUser._id);
                                message.to = newUser.email;
                                message.text = 'Du ble lagt til projektet "' + project.name + '"';
                                server.send(message, function(err, message) { console.log(err || message);});
                            });
                        });


                        message.to = newUser.email;
                        message.text = 'Hei hå';
                        server.send(message, function(err, message) { console.log(err || message);});
                    } else { // if the user exists, add him to the project
                        Access.checkAccess(user._id, project._id, 0, function(err, acc) {
                            if (err) return res.render('projectParticipants', { title: 'Nytt prosjekt - en feil oppstod', loggedin: true });
                            if (acc) { // if the user already has access to the project.. do nothing
                                console.log('user ' + user.email + ' already has access to project ' + project.name);
                            } else {
                                console.log('fant en bruker. må lage ny access til han og si i fra.');
                                var access = new Access();
                                access.user = user._id;
                                access.creator = req.user._id;
                                access.project = project._id;
                                access.save(function(err) {
                                    if (err) {
                                        console.log(err.errors);
                                        return res.render('projectParticipants', { title: 'Nytt prosjekt - en feil oppstod', loggedin: true });
                                    }
                                    console.log('made new access for user ' + user.username);
                                    message.to = user.email;
                                    message.text = 'Du ble lagt til projektet "' + project.name + '"';
                                    server.send(message, function(err, message) { console.log(err || message);});
                                });
                            }
                        });
                    }
                });
           });

            res.redirect('back');
        });
    });
}