@nestjs/common#UnauthorizedException TypeScript Examples

The following examples show how to use @nestjs/common#UnauthorizedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: acl.util.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 7 votes vote down vote up
/**
 * canUserAccessResource function is used to check if a user can view/edit a resource
 */
export function canUserAccessResource(userAccessKey: string, resource: ResourceWithACL): boolean {
  if (!userAccessKey) {
    throw new UnauthorizedException('Could not check access without userAccessKey')
  }
  if (!resource) {
    throw new UnauthorizedException('Could not check access on empty resource')
  }
  if (!resource.accessControlList) {
    throw new UnauthorizedException('Could not check access without accessControlList')
  }
  if (!resource.accessControlList.length) {
    throw new UnauthorizedException('Could not check access on empty accessControlList')
  }

  // If accessControlList contains the userAccessKey, return true.
  if (resource.accessControlList.includes(userAccessKey)) {
    return true
  }

  return false
}
Example #2
Source File: subscription.utils.ts    From relate with GNU General Public License v3.0 7 votes vote down vote up
export function subscriptionsTransportWs(systemProvider: SystemProvider): IGraphQLSubscriptionTransportWsConfig {
    return {
        async onConnect(connectionParams: Readonly<Record<string, unknown>>, ws: WebSocket) {
            const clientId = Str.from(connectionParams[CLIENT_ID_HEADER]).toString();
            const apiToken = Str.from(connectionParams[API_TOKEN_HEADER]).toString();
            const environment = await systemProvider.getEnvironment();

            if (!environment.requiresAPIToken) {
                return true;
            }

            // @ts-ignore ws contains the upgradeReq attribute,
            // but the type definition for it doesn't.
            const origin = ws.upgradeReq.headers?.origin || 'null';
            // Use the client URL otherwise fallback to the
            // Relate server URL. Requests coming from files
            // might contain either 'null' or 'file://' in the
            // Origin header.
            const requestUrl = origin && origin !== 'null' && new URL(origin).host ? origin : environment.httpOrigin;
            const requestHost = new URL(requestUrl).host;

            try {
                await environment.verifyAPIToken(requestHost, clientId, apiToken);
                return true;
            } catch (e) {
                throw new UnauthorizedException();
            }
        },
    };
}
Example #3
Source File: plugin-newsletter.resolver.ts    From Cromwell with MIT License 6 votes vote down vote up
/** Restrict via decorator: */
    @Authorized<TAuthRole>("administrator", 'guest')
    @Query(() => String)
    async pluginNewsletterStats(@Ctx() ctx: TGraphQLContext): Promise<string> {
        
        // Or via checking manually user info: (both methods can work independently)
        if (ctx.user?.role !== 'administrator')
            throw new UnauthorizedException('Forbidden');

        return (await getManager().find(PluginNewsletter) ?? []).length + '';
    }
Example #4
Source File: local.strategy.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
async validate(req: ExpressRequest, email: string, password: string): Promise<ValidateUserOutput> {
    const errors = await validate(new SignInDto(req.body)) as ValidationError[];

    if (errors.length > 0) {
      throw new ValidationExceptions(errors);
    }

    const user = await this.authService.validateUser(email, password);

    if (!user) {
      throw new UnauthorizedException();
    }

    return user;
  }
