-
-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(console): using svelte context managed stores #201
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a4f13ca
fix: convert store into context store
xmlking cdcdab2
fix(console): merge main
xmlking 9d32580
fix(console): using houdini setClientSession to update accessToken wh…
xmlking 35b30de
Merge branch 'main' into feat/context-store
xmlking ee7e065
style(console): lint fix
xmlking File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import { Logger } from '@spectacular/utils'; | ||
import type { Handle } from '@sveltejs/kit'; | ||
|
||
const log = new Logger('server:middleware:refreshToken'); | ||
|
||
export const refreshToken: Handle = async ({ event, resolve }) => { | ||
// TODO: extract refreshToken login from auth hook | ||
// https://github.com/Critteros/JavaFlavors/blob/main/web/src/lib/server/hooks/tokenRefresh.ts | ||
const response = await resolve(event); | ||
return response; | ||
}; |
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
import { browser } from '$app/environment'; | ||
import { env } from '$env/dynamic/public'; | ||
import { PUBLIC_NHOST_REGION, PUBLIC_NHOST_SUBDOMAIN } from '$env/static/public'; | ||
Check notice Code scanning / CodeQL Unused variable, import, function or class Note
Unused imports PUBLIC_NHOST_REGION, PUBLIC_NHOST_SUBDOMAIN.
|
||
import { extractSession, getClientSession, setClientSession } from '$houdini'; | ||
Check notice Code scanning / CodeQL Unused variable, import, function or class Note
Unused imports extractSession, getClientSession.
|
||
import { NHOST_SESSION_KEY } from '$lib/constants'; | ||
import { hasSecurityKey } from '$lib/nhost'; | ||
import { NhostClient, type NhostClientConstructorParams } from '@nhost/nhost-js'; | ||
import type { User } from '@nhost/nhost-js'; | ||
import { Logger } from '@spectacular/utils'; | ||
import Cookies from 'js-cookie'; | ||
import { getContext, onDestroy, setContext } from 'svelte'; | ||
import { type Readable, type Writable, derived, get, readable, readonly, writable } from 'svelte/store'; | ||
|
||
export class SvelteKitNhostClient extends NhostClient { | ||
#log = new Logger('auth.store.client'); | ||
|
||
#user = writable<User | null>(null); | ||
/** | ||
* Readable: updates every time the authentication status changes from signed-in to signed-out. | ||
*/ | ||
readonly isAuthenticated: Readable<boolean>; | ||
/** | ||
* Readable: updates every time the access or refresh token is changed. | ||
*/ | ||
readonly accessToken: Readable<string | null>; | ||
|
||
/** | ||
* Readable: updates when `accessToken` changed. | ||
* e.g., when `nhost.auth.elevateEmailSecurityKey(emmail)` is called or `accessToken` refeshed. | ||
*/ | ||
readonly elevated: Readable<boolean | null>; | ||
|
||
constructor(params: NhostClientConstructorParams) { | ||
super({ | ||
...params, | ||
start: browser, | ||
autoSignIn: browser, | ||
autoRefreshToken: browser, | ||
clientStorageType: 'cookie', | ||
}); | ||
|
||
this.isAuthenticated = readable<boolean>(false, (set) => { | ||
if (browser) { | ||
set(this.auth.isAuthenticated()); | ||
this.auth.onAuthStateChanged((event, session) => { | ||
this.#log.debug(`The auth state has changed. State is now ${event} with session:`, { session }); | ||
switch (event) { | ||
case 'SIGNED_IN': | ||
set(true); | ||
this.#user.set(session?.user || null); | ||
break; | ||
case 'SIGNED_OUT': | ||
set(false); | ||
this.#user.set(null); | ||
Cookies.remove(NHOST_SESSION_KEY); | ||
break; | ||
} | ||
}); | ||
return () => this.#log.debug('no more subscribers for isAuthenticated'); | ||
} | ||
}); | ||
|
||
this.accessToken = readable<string | null>(null, (set) => { | ||
if (browser) { | ||
set(this.auth.getAccessToken() ?? null); | ||
this.auth.onTokenChanged((session) => { | ||
this.#log.debug('The access token refreshed:', { session }); | ||
const accessToken = session?.accessToken; | ||
set(accessToken ?? null); | ||
// set fresh accessToken into HoudiniClient's session (client-side only) | ||
setClientSession({ accessToken }); | ||
// save session as cookie everytime token is refreshed or user signin via WebAuthN. | ||
// Cookie will be removed when browser closed or user explicitly SIGNED_OUT. | ||
Cookies.set(NHOST_SESSION_KEY, btoa(JSON.stringify(session)), { | ||
path: '/', | ||
sameSite: 'strict', | ||
secure: true, | ||
}); | ||
}); | ||
return () => this.#log.debug('no more subscribers for accessToken'); | ||
} | ||
}); | ||
|
||
this.elevated = derived( | ||
[this.accessToken, this.#user], | ||
([$at, $user]) => { | ||
return $at && $user ? this.auth.getHasuraClaim('x-hasura-auth-elevated') === $user.id : false; | ||
}, | ||
false, | ||
); | ||
|
||
onDestroy(() => { | ||
// Do cleanup ??? | ||
this.#log.debug('onDestroy called'); | ||
}); | ||
} | ||
|
||
get user() { | ||
return readonly(this.#user); | ||
} | ||
|
||
async isAuthenticatedAsync(): Promise<boolean> { | ||
return await this.auth.isAuthenticatedAsync(); | ||
} | ||
|
||
/** | ||
* elevate if neededelevateEmailSecurityKey | ||
* @returns error | ||
*/ | ||
async elevate() { | ||
const $elevated = get(this.elevated); | ||
const $user = get(this.#user); | ||
if (!$elevated && $user?.id && (await hasSecurityKey($user.id))) { | ||
const { error } = await this.auth.elevateEmailSecurityKey($user?.email as string); | ||
if (error) return error; | ||
} | ||
return null; | ||
} | ||
} | ||
|
||
// this is important if u are gonna have any SSR | ||
// https://www.youtube.com/watch?v=EyDV5XLfagg | ||
// https://kit.svelte.dev/docs/state-management | ||
|
||
const NHOST_CLIENT_KEY = Symbol('NHOST_CLIENT'); | ||
|
||
/** | ||
* We should not have exported state like this, to prevent: | ||
* Session state shared between different users when rendered on server(SSR), but don't worry, | ||
* This custom `nhost` object will not have sensitive data on server-side, | ||
* as we carefully check if this code is running in the browser, then only set session data. | ||
*/ | ||
// export let nhost: SvelteKitNhostClient; | ||
|
||
export const setNhostClient = () => { | ||
const nhost = new SvelteKitNhostClient({ | ||
// subdomain: PUBLIC_NHOST_SUBDOMAIN || 'local', | ||
// region: PUBLIC_NHOST_REGION, | ||
authUrl: env.PUBLIC_NHOST_AUTH_URL, | ||
graphqlUrl: env.PUBLIC_NHOST_GRAPHQL_URL, | ||
storageUrl: env.PUBLIC_NHOST_STORAGE_URL, | ||
functionsUrl: env.PUBLIC_NHOST_FUNCTIONS_URL, | ||
}); | ||
return setContext(NHOST_CLIENT_KEY, nhost); | ||
}; | ||
|
||
export const getNhostClient = () => { | ||
return getContext<ReturnType<typeof setNhostClient>>(NHOST_CLIENT_KEY); | ||
}; |
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
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
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
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
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
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check notice
Code scanning / CodeQL
Unused variable, import, function or class Note