This commit is contained in:
lesion 2019-06-07 17:02:33 +02:00
parent 7455553129
commit c408c44676
40 changed files with 270 additions and 279 deletions

View file

@ -19,6 +19,10 @@ module.exports = {
],
// add your custom rules here
rules: {
'nuxt/no-cjs-in-config': 'off'
'nuxt/no-cjs-in-config': 'off',
'camelcase': 'off',
'no-console': 'off',
'arrow-parens': 'off',
'import/order': 'off'
}
}

View file

@ -1,7 +1,7 @@
const path = require('path')
module.exports = {
'config': path.resolve('server' ,'config.js'),
'config': path.resolve('config.js'),
'migrations-path': path.resolve('server', 'migrations'),
'models-path': path.resolve('server', 'api', 'models')
}

View file

@ -41,7 +41,7 @@ const it = {
logout_ok: 'Uscita correttamente',
copy: 'Copia'
},
login: {
description: `Entrando puoi pubblicare nuovi eventi.`,
check_email: 'Controlla la tua posta (anche lo spam)',
@ -75,7 +75,9 @@ const it = {
description: `I movimenti hanno bisogno di organizzarsi e autofinanziarsi. <br/>Questo è un dono per voi, usatelo solo per eventi non commerciali e ovviamente antifascisti, antisessisti, antirazzisti.
<br/>Prima di poter pubblicare <strong>dobbiamo approvare l'account</strong>, considera che <strong>dietro questo sito ci sono delle persone</strong> di
carne e sangue, scrivici quindi due righe per farci capire che eventi vorresti pubblicare.`,
error: 'Errore: '
error: 'Errore: ',
admin_complete: 'Sei il primo utente e quindi sei amministratore!',
complete: 'Confermeremo la registrazione quanto prima.'
},
event: {
@ -124,9 +126,9 @@ const it = {
firstrun: {
basic: `Inserisci titolo e descrizione della tua istanza di gancio.`,
database: `Gancio ha bisogno di un database postgresql!`,
smtp: `Inserisci un account SMTP relativo a questa istanza di gancio.`,
smtp: `Inserisci un account SMTP relativo a questa istanza di gancio.`
}
}
export default it
export default it

View file

@ -1,4 +1,8 @@
const config = require('./server/config').SHARED_CONF
const argv = require('yargs').argv
const path = require('path')
const config_path = path.resolve(argv.config || './config.js')
const config = require(config_path).SHARED_CONF
module.exports = {
mode: 'universal',
@ -15,7 +19,6 @@ module.exports = {
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]
},
dev: (process.env.NODE_ENV !== 'production'),
serverMiddleware: [
{ path: '/api', handler: '@/server/api/index.js' }
],
@ -30,18 +33,20 @@ module.exports = {
*/
css: [
'bootstrap/dist/css/bootstrap.css',
'element-ui/lib/theme-chalk/index.css',
'element-ui/lib/theme-chalk/index.css'
],
env: {
config
},
/*
** Plugins to load before mounting the App
*/
plugins: [
'@/plugins/element-ui', // UI library -> https://element.eleme.io/#/en-US/
'@/plugins/filters', // text filters, datetime, etc.
'@/plugins/i18n', // localization plugin
'@/plugins/filters', // text filters, datetime, etc.
'@/plugins/i18n', // localization plugin
'@/plugins/vue-awesome', // icon
{ src: '@/plugins/v-calendar', ssr: false }, // calendar, TO-REDO
{ src: '@/plugins/v-calendar', ssr: false } // calendar, TO-REDO
],
/*
@ -58,7 +63,7 @@ module.exports = {
axios: {
baseURL: config.baseurl + '/api',
browserBaseURL: config.baseurl + '/api',
prefix: '/api',
prefix: '/api'
// credentials: true
// See https://github.com/nuxt-community/axios-module#options
},
@ -68,37 +73,19 @@ module.exports = {
endpoints: {
login: { url: '/auth/login', method: 'post', propertyName: 'token' },
logout: false,
user: { url: '/auth/user', method: 'get', propertyName: false },
},
user: { url: '/auth/user', method: 'get', propertyName: false }
}
}
}
},
/*
** Build configuration
*/
build: {
// babel: {
// presets: ['@nuxt/babel-preset-app']
// },
transpile: [/^element-ui/, /^vue-awesome/],
splitChunks: {
layouts: true
}
/*
** You can extend webpack config here
*/
// extend(config, ctx) {
// Run ESLint on save
// if (ctx.isDev && ctx.isClient) {
// config.module.rules.push({
// enforce: 'pre',
// test: /\.(js|vue)$/,
// loader: 'eslint-loader',
// exclude: /(node_modules)/
// })
// }
// }
}
}

View file

@ -1,5 +1,9 @@
<template lang="pug">
el-dialog(:title='$t("common.admin")' width='80%' :visible='open' :before-close='close')
el-card(:title='$t("common.admin")' width='80%' :visible='open' :before-close='close')
nuxt-link.float-right(to='/')
v-icon(name='times' color='red')
h5 {{$t('common.admin')}}
el-tabs(tabPosition='left' v-model='tab')
//- USERS
@ -81,9 +85,18 @@
template(slot='label')
v-icon(name='cog')
span {{$t('common.settings')}}
//- el-form(inline @submit.prevent.stop='save_settings' label-width='140px')
//- p {{$t('settings.name_description')}}
//- el-form-item(:label="$t('settings.name')")
//- el-input(v-model="settings.title")
//- el-form-item(:label="$t('settings.description')")
//- el-input(v-model="settings.description")
//- el-button(slot='append' @click='associate' :disabled='!mastodon_instance.length') {{$t('common.associate')}}
el-form(inline @submit.prevent.stop='associatemastodon_instance')
span {{$t('admin.mastodon_description')}}
el-input(v-model="mastodon_instance")
el-input(v-model="settings.mastodon_instance")
span(slot='prepend') {{$t('admin.mastodon_instance')}}
el-button(slot='append' @click='associate' :disabled='!mastodon_instance.length') {{$t('common.associate')}}
@ -111,7 +124,9 @@ export default {
tag: {name: '', color: ''},
events: [],
loading: false,
mastodon_instance: '',
settings: {
mastodon_instance: '',
},
settings: {},
tab: "0",
open: true

View file

@ -11,9 +11,9 @@ export default {
components: { List },
computed: mapState(['config']),
async asyncData ({ $axios, req, res }) {
const title = req.query.title || config.title
const tags = req.query.tags
const places = req.query.places
const title = req && req.query && req.query.title || this.config.title
const tags = req && req.query && req.query.tags
const places = req && req.query && req.query.places
const now = new Date()
let params = []

View file

@ -2,7 +2,6 @@
#home
Nav
Home
</template>
<script>
@ -12,22 +11,16 @@ import { mapState } from 'vuex'
export default {
name: 'Index',
async asyncData ({ redirect, store }) {
// console.error('diocane', store.state.settings)
// const firstRun = store.state.settings.firstRun
// if (firstRun!==true) {
// redirect('/firstrun')
// }
},
async fetch ({ store, $axios }) {
const now = new Date()
const events = await $axios.$get(`/event/${now.getMonth()}/${now.getFullYear()}`)
console.error(events)
store.commit('setEvents', events)
const { tags, places } = await $axios.$get('/event/meta')
store.commit('update', { tags, places })
// const settings = await $axios.$get('/settings')
// store.commit('setSettings', settings)
try {
const now = new Date()
const events = await $axios.$get(`/event/${now.getMonth()}/${now.getFullYear()}`)
store.commit('setEvents', events)
const { tags, places } = await $axios.$get('/event/meta')
store.commit('update', { tags, places })
} catch(e) {
console.error(e)
}
},
computed: mapState(['events']),
components: { Nav, Home },

View file

@ -27,7 +27,6 @@
</template>
<script>
const Cookie = process.client ? require('js-cookie') : undefined
import { mapActions } from 'vuex'
import { Message } from 'element-ui'
import get from 'lodash/get'

View file

@ -5,26 +5,26 @@
v-icon(name='times' color='red')
h5 {{$t('common.register')}}
el-form(method='POST' action='/api/user')
el-form(@submit.native.prevent='register' method='POST' action='/api/user')
p(v-html="$t('register.description')")
el-input.mb-2(ref='email' v-model='user.email' type='email' required
:placeholder='$t("common.email")' autocomplete='email' name='email')
span(slot='prepend') @
el-input.mb-2(v-model='user.password' type="password" placeholder="Password" name='password')
el-input.mb-2(v-model='user.password' type="password" placeholder="Password" name='password' required)
v-icon(name='lock' slot='prepend')
el-input.mb-2(v-model='user.description' type="textarea" rows='3' :placeholder="$t('common.description')")
v-icon(name='envelope-open-text')
el-button(plain type="success" native-type='submit'
:disabled='disabled'
@click='register') {{$t('common.send')}} <v-icon name='chevron-right'/>
:disabled='disabled') {{$t('common.send')}} <v-icon name='chevron-right'/>
</template>
<script>
import { mapActions } from 'vuex'
import { Message } from 'element-ui'
import get from 'lodash/get'
export default {
name: 'Register',
@ -44,14 +44,14 @@ export default {
...mapActions(['login']),
async register () {
try {
const user = await this.$axios.$post('/user', this.user)
const { user } = await this.$axios.$post('/user', this.user)
Message({
message: this.$t(`register.${user.is_admin && 'admin_'}complete`),
message: this.$t(`register.${user.is_admin ? 'admin_' : ''}complete`),
type: 'success'
})
this.$router.replace("/")
} catch (e) {
const error = e && e.response && e.response.data && e.response.data.errors[0].message || e
const error = get(e, 'e.response.data.errors[0].message', String(e))
Message({
message: this.$t('register.error') + this.$t(error),
type: 'error'

View file

@ -1,5 +1,9 @@
<template lang="pug">
el-dialog(:title="$t('common.settings')" :before-close='close' visible)
el-card
nuxt-link.float-right(to='/')
v-icon(name='times' color='red')
h5 {{$t('common.settings')}}
//- el-form
//- el-form-item {{$t('settings.change_password')}}
el-divider {{$t('settings.change_password')}}
@ -23,11 +27,11 @@ export default {
methods: {
async change () {
if (!this.password) return
const user = this.user
user.password = this.password
// this.$auth.user.password = this.password
const user_data = { id : this.$auth.user.id, password: this.password }
try {
// this.$axios.
// await api.updateUser(user)
const user = await this.$axios.$put('/user', user_data)
console.error(user)
} catch (e) {
console.log(e)
}

View file

@ -23,11 +23,9 @@ export default (a) => {
const end = moment(event.end_datetime)
if (event.multidate) {
return `${start.format('ddd, D MMMM')} (${short_hour(start)}) - ${end.format('ddd, D MMMM')} (${short_hour(end)})`
} else {
if (event.end_datetime && event.end_datetime !== event.start_datetime)
} else if (event.end_datetime && event.end_datetime !== event.start_datetime)
return `${start.format('ddd, D MMMM')} (${short_hour(start)}-${short_hour(end)}`
else
return `${start.format('dddd, D MMMM')} (${short_hour(start)})`
}
})
}
}

View file

@ -11,8 +11,7 @@ export default ({ app, store }) => {
locale: store.state.locale,
fallbackLocale: 'it',
messages: {
it
// 'fr': require('~/locales/fr.json')
it
}
})

View file

@ -5,4 +5,4 @@ export default () => {
Vue.use(VCalendar, {
firstDayOfWeek: 2
})
}
}

View file

@ -9,12 +9,12 @@ moment.locale('it')
const botController = {
bot: null,
async initialize () {
async initialize() {
console.error('dentro bot inizialiteds')
const settings = await settingsController.settings()
if (!settings.mastodon_auth || !settings.mastodon_auth.access_token) return
const mastodon_auth = settings.mastodon_auth
botController.bot = new Mastodon({
botController.bot = new Mastodon({
access_token: mastodon_auth.access_token,
api_url: `https://${mastodon_auth.instance}/api/v1`
})
@ -41,7 +41,7 @@ const botController = {
// listener.on('error', botController.error)
// botController.bots.push({ email: user.email, bot })
},
async post (mastodon_auth, event) {
async post(mastodon_auth, event) {
const { access_token, instance } = mastodon_auth
const bot = new Mastodon({ access_token, api_url: `https://${instance}/api/v1/` })
const status = `${event.title} @ ${event.place.name} ${moment(event.start_datetime).format('ddd, D MMMM HH:mm')} -
@ -58,20 +58,20 @@ ${event.description.length > 200 ? event.description.substr(0, 200) + '...' : ev
},
// TOFIX: enable message deletion
async message (msg) {
async message(msg) {
const replyid = msg.data.in_reply_to_id || msg.data.last_status.in_reply_to_id
if (!replyid) return
const event = await Event.findOne({ where: { activitypub_id: replyid } })
if (!event) {
// check for comment..
// const comment = await Comment.findOne( {where: { }})
return
return
}
const comment = await Comment.create({
activitypub_id: msg.data.last_status.id,
activitypub_id: msg.data.last_status.id,
// text: msg.data.last_status.content,
data: msg.data,
// author: msg.data.accounts[0].username
data: msg.data
// author: msg.data.accounts[0].username
})
event.addComment(comment)
// const comment = await Comment.findOne( { where: {activitypub_id: msg.data.in_reply_to}} )
@ -86,7 +86,7 @@ ${event.description.length > 200 ? event.description.substr(0, 200) + '...' : ev
// const comment = new Comment(req.body)
// event.addComment(comment)
},
error (err) {
error(err) {
console.log('error ', err)
}
}

View file

@ -23,7 +23,7 @@ const eventController = {
const places = await Place.findAll({
order: [[Sequelize.literal('weigth'), 'DESC']],
attributes: {
include: [[Sequelize.fn('count', Sequelize.col('events.placeId')) ,'weigth']], // <---- Here you will get the total count of user
include: [[Sequelize.fn('count', Sequelize.col('events.placeId')) , 'weigth']], // <---- Here you will get the total count of user
exclude: ['weigth', 'createdAt', 'updatedAt']
},
include: [{ model: Event, attributes: [] }],
@ -31,7 +31,7 @@ const eventController = {
})
const tags = await Tag.findAll({
order: [['weigth' , 'DESC']],
order: [['weigth', 'DESC']],
includeIgnoreAttributes: false,
attributes: {
exclude: ['createdAt', 'updatedAt']
@ -89,8 +89,8 @@ const eventController = {
Tag,
Comment,
{ model: Place, attributes: ['name', 'address'] }
] ,
order: [ [Comment, 'id', 'DESC'], [Tag, 'weigth', 'DESC'] ]
],
order: [ [Comment, 'id', 'DESC'], [Tag, 'weigth', 'DESC'] ]
})
res.json(event)
},
@ -176,13 +176,13 @@ const eventController = {
]
},
order: [
['start_datetime', 'ASC'],
['start_datetime', 'ASC'],
[Tag, 'weigth', 'DESC']
],
include: [
// { model: User, required: false },
// { type: Comment, required: false, attributes: ['']
{ model: Tag, required: false, attributes: ['tag', 'weigth','color'] },
{ model: Tag, required: false, attributes: ['tag', 'weigth', 'color'] },
{ model: Place, required: false, attributes: ['id', 'name', 'address'] }
]
})

View file

@ -1,12 +1,11 @@
const { event: Event, place: Place } = require('../models')
const { Op } = require('sequelize')
const config = require('../../config').SHARED_CONF
const moment = require('moment')
const ics = require('ics')
const exportController = {
async export (req, res) {
async export(req, res) {
console.log('type ', req.params.type)
console.error(req)
const type = req.params.type
@ -21,18 +20,17 @@ const exportController = {
if (places) {
wherePlace.id = places.split(',')
}
console.error(places)
const events = await Event.findAll({
order: ['start_datetime'],
where: {
is_visible: true,
where: {
is_visible: true,
start_datetime: { [Op.gte]: yesterday },
placeId: places.split(',')
},
attributes: {
exclude: ['createdAt', 'updatedAt']
},
include: [{model: Place, attributes: ['name', 'id', 'address', 'weigth']}]
include: [{ model: Place, attributes: ['name', 'id', 'address', 'weigth'] }]
})
switch (type) {
case 'feed':
@ -44,12 +42,12 @@ const exportController = {
}
},
async feed (res, events) {
feed(res, events) {
res.type('application/rss+xml; charset=UTF-8')
res.render('feed/rss.pug', { events, config, moment })
res.render('feed/rss.pug', { events, config: process.env.config, moment })
},
async ics (res, events) {
ics(res, events) {
const eventsMap = events.map(e => {
const tmpStart = moment(e.start_datetime)
const tmpEnd = moment(e.end_datetime)

View file

@ -1,10 +1,11 @@
const Mastodon = require('mastodon-api')
const { setting: Setting } = require('../models')
const config = require('../../config').SHARED_CONF
const baseurl = process.env.baseurl
const settingsController = {
async setAdminSetting (key, value) {
async setAdminSetting(key, value) {
await Setting.findOrCreate({ where: { key },
defaults: { value } })
.spread((settings, created) => {
@ -12,20 +13,16 @@ const settingsController = {
})
},
async getAdminSettings (req, res) {
async getAdminSettings(req, res) {
const settings = await settingsController.settings()
res.json(settings)
},
async getConfig (req, res) {
res.json(config)
},
async getAuthURL(req, res) {
const instance = req.body.instance
const callback = `${config.baseurl}/api/settings/oauth`
const callback = `${baseurl}/api/settings/oauth`
const { client_id, client_secret } = await Mastodon.createOAuthApp(`https://${instance}/api/v1/apps`,
config.title, 'read write', callback)
'gancio', 'read write', callback)
const url = await Mastodon.getAuthorizationUrl(client_id, client_secret,
`https://${instance}`, 'read write', callback)
@ -36,7 +33,7 @@ const settingsController = {
async code(req, res) {
const code = req.query.code
let client_id, client_secret, instance
const callback = `${config.baseurl}/api/settings/oauth`
const callback = `${baseurl}/api/settings/oauth`
const settings = await settingsController.settings()
@ -47,18 +44,17 @@ const settingsController = {
`https://${instance}`, callback)
const mastodon_auth = { client_id, client_secret, access_token: token, instance }
await settingsController.setAdminSetting('mastodon_auth', mastodon_auth)
res.redirect('/admin')
} catch (e) {
res.json(e)
}
},
async settings () {
console.error('ma sono dentro settings ?!?!')
async settings() {
const settings = await Setting.findAll()
return settings
},
}
}

View file

@ -4,14 +4,13 @@ const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const { Op } = require('sequelize')
const jsonwebtoken = require('jsonwebtoken')
const { SECRET_CONF, SHARED_CONF } = require('../../config')
const mail = require('../mail')
const { user: User, event: Event, tag: Tag, place: Place } = require('../models')
const eventController = require('./event')
const config = require('../../config')
const userController = {
async login(req, res) {
// find the user
const user = await User.findOne({ where: { email: { [Op.eq]: req.body && req.body.email } } })
if (!user) {
@ -31,10 +30,10 @@ const userController = {
email: user.email,
scope: [user.is_admin ? 'admin' : 'user']
},
SECRET_CONF.secret
config.SECRET_CONF.secret
)
res.json({token: accessToken})
res.json({ token: accessToken })
}
}
},
@ -89,9 +88,7 @@ const userController = {
eventDetails.image_path = req.file.filename
}
console.error('prima la creazione di evento')
let event = await Event.create(eventDetails)
console.error('dopo la creazione di evento')
// create place if needs to
let place
@ -167,7 +164,7 @@ const userController = {
if (!user) return res.sendStatus(200)
user.recover_code = crypto.randomBytes(16).toString('hex')
mail.send(user.email, 'recover', { user, config: SHARED_CONF })
mail.send(user.email, 'recover', { user, config: config.SHARED_CONF })
await user.save()
res.sendStatus(200)
@ -191,16 +188,13 @@ const userController = {
try {
await user.save()
res.sendStatus(200)
} catch(e) {
} catch (e) {
res.sendStatus(400)
}
},
async current(req, res) {
if (req.user)
res.json(req.user)
else
res.sendStatus(404)
current(req, res) {
if (req.user) { res.json(req.user) } else { res.sendStatus(404) }
},
async getAll(req, res) {
@ -212,9 +206,10 @@ const userController = {
async update(req, res) {
const user = await User.findByPk(req.body.id)
console.error(req.body.id)
if (user) {
if (!user.is_active && req.body.is_active) {
await mail.send(user.email, 'confirm', { user, config: SHARED_CONF })
await mail.send(user.email, 'confirm', { user, config: config.SHARED_CONF })
}
await user.update(req.body)
res.json(user)
@ -226,7 +221,6 @@ const userController = {
async register(req, res) {
const n_users = await User.count()
try {
// the first registered user will be an active admin
if (n_users === 0) {
req.body.is_active = req.body.is_admin = true
@ -236,7 +230,7 @@ const userController = {
const user = await User.create(req.body)
try {
mail.send([user.email, SECRET_CONF.admin], 'register', { user, config: SHARED_CONF })
mail.send([user.email, config.SECRET_CONF.admin], 'register', { user, config: config.SHARED_CONF })
} catch (e) {
return res.status(400).json(e)
}
@ -245,9 +239,8 @@ const userController = {
email: user.email,
scope: [user.is_admin ? 'admin' : 'user']
}
const token = jwt.sign(payload, SECRET_CONF.secret)
res.json({ token })
// res.redirect('/')
const token = jwt.sign(payload, config.SECRET_CONF.secret)
res.json({ token, user })
} catch (e) {
res.status(404).json(e)
}

View file

@ -3,6 +3,7 @@ const multer = require('multer')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const expressJwt = require('express-jwt')
const config = require('../config')
const { fillUser, isAuth, isAdmin } = require('./auth')
const eventController = require('./controller/event')
@ -10,8 +11,6 @@ const exportController = require('./controller/export')
const userController = require('./controller/user')
const settingsController = require('./controller/settings')
const { SECRET_CONF } = require('../config')
const storage = require('./storage')({
destination: 'uploads/'
})
@ -23,19 +22,20 @@ api.use(bodyParser.urlencoded({ extended: false }))
api.use(bodyParser.json())
const jwt = expressJwt({
secret: SECRET_CONF.secret,
credentialsRequired: false,
// getToken: req => {
// // if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
// // return req.headers.authorization.split(' ')[1];
// if (req.cookies && req.cookies['token']) {
// console.error(req.cookies['token'])
// return req.cookies['token']
// }
// return null
// }
secret: config.SECRET_CONF.secret,
credentialsRequired: false
})
function errorHandler(fn) {
return async (req, res) => {
try {
await fn(req, res)
} catch (e) {
console.error(String(e))
return res.status(500).json(e)
}
}
}
// AUTH
api.post('/auth/login', userController.login)
@ -84,7 +84,6 @@ api.get('/event/unconfirmed', jwt, isAuth, isAdmin, eventController.getUnconfirm
api.post('/event/notification', eventController.addNotification)
api.delete('/event/notification/:code', eventController.delNotification)
api.get('/config', settingsController.getConfig)
api.get('/settings', jwt, fillUser, isAdmin, settingsController.getAdminSettings)
api.post('/settings', jwt, fillUser, isAdmin, settingsController.setAdminSetting)
@ -99,7 +98,7 @@ api.get('/event/unconfirm/:event_id', jwt, isAuth, isAdmin, eventController.unco
api.get('/export/:type', exportController.export)
// get events in this range
api.get('/event/:month/:year', eventController.getAll)
api.get('/event/:month/:year', errorHandler(eventController.getAll))
// mastodon oauth auth
api.post('/settings/getauthurl', jwt, isAuth, isAdmin, settingsController.getAuthURL)

View file

@ -2,10 +2,10 @@ const Email = require('email-templates')
const path = require('path')
const moment = require('moment')
const config = require('../config')
moment.locale(config.SHARED_CONF.locale)
moment.locale(config.SHARED_CONF.locale)
const mail = {
send (addresses, template, locals) {
send(addresses, template, locals) {
const email = new Email({
views: { root: path.join(__dirname, '..', 'emails') },
juice: true,

View file

@ -1,13 +1,13 @@
'use strict';
'use strict'
module.exports = (sequelize, DataTypes) => {
const comment = sequelize.define('comment', {
activitypub_id: DataTypes.BIGINT,
data: DataTypes.JSON
}, {});
comment.associate = function(models) {
}, {})
comment.associate = function (models) {
comment.belongsTo(models.event)
// Event.hasMany(Comment)
// Event.hasMany(Comment)
// associations can be defined here
};
return comment;
};
}
return comment
};

View file

@ -1,11 +1,11 @@
'use strict';
'use strict'
module.exports = (sequelize, DataTypes) => {
const event = sequelize.define('event', {
title: DataTypes.STRING,
slug: DataTypes.STRING,
description: DataTypes.TEXT,
multidate: DataTypes.BOOLEAN,
start_datetime: {
start_datetime: {
type: DataTypes.DATE,
index: true
},
@ -16,16 +16,16 @@ module.exports = (sequelize, DataTypes) => {
type: DataTypes.BIGINT,
index: true
}
}, {});
event.associate = function(models) {
}, {})
event.associate = function (models) {
event.belongsTo(models.place)
event.belongsTo(models.user)
event.belongsToMany(models.tag, { through: 'event_tags' })
event.belongsToMany(models.notification, { through: 'event_notification' })
event.hasMany(models.comment)
// Tag.belongsToMany(Event, { through: 'tagEvent' })
// Tag.belongsToMany(Event, { through: 'tagEvent' })
// Event.hasMany(models.Tag)
// associations can be defined here
};
return event;
};
}
return event
};

View file

@ -1,4 +1,4 @@
'use strict';
'use strict'
module.exports = (sequelize, DataTypes) => {
const eventNotification = sequelize.define('eventNotification', {
status: {
@ -7,10 +7,10 @@ module.exports = (sequelize, DataTypes) => {
defaultValue: 'new',
index: true
}
}, {});
eventNotification.associate = function(models) {
}, {})
eventNotification.associate = function (models) {
// associations can be defined here
};
return eventNotification;
};
}
return eventNotification
}

View file

@ -1,31 +1,31 @@
'use strict';
const argv = require('yargs').argv
const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const config_path = path.resolve(argv.config || './config.js')
const basename = path.basename(__filename)
const config = require(config_path).SECRET_CONF.db
const db = {}
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const config = require(__dirname + '/../../config.js').SECRET_CONF.db
const db = {};
let sequelize = new Sequelize(config);
const sequelize = new Sequelize(config)
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')
})
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
const model = sequelize.import(path.join(__dirname, file))
db[model.name] = model
})
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
db[modelName].associate(db)
}
});
})
db.sequelize = sequelize;
db.Sequelize = Sequelize;
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db;
module.exports = db

View file

@ -1,4 +1,4 @@
'use strict';
'use strict'
module.exports = (sequelize, DataTypes) => {
const notification = sequelize.define('notification', {
filters: DataTypes.JSON,
@ -8,10 +8,10 @@ module.exports = (sequelize, DataTypes) => {
type: DataTypes.ENUM,
values: ['mail', 'admin_email', 'mastodon']
}
}, {});
notification.associate = function(models) {
notification.belongsToMany(models.event, { through: 'event_notification' })
}, {})
notification.associate = function (models) {
notification.belongsToMany(models.event, { through: 'event_notification' })
// associations can be defined here
};
return notification;
};
}
return notification
}

View file

@ -1,15 +1,15 @@
'use strict';
'use strict'
module.exports = (sequelize, DataTypes) => {
const place = sequelize.define('place', {
name: DataTypes.STRING,
address: DataTypes.STRING,
weigth: DataTypes.INTEGER
}, {});
}, {})
place.associate = function(models) {
place.associate = function (models) {
// associations can be defined here
place.hasMany(models.event)
};
}
return place;
};
return place
}

View file

@ -1,14 +1,14 @@
'use strict';
'use strict'
module.exports = (sequelize, DataTypes) => {
const setting = sequelize.define('setting', {
key: {
key: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false,
index: true,
index: true
},
value: DataTypes.JSON
}, {});
}, {})
return setting;
};
return setting
}

View file

@ -1,4 +1,4 @@
'use strict';
'use strict'
module.exports = (sequelize, DataTypes) => {
const tag = sequelize.define('tag', {
tag: {
@ -8,12 +8,12 @@ module.exports = (sequelize, DataTypes) => {
},
weigth: DataTypes.INTEGER,
color: DataTypes.STRING
}, {});
}, {})
tag.associate = function(models) {
tag.associate = function (models) {
tag.belongsToMany(models.event, { through: 'event_tags' })
// associations can be defined here
};
}
return tag;
};
return tag
};

View file

@ -1,4 +1,4 @@
'use strict';
'use strict'
const bcrypt = require('bcrypt')
module.exports = (sequelize, DataTypes) => {
@ -14,19 +14,23 @@ module.exports = (sequelize, DataTypes) => {
recover_code: DataTypes.STRING,
is_admin: DataTypes.BOOLEAN,
is_active: DataTypes.BOOLEAN
}, {});
}, {
defaultScope: {
exclude: ['password', 'recover_code']
}
})
user.associate = function(models) {
user.associate = function (models) {
// associations can be defined here
user.hasMany(models.event)
};
}
user.prototype.comparePassword = async function (pwd) {
if (!this.password) return false
const ret = await bcrypt.compare(pwd, this.password)
return ret
}
user.beforeSave(async (user, options) => {
if (user.changed('password')) {
const salt = await bcrypt.genSalt(10)
@ -35,5 +39,5 @@ module.exports = (sequelize, DataTypes) => {
}
})
return user;
};
return user
};

View file

@ -1,8 +1,9 @@
// check config.js existance
const fs = require('fs')
const path = require('path')
const argv = require('yargs').argv
const config_path = path.join(__dirname, 'config.js')
const config_path = path.resolve(argv.config || './config.js')
if (!fs.existsSync(config_path)) {
console.error(`Configuration file not found at '${config_path}. Please copy 'config.example.js' and modify it.`)
@ -12,30 +13,29 @@ if (!fs.existsSync(config_path)) {
const { SECRET_CONF, SHARED_CONF } = require(config_path)
if (!SECRET_CONF.secret) {
console.error(`Please specify a random 'secret' in '${config_path}'!`)
process.exit(1);
process.exit(1)
}
const Sequelize = require('sequelize')
let db
try {
db = new Sequelize(SECRET_CONF.db)
} catch(e) {
} catch (e) {
console.error(`DB Error: check '${SHARED_CONF.env}' configuration.\n (sequelize error -> ${e})`)
process.exit(1)
}
// return db existence
module.exports = db.authenticate()
.then ( () => {
require('./api/models')
if (SHARED_CONF.env === 'development') {
console.error('DB Force sync')
return db.sync({force: true})
}
})
.catch(e => {
console.error(e)
console.error(`DB Error: check '${SHARED_CONF.env}' configuration\n (sequelize error -> ${e})`)
process.exit(1)
})
.then(() => {
require('./api/models')
if (SHARED_CONF.env === 'development') {
console.error('DB Force sync')
return db.sync({ force: true })
}
})
.catch(e => {
console.error(e)
console.error(`DB Error: check '${SHARED_CONF.env}' configuration\n (sequelize error -> ${e})`)
process.exit(1)
})

View file

@ -1,13 +1,14 @@
const firstRun = require('./firstrun')
#!/bin/env node
const path = require('path')
const express = require('express')
const consola = require('consola')
const morgan = require('morgan')
const path = require('path')
const app = express()
const { Nuxt, Builder } = require('nuxt')
const firstRun = require('./firstrun')
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
const app = express()
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
@ -35,4 +36,4 @@ async function start() {
})
}
firstRun.then(start)
firstRun.then(start)