Example #5
Source File: local.strategy.ts    From barista with Apache License 2.0 6 votes vote down vote up
async validate(username: string, password: string): Promise<any> {
    let user: any = null;

    if (process.env.NODE_ENV && process.env.NODE_ENV.toLowerCase() === 'test') {
      // If this is a test, let's go ahead and validate
      // TODO: Add a provision to allow for testing of negative login conditions
      user = {
        displayName: '',
        id: 0,
        role: 'test',
        userName: 'TestUser',
        groups: ['group1', 'group1', 'group3'],
      };
    } else if (process.env.AUTH_TYPE === 'ldap') {
      user = await this.ldapService.validateUser(username, password, false);
      if (!user) {
        user = await this.ldapService.validateUser(username, password, true);
      }
      if (user) {
        user.groups = await this.ldapService.getUserGroups(username, password);
      }
    } else {
      user = await this.userService.validateUser(username, password);
    }
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
Example #6
Source File: account.service.ts    From uniauth-backend with MIT License 6 votes vote down vote up
/**
   * Function to provide response and data via oauth flow
   */
  async provideUserDetailOnAccess(accessUserDetailsDto: AccessUserDetailsDto) {
    try {
      const { clientId, clientSecret, accessToken } = accessUserDetailsDto;
      /** ensure that application exists */
      const applicationDetails = await this.applicationService.findOneByIdAndSecret(clientId, clientSecret);

      /** ensure that access_token is valid */
      const { token } = await this.jwtService.verifyAsync(accessToken, accessTokenJwtConstants);

      /** get user details by id */
      const userDetails = await this.userService.findOneById(token);
      const userDetailsJson = userDetails.toJSON();

      const resultantSet = {};
      /** map details as per application scope */
      this.logger.verbose(`Application Scope: ${JSON.stringify(applicationDetails.scope)}`);
      Object.keys(userDetailsJson).forEach((key) => {
        if (applicationDetails.scope.includes(key)) {
          resultantSet[key] = userDetailsJson[key];
        }
      });
      this.logger.verbose(`Sharing details of ${userDetailsJson.name}, ${JSON.stringify(resultantSet)}`);
      return resultantSet;
    } catch (e) {
      throw new UnauthorizedException(e.message);
    }
  }
Example #7
Source File: auth.service.ts    From svvs with MIT License 6 votes vote down vote up
/**
   * Return SignAuthResponse data
   *
   * @param signInPayload Incoming login data
   */
  async login(signInPayload: ISignAuthPayload): Promise<ISignAuthResponse> {
    const user = await this.validateUser(
      signInPayload.username,
      signInPayload.password
    );

    if (!user) {
      throw new UnauthorizedException();
    }

    const payload = { username: user.username, userId: user.id };

    return {
      accessToken: this.jwtService.sign(payload),
      expiresIn: new Date(environment.jwt.expiresIn).getDate(),
      id: user.id,
    };
  }
Example #8
Source File: auth.service.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
async validateUserCreds(email: string, password: string): Promise<any> {
    const user = await this.userService.getUserByEmail(email);

    if (!user) throw new BadRequestException();

    if (!(await bcrypt.compare(password, user.password)))
      throw new UnauthorizedException();

    return user;
  }
Example #9
Source File: auth.service.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async login(credentials: Credentials): Promise<UserInfo> {
    const { username, password } = credentials;
    const user = await this.validateUser(
      credentials.username,
      credentials.password
    );
    if (!user) {
      throw new UnauthorizedException("The passed credentials are incorrect");
    }
    //@ts-ignore
    const accessToken = await this.tokenService.createToken(username, password);
    return {
      accessToken,
      ...user,
    };
  }
Example #10
Source File: auth.guard.ts    From nestjs-keycloak-admin with MIT License 6 votes vote down vote up
async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic: boolean = this.reflector.get<boolean>(META_PUBLIC, context.getHandler())

    if (isPublic) {
      return true
    }

    const request = extractRequest(context)
    const jwt = this.extractJwt(request.headers)

    try {
      const result = await this.keycloak.connect.grantManager.validateAccessToken(jwt)

      if (typeof result === 'string') {
        request.user = await this.keycloak.connect.grantManager.userInfo<string, KeycloakUser>(jwt)
        request.accessToken = jwt
        return true
      }
    } catch (error) {
      this.logger.warn(`Error occurred validating token`, error)
    }

    throw new UnauthorizedException()
  }
Example #11
Source File: firebase-auth.strategy.ts    From aqualink-app with MIT License 6 votes vote down vote up
async authenticate(req: Request): Promise<void> {
    const self = this;
    const firebaseUser = await extractAndVerifyToken(req);
    if (!firebaseUser) {
      return self.fail(new UnauthorizedException(), 401);
    }
    const firebaseUid = firebaseUser.uid;
    const user = await this.usersRepository.findOne({ where: { firebaseUid } });
    if (!user) {
      return self.fail(new UnauthorizedException(), 401);
    }
    return self.success(user, firebaseUser);
  }
