bcrypt#hash TypeScript Examples

The following examples show how to use bcrypt#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: user.mdoel.spec.ts    From nestjs-rest-sample with GNU General Public License v3.0 8 votes vote down vote up
describe('comparePasswordMethod', () => {
  test('should be true if password is matched', async () => {
    const hashed = await hash('123456', 10);
    const contextMock = {
      password: hashed,
    };

    const result = await lastValueFrom(
      comparePasswordMethod.call(contextMock, '123456'),
    );
    expect(result).toBeTruthy();
  });

  test('should be false if password is not matched', async () => {
    const hashed = await hash('123456', 10);
    const contextMock = {
      password: hashed,
    };

    // input password is wrong
    const result = await lastValueFrom(
      comparePasswordMethod.call(contextMock, '000000'),
    );
    expect(result).toBeFalsy();
  });
});
Example #2
Source File: utils.ts    From MyAPI with MIT License 6 votes vote down vote up
encryptPassword = function (password: string) : Promise<string> {
  const saltRounds = 10
  return hash(password, saltRounds)
}
Example #3
Source File: crypt.service.ts    From wise-old-man with MIT License 6 votes vote down vote up
/**
 * Checks if a given hash matches a given code.
 */
async function verifyCode(hash: string, code: string): Promise<boolean> {
  const verified = await new Promise((resolve, reject) => {
    compare(code, hash, (err, result) => {
      if (err) reject(err);
      resolve(result);
    });
  });

  return !!verified;
}
Example #4
Source File: crypt.service.ts    From wise-old-man with MIT License 6 votes vote down vote up
/**
 * Generates a code/hash pair.
 */
async function generateVerification(): Promise<[string, string]> {
  const saltRounds = 10;

  // This code is to be given to
  // the user at the moment of creation
  const code = generateCode();

  // This hashed code is to be stored on the database
  // for later authentication (sorta)
  const hashedCode: any = await new Promise((resolve, reject) => {
    hash(code, saltRounds, (err, hash) => {
      if (err) reject(err);
      resolve(hash);
    });
  });

  return [code, hashedCode];
}
Example #5
Source File: updateUser.ts    From mayoor with MIT License 6 votes vote down vote up
UpdateUser = mutationField("updateUser", {
  type: "User",
  args: {
    id: idArg({ nullable: false }),
    input: arg({ type: UpdateUserInput, nullable: false }),
  },
  resolve: async (_, { id, input }, ctx) => {
    const { password, role, ...rest } = input;

    const user = await ctx.prisma.user.findOne({ where: { id } });

    if (!user?.canBeDeleted) {
      throw new ApolloError(
        "You cant change this users password.",
        "INVALID_OPERATION"
      );
    }

    if (password) {
      await ctx.prisma.user.update({
        where: { id },
        data: {},
      });
    }

    return ctx.prisma.user.update({
      where: { id },
      data: {
        ...rest,
        password: password ? await hash(password, 10) : undefined,
        role: role ?? undefined,
      },
    });
  },
})
Example #6
Source File: addUser.ts    From mayoor with MIT License 6 votes vote down vote up
AddUser = mutationField("addUser", {
  type: "User",
  args: {
    input: arg({ type: CreateUserInput, nullable: false }),
  },
  resolve: async (_, { input: { email, name, password, role } }, ctx) => {
    const existingUser = await ctx.prisma.user.findOne({ where: { email } });

    if (existingUser) {
      throw new Error(`User with email "${email}" already exists`);
    }

    const hashedPwd = await hash(password, 10);

    const defaultRole: NexusGenEnums["UserRole"] = "FACTORY";

    const user = await ctx.prisma.user.create({
      data: { password: hashedPwd, name, email, role: role || defaultRole },
    });

    return user;
  },
})
Example #7
Source File: changePassword.ts    From mayoor with MIT License 6 votes vote down vote up
ChangePassword = mutationField("changePassword", {
  type: "User",
  args: {
    oldPassword: stringArg({ nullable: false }),
    newPassword: stringArg({ nullable: false }),
  },
  resolve: async (_, { oldPassword, newPassword }, ctx) => {
    const { id } = await ctx.user.getCurrentUser();
    const user = await ctx.prisma.user.findOne({ where: { id } });

    if (!user) {
      throw new Error(`User with id "${id}" doesnt exist.`);
    }

    const isPasswordValid = await compare(oldPassword, user.password);

    if (!isPasswordValid) {
      throw new ApolloError("Incorrect old password", "INVALID_PASSWORD");
    }

    if (!user.canBeDeleted) {
      throw new ApolloError(
        "You cant change this users password.",
        "INVALID_OPERATION"
      );
    }

    const newHashedPwd = await hash(newPassword, 10);

    const updatedUser = ctx.prisma.user.update({
      where: { id },
      data: { password: newHashedPwd },
    });

    return updatedUser;
  },
})
Example #8
Source File: utils.ts    From MyAPI with MIT License 6 votes vote down vote up
comparePassword = async (password: string, hash: string) : Promise<boolean> => {
  return compare(password, hash)
}
Example #9
Source File: user.service.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
async updateUser(
    ctx: RequestContext,
    userId: number,
    input: UpdateUserInput,
  ): Promise<UserOutput> {
    this.logger.log(ctx, `${this.updateUser.name} was called`);

    this.logger.log(ctx, `calling ${UserRepository.name}.getById`);
    const user = await this.repository.getById(userId);

    // Hash the password if it exists in the input payload.
    if (input.password) {
      input.password = await hash(input.password, 10);
    }

    // merges the input (2nd line) to the found user (1st line)
    const updatedUser: User = {
      ...user,
      ...plainToClass(User, input),
    };

    this.logger.log(ctx, `calling ${UserRepository.name}.save`);
    await this.repository.save(updatedUser);

    return plainToClass(UserOutput, updatedUser, {
      excludeExtraneousValues: true,
    });
  }