View file

@ -1,4 +1,4 @@
'use strict';
'use strict'
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('events', {
@ -13,7 +13,7 @@ module.exports = {
},
slug: {
type: Sequelize.STRING,
index: true,
index: true
},
description: {
type: Sequelize.TEXT
@ -58,9 +58,9 @@ module.exports = {
allowNull: false,
type: Sequelize.DATE
}
});
})
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('events');
return queryInterface.dropTable('events')
}
};
}

View file

@ -1,4 +1,4 @@
'use strict';
'use strict'
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('notifications', {
@ -19,7 +19,7 @@ module.exports = {
},
type: {
type: Sequelize.ENUM,
values: ['mail', 'admin_email', 'mastodon']
values: ['mail', 'admin_email', 'mastodon']
},
createdAt: {
allowNull: false,
@ -29,9 +29,9 @@ module.exports = {
allowNull: false,
type: Sequelize.DATE
}
});
})
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('notifications');
return queryInterface.dropTable('notifications')
}
};
}

View file

@ -1,4 +1,3 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('event_notification', {
@ -30,9 +29,9 @@ module.exports = {
allowNull: false,
type: Sequelize.DATE
}
});
})
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('event_notification');
return queryInterface.dropTable('event_notification')
}
};
}

View file

@ -11,7 +11,7 @@ module.exports = {
eventId: {
type: Sequelize.INTEGER,
references: {
model: 'event',
model: 'events',
key: 'id'
}
},

View file

@ -1,4 +1,4 @@
'use strict';
'use strict'
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('settings', {
@ -6,7 +6,7 @@ module.exports = {
type: Sequelize.STRING,
primaryKey: true,
allowNull: false,
index: true,
index: true
},
value: {
type: Sequelize.JSON
@ -19,9 +19,9 @@ module.exports = {
allowNull: false,
type: Sequelize.DATE
}
});
})
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('settings');
return queryInterface.dropTable('settings')
}
};
}

