This commit is contained in:
lesion
2019-06-06 23:54:32 +02:00
parent 745b9247c9
commit 3ca818f016
66 changed files with 989 additions and 532 deletions

View File

@@ -1,22 +1,25 @@
const { Op } = require('sequelize')
const config = require('../../config')
const User = require('./models/user')
const { user: User } = require('./models')
const Settings = require('./controller/settings')
const Auth = {
async fillUser(req, res, next) {
if (!req.user) return next()
req.user = await User.findOne({
where: { id: { [Op.eq]: req.user.id }, is_active: true }
}).catch(e => {
res.sendStatus(404)
return next(false)
})
next()
},
async isAuth(req, res, next) {
console.error('ma sono dentro auth ?!?!', req.user)
if (!req.user) {
return res
.status(403)
.send({ message: 'Failed to authenticate token ' })
}
req.user = await User.findOne({
where: { id: { [Op.eq]: req.user.id }, is_active: true }
})
@@ -28,9 +31,22 @@ const Auth = {
next()
},
isAdmin(req, res, next) {
if (!req.user) {
return res
.status(403)
.send({ message: 'Failed to authenticate token ' })
}
if (req.user.is_admin && req.user.is_active) return next()
return res.status(403).send({ message: 'Admin needed' })
},
async adminOrFirstRun(req, res, next) {
if (req.user && req.user.is_admin && req.user.is_active) return next()
const settings = await Settings.settings()
if (!settings.firstRun) {
return next()
}
}
}
module.exports = Auth

View File

@@ -1,14 +0,0 @@
{
"development": {
"storage": "/home/les/dev/hacklab/gancio/db.sqlite",
"dialect": "sqlite",
"logging": false
},
"production": {
"username": "docker",
"password": "docker",
"database": "gancio",
"host": "db",
"dialect": "postgres"
}
}

View File

@@ -1,12 +1,10 @@
const { User, Event, Comment, Tag } = require('../model')
const { SHARED_CONF } = require('../../../config')
const Mastodon = require('mastodon-api')
// const Sequelize = require('sequelize')
// const Op = Sequelize.Op
const settingsController = require('./settings')
const fs = require('fs')
const path = require('path')
const moment = require('moment')
const { event: Event, comment: Comment, tag: Tag } = require('../model')
const config = require('../../config').SHARED_CONF
const Mastodon = require('mastodon-api')
const settingsController = require('./settings')
moment.locale('it')
const botController = {
@@ -47,7 +45,7 @@ const botController = {
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')} -
${event.description.length > 200 ? event.description.substr(0, 200) + '...' : event.description} - ${event.tags.map(t => '#' + t.tag).join(' ')} ${SHARED_CONF.baseurl}/event/${event.id}`
${event.description.length > 200 ? event.description.substr(0, 200) + '...' : event.description} - ${event.tags.map(t => '#' + t.tag).join(' ')} ${config.baseurl}/event/${event.id}`
let media
if (event.image_path) {
@@ -58,9 +56,9 @@ ${event.description.length > 200 ? event.description.substr(0, 200) + '...' : ev
}
return bot.post('statuses', { status, visibility: 'direct', media_ids: media ? [media.data.id] : [] })
},
// TOFIX: enable message deletion
async message (msg) {
console.log(msg)
console.log(msg.data.accounts)
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 } })
@@ -71,9 +69,9 @@ ${event.description.length > 200 ? event.description.substr(0, 200) + '...' : ev
}
const comment = await Comment.create({
activitypub_id: msg.data.last_status.id,
text: msg.data.last_status.content,
// text: msg.data.last_status.content,
data: msg.data,
author: msg.data.accounts[0].username
// author: msg.data.accounts[0].username
})
event.addComment(comment)
// const comment = await Comment.findOne( { where: {activitypub_id: msg.data.in_reply_to}} )
@@ -93,5 +91,5 @@ ${event.description.length > 200 ? event.description.substr(0, 200) + '...' : ev
}
}
setTimeout(botController.initialize, 2000)
// setTimeout(botController.initialize, 2000)
module.exports = botController

View File

@@ -2,7 +2,7 @@ const crypto = require('crypto')
const moment = require('moment')
const { Op } = require('sequelize')
const lodash = require('lodash')
const { User, Event, Comment, Tag, Place, Notification } = require('../model')
const { event: Event, comment: Comment, tag: Tag, place: Place, notification: Notification } = require('../models')
const Sequelize = require('sequelize')
const eventController = {

View File

@@ -1,6 +1,6 @@
const { Event, Comment, Tag, Place } = require('../model')
const { event: Event, place: Place } = require('../models')
const { Op } = require('sequelize')
const config = require('../../../config')
const config = require('../../config').SHARED_CONF
const moment = require('moment')
const ics = require('ics')
@@ -65,7 +65,6 @@ const exportController = {
})
res.type('text/calendar; charset=UTF-8')
const { error, value } = ics.createEvents(eventsMap)
console.log(error, value)
res.send(value)
}
}

View File

@@ -1,10 +1,11 @@
const { Settings } = require('../model')
const { SHARED_CONF } = require('../../../config')
const Mastodon = require('mastodon-api')
const { setting: Setting } = require('../models')
const config = require('../../config').SHARED_CONF
const settingsController = {
async setAdminSetting (key, value) {
await Settings.findOrCreate({ where: { key },
await Setting.findOrCreate({ where: { key },
defaults: { value } })
.spread((settings, created) => {
if (!created) return settings.update({ value })
@@ -16,11 +17,15 @@ const settingsController = {
res.json(settings)
},
async getConfig (req, res) {
res.json(config)
},
async getAuthURL(req, res) {
const instance = req.body.instance
const callback = `${SHARED_CONF.baseurl}/api/settings/oauth`
const callback = `${config.baseurl}/api/settings/oauth`
const { client_id, client_secret } = await Mastodon.createOAuthApp(`https://${instance}/api/v1/apps`,
SHARED_CONF.title, 'read write', callback)
config.title, 'read write', callback)
const url = await Mastodon.getAuthorizationUrl(client_id, client_secret,
`https://${instance}`, 'read write', callback)
@@ -31,19 +36,16 @@ const settingsController = {
async code(req, res) {
const code = req.query.code
let client_id, client_secret, instance
const callback = `${SHARED_CONF.baseurl}/api/settings/oauth`
console.error('sono dentro CODEEEEEEEEEE', code)
const callback = `${config.baseurl}/api/settings/oauth`
const settings = await settingsController.settings()
console.log(settings);
({ client_id, client_secret, instance } = settings.mastodon_auth)
try {
const token = await Mastodon.getAccessToken(client_id, client_secret, code,
`https://${instance}`, callback)
const mastodon_auth = { client_id, client_secret, access_token: token, instance }
console.error(mastodon_auth)
await settingsController.setAdminSetting('mastodon_auth', mastodon_auth)
res.redirect('/admin')
@@ -53,13 +55,11 @@ const settingsController = {
},
async settings () {
const settings = await Settings.findAll()
const map = {}
settings.forEach(setting => {
map[setting.key] = setting.value
})
return map
}
console.error('ma sono dentro settings ?!?!')
const settings = await Setting.findAll()
return settings
},
}
module.exports = settingsController

View File

@@ -4,14 +4,14 @@ const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const { Op } = require('sequelize')
const jsonwebtoken = require('jsonwebtoken')
const User = require('../models/user')
const { SECRET_CONF, SHARED_CONF } = require('../../../config')
const { SECRET_CONF, SHARED_CONF } = require('../../config')
const mail = require('../mail')
const { Event, Tag, Place } = require('../models/event')
const { user: User, event: Event, tag: Tag, place: Place } = require('../models')
const eventController = require('./event')
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) {
@@ -33,7 +33,7 @@ const userController = {
},
SECRET_CONF.secret
)
res.json({token: accessToken})
}
}
@@ -89,7 +89,9 @@ 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
@@ -195,7 +197,10 @@ const userController = {
},
async current(req, res) {
res.json(req.user)
if (req.user)
res.json(req.user)
else
res.sendStatus(404)
},
async getAll(req, res) {
@@ -219,7 +224,6 @@ const userController = {
},
async register(req, res) {
const n_users = await User.count()
try {
@@ -234,14 +238,17 @@ const userController = {
try {
mail.send([user.email, SECRET_CONF.admin], 'register', { user, config: SHARED_CONF })
} catch (e) {
console.error(e)
return res.status(400).json(e)
}
const payload = { email: user.email }
const payload = {
id: user.id,
email: user.email,
scope: [user.is_admin ? 'admin' : 'user']
}
const token = jwt.sign(payload, SECRET_CONF.secret)
res.json({ user, token })
res.json({ token })
// res.redirect('/')
} catch (e) {
console.error(e)
res.status(404).json(e)
}
}

View File

@@ -1,6 +0,0 @@
const Sequelize = require('sequelize')
const { SECRET_CONF } = require('../../config.js')
const db = new Sequelize(SECRET_CONF.db)
// db.sync()
module.exports = db

View File

@@ -1,27 +1,16 @@
const express = require('express')
const multer = require('multer')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const expressJwt = require('express-jwt')
const { fillUser, isAuth, isAdmin } = require('./auth')
const eventController = require('./controller/event')
const exportController = require('./controller/export')
const userController = require('./controller/user')
const settingsController = require('./controller/settings')
const { SECRET_CONF } = require('../../config')
const cookieParser = require('cookie-parser')
const expressJwt = require('express-jwt')
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];
} else if (req.cookies && req.cookies['auth._token.local']) {
const tmp = req.cookies['auth._token.local'].split(' ');
return tmp[1]
}
return null
}
})
const { SECRET_CONF } = require('../config')
const storage = require('./storage')({
destination: 'uploads/'
@@ -30,6 +19,24 @@ const storage = require('./storage')({
const upload = multer({ storage })
const api = express.Router()
api.use(cookieParser())
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
// }
})
// AUTH
api.post('/auth/login', userController.login)
api.post('/auth/logout', userController.logout)
@@ -77,8 +84,9 @@ api.get('/event/unconfirmed', jwt, isAuth, isAdmin, eventController.getUnconfirm
api.post('/event/notification', eventController.addNotification)
api.delete('/event/notification/:code', eventController.delNotification)
api.get('/settings', settingsController.getAdminSettings)
api.post('/settings', settingsController.setAdminSetting)
api.get('/config', settingsController.getConfig)
api.get('/settings', jwt, fillUser, isAdmin, settingsController.getAdminSettings)
api.post('/settings', jwt, fillUser, isAdmin, settingsController.setAdminSetting)
// get event
api.get('/event/:event_id', eventController.get)

View File

@@ -1,8 +1,8 @@
const Email = require('email-templates')
const path = require('path')
const { SECRET_CONF, SHARED_CONF } = require('../../config')
const moment = require('moment')
moment.locale(SHARED_CONF.locale)
const config = require('../config')
moment.locale(config.SHARED_CONF.locale)
const mail = {
send (addresses, template, locals) {
@@ -16,25 +16,25 @@ const mail = {
}
},
message: {
from: `${SHARED_CONF.title} <${SECRET_CONF.smtp.auth.user}>`
from: `${config.SHARED_CONF.title} <${config.SECRET_CONF.smtp.auth.user}>`
},
send: true,
i18n: {
directory: path.join(__dirname, '..', '..', 'locales', 'email'),
defaultLocale: SHARED_CONF.locale
defaultLocale: config.SHARED_CONF.locale
},
transport: SECRET_CONF.smtp
transport: config.SECRET_CONF.smtp
})
return email.send({
template,
message: {
to: addresses,
bcc: SECRET_CONF.admin
bcc: config.SECRET_CONF.admin
},
locals: {
...locals,
locale: SHARED_CONF.locale,
config: SHARED_CONF,
locale: config.SHARED_CONF.locale,
config: config.SHARED_CONF,
datetime: datetime => moment(datetime).format('ddd, D MMMM HH:mm')
}
})

View File

@@ -1,14 +0,0 @@
const User = require('./models/user')
const { Event, Comment, Tag, Place, Notification, EventNotification } = require('./models/event')
const Settings = require('./models/settings')
module.exports = {
User,
Event,
Comment,
Tag,
Place,
Notification,
EventNotification,
Settings
}

View File

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

View File

@@ -1,81 +1,31 @@
const Sequelize = require('sequelize')
const db = require('../db')
const User = require('./user')
const Event = db.define('event', {
title: Sequelize.STRING,
description: Sequelize.TEXT,
multidate: Sequelize.BOOLEAN,
start_datetime: { type: Sequelize.DATE, index: true },
end_datetime: { type: Sequelize.DATE, index: true },
image_path: Sequelize.STRING,
is_visible: Sequelize.BOOLEAN,
activitypub_id: { type: Sequelize.BIGINT, index: true },
activitypub_ids: {
type: Sequelize.ARRAY(Sequelize.BIGINT),
index: true,
defaultValue: []
}
})
const Tag = db.define('tag', {
tag: { type: Sequelize.STRING, index: true, unique: true, primaryKey: true },
weigth: { type: Sequelize.INTEGER, defaultValue: 0 },
color: { type: Sequelize.STRING }
})
const Comment = db.define('comment', {
activitypub_id: { type: Sequelize.BIGINT, index: true },
data: Sequelize.JSON,
// url: Sequelize.STRING,
author: Sequelize.STRING,
text: Sequelize.STRING
})
const Notification = db.define('notification', {
filters: Sequelize.JSON,
email: Sequelize.STRING,
remove_code: Sequelize.STRING,
type: {
type: Sequelize.ENUM,
values: ['mail', 'admin_email', 'mastodon']
}
})
const Place = db.define('place', {
name: { type: Sequelize.STRING, unique: true, index: true },
weigth: { type: Sequelize.INTEGER, defaultValue: 0 },
address: { type: Sequelize.STRING }
})
Comment.belongsTo(Event)
Event.hasMany(Comment)
Event.belongsToMany(Tag, { through: 'tagEvent' })
Tag.belongsToMany(Event, { through: 'tagEvent' })
const EventNotification = db.define('EventNotification', {
status: {
type: Sequelize.ENUM,
values: ['new', 'sent', 'error'],
defaultValue: 'new',
index: true
}
})
Event.belongsToMany(Notification, { through: EventNotification })
Notification.belongsToMany(Event, { through: EventNotification })
Event.belongsTo(User)
Event.belongsTo(Place)
User.hasMany(Event)
Place.hasMany(Event)
async function init() {
await Notification.findOrCreate({ where: { type: 'mastodon', filters: { is_visible: true } } })
// await Notification.findOrCreate({ where: { type: 'admin_email', filters: { is_visible: false } } })
}
init()
module.exports = { Event, Comment, Tag, Place, Notification, EventNotification }
'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: {
type: DataTypes.DATE,
index: true
},
end_datetime: DataTypes.DATE,
image_path: DataTypes.STRING,
is_visible: DataTypes.BOOLEAN,
activitypub_id: {
type: DataTypes.BIGINT,
index: true
}
}, {});
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' })
// Event.hasMany(models.Tag)
// associations can be defined here
};
return event;
};

