diff options
author | 2024-08-20 14:29:50 +0200 | |
---|---|---|
committer | 2024-08-20 14:29:50 +0200 | |
commit | 787fed8504e7ec604d96ff266f58db715e84f736 (patch) | |
tree | ef29a659ddf6511e2564ee4d442f992cc9695241 /examples/middleware/src/middleware.ts | |
parent | 6617491c3bc2bde87f7867d7dec2580781852cfc (diff) | |
parent | c6622adaeb405e961b12c91f0e5d02c7333d01cf (diff) | |
download | astro-787fed8504e7ec604d96ff266f58db715e84f736.tar.gz astro-787fed8504e7ec604d96ff266f58db715e84f736.tar.zst astro-787fed8504e7ec604d96ff266f58db715e84f736.zip |
Merge branch 'main' into next
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(); }); |