|
| 1 | +import { Entity, ManyToOne, PrimaryKey, Property } from '@mikro-orm/core' |
| 2 | +import User from './user' |
| 3 | +import crypto from 'crypto' |
| 4 | + |
| 5 | +const IV_LENGTH = 16 |
| 6 | + |
| 7 | +@Entity() |
| 8 | +export default class UserRecoveryCode { |
| 9 | + @PrimaryKey() |
| 10 | + id: number |
| 11 | + |
| 12 | + @ManyToOne(() => User) |
| 13 | + user: User |
| 14 | + |
| 15 | + @Property() |
| 16 | + code: string = this.generateCode() |
| 17 | + |
| 18 | + @Property() |
| 19 | + createdAt: Date = new Date() |
| 20 | + |
| 21 | + constructor(user: User) { |
| 22 | + this.user = user |
| 23 | + } |
| 24 | + |
| 25 | + generateCode(): string { |
| 26 | + const characters = 'ABCDEFGHIJKMNOPQRSTUVWXYZ0123456789' |
| 27 | + let code = '' |
| 28 | + |
| 29 | + for (let i = 0; i < 10; i++ ) { |
| 30 | + code += characters.charAt(Math.floor(Math.random() * characters.length)) |
| 31 | + } |
| 32 | + |
| 33 | + const iv = Buffer.from(crypto.randomBytes(IV_LENGTH)).toString('hex').slice(0, IV_LENGTH) |
| 34 | + const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(process.env.RECOVERY_CODES_SECRET), iv) |
| 35 | + let encrypted = cipher.update(code) |
| 36 | + |
| 37 | + encrypted = Buffer.concat([encrypted, cipher.final()]) |
| 38 | + return iv + ':' + encrypted.toString('hex') |
| 39 | + } |
| 40 | + |
| 41 | + getPlainCode(): string { |
| 42 | + const textParts: string[] = this.code.split(':') |
| 43 | + |
| 44 | + const iv = Buffer.from(textParts.shift(), 'binary') |
| 45 | + const encryptedText = Buffer.from(textParts.join(':'), 'hex') |
| 46 | + const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(process.env.RECOVERY_CODES_SECRET), iv) |
| 47 | + let decrypted = decipher.update(encryptedText) |
| 48 | + |
| 49 | + decrypted = Buffer.concat([decrypted, decipher.final()]) |
| 50 | + return decrypted.toString() |
| 51 | + } |
| 52 | + |
| 53 | + toJSON() { |
| 54 | + return this.getPlainCode() |
| 55 | + } |
| 56 | +} |
0 commit comments