aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLarsVomMars2020-07-30 20:03:19 +0200
committerLarsVomMars2020-07-30 20:03:19 +0200
commit14aea28ac22e5d2e9e510c5986daca1bef1c43ae (patch)
tree7d117c9aacd2fff312f4df39373d5bc57c3b58be /src
parentf5f651d5180ddd12c57288d534129c8b00ff3162 (diff)
Added some more user db functions
Diffstat (limited to 'src')
-rw-r--r--src/db/DBController.ts10
-rw-r--r--src/db/tables.sql30
-rw-r--r--src/db/user.ts76
-rw-r--r--src/views/test.ejs13
4 files changed, 85 insertions, 44 deletions
diff --git a/src/db/DBController.ts b/src/db/DBController.ts
index cb714b3..0b212e7 100644
--- a/src/db/DBController.ts
+++ b/src/db/DBController.ts
@@ -1,5 +1,5 @@
import { Client } from "https://deno.land/x/mysql/mod.ts";
-import { readFileStr } from "https://deno.land/std/fs/mod.ts";
+import * as log from "https://deno.land/std/log/mod.ts";
export default class DBController {
private client?: Client;
@@ -7,13 +7,13 @@ export default class DBController {
async init() {
await this.connect();
try {
- const sql = await readFileStr("./src/db/tables.sql");
+ const sql = await Deno.readTextFile("./src/db/tables.sql");
const queries = sql.split(";");
queries.pop();
for (const query of queries) await this.execute(query);
- console.log("Tables created");
+ log.info("Tables created");
} catch (e) {
- console.error("Could not create tables");
+ log.error("Could not create tables");
throw e;
}
}
@@ -28,7 +28,7 @@ export default class DBController {
});
return this.client;
} catch (e) {
- console.error("Could not connect to database");
+ log.error("Could not connect to database");
throw e;
}
}
diff --git a/src/db/tables.sql b/src/db/tables.sql
index a0c9eef..a7c3838 100644
--- a/src/db/tables.sql
+++ b/src/db/tables.sql
@@ -1,19 +1,23 @@
# DROP TABLE IF EXISTS access;
# DROP TABLE IF EXISTS users;
-CREATE TABLE IF NOT EXISTS users (
- id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
- email VARCHAR(48) NOT NULL UNIQUE,
- username VARCHAR(24) NOT NULL UNIQUE,
- password VARCHAR(64) NOT NULL,
+CREATE TABLE IF NOT EXISTS users
+(
+ id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+ email VARCHAR(48) NOT NULL UNIQUE,
+ username VARCHAR(24) NOT NULL UNIQUE,
+ password VARCHAR(64) NOT NULL,
verification VARCHAR(64) NOT NULL UNIQUE,
- dark_theme BOOLEAN NOT NULL DEFAULT true,
- is_admin BOOLEAN NOT NULL DEFAULT false
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+ dark_theme BOOLEAN NOT NULL DEFAULT true,
+ is_admin BOOLEAN NOT NULL DEFAULT false
+) ENGINE = InnoDB
+ DEFAULT CHARSET = utf8;
-CREATE TABLE IF NOT EXISTS access (
- id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
- uid INT(6) UNSIGNED,
+CREATE TABLE IF NOT EXISTS access
+(
+ id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+ uid INT(6) UNSIGNED,
path VARCHAR(64) NOT NULL,
- FOREIGN KEY (uid) REFERENCES users(id) ON DELETE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+ FOREIGN KEY (uid) REFERENCES users (id) ON DELETE CASCADE
+) ENGINE = InnoDB
+ DEFAULT CHARSET = utf8;
diff --git a/src/db/user.ts b/src/db/user.ts
index 9152383..4e5a76c 100644
--- a/src/db/user.ts
+++ b/src/db/user.ts
@@ -3,6 +3,7 @@ import { hash, compare, genSalt } from "https://deno.land/x/bcrypt/mod.ts";
class User {
private controller: DBController;
+
constructor() {
this.controller = new DBController();
}
@@ -17,7 +18,7 @@ class User {
async createUser(email: string, username: string, password: string, isAdmin = false): Promise<boolean> {
const salt = await genSalt(12);
const passwordHash = await hash(password, salt);
- const verification = this.generateId();
+ const verification = User.generateId();
try {
await this.controller.execute(
"INSERT INTO users (email, username, password, verification, is_admin) VALUE (?, ?, ?, ?, ?)",
@@ -35,21 +36,22 @@ class User {
* @param plainTextPassword
*/
async login(username: string, plainTextPassword: string): Promise<loginData> {
- const { uid, password, verification, darkTheme } = (
- await this.controller.query(
- "SELECT id as uid, password, verification, dark_theme as darkTheme FROM users WHERE username = ?",
- [username]
- )
- )[0];
- if (compare(plainTextPassword, password)) {
+ try {
+ const { uid, password, verification, darkTheme } = (
+ await this.controller.query(
+ "SELECT id uid, password, verification, dark_theme darkTheme FROM users WHERE username = ?",
+ [username]
+ )
+ )[0]; // Will throw an error if user does not exist => good to go?
+ if (!compare(plainTextPassword, password)) return { success: false };
return {
success: true,
uid,
darkTheme,
verification,
};
- } else {
- return { success: false };
+ } catch (e) {
+ throw e;
}
}
@@ -59,15 +61,16 @@ class User {
* @param uid
* @param userVerification
*/
- async getUserByVerificationId(uid: number, userVerification: string): Promise<userData | undefined> {
+ async getUserByVerificationId(uid?: number, userVerification?: string): Promise<userData | undefined> {
try {
+ if (!uid || !userVerification || uid < 1 || userVerification.length !== 64) throw new TypeError("Wrong parameters");
const user = (
await this.controller.query(
"SELECT id, email, username, verification, dark_theme darkTheme, is_admin isAdmin FROM users WHERE id = ? AND verification = ?",
[uid, userVerification]
)
)[0];
- if (user) return user as userData;
+ return user as userData;
} catch (e) {
throw e;
}
@@ -86,6 +89,20 @@ class User {
}
/**
+ * Gets user theme
+ * @param uid
+ */
+ async getUserTheme(uid: number): Promise<boolean> {
+ try {
+ const users = await this.controller.query("SELECT dark_theme FROM users WHERE id = ?", [uid]);
+ if (users.length > 0) return users[0].dark_theme;
+ return true;
+ } catch (e) {
+ throw e;
+ }
+ }
+
+ /**
* Sets admin status of a user
* @param uid
* @param isAdmin
@@ -99,12 +116,45 @@ class User {
}
/**
+ *
+ * @param {number} uid
+ * @returns {Promise<boolean>}
+ */
+ async isAdmin(uid: number): Promise<boolean> {
+ try {
+ const user = (await this.controller.query("SELECT is_admin FROM users WHERE id = ?", [uid]))[0];
+ return user.is_admin;
+ } catch (e) {
+ throw e;
+ }
+ }
+
+ /**
+ *
+ * @param {number} uid
+ * @param {string} currentPassword
+ * @param {string} newPassword
+ * @returns {Promise<void>}
+ */
+ async changePassword(uid: number, currentPassword: string, newPassword: string) {
+ try {
+ const userPassword = (await this.controller.query("SELECT password FROM users WHERE id = ?", [uid]))[0];
+ if (!compare(currentPassword, userPassword)) throw new Error("Passwords do not match");
+ const salt = await genSalt(12);
+ const passwordHash = await hash(newPassword, salt);
+ await this.controller.execute("UPDATE users SET password = ? WHERE id = ?", [passwordHash, uid]);
+ } catch (e) {
+ throw e;
+ }
+ }
+
+ /**
* Generate random id
* @param len
* @private
*/
// TODO: Improve
- private generateId(len = 64): string {
+ static generateId(len = 64): string {
const values = new Uint8Array(len / 2);
crypto.getRandomValues(values);
return Array.from(values, (dec) => ("0" + dec.toString(36)).substr(-2)).join("");
diff --git a/src/views/test.ejs b/src/views/test.ejs
deleted file mode 100644
index b188db3..0000000
--- a/src/views/test.ejs
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="UTF-8" />
- <title>Title</title>
- </head>
- <body>
- <h1>Home :)</h1>
- <% if (name) { %>
- <h1>hello, <%= name %>!</h1>
- <% } %>
- </body>
-</html>