NodeJS ,Restful API build authentication for multiple devices

1.please install express MVC by using the following url

https://www.npmjs.com/package/express-mvc-generator

2. build a server listner that should work for API ,api_app.js
/**
*
* importing all necessary libraries
*/
var nodemailer = require(‘nodemailer’);
var passport = require(‘passport’);
var multer = require(‘multer’);
var bcrypt = require(‘bcrypt-nodejs’);
var async = require(‘async’);
var crypto = require(‘crypto’);
var express = require(‘express’),

glob = require(‘glob’),
mongoose = require(‘mongoose’);
require(‘./config/passport’)(passport);
var cors = require(‘cors’)
var app = express();
var bodyParser = require(‘body-parser’);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
var mongoose = require(‘mongoose’);
var configDB = require(‘./config/database.js’);
//configuration ===============================================================
mongoose.connect(configDB.url);
var db = mongoose.connection;
db.on(‘error’, function () {
throw new Error(‘unable to connect to database at ‘ + config.db);
});

app.use(require(‘./app/controllers/apicontroller.js’))

// routes ======================================================================
require(‘./config/routes.js’)(app, passport); // load our routes and pass in our app and fully configured passport

port=8001;
//launch ======================================================================

var models = glob.sync(configDB.root + ‘/app/models/*.js’);
models.forEach(function (model) {
require(model);
});
var controllers = glob.sync(configDB.root + ‘/app/controllers/*.js’);
controllers.forEach(function (controller) {
require(controller)(app);
});

//catch 404 and forward to error handler
app.use(function (req, res, next) {
return res.json({success: 404, content: {message: ‘Sorry, page not found.’}});
});

app.use(function (req, res, next) {
//res.status(500).render(‘404’, {title: “Sorry, page not found”});
return res.json({success: 404, content: {message: ‘Sorry, page not found.’}});
});
exports = module.exports = app;

/**
*
* Establising a node js intance serivce
*
*/
app.listen(port, function () {
console.log(‘Express server listening on port ‘ + port);
});

 

 

 

2.  API ,apicontroller.js

var bcrypt = require(‘bcrypt-nodejs’);
var jwt = require(‘jsonwebtoken’);
var express = require(‘express’), approuter = express.Router(),
mongoose = require(‘mongoose’);
var bodyParser = require(‘body-parser’);
var morgan = require(‘morgan’);
var app = express();
var forEach = require(‘async-foreach’).forEach;
var util = require(‘util’);
var User = require(‘../.././app/models/myuser’); // get our mongoose model
var Client = require(‘../.././app/models/myclients’);
var Accesstoken = require(‘../.././app/models/myaccesstoken’);
var multipart = require(‘connect-multiparty’);
var multipartMiddleware = multipart();
var passport = require(‘passport’);
//create a route with prefix
var apiRoutes_mobile = express.Router();

module.exports = app.use(‘/mobil-api/v1’, apiRoutes_mobile);

;
/**
* initilizing JWT token based authnetication in order to protect the API access
* @param {string} devic_token
* @param string apikey
* @param {string} password
* @param String email
* @return {json}array
*/
apiRoutes_mobile.use(function (req, res, next) {
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers[‘token’];
//get last parameter
var requested_url = req.path;
var requested_url_array = requested_url.split(‘/’);
var lastsegment = requested_url_array[requested_url_array.length – 1];

// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, ‘ilovescotchyscotch’, function (err, decoded) {
if (err) {
return res.json({success: false, content: {message: ‘Failed to authenticate token,please try again.’}});
} else {
// if everything is good, save to request for use in other routes
var apikey = req.body.apikey || req.query.apikey || req.headers[‘apikey’];
Accesstoken.count({$and: [{‘token’: token}, {‘user_id’: req.headers.user_id}, {‘clientId’: apikey}]}, function (err, clientdata) {
if (clientdata == 0) {
return res.json({success: false, content: {message: ‘Failed to authenticate token,please try again.’}});
} else {
req.decoded = decoded;
next();
}
}
);
}
});
} else if (req.path == “/auth” || req.path ==”/register”) {

next();
} else {
var err = new Error(‘Not Found’);
console.log(req.path);
return res.status(403).send({
success: false,
content: {message: ‘No token provided.’}
});
return res.status(404).send({
success: false,
content: {message: ‘Page not found.’}
});
}
});

