Compare commits

..

No commits in common. "main" and "@flaschengeist/api-v1.0.0-alpha.6" have entirely different histories.

33 changed files with 279 additions and 585 deletions

View File

@ -17,11 +17,11 @@ module.exports = {
project: resolve(__dirname, './tsconfig.json'),
tsconfigRootDir: __dirname,
ecmaVersion: 2019, // Allows for the parsing of modern ECMAScript features
sourceType: 'module', // Allows for the use of imports
sourceType: 'module' // Allows for the use of imports
},
env: {
browser: true,
browser: true
},
// Rules order is important, please avoid shuffling them
@ -44,7 +44,7 @@ module.exports = {
// https://github.com/prettier/eslint-config-prettier#installation
// usage with Prettier, provided by 'eslint-config-prettier'.
'plugin:prettier/recommended',
'prettier', //'plugin:prettier/recommended'
],
plugins: [
@ -54,6 +54,10 @@ module.exports = {
// https://eslint.vuejs.org/user-guide/#why-doesn-t-it-work-on-vue-file
// required to lint *.vue files
'vue',
// https://github.com/typescript-eslint/typescript-eslint/issues/389#issuecomment-509292674
// Prettier has not been included as plugin to avoid performance impact
// add it as an extension for your IDE
],
globals: {
@ -66,7 +70,7 @@ module.exports = {
__QUASAR_SSR_PWA__: true,
process: true,
Capacitor: true,
chrome: true,
chrome: true
},
// add your custom rules here
@ -76,16 +80,20 @@ module.exports = {
'vue/multi-word-component-names': 'off',
// Rejects on promises should always be of the Error type (and allow empty rejects as well)
'prefer-promise-reject-errors': ['error', { allowEmptyReject: true }],
'prefer-promise-reject-errors': ["error", {"allowEmptyReject": true}],
// Allow " if ' is contained inside the string, so we can avoid escaping
quotes: ['error', 'single', { avoidEscape: true }],
quotes: [
process.env.NODE_ENV === 'production' ? 'error' : 'warn',
'single',
{ avoidEscape: true }
],
// TypeScript, let us be not too strict
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
// allow debugger during development only
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
},
};
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}

View File

@ -1,3 +0,0 @@
yarn-error.log
.woodpecker/

View File

@ -3,6 +3,6 @@
module.exports = {
plugins: [
// to edit target browsers: use "browserslist" field in package.json
require('autoprefixer'),
],
};
require('autoprefixer')
]
}

View File

@ -1,15 +0,0 @@
pipeline:
deploy:
when:
event: tag
tag: "@flaschengeist/api-v*"
image: node:lts-alpine
commands:
- cd api
- echo "//registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN" > .npmrc
- yarn publish --non-interactive
secrets: [ node_auth_token ]
depends_on:
- lint

View File

@ -1,9 +0,0 @@
pipeline:
lint:
when:
branch: [main, develop]
image: node:lts-alpine
commands:
- yarn install
- yarn lint

View File

