| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242 |
- const sinon = require('sinon')
- const chai = require('chai')
- const { expect } = chai
- const modulePath =
- '../../../../app/src/Features/Authentication/AuthenticationController.js'
- const SandboxedModule = require('sandboxed-module')
- const tk = require('timekeeper')
- const MockRequest = require('../helpers/MockRequest')
- const MockResponse = require('../helpers/MockResponse')
- const { ObjectId } = require('mongojs')
- describe('AuthenticationController', function() {
- beforeEach(function() {
- tk.freeze(Date.now())
- this.UserModel = { findOne: sinon.stub() }
- this.httpAuthUsers = {
- 'valid-test-user': Math.random()
- .toString(16)
- .slice(2)
- }
- this.AuthenticationController = SandboxedModule.require(modulePath, {
- globals: {
- console: console
- },
- requires: {
- '../Helpers/AsyncFormHelper': (this.AsyncFormHelper = {
- redirect: sinon.stub()
- }),
- '../../infrastructure/RequestContentTypeDetection': {
- acceptsJson: (this.acceptsJson = sinon.stub().returns(false))
- },
- './AuthenticationManager': (this.AuthenticationManager = {}),
- '../User/UserUpdater': (this.UserUpdater = {
- updateUser: sinon.stub()
- }),
- 'metrics-sharelatex': (this.Metrics = { inc: sinon.stub() }),
- '../Security/LoginRateLimiter': (this.LoginRateLimiter = {
- processLoginRequest: sinon.stub(),
- recordSuccessfulLogin: sinon.stub()
- }),
- '../User/UserHandler': (this.UserHandler = {
- setupLoginData: sinon.stub()
- }),
- '../Analytics/AnalyticsManager': (this.AnalyticsManager = {
- recordEvent: sinon.stub(),
- identifyUser: sinon.stub()
- }),
- '../../infrastructure/SessionStoreManager': (this.SessionStoreManager = {}),
- 'logger-sharelatex': (this.logger = {
- log: sinon.stub(),
- warn: sinon.stub(),
- error: sinon.stub(),
- err: sinon.stub()
- }),
- 'settings-sharelatex': {
- siteUrl: 'http://www.foo.bar',
- httpAuthUsers: this.httpAuthUsers
- },
- passport: (this.passport = {
- authenticate: sinon.stub().returns(sinon.stub())
- }),
- '../User/UserSessionsManager': (this.UserSessionsManager = {
- trackSession: sinon.stub(),
- untrackSession: sinon.stub(),
- revokeAllUserSessions: sinon.stub().callsArgWith(1, null)
- }),
- '../../infrastructure/Modules': (this.Modules = {
- hooks: { fire: sinon.stub().yields(null, []) }
- }),
- '../SudoMode/SudoModeHandler': (this.SudoModeHandler = {
- activateSudoMode: sinon.stub().callsArgWith(1, null)
- }),
- '../Notifications/NotificationsBuilder': (this.NotificationsBuilder = {
- ipMatcherAffiliation: sinon.stub()
- }),
- '../../models/User': { User: this.UserModel },
- '../../../../modules/oauth2-server/app/src/Oauth2Server': (this.Oauth2Server = {
- Request: sinon.stub(),
- Response: sinon.stub(),
- server: {
- authenticate: sinon.stub()
- }
- }),
- '../Helpers/UrlHelper': (this.UrlHelper = {
- getSafeRedirectPath: sinon.stub()
- })
- }
- })
- this.UrlHelper.getSafeRedirectPath
- .withArgs('https://evil.com')
- .returns(undefined)
- this.UrlHelper.getSafeRedirectPath.returnsArg(0)
- this.user = {
- _id: ObjectId(),
- email: (this.email = 'USER@example.com'),
- first_name: 'bob',
- last_name: 'brown',
- referal_id: 1234,
- isAdmin: false
- }
- this.password = 'banana'
- this.req = new MockRequest()
- this.res = new MockResponse()
- this.callback = sinon.stub()
- this.next = sinon.stub()
- })
- afterEach(function() {
- tk.reset()
- })
- describe('isUserLoggedIn', function() {
- beforeEach(function() {
- this.stub = sinon.stub(this.AuthenticationController, 'getLoggedInUserId')
- })
- afterEach(function() {
- this.stub.restore()
- })
- it('should do the right thing in all cases', function() {
- this.AuthenticationController.getLoggedInUserId.returns('some_id')
- expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
- true
- )
- this.AuthenticationController.getLoggedInUserId.returns(null)
- expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
- false
- )
- this.AuthenticationController.getLoggedInUserId.returns(false)
- expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
- false
- )
- this.AuthenticationController.getLoggedInUserId.returns(undefined)
- expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
- false
- )
- })
- })
- describe('setInSessionUser', function() {
- beforeEach(function() {
- this.user = {
- _id: 'id',
- first_name: 'a',
- last_name: 'b',
- email: 'c'
- }
- this.AuthenticationController.getSessionUser = sinon
- .stub()
- .returns(this.user)
- })
- it('should update the right properties', function() {
- this.AuthenticationController.setInSessionUser(this.req, {
- first_name: 'new_first_name',
- email: 'new_email'
- })
- const expectedUser = {
- _id: 'id',
- first_name: 'new_first_name',
- last_name: 'b',
- email: 'new_email'
- }
- expect(this.user).to.deep.equal(expectedUser)
- expect(this.user).to.deep.equal(expectedUser)
- })
- })
- describe('passportLogin', function() {
- beforeEach(function() {
- this.info = null
- this.req.login = sinon.stub().callsArgWith(1, null)
- this.res.json = sinon.stub()
- this.req.session = {
- passport: { user: this.user },
- postLoginRedirect: '/path/to/redir/to'
- }
- this.req.session.destroy = sinon.stub().callsArgWith(0, null)
- this.req.session.save = sinon.stub().callsArgWith(0, null)
- this.req.sessionStore = { generate: sinon.stub() }
- this.AuthenticationController.finishLogin = sinon.stub()
- this.passport.authenticate.callsArgWith(1, null, this.user, this.info)
- this.err = new Error('woops')
- })
- it('should call passport.authenticate', function() {
- this.AuthenticationController.passportLogin(this.req, this.res, this.next)
- this.passport.authenticate.callCount.should.equal(1)
- })
- describe('when authenticate produces an error', function() {
- beforeEach(function() {
- this.passport.authenticate.callsArgWith(1, this.err)
- })
- it('should return next with an error', function() {
- this.AuthenticationController.passportLogin(
- this.req,
- this.res,
- this.next
- )
- this.next.calledWith(this.err).should.equal(true)
- })
- })
- describe('when authenticate produces a user', function() {
- beforeEach(function() {
- this.req.session.postLoginRedirect = 'some_redirect'
- this.passport.authenticate.callsArgWith(1, null, this.user, this.info)
- })
- afterEach(function() {
- delete this.req.session.postLoginRedirect
- })
- it('should call finishLogin', function() {
- this.AuthenticationController.passportLogin(
- this.req,
- this.res,
- this.next
- )
- this.AuthenticationController.finishLogin.callCount.should.equal(1)
- this.AuthenticationController.finishLogin
- .calledWith(this.user)
- .should.equal(true)
- })
- })
- describe('when authenticate does not produce a user', function() {
- beforeEach(function() {
- this.info = { text: 'a', type: 'b' }
- this.passport.authenticate.callsArgWith(1, null, false, this.info)
- })
- it('should not call finishLogin', function() {
- this.AuthenticationController.passportLogin(
- this.req,
- this.res,
- this.next
- )
- this.AuthenticationController.finishLogin.callCount.should.equal(0)
- })
- it('should not send a json response with redirect', function() {
- this.AuthenticationController.passportLogin(
- this.req,
- this.res,
- this.next
- )
- this.res.json.callCount.should.equal(1)
- this.res.json.calledWith({ message: this.info }).should.equal(true)
- expect(this.res.json.lastCall.args[0].redir != null).to.equal(false)
- })
- })
- })
- describe('doPassportLogin', function() {
- beforeEach(function() {
- this.AuthenticationController._recordFailedLogin = sinon.stub()
- this.AuthenticationController._recordSuccessfulLogin = sinon.stub()
- this.Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [])
- // @AuthenticationController.establishUserSession = sinon.stub().callsArg(2)
- this.req.body = {
- email: this.email,
- password: this.password,
- session: {
- postLoginRedirect: '/path/to/redir/to'
- }
- }
- this.cb = sinon.stub()
- })
- describe('when the preDoPassportLogin hooks produce an info object', function() {
- beforeEach(function() {
- this.Modules.hooks.fire = sinon
- .stub()
- .callsArgWith(3, null, [null, { redir: '/somewhere' }, null])
- })
- it('should stop early and call done with this info object', function(done) {
- this.AuthenticationController.doPassportLogin(
- this.req,
- this.req.body.email,
- this.req.body.password,
- this.cb
- )
- this.cb.callCount.should.equal(1)
- this.cb
- .calledWith(null, false, { redir: '/somewhere' })
- .should.equal(true)
- this.LoginRateLimiter.processLoginRequest.callCount.should.equal(0)
- done()
- })
- })
- describe('when the users rate limit', function() {
- beforeEach(function() {
- this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
- })
- it('should block the request if the limit has been exceeded', function(done) {
- this.AuthenticationController.doPassportLogin(
- this.req,
- this.req.body.email,
- this.req.body.password,
- this.cb
- )
- this.cb.callCount.should.equal(1)
- this.cb.calledWith(null, null).should.equal(true)
- done()
- })
- })
- describe('when the user is authenticated', function() {
- beforeEach(function() {
- this.cb = sinon.stub()
- this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
- this.AuthenticationManager.authenticate = sinon
- .stub()
- .callsArgWith(2, null, this.user)
- this.req.sessionID = Math.random()
- this.AuthenticationController.doPassportLogin(
- this.req,
- this.req.body.email,
- this.req.body.password,
- this.cb
- )
- })
- it('should attempt to authorise the user', function() {
- this.AuthenticationManager.authenticate
- .calledWith({ email: this.email.toLowerCase() }, this.password)
- .should.equal(true)
- })
- it("should establish the user's session", function() {
- this.cb.calledWith(null, this.user).should.equal(true)
- })
- })
- describe('when the user is not authenticated', function() {
- beforeEach(function() {
- this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
- this.AuthenticationManager.authenticate = sinon
- .stub()
- .callsArgWith(2, null, null)
- this.cb = sinon.stub()
- this.AuthenticationController.doPassportLogin(
- this.req,
- this.req.body.email,
- this.req.body.password,
- this.cb
- )
- })
- it('should not establish the login', function() {
- this.cb.callCount.should.equal(1)
- this.cb.calledWith(null, false)
- // @res.body.should.exist
- expect(this.cb.lastCall.args[2]).to.contain.all.keys(['text', 'type'])
- })
- // message:
- // text: 'Your email or password were incorrect. Please try again',
- // type: 'error'
- it('should not setup the user data in the background', function() {
- this.UserHandler.setupLoginData.called.should.equal(false)
- })
- it('should record a failed login', function() {
- this.AuthenticationController._recordFailedLogin.called.should.equal(
- true
- )
- })
- it('should log the failed login', function() {
- this.logger.log
- .calledWith({ email: this.email.toLowerCase() }, 'failed log in')
- .should.equal(true)
- })
- })
- })
- describe('getLoggedInUserId', function() {
- beforeEach(function() {
- this.req = { session: {} }
- })
- it('should return the user id from the session', function() {
- this.user_id = '2134'
- this.req.session.user = { _id: this.user_id }
- const result = this.AuthenticationController.getLoggedInUserId(this.req)
- expect(result).to.equal(this.user_id)
- })
- it('should return user for passport session', function() {
- this.user_id = '2134'
- this.req.session = {
- passport: {
- user: {
- _id: this.user_id
- }
- }
- }
- const result = this.AuthenticationController.getLoggedInUserId(this.req)
- expect(result).to.equal(this.user_id)
- })
- it('should return null if there is no user on the session', function() {
- const result = this.AuthenticationController.getLoggedInUserId(this.req)
- expect(result).to.equal(null)
- })
- it('should return null if there is no session', function() {
- this.req = {}
- const result = this.AuthenticationController.getLoggedInUserId(this.req)
- expect(result).to.equal(null)
- })
- it('should return null if there is no req', function() {
- this.req = {}
- const result = this.AuthenticationController.getLoggedInUserId(this.req)
- expect(result).to.equal(null)
- })
- })
- describe('requireLogin', function() {
- beforeEach(function() {
- this.user = {
- _id: 'user-id-123',
- email: 'user@sharelatex.com'
- }
- this.middleware = this.AuthenticationController.requireLogin()
- })
- describe('when the user is logged in', function() {
- beforeEach(function() {
- this.req.session = {
- user: (this.user = {
- _id: 'user-id-123',
- email: 'user@sharelatex.com'
- })
- }
- this.middleware(this.req, this.res, this.next)
- })
- it('should call the next method in the chain', function() {
- this.next.called.should.equal(true)
- })
- })
- describe('when the user is not logged in', function() {
- beforeEach(function() {
- this.req.session = {}
- this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
- this.req.query = {}
- this.middleware(this.req, this.res, this.next)
- })
- it('should redirect to the register or login page', function() {
- this.AuthenticationController._redirectToLoginOrRegisterPage
- .calledWith(this.req, this.res)
- .should.equal(true)
- })
- })
- })
- describe('validateUserSession', function() {
- beforeEach(function() {
- this.user = {
- _id: 'user-id-123',
- email: 'user@sharelatex.com'
- }
- this.middleware = this.AuthenticationController.validateUserSession()
- })
- describe('when the user has a session token', function() {
- beforeEach(function() {
- this.req.user = this.user
- this.SessionStoreManager.hasValidationToken = sinon.stub().returns(true)
- this.middleware(this.req, this.res, this.next)
- })
- it('should call the next method in the chain', function() {
- this.next.called.should.equal(true)
- })
- })
- describe('when the user does not have a session token', function() {
- beforeEach(function() {
- this.req.session = {
- user: this.user,
- regenerate: sinon.stub().yields()
- }
- this.req.user = this.user
- this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
- this.req.query = {}
- this.SessionStoreManager.hasValidationToken = sinon
- .stub()
- .returns(false)
- this.middleware(this.req, this.res, this.next)
- })
- it('should destroy the current session', function() {
- this.req.session.regenerate.called.should.equal(true)
- })
- it('should redirect to the register or login page', function() {
- this.AuthenticationController._redirectToLoginOrRegisterPage
- .calledWith(this.req, this.res)
- .should.equal(true)
- })
- })
- })
- describe('requireOauth', function() {
- beforeEach(function() {
- this.res.send = sinon.stub()
- this.res.status = sinon.stub().returns(this.res)
- this.res.sendStatus = sinon.stub()
- this.middleware = this.AuthenticationController.requireOauth()
- })
- describe('when Oauth2Server authenticates', function() {
- beforeEach(function() {
- this.token = {
- accessToken: 'token',
- user: 'user'
- }
- this.Oauth2Server.server.authenticate.yields(null, this.token)
- this.middleware(this.req, this.res, this.next)
- })
- it('should set oauth_token on request', function() {
- this.req.oauth_token.should.equal(this.token)
- })
- it('should set oauth on request', function() {
- this.req.oauth.access_token.should.equal(this.token.accessToken)
- })
- it('should set oauth_user on request', function() {
- this.req.oauth_user.should.equal('user')
- })
- it('should call next', function() {
- this.next.should.have.been.calledOnce
- })
- })
- describe('when Oauth2Server returns 401 error', function() {
- beforeEach(function() {
- this.Oauth2Server.server.authenticate.yields({ code: 401 })
- this.middleware(this.req, this.res, this.next)
- })
- it('should return 401 error', function() {
- this.res.status.should.have.been.calledWith(401)
- })
- it('should not call next', function() {
- this.next.should.have.not.been.calledOnce
- })
- })
- })
- describe('requireGlobalLogin', function() {
- beforeEach(function() {
- this.req.headers = {}
- this.AuthenticationController.httpAuth = sinon.stub()
- this.setRedirect = sinon.spy(
- this.AuthenticationController,
- 'setRedirectInSession'
- )
- })
- afterEach(function() {
- this.setRedirect.restore()
- })
- describe('with white listed url', function() {
- beforeEach(function() {
- this.AuthenticationController.addEndpointToLoginWhitelist('/login')
- this.req._parsedUrl.pathname = '/login'
- this.AuthenticationController.requireGlobalLogin(
- this.req,
- this.res,
- this.next
- )
- })
- it('should call next() directly', function() {
- this.next.called.should.equal(true)
- })
- })
- describe('with white listed url and a query string', function() {
- beforeEach(function() {
- this.AuthenticationController.addEndpointToLoginWhitelist('/login')
- this.req._parsedUrl.pathname = '/login'
- this.req.url = '/login?query=something'
- this.AuthenticationController.requireGlobalLogin(
- this.req,
- this.res,
- this.next
- )
- })
- it('should call next() directly', function() {
- this.next.called.should.equal(true)
- })
- })
- describe('with http auth', function() {
- beforeEach(function() {
- this.req.headers['authorization'] = 'Mock Basic Auth'
- this.AuthenticationController.requireGlobalLogin(
- this.req,
- this.res,
- this.next
- )
- })
- it('should pass the request onto httpAuth', function() {
- this.AuthenticationController.httpAuth
- .calledWith(this.req, this.res, this.next)
- .should.equal(true)
- })
- })
- describe('with a user session', function() {
- beforeEach(function() {
- this.req.session = { user: { mock: 'user', _id: 'some_id' } }
- this.AuthenticationController.requireGlobalLogin(
- this.req,
- this.res,
- this.next
- )
- })
- it('should call next() directly', function() {
- this.next.called.should.equal(true)
- })
- })
- describe('with no login credentials', function() {
- beforeEach(function() {
- this.req.session = {}
- this.AuthenticationController.requireGlobalLogin(
- this.req,
- this.res,
- this.next
- )
- })
- it('should have called setRedirectInSession', function() {
- this.setRedirect.callCount.should.equal(1)
- })
- it('should redirect to the /login page', function() {
- this.res.redirectedTo.should.equal('/login')
- })
- })
- })
- describe('httpAuth', function() {
- describe('with http auth', function() {
- it('should error with incorrect user', function(done) {
- this.req.headers = {
- authorization: `Basic ${Buffer.from('user:nope').toString('base64')}`
- }
- this.req.end = status => {
- expect(status).to.equal('Unauthorized')
- done()
- }
- this.AuthenticationController.httpAuth(this.req, this.req)
- })
- it('should error with incorrect password', function(done) {
- this.req.headers = {
- authorization: `Basic ${Buffer.from('valid-test-user:nope').toString(
- 'base64'
- )}`
- }
- this.req.end = status => {
- expect(status).to.equal('Unauthorized')
- done()
- }
- this.AuthenticationController.httpAuth(this.req, this.req)
- })
- it('should fail with empty pass', function(done) {
- this.req.headers = {
- authorization: `Basic ${Buffer.from(`invalid-test-user:`).toString(
- 'base64'
- )}`
- }
- this.req.end = status => {
- expect(status).to.equal('Unauthorized')
- done()
- }
- this.AuthenticationController.httpAuth(this.req, this.req)
- })
- it('should succeed with correct user/pass', function(done) {
- this.req.headers = {
- authorization: `Basic ${Buffer.from(
- `valid-test-user:${this.httpAuthUsers['valid-test-user']}`
- ).toString('base64')}`
- }
- this.AuthenticationController.httpAuth(this.req, this.res, done)
- })
- })
- })
- describe('_redirectToLoginOrRegisterPage', function() {
- beforeEach(function() {
- this.middleware = this.AuthenticationController.requireLogin(
- (this.options = { load_from_db: false })
- )
- this.req.session = {}
- this.AuthenticationController._redirectToRegisterPage = sinon.stub()
- this.AuthenticationController._redirectToLoginPage = sinon.stub()
- this.req.query = {}
- })
- describe('they have come directly to the url', function() {
- beforeEach(function() {
- this.req.query = {}
- this.middleware(this.req, this.res, this.next)
- })
- it('should redirect to the login page', function() {
- this.AuthenticationController._redirectToRegisterPage
- .calledWith(this.req, this.res)
- .should.equal(false)
- this.AuthenticationController._redirectToLoginPage
- .calledWith(this.req, this.res)
- .should.equal(true)
- })
- })
- describe('they have come via a templates link', function() {
- beforeEach(function() {
- this.req.query.zipUrl = 'something'
- this.middleware(this.req, this.res, this.next)
- })
- it('should redirect to the register page', function() {
- this.AuthenticationController._redirectToRegisterPage
- .calledWith(this.req, this.res)
- .should.equal(true)
- this.AuthenticationController._redirectToLoginPage
- .calledWith(this.req, this.res)
- .should.equal(false)
- })
- })
- describe('they have been invited to a project', function() {
- beforeEach(function() {
- this.req.query.project_name = 'something'
- this.middleware(this.req, this.res, this.next)
- })
- it('should redirect to the register page', function() {
- this.AuthenticationController._redirectToRegisterPage
- .calledWith(this.req, this.res)
- .should.equal(true)
- this.AuthenticationController._redirectToLoginPage
- .calledWith(this.req, this.res)
- .should.equal(false)
- })
- })
- })
- describe('_redirectToRegisterPage', function() {
- beforeEach(function() {
- this.req.path = '/target/url'
- this.req.query = { extra_query: 'foo' }
- this.AuthenticationController._redirectToRegisterPage(this.req, this.res)
- })
- it('should redirect to the register page with a query string attached', function() {
- this.req.session.postLoginRedirect.should.equal(
- '/target/url?extra_query=foo'
- )
- this.res.redirectedTo.should.equal('/register?extra_query=foo')
- })
- it('should log out a message', function() {
- this.logger.log
- .calledWith(
- { url: this.url },
- 'user not logged in so redirecting to register page'
- )
- .should.equal(true)
- })
- })
- describe('_redirectToLoginPage', function() {
- beforeEach(function() {
- this.req.path = '/target/url'
- this.req.query = { extra_query: 'foo' }
- this.AuthenticationController._redirectToLoginPage(this.req, this.res)
- })
- it('should redirect to the register page with a query string attached', function() {
- this.req.session.postLoginRedirect.should.equal(
- '/target/url?extra_query=foo'
- )
- this.res.redirectedTo.should.equal('/login?extra_query=foo')
- })
- })
- describe('_recordSuccessfulLogin', function() {
- beforeEach(function() {
- this.UserUpdater.updateUser = sinon.stub().callsArg(2)
- this.AuthenticationController._recordSuccessfulLogin(
- this.user._id,
- this.callback
- )
- })
- it('should increment the user.login.success metric', function() {
- this.Metrics.inc.calledWith('user.login.success').should.equal(true)
- })
- it("should update the user's login count and last logged in date", function() {
- this.UserUpdater.updateUser.args[0][1]['$set'][
- 'lastLoggedIn'
- ].should.not.equal(undefined)
- this.UserUpdater.updateUser.args[0][1]['$inc']['loginCount'].should.equal(
- 1
- )
- })
- it('should call the callback', function() {
- this.callback.called.should.equal(true)
- })
- })
- describe('_recordFailedLogin', function() {
- beforeEach(function() {
- this.AuthenticationController._recordFailedLogin(this.callback)
- })
- it('should increment the user.login.failed metric', function() {
- this.Metrics.inc.calledWith('user.login.failed').should.equal(true)
- })
- it('should call the callback', function() {
- this.callback.called.should.equal(true)
- })
- })
- describe('setRedirectInSession', function() {
- beforeEach(function() {
- this.req = { session: {} }
- this.req.path = '/somewhere'
- this.req.query = { one: '1' }
- })
- it('should set redirect property on session', function() {
- this.AuthenticationController.setRedirectInSession(this.req)
- expect(this.req.session.postLoginRedirect).to.equal('/somewhere?one=1')
- })
- it('should set the supplied value', function() {
- this.AuthenticationController.setRedirectInSession(
- this.req,
- '/somewhere/specific'
- )
- expect(this.req.session.postLoginRedirect).to.equal('/somewhere/specific')
- })
- it('should not allow open redirects', function() {
- this.AuthenticationController.setRedirectInSession(
- this.req,
- 'https://evil.com'
- )
- expect(this.req.session.postLoginRedirect).to.be.undefined
- })
- describe('with a png', function() {
- beforeEach(function() {
- this.req = { session: {} }
- })
- it('should not set the redirect', function() {
- this.AuthenticationController.setRedirectInSession(
- this.req,
- '/something.png'
- )
- expect(this.req.session.postLoginRedirect).to.equal(undefined)
- })
- })
- describe('with a js path', function() {
- beforeEach(function() {
- this.req = { session: {} }
- })
- it('should not set the redirect', function() {
- this.AuthenticationController.setRedirectInSession(
- this.req,
- '/js/something.js'
- )
- expect(this.req.session.postLoginRedirect).to.equal(undefined)
- })
- })
- })
- describe('_getRedirectFromSession', function() {
- it('should get redirect property from session', function() {
- this.req = { session: { postLoginRedirect: '/a?b=c' } }
- expect(
- this.AuthenticationController._getRedirectFromSession(this.req)
- ).to.equal('/a?b=c')
- })
- it('should not allow open redirects', function() {
- this.req = { session: { postLoginRedirect: 'https://evil.com' } }
- expect(this.AuthenticationController._getRedirectFromSession(this.req)).to
- .be.null
- })
- it('handle null values', function() {
- this.req = { session: {} }
- expect(this.AuthenticationController._getRedirectFromSession(this.req)).to
- .be.null
- })
- })
- describe('_clearRedirectFromSession', function() {
- beforeEach(function() {
- this.req = { session: { postLoginRedirect: '/a?b=c' } }
- })
- it('should remove the redirect property from session', function() {
- this.AuthenticationController._clearRedirectFromSession(this.req)
- expect(this.req.session.postLoginRedirect).to.equal(undefined)
- })
- })
- describe('finishLogin', function() {
- // - get redirect
- // - async handlers
- // - afterLoginSessionSetup
- // - clear redirect
- // - issue redir, two ways
- beforeEach(function() {
- this.AuthenticationController._getRedirectFromSession = sinon
- .stub()
- .returns('/some/page')
- this.req.sessionID = 'thisisacryptographicallysecurerandomid'
- this.req.session = {
- passport: { user: { _id: 'one' } }
- }
- this.req.session.destroy = sinon.stub().callsArgWith(0, null)
- this.req.session.save = sinon.stub().callsArgWith(0, null)
- this.req.sessionStore = { generate: sinon.stub() }
- this.req.login = sinon.stub().yields(null)
- this.AuthenticationController._clearRedirectFromSession = sinon.stub()
- this.AuthenticationController._redirectToReconfirmPage = sinon.stub()
- this.UserSessionsManager.trackSession = sinon.stub()
- this.UserHandler.setupLoginData = sinon.stub()
- this.LoginRateLimiter.recordSuccessfulLogin = sinon.stub()
- this.AuthenticationController._recordSuccessfulLogin = sinon.stub()
- this.AnalyticsManager.recordEvent = sinon.stub()
- this.AnalyticsManager.identifyUser = sinon.stub()
- this.acceptsJson.returns(true)
- this.res.json = sinon.stub()
- this.res.redirect = sinon.stub()
- })
- it('should extract the redirect from the session', function() {
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- this.next
- )
- expect(
- this.AuthenticationController._getRedirectFromSession.callCount
- ).to.equal(1)
- expect(
- this.AuthenticationController._getRedirectFromSession.calledWith(
- this.req
- )
- ).to.equal(true)
- })
- it('should clear redirect from session', function() {
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- this.next
- )
- expect(
- this.AuthenticationController._clearRedirectFromSession.callCount
- ).to.equal(1)
- expect(
- this.AuthenticationController._clearRedirectFromSession.calledWith(
- this.req
- )
- ).to.equal(true)
- })
- it('should issue a json response with a redirect', function() {
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- this.next
- )
- expect(
- this.AsyncFormHelper.redirect.calledWith(
- this.req,
- this.res,
- '/some/page'
- )
- ).to.equal(true)
- })
- describe('with a non-json request', function() {
- beforeEach(function() {
- this.acceptsJson.returns(false)
- this.res.json = sinon.stub()
- this.res.redirect = sinon.stub()
- })
- it('should issue a plain redirect', function() {
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- this.next
- )
- expect(
- this.AsyncFormHelper.redirect.calledWith(
- this.req,
- this.res,
- '/some/page'
- )
- ).to.equal(true)
- })
- })
- describe('when user is flagged to reconfirm', function() {
- beforeEach(function() {
- this.req.session = {}
- this.user.must_reconfirm = true
- })
- it('should redirect to reconfirm page', function() {
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- this.next
- )
- expect(
- this.AuthenticationController._redirectToReconfirmPage.calledWith(
- this.req
- )
- ).to.equal(true)
- })
- })
- describe('preFinishLogin hook', function() {
- it('call hook and proceed', function() {
- this.Modules.hooks.fire = sinon.stub().yields(null, [])
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- this.next
- )
- sinon.assert.calledWith(
- this.Modules.hooks.fire,
- 'preFinishLogin',
- this.req,
- this.res,
- this.user
- )
- expect(this.AsyncFormHelper.redirect.called).to.equal(true)
- })
- it('stop if hook has redirected', function(done) {
- this.Modules.hooks.fire = sinon
- .stub()
- .yields(null, [{ doNotFinish: true }])
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- this.next
- )
- expect(this.next.callCount).to.equal(0)
- expect(this.res.json.callCount).to.equal(0)
- done()
- })
- it('call next with hook errors', function(done) {
- this.Modules.hooks.fire = sinon.stub().yields(new Error())
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- error => {
- expect(error).to.exist
- expect(this.res.json.callCount).to.equal(0)
- done()
- }
- )
- })
- })
- describe('_afterLoginSessionSetup', function() {
- beforeEach(function() {})
- it('should call req.login', function() {
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- this.next
- )
- this.req.login.callCount.should.equal(1)
- })
- it('should call req.session.save', function() {
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- this.next
- )
- this.req.session.save.callCount.should.equal(1)
- })
- it('should call UserSessionsManager.trackSession', function() {
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- this.next
- )
- this.UserSessionsManager.trackSession.callCount.should.equal(1)
- })
- describe('when req.session.save produces an error', function() {
- beforeEach(function() {
- this.req.session.save = sinon
- .stub()
- .callsArgWith(0, new Error('woops'))
- })
- it('should produce an error', function(done) {
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- err => {
- expect(err).to.not.be.oneOf([null, undefined])
- expect(err).to.be.instanceof(Error)
- done()
- }
- )
- })
- it('should not call UserSessionsManager.trackSession', function(done) {
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- err => {
- expect(err).to.exist
- this.UserSessionsManager.trackSession.callCount.should.equal(0)
- done()
- }
- )
- })
- })
- })
- describe('_loginAsyncHandlers', function() {
- beforeEach(function() {
- this.AuthenticationController.finishLogin(
- this.user,
- this.req,
- this.res,
- this.next
- )
- })
- it('should call identifyUser', function() {
- this.AnalyticsManager.identifyUser
- .calledWith(this.user._id, this.req.sessionID)
- .should.equal(true)
- })
- it('should setup the user data in the background', function() {
- this.UserHandler.setupLoginData.calledWith(this.user).should.equal(true)
- })
- it('should set res.session.justLoggedIn', function() {
- this.req.session.justLoggedIn.should.equal(true)
- })
- it('should record the successful login', function() {
- this.AuthenticationController._recordSuccessfulLogin
- .calledWith(this.user._id)
- .should.equal(true)
- })
- it('should tell the rate limiter that there was a success for that email', function() {
- this.LoginRateLimiter.recordSuccessfulLogin
- .calledWith(this.user.email)
- .should.equal(true)
- })
- it('should log the successful login', function() {
- this.logger.log
- .calledWith(
- { email: this.user.email, user_id: this.user._id.toString() },
- 'successful log in'
- )
- .should.equal(true)
- })
- it('should track the login event', function() {
- this.AnalyticsManager.recordEvent
- .calledWith(this.user._id, 'user-logged-in')
- .should.equal(true)
- })
- })
- })
- })
|