-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathregister_handler.js
More file actions
60 lines (59 loc) · 2.79 KB
/
register_handler.js
File metadata and controls
60 lines (59 loc) · 2.79 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
var pg = require('pg');
var bcrypt = require('bcrypt'); // https://github.com/nelsonic/bcrypt
var escape = require('pg-escape'); // https://github.com/segmentio/pg-escape
var help = require('./helpers');
var Hoek = require('hoek');
module.exports = function register_handler(request, reply, source, error) {
if (request.method === 'get') { // get does not send payload so return reg
return reply.view('index', { title : 'Please Register' }).code(200);
}
if(!request.payload || request.payload && error && error.data) { // joi error
return reply.view('index', {
title : 'Please Register ' + request.server.version,
errors : help.extract_validation_error(error), // error field & message
values : help.return_form_input_values(error) // avoid wiping form data
}).code(400);
} // this block is essentially doing *manual* Joi validation to show html!
else { // the payload was valid, lets see if the person has already registered
pg.connect(process.env.DATABASE_URL, function(err, client, done) {
CLIENT = client;
var select = escape('SELECT * FROM people WHERE (email = %L)',
request.payload.email); // http://stackoverflow.com/a/13823560/1148249
console.log('select: ', select);
client.query(select, function(err, result) {
console.log(err, result);
if (err || result.rowCount === 0) { // user does not exist register!
bcrypt.genSalt(12, function(err, salt) { // encrypt the password:
bcrypt.hash(request.payload.password, salt, function(err, hash) {
var q = 'INSERT INTO %s (email, password) VALUES (%L, %L)';
var insert = escape(q, 'people', request.payload.email, hash);
console.log('insert: ', insert);
client.query(insert, function(err, result) {
// at this point we should not be getting an error...
Hoek.assert(!err, 'ERROR: inserting data into Postgres');
reply.view('success', {
name : 'Friend',
email : help.validator.escape(request.payload.email)
});
done();
});
}); // end bcrypt.hash
}); // end bcrypt.genSalt
} else { // if there is no error SELECTING the User, it Exists!!
console.log(err, result);
reply.view('index', {
title: 'Sorry, Please try a different email address!',
error : { error: { email: {
message: 'That email address has already been registered.'}
}}, // yes, this is a deeply nested error object
values : { // keep form data
email: help.validator.escape(request.payload.email)
}
}).code(400);
done();
}
});
});
}
return; // always return
}