N
Nuxt4mo ago
stefanpeev

Need to set cookies in headers and figure out how to use useState

</script> import { createError, eventHandler, readBody } from 'h3'; import { z } from 'zod'; import { sign } from 'jsonwebtoken'; const refreshTokens: Record<number, Record<string, any>> = {}; export const SECRET = ''; export default eventHandler(async (event) => { const body = await readBody(event);
const result = z.object({ username: z.string().min(1), password: z.string().min(1) }).safeParse(body) if (!result.success) { throw createError({ statusCode: 400, statusMessage: 'Bad Request' }) }
const { username, password } = result.data;
try { const loginResponse = await fetch('http://localhost:8000/api/login/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) });
if (!loginResponse.ok) { throw createError({ statusCode: loginResponse.status, statusMessage: loginResponse.statusText }); }
const { access, refresh, user, user_type } = await loginResponse.json();
const expiresIn = 30; const accessToken = sign({ ...user, scope: ['test', 'user'] }, SECRET, { expiresIn });
refreshTokens[refresh] = { accessToken: accessToken, user: user };
console.log('Access Token:', accessToken); console.log('Refresh Token:', refresh); console.log('user:', user); console.log('user_type:', user_type);
ctx.res.setHeader('Set-Cookie', [ accessToken=${accessToken}; HttpOnly; Secure; SameSite=Strict;, refreshToken=${refresh}; HttpOnly; Secure; SameSite=Strict; ]);
return { token: { accessToken: accessToken, refreshToken: refresh, user: user, user_type: user_type } }; } catch (error) { throw createError({ statusCode: 500, statusMessage: 'Internal Server Error' }); } });
1 Reply
stefanpeev
stefanpeev4mo ago
I have a login page that passes creds and this is mylogin.post.ts Everything works it returns all the information I need. But now Im trying to figure out how to set these tokens so I can do Authorized requests with them in other pages, and to be authenticated in general because it stays on the login page const { signIn, status } = useAuth() console.log('status is', status.value) and status remains unauthenticated also i need to store the user_type variable in state so I can use it through the application in different components and pages. Please assist im very new at frontend and ive been having touble understanding the documentation. Managed to put them in cookies
setCookie(event, 'jwt', accessToken ) setCookie(event, 'refresh', refresh ) return {accessToken}; } catch (error) { throw createError({ statusCode: 500, statusMessage: 'Internal Server Error' }); } }); like this but im still unauthenticated and it keeps me in the same page because of my globalappmiddleware... i would prefer to continue using it, how do I change the status ?
Want results from more Discord servers?
Add your server