use oauth2 password flow for webclient

This commit is contained in:
les
2020-01-27 00:47:03 +01:00
parent 6352cb3d12
commit b706333c85
21 changed files with 367 additions and 448 deletions

View File

@@ -1,38 +1,35 @@
const { Op } = require('sequelize')
const { user: User } = require('./models')
const debug = require('debug')('auth')
const oauth = require('./oauth')
const Auth = {
/** isAuth middleware
* req.user is filled in server/helper.js#initMiddleware
*/
async isAuth (req, res, next) {
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 }
})
if (!req.user) {
return res
.status(403)
.send({ message: 'Failed to authenticate token ' })
}
next()
isAuth (req, res, next) {
return oauth.oauthServer.authenticate()(req, res, next)
},
/** isAdmin middleware */
isAdmin (req, res, next) {
if (!req.user) {
return res
.status(403)
.send({ message: 'Failed to authenticate token ' })
oauth.oauthServer.authenticate()(req, res, () => {
req.user = res.locals.oauth.token.user
if (req.user.is_admin) {
next()
} else {
res.status(404)
}
})
},
hasPerm (scope) {
return (req, res, next) => {
debug(scope, req.path)
oauth.oauthServer.authenticate({ scope })(req, res, () => {
req.user = res.locals.oauth.token.user
next()
})
}
if (req.user.is_admin && req.user.is_active) { return next() }
return res.status(403).send({ message: 'Admin needed' })
}
}

View File

