WIP: refactor

This commit is contained in:
Shane Kilkelly 2016-09-05 15:58:31 +01:00
parent e6c7aa25ec
commit ab2c1e82fb
22 changed files with 390 additions and 357 deletions

View file

@ -1,4 +1,4 @@
AnalyticsManager = require "./AnalyticsManager"
AnalyticsManager = equire "./AnalyticsManager"
module.exports = AnalyticsController =
recordEvent: (req, res, next) ->

View file

@ -14,8 +14,8 @@ Analytics = require "../Analytics/AnalyticsManager"
module.exports = AuthenticationController =
login: (req, res, next = (error) ->) ->
AuthenticationController.doLogin req.body, req, res, next
# login: (req, res, next = (error) ->) ->
# AuthenticationController.doLogin req.body, req, res, next
serializeUser: (user, callback) ->
console.log ">> serialize", user._id
@ -65,60 +65,38 @@ module.exports = AuthenticationController =
logger.log email: email, "failed log in"
return done(null, false, {message: req.i18n.translate("email_or_password_wrong_try_again"), type: 'error'})
isUserLoggedIn: (req) ->
user_id = AuthenticationController.getLoggedInUserId(req)
return user_id?
doLogin: (options, req, res, next) ->
dienow
email = options.email?.toLowerCase()
password = options.password
redir = Url.parse(options.redir or "/project").path
LoginRateLimiter.processLoginRequest email, (err, isAllowed)->
if !isAllowed
logger.log email:email, "too many login requests"
res.statusCode = 429
return res.send
message:
text: req.i18n.translate("to_many_login_requests_2_mins"),
type: 'error'
AuthenticationManager.authenticate email: email, password, (error, user) ->
return next(error) if error?
if user?
UserHandler.setupLoginData user, ->
LoginRateLimiter.recordSuccessfulLogin email
AuthenticationController._recordSuccessfulLogin user._id
AuthenticationController.establishUserSession req, user, (error) ->
return next(error) if error?
req.session.justLoggedIn = true
logger.log email: email, user_id: user._id.toString(), "successful log in"
Analytics.recordEvent user._id, "user-logged-in"
res.json redir: redir
else
AuthenticationController._recordFailedLogin()
logger.log email: email, "failed log in"
res.json message:
text: req.i18n.translate("email_or_password_wrong_try_again"),
type: 'error'
getLoggedInUserId: (req, callback = (error, user_id) ->) ->
# TODO: perhaps should produce an error if the current user is not present
getLoggedInUserId: (req) ->
# old sessions
if req?.session?.user?._id?
callback null, req.session.user._id.toString()
return req.session.user._id.toString()
# new passport sessions
else if req?.session?.passport?.user?._id?
return req.session.passport.user._id.toString()
# neither
else
callback null, null
return null
# TODO: perhaps should produce an error if the current user is not present
getLoggedInUser: (req, callback = (error, user) ->) ->
if req.session?.user?._id?
query = req.session.user._id
else
return callback null, null
UserGetter.getUser query, callback
# omit sensitive information
UserGetter.getUser query, {hashedPassword: false, refProviders: false}, callback
requireLogin: () ->
doRequest = (req, res, next = (error) ->) ->
console.log ">>>>", req.currentUser()
if !req.session.user?
if !AuthenticationController.isUserLoggedIn()?
AuthenticationController._redirectToLoginOrRegisterPage(req, res)
else
req.user = req.session.user
return next()
return doRequest
@ -133,7 +111,7 @@ module.exports = AuthenticationController =
if req.headers['authorization']?
return AuthenticationController.httpAuth(req, res, next)
else if req.session.user?
else if AuthenticationController.isUserLoggedIn()?
return next()
else
logger.log url:req.url, "user trying to access endpoint not in global whitelist"
@ -179,26 +157,59 @@ module.exports = AuthenticationController =
Metrics.inc "user.login.failed"
callback()
establishUserSession: (req, user, callback = (error) ->) ->
dienow
lightUser =
_id: user._id
first_name: user.first_name
last_name: user.last_name
isAdmin: user.isAdmin
email: user.email
referal_id: user.referal_id
session_created: (new Date()).toISOString()
ip_address: req.ip
# Regenerate the session to get a new sessionID (cookie value) to
# protect against session fixation attacks
oldSession = req.session
req.session.destroy()
req.sessionStore.generate(req)
for key, value of oldSession
req.session[key] = value
# establishUserSession: (req, user, callback = (error) ->) ->
# dienow
# lightUser =
# _id: user._id
# first_name: user.first_name
# last_name: user.last_name
# isAdmin: user.isAdmin
# email: user.email
# referal_id: user.referal_id
# session_created: (new Date()).toISOString()
# ip_address: req.ip
# # Regenerate the session to get a new sessionID (cookie value) to
# # protect against session fixation attacks
# oldSession = req.session
# req.session.destroy()
# req.sessionStore.generate(req)
# for key, value of oldSession
# req.session[key] = value
req.session.user = lightUser
# req.session.user = lightUser
UserSessionsManager.trackSession(user, req.sessionID, () ->)
callback()
# UserSessionsManager.trackSession(user, req.sessionID, () ->)
# callback()
# doLogin: (options, req, res, next) ->
# dienow
# email = options.email?.toLowerCase()
# password = options.password
# redir = Url.parse(options.redir or "/project").path
# LoginRateLimiter.processLoginRequest email, (err, isAllowed)->
# if !isAllowed
# logger.log email:email, "too many login requests"
# res.statusCode = 429
# return res.send
# message:
# text: req.i18n.translate("to_many_login_requests_2_mins"),
# type: 'error'
# AuthenticationManager.authenticate email: email, password, (error, user) ->
# return next(error) if error?
# if user?
# UserHandler.setupLoginData user, ->
# LoginRateLimiter.recordSuccessfulLogin email
# AuthenticationController._recordSuccessfulLogin user._id
# AuthenticationController.establishUserSession req, user, (error) ->
# return next(error) if error?
# req.session.justLoggedIn = true
# logger.log email: email, user_id: user._id.toString(), "successful log in"
# Analytics.recordEvent user._id, "user-logged-in"
# res.json redir: redir
# else
# AuthenticationController._recordFailedLogin()
# logger.log email: email, "failed log in"
# res.json message:
# text: req.i18n.translate("email_or_password_wrong_try_again"),
# type: 'error'

View file

@ -3,6 +3,7 @@ async = require "async"
logger = require "logger-sharelatex"
ObjectId = require("mongojs").ObjectId
Errors = require "../Errors/Errors"
AuthenticationController = require "../Authentication/AuthenticationController"
module.exports = AuthorizationMiddlewear =
ensureUserCanReadMultipleProjects: (req, res, next) ->
@ -92,20 +93,16 @@ module.exports = AuthorizationMiddlewear =
callback(null, user_id, project_id)
_getUserId: (req, callback = (error, user_id) ->) ->
if req.session?.user?._id?
user_id = req.session.user._id
else
user_id = null
callback null, user_id
user_id = AuthenticationController.getLoggedInUserId(req)
return callback(null, user_id)
redirectToRestricted: (req, res, next) ->
res.redirect "/restricted"
restricted : (req, res, next)->
if req.session.user?
if AuthenticationController.isUserLoggedIn()?
res.render 'user/restricted',
title:'restricted'
else
logger.log "user not logged in and trying to access #{req.url}, being redirected to login"
res.redirect '/register'

View file

@ -1,14 +1,18 @@
ChatHandler = require("./ChatHandler")
EditorRealTimeController = require("../Editor/EditorRealTimeController")
logger = require("logger-sharelatex")
AuthenticationController = require('../Authentication/AuthenticationController')
module.exports =
sendMessage: (req, res)->
sendMessage: (req, res, next)->
project_id = req.params.Project_id
user_id = req.session.user._id
messageContent = req.body.content
user_id = AuthenticationController.getLoggedInUserId(req)
if !user_id?
err = new Error('no logged-in user')
return next(err)
ChatHandler.sendMessage project_id, user_id, messageContent, (err, builtMessge)->
if err?
logger.err err:err, project_id:project_id, user_id:user_id, messageContent:messageContent, "problem sending message to chat api"

