SweetAuth - NodeJS User Authentication Simplified

sweet-auth handles following backend tasks for you:

Creating user accounts

Logging into accounts

Authorizing subsequent browser requests

Updating user passwords

Removing user accounts

Logging out from accounts

✔ No database required. Fully file based.

✔ Works with Express.

✔ Lightweight. Zero configurations.

API

API (req.user.*) Effect Returns create (email, password) Creates a new user A promise with success & failure handlers authenticate (email, password) Validates user login. Upon success, the client is given a token valid for 3 days. A promise with success & failure handlers isAuthorized Becomes true if the user has logged in with a valid token. N/A email Holds the user's email if logged in N/A deauthenticate () Logs out the current user. Clear the token. A promise with success & failure handlers updatePassword (currentPassword, newPassword) Updates the current password of the logged in user. A promise with success & failure handlers remove (password) Removes the account of the logged in user. A promise with success & failure handlers

QUICK START

Install sweet-auth package:

npm i sweet-auth

Add sweet-auth to your express app:

const express = require('express') const app = express() const sweetAuth = require('sweet-auth') app.use(sweetAuth) app.use(express.urlencoded()) // allows reading POST request data

Validate incoming requests for your protected pages with isAuthorized flag:

app.get('/private-page', (req, res) => { if (req.user.isAuthorized) { // user is logged in! send the requested page // you can access req.user.email } else { // user not logged in. redirect to login page } })

In order to be authorized, a user must be registered and logged in first:

app.post('/signup', (req, res) => { // extract sign up form data let email = req.body.email let password = req.body.password req.user.create(email, password) .then( () => { // tell user account is created // probably redirect to the login page }, (err) => { // tell user something went wrong } ) })

Then handle the login:

app.post('/api/login', (req, res) => { // extract html form data let email = req.body.email let password = req.body.password req.user.authenticate(email, password) .then( () => { // authentication success. // redirect to home page. }, (err) => { // authentication failed. // send error to client. } ) })

Upoun a successfull login, a token will be issued to the client which will be used to authenticate future requests. This token will be expired after 3 days.

Don't forget to checkout the demo

FAQ