Example #12
Source File: auth.controller.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Post('reset-password')
  @HttpCode(HttpStatus.OK)
  async resetPassword(@Body() input: ResetPassInput): Promise<void> {
    const { email, token, newPassword } = input;
    const exist = await this.usersService.findOneAsync({ email });
    if (!exist) throw new UnauthorizedException('Password reset failed');
    await this.authService.validatePasswordToken({
      userId: exist.id,
      plainToken: token,
      newPassword
    });
  }
Example #13
Source File: access.service.ts    From nest-casl with MIT License 6 votes vote down vote up
public assertAbility(user: AuthorizableUser, action: string, subject: Subject): void {
    if (!this.hasAbility(user, action, subject)) {
      const userAbilities = this.abilityFactory.createForUser(user, Ability);
      const relatedRules = userAbilities.rulesFor(action, typeof subject === 'object' ? subject.constructor : subject);
      if (relatedRules.some((rule) => rule.conditions)) {
        throw new NotFoundException();
      }
      throw new UnauthorizedException();
    }
  }
Example #14
Source File: auth.service.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
validateUser(username: string, pass: string): Observable<UserPrincipal> {
    return this.userService.findByUsername(username).pipe(
      //if user is not found, convert it into an EMPTY.
      mergeMap((p) => (p ? of(p) : EMPTY)),

      // Using a general message in the authentication progress is more reasonable.
      // Concise info could be considered for security.
      // Detailed info will be helpful for crackers.
      // throwIfEmpty(() => new NotFoundException(`username:${username} was not found`)),
      throwIfEmpty(() => new UnauthorizedException(`username or password is not matched`)),

      mergeMap((user) => {
        const { _id, password, username, email, roles } = user;
        return user.comparePassword(pass).pipe(map(m => {
          if (m) {
            return { id: _id, username, email, roles } as UserPrincipal;
          }else {
            // The same reason above.
            //throw new UnauthorizedException('password was not matched.')
            throw new UnauthorizedException('username or password is not matched')
          }
        }))
      })
    );
  }
Example #15
Source File: auth.controller.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@ApiExcludeEndpoint()
  @Post('login')
  async login(@Req() req: Request, @Res() res: Response): Promise<void> {
    if (this.config.get<boolean>('DISABLE_LOGIN')) {
      throw new UnauthorizedException();
    }

    let email;

    const { authorization } = req.headers;
    if (!authorization) {
      throw new UnauthorizedException();
    }

    try {
      email = await this.magicLinkService.getEmailFromHeader(authorization);
    } catch {
      throw new UnauthorizedException();
    }

    if (email) {
      const user = await this.usersService.findByEmail(email);
      if (user) {
        await this.usersService.updateLastLoginAt(user);
      } else {
        throw new UnauthorizedException({ error: 'user_invalid' });
      }
    }

    res.sendStatus(HttpStatus.OK);
  }
Example #16
Source File: admins.service.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
async getOneAdminById(requestAdminUser: RequestAdminUser, adminId: string): Promise<Admin> {
    // Fetch resource and perform ACL check.
    const admin = await this.adminsRepository.findOneById(adminId)
    if (!admin) {
      throw new NotFoundException('Could not find admin with this id')
    }
    if (!canUserAccessResource(requestAdminUser.userAccessKey, admin)) {
      throw new UnauthorizedException('User does not have access on this resource')
    }

    return admin
  }
Example #17
Source File: article.service.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
async createArticle(
    ctx: RequestContext,
    input: CreateArticleInput,
  ): Promise<ArticleOutput> {
    this.logger.log(ctx, `${this.createArticle.name} was called`);

    const article = plainToClass(Article, input);

    const actor: Actor = ctx.user;

    const user = await this.userService.getUserById(ctx, actor.id);

    const isAllowed = this.aclService
      .forActor(actor)
      .canDoAction(Action.Create, article);
    if (!isAllowed) {
      throw new UnauthorizedException();
    }

    article.author = plainToClass(User, user);

    this.logger.log(ctx, `calling ${ArticleRepository.name}.save`);
    const savedArticle = await this.repository.save(article);

    return plainToClass(ArticleOutput, savedArticle, {
      excludeExtraneousValues: true,
    });
  }
Example #18
Source File: jwt.strategy.ts    From bank-server with MIT License 6 votes vote down vote up
async validate({ iat, exp, uuid }): Promise<UserEntity> {
    const timeDiff = exp - iat;

    if (timeDiff <= 0) {
      throw new UnauthorizedException();
    }

    const user = await this._userService.getUser({ uuid });

    if (!user) {
      throw new UnauthorizedException();
    }

    return user;
  }
