How to use @loopback/authorization - 10 common examples

To help you get started, we’ve selected a few @loopback/authorization examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github strongloop / loopback4-example-shopping / packages / shopping / src / controllers / user-order.controller.ts View on Github external
/**
   * Create or update the orders for a given user
   * @param userId User id
   * @param cart Shopping cart
   */
  @post('/users/{userId}/orders', {
    responses: {
      '200': {
        description: 'User.Order model instance',
        content: {'application/json': {schema: {'x-ts-type': Order}}},
      },
    },
  })
  @authenticate('jwt')
  @authorize({resource: 'order', scopes: ['create']})
  async createOrder(
    @param.path.string('userId') userId: string,
    @requestBody() order: Order,
  ): Promise {
    // validate the payload value
    // has nothing to do with authorization
    if (userId !== order.userId) {
      throw new HttpErrors.BadRequest(
        `User id does not match: ${userId} !== ${order.userId}`,
      );
    }
    delete order.userId;
    return this.userRepo.orders(userId).create(order);
  }

  @get('/users/{userId}/orders', {
github strongloop / loopback4-example-shopping / packages / shopping / src / services / id.compare.authorizor.ts View on Github external
]);
    currentUser = {[securityId]: user.id, name: user.name, email: user.email};
  } else {
    return AuthorizationDecision.DENY;
  }

  // A workaround to bypass the authorizer priority
  // class level authorizer should have higher priority than the instance level one
  // which means the DENY returned in this function will be ignored when the global authorizer
  // says ALLOW
  if (currentUser && currentUser.name === 'customer_service')
    return AuthorizationDecision.ALLOW;

  const userId = authorizationCtx.invocationContext.args[0];
  return userId === currentUser[securityId]
    ? AuthorizationDecision.ALLOW
    : AuthorizationDecision.DENY;
}
github strongloop / loopback4-example-shopping / packages / shopping / src / services / id.compare.authorizor.ts View on Github external
export async function compareId(
  authorizationCtx: AuthorizationContext,
  metadata: MyAuthorizationMetadata,
) {
  let currentUser: UserProfile;
  if (authorizationCtx.principals.length > 0) {
    const user = _.pick(authorizationCtx.principals[0], [
      'id',
      'name',
      'email',
    ]);
    currentUser = {[securityId]: user.id, name: user.name, email: user.email};
  } else {
    return AuthorizationDecision.DENY;
  }

  // A workaround to bypass the authorizer priority
  // class level authorizer should have higher priority than the instance level one
  // which means the DENY returned in this function will be ignored when the global authorizer
  // says ALLOW
  if (currentUser && currentUser.name === 'customer_service')
    return AuthorizationDecision.ALLOW;

  const userId = authorizationCtx.invocationContext.args[0];
  return userId === currentUser[securityId]
    ? AuthorizationDecision.ALLOW
    : AuthorizationDecision.DENY;
}
github strongloop / loopback4-example-shopping / packages / shopping / src / application.ts View on Github external
paths: {},
      components: {securitySchemes: SECURITY_SCHEME_SPEC},
      servers: [{url: '/'}],
    });

    this.setUpBindings();

    // Bind authentication component related elements
    this.component(AuthenticationComponent);
    this.component(AuthorizationComponent);

    // authorization
    this.bind('casbin.enforcer').toDynamicValue(createEnforcer);
    this.bind('authorizationProviders.casbin-provider')
      .toProvider(CasbinAuthorizationProvider)
      .tag(AuthorizationTags.AUTHORIZER);

    // authentication
    registerAuthenticationStrategy(this, JWTAuthenticationStrategy);

    // Set up the custom sequence
    this.sequence(MyAuthenticationSequence);

    // Set up default home page
    this.static('/', path.join(__dirname, '../public'));

    // Customize @loopback/rest-explorer configuration here
    this.bind(RestExplorerBindings.CONFIG).to({
      path: '/explorer',
    });
    this.component(RestExplorerComponent);