@ -1,6 +1,4 @@
# Flaschengeist (frontend)
![status-badge](https://ci.os-sc.org/api/badges/Flaschengeist/flaschengeist-frontend/status.svg)
Modular student club administration system, licensed under the MIT license.

View File

@ -1,46 +0,0 @@
<template>
<q-avatar>
<slot :avatar-u-r-l="avatarURL(modelValue)">
<q-img :src="avatarURL(modelValue)" style="min-width: 100%; min-height: 100%">
<template #error>
<img :src="fallback" style="height: 100%" />
</template>
</q-img>
</slot>
</q-avatar>
</template>
<script lang="ts">
import { PropType, defineComponent } from 'vue';
import { avatarURL } from '@flaschengeist/api';
/**
* Display an avatar for an user
*
* Slots:
* default - scope: {avatarURL}
*/
export default defineComponent({
name: 'UserAvatar',
props: {
modelValue: {
type: [Object, String] as PropType<FG.User | string>,
required: true,
},
showZoom: {
type: Boolean,
default: false,
},
fallback: {
type: String,
default: 'no-image.svg',
},
},
emits: ['error'],
setup() {
return {
avatarURL,
};
},
});
</script>

View File

@ -1,5 +1,4 @@
import IsoDateInput from './IsoDateInput.vue';
import PasswordInput from './PasswordInput.vue';
import UserAvatar from './UserAvatar.vue';
export { IsoDateInput, PasswordInput, UserAvatar };
export { IsoDateInput, PasswordInput };

View File

@ -1,6 +1,6 @@
{
"license": "MIT",
"version": "1.0.0",
"version": "1.0.0-alpha.6",
"name": "@flaschengeist/api",
"author": "Tim Gröger <flaschengeist@wu5.de>",
"homepage": "https://flaschengeist.dev/Flaschengeist",
@ -8,16 +8,27 @@
"bugs": {
"url": "https://flaschengeist.dev/Flaschengeist/flaschengeist/issues"
},
"scripts": {
"format": "prettier --config ./package.json --write '{,!(node_modules)/**/}*.ts'",
"lint": "eslint --ext .js,.ts,.vue ./src"
},
"main": "./src/index.ts",
"peerDependencies": {
"@quasar/app-webpack": "^3.7.2",
"flaschengeist": "^2.0.0",
"pinia": "^2.0.8"
"@quasar/app": "^3.2.3",
"flaschengeist": "^2.0.0-alpha.1",
"pinia": "^2.0.4"
},
"devDependencies": {
"@flaschengeist/types": "^1.0.0",
"@types/node": "^14.18.0",
"typescript": "^4.5.4"
"@flaschengeist/types": "^1.0.0-alpha.9",
"@types/node": "^14.17.34",
"@typescript-eslint/eslint-plugin": "^5.4.0",
"@typescript-eslint/parser": "^5.4.0",
"eslint": "^8.3.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-vue": "^8.1.1",
"eslint-webpack-plugin": "^3.1.1",
"prettier": "^2.5.0",
"typescript": "^4.5.2"
},
"prettier": {
"singleQuote": true,

View File

@ -4,7 +4,7 @@ import { AxiosResponse } from 'axios';
import { api } from '../internal';
import { defineStore } from 'pinia';
import { PersistentStorage } from '../utils/persistent';
import { LocalStorage, SessionStorage } from 'quasar';
function reviveSession() {
return PersistentStorage.get<FG.Session>('fg_session').then((s) => fixSession(s || undefined));
}
@ -38,10 +38,6 @@ export const useMainStore = defineStore({
if (this.user === undefined) throw 'Not logged in, this should not be called';
return this.user;
},
currentSession(): FG.Session {
if (this.session === undefined) throw 'Not logged in, this should not be called';
return this.session;
},
permissions(): string[] {
return this.user?.permissions || [];
},
@ -67,14 +63,11 @@ export const useMainStore = defineStore({
},
async login(userid: string, password: string) {
const userStore = useUserStore();
try {
const { data } = await api.post<FG.Session>('/auth', { userid, password });
this.session = fixSession(data);
this.user = await userStore.getUser(data.userid, true);
return true;
} catch ({ response }) {
this.handleLoggedOut();
return (<AxiosResponse | undefined>response)?.status || false;
}
},
@ -154,8 +147,6 @@ export const useMainStore = defineStore({
handleLoggedOut() {
this.$reset();
void clearPersistant();
LocalStorage.clear();
SessionStorage.clear();
},
},
});

View File

@ -1,195 +1,84 @@
import { defineStore } from 'pinia';
import { api } from '../internal';
import { isAxiosError, useMainStore } from '.';
import { DisplayNameMode } from '@flaschengeist/users';
export function fixUser(u?: FG.User) {
return !u ? u : Object.assign(u, { birthday: u.birthday ? new Date(u.birthday) : undefined });
}
/**
* Check if state is outdated / dirty
* Value is considered outdated after 15 minutes
* @param updated Time of last updated (in milliseconds see Date.now())
* @returns True if outdated, false otherwise
*/
function isDirty(updated: number) {
return Date.now() - updated > 15 * 60 * 1000;
}
export const useUserStore = defineStore({
id: 'users',
state: () => ({
roles: [] as FG.Role[],
users: [] as FG.User[],
permissions: [] as FG.Permission[],
userSettings: {} as FG.UserSettings,
// list of all users, include deleted ones, use `users` getter for list of active ones
_users: [] as FG.User[],
// Internal flags for deciding if lists need to force-loaded
_dirty_users: 0,
_dirty_roles: 0,
_dirty_users: true,
_dirty_roles: true,
}),
getters: {
users(state) {
const u = state._users.filter((u) => !u.deleted);
switch (this.userSettings['display_name']) {
case DisplayNameMode.FIRSTNAME_LASTNAME || DisplayNameMode.FIRSTNAME:
u.sort((a, b) => {
const a_lastname = a.lastname.toLowerCase();
const b_lastname = b.lastname.toLowerCase();
const a_firstname = a.firstname.toLowerCase();
const b_firstname = b.firstname.toLowerCase();
if (a_firstname === b_firstname) {
return a_lastname < b_lastname ? -1 : 1;
}
return a_firstname < b_firstname ? -1 : 1;
});
break;
case <string>DisplayNameMode.DISPLAYNAME:
u.sort((a, b) => {
const a_displayname = a.display_name.toLowerCase();
const b_displayname = b.display_name.toLowerCase();
return a_displayname < b_displayname ? -1 : 1;
});
break;
default:
u.sort((a, b) => {
const a_lastname = a.lastname.toLowerCase();
const b_lastname = b.lastname.toLowerCase();
const a_firstname = a.firstname.toLowerCase();
const b_firstname = b.firstname.toLowerCase();
if (a_lastname === b_lastname) {
return a_firstname < b_firstname ? -1 : 1;
}
return a_lastname < b_lastname ? -1 : 1;
});
}
return u;
},
},
getters: {},
actions: {
/** Simply filter all users by ID */
findUser(userid: string) {
return this._users.find((user) => user.userid === userid);
return this.users.find((user) => user.userid === userid);
},
/** Retrieve user by ID
* @param userid ID of user to retrieve
* @param force If set to true the user is loaded from backend even when a local copy is available
* @returns Retrieved user (Promise) or raise an error
* @throws Probably an AxiosError if loading failed
*/
async getUser(userid: string, force = false) {
const idx = this._users.findIndex((user) => user.userid === userid);
if (force || idx === -1 || isDirty(this._dirty_users)) {
const idx = this.users.findIndex((user) => user.userid === userid);
if (force || this._dirty_users || idx === -1) {
try {
const { data } = await api.get<FG.User>(`/users/${userid}`);
fixUser(data);
if (idx === -1) this._users.push(data);
else this._users[idx] = data;
if (idx === -1) this.users.push(data);
else this.users[idx] = data;
return data;
} catch (error) {
// Ignore 404, throw all other
if (!isAxiosError(error, 404)) throw error;
}
} else {
return this._users[idx];
return this.users[idx];
}
},
/** Retrieve list of all users
* @param force If set to true a fresh users list is loaded from backend even when a local copy is available
* @returns Array of retrieved users (Promise)
* @throws Probably an AxiosError if loading failed
*/
async getUsers(force = false) {
if (force || isDirty(this._dirty_users)) {
if (force || this._dirty_users) {
const { data } = await api.get<FG.User[]>('/users');
data.forEach(fixUser);
this._users = data;
this._dirty_users = Date.now();
this.users = data;
this._dirty_users = false;
}
return this._users;
return this.users;
},
/** Save modifications of user on backend
* @param user Modified user to save
* @throws Probably an AxiosError if request failed (404 = Invalid userid, 400 = Invalid data)
*/
async updateUser(user: FG.User) {
await api.put(`/users/${user.userid}`, user);
// Modifcation accepted by backend
// Save modifications back to our users list
const idx = this._users.findIndex((u) => u.userid === user.userid);
if (idx > -1) this._users[idx] = user;
// If user was current user, save modifications back to the main store
const mainStore = useMainStore();
if (user.userid === mainStore.user?.userid) mainStore.user = user;
this._dirty_users = true;
},
/** Register a new user
* @param user User to register (id not set)
* @returns The registered user (id set)
* @throws Probably an AxiosError if request failed
*/
async createUser(user: FG.User) {
const { data } = await api.post<FG.User>('/users', user);
this._users.push(<FG.User>fixUser(data));
this.users.push(data);
return data;
},
/** Delete an user
* Throws if failed and resolves void if succeed
*
* @param user User or ID of user to delete
* @throws Probably an AxiosError if request failed
*/
async deleteUser(user: FG.User | string) {
if (typeof user === 'object') user = user.userid;
await api.delete(`/users/${user}`);
this._users = this._users.filter((u) => u.userid != user);
},
/** Upload an avatar for an user
* Throws if failed and resolves void if succeed
*
* @param user User or ID of user
* @param file Avatar file to upload
* @throws Probably an AxiosError if request failed
*/
async uploadAvatar(user: FG.User | string, file: string | File) {
if (typeof user === 'object') user = user.userid;
async uploadAvatar(user: FG.User, file: string | File) {
const formData = new FormData();
formData.append('file', file);
await api.post(`/users/${user}/avatar`, formData, {
await api.post(`/users/${user.userid}/avatar`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
},
/** Delete avatar of an user
* @param user User or ID of user
* @throws Probably an AxiosError if request failed
*/
async deleteAvatar(user: FG.User | string) {
if (typeof user === 'object') user = user.userid;
await api.delete(`/users/${user}/avatar`);
async deleteAvatar(user: FG.User) {
await api.delete(`/users/${user.userid}/avatar`);
},
/** Retrieve list of all permissions
* @param force If set to true a fresh list is loaded from backend even when a local copy is available
* @returns Array of retrieved permissions (Promise)
* @throws Probably an AxiosError if request failed
*/
async getPermissions(force = false) {
if (force || this.permissions.length === 0) {
const { data } = await api.get<FG.Permission[]>('/roles/permissions');
@ -198,81 +87,39 @@ export const useUserStore = defineStore({
return this.permissions;
},
/** Retrieve list of all roles
* @param force If set to true a fresh list is loaded from backend even when a local copy is available
* @returns Array of retrieved roles (Promise)
* @throws Probably an AxiosError if request failed
*/
async getRoles(force = false) {
if (force || isDirty(this._dirty_roles)) {
if (force || this._dirty_roles) {
const { data } = await api.get<FG.Role[]>('/roles');
this.roles = data;
this._dirty_roles = Date.now();
this._dirty_roles = false;
}
return this.roles;
},
/** Save modifications of role on the backend
* @param role role to save
* @throws Probably an AxiosError if request failed
*/
async updateRole(role: FG.Role) {
try {
await api.put(`/roles/${role.id}`, role);
const idx = this.roles.findIndex((r) => r.id === role.id);
if (idx != -1) this.roles[idx] = role;
else this._dirty_roles = 0;
} catch (error) {
console.warn(error);
}
this._updatePermission(role);
},
_updatePermission(role: FG.Role) {
const idx = this.roles.findIndex((r) => r.id === role.id);
if (idx != -1) this.roles[idx] = role;
this._dirty_roles = true;
},
/** Create a new role
* @param role Role to create (ID not set)
* @returns Created role (ID set)
* @throws Probably an AxiosError if request failed
*/
async newRole(role: FG.Role) {
const { data } = await api.post<FG.Role>('/roles', role);
this.roles.push(data);
return data;
},
/** Delete a role
* @param role Role or ID of role to delete
* @throws Probably an AxiosError if request failed (409 if role still in use)
*/
async deleteRole(role: FG.Role | number) {
if (typeof role === 'object') role = role.id;
await api.delete(`/roles/${role}`);
this.roles = this.roles.filter((r) => r.id !== role);
},
/** Get Settings for display name mode
* @param force If set to true a fresh list is loaded from backend even when a local copy is available
* @throws Probably an AxiosError if request failed
* @returns Settings for display name mode
*/
async getDisplayNameModeSetting(force = false): Promise<string> {
const mainStore = useMainStore();
if (force) {
const { data } = await api.get<{ data: string }>(
`users/${mainStore.currentUser.userid}/setting/display_name_mode`
);
this.userSettings['display_name'] = data.data;
}
return this.userSettings['display_name'];
},
/** Set Settings for display name mode
* @param mode New display name mode
* @throws Probably an AxiosError if request failed
* @returns Settings for display name mode
*/
async setDisplayNameModeSetting(mode: string): Promise<string> {
const mainStore = useMainStore();
await api.put(`users/${mainStore.currentUser.userid}/setting/display_name_mode`, {
data: mode,
});
this.userSettings['display_name'] = mode;
return mode;
await api.delete(`/roles/${typeof role === 'number' ? role : role.id}`);
this.roles = this.roles.filter((r) => r.id !== (typeof role == 'number' ? role : role.id));
},
},
});

View File

@ -1,35 +1,35 @@
import { LocalStorage, Platform } from 'quasar';
import { Preferences } from '@capacitor/preferences';
import { Storage } from '@capacitor/storage';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type PersitentTypes = Date | RegExp | number | boolean | string | object;
export class PersistentStorage {
static clear() {
if (Platform.is.capacitor) return Preferences.clear();
if (Platform.is.capacitor) return Storage.clear();
else return Promise.resolve(LocalStorage.clear());
}
static remove(key: string) {
if (Platform.is.capacitor) return Preferences.remove({ key: key });
if (Platform.is.capacitor) return Storage.remove({ key: key });
else return Promise.resolve(LocalStorage.remove(key));
}
static set(key: string, value: PersitentTypes) {
if (Platform.is.capacitor) return Preferences.set({ key, value: JSON.stringify(value) });
if (Platform.is.capacitor) return Storage.set({ key, value: JSON.stringify(value) });
else return Promise.resolve(LocalStorage.set(key, value));
}
static get<T extends PersitentTypes>(key: string) {
if (Platform.is.capacitor)
return Preferences.get({ key }).then((v) =>
return Storage.get({ key }).then((v) =>
v.value === null ? null : (JSON.parse(v.value) as T)
);
else return Promise.resolve(LocalStorage.getItem<T>(key));
}
static keys() {
if (Platform.is.capacitor) return Preferences.keys().then((v) => v.keys);
if (Platform.is.capacitor) return Storage.keys().then((v) => v.keys);
else return Promise.resolve(LocalStorage.getAllKeys());
}
}

View File

@ -1,6 +1,7 @@
import { api } from '../internal';
export function avatarURL(user: FG.User | string, thumbnail = true) {
if (typeof user === 'object') user = user.userid;
return `${api.defaults?.baseURL || ''}/users/${user}/avatar${thumbnail ? '?thumbnail' : ''}`;
export function avatarURL(user: FG.User, thumbnail = true) {
return `${api.defaults?.baseURL || ''}/users/${user.userid}/avatar${
thumbnail ? '?thumbnail' : ''
}`;
}

View File

@ -3,7 +3,14 @@
"target": "esnext",
"compilerOptions": {
"baseUrl": "./",
"lib": ["es2020", "dom"],
"types": ["@flaschengeist/types", "@quasar/app", "node"]
"lib": [
"es2020",
"dom"
],
"types": [
"@flaschengeist/types",
"@quasar/app",
"node"
]
}
}

View File

@ -1,4 +1,6 @@
/* eslint-env node */
module.exports = {
presets: ['@quasar/babel-preset-app'],
};
presets: [
'@quasar/babel-preset-app'
]
}

View File

@ -1,7 +1,7 @@
{
"private": true,
"license": "MIT",
"version": "2.1.0",
"version": "2.0.0-alpha.1",
"productName": "flaschengeist-frontend",
"name": "flaschengeist",
"author": "Tim Gröger <flaschengeist@wu5.de>",
@ -11,41 +11,34 @@
"url": "https://flaschengeist.dev/Flaschengeist/flaschengeist/issues"
},
"scripts": {
"format": "prettier --config ./package.json --write '{,!(node_modules|dist|.*)/**/}*.{js,ts,vue}'",
"format": "prettier --config ./package.json --write '{,!(node_modules)/**/}*.ts'",
"lint": "eslint --ext .js,.ts,.vue ./src ./api"
},
"dependencies": {
"@flaschengeist/api": "^1.0.0",
"@flaschengeist/balance": "^1.0.0",
"@flaschengeist/pricelist-old": "^1.0.0",
"@flaschengeist/schedule": "^1.0.0",
"@flaschengeist/users": "^1.0.0",
"axios": "^1.4.0",
"pinia": "^2.0.8",
"quasar": "^2.11.10",
"vue": "^3.0.0",
"vue-router": "^4.0.0"
"@flaschengeist/api": "file:./api",
"@flaschengeist/users": "^1.0.0-alpha.1",
"axios": "^0.24.0",
"pinia": "^2.0.4",
"quasar": "^2.3.3"
},
"devDependencies": {
"@capacitor/core": "^5.0.0",
"@capacitor/preferences": "^5.0.0",
"@flaschengeist/types": "^1.0.0",
"@quasar/app-webpack": "^3.7.2",
"@quasar/extras": "^1.16.3",
"@types/node": "^14.18.0",
"@capacitor/core": "^3.3.2",
"@capacitor/storage": "^1.2.3",
"@flaschengeist/types": "^1.0.0-alpha.9",
"@quasar/app": "^3.2.3",
"@quasar/extras": "^1.12.1",
"@types/node": "^14.17.34",
"@types/webpack": "^5.28.0",
"@types/webpack-env": "^1.16.3",
"@typescript-eslint/eslint-plugin": "^5.8.0",
"@typescript-eslint/parser": "^5.8.0",
"@vue/devtools": "^6.5.0",
"eslint": "^8.5.0",
"@typescript-eslint/eslint-plugin": "^5.4.0",
"@typescript-eslint/parser": "^5.4.0",
"eslint": "^8.3.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-vue": "^9.14.1",
"eslint-webpack-plugin": "^4.0.1",
"modify-source-webpack-plugin": "^4.1.0",
"prettier": "^2.5.1",
"typescript": "^4.5.4",
"eslint-plugin-vue": "^8.1.1",
"eslint-webpack-plugin": "^3.1.1",
"modify-source-webpack-plugin": "^3.0.0",
"prettier": "^2.4.1",
"typescript": "^4.5.2",
"vuedraggable": "^4.1.0"
},
"prettier": {

View File

@ -3,4 +3,4 @@ module.exports = [
// '@flaschengeist/balance',
// '@flaschengeist/schedule',
// '@flaschengeist/pricelist',
'@flaschengeist/schedule',
]

View File

@ -8,23 +8,10 @@
/* eslint-env node */
/* eslint-disable @typescript-eslint/no-var-requires */
const ESLintPlugin = require('eslint-webpack-plugin');
const { ModifySourcePlugin, ReplaceOperation } = require('modify-source-webpack-plugin');
const { configure } = require('quasar/wrappers');
const ESLintPlugin = require('eslint-webpack-plugin')
const { ModifySourcePlugin } = require('modify-source-webpack-plugin')
const { configure } = require('quasar/wrappers')
const operation = () => {
const custom_plgns = require('./plugin.config.js');
const required_plgns = require('./src/vendor-plugin.config.js');
const plugins = [...custom_plgns, ...required_plgns].map(
(v) => `import("${v}").catch(() => "${v}")`
);
const replace = new ReplaceOperation(
'all',
`\\/\\* *INSERT_PLUGIN_LIST *\\*\\/`,
`${plugins.join(', ')}`
);
return replace;
};
module.exports = configure(function (/* ctx */) {
return {
@ -35,7 +22,7 @@ module.exports = configure(function (/* ctx */) {
enabled: true,
files: './src/**/*.{ts,tsx,js,jsx,vue}',
},
},
}
},
// https://quasar.dev/quasar-cli/prefetch-feature
@ -56,7 +43,7 @@ module.exports = configure(function (/* ctx */) {
// 'ionicons-v5',
// 'line-awesome',
// 'material-icons',
'mdi-v7',
'mdi-v6',
// 'themify',
// 'roboto-font-latin-ext', // this or either 'roboto-font', NEVER both!
@ -66,9 +53,10 @@ module.exports = configure(function (/* ctx */) {
// Full list of options: https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-build
build: {
vueRouterMode: 'history', // available values: 'hash', 'history'
//publicPath: 'flaschengeist2',
// transpile: false,
// Add dependencies for transpiling with Babel (Array of string/regex)
// (from node_modules, which are by default not transpiled).
// Applies only if "transpile" is set to true.
@ -83,29 +71,33 @@ module.exports = configure(function (/* ctx */) {
// https://quasar.dev/quasar-cli/handling-webpack
// "chain" is a webpack-chain object https://github.com/neutrinojs/webpack-chain
chainWebpack(chain) {
chain.plugin('eslint-webpack-plugin').use(ESLintPlugin, [
{
extensions: ['ts', 'js', 'vue'],
exclude: ['node_modules', 'src-capacitor'],
},
]);
chain.plugin('modify-source-webpack-plugin').use(ModifySourcePlugin, [
{
chainWebpack (chain) {
chain.plugin('eslint-webpack-plugin')
.use(ESLintPlugin, [{
extensions: [ 'ts', 'js', 'vue' ],
exclude: ['node_modules', 'src-capacitor']
}])
chain.plugin('modify-source-webpack-plugin')
.use(ModifySourcePlugin, [{
rules: [
{
test: /plugins\.ts$/,
operations: [operation()],
},
],
},
]);
modify: (src, filename) => {
const custom_plgns = require('./plugin.config.js')
const required_plgns = require('./src/vendor-plugin.config.js')
return src.replace(/\/\* *INSERT_PLUGIN_LIST *\*\//,
[...custom_plgns, ...required_plgns].map(v => `import("${v}").catch(() => "${v}")`)
.join(','))
}
}
]
}])
chain.merge({
snapshot: {
managedPaths: [],
},
});
},
managedPaths: []
}
})
}
},
// Full list of options: https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-devServer
@ -113,7 +105,7 @@ module.exports = configure(function (/* ctx */) {
https: false,
port: 8080,
open: false, // opens browser window automatically
watchFiles: { paths: ['/node_modules/@flaschengeist/**/*'] },
watchFiles: {paths: ['/node_modules/@flaschengeist/**/*']}
},
// https://quasar.dev/quasar-cli/quasar-conf-js#Property%3A-framework
@ -125,8 +117,8 @@ module.exports = configure(function (/* ctx */) {
loadingBar: {
position: 'top',
color: 'warning',
size: '5px',
},
size: '5px'
}
},
// For special cases outside of where the auto-import stategy can have an impact
@ -137,7 +129,14 @@ module.exports = configure(function (/* ctx */) {
// directives: [],
// Quasar plugins
plugins: ['LocalStorage', 'SessionStorage', 'Dialog', 'Loading', 'Notify', 'LoadingBar'],
plugins: [
'LocalStorage',
'SessionStorage',
'Dialog',
'Loading',
'Notify',
'LoadingBar'
]
},
// animations: 'all', // --- includes all animations
@ -146,7 +145,7 @@ module.exports = configure(function (/* ctx */) {
// https://quasar.dev/quasar-cli/developing-ssr/configuring-ssr
ssr: {
pwa: false,
pwa: false
},
// https://quasar.dev/quasar-cli/developing-pwa/configuring-pwa
@ -165,20 +164,20 @@ module.exports = configure(function (/* ctx */) {
{
src: 'flaschengeist-logo.svg',
sizes: 'any',
type: 'image/svg+xml',
type: 'image/svg+xml'
},
{
src: 'favicon-128x128.png',
sizes: '128x128',
type: 'image/png',
type: 'image/png'
},
{
src: 'favicon-256x256.png',
sizes: '256x256',
type: 'image/png',
},
],
type: 'image/png'
},
]
}
},
// Full list of options: https://quasar.dev/quasar-cli/developing-cordova-apps/configuring-cordova
@ -188,7 +187,7 @@ module.exports = configure(function (/* ctx */) {
// Full list of options: https://quasar.dev/quasar-cli/developing-capacitor-apps/configuring-capacitor
capacitor: {
hideSplashscreen: true,
hideSplashscreen: true
},
// Full list of options: https://quasar.dev/quasar-cli/developing-electron-apps/configuring-electron
@ -197,11 +196,13 @@ module.exports = configure(function (/* ctx */) {
packager: {
// https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#options
// OS X / Mac App Store
// appBundleId: '',
// appCategoryType: '',
// osxSign: '',
// protocol: 'myapp://path',
// Windows only
// win32metadata: { ... }
},
@ -209,19 +210,16 @@ module.exports = configure(function (/* ctx */) {
builder: {
// https://www.electron.build/configuration/configuration
appId: 'flaschengeist-frontend',
appId: 'flaschengeist-frontend'
},
// More info: https://quasar.dev/quasar-cli/developing-electron-apps/node-integration
nodeIntegration: true,
extendWebpack(/* cfg */) {
extendWebpack (/* cfg */) {
// do something with Electron main process Webpack cfg
// chainWebpack also available besides this extendWebpack
},
},
bin: {
linuxAndroidStudio: '/home/crimsen/.local/share/JetBrains/Toolbox/scripts/studio',
},
};
}
}
}
});

View File

@ -1,9 +1,9 @@
/* eslint-disable */
// THIS FEATURE-FLAG FILE IS AUTOGENERATED,
// REMOVAL OR CHANGES WILL CAUSE RELATED TYPES TO STOP WORKING
import 'quasar/dist/types/feature-flag';
import "quasar/dist/types/feature-flag";
declare module 'quasar/dist/types/feature-flag' {
declare module "quasar/dist/types/feature-flag" {
interface QuasarFeatureFlags {
capacitor: true;
}

View File

@ -4,9 +4,6 @@
"bundledWebRuntime": false,
"npmClient": "yarn",
"webDir": "www",
"android": {
"minWebViewVersion": 71
},
"ios": {
"allowsLinkPreview": false
}

View File

@ -1,35 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Quasar</title>
<meta charset="utf-8">
<meta name="description" content="Quasar Capacitor App">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, viewport-fit=cover">
<style>
.page {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
text-align: center;
}
</style>
</head>
<body>
<div class="page">
<div>
This file will be auto-generated. Do not edit.
</div>
<div>
Run "quasar dev" or "quasar build" with Capacitor mode.
</div>
</div>
</body>
</html>

View File

@ -1,16 +1,16 @@
{
"name": "flaschengeist",
"version": "2.0.0",
"version": "2.0.0-alpha.1",
"description": "Modular student club administration system",
"author": "Tim Gröger <flaschengeist@wu5.de>",
"private": true,
"dependencies": {
"@capacitor/android": "^5.0.0-beta.0",
"@capacitor/app": "^5.0.0",
"@capacitor/cli": "^5.0.0",
"@capacitor/core": "^5.0.0",
"@capacitor/ios": "^5.0.0",
"@capacitor/preferences": "^5.0.0",
"@capacitor/splash-screen": "^5.0.0"
"@capacitor/android": "^3.3.2",
"@capacitor/app": "^1.0.0",
"@capacitor/cli": "^3.0.0",
"@capacitor/core": "^3.0.0",
"@capacitor/ios": "^3.0.0-beta.0",
"@capacitor/splash-screen": "^1.0.0",
"@capacitor/storage": "^1.2.3"
}
}

View File

@ -94,11 +94,12 @@ export default boot(({ router }) => {
query: { redirect: next },
});
} else if (e.response && e.response.status == 401) {
store.handleLoggedOut();
if (current.name != 'login') {
void store.handleLoggedOut();
if (current.name !== 'login') {
await router.push({
name: 'login',
query: { redirect: current.fullPath },
params: { logout: 'logout' },
query: { redirect: current.path },
});
}
}

View File

@ -21,8 +21,8 @@ async function loadBaseUrl() {
console.warn('Could not load BaseURL', e);
}
}
// eslint-disable-next-line
class BackendError extends Error { }
class BackendError extends Error {}
/**
* Loading backend information
@ -68,18 +68,8 @@ export default boot(async ({ app, router }) => {
// Handle errors from loading the backend information
if (error instanceof BackendError || isAxiosError(error)) {
router.isReady().finally(() => {
// if (Platform.is.capacitor) void router.push({ name: 'setup_backend' });
if (Platform.is.capacitor) {
//void router.push({ name: 'setup_backend' })
Notify.create({
type: 'negative',
message:
'Backend nicht erreichbar! Prüfe deine Internetverbindung oder probiere es später nochmal.',
timeout: 0,
icon: 'mdi-alert-circle-outline',
closeBtn: true,
});
} else void router.push({ name: 'offline', params: { refresh: 1 } });
if (Platform.is.capacitor) void router.push({ name: 'setup_backend' });
else void router.push({ name: 'offline', params: { refresh: 1 } });
});
} else if (typeof error === 'string') {
// Handle plugin not found errors

View File

@ -3,31 +3,46 @@
*/
import { useMainStore, hasPermissions } from '@flaschengeist/api';
import { boot } from 'quasar/wrappers';
import { RouteRecord } from 'vue-router';
export default boot(({ router }) => {
/**
* Login guard
* Check if user tries to access the secured area and validates token
*/
router.beforeEach((to, from) => {
router.beforeResolve((to, from, next) => {
const store = useMainStore();
// Skip loops
if (to.name == 'login' && from.name == 'login') return false;
// Skip if same path
if (to.path == from.path) return next();
// Secured area '/in/...' requires to be authenticated
if (to.path.startsWith('/in') && (!store.session || store.session.expires <= new Date())) {
store.handleLoggedOut();
return { name: 'login' };
// Check if secured area or public
if (to.path.startsWith('/in')) {
// Secured area (LOGIN REQUIRED)
// Check login is ok
if (!store.session || store.session.expires <= new Date()) {
void store.handleLoggedOut();
return next({ name: 'login', query: { redirect: to.fullPath } });
}
// Check if special permissions are required
if (
to.matched.every((record: RouteRecord) => {
if (!('meta' in record) || !('permissions' in record.meta)) return true;
if ((<{ permissions: FG.Permission[] }>record.meta).permissions) {
return hasPermissions((<{ permissions: FG.Permission[] }>record.meta).permissions);
}
})
) {
return next();
} else {
return next({ name: 'login', query: { redirect: to.fullPath } });
}
} else {
// Public space just handle login loops
if (to.name == 'login' && store.user && !to.params['logout']) {
// Called login while already logged in
return next({ name: 'dashboard' });
} else {
// We are on the non secured area
return next();
}
}
});
/**
* Permission guard
* Check permissions for route, cancel navigation on errors
*/
router.beforeResolve((to) => {
if (!!to.meta.permissions && !hasPermissions(<FG.Permission[]>to.meta.permissions))
return false;
});
});

View File

@ -234,12 +234,6 @@ function loadPlugin(
Array.prototype.push.apply(loadedPlugins.widgets, plugin.widgets);
}
if (!plugin.settingWidgets) plugin.settingWidgets = [];
if (plugin.settingWidgets.length > 0) {
plugin.settingWidgets.forEach((widget) => (widget.name = plugin.id + '.' + widget.name));
Array.prototype.push.apply(loadedPlugins.settingWidgets, plugin.settingWidgets);
}
loadedPlugins.plugins.push({
id: plugin.id,
name: plugin.name,
@ -258,7 +252,6 @@ export async function loadPlugins(backend: FG.Backend, baseRoutes: RouteRecordRa
shortcuts: [],
outerShortcuts: [],
widgets: [],
settingWidgets: [],
};
// Wait for all plugins to be loaded

View File

@ -14,7 +14,7 @@
class="q-ma-xs"
title="Löschen"
style="position: absolute; top: 0; right: 0; z-index: 999"
@click.stop.prevent="dismiss"
@click="dismiss"
/>
<q-card-section class="q-pa-xs">
<div class="text-overline">{{ dateString }}</div>
@ -34,7 +34,7 @@
flat
dense
size="sm"
@click.stop.prevent="accept"
@click="accept"
/>
<q-btn
v-if="modelValue.reject"
@ -44,7 +44,7 @@
flat
dense
size="sm"
@click.stop.prevent="reject"
@click="reject"
/>
</q-card-actions>
</q-card>

View File

@ -2,7 +2,7 @@
<q-layout view="hHh Lpr lff">
<q-header elevated class="bg-primary text-white">
<q-toolbar>
<q-btn dense flat round icon="mdi-menu" @click="openMenu(true)" />
<q-btn dense flat round icon="mdi-menu" @click="openMenu" />
<q-toolbar-title>
<router-link :to="{ name: 'dashboard' }" style="text-decoration: none; color: inherit">
@ -40,14 +40,7 @@
<shortcut-link :shortcut="element" context @delete-shortcut="deleteShortcut" />
</template>
</drag>
<q-btn
v-if="!platform.is.capacitor"
flat
round
dense
icon="mdi-exit-to-app"
@click="logout()"
/>
<q-btn v-if="!platform.is.capacitor" flat round dense icon="mdi-exit-to-app" @click="logout()" />
</q-toolbar>
</q-header>
@ -56,10 +49,9 @@
side="left"
bordered
:mini="leftDrawerMini"
@click.capture="openMenuMini"
@click.capture="openMenu"
>
<!-- Plugins -->
<q-scroll-area class="fit">
<essential-expansion-link
v-for="(entry, index) in mainLinks"
:key="'plugin' + index"
@ -84,17 +76,6 @@
</q-item-section>
</q-item>
</div>
</q-scroll-area>
<div class="q-mini-drawer-hide absolute" style="top: 15px; right: -17px">
<q-btn
dense
round
unelevated
color="accent"
icon="mdi-chevron-left"
@click="openMenuMini(true)"
/>
</div>
</q-drawer>
<q-page-container>
<router-view />
@ -137,7 +118,7 @@ export default defineComponent({
const mainStore = useMainStore();
const flaschengeist = inject<FG_Plugin.Flaschengeist>('flaschengeist');
const leftDrawer = ref(!Platform.is.mobile);
const leftDrawerMini = ref(true);
const leftDrawerMini = ref(false);
const mainLinks = flaschengeist?.menuLinks || [];
const notifications = computed(() => mainStore.notifications.slice().reverse());
const polling = ref(NaN);
@ -150,11 +131,9 @@ export default defineComponent({
void mainStore.getShortcuts();
});
onBeforeUnmount(() => window.clearInterval(polling.value));
/*
function openMenu(event: { target: HTMLInputElement }) {
console.log(event.target.nodeName);
if (event.target.nodeName === 'DIV' || event.target.nodeName === 'I')
leftDrawerMini.value = false;
if (event.target.nodeName === 'DIV') leftDrawerMini.value = false;
else {
if (!leftDrawer.value || leftDrawerMini.value) {
leftDrawer.value = true;
@ -165,13 +144,7 @@ export default defineComponent({
}
}
}
*/
function openMenu(value = !leftDrawer.value) {
leftDrawer.value = value;
}
function openMenuMini(value = !leftDrawerMini.value) {
leftDrawerMini.value = value;
}
function logout() {
void router.push({ name: 'login', params: { logout: 'logout' } });
void mainStore.logout();
@ -234,7 +207,6 @@ export default defineComponent({
notifications,
noPermission,
openMenu,
openMenuMini,
remove,
requestPermission,
useNative,

View File

@ -2,9 +2,9 @@
<q-page
padding
style="grid-auto-rows: 1fr"
class="row justify-center content-center items-center q-col-gutter-lg"
class="fit row justify-around items-start q-col-gutter-sm"
>
<div v-for="(item, index) in widgets" :key="index" class="full-height col-sm-6 col-xs-12">
<div v-for="(item, index) in widgets" :key="index" class="col-4 full-height col-sm-6 col-xs-12">
<component :is="item.widget" />
</div>
</q-page>

View File

@ -70,11 +70,10 @@
<script lang="ts">
import { useRouter } from 'vue-router';
import { Loading, Notify, useQuasar } from 'quasar';
import { api, notEmpty, PersistentStorage, useMainStore } from '@flaschengeist/api';
import { Loading, Notify } from 'quasar';
import { api, notEmpty, PersistentStorage, useMainStore, useUserStore } from '@flaschengeist/api';
import { PasswordInput } from '@flaschengeist/api/components';
import { defineComponent, onMounted, ref } from 'vue';
import { useSessionStore } from 'app/api';
export default defineComponent({
name: 'PageLogin',
@ -89,9 +88,8 @@ export default defineComponent({
const mainRoute = { name: 'dashboard' };
const mainStore = useMainStore();
const sessionStore = useSessionStore();
const userStore = useUserStore();
const router = useRouter();
const quasar = useQuasar();
onMounted(() => {
if (mainStore.session) void router.replace(mainRoute);
@ -117,31 +115,10 @@ export default defineComponent({
const status = await mainStore.login(userid.value, password.value);
if (status === true) {
// On capacitor we set the lifetime to at least two weeks to not annoy users.
if (quasar.platform.is.capacitor)
await sessionStore.updateSession(14 * 24 * 60 * 60, mainStore.currentSession.token);
// Redirect user to previous page, if any.
// there are different redirects possible:
// 1. when explicitely entered
// a) http://localhost:8080/ -> should be redirected to mainRoute
// b) http://localhost:8080/in/user/settings -> should be redirected to in/user/settings
// 2. when automatically logged out:
// http://localhost:8080/login?redirect=/in/user/settings
// -> should be redirected to in/user/settings
var redirect;
if (router.currentRoute.value.redirectedFrom) {
redirect = router.currentRoute.value.redirectedFrom.path;
if (redirect === '/') {
redirect = mainRoute;
}
} else if ('redirect' in router.currentRoute.value.query) {
redirect = { path: router.currentRoute.value.query.redirect as string };
mainStore.user = await userStore.getUser(userid.value, true);
const x = router.currentRoute.value.query['redirect'];
void router.push(typeof x === 'string' ? { path: x } : mainRoute);
} else {
redirect = mainRoute;
}
void router.push(redirect);
} else {
// Login failed, notify and reset form
password.value = '';
if (status === 401) {
Notify.create({

View File

@ -1 +1,3 @@
module.exports = ['@flaschengeist/users'];
module.exports = [
'@flaschengeist/users',
]

View File

@ -1,5 +1,5 @@
{
"extends": "@quasar/app-webpack/tsconfig-preset",
"extends": "@quasar/app/tsconfig-preset",
"target": "esnext",
"compilerOptions": {
"baseUrl": ".",