Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express');
- const app = express();
- const router = express.Router();
- const uril = require("util");
- const bodyParser = require('body-parser');
- const _ = require('lodash');
- const http = require('http');
- const fs = require('fs'); //file-system
- const https = require('https'); //https
- const MongoClient = require('mongodb').MongoClient;
- const moment = require('moment');
- const jwt = require('jsonwebtoken')
- // A bcrypt library for NodeJS
- const bcrypt = require('bcrypt');
- // Otherwise known as _id in mongo
- const ObjectId = require('mongodb').ObjectId;
- // Child processes
- const spawn = require('child_process').spawn;
- const spawnMongod = spawn('mongod', ['--dbpath', './data/db']);
- // should be 12 or more
- const saltRounds = 12;
- // Store these in a .JSON file and add that to .gitignore
- const secret = 'goldenbanana';
- const accessToken = 'digestweb';
- // 1 hours
- const expires_in = 60*60*1;
- const databaseName = 'digae'
- const nativeMongoDriverUrl = 'mongodb://localhost:27017/';
- const databaseUrl = nativeMongoDriverUrl+databaseName;
- const portNumber = 8001;
- const REGEX_EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
- // configure app to use bodyParser()
- // this will let us get the data from a POST request
- app.use(bodyParser.json());
- // parse application/x-www-form-urlencoded
- app.use(bodyParser.urlencoded({ extended: true }));
- app.use('/', express.static('app'));
- // Add headers
- app.use(function (req, res, next) {
- // res.setHeader('Cache-Control', 'public, max-age=31557600');
- // Website you wish to allow to connect
- res.setHeader('Access-Control-Allow-Origin', '*');
- // Request methods you wish to allowss
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
- // Request headers you wish to allow
- res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,authorization');
- // Set to true if you need the website to include cookies in the requests sent
- // to the API (e.g. in case you use sessions)
- res.setHeader('Access-Control-Allow-Credentials', true);
- // Pass to next layer of middleware
- next();
- });
- http.createServer(app).listen(portNumber);
- function checkMongod(callback){
- spawnMongod.stdout.on('data', function(data){
- console.log('Successful Mongod');
- });
- spawnMongod.stderr.on('data', (data) => {
- console.log('Error Mongod');
- });
- spawnMongod.on('close', (code) => {
- console.log('Closed Mongod');
- });
- }
- function encryptionHash(unencryptedString, saltRounds, callback){
- let callbackResponse = 'Unknown error in encryption hashing';
- return bcrypt.hash(unencryptedString, saltRounds, function(hashError, hash) {
- if (hash){
- callbackResponse = hash;
- } else if (hashError){
- callbackResponse = hashError;
- }
- callback(callbackResponse);
- }
- )}
- function encryptionCompare(unencryptedString, encryptedString, callback){
- let callbackResponse = 'Unknown error in encryption comparason';
- return bcrypt.compare(unencryptedString, encryptedString ,function(compareFailed, compareSuccessful) {
- if (compareSuccessful){
- callbackResponse = compareSuccessful;
- } else if (compareFailed) {
- callbackResponse = compareFailed;
- }
- callback(callbackResponse);
- }
- )}
- function tokenSign(payload, secretKey, options){
- return jwt.sign(payload,secretKey,options);
- }
- function tokenVerify(token, secretKey, callback){
- return jwt.verify(token, secretKey, function(error, success){
- return callback(error, success);
- });
- }
- MongoClient.connect(databaseUrl, function(err, db) {
- checkMongod();
- if (db){
- const userCollection = db.collection('user');
- const authenticationCollection = db.collection('authentication');
- const tokenCollection = db.collection('token');
- function findAllUsers(query){
- return db.collection('user').find(query);
- }
- function findUser(user, callback){
- let callbackResponse;
- return db.collection('user').findOne(user ,function(userError, userFound){
- if (userFound){
- callbackResponse = userFound;
- }
- callback(callbackResponse);
- });
- }
- function insertUser(user, callback){
- let callbackResponse;
- return db.collection('user').insertOne(user,function(userInsertError, userInserted){
- if (userInserted){
- callbackResponse = userInserted;
- }
- callback(callbackResponse);
- });
- }
- function findAllAuthentications(query){
- return db.collection('authentication').find(query);
- }
- function findAuthentication(authentication, callback){
- let callbackResponse;
- return db.collection('authentication').findOne(authentication, function(authenticationError, authenticationFound){
- if (authenticationFound){
- callbackResponse = authenticationFound;
- }
- callback(callbackResponse);
- });
- }
- function findUpdateAuthentication(authenticationFilter, authenticationUpdate, callback){
- let callbackResponse;
- return db.collection('authentication').findOneAndUpdate(authenticationFilter, authenticationUpdate, function(authenticationError, authenticationFound){
- if (authenticationFound){
- callbackResponse = authenticationFound;
- }
- callback(callbackResponse);
- });
- }
- function insertAuthentication(authentication, callback){
- let callbackResponse;
- return db.collection('authentication').insertOne(authentication,function(authenticationInsertError, authenticationInserted){
- if (authenticationInserted){
- callbackResponse = authenticationInserted;
- }
- callback(callbackResponse);
- });
- }
- function insertToken(token, callback){
- let callbackResponse;
- return db.collection('token').insertOne(token, function(tokenInsertError, tokenInserted){
- if (tokenInserted){
- callbackResponse = tokenInserted;
- }
- callback(callbackResponse);
- });
- }
- function createNewUserObject(user){
- let newUserObject;
- if (user){
- newUserObject = {
- username: user.username,
- email: user.email,
- date_created: moment().valueOf(),
- active: true
- }
- }
- return newUserObject;
- }
- function createTestTokenObject(token){
- let newTokenObject;
- if (token){
- newTokenObject = {
- user_id: token.user_id
- }
- }
- }
- function updateTestTokenObject(refreshToken){
- let updateTestTokenObject;
- if (refreshToken){
- }
- }
- function createCurrentUserObject(user){
- let userObject;
- if (user){
- userObject = {
- active: user.active || false,
- verified: user.verified || false,
- id: user._id || '',
- username: user.username || '',
- email: user.email || '',
- date_created: user.date_created || 0,
- date_birth: user.date_birth || 0,
- sex: user.sex || '',
- pregnant: user.pregnant || '',
- country: user.country || '',
- city: user.city || '',
- achievements: user.achievements || [],
- friends: user.friends || []
- }
- }
- return userObject;
- }
- function createMealObject(meal){
- let mealObject;
- if (meal){
- mealObject = {
- // _id: meal._id,
- user_id: meal.user_id || '',
- name: meal.name || '',
- description: meal.description || '',
- date_created: meal.date_created || '',
- user_ids: meal.user_ids || [],
- food_ids: meal.food_ids || [],
- comments: meal.comments || [],
- }
- }
- return mealObject;
- }
- function createEatenObject(eaten){
- let eatenObject;
- if (eaten){
- eatenObject = {
- // _id: eaten._id,
- food_id: eaten.user_id || '',
- meal_id: eaten.meal_id || '',
- nutrient_id: eaten.nutrient_id || '',
- units: eaten.units || '',
- mass: eaten.mass || '',
- date_eaten: eaten.date_eaten || ''
- }
- }
- return eatenObject;
- }
- function createCommentObject(comment){
- let commentObject;
- if (comment){
- commentObject = {
- // _id: comment._id,
- user_id: comment.user_id || '',
- content: comment.content || '',
- date_created: comment.date_created || ''
- }
- }
- return commentObject;
- }
- function createFavoriteObject(favorite){
- let favoriteObject;
- if (favorite){
- favoriteObject = {
- // _id: favorite._id,
- user_id: favorite.user_id || '',
- food_id: favorite.food_id || null,
- meal_id: favorite.meal_id || null,
- nutrient_id: favorite.nutrient_id || null,
- date_created: favorite.date_created || ''
- }
- }
- return favoriteObject;
- }
- function createPrivateMessageObject(message){
- let messageObject;
- if (message){
- messageObject = {
- // _id: message._id,
- user_id: message.user_id || '',
- recipient_id: message.recipient_id || '',
- content: message.content || '',
- date_created: message.date_created || '',
- date_read: message.date_read || ''
- }
- }
- return messageObject;
- }
- function createNewAuthenticationObject(authenticationObject){
- var newAuthenticationObject;
- if (authenticationObject){
- newAuthenticationObject = {
- user_id: authenticationObject.user_id,
- password: authenticationObject.password
- }
- }
- return newAuthenticationObject;
- }
- function createTokenObject(token, expiresIn){
- var tokenObject = {
- access_token: token,
- token_type: 'bearer',
- expires_in: expiresIn,
- scope: 'standard',
- refresh_token: ''
- }
- return tokenObject;
- }
- function createTokenPayloadObject(id, username, email){
- let tokenPayloadObject;
- tokenPayloadObject = {
- user_id: id,
- username: username,
- email: email,
- scope: ['premium', 'standard']
- }
- return tokenPayloadObject;
- }
- function sendResponseSuccess(response, code, message){
- let successObject = {
- success: true,
- message: message
- }
- return response.status(code).json(successObject);
- }
- function sendResponseError(response, code, message){
- let successObject = {
- error: true,
- message: message
- }
- return response.status(code).json(successObject);
- }
- function sendResponseObject(response, code, object){
- return response.status(code).json(object);
- }
- function getBearerToken(headerAuthorization){
- return headerAuthorization.replace('Bearer ', '');
- }
- function getBasicToken(headerAuthorization){
- return headerAuthorization.replace('Basic ', '');
- }
- function decodeToken(token){
- return new Buffer(token, 'base64').toString();
- }
- function getUsername(decodedToken){
- return decodedToken.slice(0, decodedToken.indexOf(':'));
- }
- function getPassword(decodedToken, username){
- return decodedToken.substring((decodedToken.indexOf(':'), username.length + 1));
- }
- function getTokenBody(token){
- let delimiter = '.';
- let strings = token.split(delimiter).slice(1);
- let bodyAndSignature = strings.join(delimiter);
- // console.log(tokens);
- let body = bodyAndSignature.slice(0, bodyAndSignature.indexOf('.'));
- return body;
- }
- // user get
- router.get('/user/:current?',function(request,response){
- let hasCurrentUserParameters = request.params.current === 'current';
- let userQuery = {};
- // current user
- if (hasCurrentUserParameters){
- let headerContentType = request.headers['content-type'];
- let headerAuthorization = request.headers.authorization;
- let bearerToken = getBearerToken(headerAuthorization);
- let bearerTokenBody = getTokenBody(bearerToken);
- let decodedBearerToken = decodeToken(bearerToken);
- let username = getUsername(decodedBearerToken);
- let password = getPassword(decodedBearerToken, username);
- tokenVerify(bearerToken, secret
- ,function(verifyError, verified){
- if (verified){
- userQuery = {
- _id: ObjectId(verified.user_id),
- username: verified.username
- }
- findUser(userQuery ,function(user){
- if(user) {
- let authenticationQuery = {
- user_id: ObjectId( user._id )
- }
- findAuthentication(authenticationQuery, function(authenticationFound){
- if (authenticationFound && authenticationFound.access_token === accessToken){
- sendResponseObject(response,200,createCurrentUserObject(user))
- } else {
- sendResponseError(response,400,'No authentication found');
- }
- });
- } else {
- sendResponseError(response,400,'No user found');
- }
- });
- } else if (verifyError){
- if(verifyError.name === 'TokenExpiredError'){
- sendResponseError(response,400,'Token expired');
- } else {
- sendResponseError(response,400,'Wrong token');
- }
- }
- })
- // all users
- } else {
- let users = [];
- if (request.query.id){
- userQuery = {
- _id: ObjectId( request.query.id )
- }
- }
- findAllUsers(userQuery).each(function(error, user){
- if(user) {
- users.push(createCurrentUserObject(user));
- } else {
- response.json(users);
- }
- });
- }
- });
- // user post
- router.post('/user/:current?',function(request,response){
- let hasCurrentUserParameters =
- request.params.current === 'current';
- let hasNewUserParameters =
- request.body.email &&
- request.body.username &&
- request.body.password;
- // current User
- if (hasCurrentUserParameters){
- let hasRequiredBodyParameters =
- false;
- // Update current user
- if (hasRequiredBodyParameters){
- }
- // new user
- } else if (hasNewUserParameters) {
- let bodyUsername = decodeURIComponent(request.body.username);
- let bodyPassword = decodeURIComponent(request.body.password);
- let bodyEmail = decodeURIComponent(request.body.email);
- let hasRequiredBodyParameters =
- bodyUsername &&
- bodyPassword &&
- bodyEmail;
- if (hasRequiredBodyParameters){
- let passwordLength = request.body.password.length;
- let isPasswordValid = passwordLength > 8;
- let isEmailValid = REGEX_EMAIL.test(bodyEmail);
- let isRequestValid = isEmailValid && isPasswordValid;
- if (isRequestValid){
- let queryUsername = {
- username: {$regex: bodyUsername, $options: 'i'}
- };
- let queryEmail = {
- email: {$regex: bodyEmail, $options: 'i'}
- };
- findAllUsers(queryEmail).count(function(error, userEmailFound){
- if (!userEmailFound){
- findAllUsers(queryUsername).count(function(error, userUsernameFound){
- if (!userUsernameFound){
- encryptionHash(request.body.password, saltRounds, function(hash){
- if (hash){
- insertUser(createNewUserObject(request.body),function(userInserted){
- if(userInserted.result.ok){
- let authenticationObject = {
- user_id: userInserted.ops[0]._id,
- password: hash
- };
- insertAuthentication(createNewAuthenticationObject(authenticationObject), function(authenticationInserted){
- if(authenticationInserted.result.ok){
- // create empty token with user id
- // to update with token when user
- // signs in
- let tokenObject = {
- user_id: userInserted.ops[0]._id,
- }
- insertToken(tokenObject, function(tokenInserted){
- if(tokenInserted.result.ok){
- sendResponseSuccess(response,201,'User successfully created');
- }
- });
- }
- });
- }
- });
- }
- });
- } else if (userUsernameFound){
- sendResponseError(response,400,'Username ' + bodyUsername + ' exists');
- }
- });
- } else if (userEmailFound) {
- sendResponseError(response,400,'Email ' + bodyEmail + ' exists');
- }
- });
- } else {
- if (!isEmailValid){
- sendResponseError(response,400,'Invalid email');
- }
- if (!isPasswordValid){
- sendResponseError(response,400,'Password is too short');
- }
- }
- } else {
- sendResponseError(response,400,'Missing or invalid parameters1');
- }
- } else {
- sendResponseError(response,400,'Missing or invalid parameters2');
- }
- });
- router.post('/token',function(request,response){
- let users = [];
- let user = {};
- let body = {};
- let responseObject = {};
- let hasPasswordGrantParameters =
- request.body.grant_type === 'password' &&
- request.body.username &&
- request.body.password;
- let hasRefreshTokenParameters =
- request.body.grant_type === 'refresh_token' &&
- request.body.refresh_token &&
- request.body.client_id;
- if (hasPasswordGrantParameters){
- let headerAuthorization = request.headers.authorization;
- let basicToken = getBasicToken(headerAuthorization.replace('Basic ', ''));
- let headerAuthorizationUsernamePassword = decodeToken(basicToken);
- let headerAuthorizationUsername = headerAuthorizationUsernamePassword.slice(0, headerAuthorizationUsernamePassword.indexOf(':'));
- let headerAuthorizationPassword = headerAuthorizationUsernamePassword.substring((headerAuthorizationUsernamePassword.indexOf(':'), headerAuthorizationUsername.length + 1));
- let bodyUsername = decodeURIComponent(request.body.username);
- let bodyPassword = decodeURIComponent(request.body.password);
- // auth: 1. make sure headers matches body
- if (headerAuthorizationUsername === bodyUsername && headerAuthorizationPassword === bodyPassword){
- // auth 2. find user
- let userQuery = {
- username: {$regex: bodyUsername, $options: 'i'}
- }
- findUser(userQuery, function(user){
- if (user){
- // auth 3. find authentication
- let authenticationFilter = {
- user_id: user._id
- }
- let authenticationUpdate = {
- $set:{ access_token: accessToken }
- };
- findUpdateAuthentication(authenticationFilter, authenticationUpdate, function(authenticationFoundAndUpdated){
- if (authenticationFoundAndUpdated.ok){
- // auth 4. compare the header body password with the authentication password
- encryptionCompare(bodyPassword, authenticationFoundAndUpdated.password, function(compareSuccessful){
- if (compareSuccessful) {
- // auth 5. send token
- response.json(createTokenObject(
- tokenSign(createTokenPayloadObject(user._id, bodyUsername, request.body.email), secret, {expiresIn: expires_in}),
- expires_in
- ));
- } else {
- sendResponseError(response,400,'Wrong password for user ' + bodyUsername);
- }
- });
- } else {
- sendResponseError(response,400,'Authentication for user ' + bodyUsername + ' does not exist');
- }
- });
- } else {
- sendResponseError(response,400,'User ' + bodyUsername + ' does not exist');
- }
- });
- } else {
- sendResponseError(response,400,'Wrong token information');
- }
- } else if (hasRefreshTokenParameters) {
- } else {
- sendResponseError(response,400,'Missing or invalid parameters');
- }
- });
- // Custom Shit
- router.get('/token',function(request,response){
- });
- router.post('/token',function(request,response){
- });
- app.use('/',router);
- }
- else {
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement