2.0.27 • Published 2 years ago

login-express v2.0.27

Weekly downloads
9
License
MIT
Repository
github
Last release
2 years ago

Login.js

Minimalist module built to set up a secure back-end express login system in record speed. Login.js seemlessly adds to your existing express server and sets up secure login routes.

Installation

Before installing, download and install Node.js.

For brand new projects, be sure to create a package.json first with the npm init command.

Next, run the following command in your terminal:

npm i login-express

Dependencies

This package is meant to be used in Node.js with Express and Mongoose. Make sure to install these dependencies when using login-express in your project:

npm i express mongoose

You must also have the URI of a running MongoDB cluster. We recommend getting started with a free MongoDB Atlas cluster.

Simple Setup

Create an index.js file, and paste the starter code as shown below. It assumes you've using Express.js.

const express = require('express');
const app = express();
const loginJS = require('login-express');

const dbConfig = {
  mongodbURI: 'my-mongodb-uri', // required
  jwtSecret: 'jwt-secret', // required
  passwordLength: 10, // default: 8
  jwtSessionExpiration: 3600 // default: 7200
};

const appConfig = {
  jwtResetSecret: 'jwt-reset-secret', // required
  emailFromUser: 'myemail@example.com', // required
  emailFromPass: 'myemailpassword', // required
  emailHost: 'stmp.myemailserver.com', // required
  emailPort: 465, // required
  emailSecure: true, // required
  jwtResetExpiration: 1000, // default: 900
  basePath: '/auth' // default: '/api'
};

loginJS(dbConfig, appConfig, app, express);

You can pass in custom email templates for verification and/or password reset requests.

let verifyEmailConfig = {
  emailHeading: 'Your Company Name',
  emailSubjectLine: 'Verify Password',
  emailMessage: 'Custom verify password message goes here. Verify link is auto-generated.'
};

let resetEmailConfig = {
  emailHeading: 'Your Company Name',
  emailSubjectLine: 'Reset Password',
  emailMessage: 'Custom reset password message goes here. Reset link is auto-generated.'
};

// pass these config objects into the loginJS method 
loginJS(dbConfig, appConfig, app, express, verifyEmailConfig, resetEmailConfig);

API Endpoints

The Simple Setup creates API routes for you to use. Below endpoints are created upon calling the loginJS method with the default basePath value of /api:

Register Client

POST: /api/register

Get Authorized Client

GET: /api/login

Sign In Client

POST: /api/login

Verify Email Address

PATCH: /api/verify-email

Forgot Password

PUT: /api/forgot-password

Reset Password

PATCH: /api/reset-password

Mongoose ORMs

The Simple Setup creates a user mongoose schema and document. You do not need to create or modify the user document, as it is created upon calling the loginJS method.

Below is the code that initializes the user schema and document at lib/models/User.js:

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  avatar: {
    type: String,
  },
  date: {
    type: Date,
    default: Date.now,
  },
  verifyEmail: {
    type: Boolean,
  },
  verifyEmailToken: {
    type: String,
    default: '',
  },
  resetToken: {
    type: String,
    default: '',
  },
});

module.exports = User = mongoose.model('user', UserSchema);

Advanced Setup (Class-Based Manager)

The code outlined in Quick Setup automatically creates routes and user schemas for you. If you need more fine-tuned control over your Express server, then use the LoginExpress class instead:

const express = require('express');
const mongoose = require('mongoose');
const { LoginExpress } = require('login-express');

// initialize express
const app = express();

// initialize db
mongoose.connect('my-mongodb-uri');

// initialize ORM
const accountSchema = new mongoose.Schema({
  // required fields
  name: { type: String, required: true },
  email: { type: String, required: true },
  password: { type: String, required: true },
  avatar: { type: String, default: '' },
  verifyEmail: { type: Boolean, default: false },
  verifyEmailToken: { type: [String], default: [] },
  resetToken: { type: [String], default: [] },
  auth: { type: String, default: 'USER' },
  // example of custom field
  customField: { type: String, default: 'initialValue' },
})
const accountModel = mongoose.model('Account', accountSchema);

// intialize login-express
const loginJS = new LoginExpress({
  jwtSecret: 'jwt-secret',
  jwtResetSecret: 'jwt-reset-secret',
  emailFromUser: 'myemail@example.com',
  emailFromPass: 'myemailpassword',
  emailHost: 'smtp.myemailserver.com',
  userModel: accountModel,
  clientBaseUrl: 'http://localhost:3000'
});

// create express router
const router = express.Router();

// get user
router.get('/user', loginJS.isLoggedIn, (req, res) => {
  res.status(200).send(req.user)
});

// register
router.post('/register', async (req, res) => {
  const { name, email, password } = req.body;
  try {
    await loginJS.register(res, { name, email, password });
    res.status(200).end();
  } catch (err) {
    res.status(400).send(err.message);
  }
});

// login
router.post('/login', async (req, res) => {
  const { email, password } = req.body;
  try {
    await loginJS.login(res, { email, password });
    res.status(200).end();
  } catch (err) {
    res.status(400).send(err.message);
  }
});

// logout
router.post('/logout', loginJS.isLoggedIn, async (req, res) => {
  try {
    loginJS.logout(res);
    res.status(200).end();
  } catch (err) {
    res.status(400).send(err.message);
  }
});

// send verification email
router.post(
  '/send-verify-email',
  loginJS.isLoggedIn,
  async (req, res) => {
    try {
      await loginJS.sendVerificationEmail(req.user);
      res.status(200).end();
    } catch (err) {
      res.status(400).send(err.message);
    }
  }
);

// verify email
router.patch('/verify-email', async (req, res) => {
  const { token } = req.body;
  try {
    await loginJS.verify(token);
    res.status(200).end();
  } catch (err) {
    res.status(400).send(err.message);
  }
});

// request password change
router.post('/send-reset-password', async (req, res) => {
  const { email } = req.body
  try {
    await loginJS.sendPasswordResetEmail(email);
    res.status(200).end();
  } catch (err) {
    res.status(400).send(err.message);
  }
})

// change password
router.patch('/reset-password', async (req, res) => {
  const { resetToken, newPassword } = req.body;
  try {
    await loginJS.changePassword(res, { resetToken, newPassword });
    res.status(200).end();
  } catch (err) {
    res.status(400).send(err.message);
  }
})

// all routes have a /auth path prefix
app.use('/auth', router);

// run express server
app.listen(5000, () => console.log('Server started on port 5000'));

Features

  • Client sign up and sign In

  • Client gravatar

  • Encrypted password storage in MongoDB

  • Client authentication and reset password

  • Client email verification

  • Reset password email sent to the client

  • Verify email sent to the client

TypeScript

loginJS supports TypeScript out of the box. Using some parts of the package requires you to use types that are provided by the package:

Middlewares

import { LoginExpress, AuthRequest } from 'login-express';

const loginJS = new LoginExpress({
  // ...
});

// ...

// get user
router.get('/user', loginJS.isLoggedIn, (req: AuthRequest, res) => {
  res.status(200).send(req.user);
});

Testing Endpoints in Postman (illustrations)

Register Client

Shows the req object with the client's name, email, and password sent to the server, and it shows the res object returned with the token.

register-client

Get Authorized Client Information

Shows x-auth-token and its value set in the headers, and it shows the res object returned with the client details.

get-auth-client

Sign In Client

Shows the req object sent with the client email and password to the server, and it shows the res object returned with the token.

signin-client

Verify Email Address

Shows the req object sent with the 'verifyEmailToken' to the server, and it shows the res object returned with a msg to the client.

verify-email

Forgot Password

Shows the req object sent with the client email to the server, and it shows the res object returned with a msg to the client.

forgot-password

Reset Password

Shows the req object sent with the 'resetToken' and client's 'newPassword' to the server, and it shows the res object returned with a msg to the client.

reset-password

Reset Password Email Sent to Client

reset-email

Verification Email Sent to Client

verify-your-email

Security Issues

If you discover a security vulnerability or would like to help me improve Login.js, please email me. Alternatively, submit a pull request at this project's Github, and we'll go from there. Thank you for your support.

2.0.26

2 years ago

2.0.27

2 years ago

2.0.24

2 years ago

2.0.25

2 years ago

2.0.15

2 years ago

2.0.3

2 years ago

2.0.16

2 years ago

2.0.5

2 years ago

2.0.13

2 years ago

2.0.14

2 years ago

2.0.4

2 years ago

2.0.11

2 years ago

2.0.6

2 years ago

2.0.12

2 years ago

2.0.9

2 years ago

2.0.10

2 years ago

2.0.8

2 years ago

2.0.19

2 years ago

2.0.17

2 years ago

2.0.18

2 years ago

2.0.22

2 years ago

2.0.23

2 years ago

2.0.20

2 years ago

2.0.21

2 years ago

2.0.2

4 years ago

2.0.1

4 years ago

2.0.0

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago