From 1eff39bb167515837406c7c757659aac620dac5c Mon Sep 17 00:00:00 2001 From: VLE2FE Date: Mon, 27 Apr 2020 14:26:51 +0200 Subject: [PATCH] added /user/key and edited /user regex --- oas/user.yaml | 5 ++++- src/routes/user.spec.ts | 20 ++++++++++++++++++++ src/routes/user.ts | 15 +++++++++++++-- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/oas/user.yaml b/oas/user.yaml index 6c2c3fc..c8c282d 100644 --- a/oas/user.yaml +++ b/oas/user.yaml @@ -191,7 +191,10 @@ content: application/json: schema: - $ref: 'oas.yaml#/components/schemas/User' + properties: + key: + type: string + example: 5ea0450ed851c30a90e70899 401: $ref: 'oas.yaml#/components/responses/401' 500: diff --git a/src/routes/user.spec.ts b/src/routes/user.spec.ts index 8098d9c..60f5b4d 100644 --- a/src/routes/user.spec.ts +++ b/src/routes/user.spec.ts @@ -472,4 +472,24 @@ describe('/user', () => { }); }); }); + + describe('GET /user/key', () => { + it('returns the right API key', done => { + TestHelper.request(server, done, { + method: 'get', + url: '/user/key', + auth: {basic: 'janedoe'}, + httpStatus: 200, + res: {key: TestHelper.auth.janedoe.key} + }); + }); + it('rejects requests from an API key', done => { + TestHelper.request(server, done, { + method: 'get', + url: '/user/key', + auth: {key: 'janedoe'}, + httpStatus: 401 + }); + }); + }) }); \ No newline at end of file diff --git a/src/routes/user.ts b/src/routes/user.ts index d362c79..26f21cc 100644 --- a/src/routes/user.ts +++ b/src/routes/user.ts @@ -15,7 +15,8 @@ router.get('/users', (req, res) => { }); }); -router.get('/user/:username*?', (req, res, next) => { +router.get('/user:username([/](?!key|new).?*|/?)', (req, res, next) => { // this path matches /user, /user/ and /user/xxx, but not /user/key or user/new. See https://forbeslindesay.github.io/express-route-tester/ for the generated regex + req.params.username = req.params[0]; if (!req.auth(res, ['read', 'write', 'maintain', 'dev', 'admin'], 'basic')) return; let username = req.authDetails.username; if (req.params.username !== undefined) { @@ -34,7 +35,7 @@ router.get('/user/:username*?', (req, res, next) => { }); }); -router.put('/user/:username*?', (req, res, next) => { +router.put('/user:username([/](?!key|new).?*|/?)', (req, res, next) => { // this path matches /user, /user/ and /user/xxx, but not /user/key or user/new console.log(req.authDetails); if (!req.auth(res, ['read', 'write', 'maintain', 'dev', 'admin'], 'basic')) return; let username = req.authDetails.username; @@ -87,6 +88,16 @@ router.put('/user/:username*?', (req, res, next) => { } }); +router.get('/user/key', (req, res, next) => { + console.log('hmm'); + if (!req.auth(res, ['read', 'write', 'maintain', 'dev', 'admin'], 'basic')) return; + + UserModel.findOne({name: req.authDetails.username}).lean().exec( (err, data:any) => { + if (err) next(err); + res.json({key: data.key}); + }); +}); + router.post('/user/new', (req, res, next) => { if (!req.auth(res, ['admin'], 'basic')) return;