|
|
@ -1,5 +1,8 @@ |
|
|
|
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity, OneToMany } from "typeorm"; |
|
|
|
import bcrypt from "bcrypt"; |
|
|
|
import jwt from "jsonwebtoken"; |
|
|
|
import { MovieTicket } from "./MovieTicket"; |
|
|
|
import Application from "@server/Application"; |
|
|
|
|
|
|
|
@Entity() |
|
|
|
export class User extends BaseEntity |
|
|
@ -21,4 +24,23 @@ export class User extends BaseEntity |
|
|
|
|
|
|
|
@OneToMany(() => User, user => user.movieTickets) |
|
|
|
movieTickets!: MovieTicket[]; |
|
|
|
|
|
|
|
/** |
|
|
|
* Authenticate a user and return an auth token upon success |
|
|
|
*/ |
|
|
|
public static async authenticate(email: string, password: string) { |
|
|
|
let user = <User>await User.findOne({ email }); |
|
|
|
if (user === undefined || !(await bcrypt.compare(password, user.password))) { |
|
|
|
return undefined; |
|
|
|
} |
|
|
|
return user.createJwtToken(Application.instance().APP_KEY); |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* Create an auth token for the user |
|
|
|
*/ |
|
|
|
public createJwtToken(key: string, expiresIn: number = 60*60*24) { |
|
|
|
let body = { id: this.id, name: this.name, isAdmin: this.isAdmin }; |
|
|
|
return jwt.sign(body, key, { expiresIn }); |
|
|
|
} |
|
|
|
} |