View file

@ -8,6 +8,7 @@ EmailHelper = require "../Helpers/EmailHelper"
EditorRealTimeController = require("../Editor/EditorRealTimeController")
NotificationsBuilder = require("../Notifications/NotificationsBuilder")
AnalyticsManger = require("../Analytics/AnalyticsManager")
AuthenticationController = require("../Authentication/AuthenticationController")
module.exports = CollaboratorsInviteController =
@ -23,7 +24,8 @@ module.exports = CollaboratorsInviteController =
inviteToProject: (req, res, next) ->
projectId = req.params.Project_id
email = req.body.email
sendingUser = req.session.user
AuthenticationController.getLoggedInUser req, (err, sendingUser) ->
return callback(err) if err?
sendingUserId = sendingUser._id
logger.log {projectId, email, sendingUserId}, "inviting to project"
LimitationsManager.canAddXCollaborators projectId, 1, (error, allowed) =>
@ -58,8 +60,9 @@ module.exports = CollaboratorsInviteController =
resendInvite: (req, res, next) ->
projectId = req.params.Project_id
inviteId = req.params.invite_id
sendingUser = req.session.user
logger.log {projectId, inviteId}, "resending invite"
AuthenticationController.getLoggedInUser req, (err, sendingUser) ->
return callback(err) if err?
CollaboratorsInviteHandler.resendInvite projectId, sendingUser, inviteId, (err) ->
if err?
logger.err {projectId, inviteId}, "error resending invite"
@ -69,11 +72,12 @@ module.exports = CollaboratorsInviteController =
viewInvite: (req, res, next) ->
projectId = req.params.Project_id
token = req.params.token
currentUser = req.session.user
_renderInvalidPage = () ->
logger.log {projectId, token}, "invite not valid, rendering not-valid page"
res.render "project/invite/not-valid", {title: "Invalid Invite"}
# check if the user is already a member of the project
AuthenticationController.getLoggedInUser req, (err, currentUser) ->
return callback(err) if err?
CollaboratorsHandler.isUserMemberOfProject currentUser._id, projectId, (err, isMember, _privilegeLevel) ->
if err?
logger.err {err, projectId}, "error checking if user is member of project"
@ -113,8 +117,9 @@ module.exports = CollaboratorsInviteController =
projectId = req.params.Project_id
inviteId = req.params.invite_id
{token} = req.body
currentUser = req.session.user
logger.log {projectId, inviteId, userId: currentUser._id}, "accepting invite"
AuthenticationController.getLoggedInUser req, (err, currentUser) ->
return callback(err) if err?
CollaboratorsInviteHandler.acceptInvite projectId, inviteId, token, currentUser, (err) ->
if err?
logger.err {projectId, inviteId}, "error accepting invite by token"

View file

@ -16,8 +16,7 @@ module.exports = CompileController =
res.setTimeout(5 * 60 * 1000)
project_id = req.params.Project_id
isAutoCompile = !!req.query?.auto_compile
AuthenticationController.getLoggedInUserId req, (error, user_id) ->
return next(error) if error?
user_id = AuthenticationController.getLoggedInUserId req
options = {
isAutoCompile: isAutoCompile
}
@ -45,8 +44,7 @@ module.exports = CompileController =
stopCompile: (req, res, next = (error) ->) ->
project_id = req.params.Project_id
AuthenticationController.getLoggedInUserId req, (error, user_id) ->
return next(error) if error?
user_id = AuthenticationController.getLoggedInUserId req
logger.log {project_id:project_id, user_id:user_id}, "stop compile request"
CompileManager.stopCompile project_id, user_id, (error) ->
return next(error) if error?
@ -55,14 +53,16 @@ module.exports = CompileController =
_compileAsUser: (req, callback) ->
# callback with user_id if per-user, undefined otherwise
if not Settings.disablePerUserCompiles
AuthenticationController.getLoggedInUserId req, callback # -> (error, user_id)
user_id = AuthenticationController.getLoggedInUserId req
return callback(null, user_id)
else
callback() # do a per-project compile, not per-user
_downloadAsUser: (req, callback) ->
# callback with user_id if per-user, undefined otherwise
if not Settings.disablePerUserCompiles
AuthenticationController.getLoggedInUserId req, callback # -> (error, user_id)
user_id = AuthenticationController.getLoggedInUserId req
return callback(null, user_id)
else
callback() # do a per-project compile, not per-user

