Coder Social home page Coder Social logo

trulymittal / api-authentication-nodejs Goto Github PK

View Code? Open in Web Editor NEW
220.0 7.0 101.0 322 KB

API Authentication using JWT's (JSON Web Tokens). Plug n Play inside any app which requires authentication. NodeJs Express MongoDB & Redis.

JavaScript 97.50% Shell 2.50%
authentication jwt-authentication jwt jwt-token jwt-auth jwt-tokens api nodejs redis mongodb expressjs

api-authentication-nodejs's Introduction

API Authentication using NodeJs

This is an Authentication API using JWT's that you can plug inside your current project or you can start with a new one. Email & Password is used for authentication.

The API based on Node.js, Express, MongoDB & Redis, following the MVC pattern i.e. Model View Controller.

Mongoose is used for storing Users in Database. Redis is used for storing Refresh Tokens - to validate them as well at the same time Blacklisting them.

The application is production ready.


To start setting up the project

Step 1: Clone the repo

git clone https://github.com/trulymittal/API-Authentication-NodeJs.git

Step 2: cd into the cloned repo and run:

npm install

Step 3: Put your credentials in the .env file.

PORT=3000
MONGODB_URI=mongodb://localhost:27017
DB_NAME=YOUR_DB_NAME
ACCESS_TOKEN_SECRET=GENERATE_FROM_GENERATE_KEYS_FILE_IN_HELPER
REFRESH_TOKEN_SECRET=GENERATE_FROM_GENERATE_KEYS_FILE_IN_HELPER

Step 4: To generate 256-bit keys for JWT

node ./helpers/generate_keys.js

Step 5: Install Redis (Linux Ubuntu)

sudo apt-get install redis-server

Step 6: Run Redis Server (Linux Ubuntu)

redis-server

Step 7: Install MongoDB (Linux Ubuntu)

See https://docs.mongodb.com/manual/installation/ for more infos

Step 8: Run Mongo daemon

sudo service mongod start

Step 9: Start the API by

npm start

Step 10 (Optional): Change the expiration time of Access Token and Refresh Token according to your needs by going inside the ./helpers/jwt_helper.js file.

Author

Contribute

You can fork this repo and send me a PR.

License

This project is licensed under the MIT License.

api-authentication-nodejs's People

Contributors

dependabot[bot] avatar gillesbruno avatar trulymittal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

api-authentication-nodejs's Issues

Redis connection lost and command aborted. It might have been processed

I have deployed API on another server and Redis on another server and connect each server for Redis but after some time like 10min or so if I try to access Redis data from API it's giving me AbortError: Redis connection lost and command aborted. It might have been processed but on local it's working fine.

Why you used client.SET in this module? What is the Used

signRefreshToken: (userId) => {
return new Promise((resolve, reject) => {
const payload = {}
const secret = process.env.REFRESH_TOKEN_SECRET
const options = {
expiresIn: '1y',
issuer: 'pickurpage.com',
audience: userId,
}
JWT.sign(payload, secret, options, (err, token) => {
if (err) {
console.log(err.message)
// reject(err)
reject(createError.InternalServerError())
}

    client.SET(userId, token, 'EX', 365 * 24 * 60 * 60, (err, reply) => {
      if (err) {
        console.log(err.message)
        reject(createError.InternalServerError())
        return
      }
      resolve(token)
    })
  })
})

},

Uncaught Error - App crashes

@trulymittal
Hey, Thanks for the tutorial :)
But I've got a question
in User.model.js line: 30
Let's say an error will happen while hashing the password in try block
It will pass the error to the catch block and will be passed into next() function
But where would you handle that error ??
The error is not handled anywhere and it crashes the entire app

userSchema.pre('save', async function (next) {
  try {
    // something went wrong while hashing the password
    throw new Error('something went wrong')
  } catch (error) {
    // This will crash the app
    next(error)
  }
})

jwt

Sir how jwt identifies token is expired...?

ReplyError: ERR wrong number of arguments for 'set' command

I created separate file to test REDIS SET method but sending error of wrong argument.

const client = require('./config/redis_config');
client.SET(1, "test", 'EX', 3 * 24 * 60 * 60, (err, reply) => {
  if (err) {
    console.log(err);
    return;
  }
  return reply;
});

If I remove EX and TTL it works fine.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.