summary refs log tree commit diff
path: root/src/util/entities/BackupCodes.ts
blob: 81cdbb6d8df303bf1a45deefdc9dcc6be68d2c5e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm";
import { BaseClass } from "./BaseClass";
import { User } from "./User";
import crypto from "crypto";

@Entity("backup_codes")
export class BackupCode extends BaseClass {
	@JoinColumn({ name: "user_id" })
	@ManyToOne(() => User, { onDelete: "CASCADE" })
	user: User;

	@Column()
	code: string;

	@Column()
	consumed: boolean;

	@Column()
	expired: boolean;
}

export function generateMfaBackupCodes(user_id: string) {
	let backup_codes: BackupCode[] = [];
	for (let i = 0; i < 10; i++) {
		const code = BackupCode.create({
			user: { id: user_id },
			code: crypto.randomBytes(4).toString("hex"), // 8 characters
			consumed: false,
			expired: false,
		});
		backup_codes.push(code);
	}

	return backup_codes;
}