Example #10
Source File: user.service.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
async createUser(
    ctx: RequestContext,
    input: CreateUserInput,
  ): Promise<UserOutput> {
    this.logger.log(ctx, `${this.createUser.name} was called`);

    const user = plainToClass(User, input);

    user.password = await hash(input.password, 10);

    this.logger.log(ctx, `calling ${UserRepository.name}.saveUser`);
    await this.repository.save(user);

    return plainToClass(UserOutput, user, {
      excludeExtraneousValues: true,
    });
  }
Example #11
Source File: ape-key.ts    From monkeytype with GNU General Public License v3.0 6 votes vote down vote up
export async function generateApeKey(
  req: MonkeyTypes.Request
): Promise<MonkeyResponse> {
  const { name, enabled } = req.body;
  const { uid } = req.ctx.decodedToken;
  const { maxKeysPerUser, apeKeyBytes, apeKeySaltRounds } =
    req.ctx.configuration.apeKeys;

  const currentNumberOfApeKeys = await ApeKeysDAL.countApeKeysForUser(uid);

  if (currentNumberOfApeKeys >= maxKeysPerUser) {
    throw new MonkeyError(409, "Maximum number of ApeKeys have been generated");
  }

  const apiKey = randomBytes(apeKeyBytes).toString("base64url");
  const saltyHash = await hash(apiKey, apeKeySaltRounds);

  const apeKey: MonkeyTypes.ApeKey = {
    _id: new ObjectId(),
    name,
    enabled,
    uid,
    hash: saltyHash,
    createdOn: Date.now(),
    modifiedOn: Date.now(),
    lastUsedOn: -1,
    useCount: 0,
  };

  const apeKeyId = await ApeKeysDAL.addApeKey(apeKey);

  return new MonkeyResponse("ApeKey generated", {
    apeKey: base64UrlEncode(`${apeKeyId}.${apiKey}`),
    apeKeyId,
    apeKeyDetails: cleanApeKey(apeKey),
  });
}
Example #12
Source File: password.service.ts    From svvs with MIT License 5 votes vote down vote up
/**
   * Return hash
   * @param password Plain password
   */
  getHash(password: string): Promise<string> {
    return hash(password, this.saltRounds)
  }