apiRoutes_mobile.get(‘/test’, function (req, res) {
console.log(“test”);
});

/**
* tyhis is used to authenticate the user account
* @param string name
* @param string device_token
* @param string apikey
* @param string password
* @return JSON
*
*/
apiRoutes_mobile.post(‘/auth’, function (req, res) {
var clientId = req.headers.apikey
if (!req.headers.device_token)
return res.json({success: false, content: {message: “Please send the device token.”}});
if (!req.headers.apikey)
return res.json({success: false, content: {message: “Please send the API key.”}});
if (!req.headers.email)
return res.json({success: false, content: {message: “Please send the user email.”}});
if (!req.headers.password)
return res.json({success: false, content: {message: “Please send the password.”}});

Client.findOne({clientId: clientId}, function (err, client) {
if (err)
return res.json({success: false, content: {message: “Wrong API key”}});
console.log(client);
if (!client) {
return res.json({success: false, content: {message: “Wrong API key”}});
}
User.findOne({‘local.email’: req.headers.email}, function (err, user) {
//console.log(“test”);process.exit();
if (err)
throw err;

if (!user) {
console.log(“three”);
return res.json({success: false, content: {message: ‘Authentication failed. User not found.’}});
} else if (user) {
password = req.headers.password;
username = req.headers.email;

if (!bcrypt.compareSync(password, user.local.password)) {
// if password does not match

return res.json({success: false, content: {message: “Wrong password”}});
} else {

// if everything is OK, return null as the error // and the authenticated user
con_cat = req.headers.device_token + ” + req.headers.email
var token = jwt.sign(con_cat, ‘ilovescotchyscotch’, {
expiresInMinutes: 1440// expires in 24 hours
});
var accesstok = new Accesstoken({
‘clientId’: clientId, “token”: token, “device_token”: req.headers.device_token, ‘ip’: ”, ‘os’: “ios”, ‘user_id’: user._id
});
Accesstoken.findOne({$and: [{‘device_token’: req.headers.device_token}, {‘user_id’: user._id}]}, function (err, checkaccesstoken) {
if (err)
throw err;

if (!checkaccesstoken)
{
accesstok.save(function (err, row) {
if (err)
throw err;
// return the information including token as JSON
return res.json({
success: true,
content: {message: ‘Authentication success’,
token: token,
result: user, ‘profile_img’: profile_img}
});
});
} else {

checkaccesstoken.clientId = clientId;
checkaccesstoken.token = token;
checkaccesstoken.device_token = req.headers.device_token;
checkaccesstoken.ip = ‘198.168.1.20’;
checkaccesstoken.os = “ios”;
checkaccesstoken.user_id = user._id;
checkaccesstoken.save(function (err, row) {
if (err)
throw err;
// return the information including token as JSON
return res.json({
success: true,
content: {message: ‘Authentication success’,
token: token,
result: user, ‘profile_img’: ”}
});
});
}

});
}

}

});
});
});

Uploading images over REST API -Nodejs,expressJS by using multipart

//create a route with prefix

var app = express();

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
var apiroutes = express.Router();

var multipartMiddleware = multipart();

/**

This is the function we need to call over REST API

**/
apiroutes.post(‘/update-image’, multipartMiddleware, function (req, res) {

if (!req.body.files)
{
profileImage(req, function (result) {

return res.json({message: “updated successfully.”});

});

 

});

/**
* uploading images
* @param {type} req
* @param {type} callback
* @returns {undefined}
*/
function profileImage(req, callback) {
x = req.files.files;
if(x){
fs.readFile(x[‘path’], function (err, data) {
if (err)
return callback(0)
newPath = ‘./public/api-testimages/’ + req.headers.user_id + “”” + x[‘originalFilename’];
fs.writeFile(newPath, data, function (err) {
if (err)
callback(0);
return callback(newPath);
});
//dont forgot the delete the temp files.
});
}else{
callback(0);
}
}

 

 

in ur post man

image-uploading