View file

@ -6,8 +6,7 @@ Modules = require "../../infrastructure/Modules"
module.exports = ContactsController =
getContacts: (req, res, next) ->
AuthenticationController.getLoggedInUserId req, (error, user_id) ->
return next(error) if error?
user_id = AuthenticationController.getLoggedInUserId req
ContactManager.getContactIds user_id, {limit: 50}, (error, contact_ids) ->
return next(error) if error?
UserGetter.getUsers contact_ids, {

View file

@ -1,18 +1,20 @@
NotificationsHandler = require("./NotificationsHandler")
AuthenticationController = require("../Authentication/AuthenticationController")
logger = require("logger-sharelatex")
_ = require("underscore")
module.exports =
getAllUnreadNotifications: (req, res)->
NotificationsHandler.getUserNotifications req.session.user._id, (err, unreadNotifications)->
user_id = AuthenticationController.getLoggedInUserId(req)
NotificationsHandler.getUserNotifications user_id, (err, unreadNotifications)->
unreadNotifications = _.map unreadNotifications, (notification)->
notification.html = req.i18n.translate(notification.templateKey, notification.messageOpts)
return notification
res.send(unreadNotifications)
markNotificationAsRead: (req, res)->
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
notification_id = req.params.notification_id
NotificationsHandler.markAsRead user_id, notification_id, ->
res.send()

View file

@ -18,6 +18,7 @@ InactiveProjectManager = require("../InactiveData/InactiveProjectManager")
ProjectUpdateHandler = require("./ProjectUpdateHandler")
ProjectGetter = require("./ProjectGetter")
PrivilegeLevels = require("../Authorization/PrivilegeLevels")
AuthenticationController = require("../Authentication/AuthenticationController")
module.exports = ProjectController =
@ -88,32 +89,34 @@ module.exports = ProjectController =
project_id = req.params.Project_id
projectName = req.body.projectName
logger.log project_id:project_id, projectName:projectName, "cloning project"
if !req.session.user?
if !AuthenticationController.isUserLoggedIn()?
return res.send redir:"/register"
projectDuplicator.duplicate req.session.user, project_id, projectName, (err, project)->
AuthenticationController.getLoggedInUser req, (err, currentUser) ->
return next(err) if err?
projectDuplicator.duplicate currentUser, project_id, projectName, (err, project)->
if err?
logger.error err:err, project_id: project_id, user_id: req.session.user._id, "error cloning project"
logger.error err:err, project_id: project_id, user_id: currentUser._id, "error cloning project"
return next(err)
res.send(project_id:project._id)
newProject: (req, res)->
user = req.session.user
user_id = AuthenticationController.getLoggedInUserId(req)
projectName = req.body.projectName?.trim()
template = req.body.template
logger.log user: user, projectType: template, name: projectName, "creating project"
logger.log user: user_id, projectType: template, name: projectName, "creating project"
async.waterfall [
(cb)->
if template == 'example'
projectCreationHandler.createExampleProject user._id, projectName, cb
projectCreationHandler.createExampleProject user_id, projectName, cb
else
projectCreationHandler.createBasicProject user._id, projectName, cb
projectCreationHandler.createBasicProject user_id, projectName, cb
], (err, project)->
if err?
logger.error err: err, project: project, user: user, name: projectName, templateType: template, "error creating project"
logger.error err: err, project: project, user: user_id, name: projectName, templateType: template, "error creating project"
res.sendStatus 500
else
logger.log project: project, user: user, name: projectName, templateType: template, "created project"
logger.log project: project, user: user_id, name: projectName, templateType: template, "created project"
res.send {project_id:project._id}
@ -131,7 +134,9 @@ module.exports = ProjectController =
projectListPage: (req, res, next)->
timer = new metrics.Timer("project-list")
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
AuthenticationController.getLoggedInUser req, (err, currentUser) ->
return next(err) if err?
async.parallel {
tags: (cb)->
TagsHandler.getAllTags user_id, cb
@ -140,7 +145,7 @@ module.exports = ProjectController =
projects: (cb)->
ProjectGetter.findAllUsersProjects user_id, 'name lastUpdated publicAccesLevel archived owner_ref', cb
hasSubscription: (cb)->
LimitationsManager.userHasSubscriptionOrIsGroupMember req.session.user, cb
LimitationsManager.userHasSubscriptionOrIsGroupMember currentUser, cb
user: (cb) ->
User.findById user_id, "featureSwitches", cb
}, (err, results)->
@ -183,8 +188,8 @@ module.exports = ProjectController =
if !Settings.editorIsOpen
return res.render("general/closed", {title:"updating_site"})
if req.session.user?
user_id = req.session.user._id
if AuthenticationController.isUserLoggedIn(req)?
user_id = AuthenticationController.getLoggedInUserId(req)
anonymous = false
else
anonymous = true

View file

@ -1,9 +1,11 @@
logger = require('logger-sharelatex')
ReferalHandler = require('./ReferalHandler')
AuthenticationController = require('../Authentication/AuthenticationController')
module.exports =
bonus: (req, res)->
ReferalHandler.getReferedUserIds req.session.user._id, (err, refered_users)->
user_id = AuthenticationController.getLoggedInUserId(req)
ReferalHandler.getReferedUserIds user_id, (err, refered_users)->
res.render "referal/bonus",
title: "bonus_please_recommend_us"
refered_users: refered_users

View file

@ -1,11 +1,12 @@
User = require("../../models/User").User
AuthenticationController = require('../Authentication/AuthenticationController')
module.exports = RefererMiddleware =
getUserReferalId: (req, res, next) ->
if req.session? and req.session.user?
User.findById req.session.user._id, (error, user) ->
if AuthenticationController.isUserLoggedIn()?
AuthenticationController.getLoggedInUser req, (error, user) ->
return next(error) if error?
req.session.user.referal_id = user.referal_id
req.user.referal_id = user.referal_id
next()
else
next()

View file

@ -1,5 +1,6 @@
RateLimiter = require "../../infrastructure/RateLimiter"
logger = require "logger-sharelatex"
AuthenticationController = require('../Authentication/AuthenticationController')
module.exports = RateLimiterMiddlewear =
###
@ -15,10 +16,7 @@ module.exports = RateLimiterMiddlewear =
###
rateLimit: (opts) ->
return (req, res, next) ->
if req.session?.user?
user_id = req.session.user._id
else
user_id = req.ip
user_id = AuthenticationController.getLoggedInUserId(req) || req.ip
params = (opts.params or []).map (p) -> req.params[p]
params.push user_id
if !opts.endpointName?

View file

@ -1,13 +1,15 @@
request = require 'request'
Settings = require 'settings-sharelatex'
logger = require 'logger-sharelatex'
AuthenticationController = require('../Authentication/AuthenticationController')
TEN_SECONDS = 1000 * 10
module.exports = SpellingController =
proxyRequestToSpellingApi: (req, res, next) ->
user_id = AuthenticationController.getLoggedInUserId(req)
url = req.url.slice("/spelling".length)
url = "/user/#{req.session.user._id}#{url}"
url = "/user/#{user_id}#{url}"
req.headers["Host"] = Settings.apis.spelling.host
request(url: Settings.apis.spelling.url + url, method: req.method, headers: req.headers, json: req.body, timeout:TEN_SECONDS)
.on "error", (error) ->

View file

@ -5,12 +5,13 @@ Path = require "path"
fs = require "fs"
ErrorController = require "../Errors/ErrorController"
AuthenticationController = require('../Authentication/AuthenticationController')
homepageExists = fs.existsSync Path.resolve(__dirname + "/../../../views/external/home.jade")
module.exports = HomeController =
index : (req,res)->
if req.session.user
if AuthenticationController.isUserLoggedIn(req)?
if req.query.scribtex_path?
res.redirect "/project?scribtex_path=#{req.query.scribtex_path}"
else

View file

@ -13,7 +13,7 @@ module.exports = SubscriptionController =
plansPage: (req, res, next) ->
plans = SubscriptionViewModelBuilder.buildViewModel()
if !req.session.user?
if AuthenticationController.isUserLoggedIn(req)?
baseUrl = "/register?redir="
else
baseUrl = ""

View file

@ -3,13 +3,14 @@ logger = require("logger-sharelatex")
SubscriptionLocator = require("./SubscriptionLocator")
ErrorsController = require("../Errors/ErrorController")
SubscriptionDomainHandler = require("./SubscriptionDomainHandler")
AuthenticationController = require('../Authentication/AuthenticationController')
_ = require("underscore")
async = require("async")
module.exports =
addUserToGroup: (req, res)->
adminUserId = req.session.user._id
adminUserId = AuthenticationController.getLoggedInUserId(req)
newEmail = req.body?.email?.toLowerCase()?.trim()
logger.log adminUserId:adminUserId, newEmail:newEmail, "adding user to group subscription"
SubscriptionGroupHandler.addUserToGroup adminUserId, newEmail, (err, user)->
@ -23,7 +24,7 @@ module.exports =
res.json(result)
removeUserFromGroup: (req, res)->
adminUserId = req.session.user._id
adminUserId = AuthenticationController.getLoggedInUserId(req)
userToRemove_id = req.params.user_id
logger.log adminUserId:adminUserId, userToRemove_id:userToRemove_id, "removing user from group subscription"
SubscriptionGroupHandler.removeUserFromGroup adminUserId, userToRemove_id, (err)->
@ -34,7 +35,7 @@ module.exports =
removeSelfFromGroup: (req, res)->
adminUserId = req.query.admin_user_id
userToRemove_id = req.session.user._id
userToRemove_id = AuthenticationController.getLoggedInUserId(req)
logger.log adminUserId:adminUserId, userToRemove_id:userToRemove_id, "removing user from group subscription after self request"
SubscriptionGroupHandler.removeUserFromGroup adminUserId, userToRemove_id, (err)->
if err?
@ -43,7 +44,7 @@ module.exports =
res.send()
renderSubscriptionGroupAdminPage: (req, res)->
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
SubscriptionLocator.getUsersSubscription user_id, (err, subscription)->
if !subscription.groupPlan
return res.redirect("/")
@ -55,7 +56,7 @@ module.exports =
renderGroupInvitePage: (req, res)->
group_subscription_id = req.params.subscription_id
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
licence = SubscriptionDomainHandler.findDomainLicenceBySubscriptionId(group_subscription_id)
if !licence?
return ErrorsController.notFound(req, res)
@ -77,11 +78,14 @@ module.exports =
beginJoinGroup: (req, res)->
subscription_id = req.params.subscription_id
user_id = req.session.user._id
AuthenticationController.getLoggedInUser req, (err, currentUser) ->
if err?
logger.err {subscription_id}, "error getting current user"
return res.sendStatus 500
licence = SubscriptionDomainHandler.findDomainLicenceBySubscriptionId(subscription_id)
if !licence?
return ErrorsController.notFound(req, res)
SubscriptionGroupHandler.sendVerificationEmail subscription_id, licence.name, req.session.user.email, (err)->
SubscriptionGroupHandler.sendVerificationEmail subscription_id, licence.name, currentUser.email, (err)->
if err?
res.sendStatus 500
else
@ -112,7 +116,7 @@ module.exports =
licenceName:licence.name
exportGroupCsv: (req, res)->
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
logger.log user_id: user_id, "exporting group csv"
SubscriptionLocator.getUsersSubscription user_id, (err, subscription)->
if !subscription.groupPlan

View file

@ -1,16 +1,17 @@
TagsHandler = require("./TagsHandler")
logger = require("logger-sharelatex")
AuthenticationController = require('../Authentication/AuthenticationController')
module.exports =
getAllTags: (req, res, next)->
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
logger.log {user_id}, "getting tags"
TagsHandler.getAllTags user_id, (error, allTags)->
return next(error) if error?
res.json(allTags)
createTag: (req, res, next) ->
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
name = req.body.name
logger.log {user_id, name}, "creating tag"
TagsHandler.createTag user_id, name, (error, tag) ->
@ -18,7 +19,7 @@ module.exports =
res.json(tag)
addProjectToTag: (req, res, next) ->
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
{tag_id, project_id} = req.params
logger.log {user_id, tag_id, project_id}, "adding tag to project"
TagsHandler.addProjectToTag user_id, tag_id, project_id, (error) ->
@ -26,7 +27,7 @@ module.exports =
res.status(204).end()
removeProjectFromTag: (req, res, next) ->
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
{tag_id, project_id} = req.params
logger.log {user_id, tag_id, project_id}, "removing tag from project"
TagsHandler.removeProjectFromTag user_id, tag_id, project_id, (error) ->
@ -34,7 +35,7 @@ module.exports =
res.status(204).end()
deleteTag: (req, res, next) ->
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
tag_id = req.params.tag_id
logger.log {user_id, tag_id}, "deleting tag"
TagsHandler.deleteTag user_id, tag_id, (error) ->
@ -42,7 +43,7 @@ module.exports =
res.status(204).end()
renameTag: (req, res, next) ->
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
tag_id = req.params.tag_id
name = req.body?.name
if !name?

View file

@ -5,8 +5,7 @@ AuthenticationController = require "../Authentication/AuthenticationController"
module.exports = TrackChangesController =
proxyToTrackChangesApi: (req, res, next = (error) ->) ->
AuthenticationController.getLoggedInUserId req, (error, user_id) ->
return next(error) if error?
user_id = AuthenticationController.getLoggedInUserId req
url = settings.apis.trackchanges.url + req.url
logger.log url: url, "proxying to track-changes api"
getReq = request(

View file

@ -4,11 +4,12 @@ fs = require "fs"
Path = require "path"
FileSystemImportManager = require "./FileSystemImportManager"
ProjectUploadManager = require "./ProjectUploadManager"
AuthenticationController = require('../Authentication/AuthenticationController')
module.exports = ProjectUploadController =
uploadProject: (req, res, next) ->
timer = new metrics.Timer("project-upload")
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
{originalname, path} = req.files.qqfile
name = Path.basename(originalname, ".zip")
ProjectUploadManager.createProjectFromZipArchive user_id, name, path, (error, project) ->
@ -35,7 +36,7 @@ module.exports = ProjectUploadController =
logger.err project_id:project_id, name:name, "bad name when trying to upload file"
return res.send success: false
logger.log folder_id:folder_id, project_id:project_id, "getting upload file request"
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
FileSystemImportManager.addEntity user_id, project_id, folder_id, name, path, true, (error, entity) ->
fs.unlink path, ->
timer.done()
@ -50,6 +51,3 @@ module.exports = ProjectUploadController =
project_id: project_id, file_path: path, file_name: name, folder_id: folder_id
"uploaded file"
res.send success: true, entity_id: entity?._id

View file

@ -8,6 +8,7 @@ logger = require("logger-sharelatex")
metrics = require("../../infrastructure/Metrics")
Url = require("url")
AuthenticationManager = require("../Authentication/AuthenticationManager")
AuthenticationController = require('../Authentication/AuthenticationController')
UserSessionsManager = require("./UserSessionsManager")
UserUpdater = require("./UserUpdater")
settings = require "settings-sharelatex"
@ -15,20 +16,21 @@ settings = require "settings-sharelatex"
module.exports = UserController =
deleteUser: (req, res)->
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
UserDeleter.deleteUser user_id, (err)->
if !err?
req.session?.destroy()
res.sendStatus(200)
unsubscribe: (req, res)->
UserLocator.findById req.session.user._id, (err, user)->
user_id = AuthenticationController.getLoggedInUserId(req)
UserLocator.findById user_id, (err, user)->
newsLetterManager.unsubscribe user, ->
res.send()
updateUserSettings : (req, res)->
logger.log user: req.session.user, "updating account settings"
user_id = req.session.user._id
user_id = AuthenticationController.getLoggedInUserId(req)
logger.log user: user_id, "updating account settings"
User.findById user_id, (err, user)->
if err? or !user?
logger.err err:err, user_id:user_id, "problem updaing user settings"
@ -73,7 +75,7 @@ module.exports = UserController =
if err?
logger.err err:err, user_id:user_id, "error getting user for email update"
return res.send 500
req.session.user.email = user.email
req.user.email = user.email
UserHandler.populateGroupLicenceInvite user, (err)-> #need to refresh this in the background
if err?
logger.err err:err, "error populateGroupLicenceInvite"
@ -83,7 +85,7 @@ module.exports = UserController =
metrics.inc "user.logout"
logger.log user: req?.session?.user, "logging out"
sessionId = req.sessionID
user = req?.session?.user
AuthenticationController.getLoggedInUser req, (err, user) ->
req.logout?() # passport logout
req.session.destroy (err)->
if err
@ -106,10 +108,11 @@ module.exports = UserController =
changePassword : (req, res, next = (error) ->)->
metrics.inc "user.password-change"
oldPass = req.body.currentPassword
AuthenticationManager.authenticate {_id:req.session.user._id}, oldPass, (err, user)->
user_id = AuthenticationController.getLoggedInUserId(req)
AuthenticationManager.authenticate {_id:user_id}, oldPass, (err, user)->
return next(err) if err?
if(user)
logger.log user: req.session.user, "changing password"
logger.log user: user._id, "changing password"
newPassword1 = req.body.newPassword1
newPassword2 = req.body.newPassword2
if newPassword1 != newPassword2

View file

@ -4,6 +4,7 @@ ErrorController = require("../Errors/ErrorController")
logger = require("logger-sharelatex")
Settings = require("settings-sharelatex")
fs = require('fs')
AuthenticationController = require('../Authentication/AuthenticationController')
module.exports =
@ -53,8 +54,9 @@ module.exports =
email: req.query.email
settingsPage : (req, res, next)->
logger.log user: req.session.user, "loading settings page"
UserLocator.findById req.session.user._id, (err, user)->
user_id = AuthenticationController.getLoggedInUserId(req)
logger.log user: user_id, "loading settings page"
UserLocator.findById user_id, (err, user)->
return next(err) if err?
res.render 'user/settings',
title:'account_settings'

View file

@ -5,6 +5,7 @@ Settings = require('settings-sharelatex')
SubscriptionFormatters = require('../Features/Subscription/SubscriptionFormatters')
querystring = require('querystring')
SystemMessageManager = require("../Features/SystemMessages/SystemMessageManager")
AuthenticationController = require("../Features/Authentication/AuthenticationController")
_ = require("underscore")
Modules = require "./Modules"
Url = require "url"
@ -167,7 +168,7 @@ module.exports = (app, webRouter, apiRouter)->
return ""
res.locals.getLoggedInUserId = ->
return req.session.user?._id
return AuthenticationController.getLoggedInUserId(req)
next()
webRouter.use (req, res, next) ->
@ -193,11 +194,11 @@ module.exports = (app, webRouter, apiRouter)->
next()
webRouter.use (req, res, next)->
if req.session.user?
if req.user?
res.locals.user =
email: req.session.user.email
first_name: req.session.user.first_name
last_name: req.session.user.last_name
email: req.user.email
first_name: req.user.first_name
last_name: req.user.last_name
if req.session.justRegistered
res.locals.justRegistered = true
delete req.session.justRegistered
@ -246,5 +247,3 @@ module.exports = (app, webRouter, apiRouter)->
res.locals.moduleIncludes = Modules.moduleIncludes
res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
next()