View file

@ -1,4 +1,4 @@
'use strict';
'use strict'
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('event_tags', {
@ -24,9 +24,9 @@ module.exports = {
allowNull: false,
type: Sequelize.DATE
}
});
})
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('event_tags');
return queryInterface.dropTable('event_tags')
}
};
}

View file

@ -7,13 +7,13 @@ const { Event, Notification, EventNotification,
User, Place, Tag } = require('./api/models')
let settings
async function sendNotification (notification, event, eventNotification) {
async function sendNotification(notification, event, eventNotification) {
const promises = []
switch (notification.type) {
// case 'mail':
// return mail.send(notification.email, 'event', { event, config, notification })
// return mail.send(notification.email, 'event', { event, config, notification })
// case 'admin_email':
// const admins = await User.findAll({ where: { is_admin: true } })
// const admins = await User.findAll({ where: { is_admin: true } })
// const admin_emails = admins.map(admin => admin.email)
// return mail.send(admin_emails, 'event', { event, to_confirm: true, notification })
case 'mastodon':
@ -56,11 +56,11 @@ async function notify() {
let interval
function startLoop(seconds) {
console.error('starting notifier loop')
interval = setInterval(notify, seconds*1000)
interval = setInterval(notify, seconds * 1000)
}
function stopLoop() {
stopInterval(interval)
}
module.exports = { startLoop, stopLoop }
module.exports = { startLoop, stopLoop }

View file

@ -14,7 +14,7 @@ export const state = () => ({
show_past_events: false,
show_recurrent_events: false,
show_pinned_event: false
},
}
})
export const getters = {
@ -25,7 +25,7 @@ export const getters = {
let events = state.events
// TOFIX: use lodash
if (state.filters.tags.length || state.filters.places.length){
if (state.filters.tags.length || state.filters.places.length) {
events = events.filter((e) => {
if (state.filters.tags.length) {
const m = intersection(e.tags.map(t => t.tag), state.filters.tags)
@ -41,13 +41,13 @@ export const getters = {
}
if (!state.show_past_events) {
events = events.filter( e => !e.past )
events = events.filter(e => !e.past)
}
let lastDay = null
events = map(events, e => {
const currentDay = moment(e.start_datetime).date()
e.newDay = (!lastDay || lastDay!==currentDay) && currentDay
e.newDay = (!lastDay || lastDay !== currentDay) && currentDay
lastDay = currentDay
return e
})
@ -90,20 +90,20 @@ export const mutations = {
setSearchPlaces(state, places) {
state.filters.places = places
},
showPastEvents (state, show) {
showPastEvents(state, show) {
state.show_past_events = show
},
setSettings (state, settings) {
setSettings(state, settings) {
state.settings = settings
},
setConfig (state, config) {
setConfig(state, config) {
state.config = config
}
}
export const actions = {
async updateEvents({ commit }, page) {
const events = await this.$axios.$get(`/event/${page.month-1}/${page.year}`)
const events = await this.$axios.$get(`/event/${page.month - 1}/${page.year}`)
commit('setEvents', events)
},
async updateMeta({ commit }) {