|
| 1 | +import assert from 'node:assert/strict' |
| 2 | +import test from 'node:test' |
| 3 | + |
| 4 | +process.env.LOGIN_CREDENTIALS = 'admin:secret' |
| 5 | +const { default: authMiddleware } = await import('../../lib/auth-middleware.js') |
| 6 | + |
| 7 | +function request (authorization) { |
| 8 | + return { headers: { authorization } } |
| 9 | +} |
| 10 | + |
| 11 | +function response () { |
| 12 | + return { |
| 13 | + headers: {}, |
| 14 | + setHeader (name, value) { |
| 15 | + this.headers[name] = value |
| 16 | + }, |
| 17 | + end (body) { |
| 18 | + this.body = body |
| 19 | + } |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +test('accepts the configured credentials', () => { |
| 24 | + const req = request('Basic ' + Buffer.from('admin:secret').toString('base64')) |
| 25 | + const res = response() |
| 26 | + let nextCalled = false |
| 27 | + |
| 28 | + authMiddleware(req, res, () => { nextCalled = true }) |
| 29 | + |
| 30 | + assert.equal(nextCalled, true) |
| 31 | + assert.equal(res.statusCode, undefined) |
| 32 | +}) |
| 33 | + |
| 34 | +test('rejects missing or incorrect credentials', () => { |
| 35 | + for (const authorization of [undefined, 'Basic invalid', 'Bearer token']) { |
| 36 | + const res = response() |
| 37 | + let nextCalled = false |
| 38 | + |
| 39 | + authMiddleware(request(authorization), res, () => { nextCalled = true }) |
| 40 | + |
| 41 | + assert.equal(nextCalled, false) |
| 42 | + assert.equal(res.statusCode, 401) |
| 43 | + assert.equal(res.headers['WWW-Authenticate'], 'Basic realm="nodejs-github-bot"') |
| 44 | + assert.equal(res.body, 'Unauthorized') |
| 45 | + } |
| 46 | +}) |
0 commit comments