techxnix-auth
v1.0.17
Published
Authentication library for Techxnix applications
Readme
Techxnix Auth Library
A reusable authentication library for NestJS applications.
Table of Contents
Installation
npm install techxnix-authSetup
- Import and configure TechxnixAuthModule in your app.module.ts:
import { Module } from '@nestjs/common';
import { TechxnixAuthModule } from 'techxnix-auth';
@Module({
imports: [
TechxnixAuthModule.forRoot({
jwt: {
secret: 'your-secret-key',
refreshSecret: 'your-refresh-secret-key',
expiresIn: '15m',
refreshExpiresIn: '7d',
},
}),
],
})
export class AppModule {}Decorators
@Public()
Marks a route as public, bypassing authentication:
@Public()
@Get('public-route')
publicRoute() {
return 'This route is public';
}@GetUser()
Retrieves the authenticated user from the request:
@Get('profile')
getProfile(@GetUser() user: IAuthPayload) {
return user;
}Guards
JwtAuthGuard
Protects routes requiring authentication:
@UseGuards(JwtAuthGuard)
@Get('protected')
protectedRoute(@GetUser() user: IAuthPayload) {
return `Hello ${user.email}`;
}JwtRefreshAuthGuard
Protects the refresh token endpoint:
@UseGuards(JwtRefreshAuthGuard)
@Post('refresh')
async refreshToken(@GetUser() user: IAuthPayload) {
return this.tokenService.generateTokens(user);
}Services
TokenService
Handles JWT token generation and verification:
constructor(private tokenService: TokenService) {}
async generateTokens(user: IAuthPayload) {
return this.tokenService.generateTokens(user);
}
async verifyToken(token: string) {
return this.tokenService.verifyToken(token);
}
async verifyRefreshToken(token: string) {
return this.tokenService.verifyRefreshToken(token);
}Complete Example
Here's a complete example of an auth controller:
import { Controller, Post, Get, Body, UseGuards } from '@nestjs/common';
import { TokenService } from 'techxnix-auth';
import { Public, GetUser, JwtAuthGuard, JwtRefreshAuthGuard } from 'techxnix-auth';
import { IAuthPayload } from 'techxnix-auth';
@Controller('auth')
export class AuthController {
constructor(
private readonly tokenService: TokenService,
private readonly userService: UserService
) {}
@Public()
@Post('signin')
async signIn(@Body() credentials: { email: string; password: string }) {
const user = await this.userService.validateUser(
credentials.email,
credentials.password
);
return this.tokenService.generateTokens({
sub: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName
});
}
@UseGuards(JwtAuthGuard)
@Get('me')
getProfile(@GetUser() user: IAuthPayload) {
return user;
}
@UseGuards(JwtRefreshAuthGuard)
@Post('refresh')
async refreshToken(@GetUser() user: IAuthPayload) {
return this.tokenService.generateTokens(user);
}
}Configure the module in your app.module.ts:
import { Module } from '@nestjs/common';
import { TechxnixAuthModule } from 'techxnix-auth';
@Module({
imports: [
TechxnixAuthModule.forRoot({
jwt: {
secret: 'your-secret-key',
refreshSecret: 'your-refresh-secret-key',
expiresIn: '15m',
refreshExpiresIn: '7d',
},
}),
],
})
export class AppModule {}Testing
Mock Auth Controller
For testing purposes, you can use the provided mock auth controller. Here's an example of how to set it up:
import { Controller, Post, Get, Body, UseGuards } from '@nestjs/common';
import { TokenService } from 'techxnix-auth';
import { Public, GetUser, JwtAuthGuard, JwtRefreshAuthGuard } from 'techxnix-auth';
import { IAuthPayload } from 'techxnix-auth';
// Mock user data for testing
const mockAuthPayload: IAuthPayload = {
sub: 'sub-uuid',
email: '[email protected]',
firstName: 'Test',
lastName: 'User',
};
@Controller('auth')
export class MockAuthController {
constructor(private readonly tokenService: TokenService) {}
@Public()
@Post('signin')
async signIn(@Body() payload: { email: string; password: string }) {
// Simple mock authentication
if (payload.email !== mockAuthPayload.email || payload.password !== 'password') {
throw new Error('Invalid credentials');
}
return this.tokenService.generateTokens({
...mockAuthPayload,
email: payload.email,
});
}
@UseGuards(JwtAuthGuard)
@Get('me')
getProfile(@GetUser() user: IAuthPayload) {
return user;
}
@UseGuards(JwtRefreshAuthGuard)
@Post('refresh')
async refreshToken(@GetUser() user: IAuthPayload) {
return this.tokenService.generateTokens({
...mockAuthPayload,
email: user.email,
});
}
}This mock controller provides three endpoints:
POST /auth/signin: Mock authentication endpoint that accepts email/passwordGET /auth/me: Protected endpoint that returns the current user's profilePOST /auth/refresh: Protected endpoint that refreshes the access token using a refresh token
Running E2E Tests
To run the e2e tests:
npm run test:e2eThe e2e tests verify the following authentication flows:
- Sign in and token generation
- Protected route access with valid token
- Protected route access with invalid token
- Token refresh with valid refresh token
- Token refresh with invalid token
Make sure to configure your jest-e2e.json properly:
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": "..",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": ["ts-jest", {
"tsconfig": "<rootDir>/tsconfig.json"
}]
},
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1"
}
}