bcryptjs#hash TypeScript Examples

The following examples show how to use bcryptjs#hash. 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: status.spec.ts    From nodestatus with MIT License 6 votes vote down vote up
test('auth password', async () => {
  const password = await hash('username', 8);
  ReadServerPassword.mockResolvedValue(password);
  await expect(authServer('username', 'username')).resolves.toBe(true);
  await expect(authServer('username', 'false_password')).resolves.toBe(false);
  /* NULL USERNAME */
  ReadServerPassword.mockResolvedValue(null);
  return expect(authServer('username2', 'username2')).resolves.toBe(false);
});
Example #2
Source File: prisma.ts    From nodestatus with MIT License 6 votes vote down vote up
parseFields = async (server: Prisma.ServerCreateInput) => {
  type Key = keyof Prisma.ServerCreateInput;

  /* All fields must not be empty */
  for (const key in server) {
    if (server[key as Key] === '') {
      delete server[key as Key];
    }
  }

  /* Password should be encrypted */
  if (server.password) {
    server.password = await hash(server.password, 8);
  }
}
Example #3
Source File: changePassword.ts    From tezos-academy with MIT License 6 votes vote down vote up
changePassword = async (ctx: Context, next: Next): Promise<void> => {
  const changePasswordArgs = plainToClass(ChangePasswordInputs, ctx.request.body, {
    excludeExtraneousValues: true,
  })
  await validateOrReject(changePasswordArgs, { forbidUnknownValues: true }).catch(firstError)
  const { password, newPassword } = changePasswordArgs

  const user: User = await authenticate(ctx)

  await rateLimit(user._id)

  await matchPassword(password, user.hashedPassword)

  const hashedPassword = await hash(newPassword, 12)
  await UserModel.updateOne({ _id: user._id }, { hashedPassword }).exec()

  ctx.status = 200
  ctx.body = {}

  await next()
}
Example #4
Source File: matchPassword.spec.ts    From tezos-academy with MIT License 6 votes vote down vote up
describe('User', () => {
  it('can match correct passwords', async (done) => {
    const password = 'Test#123'
    const hashedPassword = await hash(password, 12)
    await matchPassword(password, hashedPassword)
    done()
  })

  it('cannot match incorrect passwords', async (done) => {
    try {
      const password = 'Test#123'
      const hashedPassword = await hash(password, 12)
      await matchPassword(password + 'x', hashedPassword)
      throw new Error('Should not reach this point')
    } catch (error) {
      expect(error).toBeDefined()
      expect(error.message).toBe('Wrong username or password')
      done()
    }
  })
})
Example #5
Source File: resetPassword.ts    From tezos-academy with MIT License 6 votes vote down vote up
resetPassword = async (ctx: Context, next: Next): Promise<void> => {
  const resetPasswordArgs = plainToClass(ResetPasswordInputs, ctx.request.body, { excludeExtraneousValues: true })
  await validateOrReject(resetPasswordArgs, { forbidUnknownValues: true }).catch(firstError)
  const { solution, token, newPassword } = resetPasswordArgs

  const captcha: Captcha = (await CaptchaModel.findOne({
    token,
    captchaFor: CaptchaFor.CAPTCHA_FOR_RESET_PASSWORD,
  }).lean()) as Captcha
  if (!captcha) throw new ResponseError(401, 'Wrong token key')

  const user: User = (await UserModel.findOne({ _id: captcha.userId }).lean()) as User
  if (!user) throw new ResponseError(404, 'User not found')

  await rateLimit(user._id)

  await verifyCaptcha(user._id, solution, CaptchaFor.CAPTCHA_FOR_RESET_PASSWORD)

  const hashedPassword: string = await hash(newPassword, 12)

  await UserModel.updateOne({ _id: user._id }, { hashedPassword }).exec()

  await CaptchaModel.deleteOne({ _id: captcha._id }).exec()

  ctx.status = 200
  ctx.body = {}

  await next()
}
Example #6
Source File: signUp.ts    From tezos-academy with MIT License 6 votes vote down vote up
signUp = async (ctx: Context, next: Next): Promise<void> => {
  const signUpArgs = plainToClass(SignUpInputs, ctx.request.body, { excludeExtraneousValues: true })
  await validateOrReject(signUpArgs, { forbidUnknownValues: true }).catch(firstError)
  let { username, email, password, recaptchaToken } = signUpArgs

  username = username.toLowerCase()
  email = email.toLowerCase()

  await verifyRecaptchaToken(recaptchaToken)

  const emailAlreadyTaken: User | null = await UserModel.findOne({ email }).lean()
  if (emailAlreadyTaken) throw new ResponseError(400, 'Email is already taken')

  const usernameAlreadyTaken: User | null = await UserModel.findOne({ username }).lean()
  if (usernameAlreadyTaken) throw new ResponseError(400, 'Username is already taken')

  const hashedPassword = await hash(password, 12)
  const user: User = await UserModel.create({ email, username, hashedPassword } as User)
  const publicUser: PublicUser = toPublicUser(user)

  const jwt: Jwt = getSignedJwt(user._id.toHexString(), user.username)

  const response: SignUpOutputs = { jwt, user: publicUser }

  ctx.status = 200
  ctx.body = response

  await next()
}
Example #7
Source File: register.ts    From TypeScript-Login-Register with MIT License 5 votes vote down vote up
alt.onClient(
  "client::lr:registerAccount",
  async (player: alt.Player, data: IRegisterAccountData) => {
    try {
      data.socialId = player.socialId;
      const loginConnection = getConnection("lr");
      const result = await loginConnection
        .createQueryBuilder(Account, "account")
        .leftJoinAndSelect("account.validation", "validation")
        .where("account.username = :username", { username: data.username })
        .orWhere("validation.socialId = :socialId", {
          socialId: data.socialId,
        })
        .orWhere("validation.scNickname = :scNickname", {
          scNickname: data.socialClub,
        })
        .orWhere("validation.licenseHash = :licenseHash", {
          licenseHash: data.licenseHash,
        })
        .getOne();
      if (result) {
        let message: string;
        if (result.username == data.username)
          message = "The given username already exists";
        else if (result.validation.scNickname == data.socialClub)
          message =
            "There is already an account linked to your socialclub name";
        else if (result.validation.socialId == data.socialId)
          message = "There is already an account linked to your socialclub id";

        let err: IErrorMessage = {
          location: "register",
          param: "username",
          msg: message,
        };
        return alt.emitClient(player, "server::lr:showRegistrationError", err);
      }

      let accValidation = new AccountValidation();
      accValidation.discordUserID = data.discordUserID;
      accValidation.licenseHash = data.licenseHash;
      accValidation.scNickname = data.socialClub;
      accValidation.socialId = data.socialId;

      let accSaveResult = await loginConnection.manager.save(accValidation);

      const salt = await genSalt(10);
      const password = await hash(data.password, salt);

      let accData = new Account();
      accData.username = data.username;
      accData.password = password;
      accData.validation = accSaveResult;

      await loginConnection.manager.save(accData);

      const loginData: ILoginAccountData = {
        socialClub: accData.validation.scNickname,
        username: accData.username,
        discordUserID: accData.validation.discordUserID,
      };

      player.setSyncedMeta("userData", loginData);

      alt.emitClient(player, "client:lr:registrationSuccessfull");
    } catch (error) {
      alt.log(error);
      let err: IErrorMessage = {
        location: "server",
        param: "",
        msg: "Internal server error, please try again later",
      };
      return alt.emitClient(player, "server::lr:showRegistrationError", err);
    }
  }
);
Example #8
Source File: BCryptHashProvider.ts    From gobarber-api with MIT License 5 votes vote down vote up
public async generateHash(payload: string): Promise<string> {
    return hash(payload, 8);
  }
