aboutsummaryrefslogtreecommitdiff
path: root/src/db/user.ts
diff options
context:
space:
mode:
authorMarvin Borner2020-07-18 22:37:00 +0200
committerMarvin Borner2020-07-18 22:38:45 +0200
commitaccb147b54bc99e5cd20059be5cb333031f15885 (patch)
tree8523ad288cb4fbf84acd6a646bd7c04957298bf4 /src/db/user.ts
parentd3c4b447c3d882a77282e32d9e12d7c3d4f034a2 (diff)
Added user registration
Co-authored-by: LarsVomMars <lars@kroenner.eu>
Diffstat (limited to 'src/db/user.ts')
-rw-r--r--src/db/user.ts64
1 files changed, 63 insertions, 1 deletions
diff --git a/src/db/user.ts b/src/db/user.ts
index c0cb127..3041c78 100644
--- a/src/db/user.ts
+++ b/src/db/user.ts
@@ -1,9 +1,71 @@
import DBController from "./DBController.ts";
+import { hash, compare, genSalt } from "https://deno.land/x/bcrypt/mod.ts";
class User {
- createUser() {
+ private controller: DBController;
+ constructor() {
+ this.controller = new DBController();
+ }
+
+ /**
+ * Creates new user
+ * @param email
+ * @param username
+ * @param password
+ * @param isAdmin
+ */
+ async createUser(email: string, username: string, password: string, isAdmin: boolean = false): Promise<boolean> {
+ const salt = await genSalt(12);
+ const passwordHash = await hash(password, salt);
+ const verification = this.generateId();
+ try {
+ await this.controller.execute(
+ "INSERT INTO users (email, username, password, verification, is_admin) VALUE (?, ?, ?, ?, ?)",
+ [email, username, passwordHash, verification, isAdmin]
+ );
+ return true;
+ } catch (e) {
+ throw e;
+ }
+ }
+ /**
+ * Checks if the user provided password is correct
+ * @param username
+ * @param password
+ */
+ async login(username: string, password: string) {
+ const dbUser = (
+ await this.controller.query(
+ "SELECT id, password, verification, dark_theme, is_admin FROM users WHERE username = ?",
+ [username]
+ )
+ )[0];
+ if (compare(password, dbUser.password)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Generate random id
+ * @param len
+ * @private
+ */
+ // TODO: Improve
+ private generateId(len: number = 64): string {
+ const values = new Uint8Array(len / 2);
+ crypto.getRandomValues(values);
+ return Array.from(values, (dec) => ("0" + dec.toString(36)).substr(-2)).join("");
}
}
export default new User();
+
+export interface loginData {
+ success: boolean;
+ uid?: number;
+ verification?: string;
+ darkTheme?: string;
+}