Last active
March 2, 2024 18:03
-
-
Save Mlocik97/c6861d9ce88849b96e394a5f19dc81f7 to your computer and use it in GitHub Desktop.
example (writen by hand, not tested) of auth in SvelteKit. (deprecated)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export async function handle({ event, resolve }) { | |
const cookies = await cookie.parse(event.request.headers.get('cookie') || ''); | |
if (event.url.pathname == '/login') { | |
// skip verifying user, and allow to load website | |
const response = await resolve(event); | |
return response; | |
} | |
const user = DB.User.findOne({session: cookies.token}); | |
if (!user) { | |
return new Response(null, { | |
status: 302, | |
headers: { | |
location: '/login' | |
} | |
}) | |
} | |
event.locals.user = user; // put user data to locals, it will be avaiable for getSession hook and endpoints | |
const response = await resolve(event); | |
response.headers.set({ | |
'set-cookie': cookie.serialize('token', cookies.token, { // reset expire to 7 days | |
httpOnly: true, | |
path: '/', | |
maxAge: 7 * 24 * 60 * 60 // 1 week | |
}) | |
}) | |
return response; | |
} | |
export async function getSession(event) { | |
return event.locals.user ? { | |
// put here some data from event.locals.user that you wish to expose for specific user (will be aviable in Session store on client-side) | |
} : {} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export async function post({ request }) { | |
const formData = await request.formData(); | |
const data = Object.fromEntries(formData); | |
const user = DB.User.findOne({ email: data.email }); | |
const verified = bcrypt.compare(user.passwordHash, data.password); | |
if (verified) { | |
// set cookie, save cookie token to DB, and return response | |
} | |
return { status: 300 } // or resp. unauthorized, you can redirect to login page again | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This example is actually deprecated,... now there is more elegant way with build-in
cookie.set
. No more need of cookie module.So instead:
you can write just simple
Same for setting cookies. There are also few other stuff that can be simplified. Will write new example when I will have time.
Btw. getSession was removed.