import {sendNotification} from 'web-push'; import {Entity, Unique, BaseEntity, PrimaryGeneratedColumn, Column, JoinTable, ManyToMany, TreeParent, TreeChildren} from 'typeorm'; import * as mailer from 'nodemailer'; import * as jwt from 'jsonwebtoken'; import {Workspace} from '../index'; import Group from './group'; import {hashSync, compareSync} from 'bcrypt'; @Entity() @Unique(['login']) export default class User extends BaseEntity{ @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() login: string; @Column() email: string; @Column() _password: string; @Column({ nullable: true }) _subscription: string | null; @Column({ nullable: true }) icon: string | null; @ManyToMany(type => Group, g=> g.users) groups: Group[] static workspace: Workspace static get(id: string|number): Promise { if(typeof id === 'number'){ return User.findOne({ id }); }else{ return User.findOne({ login: id }); } } static login(login: string, password: string): Promise { return new Promise(async (resolve, reject) => { const user: User = await User.findOne({ login }); if(compareSync(password, user._password)){ resolve(user); }else{ resolve(false); } }); } static authorize(token: string): Promise { return new Promise((resolve, reject) => { jwt.verify(token, User.workspace.jwtSecret, (err, payload) => { if(err){ resolve(undefined); }else{ const id = payload['userId']; const user = User.get(id); resolve(user); } }); }); } set password(password: string) { this._password = hashSync(password, 10); } token(expire: string = '7d'): string { return jwt.sign( { userId: this.id }, User.workspace.jwtSecret, {expiresIn: expire} ); } mail(message: any): Promise { message.to = this.email; message.from = User.workspace.mailFrom; return new Promise((resolve, reject) => { User.workspace.mailer.sendMail(message, (err, data) => { if(err) reject(err); resolve(data); }); }); } push(obj: {}): Promise<{}> { const subscription = JSON.parse(this._subscription); return sendNotification(subscription, JSON.stringify(obj)); } }