routing improved, settings initialized

This commit is contained in:
Torsten Schulz
2024-07-21 18:47:45 +02:00
parent 12d66d6f9c
commit cd0699f3fd
23 changed files with 476 additions and 69 deletions

View File

@@ -18,7 +18,11 @@ export const login = async (req, res) => {
const result = await userService.loginUser({ username, password });
res.status(200).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
if (error.message === 'credentialsinvalid') {
res.status(404).json({ error: error.message })
} else {
res.status(500).json({ error: error.message });
}
}
};

View File

@@ -1,3 +1,7 @@
import User from '../models/community/user.js';
import UserRight from '../models/community/user_right.js';
import UserRightType from '../models/type/user_right.js';
const menuStructure = {
home: {
visible: ["all"],
@@ -49,7 +53,7 @@ const menuStructure = {
}
},
chats: {
visible: ["all"],
visible: ["over12"],
children: {
multiChat: {
visible: ["over12"],
@@ -138,11 +142,11 @@ const menuStructure = {
},
personal: {
visible: ["all"],
path: "/settings/account"
path: "/settings/personal"
},
view: {
visible: ["all"],
path: "/settings/account"
path: "/settings/view"
},
interrests: {
visible: ["all"],
@@ -202,7 +206,41 @@ const menuStructure = {
}
};
const filterMenu = (menu, rights) => {
const filteredMenu = {};
for (const [key, value] of Object.entries(menu)) {
if (value.visible.includes("all")
|| value.visible.some(v => rights.includes(v)
|| (value.visible.includes("anyadmin") && rights.length > 0))) {
const { visible, ...itemWithoutVisible } = value;
filteredMenu[key] = { ...itemWithoutVisible };
if (value.children) {
filteredMenu[key].children = filterMenu(value.children, rights);
}
}
}
return filteredMenu;
};
export const menu = async (req, res) => {
const { userid } = req.params;
res.status(200).json({ userId: userid });
}
try {
const { userid } = req.params;
const user = await User.findOne({ where: { hashedId: userid } });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const userRights = await UserRight.findAll({
where: { userId: user.id },
include: [{
model: UserRightType,
as: 'rightType'
}]
});
const rights = userRights.map(ur => ur.rightType.title);
const filteredMenu = filterMenu(menuStructure, rights);
res.status(200).json(filteredMenu);
} catch (error) {
console.error('Error fetching menu:', error);
res.status(500).json({ error: 'An error occurred while fetching the menu' });
}
};

View File

@@ -28,9 +28,6 @@ const User = sequelize.define('user', {
password: {
type: DataTypes.STRING,
allowNull: false,
set(value) {
this.setDataValue('password', bcrypt.hashSync(value, 10));
}
},
registrationDate: {
type: DataTypes.DATE,

View File

@@ -0,0 +1,32 @@
import { sequelize } from '../../utils/sequelize.js';
import { DataTypes } from 'sequelize';
import User from './user.js';
import UserRightType from '../type/user_right.js';
const UserRight = sequelize.define('user_right', {
userId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: User,
key: 'id'
}
},
rightTypeId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: UserRightType,
key: 'id'
}
},
}, {
tableName: 'user_right',
schema: 'community',
underscored: true,
});
UserRight.belongsTo(User, { foreignKey: 'userId' });
UserRight.belongsTo(UserRightType, { foreignKey: 'rightTypeId', as: 'rightType' });
export default UserRight;

View File

@@ -2,12 +2,18 @@ import User from './community/user.js';
import UserParam from './community/user_param.js';
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';
const models = {
User,
UserParam,
UserParamType,
Login
Login,
UserRightType,
UserRight,
SettingsType,
};
export default models;

View File

@@ -0,0 +1,15 @@
import { sequelize } from '../../utils/sequelize.js';
import { DataTypes } from 'sequelize';
const SettingsType = sequelize.define('settings_type', {
name: {
type: DataTypes.STRING,
allowNull: false
},
}, {
tableName: 'settings',
schema: 'type',
underscored: true
});
export default SettingsType;

View File

@@ -1,15 +1,39 @@
import { sequelize } from '../../utils/sequelize.js';
import { DataTypes } from 'sequelize';
import SettingsType from './settings_type.js';
const UserParamType = sequelize.define('user_param_type', {
description: {
type: DataTypes.STRING,
allowNull: false
}
},
minAge: {
type: DataTypes.INTEGER,
allowNull: true
},
gender: {
type: DataTypes.STRING,
allowNull: true
},
datatype: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: 'string'
},
settingsTypeId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: SettingsType,
key: 'id'
}
},
}, {
tableName: 'user_param',
schema: 'type',
underscored: true
});
UserParamType.belongsTo(SettingsType, { foreignKey: 'settingsTypeId' });
export default UserParamType;

