Skip to content

Commit

Permalink
BACKEND API update & auth
Browse files Browse the repository at this point in the history
  • Loading branch information
lecaoquochung committed Jul 26, 2016
1 parent f5f7f63 commit 8f734cd
Show file tree
Hide file tree
Showing 5 changed files with 121 additions and 33 deletions.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,16 @@ npm install mongodb --save
- load UserModel on app.js (window.onload)

### Update Backend API
-
```
npm install sha1 --save
```
- API request add record to db
- Connect to mongodb (common)
- mongodb helper: getDatabaseConnection -> connect to mongodb
- connect the first time (save to cache as object for the nex call)
- Fetching the POST data - Request handling (common)
- Router api/user/add method


### User authentication with sessions

Expand Down
98 changes: 74 additions & 24 deletions backend/API.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,78 @@
// backend/API.js
module.exports = function(req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end('{}' + '\n');
}
// mongodb
var MongoClient = require('mongodb').MongoClient;
var database;

var response = function(result, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(result) + '\n');
}
// mongodb helper: getDatabaseConnection -> connect to mongodb
// connect the first time (save to cache as object for the nex call)
var getDatabaseConnection = function(callback) {
if(database) {
callback(database);
return;
} else {
MongoClient.connect('mongodb://127.0.0.1:27017/nodejs-example',
function(err, db) {
if(err) {
throw err;
};
database = db;
callback(database);
});
}
};

var Router = require('../frontend/js/lib/router')();
// POST request handling
var querystring = require('querystring');
var processPOSTRequest = function(req, callback) {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
callback(querystring.parse(body));
});
};

Router
.add('api/version', function(req, res) {
response({
version: '0.1'
}, res);
})
.add(function(req, res) {
response({
success: true
}, res);
});
// email validation
var validEmail = function(value) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@(9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(value);
};

module.exports = function(req, res) {
Router.check(req.url, [req, res]);
}
// router api/user with add method
Router.add('api/user', function(req, res) {
switch(req.method) {
case 'GET':
// ...
break;
case 'PUT':
// ...
break;
case 'POST':
processPOSTRequest(req, function(data) {
if(!data.firstName || data.firstName === '') {
error('Please fill your first name.', res);
} else if(!data.lastName || data.lastName === '') {
error('Please fill your last name.', res);
} else if(!data.email || data.email === '' ||
!validEmail(data.email)) {
error('Invalid or missing email.', res);
} else if(!data.password || data.password === '') {
error('Please fill your password.', res);
} else {
getDatabaseConnection(function(db) {
var collection = db.collection('users');
data.password = sha1(data.password);
collection.insert(data, function(err, docs) {
response({
success: 'OK'
}, res);
});
});
}
});
break;
case 'DELETE':
// ...
break;
};
});
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"gulp-uglify": "^1.5.4",
"mongodb": "^2.2.4",
"ractive": "^0.7.3",
"reactive": "^1.2.0"
"reactive": "^1.2.0",
"sha1": "^1.1.1"
},
"author": "lecaoquochung@gmail.com",
"license": "MIT"
Expand Down
28 changes: 28 additions & 0 deletions sample/API/api_default.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// backend/API.js
module.exports = function(req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end('{}' + '\n');
}

var response = function(result, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(result) + '\n');
}

var Router = require('../frontend/js/lib/router')();

Router
.add('api/version', function(req, res) {
response({
version: '0.1'
}, res);
})
.add(function(req, res) {
response({
success: true
}, res);
});

module.exports = function(req, res) {
Router.check(req.url, [req, res]);
}
14 changes: 7 additions & 7 deletions sample/mongodb/connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ function(err, db) {
});

// db object with CRUD
var collection = db.collection('users');
collection.insert({
name: 'Hung',
email: 'lehung@test.com'
}, function(err, result) {
// ...
});
// var collection = db.collection('users');
// collection.insert({
// name: 'Hung',
// email: 'lehung@test.com'
// }, function(err, result) {
// // ...
// });

0 comments on commit 8f734cd

Please sign in to comment.