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

nucleusoauth

v1.1.1

Published

sign in using nucleus auth for PSG students

Downloads

3

Readme

Nucleus Oauth

The Auth tool for Students

Build

Use the NucleusAuth protocol for authentication and authorization. This package supports common OAuth scenarios such as those for web server, client-side, installed, and limited-input device applications.

To begin, obtain OAuth credentials from the nucleus Console. Then your client application requests an access token from the Nucleus Authorization Server, extracts a token from the response, and sends the token to the Nucleus API that you want to access.

  • Easy sign in option
  • Retains cookies and gives a single sign on option using pre existing cookies
  • ✨LOGIN Magic ✨

This module provides Express middleware for validating JWTs (JSON Web Tokens) through the jsonwebtoken module. The decoded JWT payload is available on the request object.

Install

$ npm install nucleusoauth

Usage

Basic usage using an HS256 secret:

var jwt = require("express-jwt");

app.get(
	"/protected",
	jwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }),
	function (req, res) {
		if (!req.user.admin) return res.sendStatus(401);
		res.sendStatus(200);
	}
);

The decoded JWT payload is available on the request via the user property.

Required Parameters

The algorithms parameter is required to prevent potential downgrade attacks when providing third party libraries as secrets.

:warning: Do not mix symmetric and asymmetric (ie HS256/RS256) algorithms: Mixing algorithms without further validation can potentially result in downgrade vulnerabilities.

jwt({
	secret: "shhhhhhared-secret",
	algorithms: ["HS256"],
	//algorithms: ['RS256']
});

If the JWT has an expiration (exp), it will be checked.

If you are using a base64 URL-encoded secret, pass a Buffer with base64 encoding as the secret instead of a string:

jwt({
	secret: Buffer.from("shhhhhhared-secret", "base64"),
	algorithms: ["RS256"],
});

Optionally you can make some paths unprotected as follows:

app.use(
	jwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }).unless({
		path: ["/token"],
	})
);

Use function nucleus_auth to use the API These params must be included in the request body:

  • Username
  • Password
  • Student/tutor
await axios
	.post("https://nucleus.amcspsgtech.in/oauth", request_body)
	.then(async (response) => {
		if (response.status === 200 && response.data.status === "Success") {
			const cookies = response.headers["set-cookie"];
			const data = {
				role: req.body.role,
				id: req.body.userID,
				cookies: cookies,
			};
			const userData = await userHelper.fetch_user(data);
			const response_data = {
				rollNo: userData.id,
				firstName: userData.firstName,
				lastName: userData.lastName,
				email: userData.email,
				classId: userData.classId,
				role: "student",
			};
			const token = jsonwebtoken.sign(response_data, process.env.JWT_SECRET);
			res.cookie("bonafide_token", token);
			res.status(200).json({
				success: true,
				data: response_data,
			});
		}
	})
	.catch(() => {
		res.clearCookie("bonafide_token");
		res.status(401).json({
			success: false,
		});
	});

Customizing Token Location

A custom function for extracting the token from a request can be specified with the getToken option. This is useful if you need to pass the token through a query parameter or a cookie. You can throw an error in this function and it will be handled by express-jwt.

app.use(
	jwt({
		secret: "hello world !",
		algorithms: ["HS256"],
		credentialsRequired: false,
		getToken: function fromHeaderOrQuerystring(req) {
			if (
				req.headers.authorization &&
				req.headers.authorization.split(" ")[0] === "Bearer"
			) {
				return req.headers.authorization.split(" ")[1];
			} else if (req.query && req.query.token) {
				return req.query.token;
			}
			return null;
		},
	})
);

For example, if the secret varies based on the JWT issuer:

var jwt = require("express-jwt");
var data = require("./data");
var utilities = require("./utilities");

var secretCallback = function (req, payload, done) {
	var issuer = payload.iss;

	data.getTenantByIdentifier(issuer, function (err, tenant) {
		if (err) {
			return done(err);
		}
		if (!tenant) {
			return done(new Error("missing_secret"));
		}

		var secret = utilities.decrypt(tenant.secret);
		done(null, secret);
	});
};

app.get(
	"/protected",
	jwt({ secret: secretCallback, algorithms: ["HS256"] }),
	function (req, res) {
		if (!req.user.admin) return res.sendStatus(401);
		res.sendStatus(200);
	}
);

Error handling

The default behavior is to throw an error when the token is invalid, so you can add your custom logic to manage unauthorized access as follows:

app.use(function (err, req, res, next) {
	if (err.name === "UnauthorizedError") {
		res.status(401).send("invalid token...");
	}
});

You might want to use this module to identify registered users while still providing access to unregistered users. You can do this by using the option credentialsRequired:

app.use(
	jwt({
		secret: "hello world !",
		algorithms: ["HS256"],
		credentialsRequired: false,
	})
);

Tests

$ npm install
$ npm test

Development

Want to contribute? Great! Go to the github and put in a merge rqeuest

License

MIT

Free Software, Hell Yeah!