Skip to content

Commit

Permalink
Add JSDoc and rename the logout function to invalidateSessionCookie, …
Browse files Browse the repository at this point in the history
…which will delete the session from the database as well
  • Loading branch information
gustavocadev committed Feb 22, 2024
1 parent bfc9e0c commit be0dc0a
Showing 1 changed file with 38 additions and 3 deletions.
41 changes: 38 additions & 3 deletions src/utils/qwikLuciaConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,24 @@ const handleRequest = (
) => {
const sessionId = event.cookie.get(lucia.sessionCookieName);

/**
* Validates the user session
* @returns The user and session
* @example
* ```ts
* const { user, session } = await validateUser();
* if (user) {
* console.log('User is logged in');
* }
* ```
* @example
* ```ts
* const { user, session } = await validateUser();
* if (!user) {
* console.log('User is not logged in');
* }
* ```
*/
const validateUser = async () => {
const sessionIdValue = sessionId?.value;

Expand Down Expand Up @@ -40,6 +58,11 @@ const handleRequest = (
};
};

/**
* Sets the session cookie
* @param session - The session to set
* @returns void
*/
const setSession = (session: Session) => {
const sessionCookie = lucia.createSessionCookie(session.id);
event.cookie.set(sessionCookie.name, sessionCookie.value, {
Expand All @@ -48,9 +71,16 @@ const handleRequest = (
});
};

const logout = async () => {
const sessionCookie = lucia.createBlankSessionCookie();
/**
* Removes the session cookie from the database and from the cookies
* @returns void
*/
const invalidateSessionCookie = async (session: Session) => {
// Remove the session from the db
await lucia.invalidateSession(session.id);

// Remove the session cookie from the cookies
const sessionCookie = lucia.createBlankSessionCookie();
event.cookie.set(sessionCookie.name, sessionCookie.value, {
path: '.',
...sessionCookie.attributes,
Expand All @@ -60,10 +90,15 @@ const handleRequest = (
return {
validateUser,
setSession,
logout,
invalidateSessionCookie,
};
};

/**
* Configures the Qwik Lucia library
* @param lucia - The Lucia instance
* @returns The handleRequest function
*/
export const qwikLuciaConfig = (lucia: Lucia) => {
return {
handleRequest: (event: RequestEventLoader | RequestEventAction) => {
Expand Down

0 comments on commit be0dc0a

Please sign in to comment.