Example #19
Source File: auth.service.ts    From MyAPI with MIT License 6 votes vote down vote up
async validateUser(id: string, password: string): Promise<User> {
    const user = await this.userService.findOne(id)
    if (!user) return null
    else if (!isEmpty(user.password)) {
      const matchPassword = await comparePassword(password, user.password)
      if (matchPassword) {
        user.role = await this.roleService.findById(user.roleId)
        delete user.password
        return user
      }
    }
    throw new UnauthorizedException(ERRORS.USER_INVALID_PASSWORD)
  }
Example #20
Source File: NestHttpExceptionFilter.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
private handleNestError(error: Error, errorResponse: CoreApiResponse<unknown>): CoreApiResponse<unknown> {
    if (error instanceof HttpException) {
      errorResponse = CoreApiResponse.error(error.getStatus(), error.message, null);
    }
    if (error instanceof UnauthorizedException) {
      errorResponse = CoreApiResponse.error(Code.UNAUTHORIZED_ERROR.code, Code.UNAUTHORIZED_ERROR.message, null);
    }
    
    return errorResponse;
  }
Example #21
Source File: form.controller.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
@Delete('/:id')
	@Permissions('forms/delete')
	@AuditLog('forms/delete')
	public async delete(@Param('id') uuid: string): Promise<any> {
		if (!await this.formService.findOnePure({ uuid })) {
			throw new UnauthorizedException()
		}

		await this.formService.delete(uuid);
		return {};
	}
Example #22
Source File: role.guard.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
async canActivate(context: ExecutionContext): Promise<boolean> {
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!roles) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const { courseId, user } = await this.setupData(request);

    if (!user) {
      throw new UnauthorizedException(ERROR_MESSAGES.roleGuard.notLoggedIn);
    }

    if (!courseId) {
      throw new NotFoundException(ERROR_MESSAGES.roleGuard.noCourseIdFound);
    }

    return this.matchRoles(roles, user, courseId);
  }
Example #23
Source File: auth.service.ts    From nestjs-angular-starter with MIT License 6 votes vote down vote up
/**
   * Checks if the provided username and password valid, if so, returns the user match. If not, returns null.
   * @param email
   * @param password
   */
  authenticate(email: string, password: string): Promise<IUserProfileDbModel> {
    return UserProfileDbModel.findOne({ email }).then(user => {
      // If this user does not exist, throw the same error for security reasons
      if (!user)
        throw new UnauthorizedException('Email or password are invalid!');

      return bcrypt.compare(password, user.password).then(match => {
        // The password do not match the one saved on the database
        if (!match)
          throw new UnauthorizedException('Email or password are invalid!');
        return user;
      });
    });
  }
Example #24
Source File: invalid-user.exception.ts    From nestjs-oauth2-server-module with MIT License 6 votes vote down vote up
/**
 * Exception thrown when a user is invalid
 */
export class InvalidUserException extends UnauthorizedException {

    /**
     * Kind message with username and password
     *
     * @param username
     * @param password
     */
    static withUsernameAndPassword(username: string, password: string): InvalidUserException {
        return new InvalidUserException(`The user with username "${username}" and password "${password}" was not found`);
    }

    /**
     * Kind message with id
     *
     * @param userId
     */
    static withId(userId: string): InvalidUserException {
        return new InvalidUserException(`The user with id "${userId}" was not found`);
    }
}
Example #25
Source File: auth.service.ts    From pknote-backend with GNU General Public License v3.0 6 votes vote down vote up
async loginByPwd(
    loginData: LoginByPwdDto,
  ): Promise<{ accessToken: string; user: unknown }> {
    const user = await this.userRepository.validateuserPassword(loginData);

    if (!user) {
      throw new UnauthorizedException('Invalid credentials');
    }

    const { userId } = user;
    const payload: JwtPayload = { userId };
    const accessToken: string = await this.jwtService.sign(payload);

    this.logger.debug(
      `Generator JWT token with payload ${JSON.stringify(payload)}`,
    );
    return { accessToken, user };
  }