Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason Williams committed May 9, 2017
0 parents commit 690a53b
Show file tree
Hide file tree
Showing 12 changed files with 443 additions and 0 deletions.
68 changes: 68 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@

# Created by https://www.gitignore.io/api/node

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

#configuration
.configuration.js


# End of https://www.gitignore.io/api/node
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"angulardoc.repoId": "ddaa25d9-04a9-4d6e-b56a-a405c1c4851b",
"angulardoc.lastSync": 0
}
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Node Server Auth API

```
> git clone
> cd
> npm install
> npm run dev
> This will open automatically on http://localhost:3000
```

## Instructions
52 changes: 52 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

const index = require('./routes/index');
const users = require('./routes/users');

const mongoose = require('mongoose');

/************************db setup*********************************/
/********add and replace your own database connection here********/
/*****************************************************************/
mongoose.connect('mongodb://localhost:auth/authorization');


const app = express();



//uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;
90 changes: 90 additions & 0 deletions bin/www
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env node

/**
* Module dependencies.
*/

const app = require('../app');
const debug = require('debug')('authapi:server');
const http = require('http');

/**
* Get port from environment and store in Express.
*/

const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
* Create HTTP server.
*/

const server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
const port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
const addr = server.address();
const bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
55 changes: 55 additions & 0 deletions controllers/authentication.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const User = require('../models/user');
const jwt = require('jwt-simple');
const JWT_SECRET = require('../.configuration');


//create jwt-token and set subject, timestamp and secret
function createJwtToken(user) {
const timestamp = new Date().getDate();
return jwt.encode({ sub: user.id, iat: timestamp }, JWT_SECRET.ID)
};


//authorized just need to issue a jwt_token
exports.signin = (req, res, next) => {
res.send({ web_token: createJwtToken(req.user) })
}

exports.signup = (req, res, next) => {
const email = req.body.email;
const password = req.body.password;

if (!email || !password) {
return res.status(422).send({ error: 'Email and Password are required' })
}

/****************add email validation********************/


//does user with email exist?
User.findOne({ email }, (err, existingUser) => {
if (err) {
return next(err);
}

//if email already exists return error message
if (existingUser) {
return res.status(422).send({ error: 'Email already exists' })
}

//if new user create new User and return JWT_TOKEN
const user = new User({
email: email,
password: password
});
user.save((err) => {
if (err) {
return next(err);
}
res.send({ Web_token: createJwtToken(user) });
});

});

};

51 changes: 51 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');


// Define schema
const userSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true,
},
password: String
});


//on save hook for hash and salting password
userSchema.pre('save', function (next) {
const user = this;
bcrypt.genSalt(10, function (err, salt) {
if (err) {
return next(err);
}
hash = bcrypt.hash(user.password, salt, null, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
});


// compare hash user password against loginPassword
userSchema.methods.comparePassword = function (candidatePassword, callback) {
bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
if (err) {
return callback(err)
}
callback(null, isMatch)
});
}

// Create Model Class
const userModel = mongoose.model('user', userSchema);

//Export model
module.exports = userModel;


27 changes: 27 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "authapi",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"dev": " start http://localhost:3000 & nodemon ./bin/www "
},
"dependencies": {
"bcrypt-nodejs": "0.0.3",
"body-parser": "~1.17.1",
"cookie-parser": "~1.4.3",
"debug": "~2.6.3",
"ejs": "~2.5.6",
"express": "~4.15.2",
"jwt-simple": "^0.5.1",
"mongoose": "^4.9.8",
"morgan": "~1.8.1",
"passport": "^0.3.2",
"passport-jwt": "^2.2.1",
"passport-local": "^1.0.0",
"serve-favicon": "~2.4.2"
},
"devDependencies": {
"nodemon": "^1.11.0"
}
}
23 changes: 23 additions & 0 deletions routes/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const express = require('express');
const router = express.Router();
const Authentication = require('../controllers/authentication');
const passport = require('passport');
const passportService = require('../services/passport_jwt');
const passportLocalService = require('../services/passport_local');

//middleware to use jwt strategy and set session to false as using jwt token
const AuthGuard = passport.authenticate('jwt', { session: false });
const local_Login = passport.authenticate('local', { session: false });

/* GET '/' */
router.get('/', AuthGuard, function (req, res, next) {
res.send('Working ok ');
});

/* POST signup. */
router.post('/signup', Authentication.signup);

/* POST signin. */
router.post('/signin', local_Login, Authentication.signin);

module.exports = router;
Loading

0 comments on commit 690a53b

Please sign in to comment.