Socket
Book a DemoInstallSign in
Socket

@kaname-png/plugin-api-jwt

Package Overview
Dependencies
Maintainers
0
Versions
238
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@kaname-png/plugin-api-jwt

Plugin for @sapphire/framework to add JSON Web Tokens strategy in @sapphire/plugin-api plugin.

5.0.1
latest
Source
npmnpm
Version published
Weekly downloads
69
165.38%
Maintainers
0
Weekly downloads
 
Created
Source

Neko Plugins Logo

@kaname-png/plugin-api-jwt

Plugin for @sapphire/framework to add JSON Web Tokens strategy in @sapphire/plugin-api plugin to JWT.

GitHub codecov npm (scoped) npm

Description

This plugin add the authentication system JSON Web Tokens to @sapphire/plugin-api plugin for @sapphire/framework.

This plugin does not change the behavior of the @sapphire/plugin-api plugin, so after installing the plugin you can continue to use the @sapphire/plugin-api plugin as you always have.

Features

  • Fully ready for TypeScript!
  • Includes ESM ready entrypoint
  • Easy to use

Installation

@kaname-png/plugin-api-jwt depends on the following packages. Be sure to install these along with this package!

You can use the following command to install this package, or replace npm install with your package manager of choice.

npm install @kaname-png/plugin-api-jwt @sapphire/framework @sapphire/plugin-api

Usage

JavaScript

In your main or setup file, register the plugin:

// Remember to register the API plugin first, then this plugin.
require('@sapphire/plugin-api/register');
require('@kaname-png/plugin-api-jwt/register');

Once the plugin is registered, we have to configure some options.

async function main() {
	const client = new SapphireClient({
		api: {
			auth: {
				id: 'xxx' /** client oauth id **/,
				secret: 'xxx' /** client oauth secret **/,
				redirect: 'https://kaname.netlify.app/oauth' /** client oauth redirect **/,
				jwt: {
					secret: 'uwu' /** JWT tokens are signed with this secret key. (required) **/,
					issuer: 'kaname.netlify.app' /** See https://jwt.io/introduction  (optional and by default api.auth.redirect) **/,
					algorithm: 'HS256' /**  (optional and by default HS512) **/,
					sessionsHooks: {
						/** Optional hooks for persistent sessions (optional) **/,
						get: (token, type) => {
							// Do something with your database or something else.
							// ...

							return { access_token: '<access_token>', refresh_token: '<refresh_token>' };
						},
						create: (payload) => {
							// Do something with your database or something else.
							// ...
						},
						delete: (accessToken) => {
							// Do something with your database or something else.
							// ...
						}
					}
				}
			}
		}
	});

	await client.login();
}

void main();

TypeScript

In your main or setup file, register the plugin:

// Remember to register the API plugin first, then this plugin.
import '@sapphire/plugin-api/register';
import '@kaname-png/plugin-api-jwt/register';

Once the plugin is registered, we have to configure some options.

async function main() {
	const client = new SapphireClient({
		api: {
			auth: {
				id: 'xxx' /** client oauth id **/,
				secret: 'xxx' /** client oauth secret **/,
				redirect: 'https://kaname.netlify.app/oauth' /** client oauth redirect **/,
				jwt: {
					secret: 'uwu' /** JWT tokens are signed with this secret key. (required) **/,
					issuer: 'kaname.netlify.app' /** See https://jwt.io/introduction  (optional and by default api.auth.redirect) **/,
					algorithm: 'HS256' /**  (optional and by default HS512) **/,
					sessionsHooks: {
						/** Optional hooks for persistent sessions (optional) **/,
						get: (token, type) => {
							// Do something with your database or something else.
							// ...

							return { access_token: '<access_token>', refresh_token: '<refresh_token>' };
						},
						create: (payload) => {
							// Do something with your database or something else.
							// ...
						},
						delete: (accessToken) => {
							// Do something with your database or something else.
							// ...
						}
					}
				}
			}
		}
	});

	await client.login();
}

void main();

How to use

Now, when you log in you will get a response like this, where the authentication token is attached.

Remember that the authentication token must be in the authorization header with the value: Bearer [ token here ].

{
	"user": {
		"auth": {
			// See https://discord.com/developers/docs/topics/oauth2#authorization-code-grant-access-token-response
		},
		"data": {
			"id": "858367536240394259",
			"username": "kaname-png",
			"avatar": "28f2ec4eec159df460dc9b58f2a80318",
			"discriminator": "1751",
			"public_flags": 0,
			"flags": 0,
			"banner": null,
			"banner_color": null,
			"accent_color": null,
			"verified": true
		}
	},
	"access_token": "eyJhbGciOiJIUzI1NiJ9.XXXXX",
	"refresh_token": "eyJhbGciOiJIUzI1NiJ9.XXXXX"
}

You can get the token information on a route, middleware, etc. in the following way:

Javascript

const { methods, Route } = require('@sapphire/plugin-api');

class UserRoute extends Route {
	constructor(context, options) {
		super(context, {
			...options,
			route: 'user/route'
		});
	}

	[methods.GET](request, response) {
		const session = request.session;
		response.json({ session });
	}
}

exports.default = UserRoute;

Typescript

import { ApiResponse, methods, Route } from '@sapphire/plugin-api';
import type { ApiRequest } from '@kaname-png/plugin-api-jwt';

export class UserRoute extends Route {
	constructor(context: Route.Context, options: Route.Options) {
		super(context, {
			...options,
			route: 'user/route'
		});
	}

	[methods.GET](request: ApiRequest, response: ApiResponse) {
		const session = request.session;
		response.json({ session });
	}
}

It is important to remember that if the authorization token is invalid, then the _request.auth variable will be null.

And as mentioned in the description, this plugin does not change the way @sapphire/plugin-api plugin is used, so you can follow the @sapphire/plugin-api plugin documentation.

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Kaname

💻 🐛 📖 🚇 🚧 👀

This project follows the all-contributors specification. Contributions of any kind welcome!

Keywords

sapphiredev

FAQs

Package last updated on 16 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.