Skip to content

Commit

Permalink
save settings to db
Browse files Browse the repository at this point in the history
  • Loading branch information
targoninc-alex committed Jun 8, 2024
1 parent 8a3bd7e commit c05d9a3
Show file tree
Hide file tree
Showing 7 changed files with 104 additions and 2 deletions.
7 changes: 7 additions & 0 deletions src/enums/settings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export enum Settings {
notifications = "notifications",
systemNotifications = "systemNotifications",
sound = "sound",
currentSound = "currentSound",
currentCallSound = "currentCallSound",
}
36 changes: 36 additions & 0 deletions src/features/authentication/endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import Jimp from "jimp";
import {OwnUser} from "../../models/ownUser";
import {AdminPanelUser} from "../../models/adminPanelUser";
import {DefaultRoles} from "../../enums/defaultRoles";
import {Settings} from "../../enums/settings";

export class AuthEndpoints {
static logout(): (arg0: Request, arg1: Response) => void {
Expand Down Expand Up @@ -44,6 +45,14 @@ export class AuthEndpoints {
permissions = [];
}
user.permissions = permissions;
const rows = await db.getUserSettings(user.id);
if (rows) {
// @ts-ignore
user.settings = {};
for (const row of rows) {
user.settings[row.settingKey] = row.value;
}
}

res.send({ user });
};
Expand Down Expand Up @@ -521,6 +530,33 @@ export class AuthEndpoints {
}
}

static updateSetting(db: MariaDbDatabase) {
return async (req: Request, res: Response) => {
const user = req.user as User;
let {setting, value} = req.body;
if (!setting || value === null || value === undefined) {
res.status(400).send({error: "setting and value are required"});
return;
}

if (!Object.values(Settings).includes(setting)) {
res.status(400).send({error: `Invalid setting, must be one of ${Object.values(Settings).join(", ")}`});
return;
}

if (value === true) {
value = "true";
}
if (value === false) {
value = "false";
}

CLI.debug(`Updating setting ${setting} to ${value} for user ${user.id}`);
await db.updateUserSetting(user.id, setting, value);
res.send({message: "Setting updated successfully"});
}
}

static getConnectionSid() {
return (req: Request, res: Response) => {
let connectSid = req.headers.cookie?.split(';').find((c: string) => c.trim().startsWith('connect.sid='));
Expand Down
1 change: 1 addition & 0 deletions src/features/authenticationFeature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export class AuthenticationFeature {
app.patch(`${prefix}/updateUser`, AuthActions.checkAuthenticated, AuthEndpoints.updateUser(db));
app.post(`${prefix}/updateAvatar`, AuthActions.checkAuthenticated, AuthEndpoints.updateAvatar(db));
app.delete(`${prefix}/deleteUser`, AuthActions.checkAuthenticated, AuthEndpoints.deleteUser(db));
app.patch(`${prefix}/updateSetting`, AuthActions.checkAuthenticated, AuthEndpoints.updateSetting(db));
app.get(`${prefix}/getConnectionSid`, AuthActions.checkAuthenticated, AuthEndpoints.getConnectionSid());

// Permissions and roles
Expand Down
10 changes: 9 additions & 1 deletion src/features/database/mariaDbDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
Reaction,
ReactionGroup,
Role,
User
User, UserSetting
} from "./models";
import {SafeUser} from "../../models/safeUser";

Expand Down Expand Up @@ -317,4 +317,12 @@ WHERE ur.userId = ?`, [userId]);
async removeReaction(userId: Id, messageId: Id, reactionId: Id) {
await this.query("DELETE FROM venel.messageReactions WHERE userId = ? AND messageId = ? AND reactionId = ?", [userId, messageId, reactionId]);
}

async updateUserSetting(id: Id, setting: string, value: string) {
await this.query("INSERT INTO venel.userSettings (userId, settingKey, value) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE value = ?", [id, setting, value, value]);
}

async getUserSettings(id: Id): Promise<UserSetting[] | null> {
return await this.query("SELECT * FROM venel.userSettings WHERE userId = ?", [id]);
}
}
3 changes: 3 additions & 0 deletions src/models/ownUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,7 @@ import {Permission, Role, User} from "../features/database/models";
export interface OwnUser extends User {
'roles': Role[];
'permissions': Permission[];
'settings': {
[key: string]: any;
}
}
47 changes: 47 additions & 0 deletions src/swagger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,53 @@ export const swaggerOptions = {
]
}
},
"/api/auth/updateSetting": {
patch: {
summary: "Update a user's setting",
tags: [
"User Management"
],
description: "Update a user's setting",
requestBody: {
description: "Setting's entity",
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: [
"setting",
"value"
],
properties: {
setting: {
type: "string",
description: "The setting to update"
},
value: {
type: "string",
description: "The new value for the setting"
}
}
}
}
}
},
responses: {
200: {
description: "Setting updated successfully"
},
401: {
description: "Unauthorized"
}
},
security: [
{
cookieAuth: []
}
]
}
},
"/api/auth/roles": {
get: {
summary: "Get a list of roles",
Expand Down
2 changes: 1 addition & 1 deletion tools/apiBuilder.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from "fs";
import {swaggerOptions} from "../src/swagger.ts";
import {swaggerOptions} from "../src/swagger.js";

const start = `import {ApiBase} from "./ApiBase.mjs";
Expand Down

0 comments on commit c05d9a3

Please sign in to comment.