Example #13
Source File: login-routes.test.ts    From clean-ts-api with GNU General Public License v3.0 5 votes vote down vote up
describe('Login Routes', () => {
  beforeAll(async () => {
    app = await setupApp()
    await MongoHelper.connect(process.env.MONGO_URL)
  })

  afterAll(async () => {
    await MongoHelper.disconnect()
  })

  beforeEach(async () => {
    accountCollection = MongoHelper.getCollection('accounts')
    await accountCollection.deleteMany({})
  })

  describe('POST /signup', () => {
    test('Should return 200 on signup', async () => {
      await request(app)
        .post('/api/signup')
        .send({
          name: 'Rodrigo',
          email: '[email protected]',
          password: '123',
          passwordConfirmation: '123'
        })
        .expect(200)
      await request(app)
        .post('/api/signup')
        .send({
          name: 'Rodrigo',
          email: '[email protected]',
          password: '123',
          passwordConfirmation: '123'
        })
        .expect(403)
    })
  })

  describe('POST /login', () => {
    test('Should return 200 on login', async () => {
      const password = await hash('123', 12)
      await accountCollection.insertOne({
        name: 'Rodrigo',
        email: '[email protected]',
        password
      })
      await request(app)
        .post('/api/login')
        .send({
          email: '[email protected]',
          password: '123'
        })
        .expect(200)
    })

    test('Should return 401 on login', async () => {
      await request(app)
        .post('/api/login')
        .send({
          email: '[email protected]',
          password: '123'
        })
        .expect(401)
    })
  })
})
Example #14
Source File: user.model.ts    From nestjs-rest-sample with GNU General Public License v3.0 5 votes vote down vote up
// see: https://wanago.io/2020/05/25/api-nestjs-authenticating-users-bcrypt-passport-jwt-cookies/
// and https://stackoverflow.com/questions/48023018/nodejs-bcrypt-async-mongoose-login
async function preSaveHook(next) {
  // Only run this function if password was modified
  if (!this.isModified('password')) return next();

  // Hash the password
  const password = await hash(this.password, 12);
  this.set('password', password);

  next();
}
Example #15
Source File: password.service.ts    From amplication with Apache License 2.0 5 votes vote down vote up
hashPassword(password: string): Promise<string> {
    return hash(password, this.bcryptSaltRounds);
  }
Example #16
Source File: password.service.ts    From amplication with Apache License 2.0 5 votes vote down vote up
/**
   * @param password the password to be encrypted
   * @return encrypted password
   */
  hash(password: string): Promise<string> {
    return hash(password, this.salt);
  }
