0.2.0 ā€¢ Published 8 months ago

nest-auth-base v0.2.0

Weekly downloads
-
License
UNLICENSED
Repository
github
Last release
8 months ago

Auth base banner with 'Auth base' heading, 'Wrote the routine code for you, so you don't have to' paragraph and decorative icons

Nest auth base

Customizable module for JWT username-password authentication & authorization. Create one service, put some guards and it's done

Installation

$ npm i nest-auth-base

Working simple usage

  • Create your account interface, unique username and password are always required. If you want to use roles guard, you must add the roles property
export interface Account {
  username : string,
  password : string,
  roles : string[],
  reputation : number
}
  • Create accounts service, so library will be able to manage your datasource. In this example we use just a simple array
@Injectable()
export class AccountsService extends AuthBaseAccountsService<Account> {
    private readonly accounts : Account[]

    createAccount(credentials: ProcessedCredentials) {
        const newAccount : Account = {
            username: credentials.username,
            password: credentials.hashedPassword,
            roles: [ 'USER' ],
            reputation: 0 
        }

        this.accounts.push(newAccount)

        return newAccount
    }
    
    getAccountByUsername(username: string) {
        return this.accounts.find(account => account.username === username)
    }
}
  • Import AuthBaseModule. It's global so you can just import it in app module and use guards everywhere ā€Žā€Ž
@Module({
    imports: [
        AuthBaseModule.register({
            accountsService: AccountsService,
            jwtSecretKey: 'YOUR_SECRET_KEY'
        })
    ],
    controllers: [ AppController ],
})
export class AppModule {}

It's strongly recommended to get your jwtSecretKey from your enviroment variables via Nest.js config module

Now there are two endpoints available:

{
  "username": "USERNAME",
  "password": "PASSWORD"
}
{
  "username": "USERNAME",
  "password": "PASSWORD"
}

ā €

  • Add guards to your whole controller or its methods

AuthGuard checks if user is authenticated by verifying JWT token in bearer-type Authorization header

@Controller()
export class AppController {
    @Get('me')
    @UseGuards(AuthGuard)
    async getAccount(@CurrentAccount() account : Account) {   
        return account
    }
}

RolesGuard checks if user is authenticated and has one of specified roles

@Controller()
export class AppController {
    @Get('me')
    @AllowedRoles('ADMIN', 'DEVELOPER')
    @UseGuards(RolesGuard)
    async getAccount(@CurrentAccount() account : Account) {   
        return account
    }
}

That's all. Now you have secured API

Learn more

Docs soon

0.2.0

8 months ago

0.1.0

8 months ago

0.0.6

9 months ago

0.0.5

9 months ago

0.0.4

9 months ago

0.0.3

9 months ago

0.0.2

9 months ago

0.0.1

9 months ago