Go to bilibili.com for an accompanying video tutorial

In my article “LoopBack3.0 API creation practice”, I configured the permission management in the official example cafe comment project, and realized the permission control according to the project requirements. However, when we configure the permission management policy, we define that all commenters cannot add, delete, change and check the CoffeeShop model.

How to manage the data of coffeeShops? This is the background management we often say, need an administrator admin role to assume. This paper continues this project to introduce how to define a role admin, associate the role with users, and grant the super administrator permission to the role, which can add, delete, change and check all models including CoffeeShop.

I. Project Overview

This is an official example of a coffee shop review.

Cafe Review is a website that we can use to post reviews of coffee shops. There are three data models:

  • CoffeeShop coffee shop
  • Review comments
  • Reviewer reviewers

They have the following relationship:

  • CoffeeShop has several reviews
  • CoffeeShop has multiple Reviewer’s
  • Review belongs to a CoffeeShop
  • Review belongs to a Reviewer
  • Reviewer has multiple reviews

In general, users can create, edit, delete, and read coffee shop reviews and specify basic rules and permissions via ACLs:

  • Comments can be read by anyone, but they must be logged in to create, edit or delete them.
  • Anyone can register as a user and be logged in or logged out.
  • Logged-in users can create new reviews and edit or delete their own, but they cannot modify content related to coffee shops.

2. Create roles

LoopBack allows us to define static and dynamic roles. Static roles are stored in the data source and mapped to users. In contrast, dynamic roles are not assigned to users but are determined during access.

LoopBack provides the following built-in dynamic roles:

Role object property String value Description
Role.OWNER $owner Owner of the object
Role.AUTHENTICATED $authenticated authenticated user
Role.UNAUTHENTICATED $unauthenticated Unauthenticated user
Role.EVERYONE $everyone Everyone

Static roles can be created by coding. LoopBack allows you to write your own JS script files, which can be named at any time and stored in the /server/boot/ directory. When the node. Command is executed, the code in the script file is automatically executed. We can write it this way/server/boot/createAdmin js code:

module.exports = function(app) {
  var User = app.models.Reviewer;
  var Role = app.models.Role;
  var RoleMapping = app.models.RoleMapping;

  User.create(
    [{ username: "admin", email: "[email protected]", password: "admin"}].function(err, users) {
      if (err) throw err;

      console.log("Created users:", users);

      //create the admin role
      Role.create(
        {
          name: "admin"
        },
        function(err, role) {
          if (err) throw err;

          console.log("Created role:", role);

          //make RoleMapping
          role.principals.create(
            {
              principalType: RoleMapping.USER,
              principalId: users[0].id
            },
            function(err, principal) {
              if (err) throw err;

              console.log("Created principal:", principal); }); }); }); };Copy the code

Code parsing

  • Line 1 is the fixed notation. Define a function and expose it and pass it inappParameter to call the model of the app.
  • Lines 2-4 define and assign user, role, and mapping variables, respectively.
  • Lines 6 through 11 create the user. If the user is created successfully, continue to create the role.
  • Lines 14 to 21 create the role. If the user is created successfully, continue to create the mapping.
  • Lines 24 through 32 create the mapping between users and roles.

After the role is created, we can see the three documents we just created in the MongoDB database:

> use cshop
switched to db cshop
> show collections
Reviewer
Role
RoleMapping
> db.Role.find()
{ "_id" : ObjectId("5d875ecf98b8840aad726654"), "name" : "admin"."created" : ISODate("The 2019-09-22 T11: earth. 325 z"), "modified" : ISODate("The 2019-09-22 T11: earth. 325 z")}Copy the code

Role authorization

The lb acl command is used for role authorization. This time we give the admin role the maximum permissions within the application.

lb acl ? Select the model to which ACL entries apply: (all existing models)? Select ACL scope: All methods and attributes? Select access type: All (matches all types)? Select characters other? Please enter a role name: admin? Explicitly authorize access by selecting the permissions to applyCopy the code

Json file, you can see the authorization configuration code for the admin role: /common/ Models /coffee-shop.json

{
      "accessType": "*"."principalType": "ROLE"."principalId": "admin"."permission": "ALLOW"
    }
Copy the code

In/common/models/review. Json and/common/models/review. The json file also can see on the admin role authorization configuration code.

4. Interface debugging

Enter the command node. In the project root directory to start the application. According to the prompt input http://localhost:3000/explorer/ in your browser’s address bar, to interface debugging page.

An operation performed by an unlogged user

  • Click on Reviewer to expand the Reviewer API.

  • Click on theget/ReviewersThe operation prompt page is displayed.

  • Click on theTry it out!Button to display a 401 error indicating authorization is required.

Log in as the admin user

  • Click on thePost/Reviewers/loginThe login prompt page is displayed.

  • Enter login parameters:

  • After a successful login, information about admin is displayed.

  • Copy the message returned by adminidString value, in this case2F410ZR1bEMJFrTY4LtVPRb6TPzsCPsXOEXpO1u9weD561dx1hkim87AY1fQGlt7Pasted to the first line of the window pageaccessToken, and then clickSet Access TokenButton.

  • Click again on theget/Reviewers, and click when the operation prompt interface appearsTry it out!Button, no longer prompts the information that requires authorization, successfully returns the information of the two existing users in the application.

Log out

  • Click on thePost/Reviewers/logout, log out.

  • Click again on theget/Reviewers, and click when the operation prompt interface appearsTry it out!Button, again prompting the information to be authorized.

Permission to verify

We have preliminarily verified the permissions of the admin super administrator role. We can also use these methods to validate other permission controls in our application.

In my article “LoopBack3.0 API creation practice”, I configured the permission management in the official example cafe comment project, and realized the permission control according to the project requirements.

  • Comments can be read by anyone, but they must be logged in to create, edit or delete them.
  • Anyone can register as a user and be logged in or logged out.
  • Logged-in users can create new reviews and edit or delete their own, but they cannot modify content related to coffee shops.

We can verify this on the interface debug page.