|
| 1 | +const chai = require('chai'); |
| 2 | +const chaiHttp = require('chai-http'); |
| 3 | +const sinon = require('sinon'); |
| 4 | +const express = require('express'); |
| 5 | +const authRouter = require('../../../src/service/routes/auth'); |
| 6 | +const db = require('../../../src/db'); |
| 7 | + |
| 8 | +const { expect } = chai; |
| 9 | +chai.use(chaiHttp); |
| 10 | + |
| 11 | +const newApp = (username) => { |
| 12 | + const app = express(); |
| 13 | + app.use(express.json()); |
| 14 | + |
| 15 | + if (username) { |
| 16 | + app.use((req, res, next) => { |
| 17 | + req.user = { username }; |
| 18 | + next(); |
| 19 | + }); |
| 20 | + } |
| 21 | + |
| 22 | + app.use('/auth', authRouter); |
| 23 | + return app; |
| 24 | +}; |
| 25 | + |
| 26 | +describe('Auth API', function () { |
| 27 | + afterEach(function () { |
| 28 | + sinon.restore(); |
| 29 | + }); |
| 30 | + |
| 31 | + describe('/me', function () { |
| 32 | + it('GET /me returns Unauthorized if authenticated user not in request', async () => { |
| 33 | + const res = await chai.request(newApp()).get('/auth/me'); |
| 34 | + |
| 35 | + expect(res).to.have.status(401); |
| 36 | + }); |
| 37 | + |
| 38 | + it('GET /me serializes public data representation of current authenticated user', async function () { |
| 39 | + sinon.stub(db, 'findUser').resolves({ |
| 40 | + username: 'alice', |
| 41 | + password: 'secret-hashed-password', |
| 42 | + |
| 43 | + displayName: 'Alice Walker', |
| 44 | + otherUserData: 'should not be returned', |
| 45 | + }); |
| 46 | + |
| 47 | + const res = await chai.request(newApp('alice')).get('/auth/me'); |
| 48 | + expect(res).to.have.status(200); |
| 49 | + expect(res.body).to.deep.equal({ |
| 50 | + username: 'alice', |
| 51 | + displayName: 'Alice Walker', |
| 52 | + |
| 53 | + title: '', |
| 54 | + gitAccount: '', |
| 55 | + admin: false, |
| 56 | + }); |
| 57 | + }); |
| 58 | + }); |
| 59 | + |
| 60 | + describe('/profile', function () { |
| 61 | + it('GET /profile returns Unauthorized if authenticated user not in request', async () => { |
| 62 | + const res = await chai.request(newApp()).get('/auth/profile'); |
| 63 | + |
| 64 | + expect(res).to.have.status(401); |
| 65 | + }); |
| 66 | + |
| 67 | + it('GET /profile serializes public data representation of current authenticated user', async function () { |
| 68 | + sinon.stub(db, 'findUser').resolves({ |
| 69 | + username: 'alice', |
| 70 | + password: 'secret-hashed-password', |
| 71 | + |
| 72 | + displayName: 'Alice Walker', |
| 73 | + otherUserData: 'should not be returned', |
| 74 | + }); |
| 75 | + |
| 76 | + const res = await chai.request(newApp('alice')).get('/auth/profile'); |
| 77 | + expect(res).to.have.status(200); |
| 78 | + expect(res.body).to.deep.equal({ |
| 79 | + username: 'alice', |
| 80 | + displayName: 'Alice Walker', |
| 81 | + |
| 82 | + title: '', |
| 83 | + gitAccount: '', |
| 84 | + admin: false, |
| 85 | + }); |
| 86 | + }); |
| 87 | + }); |
| 88 | +}); |
0 commit comments