Skip to content

Commit

Permalink
fix: user role
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolaslabbe committed Nov 25, 2016
1 parent 115f3d8 commit 015dfc8
Show file tree
Hide file tree
Showing 15 changed files with 172 additions and 133 deletions.
1 change: 1 addition & 0 deletions dump.rdb
@@ -0,0 +1 @@
REDIS0006�ܳC�Z��V
10 changes: 7 additions & 3 deletions src/cli/core/config/config.js
Expand Up @@ -108,10 +108,14 @@ result.set = (json) => {
}

result.save = (json) => {
extend(true, result, json)
// extend(true, result, json)

var confPath = path.join(result.root,'abe.json')
fse.writeJsonSync(confPath, json, { space: 2, encoding: 'utf-8' })
if (result.localConfigExist()){
// var abeJson = fse.readJsonSync(path.join(result.root,'abe.json'))
// extend(true, abeJson, json)
var confPath = path.join(result.root,'abe.json')
fse.writeJsonSync(confPath, json, { space: 2, encoding: 'utf-8' })
}
}

result.getConfigByWebsite = () => {
Expand Down
12 changes: 6 additions & 6 deletions src/cli/users/operations.js
Expand Up @@ -29,7 +29,7 @@ export function add(newUser) {
newUser.password = User.utils.encryptPassword(10, newUser.password)
bdd.push(newUser)

User.manager.instance.save(bdd)
User.manager.instance.update(bdd)

return {
success:1,
Expand All @@ -46,7 +46,7 @@ export function deactivate(id) {
bdd[i].actif = 0
}
}
User.manager.instance.save(bdd)
User.manager.instance.update(bdd)
return bdd
}

Expand All @@ -59,7 +59,7 @@ export function activate(id) {
bdd[i].actif = 1
}
}
User.manager.instance.save(bdd)
User.manager.instance.update(bdd)
return bdd
}

Expand All @@ -74,7 +74,7 @@ export function remove(id) {
}
}
bdd = newBdd
User.manager.instance.save(bdd)
User.manager.instance.update(bdd)
return bdd
}

Expand All @@ -100,7 +100,7 @@ export function update(data) {
})
}
}
bdd = User.manager.instance.save(bdd)
bdd = User.manager.instance.update(bdd)

return {
success:1,
Expand All @@ -123,7 +123,7 @@ export function updatePassword(data, password) {
}
}

bdd = User.manager.instance.save(bdd)
bdd = User.manager.instance.update(bdd)

