Skip to content

thanglq1/nestjs-authentication-casl

Repository files navigation

Installation

$ npm install

Running the app

# development
$ npm run start

# watch mode
$ npm run start:dev

# production mode
$ npm run start:prod

Database

Database design just for testing authentication and authorization

Users

Roles

featurePermissions field is array contains multiple object. Each object is one feature and permission

Mail Service

After user signup. We'll send an email to user confirm

We are using node mailer, handlebars template and Amazon SES

Setup Amazon SES

Go to SES => SMTP Setting create ses-smtp account to get username and password. After create ses-smtp account success then go to SES => SMTP Setting to get host and port

Endpoints

POST - Signup

http://localhost:3000/api/auth/signup

Parameters

{
    "username": "admin",
    "email": "[email protected]",
    "password": "123456"
}

PUT-Verify Email

http://localhost:3000/api/users/verifyMail

Parameters

{
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IlRoYW5nTFEiLCJzdWIiOiI2MzRhNzI3NDA5ZWVkMzBkN2NlZTg1OWIiLCJlbWFpbCI6InRoYW5nbHFAdGVyYWFyay5jb20iLCJpYXQiOjE2NjU4MjMzNDksImV4cCI6MTY2NjQyODE0OX0.knkeR0EMWbuzE9OFhPaFEaudo07YHdWEu5dBr1aPgj8"
}

POST - Create Role

http://localhost:3000/api/roles

Parameters

{
    "name": "Seller",
    "description": "This is Seller role"
}

PUT - Assign Features And Permissions To Role

http://localhost:3000/api/roles/63254e0455b58996340b4b44/assignFeaturePermissionToRole

Parameters

{
    "featurePermissions": [
        {
            "feature": "INVOICE",
            "permissions": ["READ"]
        },
        {
            "feature": "ORDER",
            "permissions": ["CREATE", "READ", "UPDATE"]
        }
    ]
}

PUT - Assign Role To User

http://localhost:3000/api/users/assignRoleToUser

Parameters

{
    "roleId":"63254e0455b58996340b4b44",
    "userId": "63254dd955b58996340b4b3f"
}

Authorization

We have 2 ways authorization

  1. Use decorator CheckPermission and AuthzGuard
  @Post()
  @UseGuards(AuthzGuard)
  @CheckPermission([PermissionsType.CREATE, FeaturesType.ORDER])
  async create(@Body() createOrderDto: CreateOrderDto, @CurrentUser() user) {
    return this.ordersService.createOrder(createOrderDto);
  }
  1. Use caslAbilityFactory
  @Post()
  @UseGuards(AuthzGuard)
  async create(@Body() createOrderDto: CreateOrderDto, @CurrentUser() user) {
    const ability = await this.caslAbilityFactory.createForUser(user.sub);
    if (ability.can(PermissionsType.CREATE, FeaturesType.ORDER)) {
      return this.ordersService.createOrder(createOrderDto);
    }
    throw new CustomForbiddenException();
  }

Releases

No releases published

Packages

No packages published