View File

@@ -0,0 +1,16 @@
'use strict';
module.exports = (sequelize, DataTypes) => {
const eventNotification = sequelize.define('eventNotification', {
status: {
type: DataTypes.ENUM,
values: ['new', 'sent', 'error'],
defaultValue: 'new',
index: true
}
}, {});
eventNotification.associate = function(models) {
// associations can be defined here
};
return eventNotification;
};

View File

@@ -1,29 +1,31 @@
const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const basename = path.basename(__filename)
const config = require('../../../config')
const db = {}
'use strict';
const sequelize = new Sequelize(config.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);
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))
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;

View File

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

View File

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

View File

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

View File

@@ -1,9 +0,0 @@
const db = require('../db')
const Sequelize = require('sequelize')
const Settings = db.define('settings', {
key: { type: Sequelize.STRING, primaryKey: true, index: true },
value: Sequelize.JSON
})
module.exports = Settings

19
server/api/models/tag.js Normal file
View File

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

View File

@@ -1,34 +1,39 @@
const Sequelize = require('sequelize')
'use strict';
const bcrypt = require('bcrypt')
const db = require('../db')
const User = db.define('user', {
email: {
type: Sequelize.STRING,
unique: { msg: 'err.register_error' },
index: true,
allowNull: false
},
description: Sequelize.TEXT,
password: Sequelize.STRING,
recover_code: Sequelize.STRING,
is_admin: Sequelize.BOOLEAN,
is_active: Sequelize.BOOLEAN,
mastodon_auth: Sequelize.JSON
})
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define('user', {
email: {
type: DataTypes.STRING,
unique: { msg: 'err.register_error' },
index: true,
allowNull: false
},
description: DataTypes.TEXT,
password: DataTypes.STRING,
recover_code: DataTypes.STRING,
is_admin: DataTypes.BOOLEAN,
is_active: DataTypes.BOOLEAN
}, {});
User.prototype.comparePassword = async function (pwd) {
if (!this.password) return false
const ret = await bcrypt.compare(pwd, this.password)
return ret
}
user.associate = function(models) {
// associations can be defined here
user.hasMany(models.event)
};
User.beforeSave(async (user, options) => {
if (user.changed('password')) {
const salt = await bcrypt.genSalt(10)
const hash = await bcrypt.hash(user.password, salt)
user.password = hash
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)
const hash = await bcrypt.hash(user.password, salt)
user.password = hash
}
})
module.exports = User
return user;
};

