How to use the @loopback/rest.HttpErrors.Unauthorized function in @loopback/rest

To help you get started, we’ve selected a few @loopback/rest 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 / loopback-next / packages / authentication / src / __tests__ / fixtures / strategies / basic-strategy.ts View on Github external
extractCredentials(request: Request): BasicAuthenticationStrategyCredentials {
    if (!request.headers.authorization) {
      throw new HttpErrors.Unauthorized(`Authorization header not found.`);
    }

    // for example : Basic Z2l6bW9AZ21haWwuY29tOnBhc3N3b3Jk
    const authHeaderValue = request.headers.authorization;

    if (!authHeaderValue.startsWith('Basic')) {
      throw new HttpErrors.Unauthorized(
        `Authorization header is not of type 'Basic'.`,
      );
    }

    //split the string into 2 parts. We are interested in the base64 portion
    const parts = authHeaderValue.split(' ');
    if (parts.length !== 2)
      throw new HttpErrors.Unauthorized(
        `Authorization header value has too many parts. It must follow the pattern: 'Basic xxyyzz' where xxyyzz is a base64 string.`,
      );
    const encryptedCredentails = parts[1];

    // decrypt the credentials. Should look like :   'username:password'
    const decryptedCredentails = Buffer.from(
      encryptedCredentails,
      'base64',
github strongloop / loopback4-example-shopping / packages / shopping / src / services / jwt-service.ts View on Github external
async generateToken(userProfile: UserProfile): Promise {
    if (!userProfile) {
      throw new HttpErrors.Unauthorized(
        'Error generating token : userProfile is null',
      );
    }
    const userInfoForToken = {
      id: userProfile[securityId],
      name: userProfile.name,
      email: userProfile.email,
    };
    // Generate a JSON Web Token
    let token: string;
    try {
      token = await signAsync(userInfoForToken, this.jwtSecret, {
        expiresIn: Number(this.jwtExpiresIn),
      });
    } catch (error) {
      throw new HttpErrors.Unauthorized(`Error encoding token : ${error}`);
github sourcefuse / loopback4-starter / src / modules / auth / login.controller.ts View on Github external
} else if (payload.userId) {
        user = await this.userRepo.findById(payload.userId);
      }
      if (!user) {
        throw new HttpErrors.Unauthorized(
          AuthenticateErrorKeys.UserDoesNotExist,
        );
      }
      const userTenant = await this.userTenantRepo.findOne({
        where: {
          userId: user.getId(),
          tenantId: user.defaultTenant,
        },
      });
      if (!userTenant) {
        throw new HttpErrors.Unauthorized(
          AuthenticateErrorKeys.UserDoesNotExist,
        );
      } else if (userTenant.status !== 'active') {
        throw new HttpErrors.Unauthorized(AuthenticateErrorKeys.UserInactive);
      }
      // Create user DTO for payload to JWT
      const authUser: AuthUser = new AuthUser(user);
      authUser.tenant = await this.userTenantRepo.tenant(userTenant.id);
      const role = await this.userTenantRepo.role(userTenant.id);
      const utPerms = await this.utPermsRepo.find({
        where: {
          userTenantId: userTenant.id,
        },
        fields: {
          permission: true,
          allowed: true,
github strongloop / loopback4-example-shopping / packages / shopping / src / __tests__ / acceptance / authentication.acceptance.ts View on Github external
it('user service verifyCredentials() fails with user not found', async () => {
    const credentials = {email: 'idontexist@example.com', password: 'p4ssw0rd'};

    const expectedError = new HttpErrors.Unauthorized(
      'Invalid email or password.',
    );

    await expect(userService.verifyCredentials(credentials)).to.be.rejectedWith(
      expectedError,
    );
  });
github strongloop / loopback-next / packages / authentication / src / __tests__ / fixtures / services / basic-auth-user-service.ts View on Github external
throw new HttpErrors.Unauthorized(`'credentials.username' is null`);
    }

    if (!credentials.password) {
      throw new HttpErrors.Unauthorized(`'credentials.password' is null`);
    }

    const foundUser = this.userRepository.find(credentials.username);
    if (!foundUser) {
      throw new HttpErrors['Unauthorized'](
        `User with username ${credentials.username} not found.`,
      );
    }

    if (credentials.password !== foundUser.password) {
      throw new HttpErrors.Unauthorized('The password is not correct.');
    }

    return foundUser;
  }
github strongloop / loopback-next / packages / authentication / src / __tests__ / fixtures / services / basic-auth-user-service.ts View on Github external
convertToUserProfile(user: User): UserProfile {
    if (!user) {
      throw new HttpErrors.Unauthorized(`'user' is null`);
    }

    if (!user.id) {
      throw new HttpErrors.Unauthorized(`'user id' is null`);
    }

    return this.userProfileFactory(user);
  }
}
github strongloop / loopback-next / packages / authentication / src / strategy-adapter.ts View on Github external
strategy.fail = function(challenge: string) {
        reject(new HttpErrors.Unauthorized(challenge));
      };
github sourcefuse / loopback4-starter / src / modules / auth / login.controller.ts View on Github external
private async createJWT(
    payload: ClientAuthCode,
    authClient: AuthClient,
  ): Promise {
    try {
      let user: User | undefined;
      if (payload.user) {
        user = payload.user;
      } else if (payload.userId) {
        user = await this.userRepo.findById(payload.userId);
      }
      if (!user) {
        throw new HttpErrors.Unauthorized(
          AuthenticateErrorKeys.UserDoesNotExist,
        );
      }
      const userTenant = await this.userTenantRepo.findOne({
        where: {
          userId: user.getId(),
          tenantId: user.defaultTenant,
        },
      });
      if (!userTenant) {
        throw new HttpErrors.Unauthorized(
          AuthenticateErrorKeys.UserDoesNotExist,
        );
      } else if (userTenant.status !== 'active') {
        throw new HttpErrors.Unauthorized(AuthenticateErrorKeys.UserInactive);
      }
github iqbaldjulfri / lb4-jwt-role-based-auth-sample / src / auth.ts View on Github external
if (count) return;
    } else if (type === SecuredType.HAS_ROLES && roles.length) {
      const userRoles = await this.userRoleRepository.find({where: {userId: username}});
      const roleIds = userRoles.map(ur => ur.roleId);
      let valid = true;
      for (const role of roles)
        if (!roleIds.includes(role)) {
          valid = false;
          break;
        }

      if (valid) return;
    }

    throw new HttpErrors.Unauthorized('Invalid authorization');
  }
}
github gobackhuoxing / first-web-game-lb4 / firstgame / src / authorization / services / JWT.service.ts View on Github external
async verifyToken(token: string): Promise {
    if (!token) {
      throw new HttpErrors.Unauthorized(
        `Error verifying token : 'token' is null`,
      );
    }

    const decryptedToken = await verifyAsync(token, TokenServiceConstants.TOKEN_SECRET_VALUE);
    let userProfile = _.pick(decryptedToken, ['id', 'email', 'name', `permissions`]);
    return userProfile;
  }