Example #17
Source File: login.test.ts    From clean-ts-api with GNU General Public License v3.0 4 votes vote down vote up
describe('Login GraphQL', () => {
  beforeAll(async () => {
    app = await setupApp()
    await MongoHelper.connect(process.env.MONGO_URL)
  })

  afterAll(async () => {
    await MongoHelper.disconnect()
  })

  beforeEach(async () => {
    accountCollection = MongoHelper.getCollection('accounts')
    await accountCollection.deleteMany({})
  })

  describe('Login Query', () => {
    const query = `query {
      login (email: "[email protected]", password: "123") {
        accessToken
        name
      }
    }`

    test('Should return an Account on valid credentials', async () => {
      const password = await hash('123', 12)
      await accountCollection.insertOne({
        name: 'Rodrigo',
        email: '[email protected]',
        password
      })
      const res = await request(app)
        .post('/graphql')
        .send({ query })
      expect(res.status).toBe(200)
      expect(res.body.data.login.accessToken).toBeTruthy()
      expect(res.body.data.login.name).toBe('Rodrigo')
    })

    test('Should return UnauthorizedError on invalid credentials', async () => {
      const res = await request(app)
        .post('/graphql')
        .send({ query })
      expect(res.status).toBe(401)
      expect(res.body.data).toBeFalsy()
      expect(res.body.errors[0].message).toBe('Unauthorized')
    })
  })

  describe('SignUp Mutation', () => {
    const query = `mutation {
      signUp (name: "Rodrigo", email: "[email protected]", password: "123", passwordConfirmation: "123") {
        accessToken
        name
      }
    }`

    test('Should return an Account on valid data', async () => {
      const res = await request(app)
        .post('/graphql')
        .send({ query })
      expect(res.status).toBe(200)
      expect(res.body.data.signUp.accessToken).toBeTruthy()
      expect(res.body.data.signUp.name).toBe('Rodrigo')
    })

    test('Should return EmailInUseError on invalid data', async () => {
      const password = await hash('123', 12)
      await accountCollection.insertOne({
        name: 'Rodrigo',
        email: '[email protected]',
        password
      })
      const res = await request(app)
        .post('/graphql')
        .send({ query })
      expect(res.status).toBe(403)
      expect(res.body.data).toBeFalsy()
      expect(res.body.errors[0].message).toBe('The received email is already in use')
    })
  })
})
Example #18
Source File: user.entity.ts    From codeclannigeria-backend with MIT License 4 votes vote down vote up
@pre<User>('save', async function () {
  try {
    (this as Writable<User>).password = await hash(this.password, 10);
  } catch (e) {
    throw new InternalServerErrorException(e);
  }
})
@index({ email: 1 }, { unique: true })
// @plugin(autopopulate as any)
export class User extends BaseEntity {
  @prop({
    required: true,
    maxlength: columnSize.length64,
    trim: true,
    text: true
  })
  readonly firstName!: string;
  @prop({
    required: true,
    maxlength: columnSize.length64,
    trim: true,
    text: true
  })
  readonly lastName!: string;
  @prop({
    required: true,
    maxlength: columnSize.length64,
    trim: true,
    lowercase: true,
    text: true,
    unique: false
  })
  readonly email!: string;
  @prop({
    maxlength: columnSize.length64,
    trim: true,
    text: true,
    default: null
  })
  readonly phoneNumber!: string;
  @prop({ default: null })
  readonly photoUrl: string = null;
  @prop({
    maxlength: columnSize.length128,
    trim: true,
    text: true,
    default: null
  })
  readonly description!: string;
  @prop({
    maxlength: columnSize.length64,
    trim: true,
    text: true,
    default: null
  })
  readonly city: string = null;
  @prop({
    maxlength: columnSize.length64,
    trim: true,
    text: true,
    default: null
  })
  readonly country: string = null;
  @prop({
    enum: Gender,
    type: String,
    default: Gender.UNSPECIFIED
  })
  readonly gender: Gender = Gender.UNSPECIFIED;
  @prop({ type: Date, default: null })
  readonly dob: Date = null;
  @prop({ type: String, default: null })
  readonly technologies: string[] = [];
  @prop({ required: true, maxlength: columnSize.length64 })
  @Exclude()
  readonly password!: string;
  @Exclude()
  @prop({ default: 0 })
  readonly loginAttemptCount!: number;
  @prop({
    enum: UserRole,
    type: String,
    required: true,
    default: UserRole.MENTEE
  })
  readonly role = UserRole.MENTEE;
  @prop({ required: true, default: false })
  readonly isEmailVerified: boolean;
  @prop({ default: undefined })
  readonly lockOutEndDate?: Date;
  @prop({ required: true, default: 0 })
  readonly failedSignInAttempts!: number;
  @prop({ ref: Track, default: [] })
  readonly tracks: Ref<Track>[] = [];
  @prop({ default: 0 })
  readonly notifyCount: number;
  @prop({ default: 0 })
  readonly notifUnreadCount: number;
  /**
   * Get User's full name
   *
   * @readonly
   * @memberof User
   */
  get fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
  setRandomPass(): void {
    (this as Writable<User>).password = crypto
      .randomBytes(columnSize.length32)
      .toString();
  }
  confirmEmail(): void {
    (this as Writable<User>).isEmailVerified = true;
  }
  static get model(): ReturnModelType<typeof User> {
    return getModelForClass(this);
  }
}