import { Entity, Column, PrimaryGeneratedColumn, BeforeInsert, OneToMany } from 'typeorm'; import * as bcrypt from 'bcryptjs'; import * as jwt from 'jsonwebtoken'; import { MapMarkerEntity } from '../mapmarkers/mapmarker.entity'; import { Game_PersonEntity } from '../game/game.entity'; @Entity('Person') export class PersonEntity { @PrimaryGeneratedColumn('uuid') id: string; @Column({type: 'text', unique: true}) name: string; @Column('text') password: string; @OneToMany(type => MapMarkerEntity, marker => marker.player) markers: MapMarkerEntity[]; @OneToMany(type => Game_PersonEntity, game_persons => game_persons.person) game_persons: Game_PersonEntity[]; // hashes the password before inserting it to database @BeforeInsert() async hashPassword() { this.password = await bcrypt.hash(this.password, 10); } // returns username and associated token tokenObject() { const {name, token} = this; return {name, token}; } // returns username and the id nameObject() { const {id, name} = this; return {id, name}; } async comparePassword(attempt: string) { return await bcrypt.compareSync(attempt, this.password); } private get token() { const {id, name} = this; return jwt.sign({ id, name }, process.env.SECRET, { expiresIn: '7d'}, ); } }