github strongloop / loopback4-example-shopping / packages / shopping / src / controllers / user-order.controller.ts View on Github external
@requestBody() order: Partial,
    @param.query.string('where') where?: Where,
  ): Promise {
    return this.userRepo.orders(userId).patch(order, where);
  }

  @del('/users/{userId}/orders', {
    responses: {
      '200': {
        description: 'User.Order DELETE success count',
        content: {'application/json': {schema: CountSchema}},
      },
    },
  })
  @authenticate('jwt')
  @authorize({resource: 'order', scopes: ['delete'], voters: [compareId]})
  async deleteOrders(
    @param.path.string('userId') userId: string,
    @param.query.string('where') where?: Where,
  ): Promise {
    return this.userRepo.orders(userId).delete(where);
  }
}
github strongloop / loopback4-example-shopping / packages / shopping / src / controllers / user-order.controller.ts View on Github external
}

  @get('/users/{userId}/orders', {
    responses: {
      '200': {
        description: "Array of User's Orders",
        content: {
          'application/json': {
            schema: {type: 'array', items: {'x-ts-type': Order}},
          },
        },
      },
    },
  })
  @authenticate('jwt')
  @authorize({resource: 'order', scopes: ['find'], voters: [compareId]})
  async findOrders(
    @param.path.string('userId') userId: string,
    @param.query.string('filter') filter?: Filter,
  ): Promise {
    const orders = await this.userRepo.orders(userId).find(filter);
    return orders;
  }

  @patch('/users/{userId}/orders', {
    responses: {
      '200': {
        description: 'User.Order PATCH success count',
        content: {'application/json': {schema: CountSchema}},
      },
    },
  })
github strongloop / loopback4-example-shopping / packages / shopping / src / controllers / user-order.controller.ts View on Github external
@param.query.string('filter') filter?: Filter,
  ): Promise {
    const orders = await this.userRepo.orders(userId).find(filter);
    return orders;
  }

  @patch('/users/{userId}/orders', {
    responses: {
      '200': {
        description: 'User.Order PATCH success count',
        content: {'application/json': {schema: CountSchema}},
      },
    },
  })
  @authenticate('jwt')
  @authorize({resource: 'order', scopes: ['patch'], voters: [compareId]})
  async patchOrders(
    @param.path.string('userId') userId: string,
    @requestBody() order: Partial,
    @param.query.string('where') where?: Where,
  ): Promise {
    return this.userRepo.orders(userId).patch(order, where);
  }

  @del('/users/{userId}/orders', {
    responses: {
      '200': {
        description: 'User.Order DELETE success count',
        content: {'application/json': {schema: CountSchema}},
      },
    },
  })
github strongloop / loopback4-example-shopping / packages / shopping / src / services / authorizor.ts View on Github external
async authorize(
    authorizationCtx: AuthorizationContext,
    metadata: AuthorizationMetadata,
  ) {
    const request: AuthorizationRequest = {
      subject: authorizationCtx.principals[0].name,
      object: metadata.resource ?? authorizationCtx.resource,
      action: (metadata.scopes && metadata.scopes[0]) || 'execute',
    };

    const allow = await this.enforcer.enforce(
      request.subject,
      request.object,
      request.action,
    );
    if (allow) return AuthorizationDecision.ALLOW;
    else if (allow === false) return AuthorizationDecision.DENY;
    return AuthorizationDecision.ABSTAIN;
  }
}
github strongloop / loopback4-example-shopping / packages / shopping / src / services / authorizor.ts View on Github external
authorizationCtx: AuthorizationContext,
    metadata: AuthorizationMetadata,
  ) {
    const request: AuthorizationRequest = {
      subject: authorizationCtx.principals[0].name,
      object: metadata.resource ?? authorizationCtx.resource,
      action: (metadata.scopes && metadata.scopes[0]) || 'execute',
    };

    const allow = await this.enforcer.enforce(
      request.subject,
      request.object,
      request.action,
    );
    if (allow) return AuthorizationDecision.ALLOW;
    else if (allow === false) return AuthorizationDecision.DENY;
    return AuthorizationDecision.ABSTAIN;
  }
}
github strongloop / loopback4-example-shopping / packages / shopping / src / services / authorizor.ts View on Github external
metadata: AuthorizationMetadata,
  ) {
    const request: AuthorizationRequest = {
      subject: authorizationCtx.principals[0].name,
      object: metadata.resource ?? authorizationCtx.resource,
      action: (metadata.scopes && metadata.scopes[0]) || 'execute',
    };

    const allow = await this.enforcer.enforce(
      request.subject,
      request.object,
      request.action,
    );
    if (allow) return AuthorizationDecision.ALLOW;
    else if (allow === false) return AuthorizationDecision.DENY;
    return AuthorizationDecision.ABSTAIN;
  }
}