return {
success:1,
Expand Down
54 changes: 54 additions & 0 deletions src/cli/users/utils.js
@@ -1,3 +1,5 @@
import redis from 'redis'
import Limiter from 'ratelimiter'
import owasp from 'owasp-password-strength-test'
import bcrypt from 'bcrypt-nodejs'
import Cookies from 'cookies'
Expand Down Expand Up @@ -190,7 +192,22 @@ export function getTokenFromCookies(req, res) {
return cookies.get('x-access-token')
}

export function isAbeRestrictedUrl(currentRoute) {
if( currentRoute.indexOf('/abe/users/forgot') > -1
|| currentRoute.indexOf('/abe/users/login') > -1
|| currentRoute.indexOf('/abe/users/reset') > -1
|| !/^\/abe/.test(currentRoute)) {
return false
}

return true
}

export function isUserAllowedOnRoute(workflow, currentRoute) {
if( currentRoute.indexOf('/abe/users/forgot') > -1 || currentRoute.indexOf('/abe/users/login') > -1 || !/^\/abe/.test(currentRoute)) {
return true
}

var isAllowed = false

if (currentRoute.indexOf('abe/') === -1) {
Expand Down Expand Up @@ -252,4 +269,41 @@ export function getUserWorkflow(status, role) {
flows = [addFlow("draft", "draft", "submit"), addFlow("publish", "publish", "submit")]
}
return flows
}

export function loginLimitTry(username) {
var p = new Promise((resolve) => {
var isNexted = false
try {
var limiterConfig = config.users.limiter

var client = redis.createClient()
client.on('error', function() {
if (!isNexted) {
isNexted = true
resolve()
}
})

var limit = new Limiter({
id: username,
db: client,
duration: limiterConfig.duration,
max: limiterConfig.max
})

limit.get(function(err, limit) {
if (err) {
resolve()
}else {
resolve(limit)
}
})
}catch(e) {
console.log('loginLimitTry', e)
resolve()
}
})

return p
}
10 changes: 0 additions & 10 deletions src/server/app.js
Expand Up @@ -105,16 +105,6 @@ app.use(function (req, res, next) {
res.locals.nonce = uuid.v4()
next()
})
app.use(function (req, res, next) {
if(typeof req.query.logs !== 'undefined' && req.query.logs !== null
&& req.query.logs === 'true') {
config.logs = true
}else if(typeof req.query.logs !== 'undefined' && req.query.logs !== null
&& req.query.logs === 'false') {
config.logs = false
}
next()
})

if(config.security === true){
app.use(helmet())
Expand Down
21 changes: 13 additions & 8 deletions src/server/middlewares/isAuthorized.js
Expand Up @@ -6,26 +6,31 @@ import {
var middleware = function(req, res, next) {
if (!config.users.enable) {
if (req.url.indexOf('/abe/users/login') > -1) {
res.redirect('/abe')
res.redirect('/abe/editor')
return
}else {
next()
return
}
}

if( req.url.indexOf('/abe/users/forgot') > -1 || req.url.indexOf('/abe/users/login') > -1 || !/^\/abe/.test(req.url)) {
next()
return
var decoded = User.utils.decodeUser(req, res)
var user = User.utils.findSync(decoded.iss)
res.user = user

if(!User.utils.isAbeRestrictedUrl(req.url)) {
// if (user != null && req.url.indexOf('/abe/users/login') > -1 && req.method === 'GET' ) {
// res.redirect('/abe/editor')
// return
// }else {
next()
return
// }
}

var isHtml = /text\/html/.test(req.get('accept')) ? true : false

var decoded = User.utils.decodeUser(req, res)
var user = User.utils.findSync(decoded.iss)

if (user != null && User.utils.isUserAllowedOnRoute(user.role.workflow, req.url)) {
res.user = user
next()
}else {
if(isHtml) {
Expand Down
52 changes: 2 additions & 50 deletions src/server/middlewares/login.js
@@ -1,58 +1,10 @@
import redis from 'redis'
import Limiter from 'ratelimiter'

import {
config
,User
} from '../../cli'

var middleware = function(req, res, next) {
var isNexted = false
if( req.url === '/abe/users/login' && req.method === 'POST' ) {
try {
var username = req.body.username
var limiterConfig = config.users.limiter

var client = redis.createClient()
client.on('error', function() {
if (!isNexted) {
isNexted = true
next()
}
})

var limit = new Limiter({
id: username,
db: client,
duration: limiterConfig.duration,
max: limiterConfig.max
})

limit.get(function(err, limit) {
if (err) return next(err)

try {
res.set('X-RateLimit-Limit', limit.total)
res.set('X-RateLimit-Remaining', limit.remaining - 1)
res.set('X-RateLimit-Reset', limit.reset)

// all good
console.log('remaining ', limit.remaining - 1, limit.total, username)
if (limit.remaining) return next()

// not good
var after = limit.reset - (Date.now() / 1000) | 0
res.set('Retry-After', after)
res.send(429, 'Rate limit exceeded')
} catch(e) {
console.log('e', e)
next()
}
})
} catch(e) {
console.log('e', e)
next()
}
}else if( req.url.indexOf('/abe/') > -1) {
if( req.url.indexOf('/abe/') > -1) {
var send = res.send
var token = req.csrfToken()
res.send = function (string) {
Expand Down
12 changes: 6 additions & 6 deletions src/server/public/scripts/modules/EditorJson.js
Expand Up @@ -68,12 +68,12 @@ export default class Json {
alert(jsonRes.error)
return
}
// if(typeof jsonRes.reject !== 'undefined' && jsonRes.reject !== null) {
// location.reload()
// return
// }
this.data = jsonRes.json
location.reload()
if (jsonRes.success == 1) {
this.data = jsonRes.json
location.reload()
}else {
alert(jsonRes.message)
}
}
catch(e){
alert('The following error happened : \n' + e + '\n if it persist, reload your web page tab.')
Expand Down
2 changes: 1 addition & 1 deletion src/server/public/scripts/modules/EditorSave.js
Expand Up @@ -122,8 +122,8 @@ export default class EditorSave {
target.classList.remove('done')
target.removeAttribute('disabled')

this._abeDisplayStatus.innerHTML = result.json.abe_meta.status
if(result.success === 1) {
this._abeDisplayStatus.innerHTML = result.json.abe_meta.status
window.json = result.json
}
var formWrapper = document.querySelector('#abeForm')
Expand Down
16 changes: 11 additions & 5 deletions src/server/public/scripts/modules/UserList.js
Expand Up @@ -39,7 +39,9 @@ var usersList = {
'info': false,
'columns': columns
})
}

if ($('#filtered-list-url').size() > 0) {
this._handleFormUserRoleSubmit = this._formUserRoleSubmit.bind(this)

this._formUserRole = document.querySelector('[data-user-role]')
Expand Down Expand Up @@ -93,15 +95,19 @@ var usersList = {
var inputs = this._formUserRole.querySelectorAll('input[type=checkbox]')
var data = {}
Array.prototype.forEach.call(inputs, (input) => {
var name = input.getAttribute('name')
if (data[name] == null) {
data[name] = []
if (!input.disabled) {
var name = input.getAttribute('name')
if (data[name] == null) {
data[name] = []
}
if (input.checked) {
data[name].push(input.getAttribute('value'))
}
}
data[name].push(input.getAttribute('value'))
})

var toSave = qs.stringify(data)

this._ajax(
{
url: '/abe/list-url/save',
Expand Down
2 changes: 1 addition & 1 deletion src/server/routes/get-list-url.js
Expand Up @@ -17,7 +17,7 @@ var route = function(router, req, res, next) {
urls.push({
url: route.route.path,
method: Object.keys(route.route.methods)[0].toUpperCase(),
regex: '^\\' + route.route.path.replace(/\*$/, '') + '.*?'
regex: route.route.path.replace(/\*$/, '') + '.*'
})
})

Expand Down
19 changes: 15 additions & 4 deletions src/server/routes/post-list-url-save.js
Expand Up @@ -10,11 +10,22 @@ import {
var route = function(req, res, next) {

var authorizations = req.body
delete authorizations.admin

config.user
console.log('* * * * * * * * * * * * * * * * * * * * * * * * * * * * *')
console.log('authorizations', authorizations)
let json = config.getLocalConfig()

Array.prototype.forEach.call(Object.keys(authorizations), (key) => {
if (key != "admin") {
json.users.routes[key] = authorizations[key]
}
})

config.save(json)

res.set('Content-Type', 'application/json')
res.send(JSON.stringify({
success: 1,
message: 'config saved'
}))
}

export default route

0 comments on commit 015dfc8

Please sign in to comment.