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

@@ -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
};