Verified Commit aa63c3e7 authored by les's avatar les
Browse files

[refactoring] settings middleware

parent 7f70eae3
All notable changes to this project will be documented in this file.
### unreleased
- [feat] add cors to feed requests
- [refactoring] settings middleware
### 0.14.18
- [improve] better quality for images
- [fix] password recovery email
......
{
"name": "gancio",
"version": "0.14.17",
"version": "0.14.18",
"description": "A shared agenda for local communities",
"author": "lesion",
"scripts": {
......
<template lang="pug">
el-card
nuxt-link.float-right(to='/')
v-icon(name='times' color='red')
el-button(circle icon='el-icon-close' type='danger' size='small' plain)
h3 {{$t('common.info')}}
div(v-html='$t("about")')
......
<template lang="pug">
<template lang='pug'>
#home
Nav
Home
......@@ -11,7 +11,7 @@ import Nav from '~/components/Nav.vue'
export default {
name: 'Index',
async fetch ({ store, $axios }) {
try {
try {
const now = new Date()
const events = await $axios.$get(`/event/${now.getMonth()}/${now.getFullYear()}`)
store.commit('setEvents', events)
......
......@@ -4,7 +4,6 @@
el-button(circle icon='el-icon-close' type='danger' size='small' plain)
h5 {{$t('common.settings')}}
el-divider {{$auth.user.email}}
el-form(action='/api/user' method='PUT' @submit.native.prevent='update_settings' inline label-width='200px')
el-form-item(:label="$t('settings.change_password')")
......
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import merge from 'lodash/merge'
import locales from '../locales'
import acceptLanguage from 'accept-language'
import messages from '../locales'
// import acceptLanguage from 'accept-language'
Vue.use(VueI18n)
export default async ({ app, store, req }) => {
if (process.server) {
const acceptedLanguages = req.headers['accept-language']
const supportedLanguages = ['en', 'it', 'es']
acceptLanguage.languages(supportedLanguages)
const lang = acceptLanguage.get(acceptedLanguages)
store.commit('setLocale', lang || 'it')
const user_locale = await app.$axios.$get('/settings/user_locale')
if (user_locale[store.state.locale]) { store.commit('setUserLocale', user_locale[store.state.locale]) }
store.commit('setLocale', req.settings.locale)
if (req.settings.user_locale) store.commit('setUserLocale', req.settings.user_locale)
}
if (store.state.user_locale) {
merge(locales[store.state.locale], store.state.user_locale)
merge(messages[store.state.locale], store.state.user_locale)
}
// Set i18n instance on app
app.i18n = new VueI18n({
locale: store.state.locale,
fallbackLocale: 'it',
messages: locales
fallbackLocale: 'en',
messages
})
}
......@@ -5,6 +5,17 @@ const path = require('path')
const fs = require('fs')
const package = require('../../../package.json')
/**
* Settings controller: store instance settings
* Current supported settings:
*
*
* Usage:
* backend/fediverse/api:
*
* frontend:
*/
const settingsController = {
settings: { initialized: false },
user_locale: {},
......
......@@ -24,19 +24,21 @@ api.use(bodyParser.json())
const jwt = expressJwt({
secret: config.secret,
credentialsRequired: false,
getToken: function fromHeaderOrQuerystring (req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1]
} else if (req.cookies && req.cookies['auth._token.local']) {
const [ prefix, token ] = req.cookies['auth._token.local'].split(' ')
if (prefix === 'Bearer') { return token }
}
}
// getToken: function fromHeaderOrQuerystring (req) {
// if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
// return req.headers.authorization.split(' ')[1]
// } else if (req.cookies && req.cookies['auth._token.local']) {
// const [ prefix, token ] = req.cookies['auth._token.local'].split(' ')
// if (prefix === 'Bearer') { return token }
// }
// }
})
// api.use(jwt)
// AUTH
api.post('/auth/login', userController.login)
api.get('/auth/user', jwt, fillUser, userController.current)
api.get('/auth/user', fillUser, userController.current)
api.post('/user/recover', userController.forgotPassword)
api.post('/user/check_recover_code', userController.checkRecoverCode)
......@@ -44,56 +46,56 @@ api.post('/user/recover_password', userController.updatePasswordWithRecoverCode)
// register and add users
api.post('/user/register', userController.register)
api.post('/user', jwt, isAuth, isAdmin, userController.create)
api.post('/user', isAuth, isAdmin, userController.create)
// update user
api.put('/user', jwt, isAuth, userController.update)
api.put('/user', isAuth, userController.update)
// delete user
api.delete('/user/:id', jwt, isAuth, isAdmin, userController.remove)
api.delete('/user/:id', isAuth, isAdmin, userController.remove)
//
// api.delete('/user', userController.remove)
// get all users
api.get('/users', jwt, isAuth, isAdmin, userController.getAll)
api.get('/users', isAuth, isAdmin, userController.getAll)
// update a tag (modify color)
api.put('/tag', jwt, isAuth, isAdmin, eventController.updateTag)
api.put('/tag', isAuth, isAdmin, eventController.updateTag)
// update a place (modify address..)
api.put('/place', jwt, isAuth, isAdmin, eventController.updatePlace)
api.put('/place', isAuth, isAdmin, eventController.updatePlace)
// add event
api.post('/user/event', jwt, fillUser, upload.single('image'), userController.addEvent)
api.post('/user/event', fillUser, upload.single('image'), userController.addEvent)
// update event
api.put('/user/event', jwt, isAuth, upload.single('image'), userController.updateEvent)
api.put('/user/event', isAuth, upload.single('image'), userController.updateEvent)
// remove event
api.delete('/user/event/:id', jwt, isAuth, userController.delEvent)
api.delete('/user/event/:id', isAuth, userController.delEvent)
// get tags/places
api.get('/event/meta', eventController.getMeta)
// get unconfirmed events
api.get('/event/unconfirmed', jwt, isAuth, isAdmin, eventController.getUnconfirmed)
api.get('/event/unconfirmed', isAuth, isAdmin, eventController.getUnconfirmed)
// add event notification
api.post('/event/notification', eventController.addNotification)
api.delete('/event/notification/:code', eventController.delNotification)
api.get('/settings', settingsController.getAllRequest)
api.post('/settings', jwt, fillUser, isAdmin, settingsController.setRequest)
api.post('/settings', fillUser, isAdmin, settingsController.setRequest)
api.get('/settings/user_locale', settingsController.getUserLocale)
// confirm event
api.get('/event/confirm/:event_id', jwt, isAuth, isAdmin, eventController.confirm)
api.get('/event/unconfirm/:event_id', jwt, isAuth, isAdmin, eventController.unconfirm)
api.get('/event/confirm/:event_id', isAuth, isAdmin, eventController.confirm)
api.get('/event/unconfirm/:event_id', isAuth, isAdmin, eventController.unconfirm)
// get event
api.get('/event/:event_id', jwt, fillUser, eventController.get)
api.get('/event/:event_id', fillUser, eventController.get)
// export events (rss/ics)
api.get('/export/:type', exportController.export)
......
const settingsController = require('./api/controller/settings')
const acceptLanguage = require('accept-language')
const expressJwt = require('express-jwt')
const debug = require('debug')
const config = require('config')
const package = require('../package.json')
const jwt = expressJwt({
secret: config.secret,
credentialsRequired: false,
getToken: function fromHeaderOrQuerystring (req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1]
} else if (req.cookies && req.cookies['auth._token.local']) {
const [ prefix, token ] = req.cookies['auth._token.local'].split(' ')
if (prefix === 'Bearer') { return token }
}
return null
}
})
module.exports = {
initMiddleware (req, res, next) {
// initialize settings
req.settings = settingsController.settings
req.secretSettings = settingsController.secretSettings
// const package = require('../package.json')
req.settings.baseurl = config.baseurl
req.settings.title = config.title
req.settings.description = config.description
req.settings.version = package.version
// set locale and user locale
const acceptedLanguages = req.headers['accept-language']
const supportedLanguages = ['en', 'it', 'es']
acceptLanguage.languages(supportedLanguages)
req.settings.locale = acceptLanguage.get(acceptedLanguages)
req.settings.user_locale = settingsController.user_locale[req.settings.locale]
// auth
jwt(req, res, () => {
next()
})
}
}
\ No newline at end of file
......@@ -8,8 +8,9 @@ const webfinger = require('./federation/webfinger')
const { spamFilter } = require('./federation/helpers')
const debug = require('debug')('routes')
const exportController = require('./api/controller/export')
const helpers = require('./helpers')
const router = express.Router()
router.use((req, res, next) => {
debug(req.path)
next()
......@@ -18,9 +19,17 @@ router.use((req, res, next) => {
// ignore unimplemented ping url from fediverse
router.use(spamFilter)
// serve favicon and static content
router.use('/favicon.ico', express.static(path.resolve(config.favicon || './assets/favicon.ico')))
router.use('/media/', express.static(config.upload_path))
// get instance settings
router.use(helpers.initMiddleware)
// rss/ics/atom feed
router.get('/feed/:type', cors(), exportController.export)
// api!
router.use('/api', api)
// federation api / activitypub / webfinger / nodeinfo
......@@ -33,6 +42,7 @@ router.use((error, req, res, next) => {
res.status(500).send('500: Internal Server Error')
})
// remaining request are for nuxt...
// remaining request goes to nuxt
// first nuxt component is ./pages/index.vue
module.exports = router
......@@ -146,11 +146,8 @@ export const actions = {
// this method is called server side only for each request
// we use it to get configuration from db, setting locale, etc...
async nuxtServerInit ({ commit }, { app, store, req }) {
// TOFIX: check if we could retrieve it directly?
const settings = await app.$axios.$get('/settings')
const settings = req.settings
commit('setSettings', settings)
// apply settings
commit('showRecurrentEvents', settings.allow_recurrent_event && settings.recurrent_event_visible)
},
......
This diff is collapsed.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment