diff options
Diffstat (limited to 'examples/middleware/src/middleware.ts')
-rw-r--r-- | examples/middleware/src/middleware.ts | 31 |
1 files changed, 21 insertions, 10 deletions
diff --git a/examples/middleware/src/middleware.ts b/examples/middleware/src/middleware.ts index f92b64d44..4854105ca 100644 --- a/examples/middleware/src/middleware.ts +++ b/examples/middleware/src/middleware.ts @@ -56,16 +56,27 @@ const validation = defineMiddleware(async (context, next) => { } else if (context.request.url.endsWith('/api/login')) { const response = await next(); // the login endpoint will return to us a JSON with username and password - const data = await response.json(); - // we naively check if username and password are equals to some string - if (data.username === 'astro' && data.password === 'astro') { - // we store the token somewhere outside of locals because the `locals` object is attached to the request - // and when doing a redirect, we lose that information - loginInfo.token = 'loggedIn'; - loginInfo.currentTime = new Date().getTime(); - return context.redirect('/admin'); - } - } + if (response.headers.get('content-type') === 'application/json') { + const data = await response.json(); + // we naively check if username and password are equals to some string + if (data.username === 'astro' && data.password === 'astro') { + // we store the token somewhere outside of locals because the `locals` object is attached to the request + // and when doing a redirect, we lose that information + loginInfo.token = 'loggedIn'; + loginInfo.currentTime = new Date().getTime(); + return context.redirect('/admin'); + } + } + return response; + } else if (context.request.url.endsWith('/api/logout')) { + const response = await next(); + if (response.ok) { + loginInfo.token = undefined; + loginInfo.currentTime = undefined; + return context.redirect('/login'); + } + return response; + } return next(); }); |