npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

secure-tokenize

v3.2.1

Published

A simplified authentication package

Downloads

10

Readme

Authentication Package

This package provides utilities for user authentication using JSON Web Tokens (JWT).

Installation

Install the package using npm:

npm install secure-tokenize

Usage

Import the Authentication class from the package:

const Authentication = require("secure-tokenize");

Simple JWT Authentication

Creating Instance

Create an instance of the Authentication class by providing the JWT secret key.

const auth = new Authentication({
  jwtSecretKey:"jwt_secret_key",
  authMethod:"jwt",
});

Generate a JWT token for a user object:

const user = { userId: 123, username: 'john_doe' }; // Sample

const token = auth.generateToken({
  user,
  jwt:{
     options:{
         expiresIn:6000
     } 
  }
});

Verify Token

Set middleware in express application.

const app = require("express")();

// Middleware
app.use('/protected', auth.authenticate(),(request, response, next) => {
    
    // This will contain user data 
    req.auth;
    
    next()
});

Authenticate Via Facebook

Creating Instance

const auth = new Authentication({
    jwtSecretKey:"jwt_secret_key",
    authMethod:"facebook",
    facebookAppId:"<facebook_app_id>",
    facebookAppSecret:"<facebook_app_secret_key>",
    url:"http://localhost:3000",
    callbackUrl:"/auth/facebook/callback",
    facebookAPIVersion:"v19.0"
});

Creating Routes For Authentication And Callback

Use the auth.facebookRedirect middleware to authenticate user and generate code.


// Route for initiating the authentication process
app.get('/auth/facebook', auth.facebookRedirect.bind(auth));

Here you will be redirected after successfully signed in. You will get code in the query params which you can get and create a JWT token based on the facebook data you get.

app.get("/auth/facebook/callback", async (req,res,next) => {

    const token = await auth.generateToken({
        jwt:{
            options:{
                expiresIn:6000
            }
        },
        faceBook:{
            code:req.query.code
        }
    })
    
    res.send(token)
});

After that the authenticate middleware remains the same.

// Middleware
app.use('/protected', auth.authenticate(),(request, response, next) => {
    
    // This will contain user data from facebook
    req.auth;
    
    next()
});

Authentication Via Google

Creating Instance

You can authenticate user via google by doing some minimal changes if required.

const auth = new Authentication({
    jwtSecretKey:"AveryMuchSecretThatNoOneCanHack",
    authMethod:"google",
    googleAppClientId:"<GOOGLE_APP_CLIENT_ID>",
    googleClientSecret:"<GOOGLE_CLIENT_SECRET>",
    googleRedirectURL:"http://localhost:3000/auth/google/callback"
});

Setting Up Routes

These routes facilitate Google authentication, redirecting user to Google's login page and handling the callback to generate a token for authenticated user.

// Route for initiating the authentication process
app.get('/auth/google', auth.googleRedirect.bind(auth));

app.get("/auth/google/callback", async (req,res,next) => {

    const token = await auth.generateToken({
        jwt:{
            options:{
                expiresIn:6000
            }
        },
        google:{
            code: req.query.code
        }
    })

    res.send(token)

});

Getting Authenticated Data

This route mandates authentication via auth.authenticate() middleware and returns authenticated user data from Google in JSON format.

app.get("/protectedRoute",auth.authenticate(),(req, res, next) => {

    // This will contain user data returned from google
    res.json({
        data: req.auth
    });
})

The above will give the access token and bearer token for the user. You can get user specific details like emails, names etc by using the below method if needed. The first param is access_token and the second param is personFields

Available personFields can be found on this link personFields

app.get("/protectedRoute",auth.authenticate(), async (req, res, next) => {

    // This will contain user data returned from google
    const accessToken = req.auth.access_token;
    
    const user = await auth.getGoogleUserProfile(accessToken,"names,addresses");
    
    res.status(200).send();
})

Others

Custom Function When Using auth.authenticate().


// In result you will get the verified data from the token.

const customFn = function (result) {
  return {
    keyToSetAgainst:"userData", // this will be the key set to request object. (Required)
    data:{                      // Modified data along with the verified data. (Optional)
      ...result,
      timeStamp: new Date()
    }
  }
}

app.get("/protectedRoute",auth.authenticate({customFn}),(req, res, next) => {
  res.json(req.userData);
})

License

This project is licensed under the MIT License - see the LICENSE.md file for details.