View File

@@ -0,0 +1,15 @@
import { sequelize } from '../../utils/sequelize.js';
import { DataTypes } from 'sequelize';
const UserRightType = sequelize.define('user_right_type', {
title: {
type: DataTypes.STRING,
allowNull: false
}
}, {
tableName: 'user_right',
schema: 'type',
underscored: true
});
export default UserRightType;

View File

@@ -4,24 +4,30 @@ import User from '../models/community/user.js';
import UserParam from '../models/community/user_param.js';
import UserParamType from '../models/type/user_param.js';
import { sendAccountActivationEmail, sendPasswordResetEmail } from './emailService.js';
import { sequelize } from '../utils/sequelize.js';
import { encrypt, generateIv } from '../utils/encryption.js';
const saltRounds = 10;
export const registerUser = async ({ email, username, password, language }) => {
const [results] = await sequelize.query(
'SELECT * FROM "community"."user" WHERE pgp_sym_decrypt("email", :key) = :email',
const iv = generateIv();
const encryptedEmail = encrypt(email, iv);
const results = await sequelize.query(
`SELECT * FROM "community"."user" WHERE public.pgp_sym_decrypt("email"::bytea, :key::text) = :email`,
{
replacements: { key: process.env.SECRET_KEY, email },
type: sequelize.QueryTypes.SELECT
}
);
if (results.length > 0) {
console.log(results);
if (results.length && results.length > 0) {
throw new Error('Email already in use');
}
const iv = generateIv();
const encryptedEmail = encrypt(email, iv);
const hashedPassword = await bcrypt.hash(password, saltRounds);
const resetToken = uuidv4();
const user = await User.create({
email: encryptedEmail,
iv: iv.toString('hex'),
@@ -31,17 +37,21 @@ export const registerUser = async ({ email, username, password, language }) => {
active: false,
registration_date: new Date()
});
const languageType = await UserParamType.findOne({ where: { description: 'language' } });
if (!languageType) {
throw new Error('Language type not found');
}
await UserParam.create({
userId: user.id,
paramTypeId: languageType.id,
value: language
});
const activationLink = `${process.env.FRONTEND_URL}/activate?token=${resetToken}`;
await sendAccountActivationEmail(email, activationLink, username, resetToken, language);
return { id: user.hashedId, username: user.username, active: user.active };
};
@@ -52,10 +62,22 @@ 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');
}
return { id: user.hashedId, username: user.username, active: user.active };
const neededParams = await UserParam.findAll({
where: {
userId: user.id
},
include: {
model: UserParamType,
where: {
description: ['birthdate', 'gender']
}
}
});
return { id: user.hashedId, username: user.username, active: user.active, forwardDataInput: neededParams.length < 2 };
};
export const handleForgotPassword = async ({ email }) => {

View File

@@ -0,0 +1,18 @@
import SettingsType from "../models/type/settings_type.js";
const initializeSettings = async () => {
await SettingsType.findOrCreate({
where: { name: 'personal' },
defaults: { name: 'personal' }
});
await SettingsType.findOrCreate({
where: { name: 'view' },
defaults: { name: 'view' }
});
await SettingsType.findOrCreate({
where: { name: 'sexuality' },
defaults: { name: 'sexuality' }
});
};
export default initializeSettings;

View File

@@ -1,9 +1,86 @@
import UserParamType from '../models/type/user_param.js';
import SettingsType from '../models/type/settings_type.js'; // Importiere SettingsType
const initializeTypes = async () => {
const settingsTypes = await SettingsType.findAll();
const settingsTypeMap = settingsTypes.reduce((map, type) => {
map[type.name] = type.id;
return map;
}, {});
const getSettingsTypeId = (name) => settingsTypeMap[name];
await UserParamType.findOrCreate({
where: { description: 'language' },
defaults: { description: 'language' }
defaults: { description: 'language', datatype: 'string', settingsTypeId: getSettingsTypeId('personal') }
});
await UserParamType.findOrCreate({
where: { description: 'birthdate' },
defaults: { description: 'birthdate', datatype: 'date', settingsTypeId: getSettingsTypeId('personal') }
});
await UserParamType.findOrCreate({
where: { description: 'zip' },
defaults: { description: 'zip', datatype: 'string', settingsTypeId: getSettingsTypeId('personal') }
});
await UserParamType.findOrCreate({
where: { description: 'town' },
defaults: { description: 'town', datatype: 'string', settingsTypeId: getSettingsTypeId('personal') }
});
await UserParamType.findOrCreate({
where: { description: 'bodyheight' },
defaults: { description: 'bodyheight', datatype: 'float', settingsTypeId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'weight' },
defaults: { description: 'weight', datatype: 'float', settingsTypeId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'eyecolor' },
defaults: { description: 'eyecolor', datatype: 'string', settingsTypeId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'haircolor' },
defaults: { description: 'haircolor', datatype: 'string', settingsTypeId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'hairlength' },
defaults: { description: 'hairlength', datatype: 'int', settingsTypeId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'skincolor' },
defaults: { description: 'skincolor', datatype: 'int', settingsTypeId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'freckles' },
defaults: { description: 'freckles', datatype: 'int', settingsTypeId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'piercings' },
defaults: { description: 'piercings', datatype: 'bool', settingsTypeId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'tattoos' },
defaults: { description: 'tattoos', datatype: 'bool', settingsTypeId: getSettingsTypeId('view') }
});
await UserParamType.findOrCreate({
where: { description: 'sexualpreference' },
defaults: { description: 'sexualpreference', minAge: 14, datatype: 'int', settingsTypeId: getSettingsTypeId('sexuality') }
});
await UserParamType.findOrCreate({
where: { description: 'gender' },
defaults: { description: 'gender', datatype: 'string', settingsTypeId: getSettingsTypeId('personal') }
});
await UserParamType.findOrCreate({
where: { description: 'pubichair' },
defaults: { description: 'pubichair', minAge: 14, datatype: 'int', settingsTypeId: getSettingsTypeId('sexuality') }
});
await UserParamType.findOrCreate({
where: { description: 'penislength' },
defaults: { description: 'penislength', minAge: 14, gender: 'm', datatype: 'int', settingsTypeId: getSettingsTypeId('sexuality') }
});
await UserParamType.findOrCreate({
where: { description: 'brasize' },
defaults: { description: 'brasize', minAge: 14, gender: 'f', datatype: 'string', settingsTypeId: getSettingsTypeId('sexuality') }
});
};

View File

@@ -0,0 +1,39 @@
import UserRightType from "../models/type/user_right.js";
const initializeUserRights = async() => {
await UserRightType.findOrCreate({
where: { title: "mainadmin"},
defaults: { title: "mainadmin"}
});
await UserRightType.findOrCreate({
where: { title: "contactrequests"},
defaults: { title: "contactrequests"}
});
await UserRightType.findOrCreate({
where: { title: "useradministration"},
defaults: { title: "useradministration"}
});
await UserRightType.findOrCreate({
where: { title: "forum"},
defaults: { title: "forum"}
});
await UserRightType.findOrCreate({
where: { title: "rights"},
defaults: { title: "rights"}
});
await UserRightType.findOrCreate({
where: { title: "interrests"},
defaults: { title: "interrests"}
});
await UserRightType.findOrCreate({
where: { title: "falukant"},
defaults: { title: "falukant"}
});
await UserRightType.findOrCreate({
where: { title: "developer"},
defaults: { title: "developer"}
});
};
export default initializeUserRights;

View File

@@ -1,10 +1,14 @@
import { initializeDatabase } from './sequelize.js';
import initializeTypes from './initializeTypes.js';
import initializeSettings from './initializeSettings.js';
import initializeUserRights from './initializeUserRights.js';
const syncDatabase = async () => {
try {
await initializeDatabase();
await initializeSettings();
await initializeTypes();
await initializeUserRights();
console.log('All models were synchronized successfully.');
} catch (error) {
console.error('Unable to synchronize the database:', error);

1
frontend/src/assets/images Symbolic link
View File

@@ -0,0 +1 @@
../../public/images

View File

@@ -1,42 +1,42 @@
<template>
<nav>
<ul>
<li v-for="item in menu" :key="item.text">
<a href="#">{{ $t(`navigation.${item.text}`) }}</a>
<ul v-if="item.submenu">
<li v-for="subitem in item.submenu" :key="subitem.text">
<a href="#">{{ $t(`navigation.${subitem.text}`) }}</a>
<li v-for="(item, key) in menu" :key="key" class="mainmenuitem">
<a :href="item.path" v-if="item.path" class="menuitem">{{ $t(`navigation.${key}`) }}</a>
<span v-if="!item.path" class="menuitem">{{ $t(`navigation.${key}`) }}</span>
<ul v-if="item.children" class="submenu1">
<li v-for="(subitem, subkey) in item.children" :key="subitem.text">
<a :href="subitem.path" v-if="subitem.path">{{ $t(`navigation.m-${key}.${subkey}`) }}</a>
<span v-if="!subitem.path">{{ $t(`navigation.m-${key}.${subkey}`) }}</span>
</li>
</ul>
</li>
</ul>
<div class="right-block">
<button @click="accessMailbox">{{ $t('navigation.mailbox') }}</button>
<button @click="logout">{{ $t('navigation.logout') }}</button>
<span @click="accessMailbox" class="mailbox"></span>
<span class="logoutblock">
<span class="username">{{ user.username }} </span>
<span @click="logout" class="menuitem">{{ $t('navigation.logout') }}</span>
</span>
</div>
</nav>
</template>
<script>
import { mapGetters } from 'vuex';
import { mapGetters, mapActions } from 'vuex';
export default {
name: 'AppNavigation',
computed: {
...mapGetters('menu'),
...mapGetters(['menu', 'user']),
},
created() {
if(this.$store.getters.hashedId) {
this.$store.dispatch('loadMenu');
if (this.user && this.user.hashedId) {
this.loadMenu();
}
},
methods: {
accessMailbox() {
alert('Accessing Mailbox...');
},
logout() {
this.$store.dispatch('logout');
}
...mapActions(['loadMenu', 'logout']),
}
};
</script>
@@ -45,37 +45,87 @@ export default {
@import '../assets/styles.scss';
nav,
nav > ul{
nav>ul {
display: flex;
justify-content: space-between;
background-color: #F9A22C;
color: #000000;
padding: 10px;
padding: 0;
flex-direction: row;
margin: 0;
}
ul {
list-style-type: none;
padding: 0;
margin: 0;
}
li {
margin: 5px 0;
nav>ul>li {
padding: 0 1em;
line-height: 2.5em;
transition: background-color 0.25s;
}
a {
nav>ul>li:hover {
background-color: #D37C06;
white-space: nowrap;
}
nav>ul>li:hover > span {
color: #000000;
}
nav>ul>li:hover > ul{
display: inline-block;
}
a {
text-decoration: none;
}
.right-block {
display: flex;
gap: 10px;
}
button {
background-color: #495057;
color: white;
border: none;
padding: 5px 10px;
cursor: pointer;
.logoutblock {
display: flex;
flex-direction: column;
}
button:hover {
background-color: #6c757d;
.menuitem {
cursor: pointer;
color: #7E471B;
}
.mailbox {
background-image: url('@/assets/images/icons/message24.png');
background-size: contain;
background-repeat: no-repeat;
background-position: center;
padding-left: 24px;
text-align: left;
}
.mainmenuitem {
position: relative;
}
.submenu1 {
position: absolute;
border: 1px solid #7E471B;
background-color: #F9A22C;
display: none;
left: 0;
top: 2.5em;
}
.submenu1 > li {
padding: 0.5em;
line-height: 1em;
color: #7E471B;
}
.submenu1>li:hover {
color: #000000;
background-color: #D37C06;
}
</style>

View File

@@ -1,6 +1,7 @@
{
"error": {
"title": "Fehler aufgetreten",
"close": "Schließen"
"close": "Schließen",
"credentialsinvalid": "Die Zugangsdaten sind nicht korrekt."
}
}

View File

@@ -1,12 +1,44 @@
{
"home": "Startseite",
"about": "Über uns",
"services": "Dienstleistungen",
"team": "Team",
"company": "Firma",
"consulting": "Beratung",
"development": "Entwicklung",
"mailbox": "Briefkasten",
"logout": "Abmelden"
"navigation": {
"home": "Startseite",
"logout": "Abmelden",
"friends": "Freunde",
"socialnetwork": "Treffpunkt",
"chats": "Chats",
"falukant": "Falukant",
"minigames": "Minispiele",
"settings": "Einstellungen",
"administration": "Verwaltung",
"m-chats": {
"multiChat": "Multiuser-Chat",
"randomChat": "Zufalls-Singlechat"
},
"m-socialnetwork": {
"guestbook": "Gästebuch",
"usersearch": "Benutzersuche",
"forum": "Forum",
"gallery": "Galerie",
"blockedUsers": "Blockierte Benutzer",
"oneTimeInvitation": "Einmal-Einladungen",
"diary": "Tagebuch"
},
"m-settings": {
"homepage": "Startseite",
"account": "Account",
"personal": "Persönliches",
"view": "Aussehen",
"interrests": "Interessen",
"notifications": "Benachrichtigungen",
"sexuality": "Sexualität"
},
"m-administration": {
"contactrequests": "Kontaktanfragen",
"useradministration": "Benutzerverwaltung",
"forum": "Forum",
"userrights": "Benutzerrechte",
"interrests": "Interessen",
"falukant": "Falukant"
}
}
}

View File

@@ -1,6 +1,8 @@
import { createRouter, createWebHistory } from 'vue-router';
import store from '../store';
import HomeView from '../views/HomeView.vue';
import ActivateView from '../views/auth/ActivateView.vue';
import PeronalSettingsView from '../views/settings/PersonalView.vue';
const routes = [
{
@@ -12,9 +14,16 @@ const routes = [
path: '/activate',
name: 'Activate page',
component: ActivateView
},
{
path: '/settings/personal',
name: 'Personal settings',
component: PeronalSettingsView,
meta: { requiresAuth: true }
}
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
@@ -24,10 +33,10 @@ router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.isLoggedIn) {
next('/');
} else if (!store.user.active) {
next();
} else {
} else if (!store.getters.user.active) {
next('/activate');
} else {
next();
}
} else {
next();

View File

@@ -1,6 +1,7 @@
import { createStore } from 'vuex';
import dialogs from './modules/dialogs';
import loadMenu from '../utils/menuLoader.js';
import router from '../router';
const store = createStore({
state: {
@@ -43,13 +44,14 @@ const store = createStore({
}
},
actions: {
async login({ commit, dispatch }, user) { // Dispatch hinzufügen
async login({ commit, dispatch }, user) {
commit('dologin', user);
await dispatch('loadMenu'); // Korrekte Verwendung von dispatch
await dispatch('loadMenu');
dispatch('startMenuReload');
},
logout({ commit }) {
commit('dologout');
router.push('/');
},
loadLoginState({ commit }) {
commit('loadLoginState');
@@ -69,7 +71,7 @@ const store = createStore({
startMenuReload({ dispatch }) {
setInterval(() => {
dispatch('loadMenu');
}, 5000);
}, 10000);
},
},
getters: {

View File

@@ -3,7 +3,6 @@ import store from '../store';
const loadMenu = async () => {
try {
console.log(store.getters.user);
const userId = store.getters.user ? store.getters.user.id : null;
if (!userId) {
throw new Error('User ID not found');

View File

@@ -39,7 +39,7 @@ export default {
const response = await apiClient.post('/api/auth/activate', { token: this.token });
if (response.status === 200) {
this.user.active = true;
this.$router.push('/'); // Redirect to login after activation
this.$router.push('/settings/personal');
}
} catch (error) {
console.error('Error activating account:', error);

View File

@@ -38,6 +38,7 @@
<RandomChatDialog ref="randomChatDialog" />
<RegisterDialog ref="registerDialog" />
<PasswordResetDialog ref="passwordResetDialog" />
<ErrorDialog ref="errorDialog" />
</div>
</template>
@@ -47,6 +48,7 @@ import RegisterDialog from '@/dialogues/auth/RegisterDialog.vue';
import PasswordResetDialog from '@/dialogues/auth/PasswordResetDialog.vue';
import apiClient from '@/utils/axios.js';
import { mapActions } from 'vuex';
import ErrorDialog from '@/dialogues/standard/ErrorDialog.vue';
export default {
name: 'HomeNoLoginView',
@@ -60,6 +62,7 @@ export default {
RandomChatDialog,
RegisterDialog,
PasswordResetDialog,
ErrorDialog,
},
methods: {
...mapActions(['login']),
@@ -73,8 +76,16 @@ export default {
this.$refs.passwordResetDialog.open();
},
async doLogin() {
const response = await apiClient.post('/api/auth/login', { username: this.username, password: this.password });
this.login(response.data);
try {
const response = await apiClient.post('/api/auth/login', { username: this.username, password: this.password });
this.login(response.data);
if (response.data.forwardDataInput) {
console.log(response.data);
this.$router.push({ path: '/settings/personal' });
}
} catch (error) {
this.$refs.errorDialog.open(`tr:error.${error.response.data.error}`);
}
}
}
};

View File

@@ -0,0 +1,11 @@
<template>
<div>
Persönliche Einstellungen
</div>
</template>
<script>
export default {
name: 'PersonalSettingsView',
}
</script>