View File

@@ -0,0 +1,23 @@
doctype xml
rss(version='2.0')
channel
title #{config.title}
link #{config.baseurl}
description #{config.description}
language #{config.locale}
//- if events.length
lastBuildDate= new Date(posts[0].publishedAt).toUTCString()
each event in events
item
title= event.title
link #{config.baseurl}/event/#{event.id}
description
| <![CDATA[
| <h4>#{event.title}</h4>
| <strong>#{event.place.name} - #{event.place.address}</strong>
| #{moment(event.start_datetime).format("dddd, D MMMM HH:mm")}<br/>
| <img src="#{config.apiurl}/../uploads/#{event.image_path}"/>
| <pre>!{event.description}</pre>
| ]]>
pubDate= new Date(event.createdAt).toUTCString()
guid(isPermaLink='false') #{config.baseurl}/event/#{event.id}

59
server/config.example.js Normal file
View File

@@ -0,0 +1,59 @@
/**
* GANCIO CONFIGURATION
*/
const env = process.env.NODE_ENV || 'development'
/**
* Database configuration
* `development` configuration is enabled running `yarn dev`
* while `production` with `yarn start`
* ref: http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor
*/
const DB_CONF = {
development: {
storage: __dirname + '/db.sqlite',
dialect: 'sqlite',
},
production: {
username: '',
password: '',
database: 'gancio',
host: 'localhost',
dialect: 'postgres',
logging: false
},
}
const SECRET_CONF = {
// where events/users confirmation email are sent
admin: 'gancio@example.com',
db: DB_CONF[env],
// jwt salt secret (generate it randomly)
secret: '',
// smtp account to send email
smtp: {
host: process.env.SMTP_HOST || 'mail.example.com',
secure: true,
auth: {
user: process.env.SMTP_USER || 'gancio@example.com',
pass: process.env.SMTP_PASS || ''
}
},
}
/**
* Main Gancio configuration
*/
const SHARED_CONF = {
locale: 'it',
title: 'GANCIO',
description: 'A calendar for radical communities',
baseurl: env === 'development' ? 'http://localhost:3000': 'https://gancio.example.com',
env
}
module.exports = { SHARED_CONF, SECRET_CONF }

