overleaf/services/web/app/coffee/Features/TokenAccess/TokenAccessHandler.coffee

62 lines
2 KiB
CoffeeScript
Raw Normal View History

2017-09-22 09:54:35 -04:00
Project = require('../../models/Project').Project
PublicAccessLevels = require '../Authorization/PublicAccessLevels'
ObjectId = require("mongojs").ObjectId
module.exports = TokenAccessHandler =
findProjectWithReadOnlyToken: (token, callback=(err, project)->) ->
Project.findOne {
'tokens.readOnly': token,
'publicAccesLevel': PublicAccessLevels.TOKEN_BASED
2017-10-03 09:14:22 -04:00
}, {_id: 1, publicAccesLevel: 1}, callback
2017-09-22 09:54:35 -04:00
findProjectWithReadAndWriteToken: (token, callback=(err, project)->) ->
Project.findOne {
'tokens.readAndWrite': token,
'publicAccesLevel': PublicAccessLevels.TOKEN_BASED
2017-10-03 09:14:22 -04:00
}, {_id: 1, publicAccesLevel: 1}, callback
2017-09-22 09:54:35 -04:00
addReadOnlyUserToProject: (userId, projectId, callback=(err)->) ->
userId = ObjectId(userId.toString())
projectId = ObjectId(projectId.toString())
Project.update {
_id: projectId
}, {
$addToSet: {tokenAccessReadOnly_refs: userId}
2017-10-03 09:14:22 -04:00
}, callback
2017-09-22 09:54:35 -04:00
addReadAndWriteUserToProject: (userId, projectId, callback=(err)->) ->
userId = ObjectId(userId.toString())
projectId = ObjectId(projectId.toString())
Project.update {
_id: projectId
}, {
$addToSet: {tokenAccessReadAndWrite_refs: userId}
2017-10-03 09:14:22 -04:00
}, callback
2017-09-22 09:54:35 -04:00
2017-09-27 09:01:52 -04:00
grantSessionReadOnlyTokenAccess: (req, projectId, token) ->
2017-09-22 09:54:35 -04:00
if req.session?
if !req.session.anonReadOnlyTokenAccess?
req.session.anonReadOnlyTokenAccess = {}
2017-09-27 09:01:52 -04:00
req.session.anonReadOnlyTokenAccess[projectId.toString()] = token.toString()
2017-09-22 09:54:35 -04:00
getRequestToken: (req, projectId) ->
2017-09-27 09:01:52 -04:00
token = (
req?.session?.anonReadOnlyTokenAccess?[projectId.toString()] or
req?.headers['x-sl-anon-token']
2017-09-27 09:01:52 -04:00
)
return token
isValidReadOnlyToken: (projectId, token, callback=(err, allowed)->) ->
2017-09-27 09:01:52 -04:00
if !token
return callback null, false
TokenAccessHandler.findProjectWithReadOnlyToken token, (err, project) ->
return callback(err) if err?
isAllowed = (
project? and
project.publicAccesLevel == PublicAccessLevels.TOKEN_BASED and
project._id.toString() == projectId.toString()
)
callback null, isAllowed
2017-09-22 09:54:35 -04:00