Code Monkey home page Code Monkey logo

loopback4-starter's Introduction

loopback4-starter

LoopBack

Dependencies Status Loopback Core Version Loopback Build Version License

This is a LoopBack 4 starter application to get you upto speed with initial setup of a very standard REST API application with LoopBack 4 as framework. It provides you with all the core requisite features for most of the applications over and above framework features, viz.,

  1. Users
  2. Authentication
  3. Authorization
  4. Environment configs
  5. Audit logs
  6. DB upgrade, migration and versioning

In addition to that, it also provides you with some of the good to have items

  1. Multi-tenant architecture system
  2. Soft deletes

NOTE: For a non multi-tenant starter, please refer to the branch single_tenant.

Table of Contents

How to use

Please follow below guidelines to use this starter app to create a fresh LB4 application.

Do remember that this is just one of the way to use it. You can always build your own LB4 application using LB4 CLI as mentioned here. Then, you can just cherry-pick what you need from here. Clone this repo in separate directory, then copy-paste. :)

Clone the repository

git clone https://github.com/sourcefuse/loopback4-starter.git

Install dependencies

npm i

Update app name

Say the application you are developing is named 'To Do List'. Change as below.

  • Rename the directory to to-do-list.
  • package.json and package-lock.json - Replace loopback4-starter with to-do-list in entire file. Update description.
  • public/index.html - Update title tag and h1 tag inside body as per your app name.
  • src/application.ts - Rename class to ToDoListApplication and all its references. If you are using VSCode, select the class name, press F2 and then rename it. This will update all its references as well.
  • src/index.ts - Replace all refences of Loopback4StarterApplication with ToDoListApplication.
  • src/__tests__/** - Replace all refences of Loopback4StarterApplication with ToDoListApplication.
  • Update README.md with details of your application
  • Update CONTRIBUTING.md with details as per your application.

Update git origin

git remote set-url origin https://github.com/USERNAME/REPOSITORY.git

Setup database

Database supported in this starter project is postgresql. But you can use any other SQL database. You will need to replace loopback-connector-postgresql in dependencies with your required connector. If you are using postgresql, follow as below. Setup a postgresql instance. Create a database named todolist. DB Schema will be setup automatically via our aplication later.

We are using DbSchema in this starter project to design our ERD for database. You can replace lbstarter.dbs with your own schema file.

Setup redis

This starter project uses redis as key value db for keeping revoked tokens (logout). Setup a redis instance. Follow the quick start guide here.

Configure environment

You need to configure your environment variables now. Copy .env.example and rename as .env. Now provide values for the keys mentioned there. These are going to be database credentials (created here) and redis credentials (created here). You don't need to provide all the keys though. For some of these (not needed to be secure keys), we have already specified default values in .env.defaults. You can remove them. You will require to fill at least these ones.

DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=********
DB_DATABASE=todolist
DB_SCHEMA=todolist
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_URL=
REDIS_PASSWORD=
REDIS_DATABASE=0

Run DB migrations

In this project, we are using db-migrate for db migrations, upgrades and versioning.

LoopBack4 also provides auto migration from models to DB but considering that its not guaranteed to be safe as mentioned here, we prefer to keep DB stuff outside of the ORM layer. This also helps in abstracting our models in codebase from DB tables. If you are good with LB4 way, please ignore below.

Replace all occurences of 'lbstarter' with 'todolist' in ./migrations folder. Run the below command to setup the database schema and tables with initial seed data.

npm run db:migrate

The above will setup the database as per the diagram here. It will also add a default first super admin user. Details for that is as follows

username=super_admin
password=test123!@#

Start server

Start the node server as below.

npm start

In a browser, visit http://127.0.0.1:3000/ping

API Explorer

In a browser, visit http://localhost:3000. Click on explorer. You will see the API documentation.

You can try out only the unsecured APIs here, like auth/login. The secure endpoints require bearer token as authorization header which is currently not possible to pass from this page. For that, you can use Postman.

Architecture overview

Database Model

db-schema

Key Notes
  • Database used is Postgresql version 10 and above.
  • Database schema is based on multi-tenant architecture overall.
  • Each table have default columns - id (Primary Key), created_by, modified_by, created_on, modified_on, deleted.
Multi-tenant system
  • Tenants are the organisational entities using the application.
  • Tenant types - Customer, Application (Umbrella Tenant for super admin work).
  • Every user will need be associated to a tenant in order to access the application.
  • User tenant has a m:n relationship, user_tenants table is the link table for the same.
  • Every user will have a role associated for every tenant it belongs to, role_id in user_tenants table.
  • Every role has associated permissions.
  • Each user may have some extra permissions (allowed or denied) per tenant over and above its role, user_tenant_permissions table takes care of it.

For detailed description of database tables and columns, please open lbstarter.dbs in DbSchema tool.

Authentication

This starter project uses loopback4-authentication package for authentication purposes.

If you only want to use authentication, not the whole starter codebase, you can use the package directly in you application. Refer loopback4-authentication documentation for more details.

There are two different strategies of authentication used here.

  • Oauth2 client password + Passport local - This is a 2-step auth process

    1. Client need to send client credentials (client id and client public key) and user credentials (username and password) to '/auth/login' API. After successful verification, it will return a jwt code containing client details, signed using client's private key (secret) stored in DB. Expiration time of code will be based on value in DB against that auth client.
    2. Next, client will need to send this code along with client id and username to '/auth/token' API. After successful verification, it will return access token (jwt containing user details) and refresh token. Expiration time of token will be based on value in DB against that auth client.

    The front end application will be mostly using this strategy.

  • Oauth2 resource owner password - This is a single step process where in client need to send client credentials (client id and client public key) and user credentials (username and password) to '/auth/login-token' API. In this case, in addition to verifying client credentials and user password, system will also check if the user has permission to access APIs via this auth client. Only those auth clients which have associated userids can use this API for authentication.

    Any 3rd party application accessing your APIs will be using this strategy, like from AWS Lambda function.

Once access token is obtained, it is needed to be passed into every API as Authorization bearer token header, which will be validated for access to API.

Authorization

This starter project uses loopback4-authorization package for authorization purposes.

If you only want to use authorization, not the whole starter codebase, you can use the package directly in you application. Refer loopback4-authorization documentation for more details.

Permissions are part of the access token generated. Authorization implementation is following the Role based permissions with user level override strategy here.

Soft Delete

This starter project uses loopback4-soft-delete package for authorization purposes.

Audit Logs

Audit logs are updated using DB triggers in this project. Refer to the lbstarter-schema.html for the details.

Feedback

If you've noticed a bug or have a question or have a feature request, search the issue tracker to see if someone else in the community has already created a ticket. If not, go ahead and make one! All feature requests are welcome. Implementation time may vary. Feel free to contribute the same, if you can. If you think this extension is useful, please star it. Appreciation really helps in keeping this project alive.

Contributing

Please read CONTRIBUTING.md for details on the process for submitting pull requests to us.

Code of conduct

Code of conduct guidelines here.

License

MIT

loopback4-starter's People

Contributors

akshatdubeysf avatar arpit1503khanna avatar asakapab0i avatar d-sooter avatar dependabot[bot] avatar duanvnc avatar ishusf avatar kjellouli avatar lauksas avatar mlakdawala avatar raghavarorasf avatar samarpan-b avatar sherif2011 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

loopback4-starter's Issues

credentials

Hello,

I couldn't find any controllers to set or reset user password. What's the best way to do that? I tried creating a controller using lb4/cli

? What kind of controller would you like to generate? REST Controller with CRUD functions
? What is the name of the model to use with this CRUD repository? UserCredentials
? What is the name of your CRUD repository? UserCredentialsRepository
? What is the type of your ID? number
? What is the base HTTP path name of the CRUD operations? /user-credentials
create src\controllers\credentials.controller.ts
update src\controllers\index.ts

Controller Credentials was created in src\controllers/

When I try accessing any of the end points I am getting
{
"error": {
"statusCode": 403,
"name": "ForbiddenError",
"message": "NotAllowedAccess"
}
}

Thanks!!

subscriber Role

why with subscriber Role, I can create any a new user or a new tenant? I just have an access token of the user who has a subscriber role and I can do any post request and i can do any change like super_admin while I'm subscriber?

my .env file included DEFAULT_ROLE=subscriber

Are there any configurations I missed?

CORS not operational

Describe the bug
In my env developement, my front-end use localhost:3000, et my loopback backend use localhost:3001.
Because front & end use different URL, the browser use CORS to check if the front is allow to request the backend.
The browser send OPTIONS request, and get a reply "403 Forbidden".

My FrontEnd can't authentify to the backend (@post('/auth/login') because of this behaviour.
I try to trace the request: i checked my login controller & sequence : but the request is blocked somewhere else.

To Reproduce

  • Install loopback4-starter, (default port:3000), use your frontend with a different port (eg: 3001). Try to authenticate on '/auth/login', get the CORS error

Expected behavior
With a correct ApplicationConfig (see below), CORS should be authorized for all requests & origin.

Screenshots
na

Additional context

My ApplicationConfig :
  const config: ApplicationConfig = {
    rest: {
      cors: {
        origin: '*',
        methods: 'OPTIONS, GET,HEAD,PUT,PATCH,POST,DELETE',
        preflightContinue: false,
        optionsSuccessStatus: 204,
        maxAge: 86400,
        credentials: true
      },
      port: +(process.env.PORT ?? 3001),
      host: process.env.HOST,
      gracePeriodForClose: 5000, // 5 seconds
      openApiSpec: {  setServersFromRequest: true   },
    },
  };

My login-controller:

@authenticateClient(STRATEGY.CLIENT_PASSWORD)
 @authenticate(STRATEGY.LOCAL)
 @authorize({ permissions: ['*'] })
 @post('/auth/login', {
   responses: {
     [STATUS_CODE.OK]: {
       description: 'Auth Code',
       content: {
         [CONTENT_TYPE.JSON]: Object,
       },
     },
   },
 })
 async login(
   @requestBody() req: LoginRequest,
 ): Promise<{ code: string; }> {


Two-factor authentication

Hello,
Any plan featuring two-factor authentication soon in lb? If not, any recommendations what are best npm packages to use for that purpose?
Thanks!

npm run migrate --rebuild does not work as expected

Describe the bug
Using the command "npm run migrate --rebuild ", the '--rebuild' arg is not passed to arguments list. The program is kept using ALTER mode.

To Reproduce
In command line, execute "npm run migrate --rebuild "
The utility write "Migrating schemas (alter existing schema)" instead of "Migrating schemas (drop existing schema)"

Expected behavior
The program should take into account the --rebuild flag

Additional context
A dump of args show the --rebuild is not present.

I have upgraded my migrate function with the code below.
However, I'm a new Loppback user, I think i saw it worked several month ago. I must have done something wrong somewhere :) (Note: I'm using npm version 7.6.2) .


export async function migrate(args: string[]) {
  console.log('=== Schema migration utility ===');
  console.log('Usage: npm run migrate [rebuild]');

  const existingSchema = args.includes('rebuild') ? 'drop' : 'alter';
  console.log('> Migrating schemas using %s mode', existingSchema.toUpperCase());

  console.log(" - Instanciating RESTApp...")
  const app = new RESTApp();
  console.log(" - Booting RESTApp...")
  await app.boot();
  console.log(" - Migrating schemas using %s mode...", existingSchema.toUpperCase())
  await app.migrateSchema({ existingSchema });
  console.log(" - Done. Exiting.")

  // Connectors usually keep a pool of opened connections,
  // this keeps the process running even after all work is done.
  // We need to exit explicitly.
  process.exit(0);
}

Unable to run repo

Describe the bug
If we follow the instructions on README to setup this project we get the following error when we try to authenticate:

{
  "error": {
    "statusCode": 401,
    "name": "UnauthorizedError",
    "message": {
      "name": "error",
      "length": 121,
      "severity": "ERROR",
      "code": "42P01",
      "position": "194",
      "file": "parse_relation.c",
      "line": "1159",
      "routine": "parserOpenTable"
    }
  }
}

I have successfully executed the migrations and redis server is up and running (tested with redis-cli). If we provide wrong credentials the output is the same. I tested both with Postman and with /explorer.

To Reproduce
Steps to reproduce the behavior:

  1. Follow the instructions on README to setup and run the project.
  2. Try to authenticate using the /auth/login endpoint
  3. See the error

Expected behavior
The user should be authenticated and a JWT token should be returned.

Screenshots
image

image

image

Am I doing something wrong?

Initial authorization

Not a bug, but just wondering why everything requires bearer authentication? How do you get the initial token then?

user_tenants

Hi! I just wondering how come there is no way to update the user_tenants table when a new user is added? Shouldn't it be updated with the addition of a user? Should we manually add a controller to do this or am I missing something? Because how would the program know what permissions the user has.

Login Problem

I'm testing and can't log in. But I don't know if I'm doing the right thing. as I read. I must first go to

auth/login

with these parameters

{
  "client_id": "webapp",
  "client_secret": "saqw21!@",
  "username": "super_admin",
  "password": "test123!@#"
}

and that returns this code to me.

{
"code": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRJZCI6IndlYmFwcCIsInVzZXJJZCI6MSwiaWF0IjoxNTg2OTU3MzMzLCJleHAiOjE1ODY5NTc1MTMsImF1ZCI6IndlYmFwcCIsImlzcyI6Im1mZ3FmIiwic3ViIjoic3VwZXJfYWRtaW4ifQ.wgHgBirDz1T9YW1pG133XGBwJRM7q61GsgfCRrpC4ws"
}

Then I must go to

auth/token

with these parameters

{
  "code": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnRJZCI6IndlYmFwcCIsInVzZXJJZCI6MSwiaWF0IjoxNTg2OTU3MzMzLCJleHAiOjE1ODY5NTc1MTMsImF1ZCI6IndlYmFwcCIsImlzcyI6Im1mZ3FmIiwic3ViIjoic3VwZXJfYWRtaW4ifQ.wgHgBirDz1T9YW1pG133XGBwJRM7q61GsgfCRrpC4ws",
  "clientId": "webapp",
  "username": "super_admin"
}

so that it gives me the true token but it returns a 401.

{
  "error": {
    "statusCode": 401,
    "name": "UnauthorizedError",
    "message": "Invalid Credentials"
  }
}

Can someone tell me what I'm doing wrong?
thank in advance @samarpanB

Question: Alternatives to Redis

I'm new to all this so bear with me.
Just wondering why this project uses Redis to store revoked tokens, instead of the main SQL database?
When implementing LB4 with auth for my apps I would prefer to only have to set up and manage one database, especially since I am completely unfamiliar with Redis.
Has anyone implemented this project, or something similar, without Redis? How did you do it?

Thanks!

How to refresh explorer?

Hello @samarpan-b ,

I am having troubles refreshing API explorer after making some changes to controllers. Some times I totally drop a controller, save and run, and still see end points there in API explorer. How can I refresh explorer?

I tried npm run clean then npm run build but that didn't help. Actually if I do that I lose all files in dist folder except for readme files and get the following error:
Error: Cannot find module './dist'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object. (C:\Users\smankarious\Desktop\admin\index.js:1:21)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)

Any clue please?

For your reference, if needed here is my package.json file.

package_json.txt

Request support for Mongodb

Is your feature request related to a problem? Please describe.
Would it possible for you to add support for Mongodb?

DB unable to migrate any script

Describe the bug
pgdb unable to migrate the database structure

To Reproduce
Steps to reproduce the behavior:

  1. Create .env file with info:
NODE_ENV=production
LOG_LEVEL=info
DB_HOST=localhost
DB_PORT=5432
DB_USER=root
DB_PASSWORD=root
DB_DATABASE=lbstarter
DB_SCHEMA=
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_URL=
REDIS_PASSWORD=
REDIS_DATABASE=0
JWT_SECRET=plmnkoxswqaz
JWT_ISSUER=lb_api
AUDIT_SCHEMA=logs
USER_TEMP_PASSWORD=temp123!@#
DEFAULT_ROLE=super_admin
  1. PostgresSQL and Redis are connected already.
  2. Run 3 commands to setup project:
  • npm install
  • npm run build
  • npm run db:migrate
  1. No error message found.
➜  loopback4-starter git:(master) ✗ npm run db:migrate

> [email protected] db:migrate /Users/myaccount/loopback4-starter
> ./node_modules/db-migrate/bin/db-migrate up --config './migrations/database.json'

Expected behavior
The Postgres databases: lbstarter and logs structures should be seen on PostgresSQL database

Screenshots

PostgresDB photo: https://prnt.sc/tlmyv8

A single connection pool

Does this starter boilerplate support a single connection pool per app?
I don't want to create a connection pool per tenant (just want a single connection pool for multi-tenant)
In PostgreSQL usually we use a schema per tenant which means the app uses a single database with multi schemas.

Help with tenant-aware operations

Hi,

Thank you for providing this awesome boilerplate!
Can you please help me with some samples on how to apply some tenant awareness.
For example how to get all users that are part of my current user tenant, because /users returns all existing users in all tenants?
I'm new to Loopback and I don't know if it is correct to bind the tenant in the repository and filter there or there is some different approach.

bringup fails due to package dependencies

It looks like you need to update your package.json file which is currently pointing to the following dependencies

"loopback4-authentication": "file:../lb4-authentication",
"loopback4-authorization": "file:../lb4-authorization",

It looks like these files are not downloaded as part of git clone, running "npm start" results in failure.

see below log
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

[email protected] prestart /home/vagrant/tryout/loopback4-starter
npm run build
[email protected] build /home/vagrant/tryout/loopback4-starter
lb-tsc es2017 --outDir dist
src/application.ts:15:8 - error TS2307: Cannot find module 'loopback4-authentication'.
15 } from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/application.ts:16:38 - error TS2307: Cannot find module 'loopback4-authorization'.
16 import {AuthorizationComponent} from 'loopback4-authorization';
~~~~~~~~~~~~~~~~~~~~~~~~~
src/controllers/home-page.controller.ts:7:25 - error TS2307: Cannot find module 'loopback4-authorization'.
7 import {authorize} from 'loopback4-authorization';
~~~~~~~~~~~~~~~~~~~~~~~~~
src/controllers/ping.controller.ts:3:25 - error TS2307: Cannot find module 'loopback4-authorization'.
3 import {authorize} from 'loopback4-authorization';
~~~~~~~~~~~~~~~~~~~~~~~~~
src/models/auth-client.model.ts:2:27 - error TS2307: Cannot find module 'loopback4-authentication'.
2 import {IAuthClient} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/models/user-tenant-permission.model.ts:5:30 - error TS2307: Cannot find module 'loopback4-authorization'.
5 import {UserPermission} from 'loopback4-authorization';
~~~~~~~~~~~~~~~~~~~~~~~~~
src/models/user.model.ts:2:25 - error TS2307: Cannot find module 'loopback4-authentication'.
2 import {IAuthUser} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/audit/audit-log.controller.ts:21:38 - error TS2307: Cannot find module 'loopback4-authentication'.
21 import {authenticate, STRATEGY} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/audit/audit-log.controller.ts:22:25 - error TS2307: Cannot find module 'loopback4-authorization'.
22 import {authorize} from 'loopback4-authorization';
~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/auth/login.controller.ts:13:8 - error TS2307: Cannot find module 'loopback4-authentication'.
13 } from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/auth/login.controller.ts:18:8 - error TS2307: Cannot find module 'loopback4-authorization'.
18 } from 'loopback4-authorization';
~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/auth/logout.controller.ts:4:53 - error TS2307: Cannot find module 'loopback4-authentication'.
4 import {authenticate, AuthErrorKeys, STRATEGY} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/auth/logout.controller.ts:5:25 - error TS2307: Cannot find module 'loopback4-authorization'.
5 import {authorize} from 'loopback4-authorization';
~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/auth/providers/bearer-token-verify.provider.ts:5:30 - error TS2307: Cannot find module 'loopback4-authentication'.
5 import {VerifyFunction} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/auth/providers/bearer-token-verify.provider.ts:20:18 - error TS7006: Parameter 'token' implicitly has an 'any' type.
20 return async token => {
~~~~~
src/modules/auth/providers/client-password-verify.provider.ts:3:30 - error TS2307: Cannot find module 'loopback4-authentication'.
3 import {VerifyFunction} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/auth/providers/client-password-verify.provider.ts:15:19 - error TS7006: Parameter 'clientId' implicitly has an 'any' type.
15 return async (clientId, clientSecret) => {
~~~~~~~~
src/modules/auth/providers/client-password-verify.provider.ts:15:29 - error TS7006: Parameter 'clientSecret' implicitly has an 'any' type.
15 return async (clientId, clientSecret) => {
~~~~~~~~~~~~
src/modules/auth/providers/local-password-verify.provider.ts:3:30 - error TS2307: Cannot find module 'loopback4-authentication'.
3 import {VerifyFunction} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/auth/providers/local-password-verify.provider.ts:17:19 - error TS7006: Parameter 'username' implicitly has an 'any' type.
17 return async (username, password) => {
~~~~~~~~
src/modules/auth/providers/local-password-verify.provider.ts:17:29 - error TS7006: Parameter 'password' implicitly has an 'any' type.
17 return async (username, password) => {
~~~~~~~~
src/modules/auth/providers/resource-owner-verify.provider.ts:3:45 - error TS2307: Cannot find module 'loopback4-authentication'.
3 import {VerifyFunction, AuthErrorKeys} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/auth/providers/resource-owner-verify.provider.ts:18:19 - error TS7006: Parameter 'clientId' implicitly has an 'any' type.
18 return async (clientId, clientSecret, username, password) => {
~~~~~~~~
src/modules/auth/providers/resource-owner-verify.provider.ts:18:29 - error TS7006: Parameter 'clientSecret' implicitly has an 'any' type.
18 return async (clientId, clientSecret, username, password) => {
~~~~~~~~~~~~
src/modules/auth/providers/resource-owner-verify.provider.ts:18:43 - error TS7006: Parameter 'username' implicitly has an 'any' type.
18 return async (clientId, clientSecret, username, password) => {
~~~~~~~~
src/modules/auth/providers/resource-owner-verify.provider.ts:18:53 - error TS7006: Parameter 'password' implicitly has an 'any' type.
18 return async (clientId, clientSecret, username, password) => {
~~~~~~~~
src/modules/roles/role.controller.ts:19:38 - error TS2307: Cannot find module 'loopback4-authentication'.
19 import {authenticate, STRATEGY} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/roles/role.controller.ts:20:25 - error TS2307: Cannot find module 'loopback4-authorization'.
20 import {authorize} from 'loopback4-authorization';
~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/user-tenants/tenant.controller.ts:19:38 - error TS2307: Cannot find module 'loopback4-authentication'.
19 import {authenticate, STRATEGY} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/user-tenants/tenant.controller.ts:20:25 - error TS2307: Cannot find module 'loopback4-authorization'.
20 import {authorize} from 'loopback4-authorization';
~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/user-tenants/user.controller.ts:19:38 - error TS2307: Cannot find module 'loopback4-authentication'.
19 import {authenticate, STRATEGY} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/user-tenants/user.controller.ts:20:25 - error TS2307: Cannot find module 'loopback4-authorization'.
20 import {authorize} from 'loopback4-authorization';
~~~~~~~~~~~~~~~~~~~~~~~~~
src/repositories/default-user-modify-crud.repository.base.ts:9:29 - error TS2307: Cannot find module 'loopback4-authentication'.
9 import {AuthErrorKeys} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/repositories/tenant.repository.ts:2:38 - error TS2307: Cannot find module 'loopback4-authentication'.
2 import {AuthenticationBindings} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/repositories/user-tenant-permission.repository.ts:3:38 - error TS2307: Cannot find module 'loopback4-authentication'.
3 import {AuthenticationBindings} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/repositories/user.repository.ts:6:53 - error TS2307: Cannot find module 'loopback4-authentication'.
6 import {AuthenticationBindings, AuthErrorKeys} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/sequence.ts:13:54 - error TS2307: Cannot find module 'loopback4-authentication'.
13 import {AuthenticateFn, AuthenticationBindings} from 'loopback4-authentication';
~~~~~~~~~~~~~~~~~~~~~~~~~~
src/sequence.ts:18:8 - error TS2307: Cannot find module 'loopback4-authorization'.
18 } from 'loopback4-authorization';
~~~~~~~~~~~~~~~~~~~~~~~~~
Found 38 errors.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] build: lb-tsc es2017 --outDir dist
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/vagrant/.npm/_logs/2019-05-16T19_33_12_329Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] prestart: npm run build
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] prestart script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/vagrant/.npm/_logs/2019-05-16T19_33_12_348Z-debug.log
vagrant:/tryout/loopback4-starter$ vi package.json
vagrant:
/tryout/loopback4-starter$ npm i --save @loopback-authorization @loopback-authentication
npm ERR! code EINVALIDTAGNAME
npm ERR! Invalid tag name "@loopback-authorization": Tags may not have any characters that encodeURIComponent encodes.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/vagrant/.npm/_logs/2019-05-16T19_34_53_682Z-debug.log

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

I even tried the following

downloaded loopback4-authentication + loopback4-authorization repos from your repo, edited the package.json entries from

../lb4-xxxx to ../loopback-xxxx

ran npm -i
ran npm start which results in the following errors.

vagrant:~/tryout/sourcefuse/loopback4-starter$ npm i
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

[email protected] install /home/vagrant/tryout/sourcefuse/loopback4-starter/node_modules/bcrypt
node-pre-gyp install --fallback-to-build

node-pre-gyp WARN Using needle for node-pre-gyp https download
[bcrypt] Success: "/home/vagrant/tryout/sourcefuse/loopback4-starter/node_modules/bcrypt/lib/binding/bcrypt_lib.node" is installed via remote
added 914 packages from 1542 contributors and audited 6473 packages in 29.392s
found 3 vulnerabilities (1 low, 2 moderate)
run npm audit fix to fix them, or npm audit for details
vagrant:~/tryout/sourcefuse/loopback4-starter$ npm start
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

[email protected] prestart /home/vagrant/tryout/sourcefuse/loopback4-starter
npm run build
[email protected] build /home/vagrant/tryout/sourcefuse/loopback4-starter
lb-tsc es2017 --outDir dist
../loopback4-authentication/src/strategies/client-auth-strategy.provider.ts:7:8 - error TS7016: Could not find a declaration file for module 'passport-oauth2-client-password'. '/home/vagrant/tryout/sourcefuse/loopback4-authentication/node_modules/passport-oauth2-client-password/lib/index.js' implicitly has an 'any' type.
Try npm install @types/passport-oauth2-client-password if it exists or add a new declaration (.d.ts) file containing declare module 'passport-oauth2-client-password';

7 } from 'passport-oauth2-client-password';
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../loopback4-authentication/src/strategies/user-auth-strategy.provider.ts:4:33 - error TS7016: Could not find a declaration file for module 'passport-http-bearer'. '/home/vagrant/tryout/sourcefuse/loopback4-authentication/node_modules/passport-http-bearer/lib/index.js' implicitly has an 'any' type.
Try npm install @types/passport-http-bearer if it exists or add a new declaration (.d.ts) file containing declare module 'passport-http-bearer';

4 import * as PassportBearer from 'passport-http-bearer';
~~~~~~~~~~~~~~~~~~~~~~
../loopback4-authentication/src/strategies/user-auth-strategy.provider.ts:5:32 - error TS7016: Could not find a declaration file for module 'passport-local'. '/home/vagrant/tryout/sourcefuse/loopback4-authentication/node_modules/passport-local/lib/index.js' implicitly has an 'any' type.
Try npm install @types/passport-local if it exists or add a new declaration (.d.ts) file containing declare module 'passport-local';

5 import * as PassportLocal from 'passport-local';
~~~~~~~~~~~~~~~~
../loopback4-authorization/src/providers/authorization-action.provider.ts:6:28 - error TS7016: Could not find a declaration file for module 'lodash'. '/home/vagrant/tryout/sourcefuse/loopback4-authorization/node_modules/lodash/lodash.js' implicitly has an 'any' type.
If the 'lodash' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/lodash`

6 import {intersection} from 'lodash';
~~~~~~~~
Found 4 errors.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] build: lb-tsc es2017 --outDir dist
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/vagrant/.npm/_logs/2019-05-16T19_51_42_092Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] prestart: npm run build
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] prestart script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/vagrant/.npm/_logs/2019-05-16T19_51_42_110Z-debug.log

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

I was able to address the above errors by doing an "npm i" within the loopback-authentication and loopback-authoriziation folders.

but when I try to run the code using "npm start" or "node ." I get the following error.

vagrant@arigapcloud:~/tryout/sourcefuse/loopback4-starter$ node .
internal/modules/cjs/loader.js:584
throw err;
^

Error: Cannot find module './dist'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
at Function.Module._load (internal/modules/cjs/loader.js:508:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object. (/home/vagrant/tryout/sourcefuse/loopback4-authentication/index.js:1:80)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object. (/home/vagrant/tryout/sourcefuse/loopback4-starter/dist/application.js:10:36)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
vagrant:~/tryout/sourcefuse/loopback4-starter$ npm start

[email protected] prestart /home/vagrant/tryout/sourcefuse/loopback4-starter
npm run build

[email protected] build /home/vagrant/tryout/sourcefuse/loopback4-starter
lb-tsc es2017 --outDir dist

[email protected] start /home/vagrant/tryout/sourcefuse/loopback4-starter
node .

internal/modules/cjs/loader.js:584
throw err;
^

Error: Cannot find module './dist'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
at Function.Module._load (internal/modules/cjs/loader.js:508:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object. (/home/vagrant/tryout/sourcefuse/loopback4-authentication/index.js:1:80)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object. (/home/vagrant/tryout/sourcefuse/loopback4-starter/dist/application.js:10:36)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: node .
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/vagrant/.npm/_logs/2019-05-17T01_06_34_518Z-debug.log
vagrant@~/tryout/sourcefuse/loopback4-starter$

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

below si the logfile

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'start' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle [email protected]prestart: [email protected]
6 verbose lifecycle [email protected]
prestart: unsafe-perm in lifecycle true
7 verbose lifecycle [email protected]prestart: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/vagrant/tryout/sourcefuse/loopback4-starter/node_modules/.bin:/home/vagrant/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin
8 verbose lifecycle [email protected]
prestart: CWD: /home/vagrant/tryout/sourcefuse/loopback4-starter
9 silly lifecycle [email protected]prestart: Args: [ '-c', 'npm run build' ]
10 silly lifecycle [email protected]
prestart: Returned: code: 0 signal: null
11 info lifecycle [email protected]start: [email protected]
12 verbose lifecycle [email protected]
start: unsafe-perm in lifecycle true
13 verbose lifecycle [email protected]start: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/vagrant/tryout/sourcefuse/loopback4-starter/node_modules/.bin:/home/vagrant/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin
14 verbose lifecycle [email protected]
start: CWD: /home/vagrant/tryout/sourcefuse/loopback4-starter
15 silly lifecycle [email protected]start: Args: [ '-c', 'node .' ]
16 silly lifecycle [email protected]
start: Returned: code: 1 signal: null
17 info lifecycle [email protected]~start: Failed to exec start script
18 verbose stack Error: [email protected] start: node .
18 verbose stack Exit status 1
18 verbose stack at EventEmitter. (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
18 verbose stack at EventEmitter.emit (events.js:189:13)
18 verbose stack at ChildProcess. (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
18 verbose stack at ChildProcess.emit (events.js:189:13)
18 verbose stack at maybeClose (internal/child_process.js:970:16)
18 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
19 verbose pkgid [email protected]
20 verbose cwd /home/vagrant/tryout/sourcefuse/loopback4-starter
21 verbose Linux 4.15.0-47-generic
22 verbose argv "/usr/bin/node" "/usr/bin/npm" "start"
23 verbose node v10.15.3
24 verbose npm v6.4.1
25 error code ELIFECYCLE
26 error errno 1
27 error [email protected] start: node .
27 error Exit status 1
28 error Failed at the [email protected] start script.
28 error This is probably not a problem with npm. There is likely additional logging output above.
29 verbose exit [ 1, true ]
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Cannot Access Postgres when application is containerized

This is more of a question than a bug.

Here is my repository: https://github.com/sherif2011/docker-admin/

I am trying to containerize (through docker) my application.
You can start application by running "./admin.sh run"
This will spin up containers for Admin (application), Redis and Postgres.
If you try running http://127.0.0.1/explorer an the following error will appear:

Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14)
Emitted 'error' event at:
at PgdbDataSource.postInit (/home/node/app/node_modules/@loopback/repository/node_modules/loopback-datasource-juggler/lib/datasource.js:486:16)
at PendingItem.callback (/home/node/app/node_modules/loopback-connector-postgresql/lib/postgresql.js:103:17)
at client.connect (/home/node/app/node_modules/pg-pool/index.js:248:23)
at Connection.connectingErrorHandler (/home/node/app/node_modules/pg/lib/client.js:163:14)
at Connection.emit (events.js:198:13)
at Socket.reportStreamError (/home/node/app/node_modules/pg/lib/connection.js:71:10)
at Socket.emit (events.js:198:13)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19)

If I stop admin container, and nom run start, application will run fine and will be able to access Postgres.

Meaning that only when the main application (Admin) is containerized, that it's not able to access Postgres.

Can you provide assistance on this one? Am I doing something wrong?

Again here is my repository: https://github.com/sherif2011/docker-admin/

lb4 not work before last update

@samarpanB

lb4 rest-crud

(node:4884) UnhandledPromiseRejectionWarning: Error: Cannot load /home/fvicente/Proyectos/loopback4apps/new/marqfapp/src/datasources/auditdb.datasource.config.json: ENOENT: no such file or directory, open '/home/fvicente/Proyectos/loopback4apps/new/marqfapp/src/datasources/auditdb.datasource.config.json'
at Object.openSync (fs.js:457:3)
at Object.readFileSync (fs.js:359:35)
at Object.exports.isConnectorOfType (/home/fvicente/.nvm/versions/node/v12.16.1/lib/node_modules/@loopback/cli/lib/utils.js:608:37)
at /home/fvicente/.nvm/versions/node/v12.16.1/lib/node_modules/@loopback/cli/generators/rest-crud/index.js:163:28
at Array.filter ()
at RestCrudGenerator.promptDataSourceName (/home/fvicente/.nvm/versions/node/v12.16.1/lib/node_modules/@loopback/cli/generators/rest-crud/index.js:161:50)
(node:4884) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:4884) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

lb4 repository

(node:5049) UnhandledPromiseRejectionWarning: Error: Cannot load /home/fvicente/Proyectos/loopback4apps/new/marqfapp/src/datasources/auditdb.datasource.config.json: ENOENT: no such file or directory, open '/home/fvicente/Proyectos/loopback4apps/new/marqfapp/src/datasources/auditdb.datasource.config.json'
at Object.openSync (fs.js:457:3)
at Object.readFileSync (fs.js:359:35)
at Object.exports.isConnectorOfType (/home/fvicente/.nvm/versions/node/v12.16.1/lib/node_modules/@loopback/cli/lib/utils.js:608:37)
at /home/fvicente/.nvm/versions/node/v12.16.1/lib/node_modules/@loopback/cli/generators/repository/index.js:262:28
at Array.filter ()
at RepositoryGenerator.promptDataSourceName (/home/fvicente/.nvm/versions/node/v12.16.1/lib/node_modules/@loopback/cli/generators/repository/index.js:260:50)
(node:5049) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:5049) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

lb4 discover
? Seleccione el conector que se va a descubrir (Use arrow keys)
❯ auditdb
pgdb
redis La conexión falla: error: no existe el rol «fvicente»
Se reintentará en la siguiente solicitud.

events.js:288
throw er; // Unhandled 'error' event
^

error: no existe el rol «fvicente»
at Connection.parseE (/home/fvicente/Proyectos/loopback4apps/new/marqfapp/node_modules/loopback-connector-postgresql/node_modules/pg/lib/connection.js:581:48)
at Connection.parseMessage (/home/fvicente/Proyectos/loopback4apps/new/marqfapp/node_modules/loopback-connector-postgresql/node_modules/pg/lib/connection.js:380:19)
at Socket. (/home/fvicente/Proyectos/loopback4apps/new/marqfapp/node_modules/loopback-connector-postgresql/node_modules/pg/lib/connection.js:116:22)
at Socket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
at readableAddChunk (_stream_readable.js:275:11)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
Emitted 'error' event on AuditdbDataSource instance at:
at AuditdbDataSource.postInit (/home/fvicente/Proyectos/loopback4apps/new/marqfapp/node_modules/loopback-datasource-juggler/lib/datasource.js:502:16)
at PendingItem.callback (/home/fvicente/Proyectos/loopback4apps/new/marqfapp/node_modules/loopback-connector-postgresql/lib/postgresql.js:102:17)
at /home/fvicente/Proyectos/loopback4apps/new/marqfapp/node_modules/loopback-connector-postgresql/node_modules/pg-pool/index.js:237:23
at Connection.connectingErrorHandler (/home/fvicente/Proyectos/loopback4apps/new/marqfapp/node_modules/loopback-connector-postgresql/node_modules/pg/lib/client.js:216:14)
at Connection.emit (events.js:311:20)
at Socket. (/home/fvicente/Proyectos/loopback4apps/new/marqfapp/node_modules/loopback-connector-postgresql/node_modules/pg/lib/connection.js:121:12)
at Socket.emit (events.js:311:20)
[... lines matching original stack trace ...]
at TCP.onStreamRead (internal/stream_base_commons.js:186:23) {
name: 'error',
length: 99,
severity: 'FATAL',
code: '28000',
detail: undefined,
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'miscinit.c',
line: '607',
routine: 'InitializeSessionUserId'
}

DefaultUserModifyCrudRepository not setting properly created_by

DefaultUserModifyCrudRepository gets CurrentUser.id and pass it to entity.createdBy.
I've migrated the project to use uuid isntead of id and noticed that currentUser.id returns the user id but not the user_tenant id.
And when creating the tables in the migrations we have relation between created_by and user_tenants id, then I'm having constraint fail.

I've added userTenantId in the AuthUser model but I'm not sure if I'm wrong or there is really a bug?

Any help is appreciated, thanks!

UnauthorizedError !

Whenever I call /auth/login-token or /auth/login I get the following response:
Request:

{
  "client_id": "webapp",
  "client_secret": "saqw21!@",
  "username": "super_admin",
  "password": "test123!@#"
}

Response:

{
  "error": {
    "statusCode": 401,
    "name": "UnauthorizedError",
    "message": {}
  }
}

.env:

NODE_ENV=production
LOG_LEVEL=info
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=123654789
DB_DATABASE=todolist
DB_SCHEMA=lbstarter
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_URL=
REDIS_PASSWORD=
REDIS_DATABASE=0
JWT_SECRET=plmnkoxswqaz
JWT_ISSUER=lb_api
AUDIT_SCHEMA=logs
USER_TEMP_PASSWORD=temp123!@#
GOOGLE_AUTH_URL=
GOOGLE_AUTH_CLIENT_ID=
GOOGLE_AUTH_CLIENT_SECRET=
GOOGLE_AUTH_TOKEN_URL=
GOOGLE_AUTH_CALLBACK_URL=
DEFAULT_ROLE=super_admin

DB structure:
image
More info:

$ npm ls --prod --depth 0 | grep loopback
[email protected] /home/laptop/loopback4-starter
├── @loopback/[email protected]
├── @loopback/[email protected]
├── @loopback/[email protected]
├── @loopback/[email protected]
├── @loopback/[email protected]
├── @loopback/[email protected]
├── @loopback/[email protected]
├── @loopback/[email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
$

NOTE: I tried to use both options JWT_SECRET=plmnkoxswqaz & JWT_SECRET=plmnkoqazxsw, but I always get the same result.

usage of .env file in README conflicts with application.ts

Describe the bug
application.ts points to schema ".env.example" while README suggests renaming ".env.example" to ".env"

dotenv.config();
dotenvExt.load({
schema: '.env.example',
errorOnMissing: false,
});

Expected behavior
Application.ts file not in sync with steps outlined in README

Configure environment
You need to configure your environment variables now. Copy .env.example and rename as .env. Now provide values for the keys mentioned there. These are going to be database credentials (created here) and redis credentials (created here). You don't need to provide all the keys though. For some of these (not needed to be secure keys), we have already specified default values in .env.defaults. You can remove them. You will require to fill at least these ones.

It might help to put a console.log statement that prints some of the values.

Thanks

type missing in tenant model

Describe the bug
type property is missing in tenant.model.ts but is there in db schema. Its a required parameter.

Expected behavior
type property should be there in tenant.model.ts with string type.

Screenshots
None needed.

Additional context
This will cause tenant creation to fail.
Raised here.

lb4 discover not work

im add many tables and discover not work

lb4 discover

El proyecto lo generó originalmente @loopback/cli@.
Las dependencias siguientes son incompatibles con @loopback/[email protected]:
dependencies

  • @loopback/boot: ^1.4.4 (cli ^3.0.2)
  • @loopback/context: ^1.20.2 (cli ^3.12.0)
  • @loopback/core: ^1.8.5 (cli ^2.11.0)
  • @loopback/openapi-v3: ^1.7.0 (cli ^5.0.0)
  • @loopback/repository: ^1.8.2 (cli ^3.1.0)
  • @loopback/rest: ^1.16.3 (cli ^8.0.0)
  • @loopback/service-proxy: ^1.2.3 (cli ^3.0.2)
  • @loopback/rest-explorer: ^1.2.5 (cli ^3.0.2)
    devDependencies
  • typescript: ^3.5.2 (cli ~4.0.3)
  • @loopback/build: ^2.0.5 (cli ^6.2.5)
  • @loopback/testlab: ^1.6.3 (cli ^3.2.7)
  • eslint: ^6.0.1 (cli ^7.10.0)
    peerDependencies
    ? ¿Cómo desea continuar? (Use arrow keys)
    ❯ Terminar anormalmente ahora
    Actualizar dependencias de proyecto
    Saltar la actualización de dependencias de proyecto La conexión falla: Error: Connection terminated unexpectedly
    Se reintentará en la siguiente solicitud.

events.js:174
throw er; // Unhandled 'error' event
^

Error: Connection terminated unexpectedly
at Connection.con.once (/home/fvicente/Proyectos/test/loopback4-starter/node_modules/pg/lib/client.js:223:9)
at Object.onceWrapper (events.js:286:20)
at Connection.emit (events.js:198:13)
at Socket. (/home/fvicente/Proyectos/test/loopback4-starter/node_modules/pg/lib/connection.js:130:10)
at Socket.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
at AuditdbDataSource.postInit (/home/fvicente/Proyectos/test/loopback4-starter/node_modules/@loopback/repository/node_modules/loopback-datasource-juggler/lib/datasource.js:486:16)
at PendingItem.callback (/home/fvicente/Proyectos/test/loopback4-starter/node_modules/loopback-connector-postgresql/lib/postgresql.js:103:17)
at client.connect (/home/fvicente/Proyectos/test/loopback4-starter/node_modules/pg-pool/index.js:248:23)
at Connection.con.once (/home/fvicente/Proyectos/test/loopback4-starter/node_modules/pg/lib/client.js:234:11)
at Object.onceWrapper (events.js:286:20)
[... lines matching original stack trace ...]

Cant seem to run repo.

After downloading the repo, it won't run, giving me the errors:

image

OK I FIXED THIS BY PLACING OAUTH before the 2 but now I am getting

image
Ok I fixed this by adding Oauth before the Client.

Question: Removing Redis/Putting Redis in the Cloud

I uploaded my git to the cloud but can't seem to get the redis part working. I've tried opening an elasticache instance on aws as well as connecting to my local redis server from the ec2 running my application. Both seem to fail, so I was wondering if it's possible to remove redis altogether without affecting the latency/functionality of the app. Also.. in the loopback4 docs, it seems to show redis without a url:
https://loopback.io/doc/en/lb4/Repositories.html
I was wondering if this had anything to do with why I couldnt connect to the cloud redis?

Login not work

I install the demo everything work fine, but when i try to login from the explorer it response with this error:

To Reproduce
Steps to reproduce the behavior:

  1. Go to http://[::1]:3000/explorer/#/LoginController/LoginController.login
  2. POST /auth/login
  3. Send :
    {
    "client_id": "webapp",
    "client_secret": "saqw21!@",
    "username": "super_admin",
    "password": "test123!@#"
    }
  4. See error:
    {
    "error": {
    "statusCode": 401,
    "name": "UnauthorizedError",
    "message": {
    "name": "error",
    "length": 119,
    "severity": "ERROR",
    "code": "42P01",
    "position": "194",
    "file": "parse_relation.c",
    "line": "1173",
    "routine": "parserOpenTable"
    }
    }
    }

Can you help me?

malformed array literal upon posting a role

Hello,

When I try creating a new role through Postman, I get a 500 and below error.
Any clue, does postgres/repository have an issue storing the passed array of strings (permissions)?

{
"deleted": true,
"createdOn": "2019-07-16T15:30:29.847Z",
"modifiedOn": "2019-07-16T15:30:29.847Z",
"name": "roletest",
"permissions": [
"test"
],
"roleKey": 5
}

Unhandled error in POST /roles: 500 error: malformed array literal: "["test"]"
at Connection.parseE (C:\Users\smankarious\Desktop\admin\node_modules\pg\lib\connection.js:601:11)
at Connection.parseMessage (C:\Users\smankarious\Desktop\admin\node_modules\pg\lib\connection.js:398:19)
at Socket. (C:\Users\smankarious\Desktop\admin\node_modules\pg\lib\connection.js:120:22)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)

Thanks,

Update: explorer is blank. Started to work by itself

What does it mean if I set up the entire project as described but my explorer is blank? What could I have done wrong? I have set it up twice now and /openAPI returns an API and localhost:3000 works, but the explorer page is blank. This is the error I get in the inspection:
image

usersId not found

kept getting errors about usersId not found

added this in src/models/user-credentials.model.ts to make it run

  @property({
    type: 'number',
  })
  user_id?: number;

Single Tanent not work after update

update the dependencies because lb4 discover doesn't work. but now the login does not work nor does lb4 discover

"dependencies": {
"@loopback/boot": "^1.2.3",
"@loopback/context": "^1.12.0",
"@loopback/core": "^1.6.0",
"@loopback/openapi-v3": "^1.3.7",
"@loopback/repository": "^1.5.1",
"@loopback/rest": "^1.10.4",
"@loopback/rest-explorer": "^1.1.18",
"@loopback/service-proxy": "^1.1.6",
"bcrypt": "^3.0.6",
"db-migrate": "^0.11.5",
"db-migrate-pg": "^0.5.0",
"dotenv": "^7.0.0",
"dotenv-extended": "^2.4.0",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.11",
"loopback-connector": "^4.7.0",
"loopback-connector-kv-redis": "^3.0.1",
"loopback-connector-postgresql": "^3.6.1",
"loopback4-authentication": "^1.0.5",
"loopback4-authorization": "^2.0.0",
"loopback4-soft-delete": "^1.0.0"
},
"devDependencies": {
"@loopback/build": "^1.5.2",
"@loopback/testlab": "^1.2.5",
"@loopback/tslint-config": "^2.0.4",
"@types/bcrypt": "^3.0.0",
"@types/jsonwebtoken": "^8.3.2",
"@types/node": "^10.11.2",
"tslint": "^5.15.0",
"typescript": "^3.4.3"
}

lb4 discover (node:472216) UnhandledPromiseRejectionWarning: TypeError: Cannot set property host of #<Object> which has only a getter at Function.assign (<anonymous>) at new AuditdbDataSource (/home/user/Proyectos/test/test/dist/datasources/auditdb.datasource.js:11:16) at Object.loadDataSource (/usr/local/lib/node_modules/@loopback/cli/lib/model-discoverer.js:49:15) at dataSourceChoices.datasourcesList.map.s (/usr/local/lib/node_modules/@loopback/cli/generators/discover/index.js:108:23) at Array.map (<anonymous>) at DiscoveryGenerator.loadAllDatasources (/usr/local/lib/node_modules/@loopback/cli/generators/discover/index.js:107:46) (node:472216) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:472216) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

curl -X POST "http://localhost:3000/auth/login" -H "accept: */*" -H "Content-Type: application/json" -d "{\"client_id\":\"webapp\",\"client_secret\":\"saqw21!@\",\"username\":\"super_admin\",\"password\":\"test123!@#\"}"

{ "error": { "statusCode": 401, "name": "UnauthorizedError", "message": { "message": "VerifyFunction.OauthClientPasswordFn is not implemented" } } }

@samarpan-b thanks in advance

API Explorer: Unable to render this definition

Hello,
This is not a bug from the package, but because of my mistake. I was not able to find any documentation about this bug or behavious, and i spent 1 or 2 hours to correct this problem. I thought here could be a good place to record this solution. If not, I apologize and you can delete it (or resolve it :)). See this bug report as my tiny contribution to thank and help this project.