41
server/firstrun.js Normal file
View File

@@ -0,0 +1,41 @@
// check config.js existance
const fs = require('fs')
const path = require('path')
const config_path = path.join(__dirname, 'config.js')
if (!fs.existsSync(config_path)) {
console.error(`Configuration file not found at '${config_path}. Please copy 'config.example.js' and modify it.`)
process.exit(1)
}
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);
}
const Sequelize = require('sequelize')
let db
try {
db = new Sequelize(SECRET_CONF.db)
} 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)
})

View File

@@ -1,23 +1,12 @@
const firstRun = require('./firstrun')
const express = require('express')
const consola = require('consola')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const path = require('path')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const cors = require('cors')
const notifier = require('./notifier')
const corsConfig = {
allowedHeaders: ['Authorization'],
exposeHeaders: ['Authorization']
}
const { Nuxt, Builder } = require('nuxt')
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
@@ -34,12 +23,8 @@ async function start() {
}
// Give nuxt middleware to express
app.use(cors(corsConfig))
app.use(morgan('dev'))
app.use('/media/', express.static(path.join(__dirname, '..', 'uploads')))
app.use(cookieParser())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(nuxt.render)
// Listen the server
@@ -49,5 +34,5 @@ async function start() {
badge: true
})
}
start()
notifier.startLoop(20)
firstRun.then(start)