@@ -9,23 +9,7 @@ const debug = require('debug')('controller:event')
const eventController = {
/** add a resource to event
* @todo not used anywhere, should we use with webmention?
* @todo should we use this for roply coming from fediverse?
*/
// async addComment (req, res) {
// // comments could be added to an event or to another comment
// let event = await Event.findOne({ where: { activitypub_id: { [Op.eq]: req.body.id } } })
// if (!event) {
// const comment = await Resource.findOne({ where: { activitypub_id: { [Op.eq]: req.body.id } }, include: Event })
// event = comment.event
// }
// const comment = new Comment(req.body)
// event.addComment(comment)
// res.json(comment)
// },
async getMeta (req, res) {
async _getMeta () {
const places = await Place.findAll({
order: [[Sequelize.literal('weigth'), 'DESC']],
attributes: {
@@ -44,7 +28,11 @@ const eventController = {
}
})
res.json({ tags, places })
return { places, tags }
},
async getMeta (req, res) {
res.json(await eventController._getMeta())
},
async getNotifications (event, action) {
@@ -197,131 +185,113 @@ const eventController = {
res.sendStatus(200)
},
async addRecurrent (start, places, where_tags, limit) {
const where = {
is_visible: true,
recurrent: { [Op.ne]: null }
// placeId: places
}
// async addRecurrent (start, places, where_tags, limit) {
// const where = {
// is_visible: true,
// recurrent: { [Op.ne]: null }
// // placeId: places
// }
const events = await Event.findAll({
where,
limit,
attributes: {
exclude: ['slug', 'likes', 'boost', 'userId', 'is_visible', 'description', 'createdAt', 'updatedAt', 'placeId']
},
order: ['start_datetime', [Tag, 'weigth', 'DESC']],
include: [
{ model: Resource, required: false, attributes: ['id'] },
{ model: Tag, ...where_tags, attributes: ['tag'], through: { attributes: [] } },
{ model: Place, required: false, attributes: ['id', 'name', 'address'] }
]
})
// const events = await Event.findAll({
// where,
// limit,
// attributes: {
// exclude: ['slug', 'likes', 'boost', 'userId', 'is_visible', 'description', 'createdAt', 'updatedAt', 'placeId']
// },
// order: ['start_datetime', [Tag, 'weigth', 'DESC']],
// include: [
// { model: Resource, required: false, attributes: ['id'] },
// { model: Tag, ...where_tags, attributes: ['tag'], through: { attributes: [] } },
// { model: Place, required: false, attributes: ['id', 'name', 'address'] }
// ]
// })
debug(`Found ${events.length} recurrent events`)
let allEvents = []
_.forEach(events, e => {
allEvents = allEvents.concat(eventController.createEventsFromRecurrent(e.get(), start))
})
// let allEvents = []
// _.forEach(events, e => {
// allEvents = allEvents.concat(eventController.createEventsFromRecurrent(e.get(), start))
// })
debug(`Created ${allEvents.length} events`)
return allEvents
},
// return allEvents
// },
// build singular events from a recurrent pattern
createEventsFromRecurrent (e, start, dueTo = null) {
const events = []
const recurrent = JSON.parse(e.recurrent)
if (!recurrent.frequency) { return false }
if (!dueTo) {
dueTo = moment.unix(start).add(2, 'month')
}
let cursor = moment.unix(start).startOf('week')
const start_date = moment.unix(e.start_datetime)
const duration = moment.unix(e.end_datetime).diff(start_date, 's')
const frequency = recurrent.frequency
const days = recurrent.days
const type = recurrent.type
// // build singular events from a recurrent pattern
// createEventsFromRecurrent (e, start, dueTo = null) {
// const events = []
// const recurrent = JSON.parse(e.recurrent)
// if (!recurrent.frequency) { return false }
// if (!dueTo) {
// dueTo = start.add(2, 'month')
// }
// let cursor = start.startOf('week')
// const start_date = moment.unix(e.start_datetime)
// const duration = moment.unix(e.end_datetime).diff(start_date, 's')
// const frequency = recurrent.frequency
// const days = recurrent.days
// const type = recurrent.type
// default frequency is '1d' => each day
const toAdd = { n: 1, unit: 'day' }
// // default frequency is '1d' => each day
// const toAdd = { n: 1, unit: 'day' }
// each week or 2 (search for the first specified day)
if (frequency === '1w' || frequency === '2w') {
cursor.add(days[0] - 1, 'day')
if (frequency === '2w') {
const nWeeks = cursor.diff(e.start_datetime, 'w') % 2
if (!nWeeks) { cursor.add(1, 'week') }
}
toAdd.n = Number(frequency[0])
toAdd.unit = 'week'
// cursor.set('hour', start_date.hour()).set('minute', start_date.minutes())
}
// // each week or 2 (search for the first specified day)
// if (frequency === '1w' || frequency === '2w') {
// cursor.add(days[0] - 1, 'day')
// if (frequency === '2w') {
// const nWeeks = cursor.diff(e.start_datetime, 'w') % 2
// if (!nWeeks) { cursor.add(1, 'week') }
// }
// toAdd.n = Number(frequency[0])
// toAdd.unit = 'week'
// // cursor.set('hour', start_date.hour()).set('minute', start_date.minutes())
// }
cursor.set('hour', start_date.hour()).set('minute', start_date.minutes())
// cursor.set('hour', start_date.hour()).set('minute', start_date.minutes())
// each month or 2
if (frequency === '1m' || frequency === '2m') {
// find first match
toAdd.n = 1
toAdd.unit = 'month'
if (type === 'weekday') {
// // each month or 2
// if (frequency === '1m' || frequency === '2m') {
// // find first match
// toAdd.n = 1
// toAdd.unit = 'month'
// if (type === 'weekday') {
} else if (type === 'ordinal') {
// } else if (type === 'ordinal') {
}
}
// }
// }
// add event at specified frequency
while (true) {
const first_event_of_week = cursor.clone()
days.forEach(d => {
if (type === 'ordinal') {
cursor.date(d)
} else {
cursor.day(d - 1)
}
if (cursor.isAfter(dueTo) || cursor.isBefore(start)) { return }
e.start_datetime = cursor.unix()
e.end_datetime = e.start_datetime + duration
events.push(Object.assign({}, e))
})
if (cursor.isAfter(dueTo)) { break }
cursor = first_event_of_week.add(toAdd.n, toAdd.unit)
cursor.set('hour', start_date.hour()).set('minute', start_date.minutes())
}
// // add event at specified frequency
// while (true) {
// const first_event_of_week = cursor.clone()
// days.forEach(d => {
// if (type === 'ordinal') {
// cursor.date(d)
// } else {
// cursor.day(d - 1)
// }
// if (cursor.isAfter(dueTo) || cursor.isBefore(start)) { return }
// e.start_datetime = cursor.unix()
// e.end_datetime = e.start_datetime + duration
// events.push(Object.assign({}, e))
// })
// if (cursor.isAfter(dueTo)) { break }
// cursor = first_event_of_week.add(toAdd.n, toAdd.unit)
// cursor.set('hour', start_date.hour()).set('minute', start_date.minutes())
// }
return events
},
// return events
// },
/**
* Select events based on params
*/
async select (req, res) {
const start = req.query.start || moment().unix()
const limit = req.query.limit || 100
const show_recurrent = req.query.show_recurrent || true
const filter_tags = req.query.tags || ''
const filter_places = req.query.places || ''
debug(`select limit:${limit} rec:${show_recurrent} tags:${filter_tags} places:${filter_places}`)
let where_tags = {}
async _select (start = moment.unix(), limit = 100, show_recurrent = true) {
const where = {
// confirmed event only
is_visible: true,
start_datetime: { [Op.gt]: start },
recurrent: null
start_datetime: { [Op.gt]: start }
}
if (filter_tags) {
where_tags = { where: { tag: filter_tags.split(',') } }
if (!show_recurrent) {
where.recurrent = null
}
if (filter_places) {
where.placeId = filter_places.split(',')
}
let events = await Event.findAll({
const events = await Event.findAll({
where,
limit,
attributes: {
@@ -331,80 +301,77 @@ const eventController = {
order: ['start_datetime', [Tag, 'weigth', 'DESC']],
include: [
{ model: Resource, required: false, attributes: ['id'] },
{ model: Tag, ...where_tags, attributes: ['tag'], through: { attributes: [] } },
{ model: Tag, attributes: ['tag'], required: false, through: { attributes: [] } },
{ model: Place, required: false, attributes: ['id', 'name', 'address'] }
]
})
let recurrentEvents = []
events = _.map(events, e => e.get())
if (show_recurrent) {
recurrentEvents = await eventController.addRecurrent(start, where.placeId, where_tags, limit)
events = _.concat(events, recurrentEvents)
}
// flat tags
events = _(events).map(e => {
e.tags = e.tags.map(t => t.tag)
return _(events).map(e => {
e = e.get()
e.tags = e.tags ? e.tags.map(t => t && t.tag) : []
return e
})
// allEvents.sort((a,b) => a.start_datetime-b.start_datetime)
res.json(events.sort((a, b) => a.start_datetime - b.start_datetime))
// res.json(recurrentEvents)
},
/**
* Select events based on params
*/
async select (req, res) {
const start = req.query.start || moment().unix()
const limit = req.query.limit || 100
const show_recurrent = req.query.show_recurrent || true
res.json(await eventController._select(start, limit, show_recurrent))
// const filter_tags = req.query.tags || ''
// const filter_places = req.query.places || ''
// debug(`select limit:${limit} rec:${show_recurrent} tags:${filter_tags} places:${filter_places}`)
// let where_tags = {}
// const where = {
// // confirmed event only
// is_visible: true,
// start_datetime: { [Op.gt]: start },
// recurrent: null
// }
// if (filter_tags) {
// where_tags = { where: { tag: filter_tags.split(',') } }
// }
// if (filter_places) {
// where.placeId = filter_places.split(',')
// }
// let events = await Event.findAll({
// where,
// limit,
// attributes: {
// exclude: ['slug', 'likes', 'boost', 'userId', 'is_visible', 'description', 'createdAt', 'updatedAt', 'placeId']
// // include: [[Sequelize.fn('COUNT', Sequelize.col('activitypub_id')), 'ressources']]
// },
// order: ['start_datetime', [Tag, 'weigth', 'DESC']],
// include: [
// { model: Resource, required: false, attributes: ['id'] },
// { model: Tag, ...where_tags, attributes: ['tag'], through: { attributes: [] } },
// { model: Place, required: false, attributes: ['id', 'name', 'address'] }
// ]
// })
// let recurrentEvents = []
// events = _.map(events, e => e.get())
// if (show_recurrent) {
// recurrentEvents = await eventController.addRecurrent(moment.unix(start), where.placeId, where_tags, limit)
// events = _.concat(events, recurrentEvents)
// }
// // flat tags
// events = _(events).map(e => {
// e.tags = e.tags.map(t => t.tag)
// return e
// })
// res.json(events.sort((a, b) => a.start_datetime - b.start_datetime))
}
// async getAll (req, res) {
// // this is due how v-calendar shows dates
// const start = moment()
// .year(req.params.year)
// .month(req.params.month)
// .startOf('month')
// .startOf('week')
// let end = moment()
// .year(req.params.year)
// .month(req.params.month)
// .endOf('month')
// const shownDays = end.diff(start, 'days')
// if (shownDays <= 35) { end = end.add(1, 'week') }
// end = end.endOf('week')
// let events = await Event.findAll({
// where: {
// // return only confirmed events
// is_visible: true,
// [Op.or]: [
// // return all recurrent events regardless start_datetime
// { recurrent: { [Op.ne]: null } },
// // and events in specified range
// { start_datetime: { [Op.between]: [start.unix(), end.unix()] } }
// ]
// },
// attributes: { exclude: ['createdAt', 'updatedAt', 'placeId'] },
// order: [[Tag, 'weigth', 'DESC']],
// include: [
// { model: Resource, required: false, attributes: ['id'] },
// { model: Tag, required: false },
// { model: Place, required: false, attributes: ['id', 'name', 'address'] }
// ]
// })
// events = events.map(e => e.get()).map(e => {
// e.tags = e.tags.map(t => t.tag)
// return e
// })
// let allEvents = events.filter(e => !e.recurrent || e.recurrent.length === 0)
// events.filter(e => e.recurrent && e.recurrent.length).forEach(e => {
// const events = createEventsFromRecurrent(e, end)
// if (events) { allEvents = allEvents.concat(events) }
// })
// // allEvents.sort((a,b) => a.start_datetime-b.start_datetime)
// res.json(allEvents.sort((a, b) => a.start_datetime - b.start_datetime))
// }
}
module.exports = eventController

View File

@@ -76,12 +76,12 @@ const oauthController = {
* */
async getAccessToken (accessToken) {
const oauth_token = await OAuthToken.findByPk(accessToken,
{ include: [User, { model: OAuthClient, as: 'client' }], nest: true, raw: true })
{ include: [User, { model: OAuthClient, as: 'client' }] })
return oauth_token
},
/**
* Invoked to retrieve a client using a client id or a client id/client secret combination, depending on the grant type.
* Invoked to retrieve a client using a client id or a client id/client secret combination, depend on the grant type.
*/
async getClient (client_id, client_secret) {
const client = await OAuthClient.findByPk(client_id, { raw: true })
@@ -89,7 +89,7 @@ const oauthController = {
return false
}
if (client) { client.grants = ['authorization_code'] }
if (client) { client.grants = ['authorization_code', 'password'] }
return client
},
@@ -119,11 +119,32 @@ const oauthController = {
return oauth_code.destroy()
},
async getUser (username, password) {
const user = await User.findOne({ where: { email: username } })
if (!user || !user.is_active) {
return false
}
// check if password matches
if (await user.comparePassword(password)) {
return user
}
return false
},
async saveAuthorizationCode (code, client, user) {
code.userId = user.id
code.oauthClientId = client.id
const ret = await OAuthCode.create(code)
return ret
},
verifyScope (token, scope) {
debug(token.user.is_admin)
if (token.user.is_admin) {
return true
} else {
return false
}
}
}

View File

@@ -1,9 +1,7 @@
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const { Op } = require('sequelize')
const jsonwebtoken = require('jsonwebtoken')
const sanitizeHtml = require('sanitize-html')
const config = require('config')
const mail = require('../mail')
@@ -12,33 +10,6 @@ const settingsController = require('./settings')
const debug = require('debug')('user:controller')
const userController = {
async login (req, res) {
// find the user
const user = await User.findOne({ where: { email: req.body.email } })
if (!user) {
res.status(403).json({ success: false, message: 'auth.fail' })
} else if (user) {
if (!user.is_active) {
res.status(403).json({ success: false, message: 'auth.not_confirmed' })
// check if password matches
} else if (!await user.comparePassword(req.body.password)) {
res.status(403).json({ success: false, message: 'auth.fail' })
} else {
// if user is found and password is right
// create a token
const accessToken = jsonwebtoken.sign(
{
id: user.id,
email: user.email,
scope: [user.is_admin ? 'admin' : 'user']
},
config.secret
)
res.json({ token: accessToken })
}
}
},
async delEvent (req, res) {
const event = await Event.findByPk(req.params.id)
// check if event is mine (or user is admin)

View File

@@ -2,7 +2,7 @@ const express = require('express')
const multer = require('multer')
const cors = require('cors')()
const { isAuth, isAdmin } = require('./auth')
const { isAuth, isAdmin, hasPerm } = require('./auth')
const eventController = require('./controller/event')
const exportController = require('./controller/export')
const userController = require('./controller/user')
@@ -11,7 +11,6 @@ const instanceController = require('./controller/instance')
const apUserController = require('./controller/ap_user')
const resourceController = require('./controller/resource')
const oauthController = require('./controller/oauth')
const oauth = require('./oauth')
const storage = require('./storage')
const upload = multer({ storage })
@@ -22,10 +21,9 @@ const api = express.Router()
api.use(express.urlencoded({ extended: false }))
api.use(express.json())
// AUTH
api.post('/auth/login', userController.login)
api.get('/auth/user', userController.current)
api.get('/user', isAuth, (req, res) => res.json(res.locals.oauth.token.user))
// api.post('/user/login', userController.login)
// api.get('/user/logout', userController.logout)
api.post('/user/recover', userController.forgotPassword)
api.post('/user/check_recover_code', userController.checkRecoverCode)
api.post('/user/recover_password', userController.updatePasswordWithRecoverCode)
@@ -35,12 +33,11 @@ api.post('/user/register', userController.register)
api.post('/user', isAdmin, userController.create)
// update user
api.put('/user', isAuth, userController.update)
api.put('/user', hasPerm('user:update'), userController.update)
// delete user
api.delete('/user/:id', isAdmin, userController.remove)
// api.delete('/user', userController.remove)
api.delete('/user', hasPerm('user:remove'), userController.remove)
// get all users
api.get('/users', isAdmin, userController.getAll)
@@ -52,10 +49,10 @@ api.put('/place', isAdmin, eventController.updatePlace)
api.post('/user/event', upload.single('image'), userController.addEvent)
// update event
api.put('/user/event', isAuth, upload.single('image'), userController.updateEvent)
api.put('/user/event', hasPerm('event:write'), upload.single('image'), userController.updateEvent)
// remove event
api.delete('/user/event/:id', isAuth, userController.delEvent)
api.delete('/user/event/:id', hasPerm('event:remove'), userController.delEvent)
// get tags/places
api.get('/event/meta', eventController.getMeta)
@@ -63,18 +60,17 @@ api.get('/event/meta', eventController.getMeta)
// get unconfirmed events
api.get('/event/unconfirmed', isAdmin, eventController.getUnconfirmed)
// add event notification
// add event notification TODO
api.post('/event/notification', eventController.addNotification)
api.delete('/event/notification/:code', eventController.delNotification)
api.get('/settings', settingsController.getAllRequest)
api.post('/settings', isAdmin, settingsController.setRequest)
api.post('/settings/favicon', isAdmin, multer({ dest: 'thumb/' }).single('favicon'), settingsController.setFavicon)
// api.get('/settings/user_locale', settingsController.getUserLocale)
// confirm eventtags
api.get('/event/confirm/:event_id', isAuth, eventController.confirm)
api.get('/event/unconfirm/:event_id', isAuth, eventController.unconfirm)
// confirm event
api.get('/event/confirm/:event_id', hasPerm('event:write'), eventController.confirm)
api.get('/event/unconfirm/:event_id', hasPerm('event:write'), eventController.unconfirm)
// get event
api.get('/event/:event_id.:format?', cors, eventController.get)
@@ -94,18 +90,11 @@ api.put('/resources/:resource_id', isAdmin, resourceController.hide)
api.delete('/resources/:resource_id', isAdmin, resourceController.remove)
api.get('/resources', isAdmin, resourceController.getAll)
api.get('/clients', isAuth, oauthController.getClients)
api.get('/client/:client_id', isAuth, oauthController.getClient)
api.get('/clients', hasPerm('oauth:read'), oauthController.getClients)
api.get('/client/:client_id', hasPerm('oauth:read'), oauthController.getClient)
api.post('/client', oauthController.createClient)
// api.get('/verify', oauth.oauthServer.authenticate(), (req, res) => {
// })
// Handle 404
api.use((req, res) => {
debug('404 Page not found: %s', req.path)
res.status(404).send('404: Page not Found')
})
api.use((req, res) => res.sendStatus(404))
// Handle 500
api.use((error, req, res, next) => {

View File

@@ -32,7 +32,7 @@ const mail = {
updateFiles: false,
defaultLocale: settings.locale,
locale: settings.locale,
locales: ['it', 'es'] // TOFIX
locales: ['it', 'es', 'en', 'ca']
},
transport: config.smtp
})

View File

@@ -10,6 +10,7 @@ const oauthServer = new OAuthServer({
useErrorHandler: true,
continueMiddleware: false,
debug: true,
requireClientAuthentication: { password: false },
authenticateHandler: {
handle (req) {
if (!req.user) {
@@ -25,9 +26,12 @@ oauth.use(express.json())
oauth.use(express.urlencoded({ extended: false }))
oauth.post('/token', oauthServer.token())
oauth.post('/login', oauthServer.token())
oauth.get('/authorize', oauthServer.authorize())
oauth.use((req, res) => res.sendStatus(404))
oauth.use((err, req, res, next) => {
const error_msg = err.toString()
debug(err)