Describe the bug
Install loopback4-starter, execute all the installation procedure. Go to the http://[::1]:3001/explorer/ and get the error "Unable to render this definition"

Unable to render this definition
The provided definition does not specify a valid version field.
Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0).

To Reproduce
Edit packages.json. Set the author value => "author": "(C) 2021 MySelf Corporate". Rebuild & restart
Go to http://[::1]:3001/explorer/ and get the error "Unable to render this definition"

Expected behavior
The working explorer, OR an explicit error.

Screenshots
n/a

Additional context
In my case, the field /info/contact/url was not correct. This url is taken from packages.json field "author".
Check the documentation : https://docs.npmjs.com/cli/v7/configuring-npm/package-json

Can't use Oauth2 resource owner login way

Describe the bug
Can't connect via auth/login-token

I have add my user's id in user_id column of auth_clients table (and save it) but i still get this error :

{
    "error": {
        "statusCode": 401,
        "name": "UnauthorizedError",
        "message": "Bearer realm=\"Users\""
    }
}

The request body: (with the same body i can get the code with

{
    "client_id": "webapp",
    "client_secret": "saqw21!@",
    "username": "super_admin",
    "password": "test123!@#"
}

Question about testing / access-token passing

Hello,

I don't have experience with testing, but I am seeing how loopback4-starter has a good example for automated testing using mocha. I would like to start testing my end points but am wondering how to pass tokens? I am seeing some examples here https://www.npmjs.com/package/@loopback/testlab#createrestappclient but nothing mentions passing Authorization: in requests header. Do you mind provide me with any references, links or thoughts to get myself started?

Thanks,
Sherif

Using SQL Server

Hello, I tried this and it worked great. Now I am trying to get it to work with MS Sql Server. I am stuck with migration and am getting error :ifError got unwanted exception: Connection terminated unexpectedly.
I installed "loopback-connector-mssql": "^3.3.0"
I modified .env to include connection information

Only thing I have doubts about is the database.json "driver":"pg", should this be changed to something else? What?
Also do I need to install sql server migration drivers? to replace "db-migrate-pg" ?

Thanks for advising.

Sherif

User Tenant Belongs To relations returning undefined

I'm running into an issue when making use of the userTenantRepo's belongsTo functions. The role, user and tenant properties are returning undefined when called with the userTenant's id.

The following are rows in my user_tenants and roles table. The user is super_admin

image

image

The code for the user_tenant model and repository are unchanged, same with the role model and repo.

Any advice would be appreciated, thanks.

Re run db: migrate

How do I re run db: migrate? I changed the sql files and wanted to re run migrate but it just says nothing to migrate. I emptied my database and it still wont migrate, it just says No migrations to run.
image

Audit-log model bug

Describe the bug
Error while fetching user data.

To Reproduce
Steps to reproduce the behavior:

  1. Create a '/me' api which returns user data.
  2. This should break the application giving an error

Screenshots
starter_bug

login auth/login

when I go to http://127.0.0.1:3000/auth/login and send the request with the below

{
"client_id": "webapp",
"client_secret": "saqw21!@",
"username": "super_admin",
"password": "test123!@#"
}

I got reponed of

{
"error": {
"statusCode": 401,
"name": "UnauthorizedError",
"message": {
"name": "error",
"length": 185,
"severity": "ERROR",
"code": "42P01",
"position": "194",
"file": "d:\pginstaller_12.auto\postgres.windows-x64\src\backend\parser\parse_relation.c",
"line": "1173",
"routine": "parserOpenTable"
}
}
}

error using lb4 repositoru

I 'm trying to add a new repository for a connection to get data from another app and in console appears the following error, it is like a failure with the audit datasource

lb4 repository
(node:2882) UnhandledPromiseRejectionWarning: Error: Cannot load /home/georman/Documents/crm-api/src/datasources/pgdb.datasource.config.json: ENOENT: no such file or directory, open '/home/georman/Documents/crm-api/src/datasources/pgdb.datasource.config.json'
at Object.openSync (fs.js:458:3)
at Object.readFileSync (fs.js:360:35)
at readDataSourceConfigFromJSON (/usr/lib/node_modules/@loopback/cli/lib/utils.js:641:26)
at Object.getDataSourceConfig (/usr/lib/node_modules/@loopback/cli/lib/utils.js:612:5)
at Object.exports.isConnectorOfType (/usr/lib/node_modules/@loopback/cli/lib/utils.js:583:26)
at /usr/lib/node_modules/@loopback/cli/generators/repository/index.js:264:28
at Array.filter ()
at RepositoryGenerator.promptDataSourceName (/usr/lib/node_modules/@loopback/cli/generators/repository/index.js:263:50)
(node:2882) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:2882) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

