refactor(jwt): refactor code and add more tests (#611)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent 33f1cbd · Browse files · 3 files·+66 added−46 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+66 added−46 removed
- tests:+60 added−34 removed
- other:+6 added−12 removed
Provenance
- Commit
944dfc2- Tree
0d9f96b- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
33f1cbd
3 files changed+66 added−46 removed
modified:deno_dist/middleware/jwt/index.ts+3 added-6 removed
19 unmodified lines20212223242425262728293030313233343536373938394041424345444546472 unmodified lines50515253565455565758596063616263646519 unmodified lines let token if (credentials) { const parts = credentials.split(/\s+/) if (parts.length !== 2) { ctx.res = new Response('Unauthorized', { return new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="invalid credentials structure"`, }, }) return } else { token = parts[1] } } else if (options.cookie) { token = ctx.req.cookie(options.cookie) }
if (!token) { ctx.res = new Response('Unauthorized', { return new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="no authorization included in request"`, }, }) return }
let authorized = false let msg = ''2 unmodified lines } catch (e) { msg = `${e}` } if (!authorized) { ctx.res = new Response('Unauthorized', { return new Response('Unauthorized', { status: 401, statusText: msg, headers: { 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_token",error_description="token verification failure"`, }, }) return }
await next() }}modified:src/middleware/jwt/index.test.ts+60 added-34 removed
1 import { Hono } from '../../hono'2 import { jwt } from '.'3 4-4 describe('JWT', () => {5 describe('Credentials in header', () => {6 const crypto = global.crypto7+ let handlerExecuted: boolean8 beforeAll(() => {9 global.crypto = require('crypto').webcrypto10 })11 afterAll(() => {12 global.crypto = crypto13 })14+ beforeEach(() => {15+ handlerExecuted = false16+ })17 18 const app = new Hono()19 17- app.use('/*', async (c, next) => {18- await next()19- c.header('x-foo', c.get('x-foo') || '')20- })21-20 app.use('/auth/*', jwt({ secret: 'a-secret' }))21 app.use('/auth-unicode/*', jwt({ secret: 'a-secret' }))22+ app.use('/nested/*', async (c, next) => {23+ const auth = jwt({ secret: 'a-secret' })24+ return auth(c, next)25+ })26 27 app.get('/auth/*', (c) => {26- c.set('x-foo', 'bar')27- return new Response('auth')28+ handlerExecuted = true29+ return c.text('auth')30 })31 app.get('/auth-unicode/*', (c) => {30- c.set('x-foo', 'bar')31- return new Response('auth')32+ handlerExecuted = true33+ return c.text('auth')34 })35+ app.get('/nested/*', (c) => {36+ handlerExecuted = true37+ return c.text('auth')38+ })39 40 it('Should not authorize', async () => {41 const req = new Request('http://localhost/auth/a')42 const res = await app.request(req)43 expect(res).not.toBeNull()44 expect(res.status).toBe(401)45 expect(await res.text()).toBe('Unauthorized')40- expect(res.headers.get('x-foo')).toBeFalsy()46+ expect(handlerExecuted).toBeFalsy()47 })48 49 it('Should authorize', async () => {50 const credential =3 unmodified lines54 const res = await app.request(req)55 expect(res).not.toBeNull()56 expect(res.status).toBe(200)57 expect(await res.text()).toBe('auth')52- expect(res.headers.get('x-foo')).toBe('bar')58+ expect(handlerExecuted).toBeTruthy()59 })60 61 it('Should authorize Unicode', async () => {62 const credential =4 unmodified lines67 const res = await app.request(req)68 expect(res).not.toBeNull()69 expect(res.status).toBe(200)70 expect(await res.text()).toBe('auth')65- expect(res.headers.get('x-foo')).toBe('bar')71+ expect(handlerExecuted).toBeTruthy()72 })73 74 it('Should not authorize Unicode', async () => {75 const invalidToken =7 unmodified lines83 expect(res.status).toBe(401)84 expect(res.headers.get('www-authenticate')).toEqual(85 `Bearer realm="${url}",error="invalid_token",error_description="token verification failure"`86 )81- expect(res.headers.get('x-foo')).toBeFalsy()87+ expect(handlerExecuted).toBeFalsy()88 })89 90 it('Should not authorize', async () => {91 const invalid_token = 'invalid token'5 unmodified lines97 expect(res.status).toBe(401)98 expect(res.headers.get('www-authenticate')).toEqual(99 `Bearer realm="${url}",error="invalid_request",error_description="invalid credentials structure"`100 )95- expect(res.headers.get('x-foo')).toBeFalsy()101+ expect(handlerExecuted).toBeFalsy()102 })103+104+ it('Should not authorize - nested', async () => {105+ const req = new Request('http://localhost/nested/a')106+ const res = await app.request(req)107+ expect(res).not.toBeNull()108+ expect(res.status).toBe(401)109+ expect(await res.text()).toBe('Unauthorized')110+ expect(handlerExecuted).toBeFalsy()111+ })112+113+ it('Should authorize - nested', async () => {114+ const credential =115+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'116+ const req = new Request('http://localhost/nested/a')117+ req.headers.set('Authorization', `Bearer ${credential}`)118+ const res = await app.request(req)119+ expect(res).not.toBeNull()120+ expect(res.status).toBe(200)121+ expect(await res.text()).toBe('auth')122+ expect(handlerExecuted).toBeTruthy()123+ })124 })125 126 describe('Credentials in cookie', () => {127 const crypto = global.crypto128+ let handlerExecuted: boolean129 beforeAll(() => {130 global.crypto = require('crypto').webcrypto131 })132 afterAll(() => {133 global.crypto = crypto134 })135+ beforeEach(() => {136+ handlerExecuted = false137+ })138 139 const app = new Hono()140 110- app.use('/*', async (c, next) => {111- await next()112- c.header('x-foo', c.get('x-foo') || '')113- })114-141 app.use('/auth/*', jwt({ secret: 'a-secret', cookie: 'access_token' }))142 app.use('/auth-unicode/*', jwt({ secret: 'a-secret', cookie: 'access_token' }))143 144 app.get('/auth/*', (c) => {119- c.set('x-foo', 'bar')120- return new Response('auth')145+ handlerExecuted = true146+ return c.text('auth')147 })148 app.get('/auth-unicode/*', (c) => {123- c.set('x-foo', 'bar')124- return new Response('auth')149+ handlerExecuted = true150+ return c.text('auth')151 })152 153 it('Should not authorize', async () => {154 const req = new Request('http://localhost/auth/a')155 const res = await app.request(req)156 expect(res).not.toBeNull()157 expect(res.status).toBe(401)158 expect(await res.text()).toBe('Unauthorized')133- expect(res.headers.get('x-foo')).toBeFalsy()159+ expect(handlerExecuted).toBeFalsy()160 })161 162 it('Should authorize', async () => {163 const url = 'http://localhost/auth/a'164 const credential =165 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'166 const req = new Request(url, {167 headers: new Headers({142- 'Cookie': `access_token=${credential}`,143- })168+ Cookie: `access_token=${credential}`,169+ }),170 })171 const res = await app.request(req)172 expect(res).not.toBeNull()173 expect(await res.text()).toBe('auth')174 expect(res.status).toBe(200)149- expect(res.headers.get('x-foo')).toBe('bar')175+ expect(handlerExecuted).toBeTruthy()176 })177 178 it('Should authorize Unicode', async () => {179 const credential =180 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'181 182 const req = new Request('http://localhost/auth-unicode/a', {183 headers: new Headers({158- 'Cookie': `access_token=${credential}`,159- })184+ Cookie: `access_token=${credential}`,185+ }),186 })187 const res = await app.request(req)188 expect(res).not.toBeNull()189 expect(res.status).toBe(200)190 expect(await res.text()).toBe('auth')165- expect(res.headers.get('x-foo')).toBe('bar')191+ expect(handlerExecuted).toBeTruthy()192 })193 194 it('Should not authorize Unicode', async () => {195 const invalidToken =7 unmodified lines203 expect(res.status).toBe(401)204 expect(res.headers.get('www-authenticate')).toEqual(205 `Bearer realm="${url}",error="invalid_token",error_description="token verification failure"`206 )181- expect(res.headers.get('x-foo')).toBeFalsy()207+ expect(handlerExecuted).toBeFalsy()208 })209 210 it('Should not authorize', async () => {211 const invalidToken = 'invalid token'5 unmodified lines217 expect(res.status).toBe(401)218 expect(res.headers.get('www-authenticate')).toEqual(219 `Bearer realm="${url}",error="invalid_token",error_description="token verification failure"`220 )195- expect(res.headers.get('x-foo')).toBeFalsy()221+ expect(handlerExecuted).toBeFalsy()222 })223 })198-})224+})modified:src/middleware/jwt/index.ts+3 added-6 removed
19 unmodified lines20212223242425262728293030313233343536373938394041424345444546472 unmodified lines50515253565455565758596063616263646519 unmodified lines let token if (credentials) { const parts = credentials.split(/\s+/) if (parts.length !== 2) { ctx.res = new Response('Unauthorized', { return new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="invalid credentials structure"`, }, }) return } else { token = parts[1] } } else if (options.cookie) { token = ctx.req.cookie(options.cookie) }
if (!token) { ctx.res = new Response('Unauthorized', { return new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="no authorization included in request"`, }, }) return }
let authorized = false let msg = ''2 unmodified lines } catch (e) { msg = `${e}` } if (!authorized) { ctx.res = new Response('Unauthorized', { return new Response('Unauthorized', { status: 401, statusText: msg, headers: { 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_token",error_description="token verification failure"`, }, }) return }
await next() }}