sourcefuse / loopback4-starter

Loopback 4 starter application. Multi-tenant architecture supported. Authentication, Authorization, Soft deletes, environment vars, Audit logs, included.
MIT License
158 stars 59 forks source link

DefaultUserModifyCrudRepository not setting properly created_by #84

Closed dkmanolov closed 3 years ago

dkmanolov commented 3 years ago

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!

akshatdubeysf commented 3 years ago

Hi @dkmanolov,

If I understood it correctly, your issue is that you are not getting the current user_tenant id as uuid in CurrentUser? For that you would have to change the Tenant model, and make appropriate changes in the DB accordingly, if you are getting any issues doing that, please share them here, preferably with a screenshot of any error you are facing. After doing all this, you would still need to generate a new token to get the changes in the CurrentUser binding.

dkmanolov commented 3 years ago

Hi @akshatdubeysf, thank's for your reply. I'll try to provide more detail info about the case. The problem is that when I try to create for example a new tenant, I'm getting: Request POST /tenants failed with status code 500. error: insert or update on table "tenants" violates foreign key constraint "fk_created_by"

When I debug, I saw that in DefaultUserModifyCrudRepository in create method I have this:

async create(entity: DataObject<T>, options?: Options): Promise<T> {
    const currentUser = await this.getCurrentUser();
    if (!currentUser) {
      throw new HttpErrors.Forbidden(AuthErrorKeys.InvalidCredentials);
    }

    entity.createdBy = currentUser.id;
    entity.modifiedBy = currentUser.id;

    return super.create(entity, options);
  }

And if I console log currentUser.id shows the id from the users table. But according to the migrations here user_tanants id is expected so that's why I'm getting such error.

I don't think this is related to the uuid transition, I've noticed it then because when I've tested with just single user and signle row in user_tenants they both have id of 1, but with uuid every id is unique and the error appear.

akshatdubeysf commented 3 years ago

Thanks for you detailed response, it is indeed an issue, I'll try and raise a PR to fix this as soon as possible.

dkmanolov commented 3 years ago

No problem thank you for your time!

My quick fix was to extend the AuthUser model with userTenantId and use it later where needed (in the DefaultUserModifyCrudRepository).

entity.createdBy = currentUser.userTenantId;