diff --git a/components/admin/Places.vue b/components/admin/Places.vue index 2516a7dd..0bf91ffa 100644 --- a/components/admin/Places.vue +++ b/components/admin/Places.vue @@ -7,12 +7,13 @@ el-form-item(:label="$t('common.address')") el-input.mr-1(:placeholder='$t("common.address")' v-model='place.address') el-button(variant='primary' @click='savePlace') {{$t('common.save')}} + el-table(:data='paginatedPlaces' small) - el-table-column(:label="$t('common.name')") + el-table-column(:label="$t('common.name')" width='200') template(slot-scope='data') {{data.row.name}} - el-table-column(:label="$t('common.address')") + el-table-column(:label="$t('common.address')" width='400') template(slot-scope='data') {{data.row.address}} - el-table-column(:label="$t('common.actions')") + el-table-column(:label="$t('common.actions')" width='200') template(slot-scope='data') el-button(size='mini' type='success' diff --git a/components/admin/Users.vue b/components/admin/Users.vue index dc89ddc4..1cb9b0a2 100644 --- a/components/admin/Users.vue +++ b/components/admin/Users.vue @@ -16,14 +16,14 @@ div //- USERS LIST el-table(:data='paginatedUsers' small) - el-table-column(label='Username') + el-table-column(label='Username' width='150') template(slot-scope='data') span(slot='reference') {{data.row.username}} - el-table-column(label='Email') + el-table-column(label='Email' width='300') template(slot-scope='data') el-popover(trigger='hover' :content='data.row.description' width='400') span(slot='reference') {{data.row.email}} - el-table-column(:label="$t('common.actions')") + el-table-column(:label="$t('common.actions')" width='300') template(slot-scope='data') div(v-if='data.row.id!==$auth.user.id') el-button-group diff --git a/locales/it.js b/locales/it.js index f8265284..ab7d09fb 100644 --- a/locales/it.js +++ b/locales/it.js @@ -160,6 +160,7 @@ export default { }, settings: { + update_confirm: 'Sicura di voler salvare le modifiche?', change_password: 'Cambia password', password_updated: 'Password modificata', danger_section: 'Sezione pericolosa', diff --git a/pages/settings.vue b/pages/settings.vue index 8826745d..f5a0a0e5 100644 --- a/pages/settings.vue +++ b/pages/settings.vue @@ -3,7 +3,7 @@ nuxt-link.float-right(to='/') el-button(circle icon='el-icon-close' type='danger' size='small' plain) h5 {{$t('common.settings')}} - hr + el-divider {{$auth.user.email}} el-form(action='/api/user' method='PUT' @submit.native.prevent='update_settings' inline label-width='200px') @@ -17,7 +17,7 @@ div(v-if='user.settings.enable_federation') el-form-item(:label="$t('common.username')") - el-input(v-if='user.username.length==0' type='text' name='username' v-model='user.username') + el-input(v-if='username_editable' type='text' name='username' v-model='user.username') template(slot='suffix') @{{baseurl}} span(v-else) {{user.username}}@{{baseurl}} //- el-button(slot='append') {{$t('common.save')}} @@ -40,6 +40,7 @@ export default { name: 'Settings', data () { return { + username_editable: false, password: '', user: { } } @@ -51,7 +52,7 @@ export default { }, async asyncData ({ $axios, params }) { const user = await $axios.$get('/auth/user') - return { user } + return { user, username_editable: user.username.length===0 } }, computed: { ...mapState(['settings']), @@ -72,12 +73,16 @@ export default { } }, async update_settings () { - try { - const user = await this.$axios.$put('/user', { ...this.user, password: this.password }) - this.user = user - } catch (e) { + MessageBox.confirm(this.$t('settings.update_confirm'), + this.$t('common.confirm'), { + confirmButtonText: this.$t('common.ok'), + cancelButtonText: this.$t('common.cancel'), + type: 'error' + }).then(async () => { + this.user = await this.$axios.$put('/user', { ...this.user, password: this.password }) + }).catch( e => { Message({ message: e, showClose: true, type: 'warning' }) - } + }) }, async remove_account () { MessageBox.confirm(this.$t('settings.remove_account_confirm'), this.$t('common.confirm'), { diff --git a/server/api/controller/settings.js b/server/api/controller/settings.js index ba964986..128ec66f 100644 --- a/server/api/controller/settings.js +++ b/server/api/controller/settings.js @@ -81,5 +81,5 @@ const settingsController = { }, } -setTimeout(settingsController.initialize, 200) +settingsController.initialize() module.exports = settingsController diff --git a/server/api/controller/user.js b/server/api/controller/user.js index 0402b04f..292f4623 100644 --- a/server/api/controller/user.js +++ b/server/api/controller/user.js @@ -6,7 +6,7 @@ const { Op } = require('sequelize') const jsonwebtoken = require('jsonwebtoken') const config = require('config') const mail = require('../mail') -const { user: User, event: Event, tag: Tag, place: Place } = require('../models') +const { user: User, event: Event, tag: Tag, place: Place, fed_users: FedUsers } = require('../models') const settingsController = require('./settings') const federation = require('../../federation/helpers') @@ -118,7 +118,8 @@ const userController = { // send response to client res.json(event) - if (req.user) { federation.sendEvent(event, req.user) } + const user = await User.findByPk(req.user.id, { include: { model: FedUsers, as: 'followers' }}) + if (user) { federation.sendEvent(event, user) } // res.sendStatus(200) @@ -207,8 +208,10 @@ const userController = { } }, - current (req, res) { - if (req.user) { res.json(req.user) } else { res.sendStatus(404) } + async current (req, res) { + if (!req.user) return res.status(400).send('Not logged') + const user = await User.findByPk(req.user.id, { include: { model: FedUsers, as: 'followers' } }) + res.json(user) }, async getAll (req, res) { diff --git a/server/api/models/fed_users.js b/server/api/models/fed_users.js new file mode 100644 index 00000000..7b478052 --- /dev/null +++ b/server/api/models/fed_users.js @@ -0,0 +1,13 @@ +module.exports = (sequelize, DataTypes) => { + const fed_users = sequelize.define('fed_users', { + ap_id: { + type: DataTypes.STRING, + primaryKey: true + }, + object: DataTypes.JSON + }, {}) + fed_users.associate = function(models) { + // associations can be defined here + }; + return fed_users +} \ No newline at end of file diff --git a/server/api/models/user.js b/server/api/models/user.js index 809d9430..af468fd4 100644 --- a/server/api/models/user.js +++ b/server/api/models/user.js @@ -28,10 +28,6 @@ module.exports = (sequelize, DataTypes) => { is_admin: DataTypes.BOOLEAN, is_active: DataTypes.BOOLEAN, rsa: DataTypes.JSON, - followers: { - type: DataTypes.JSON, - defaultValue: [] - } }, { scopes: { withoutPassword: { @@ -43,6 +39,7 @@ module.exports = (sequelize, DataTypes) => { user.associate = function (models) { // associations can be defined here user.hasMany(models.event) + user.belongsToMany(models.fed_users, { through: 'user_followers', as: 'followers' }) } user.prototype.comparePassword = async function (pwd) { diff --git a/server/federation/follows.js b/server/federation/follows.js index 4fe8facf..3ee7d7f4 100644 --- a/server/federation/follows.js +++ b/server/federation/follows.js @@ -1,6 +1,6 @@ const config = require('config') const Helpers = require('./helpers') -const { user: User } = require('../api/models') +const { user: User, fed_users: FedUsers } = require('../api/models') const crypto = require('crypto') const debug = require('debug')('federation:follows') @@ -10,13 +10,14 @@ module.exports = { const body = req.body if (typeof body.object !== 'string') { return } const username = body.object.replace(`${config.baseurl}/federation/u/`, '') - const user = await User.findOne({ where: { username } }) + const user = await User.findOne({ where: { username }, include: { model: FedUsers, as: 'followers' }}) if (!user) { return res.status(404).send('User not found') } // check for duplicate - if (!user.followers.includes(body.actor)) { - await user.update({ followers: [...user.followers, body.actor] }) - debug('%s followed by %s (%d)', username, body.actor, user.followers.length) + if (!user.fed_users.includes(body.actor)) { + await user.addFed_users([req.fedi_user.id]) + // await user.update({ followers: [...user.followers, body.actor] }) + debug('%s followed by %s (%d)', username, body.actor, user.fed_users.length+1) } else { debug('duplicate %s followed by %s', username, body.actor) } @@ -39,13 +40,13 @@ module.exports = { const user = await User.findOne({ where: { username } }) if (!user) { return res.status(404).send('User not found') } - if (body.actor !== body.object.actor) { + if (body.actor !== body.object.actor || body.actor !== req.fedi_user.id) { debug('Unfollow an user created by a different actor !?!?') return res.status(400).send('Bad things') } - const followers = user.followers.filter(follower => follower !== body.actor) - await user.update({ followers }) - debug('%s unfollowed by %s (%d)', username, body.actor, user.followers.length) + + if (req.fedi_user) await user.removeFed_users(req.fedi_user.id) + debug('%s unfollowed by %s', username, body.actor) res.sendStatus(200) } } diff --git a/server/federation/helpers.js b/server/federation/helpers.js index c780c6d0..bb0270db 100644 --- a/server/federation/helpers.js +++ b/server/federation/helpers.js @@ -4,31 +4,29 @@ const crypto = require('crypto') const config = require('config') const httpSignature = require('http-signature') const debug = require('debug')('federation:helpers') -const { user: User } = require('../api/models') +const { user: User, fed_users: FedUsers } = require('../api/models') const url = require('url') - -const actorCache = [] +const settings = require('../api/controller/settings') const Helpers = { async signAndSend (message, user, to) { // get the URI of the actor object and append 'inbox' to it - const toInbox = to + '/inbox' - const toOrigin = url.parse(to) - const toPath = toOrigin.path + '/inbox' + const toUrl = url.parse(to) + // const toPath = toOrigin.path + '/inbox' // get the private key const privkey = user.rsa.privateKey const signer = crypto.createSign('sha256') const d = new Date() - const stringToSign = `(request-target): post ${toPath}\nhost: ${toOrigin.hostname}\ndate: ${d.toUTCString()}` + const stringToSign = `(request-target): post ${toUrl.path}\nhost: ${toUrl.hostname}\ndate: ${d.toUTCString()}` signer.update(stringToSign) signer.end() const signature = signer.sign(privkey) const signature_b64 = signature.toString('base64') const header = `keyId="${config.baseurl}/federation/u/${user.username}",headers="(request-target) host date",signature="${signature_b64}"` - const ret = await fetch(toInbox, { + const ret = await fetch(to, { headers: { - 'Host': toOrigin.hostname, + 'Host': toUrl.hostname, 'Date': d.toUTCString(), 'Signature': header, 'Content-Type': 'application/activity+json; charset=utf-8', @@ -40,67 +38,97 @@ const Helpers = { }, async sendEvent (event, user) { - // TODO: has to use sharedInbox! + if (!settings.settings.enable_federation) { + console.error(settings.settings) + console.error(settings.secretSettings) + debug('federation disabled') + return + } + + console.error('dentro sendEvent ', user) + // event is sent by user that published it and by the admin instance - const instanceAdmin = await User.findOne({ where: { email: config.admin } }) + // collect followers from admin and user + const instanceAdmin = await User.findOne({ where: { email: config.admin }, include: { model: FedUsers, as: 'followers' } }) if (!instanceAdmin || !instanceAdmin.username) { debug('Instance admin not found (there is no user with email => %s)', config.admin) return } - for (const follower of instanceAdmin.followers) { - debug('Notify %s with event %s (from admin user %s)', follower, event.title, instanceAdmin.username) + console.error(instanceAdmin.followers) + let recipients = {} + instanceAdmin.followers.forEach(follower => { + const sharedInbox = follower.user_followers.endpoints.sharedInbox + if (!recipients[sharedInbox]) recipients[sharedInbox] = [] + recipients[sharedInbox].push(follower.id) + }) + + for(const sharedInbox in recipients) { + debug('Notify %s with event %s (from admin user %s) cc => %d', sharedInbox, event.title, instanceAdmin.username, recipients[sharedInbox].length) const body = { id: `${config.baseurl}/federation/m/${event.id}#create`, type: 'Create', to: ['https://www.w3.org/ns/activitystreams#Public'], - cc: [`${config.baseurl}/federation/u/${instanceAdmin.username}/followers`, follower], + cc: [`${config.baseurl}/federation/u/${instanceAdmin.username}/followers`, ...recipients[sharedInbox]], actor: `${config.baseurl}/federation/u/${instanceAdmin.username}`, - object: event.toAP(instanceAdmin.username, [`${config.baseurl}/federation/u/${instanceAdmin.username}/followers`, follower]) + object: event.toAP(instanceAdmin.username, [`${config.baseurl}/federation/u/${instanceAdmin.username}/followers`, ...recipients[sharedInbox]]) } body['@context'] = 'https://www.w3.org/ns/activitystreams' - Helpers.signAndSend(body, instanceAdmin, follower) + Helpers.signAndSend(body, instanceAdmin, sharedInbox) } - // in case the event is published by the Admin itself do not republish + // in case the event is published by the Admin itself do not add user if (instanceAdmin.id === user.id) { debug('Event published by instance Admin') return - } - + } if (!user.settings.enable_federation || !user.username) { debug('Federation disabled for user %d (%s)', user.id, user.username) return } - for (const follower of user.followers) { - debug('Notify %s with event %s (from user %s)', follower, event.title, user.username) + + recipients = {} + user.followers.forEach(follower => { + const sharedInbox = follower.object.endpoints.sharedInbox + if (!recipients[sharedInbox]) recipients[sharedInbox] = [] + recipients[sharedInbox].push(follower.id) + }) + + debug(recipients) + for(const sharedInbox in recipients) { + debug('Notify %s with event %s (from admin user %s) cc => %d', sharedInbox, event.title, user.username, recipients[sharedInbox].length) const body = { id: `${config.baseurl}/federation/m/${event.id}#create`, type: 'Create', to: ['https://www.w3.org/ns/activitystreams#Public'], - cc: [`${config.baseurl}/federation/u/${user.username}/followers`, follower], - published: event.createdAt, + cc: [`${config.baseurl}/federation/u/${user.username}/followers`, ...recipients[sharedInbox]], actor: `${config.baseurl}/federation/u/${user.username}`, - object: event.toAP(user.username, [`${config.baseurl}/federation/u/${user.username}/followers`, follower]) + object: event.toAP(user.username, [`${config.baseurl}/federation/u/${user.username}/followers`, ...recipients[sharedInbox]]) } body['@context'] = 'https://www.w3.org/ns/activitystreams' - Helpers.signAndSend(body, user, follower) + Helpers.signAndSend(body, user, sharedInbox) } + }, - async getFederatedUser (address) { - address = address.trim() - const [ username, host ] = address.split('@') - const url = `https://${host}/.well-known/webfinger?resource=acct:${username}@${host}` - return Helpers.getActor(url) - }, + // DO NOT USE THIS! (why is this needed btw?) + // async getFederatedUser (address) { + // address = address.trim() + // const [ username, host ] = address.split('@') + // const url = `https://${host}/.well-known/webfinger?resource=acct:${username}@${host}` + // return Helpers.getActor(url) + // }, // TODO: cache async getActor (url, force = false) { + let fedi_user + // try with cache first - if (!force && actorCache[url]) { return actorCache[url] } - const user = await fetch(url, { headers: { 'Accept': 'application/jrd+json, application/json' } }) + if (!force) fedi_user = await FedUsers.findByPk(url) + + if (fedi_user) return fedi_user.object + fedi_user = await fetch(url, { headers: { 'Accept': 'application/jrd+json, application/json' } }) .then(res => { if (!res.ok) { debug('[ERR] Actor %s => %s', url, res.statusText) @@ -108,32 +136,37 @@ const Helpers = { } return res.json() }) - actorCache[url] = user - return user + if (fedi_user) { + await FedUsers.create({ap_id: url, object: fedi_user}) + } + return fedi_user }, // ref: https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/ async verifySignature (req, res, next) { let user = await Helpers.getActor(req.body.actor) if (!user) { return res.status(401).send('Actor not found') } - + // little hack -> https://github.com/joyent/node-http-signature/pull/83 req.headers.authorization = 'Signature ' + req.headers.signature + + req.fedi_user = user // another little hack :/ // https://github.com/joyent/node-http-signature/issues/87 req.url = '/federation' + req.url const parsed = httpSignature.parseRequest(req) if (httpSignature.verifySignature(parsed, user.publicKey.publicKeyPem)) { return next() } - + // signature not valid, try without cache user = await Helpers.getActor(req.body.actor, true) if (!user) { return res.status(401).send('Actor not found') } if (httpSignature.verifySignature(parsed, user.publicKey.publicKeyPem)) { return next() } - + // still not valid debug('Invalid signature from user %s', req.body.actor) res.send('Request signature could not be verified', 401) + } } diff --git a/server/federation/users.js b/server/federation/users.js index 4e9a1df4..732385a5 100644 --- a/server/federation/users.js +++ b/server/federation/users.js @@ -1,4 +1,4 @@ -const { user: User, event: Event, place: Place, tag: Tag } = require('../api/models') +const { user: User, event: Event, place: Place, tag: Tag, fed_users: FedUsers } = require('../api/models') const config = require('config') const get = require('lodash/get') const debug = require('debug')('fediverse:user') @@ -45,7 +45,7 @@ module.exports = { const page = req.query.page debug('Retrieve %s followers', name) if (!name) return res.status(400).send('Bad request.') - const user = await User.findOne({where: { username: name }}) + const user = await User.findOne({where: { username: name }, include: { model: FedUsers, as: 'followers' }}) if (!user) return res.status(404).send(`No record found for ${name}`) res.type('application/activity+json; charset=utf-8') diff --git a/server/migrations/20190911204228-recurrent.js b/server/migrations/20190911204228-recurrent.js new file mode 100644 index 00000000..d119ede8 --- /dev/null +++ b/server/migrations/20190911204228-recurrent.js @@ -0,0 +1,27 @@ +'use strict'; + +module.exports = { + up: (queryInterface, Sequelize) => { + return queryInterface.addColumn('events', 'recurrent', { + type: Sequelize.JSON + }) + + /* + Add altering commands here. + Return a promise to correctly handle asynchronicity. + + Example: + return queryInterface.createTable('users', { id: Sequelize.INTEGER }); + */ + }, + + down: (queryInterface, Sequelize) => { + /* + Add reverting commands here. + Return a promise to correctly handle asynchronicity. + + Example: + return queryInterface.dropTable('users'); + */ + } +}; diff --git a/server/migrations/20190912093154-create-fed-users.js b/server/migrations/20190912093154-create-fed-users.js new file mode 100644 index 00000000..524cef53 --- /dev/null +++ b/server/migrations/20190912093154-create-fed-users.js @@ -0,0 +1,25 @@ +'use strict'; +module.exports = { + up: (queryInterface, Sequelize) => { + return queryInterface.createTable('fed_users', { + ap_id: { + type: Sequelize.STRING, + primaryKey: true + }, + object: { + type: Sequelize.JSON + }, + createdAt: { + allowNull: false, + type: Sequelize.DATE + }, + updatedAt: { + allowNull: false, + type: Sequelize.DATE + } + }); + }, + down: (queryInterface, Sequelize) => { + return queryInterface.dropTable('fed_users'); + } +}; \ No newline at end of file diff --git a/server/migrations/20190912093645-fedi_followers.js b/server/migrations/20190912093645-fedi_followers.js new file mode 100644 index 00000000..0394b8ed --- /dev/null +++ b/server/migrations/20190912093645-fedi_followers.js @@ -0,0 +1,47 @@ +'use strict'; + +module.exports = { + up: (queryInterface, Sequelize) => { + return Promise.all([ + queryInterface.removeColumn('users', 'followers'), + queryInterface.createTable('user_followers', { + userId: { + type: Sequelize.INTEGER, + references: { + model: 'users', + key: 'id' + }, + primaryKey: true, + allowNull: false + }, + fedUserApId: { + primaryKey: true, + type: Sequelize.STRING, + references: { + model: 'fed_users', + key: 'ap_id' + } + }, + createdAt: { type: Sequelize.DATE, allowNull: false }, + updatedAt: { type: Sequelize.DATE, allowNull: false } + }) + ])}, + + down: (queryInterface, Sequelize) => { + return Promise.all([ + queryInterface.addColumn( + 'users', 'followers', { + type: JSON, + defaultValue: [] + }), + queryInterface.dropTable('user_followers') + ]) + /* + Add reverting commands here. + Return a promise to correctly handle asynchronicity. + + Example: + return queryInterface.dropTable('users'); + */ + } +};