Example #9
Source File: BCryptHashProvider.ts    From hotseat-api with MIT License 5 votes vote down vote up
public async generateHash(payload: string, salt = 8): Promise<string> {
    const payloadHash = await hash(payload, salt);

    return payloadHash;
  }
Example #10
Source File: user.ts    From ts-oauth2-server with MIT License 5 votes vote down vote up
async setPassword(password: string) {
    this.passwordHash = await hash(password, 12);
  }
Example #11
Source File: BCryptHashProvider.ts    From gobarber-project with MIT License 5 votes vote down vote up
public async generateHash(payload: string): Promise<string> {
    return hash(payload, 8);
  }
Example #12
Source File: BCryptHashProvider.ts    From GoBarber with MIT License 5 votes vote down vote up
public async generateHash(payload: string): Promise<string> {
    return hash(payload, 8);
  }
Example #13
Source File: user.entity.ts    From postgres-nest-react-typescript-boilerplate with GNU General Public License v3.0 5 votes vote down vote up
@BeforeInsert()
  hashPassword = async () => {
    this.password = await hash(this.password, 8);
  };
Example #14
Source File: User.ts    From typescript-clean-architecture with MIT License 5 votes vote down vote up
public async hashPassword(): Promise<void> {
    const salt: string = await genSalt();
    this.password = await hash(this.password, salt);
    
    await this.validate();
  }
Example #15
Source File: user.entity.ts    From nestjs-starter with MIT License 5 votes vote down vote up
@BeforeInsert()
  @BeforeUpdate()
  async hashPassword() {
    if (!this.password) {
      return;
    }
    this.password = await hash(this.password, 10);
  }