loopback3 learning notes

Posted by techker on Tue, 26 Oct 2021 02:23:45 +0200

loopback3 has stopped, so if you are a beginner, go to loopback4

Why are you doing this? Because a project needs to be used, loopback is used more abroad than at home, but the open source code of the project in hand is based on loopback3. If you do it from scratch, it is not cost-effective in terms of time and cost, so you can only spend time doing it

loopback is the back-end restful API framework under the front-end and back-end separation architecture of the current web site. It is made by IBM and benchmarked with springboot. It is completely based on nodejs

1. Application directory structure
The LoopBack project files and directories are located in the application root directory. In this directory, the standard LoopBack project structure has the following subdirectories:

  • server - node application scripts and configuration files.
  • Client - client JavaScript, HTML, and CSS files (LoopBack tool only).
  • common - files shared by the client and server. The / models subdirectory contains model JSON and JavaScript files.
  • definitions- API and product definition YAML files

Reference section

2. Create application

lb

He will ask you a lot of questions, automatically create directories and configuration files, and then the generator will display messages when building the application, including:

  • Initialize the project folder structure.
  • Create a default JSON file.
  • Create a default JavaScript file.
  • Download and install the dependent Node module (just like npm install you completed manually)

3. Create data source

lb datasource

4. Create model

 lb model

It is the mapping and corresponding functions of database tables
After creation, you will find two more files in the common - > models directory
XXXX.js
XXXX.json
json corresponds to your table structure, and js corresponds to your external rest API

5. Extended API, remote method

There are two ways to register remote methods:

In the code, in the model extension file (modelName.js).
In JSON, in the model definition JSON file (modelName.json).

Suppose you have a Person model and you want to add a REST endpoint, / greet, which returns a greeting with the name provided in the request. You add this code to / common/models/person.js:

/common/models/person.js

module.exports = function(Person){

    Person.greet = function(msg, cb) {
      cb(null, 'Greetings... ' + msg);
    }

    Person.remoteMethod('greet', {
          accepts: {arg: 'msg', type: 'string'},
          returns: {arg: 'greeting', type: 'string'}
    });
};

Now, for example, request

POST /api/people/greet

With data {msg ":" John "} will return:

Greetings... John!

Change route

Person.remoteMethod('greet',{
  accepts: {arg: 'msg', type: 'string'},
  returns: {arg: 'greeting', type: 'string'},
  http: {path: '/sayhi', verb: 'get'}
});

This call changes the default route to

GET /api/people/sayhi

So a GET request http://localhost:3000/api/people/sayhi?msg=LoopBack%20developer return:

{"greeting": "Greetings... LoopBack developer"}

Note that the REST API request above uses the plural "people" instead of "person". LoopBack exposes plural model names for REST API routing.
By default, the REST APIs are mounted to the plural of the model name; specifically:
Automatically-pluralized model name (the default). For example, if you have a location model, by default it is mounted to /locations.

To put it bluntly, routes are automatically attached to routes in plural forms, rather than handwritten statements one by one
loopback inherits many things from Express by default, so we have to go back, otherwise we don't know

Reference section

6. Add ACL to remote method
To restrict access to custom remote methods, use the ACL generator in the same way you control access to any model API. The access type of the custom remote method is execution

 lb acl

Reference section

7. Remote hook

Remote hook enables you to perform a function before or after a remote method is called by the client:

beforeRemote() runs before the remote method.
After remote() runs after the remote method completes successfully.
afterRemoteError() runs after the remote method completes with an error

modelName.beforeRemote( methodName, function( ctx, modelInstance, next) {
    //...
    next();
});

wildcard
You can use the following wildcard methodName in:

The asterisk '' matches any character until the first occurrence of the separator '.' (period).
The double asterisk matches any character, including the separator '. (period).
For example, used to match any static method with '.'; Method used to match any instance of 'prototype.'.

The following example uses wildcards in remote method names. This remote hook is called whenever any remote method whose name ends with "save" is executed:

Generic / model / customer.js

Customer.beforeRemote('*.save', function(ctx, unused, next) {
  if(ctx.req.accessToken) {
    next();
  } else {
    next(new Error('must be logged in to update'))
  }
});

Customer.afterRemote('*.save', function(ctx, user, next) {
  console.log('user has been saved', user);
  next();
});

8. Oauth2.0 components

The LoopBack OAuth 2.0 component has the following key elements:

Authorization server: issue an access token to the client after successfully verifying the resource owner and obtaining authorization. This component implements OAuth 2.0 protocol endpoint, including authorization endpoint and token endpoint.

Resource server: it hosts protected resources and can accept and respond to protected resource requests using access tokens. This component provides middleware to protect API endpoints so that only requests with valid OAuth 2.0 access tokens are accepted. It also establishes identities such as client application ID and user ID for further access control and personalization.

We have a special authorization server, so we focus on the use of resource server
Third-party login using Passport

Reference link
The module includes:

  • UserIdentity model - tracking third-party login profiles
  • UserCredential model - stores credentials from third-party providers to represent user rights and authorization
  • ApplicationCredential model - stores the credentials associated with the client application
  • Passport configurator - bridge between loopback and passport

As usual, install the third-party login (Passport) component for the Node package:

$ npm install loopback-component-passport

The official examples are google and twitter, which are supported by the module package. What we need to access is our own single sign on authentication, which is not applicable, so we need to write it ourselves
Add the following code to server.js:

var passport = require("passport"); 
var OAuth2Strategy = require("passport-oauth2").Strategy; 
 
app.use(session({ 
  resave: false,  
  saveUninitialized: true,  
  secret: "SECRET", 
}));  

app.use(passport.initialize()); 
app.use(passport.session());  

passport.serializeUser(function(user, cb) {
  cb(null, user); 
});  

passport.deserializeUser(function(obj, cb) {
  cb(null, obj); 
}); 

require("https").globalAgent.options.rejectUnauthorized = false; 

passport.use( 
  new OAuth2Strategy(
    {  
    authorizationURL: "https://xxxxxx/oauth2/authorize",  
    tokenURL: "https://xxxxxx/oauth2/token",  
    clientID: "48144",  
    clientSecret: "rQxxxxxxfiaNrS742xR3Q2pYqInyvK",  
    callbackURL: "http://localhost:3000/auth/oauth2/callback",  
    proxy: true,  
    },  
    function(accessToken, refreshToken, params, profile, cb) {      
       console.log(params);  //Generally, the user data is obtained from the profile, but the problem here may be that our single sign on does not use the profile, which makes the data unavailable, so we use params to obtain it
       return cb(null, profile);  
    }
  )
);  

app.get("/auth/oauth2",  
  passport.authenticate("oauth2"));  

app.get("/auth/oauth2/callback",  
  passport.authenticate("oauth2", { failureRedirect: "/" }),  
  function(req, res) { 
  res.send("Login efetuado com sucesso!");  
  }
);

After running, you can see the successful return "Login efetuado com sucesso!" in the interface, you can see all the output user parameters in the console, and then get the segmentation yourself.

Topics: node.js