How to use include support?

Hi @team,

I'm trying to setup this repository, and it's done perfectly.

Now, If I want to include credentials while finding user by id, how can I do that?

I tried as below:

async findById(@param.path.number('id') id: number): Promise<User> {
    return await this.userRepository.findById(id, { include: [{ relation: "credentials" }] });
}

but it did not work, got error:

Unhandled error in GET /users/1: 500 Error: Relation "credentials" is not defined for users model.

Note: I understood there is no need to include credentials on client side, but I was testing for hasOne relation include which I want to utilise in different model

Controller with relation returning 403 NotAllowed

Hello @samarpan-b ,

So it's my first attempt to try creating a controller to post credentials for a specific user (with relations Belongsto/Hasmany). I am getting a 403, as if end-point isn't there.
Please check full project here

below is a peak of controller:

import {post, param, requestBody} from '@loopback/rest';
import {UserRepository} from '../../repositories';
import {User, UserCredentials} from '../../models';
import {repository} from '@loopback/repository';
import {authorize} from 'loopback4-authorization';

export class UserCredentialsController {
constructor(
@repository(UserRepository)
protected userRepository: UserRepository,
) {}

@authorize(['*'])
@post('/users/{id}/credentials')
async createAccount(
@param.path.number('id') userId: typeof User.prototype.id,
@requestbody() credentials: UserCredentials,
): Promise {
return await this.userRepository.credentials(userId).create(credentials);
}
}

Thanks,
Sherif

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.