Implemented personal settings

This commit is contained in:
Torsten Schulz
2024-07-22 18:14:12 +02:00
parent cd0699f3fd
commit 89842ff6c5
34 changed files with 899 additions and 113 deletions

View File

@@ -4,6 +4,7 @@ import { fileURLToPath } from 'url';
import chatRouter from './routers/chatRouter.js';
import authRouter from './routers/authRouter.js';
import navigationRouter from './routers/navigationRouter.js'
import settingsRouter from './routers/settingsRouter.js';
import cors from 'cors';
const __filename = fileURLToPath(import.meta.url);
@@ -17,6 +18,7 @@ app.use(express.json()); // To handle JSON request bodies
app.use('/api/chat', chatRouter);
app.use('/api/auth', authRouter);
app.use('/api/navigation', navigationRouter);
app.use('/api/settings', settingsRouter);
app.use('/images', express.static(path.join(__dirname, '../frontend/public/images')));
app.use((req, res) => {

View File

@@ -21,6 +21,7 @@ export const login = async (req, res) => {
if (error.message === 'credentialsinvalid') {
res.status(404).json({ error: error.message })
} else {
console.log(error);
res.status(500).json({ error: error.message });
}
}

View File

@@ -0,0 +1,113 @@
import UserParamType from '../models/type/user_param.js';
import SettingsType from '../models/type/settings.js';
import UserParam from '../models/community/user_param.js';
import User from '../models/community/user.js';
import UserParamValue from '../models/type/user_param_value.js';
export const filterSettings = async (req, res) => {
const { userid, type } = req.body;
console.log(userid, type);
try {
const fields = await UserParamType.findAll({
include: [
{
model: SettingsType,
as: 'settings_type',
where: { name: type }
},
{
model: UserParam,
as: 'user_params',
required: false,
include: [
{
model: User,
as: 'user',
where: { hashedId: userid }
}
]
}
]
});
const responseFields = await Promise.all(fields.map(async (field) => {
const options = ['singleselect', 'multiselect'].includes(field.datatype) ? await UserParamValue.findAll({
where: { userParamTypeId: field.id }
}) : [];
return {
id: field.id,
name: field.description,
minAge: field.minAge,
gender: field.gender,
datatype: field.datatype,
value: field.user_params.length > 0 ? field.user_params[0].value : null,
options: options.map(opt => ({ id: opt.id, value: opt.value }))
};
}));
res.status(200).json(responseFields);
} catch (error) {
console.error('Error fetching settings:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
export const updateSetting = async (req, res) => {
const { userid, settingId, value } = req.body;
try {
const user = await User.findOne({ where: { hashedId: userid } });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const paramType = await UserParamType.findOne({ where: { id: settingId } });
if (!paramType) {
return res.status(404).json({ error: 'Parameter type not found' });
}
console.log(value);
await UserParam.upsertParam(user.id, paramType.id, value);
res.status(200).json({ message: 'Setting updated successfully' });
} catch (error) {
console.error('Error updating user setting:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
export const getTypeParamValueId = async(req, res) => {
const { paramValue } = req.body;
const userParamValueObject = await UserParamValue.findOne({
where: { value: paramValue }
});
if (!userParamValueObject) {
res.status(404).json({ error: "notfound" });
return;
}
res.status(200).json({ paramValueId: userParamValueObject.id });
};
export const getTypeParamValues = async(req, res) => {
const { type } = req.body;
const userParamValues = await UserParamValue.findAll({
include: [
{
model: UserParamType,
as: 'user_param_type',
where: { description: type }
}
]
});
res.status(200).json(userParamValues.map(type => { return { id: type.dataValues.id, name: type.dataValues.value}}));
}
export const getTypeParamValue = async(req, res) => {
const { id } = req.param;
const userParamValueObject = await UserParamValue.findOne({
where: { id: id }
});
if (!userParamValueObject) {
res.status(404).json({ error: "notfound" });
return;
}
res.status(200).json({ paramValueId: userParamValueObject.value });
};

View File

@@ -0,0 +1,24 @@
import User from './community/user.js';
import UserParam from './community/user_param.js';
import UserParamType from './type/user_param.js';
import UserRightType from './type/user_right.js';
import UserRight from './community/user_right.js';
import SettingsType from './type/settings.js';
import UserParamValue from './type/user_param_value.js';
export default function setupAssociations() {
SettingsType.hasMany(UserParamType, { foreignKey: 'settingsId', as: 'user_param_types' });
UserParamType.belongsTo(SettingsType, { foreignKey: 'settingsId', as: 'settings_type' });
UserParamType.hasMany(UserParam, { foreignKey: 'paramTypeId', as: 'user_params' });
UserParam.belongsTo(UserParamType, { foreignKey: 'paramTypeId', as: 'paramType' });
UserParam.belongsTo(SettingsType, { foreignKey: 'settingsId', as: 'settings' });
UserParam.belongsTo(User, { foreignKey: 'userId', as: 'user' });
UserRight.belongsTo(User, { foreignKey: 'userId' });
UserRight.belongsTo(UserRightType, { foreignKey: 'rightTypeId', as: 'rightType' });
UserParamType.hasMany(UserParamValue, { foreignKey: 'userParamTypeId', as: 'user_param_values' });
UserParamValue.belongsTo(UserParamType, { foreignKey: 'userParamTypeId', as: 'user_param_type' });
}

View File

@@ -2,6 +2,7 @@ import { sequelize } from '../../utils/sequelize.js';
import { DataTypes } from 'sequelize';
import bcrypt from 'bcrypt';
import { encrypt, generateIv } from '../../utils/encryption.js';
import crypto from 'crypto';
const User = sequelize.define('user', {
email: {
@@ -49,7 +50,14 @@ const User = sequelize.define('user', {
}, {
tableName: 'user',
schema: 'community',
underscored: true
underscored: true,
hooks: {
afterCreate: async (user, options) => {
const hashedId = crypto.createHash('sha256').update(user.id.toString()).digest('hex');
user.hashedId = hashedId;
await user.save();
}
}
});
export default User;

View File

@@ -26,9 +26,25 @@ const UserParam = sequelize.define('user_param', {
allowNull: false,
set(value) {
if (value) {
try {
const iv = generateIv();
console.log(value);
this.setDataValue('iv', iv.toString('hex'));
this.setDataValue('value', encrypt(value, iv));
} catch (error) {
console.log('Error setting value:', error);
this.setDataValue('value', '');
}
}
},
get() {
try {
const value = this.getDataValue('value');
const iv = Buffer.from(this.getDataValue('iv'), 'hex');
return decrypt(value, iv);
} catch (error) {
console.log('Error getting value:', error);
return '';
}
}
},
@@ -40,31 +56,29 @@ const UserParam = sequelize.define('user_param', {
tableName: 'user_param',
schema: 'community',
underscored: true,
hooks: {
beforeSave: (userParam) => {
if (userParam.value && !userParam.iv) {
const iv = generateIv();
userParam.iv = iv.toString('hex');
userParam.value = encrypt(userParam.value, iv);
}
},
afterFind: (userParams) => {
if (userParams) {
if (Array.isArray(userParams)) {
userParams.forEach((userParam) => {
const iv = Buffer.from(userParam.iv, 'hex');
userParam.value = decrypt(userParam.value, iv);
});
} else {
const iv = Buffer.from(userParams.iv, 'hex');
userParams.value = decrypt(userParams.value, iv);
}
}
}
indexes: [
{
unique: true,
fields: ['user_id', 'param_type_id']
}
]
});
UserParam.belongsTo(User, { foreignKey: 'userId' });
UserParam.belongsTo(UserParamType, { foreignKey: 'paramTypeId' });
UserParam.upsertParam = async function (userId, paramTypeId, value) {
try {
const [userParam, created] = await UserParam.findOrCreate({
where: { userId, paramTypeId },
defaults: { value }
});
if (!created) {
userParam.value = value;
await userParam.save();
}
} catch (error) {
console.error('Error in upsertParam:', error);
throw error;
}
};
export default UserParam;

View File

@@ -26,7 +26,4 @@ const UserRight = sequelize.define('user_right', {
underscored: true,
});
UserRight.belongsTo(User, { foreignKey: 'userId' });
UserRight.belongsTo(UserRightType, { foreignKey: 'rightTypeId', as: 'rightType' });
export default UserRight;

View File

@@ -4,7 +4,8 @@ import UserParamType from './type/user_param.js';
import Login from './logs/login.js';
import UserRightType from './type/user_right.js';
import UserRight from './community/user_right.js';
import SettingsType from './type/settings_type.js';
import SettingsType from './type/settings.js';
import UserParamValue from './type/user_param_value.js';
const models = {
User,
@@ -14,6 +15,7 @@ const models = {
UserRightType,
UserRight,
SettingsType,
UserParamValue,
};
export default models;

View File

@@ -1,7 +1,7 @@
import { sequelize } from '../../utils/sequelize.js';
import { DataTypes } from 'sequelize';
const SettingsType = sequelize.define('settings_type', {
const Settings = sequelize.define('settings_type', {
name: {
type: DataTypes.STRING,
allowNull: false
@@ -12,4 +12,4 @@ const SettingsType = sequelize.define('settings_type', {
underscored: true
});
export default SettingsType;
export default Settings;

View File

@@ -1,6 +1,5 @@
import { sequelize } from '../../utils/sequelize.js';
import { DataTypes } from 'sequelize';
import SettingsType from './settings_type.js';
const UserParamType = sequelize.define('user_param_type', {
description: {
@@ -20,20 +19,18 @@ const UserParamType = sequelize.define('user_param_type', {
allowNull: false,
defaultValue: 'string'
},
settingsTypeId: {
settingsId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: SettingsType,
model: 'settings',
key: 'id'
}
},
}
}, {
tableName: 'user_param',
schema: 'type',
underscored: true
});
UserParamType.belongsTo(SettingsType, { foreignKey: 'settingsTypeId' });
export default UserParamType;

View File

@@ -0,0 +1,22 @@
import { sequelize } from '../../utils/sequelize.js';
import { DataTypes } from 'sequelize';
import UserParam from './user_param.js';
const UserParamValue = sequelize.define('user_param_value', {
userParamTypeId: {
type: DataTypes.INTEGER,
allowNull: false
},
value: {
type: DataTypes.STRING,
allowNull: false
}
},
{
tableName: 'user_param_value',
schema: 'type',
underscored: true
}
);
export default UserParamValue;

View File

@@ -0,0 +1,11 @@
import { Router } from 'express';
import { filterSettings, updateSetting, getTypeParamValueId, getTypeParamValues, getTypeParamValue } from '../controllers/settingsController.js';
const settingsRouter = Router();
settingsRouter.post('/filter', filterSettings);
settingsRouter.post('/update', updateSetting);
settingsRouter.post('/getparamvalueid', getTypeParamValueId);
settingsRouter.post('/getparamvalues', getTypeParamValues);
settingsRouter.post('/getparamvalue/:id', getTypeParamValue);
export default settingsRouter;

View File

@@ -12,11 +12,11 @@ const saltRounds = 10;
export const registerUser = async ({ email, username, password, language }) => {
const iv = generateIv();
const encryptedEmail = encrypt(email, iv);
console.log(email, iv, process.env.SECRET_KEY);
const results = await sequelize.query(
`SELECT * FROM "community"."user" WHERE public.pgp_sym_decrypt("email"::bytea, :key::text) = :email`,
`SELECT * FROM "community"."user" WHERE "email" = :email`,
{
replacements: { key: process.env.SECRET_KEY, email },
replacements: { key: process.env.SECRET_KEY, email: encryptedEmail },
type: sequelize.QueryTypes.SELECT
}
);
@@ -62,7 +62,6 @@ export const loginUser = async ({ username, password }) => {
throw new Error('credentialsinvalid');
}
const match = await bcrypt.compare(password, user.password);
console.log(match, password, user.password, await bcrypt.hash(password, saltRounds));
if (!match) {
throw new Error('credentialsinvalid');
}
@@ -72,12 +71,25 @@ export const loginUser = async ({ username, password }) => {
},
include: {
model: UserParamType,
as: 'paramType',
where: {
description: ['birthdate', 'gender']
}
}
});
return { id: user.hashedId, username: user.username, active: user.active, forwardDataInput: neededParams.length < 2 };
const language = await UserParam.findOne({
where: {
userId: user.id
},
include: {
model: UserParamType,
as: 'paramType',
where: {
description: 'language'
}
}
});
return { id: user.hashedId, username: user.username, active: user.active, forwardDataInput: neededParams.length < 2, language: language.value };
};
export const handleForgotPassword = async ({ email }) => {

View File

@@ -1,32 +1,23 @@
import crypto from 'crypto';
import dotenv from 'dotenv';
dotenv.config(); // Laden der Umgebungsvariablen
const algorithm = 'aes-256-cbc';
const secretKey = process.env.SECRET_KEY;
if (!secretKey || secretKey.length !== 32) {
throw new Error('SECRET_KEY length must be 32 bytes');
}
const encrypt = (text, iv) => {
const cipher = crypto.createCipheriv(algorithm, Buffer.from(secretKey, 'utf-8'), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return encrypted.toString('hex');
};
const decrypt = (encryptedText, iv) => {
const encryptedBuffer = Buffer.from(encryptedText, 'hex');
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(secretKey, 'utf-8'), iv);
let decrypted = decipher.update(encryptedBuffer);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
};
const generateIv = () => {
export const generateIv = () => {
return crypto.randomBytes(16);
};
export { encrypt, decrypt, generateIv };
export const encrypt = (text, iv) => {
const cipher = crypto.createCipheriv(algorithm, Buffer.from(secretKey, 'utf-8'), iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
};
export const decrypt = (text, iv) => {
console.log(text, secretKey, iv);
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(secretKey, 'utf-8'), iv);
let decrypted = decipher.update(text, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
};

View File

@@ -1,4 +1,4 @@
import SettingsType from "../models/type/settings_type.js";
import SettingsType from "../models/type/settings.js";
const initializeSettings = async () => {
await SettingsType.findOrCreate({

View File

@@ -1,5 +1,6 @@
import UserParamType from '../models/type/user_param.js';
import SettingsType from '../models/type/settings_type.js'; // Importiere SettingsType
import SettingsType from '../models/type/settings.js';
import UserParamValue from '../models/type/user_param_value.js';
const initializeTypes = async () => {
const settingsTypes = await SettingsType.findAll();
@@ -9,78 +10,141 @@ const initializeTypes = async () => {
}, {});
const getSettingsTypeId = (name) => settingsTypeMap[name];
console.log(settingsTypeMap, getSettingsTypeId('personal'));
const getUserParamTypeId = async(name) => {
const userParamType = await UserParamType.findOne({
where: {
description: name
}
});
return userParamType.id;
};
await UserParamType.findOrCreate({
where: { description: 'language' },
defaults: { description: 'language', datatype: 'string', settingsTypeId: getSettingsTypeId('personal') }
defaults: { description: 'language', datatype: 'singleselect', settingsId: getSettingsTypeId('personal') }
});
await UserParamType.findOrCreate({
where: { description: 'birthdate' },
defaults: { description: 'birthdate', datatype: 'date', settingsTypeId: getSettingsTypeId('personal') }
defaults: { description: 'birthdate', datatype: 'date', settingsId: getSettingsTypeId('personal') }
});
await UserParamType.findOrCreate({
where: { description: 'zip' },
defaults: { description: 'zip', datatype: 'string', settingsTypeId: getSettingsTypeId('personal') }
defaults: { description: 'zip', datatype: 'string', settingsId: getSettingsTypeId('personal') }
});
await UserParamType.findOrCreate({
where: { description: 'town' },
defaults: { description: 'town', datatype: 'string', settingsTypeId: getSettingsTypeId('personal') }
defaults: { description: 'town', datatype: 'string', settingsId: getSettingsTypeId('personal') }
});
await UserParamType.findOrCreate({
where: { description: 'bodyheight' },
defaults: { description: 'bodyheight', datatype: 'float', settingsTypeId: getSettingsTypeId('view') }
defaults: { description: 'bodyheight', datatype: 'float', settingsId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'weight' },
defaults: { description: 'weight', datatype: 'float', settingsTypeId: getSettingsTypeId('view') }
defaults: { description: 'weight', datatype: 'float', settingsId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'eyecolor' },
defaults: { description: 'eyecolor', datatype: 'string', settingsTypeId: getSettingsTypeId('view') }
defaults: { description: 'eyecolor', datatype: 'string', settingsId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'haircolor' },
defaults: { description: 'haircolor', datatype: 'string', settingsTypeId: getSettingsTypeId('view') }
defaults: { description: 'haircolor', datatype: 'string', settingsId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'hairlength' },
defaults: { description: 'hairlength', datatype: 'int', settingsTypeId: getSettingsTypeId('view') }
defaults: { description: 'hairlength', datatype: 'int', settingsId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'skincolor' },
defaults: { description: 'skincolor', datatype: 'int', settingsTypeId: getSettingsTypeId('view') }
defaults: { description: 'skincolor', datatype: 'int', settingsId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'freckles' },
defaults: { description: 'freckles', datatype: 'int', settingsTypeId: getSettingsTypeId('view') }
defaults: { description: 'freckles', datatype: 'int', settingsId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'piercings' },
defaults: { description: 'piercings', datatype: 'bool', settingsTypeId: getSettingsTypeId('view') }
defaults: { description: 'piercings', datatype: 'bool', settingsId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'tattoos' },
defaults: { description: 'tattoos', datatype: 'bool', settingsTypeId: getSettingsTypeId('view') }
defaults: { description: 'tattoos', datatype: 'bool', settingsId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'sexualpreference' },
defaults: { description: 'sexualpreference', minAge: 14, datatype: 'int', settingsTypeId: getSettingsTypeId('sexuality') }
defaults: { description: 'sexualpreference', minAge: 14, datatype: 'int', settingsId: getSettingsTypeId('sexuality') }
});
await UserParamType.findOrCreate({
where: { description: 'gender' },
defaults: { description: 'gender', datatype: 'string', settingsTypeId: getSettingsTypeId('personal') }
defaults: { description: 'gender', datatype: 'singleselect', settingsId: getSettingsTypeId('personal') }
});
await UserParamType.findOrCreate({
where: { description: 'pubichair' },
defaults: { description: 'pubichair', minAge: 14, datatype: 'int', settingsTypeId: getSettingsTypeId('sexuality') }
defaults: { description: 'pubichair', minAge: 14, datatype: 'int', settingsId: getSettingsTypeId('sexuality') }
});
await UserParamType.findOrCreate({
where: { description: 'penislength' },
defaults: { description: 'penislength', minAge: 14, gender: 'm', datatype: 'int', settingsTypeId: getSettingsTypeId('sexuality') }
defaults: { description: 'penislength', minAge: 14, gender: 'm', datatype: 'int', settingsId: getSettingsTypeId('sexuality') }
});
await UserParamType.findOrCreate({
where: { description: 'brasize' },
defaults: { description: 'brasize', minAge: 14, gender: 'f', datatype: 'string', settingsTypeId: getSettingsTypeId('sexuality') }
defaults: { description: 'brasize', minAge: 14, gender: 'f', datatype: 'string', settingsId: getSettingsTypeId('sexuality') }
});
const genderId = await getUserParamTypeId('gender');
await UserParamValue.findOrCreate({
where: {
userParamTypeId: genderId,
value: 'male'
},
defaults: { userParamTypeId: genderId, value: 'male' }
});
await UserParamValue.findOrCreate({
where: {
userParamTypeId: genderId,
value: 'female'
},
defaults: { userParamTypeId: genderId, value: 'female' }
});
await UserParamValue.findOrCreate({
where: {
userParamTypeId: genderId,
value: 'transfemale'
},
defaults: { userParamTypeId: genderId, value: 'transfemale' }
});
await UserParamValue.findOrCreate({
where: {
userParamTypeId: genderId,
value: 'transmale'
},
defaults: { userParamTypeId: genderId, value: 'transmale' }
});
await UserParamValue.findOrCreate({
where: {
userParamTypeId: genderId,
value: 'nonbinary'
},
defaults: { userParamTypeId: genderId, value: 'nonbinary' }
});
const languageId = await getUserParamTypeId('language');
await UserParamValue.findOrCreate({
where: {
userParamTypeId: languageId,
value: 'de'
},
defaults: { userParamTypeId: languageId, value: 'de' }
});
await UserParamValue.findOrCreate({
where: {
userParamTypeId: languageId,
value: 'en'
},
defaults: { userParamTypeId: languageId, value: 'en' }
});
};

View File

@@ -2,10 +2,19 @@ import { initializeDatabase } from './sequelize.js';
import initializeTypes from './initializeTypes.js';
import initializeSettings from './initializeSettings.js';
import initializeUserRights from './initializeUserRights.js';
import setupAssociations from '../models/associations.js';
import models from '../models/index.js';
const syncDatabase = async () => {
try {
await initializeDatabase();
for (const model of Object.values(models)) {
await model.sync({ alter: true });
}
setupAssociations();
for (const model of Object.values(models)) {
await model.sync({ alter: true });
}
await initializeSettings();
await initializeTypes();
await initializeUserRights();

View File

@@ -0,0 +1,100 @@
<template>
<div class="settings-widget">
<h2>{{ $t("settings.personal.title") }}</h2>
<template v-for="setting in settings">
<InputStringWidget v-if="setting.datatype == 'string'"
:labelTr="`settings.personal.label.${setting.name}`"
:tooltipTr="`settings.personal.tooltip.${setting.name}`" :value=setting.value :list="languagesList()"
@input="handleInput(setting.id, $event)" />
<DateInputWidget v-else-if="setting.datatype == 'date'" :labelTr="`settings.personal.label.${setting.name}`"
:tooltipTr="`settings.personal.tooltip.${setting.name}`" :value=setting.value
@input="handleInput(setting.id, $event)" />
<SelectDropdownWidget v-else-if="setting.datatype == 'singleselect'"
:labelTr="`settings.personal.label.${setting.name}`"
:tooltipTr="`settings.personal.tooltip.${setting.name}`" :value=setting.value
:list="getSettingOptions(setting.name, setting.options)" @input="handleInput(setting.id, $event)" />
<div v-else>{{ setting }}
</div>
</template>
</div>
</template>
<script>
import apiClient from '@/utils/axios.js';
import { mapGetters } from 'vuex';
import InputStringWidget from '@/components/form/InputStringWidget.vue';
import DateInputWidget from '@/components/form/DateInputWidget.vue';
import SelectDropdownWidget from '@/components/form/SelectDropdownWidget';
export default {
name: "SettingsWidget",
components: {
InputStringWidget,
DateInputWidget,
SelectDropdownWidget,
},
props: {
settingsType: {
type: String,
required: true
}
},
computed: {
...mapGetters(['user']),
},
async mounted() {
await this.fetchSettings();
},
methods: {
async fetchSettings() {
if (this.user && this.user.id) {
try {
const userid = this.user.id;
const response = await apiClient.post('/api/settings/filter', {
userid: userid,
type: this.settingsType
});
this.settings = response.data;
} catch (err) {
this.settings = [];
}
}
},
getSettingOptions(fieldName, options) {
return options.map((option) => {
return {
value: option.id,
captionTr: `settings.personal.${fieldName}.${option.value}`
}
});
},
async handleInput(settingId, value) {
if (['object', 'array'].includes(typeof value)) {
return;
}
try {
const userid = this.user.id;
await apiClient.post('/api/settings/update', {
userid: userid,
settingId: settingId,
value: value
});
console.log('Setting updated:', settingId, value);
} catch (err) {
console.error('Error updating setting:', err);
}
},
languagesList() {
return [
{ value: 'en', captionTr: 'settings.personal.languages.en' },
{ value: 'de', captionTr: 'settings.personal.languages.de' },
];
}
},
data() {
return {
settings: [],
};
}
};
</script>

View File

@@ -0,0 +1,48 @@
<template>
<label>
<input type="checkbox" :checked="value" @change="updateValue($event.target.checked)" :title="$t(tooltipTr)" />
<span :style="{ width: width + 'em' }">{{ $t(labelTr) }}</span>
</label>
</template>
<script>
export default {
name: "CheckboxWidget",
props: {
labelTr: {
type: String,
required: true,
},
value: {
type: Boolean,
required: false,
default: false
},
tooltipTr: {
type: String,
required: true,
},
width: {
type: Number,
required: false,
default: 10
}
},
methods: {
updateValue(checked) {
this.$emit("input", checked);
}
}
};
</script>
<style scoped>
label {
display: flex;
align-items: center;
}
input[type="checkbox"] {
margin-right: 0.5em;
}
</style>

View File

@@ -0,0 +1,67 @@
<template>
<label>
<span :style="{ width: width + 'em' }">{{ $t(labelTr) }}</span>
<input type="date" v-model="internalValue" :placeholder="$t(labelTr)" :title="$t(tooltipTr)"
@change="updateValue($event.target.value)" />
</label>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
name: "DateInputWidget",
props: {
labelTr: {
type: String,
required: true,
},
value: {
type: String,
required: false,
},
tooltipTr: {
type: String,
required: true,
},
width: {
type: Number,
required: false,
default: 10
}
},
data() {
return {
internalValue: this.value
}
},
watch: {
value(newValue) {
this.internalValue = newValue;
}
},
computed: {
...mapGetters(['language']),
},
methods: {
updateValue(value) {
this.internalValue = value;
this.$emit("input", value);
}
}
};
</script>
<style scoped>
label {
display: block;
}
label>span {
display: inline-block;
}
input {
margin-left: 0.5em;
}
</style>

View File

@@ -0,0 +1,67 @@
<template>
<label>
<span :style="{ width: width + 'em' }">{{ $t(labelTr) }}</span>
<input type="number" :value="formattedValue" :placeholder="$t(labelTr)" :title="$t(tooltipTr)"
@input="updateValue($event.target.value)" :step="step" />
<span v-if="postfix">{{ postfix }}</span>
</label>
</template>
<script>
export default {
name: "FloatInputWidget",
props: {
labelTr: {
type: String,
required: true,
},
value: {
type: Number,
required: false,
},
tooltipTr: {
type: String,
required: true,
},
width: {
type: Number,
required: false,
default: 10
},
decimals: {
type: Number,
required: false,
default: 2
},
postfix: {
type: String,
required: false,
default: ''
}
},
computed: {
formattedValue() {
return this.value != null ? this.value.toFixed(this.decimals) : '';
},
step() {
return Math.pow(10, -this.decimals);
}
},
methods: {
updateValue(value) {
this.$emit("input", parseFloat(value).toFixed(this.decimals));
}
}
};
</script>
<style scoped>
label {
display: flex;
align-items: center;
}
input {
margin-right: 0.5em;
}
</style>

View File

@@ -0,0 +1,45 @@
<template>
<label>
<span :style="{ width: width + 'em' }">{{ $t(labelTr) }}</span>
<input type="number" :value="value" :title="$t(tooltipTr)" :min="min" :max="max"
@input="updateValue($event.target.value)" />
</label>
</template>
<script>
export default {
name: "InputNumberWidget",
props: {
labelTr: {
type: String,
required: true,
},
value: {
type: Number,
required: false,
},
tooltipTr: {
type: String,
required: true,
},
width: {
type: Number,
required: false,
default: 10
},
min: {
type: Number,
required: false
},
max: {
type: Number,
required: false
}
},
methods: {
updateValue(value) {
this.$emit("input", parseFloat(value));
}
}
};
</script>

View File

@@ -0,0 +1,65 @@
<template>
<label>
<span :style="{ width: width + 'em' }">{{ $t(labelTr) }}</span>
<input type="text" :value="value" :placeholder="$t(labelTr)" :title="$t(tooltipTr)"
@input="validateAndUpdate($event.target.value)" />
</label>
</template>
<script>
export default {
name: "InputStringWidget",
props: {
labelTr: {
type: String,
required: true,
},
value: {
type: String,
required: false,
},
tooltipTr: {
type: String,
required: true,
},
width: {
type: Number,
required: false,
default: 10
},
regex: {
type: String,
required: false,
default: null
}
},
methods: {
validateAndUpdate(value) {
if (this.regex) {
const pattern = new RegExp(this.regex);
if (pattern.test(value)) {
this.updateValue(value);
}
} else {
this.updateValue(value);
}
},
updateValue(value) {
this.$emit("input", value);
}
}
};
</script>
<style scoped>
label {
display: block;
}
label > span {
display: inline-block;
}
input {
margin-left: 0.5em;
}
</style>

View File

@@ -0,0 +1,69 @@
<template>
<label>
<span :style="{ width: width + 'em' }">{{ $t(labelTr) }}</span>
<select :title="$t(tooltipTr)" :value="value" @change="updateValue($event.target.value)">
<option v-if="allowNone" :value="noneValue">{{ $t('none') }}</option>
<option v-for="item in list" :key="item.value" :value="item.value">
{{ item.captionTr ? $t(item.captionTr) : item.caption }}
</option>
</select>
</label>
</template>
<script>
export default {
name: "SelectDropdownWidget",
props: {
labelTr: {
type: String,
required: true,
},
value: {
type: String,
required: false,
},
tooltipTr: {
type: String,
required: true,
},
width: {
type: Number,
required: false,
default: 10
},
list: {
type: Array,
required: true,
},
allowNone: {
type: Boolean,
required: false,
default: false
},
noneValue: {
type: String,
required: false,
default: ''
}
},
methods: {
updateValue(value) {
this.$emit("input", value);
}
}
};
</script>
<style scoped>
label {
display: block;
}
label>span {
display: inline-block;
}
select {
margin-left: 0.5em;
}
</style>

View File

@@ -15,12 +15,8 @@
<div>
<label>{{ $t("register.repeatPassword") }}<input type="password" v-model="repeatPassword" /></label>
</div>
<div>
<label>{{ $t("register.language") }}<select v-model="language">
<option value="en">{{ $t("register.languages.en") }}</option>
<option value="de">{{ $t("register.languages.de") }}</option>
</select></label>
</div>
<SelectDropdownWidget labelTr="settings.personal.label.language" :v-model="language"
tooltipTr="settings.personal.tooltip.language" :list="languages" :value="language" />
</div>
<ErrorDialog ref="errorDialog" />
</DialogWidget>
@@ -31,12 +27,14 @@ import { mapActions } from 'vuex';
import apiClient from '@/utils/axios.js';
import DialogWidget from '@/components/DialogWidget.vue';
import ErrorDialog from '@/dialogues/standard/ErrorDialog.vue';
import SelectDropdownWidget from '@/components/form/SelectDropdownWidget.vue';
export default {
name: 'RegisterDialog',
components: {
DialogWidget,
ErrorDialog,
SelectDropdownWidget,
},
data() {
return {
@@ -44,7 +42,8 @@ export default {
username: '',
password: '',
repeatPassword: '',
language: this.getBrowserLanguage(),
language: null,
languages: [],
buttons: [
{ text: 'register.close', action: 'close' },
{ text: 'register.register', action: 'register', disabled: !this.canRegister }
@@ -61,15 +60,22 @@ export default {
this.buttons[1].disabled = !newValue;
}
},
async created() {
await this.getLanguages();
await this.getBrowserLanguage();
},
methods: {
...mapActions(['login']),
getBrowserLanguage() {
async getBrowserLanguage() {
const browserLanguage = navigator.language || navigator.languages[0];
let short = '';
if (browserLanguage.startsWith('de')) {
return 'de';
short = 'de';
} else {
return 'en';
short = 'en';
}
const response = await apiClient.post('/api/settings/getparamvalueid', { paramValue: short });
this.language = response.data.paramValueId;
},
open() {
this.$refs.dialog.open();
@@ -93,7 +99,6 @@ export default {
});
if (response.status === 201) {
console.log(response.data);
this.login(response.data);
this.$refs.dialog.close();
this.$router.push('/activate');
@@ -108,6 +113,16 @@ export default {
this.$refs.errorDialog.open('tr:register.' + error.response.data.error);
}
}
},
async getLanguages() {
try {
const response = await apiClient.post('/api/settings/getparamvalues', {
type: 'language'
});
this.languages = response.data.map(item => { return { value: item.id, captionTr: `settings.personal.language.${item.name}` } });
} catch (err) {
console.error('Error loading languages:', err);
}
}
}
};

View File

@@ -9,6 +9,7 @@ import enChat from './locales/en/chat.json';
import enRegister from './locales/en/register.json';
import enError from './locales/en/error.json';
import enActivate from './locales/en/activate.json';
import enSettings from './locales/en/settings.json';
import deGeneral from './locales/de/general.json';
import deHeader from './locales/de/header.json';
@@ -18,6 +19,7 @@ import deChat from './locales/de/chat.json';
import deRegister from './locales/de/register.json';
import deError from './locales/de/error.json';
import deActivate from './locales/de/activate.json';
import deSettings from './locales/de/settings.json';
const messages = {
en: {
@@ -29,6 +31,7 @@ const messages = {
...enRegister,
...enError,
...enActivate,
...enSettings,
},
de: {
...deGeneral,
@@ -39,6 +42,7 @@ const messages = {
...deRegister,
...deError,
...deActivate,
...deSettings,
}
};

View File

@@ -38,6 +38,9 @@
"userrights": "Benutzerrechte",
"interrests": "Interessen",
"falukant": "Falukant"
},
"m-friends": {
"manageFriends": "Freunde verwalten"
}
}
}

View File

@@ -0,0 +1,32 @@
{
"settings": {
"personal": {
"title": "Persönliche Daten",
"label": {
"language": "Sprache",
"birthdate": "Geburtsdatum",
"gender": "Geschlecht",
"town": "Stadt",
"zip": "PLZ"
},
"tooltip": {
"language": "Sprache",
"birthdate": "Geburtsdatum",
"gender": "Geschlecht",
"town": "Stadt",
"zip": "PLZ"
},
"gender": {
"male": "Männlich",
"female": "Weiblich",
"transmale": "Trans-Frau",
"transfemale": "Trans-Mann",
"nonbinary": "Nonbinär"
},
"language": {
"de": "Deutsch",
"en": "Englisch"
}
}
}
}

View File

@@ -0,0 +1,3 @@
{
}

View File

@@ -7,7 +7,6 @@ import i18n from './i18n';
function getBrowserLanguage() {
const browserLanguage = navigator.language || navigator.languages[0];
console.log(browserLanguage);
if (browserLanguage.startsWith('de')) {
return 'de';
} else {

View File

@@ -11,12 +11,11 @@ const store = createStore({
menu: [],
},
mutations: {
dologin(state, user) {
async dologin(state, user) {
state.isLoggedIn = true;
state.user = user;
localStorage.setItem('isLoggedIn', 'true');
localStorage.setItem('user', JSON.stringify(user));
console.log(state.user);
},
dologout(state) {
state.isLoggedIn = false;
@@ -45,7 +44,7 @@ const store = createStore({
},
actions: {
async login({ commit, dispatch }, user) {
commit('dologin', user);
await commit('dologin', user);
await dispatch('loadMenu');
dispatch('startMenuReload');
},

View File

@@ -1,11 +1,14 @@
<template>
<div>
Persönliche Einstellungen
</div>
<SettingsWidget :settingsType="'personal'" />
</template>
<script>
import SettingsWidget from '@/components/SettingsWidget.vue';
export default {
name: 'PersonalSettingsView',
components: {
SettingsWidget,
}
}
</script>