0.9.2 • Published 2 years ago

@rhangai/nest-auth v0.9.2

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

@rhangai/nest-auth

Simpler implementation of a guard without using passport

Installation

yarn add @rhangai/nest-auth

Quick Usage

Define your authentication data

import { createAuthDefinition } from '@rhangai/nest-auth';

export type AuthData = {
	user: MyUserType;
};

const AuthDefinition = createAuthDefinition<AuthData>();

Create the guard

import { Injectable } from '@nestjs/common';
import { AuthData, AuthDefinition } from './auth-data';

@Injectable()
export class AuthGuard implements CanActivate {
	canActivate(ctx): Promise<boolean> {
		const [isValid] = await AuthDefinition.authenticate(ctx, () => this.getAuthData(ctx));
		if (isValid == null) return true;
		return isValid;
	}

	private async getAuthData(
		authExecutionContext: AuthExecutionContext
	): Promise<AuthData | null> {
		// Do your logic
		return {
			user: {}, // From somewhere
		};
	}
}

Use the module globally or locally

import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { AuthGuard } from './auth.guard';

@Module({
	providers: [
		// Global guard
		{
			provide: APP_GUARD,
			useClass: AuthGuard,
		},
	],
})
export class AuthModule {}

Decorators

Create the decorators

import { AuthDefinition } from './auth-data';

export const AuthUser = AuthDefinition.createDecorator((_, authData) => authData.user);

Use in the controller

import { Controller, Get } from '@nestjs/common';
import { AuthUser } from './auth-decorators';

@Controller()
export class SomeController {
	@Get()
	handler(@AuthUser() user: MyUserType) {
		return user;
	}
}
0.9.0

2 years ago

0.8.0

2 years ago

0.9.2

2 years ago

0.9.1

2 years ago

0.7.0

3 years ago

0.5.0

3 years ago

0.6.0

3 years ago

0.4.19

3 years ago

0.4.19-alpha.0

3 years ago

0.3.0

4 years ago

0.3.2

4 years ago

0.4.0

4 years ago

0.2.10

4 years ago

0.2.5

4 years ago

0.2.0

4 years ago

0.1.2

4 years ago

0.1.3

4 years ago

0.1.0

4 years ago

0.0.12

4 years ago

0.0.10

4 years ago

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.6

4 years ago

0.0.5

4 years ago