View File

@@ -0,0 +1,38 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('comments', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
eventId: {
type: Sequelize.INTEGER,
references: {
model: 'event',
key: 'id'
}
},
activitypub_id: {
type: Sequelize.BIGINT,
index: true,
},
data: {
type: Sequelize.JSON
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('comments');
}
};

View File

@@ -0,0 +1,45 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
email: {
type: Sequelize.STRING,
unique: { msg: 'err.register_error' },
index: true,
allowNull: false
},
description: {
type: Sequelize.TEXT
},
password: {
type: Sequelize.STRING
},
recover_code: {
type: Sequelize.STRING
},
is_admin: {
type: Sequelize.BOOLEAN
},
is_active: {
type: Sequelize.BOOLEAN
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('users');
}
};

View File

@@ -0,0 +1,66 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('events', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
title: {
type: Sequelize.STRING
},
slug: {
type: Sequelize.STRING,
index: true,
},
description: {
type: Sequelize.TEXT
},
multidate: {
type: Sequelize.BOOLEAN
},
start_datetime: {
type: Sequelize.DATE
},
end_datetime: {
type: Sequelize.DATE
},
image_path: {
type: Sequelize.STRING
},
is_visible: {
type: Sequelize.BOOLEAN
},
activitypub_id: {
type: Sequelize.BIGINT
},
userId: {
type: Sequelize.INTEGER,
references: {
model: 'users',
key: 'id'
}
},
placeId: {
type: Sequelize.INTEGER,
references: {
model: 'places',
key: 'id'
}
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('events');
}
};

View File

@@ -0,0 +1,33 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('places', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
address: {
type: Sequelize.STRING
},
weigth: {
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('places');
}
};

View File

@@ -0,0 +1,37 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('notifications', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
filters: {
type: Sequelize.JSON
},
email: {
type: Sequelize.STRING
},
remove_code: {
type: Sequelize.STRING
},
type: {
type: Sequelize.ENUM,
values: ['mail', 'admin_email', 'mastodon']
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('notifications');
}
};

View File

@@ -0,0 +1,29 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('tags', {
tag: {
type: Sequelize.STRING,
allowNull: false,
primaryKey: true
},
weigth: {
type: Sequelize.INTEGER
},
color: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('tags');
}
};

View File

@@ -0,0 +1,38 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('event_notification', {
eventId: {
type: Sequelize.INTEGER,
references: {
model: 'events',
key: 'id'
}
},
notificationId: {
type: Sequelize.INTEGER,
references: {
model: 'notifications',
key: 'id'
}
},
status: {
type: Sequelize.ENUM,
values: ['new', 'sent', 'error'],
defaultValue: 'new',
index: true
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('event_notification');
}
};

View File

@@ -0,0 +1,27 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('settings', {
key: {
type: Sequelize.STRING,
primaryKey: true,
allowNull: false,
index: true,
},
value: {
type: Sequelize.JSON
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('settings');
}
};

View File

@@ -0,0 +1,32 @@
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('event_tags', {
eventId: {
type: Sequelize.INTEGER,
references: {
model: 'events',
key: 'id'
}
},
tagTag: {
type: Sequelize.STRING,
references: {
model: 'tags',
key: 'tag'
}
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('event_tags');
}
};

View File

@@ -1,10 +1,10 @@
// const mail = require('./mail')
const bot = require('./api/controller/bot')
const settingsController = require('./api/controller/settings')
// const config = require('./api/config.js')
const config = require('./config.js')
const { Event, Notification, EventNotification,
User, Place, Tag } = require('./api/model')
User, Place, Tag } = require('./api/models')
let settings
async function sendNotification (notification, event, eventNotification) {