54 lines
1.1 KiB
TypeScript
Raw Normal View History

import * as bcrypt from "bcrypt";
import { omit } from "lodash";
2018-09-02 02:57:55 -06:00
import {
Column,
Entity,
2018-09-04 14:50:08 -06:00
Index,
2018-09-02 02:57:55 -06:00
JoinTable,
ManyToMany,
2018-09-04 14:50:08 -06:00
PrimaryGeneratedColumn
2018-09-02 02:57:55 -06:00
} from "typeorm";
2018-08-12 11:55:15 +03:00
import { IUser } from "@common/httpApi";
2018-09-02 02:57:55 -06:00
import { SprinklersDevice } from "./SprinklersDevice";
const HASH_ROUNDS = 1;
@Entity()
2018-08-12 11:55:15 +03:00
export class User implements IUser {
2018-09-02 02:57:55 -06:00
@PrimaryGeneratedColumn()
id!: number;
2018-09-04 14:46:26 -06:00
@Column()
@Index("user_username_unique", { unique: true })
2018-09-02 02:57:55 -06:00
username: string = "";
2018-09-02 02:57:55 -06:00
@Column()
name: string = "";
2018-09-02 02:57:55 -06:00
@Column()
passwordHash: string = "";
2018-09-02 02:57:55 -06:00
@ManyToMany(type => SprinklersDevice)
@JoinTable({ name: "user_sprinklers_device" })
devices: SprinklersDevice[] | undefined;
2018-09-02 02:57:55 -06:00
constructor(data?: Partial<User>) {
if (data) {
Object.assign(this, data);
}
2018-09-02 02:57:55 -06:00
}
2018-09-02 02:57:55 -06:00
async setPassword(newPassword: string): Promise<void> {
this.passwordHash = await bcrypt.hash(newPassword, HASH_ROUNDS);
}
2018-09-02 02:57:55 -06:00
async comparePassword(password: string): Promise<boolean> {
return bcrypt.compare(password, this.passwordHash);
}
2018-09-02 02:57:55 -06:00
toJSON() {
return omit(this, "passwordHash");
}
}