Skip to content

Commit

Permalink
fix(console): refine profile page
Browse files Browse the repository at this point in the history
  • Loading branch information
xmlking committed Jun 26, 2024
1 parent 41607b4 commit f0652d2
Show file tree
Hide file tree
Showing 5 changed files with 223 additions and 21 deletions.
155 changes: 154 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,79 @@
"files.autoSave": "afterDelay",
"files.autoSaveDelay": 1000,
"files.exclude": {
".changeset": true,
".dockerignore": true,
".editorconfig": true,
".env": true,
".env.development.local": true,
".env.example": true,
".env.local": true,
".env.prod": true,
".env.prod.example": true,
".env.test": true,
".git": true,
".gitattributes": true,
".github": true,
".gitignore": true,
".markdownlintignore": true,
".markuplintrc.cjs": true,
".nhost": true,
".npmrc": true,
".secrets": true,
".secrets.example": true,
".secrets.prod": true,
".secrets.prod.example": true,
".textlintignore": true,
".turbo": true,
".vercel": true,
".vercelignore": true,
".vscode": true,
"CHANGELOG.md": true,
"CODE_OF_CONDUCT.md": true,
"CONTRIBUTING.md": true,
"DEVELOPERS.md": true,
"Dockerfile": true,
"LICENSE": true,
"Makefile": true,
"README.md": true,
"TODO": true,
"biome.jsonc": true,
"bun.Dockerfile": true,
"bun.lockb": true,
"cog.toml": true,
"compose.nhost.yml": true,
"compose.override.yml": true,
"compose.yml": true,
"config": true,
"config.yaml": true,
"degit.json": true,
"docs": true,
"flake.nix": true,
"functions": true,
"infra": true,
"nhost": true,
"node_modules": true,
"package.json": true,
"packages": true,
"patches": true,
"pnpm-lock.yaml": true,
"pnpm-workspace.yaml": true,
"scripts": true,
"turbo.json": true,
"vercel.json": true,
"vitest.config.ts": true,
"vitest.workspaces.ts": true,
"apps/console-fb": true,
"apps/console-sc": true,
"apps/docs": true,
"apps/playground": true,
"apps/web": true,
"packages/assets": true,
"packages/biome-config": true,
"packages/skeleton-ui": true,
"packages/typescript-config": true,
"packages/ui": true,
"packages/utils": true,
"**/.git": true,
"**/.DS_Store": true,
".idea": true,
Expand Down Expand Up @@ -326,5 +399,85 @@
"[yaml]": {
"editor.defaultFormatter": "redhat.vscode-yaml"
},
"redhat.telemetry.enabled": false
"redhat.telemetry.enabled": false,
"monorepoFocusWorkspace.internal": {
"spectacular": {
"managedFilesIgnoreEntries": [
".changeset",
".dockerignore",
".editorconfig",
".env",
".env.development.local",
".env.example",
".env.local",
".env.prod",
".env.prod.example",
".env.test",
".git",
".gitattributes",
".github",
".gitignore",
".markdownlintignore",
".markuplintrc.cjs",
".nhost",
".npmrc",
".secrets",
".secrets.example",
".secrets.prod",
".secrets.prod.example",
".textlintignore",
".turbo",
".vercel",
".vercelignore",
".vscode",
"CHANGELOG.md",
"CODE_OF_CONDUCT.md",
"CONTRIBUTING.md",
"DEVELOPERS.md",
"Dockerfile",
"LICENSE",
"Makefile",
"README.md",
"TODO",
"biome.jsonc",
"bun.Dockerfile",
"bun.lockb",
"cog.toml",
"compose.nhost.yml",
"compose.override.yml",
"compose.yml",
"config",
"config.yaml",
"degit.json",
"docs",
"flake.nix",
"functions",
"infra",
"nhost",
"node_modules",
"package.json",
"packages",
"patches",
"pnpm-lock.yaml",
"pnpm-workspace.yaml",
"scripts",
"turbo.json",
"vercel.json",
"vitest.config.ts",
"vitest.workspaces.ts",
"apps/console-fb",
"apps/console-sc",
"apps/docs",
"apps/playground",
"apps/web",
"packages/assets",
"packages/biome-config",
"packages/skeleton-ui",
"packages/typescript-config",
"packages/ui",
"packages/utils"
],
"focusedWorkspace": "console"
}
}
}
17 changes: 15 additions & 2 deletions apps/console/src/lib/auth.ts → apps/console/src/lib/nhost.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { goto } from '$app/navigation';
import { nhost, user } from '$lib/stores/user';
import { Logger } from '@spectacular/utils';
import { SearchSecurityKeysStore } from '$houdini';

/**
* NOTE: These methods are still not in use.
* TODO: Evaulate switching to auth managment to client,
Expand All @@ -21,7 +23,7 @@ export async function signUp(email: string, password: string, displayName: strin
throw error;
}
if (session) {
user.set(nhost.auth.getUser());
// user.set(nhost.auth.getUser());
goto('/dashboard');
}
}
Expand All @@ -33,7 +35,7 @@ export async function signIn(email: string, password: string): Promise<void> {
throw error;
}
if (session) {
user.set(nhost.auth.getUser());
// user.set(nhost.auth.getUser());
goto('/dashboard');
}
}
Expand All @@ -49,3 +51,14 @@ export async function signOut() {
export async function isAuthenticated(): Promise<boolean> {
return await nhost.auth.isAuthenticatedAsync();
}

const skQuery = new SearchSecurityKeysStore().artifact.raw;
export async function hasSecurityKey(userId: string) {
const { data, error } = await nhost.graphql.request(skQuery, { userId });
if(error) {
log.error({error})
return false
}
return data?.authUserSecurityKeys.length > 0
}

1 change: 1 addition & 0 deletions apps/console/src/lib/stores/cookie-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// TODO Svelte store implemented on CookieStore API
50 changes: 43 additions & 7 deletions apps/console/src/lib/stores/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { browser } from '$app/environment';
import { env } from '$env/dynamic/public';
import { PUBLIC_NHOST_REGION, PUBLIC_NHOST_SUBDOMAIN } from '$env/static/public';
import { NHOST_SESSION_KEY } from '$lib/constants';
import { hasSecurityKey } from '$lib/nhost';
import type { User } from '@nhost/nhost-js';
import { NhostClient } from '@nhost/nhost-js';
import { Logger } from '@spectacular/utils';
import { derived, readable, writable } from 'svelte/store';
import { derived, get, readable, readonly, writable } from 'svelte/store';

const log = new Logger('user.store.client');

Expand All @@ -18,32 +19,67 @@ export const nhost = new NhostClient({
functionsUrl: env.PUBLIC_NHOST_FUNCTIONS_URL,
});

export const user = writable<User | null>(null);
/**
* Readable: updates every time the authentication status changes from signed-in to signed-out, vice versa.
* a private `_user` Writable used internally.
*/
export const _user = writable<User | null>(null);
export const user = readonly(_user);

/**
* Readable: updates every time the authentication status changes from signed-in to signed-out.
*/
export const isAuthenticated = readable<boolean>(false, (set) => {
set(nhost.auth.isAuthenticated());
nhost.auth.onAuthStateChanged((event, session) => {
log.debug(`The auth state has changed. State is now ${event} with session:`, { session });
switch (event) {
case 'SIGNED_IN':
set(true);
user.set(session?.user || null);
_user.set(session?.user || null);
break;
case 'SIGNED_OUT':
set(false);
user.set(null);
_user.set(null);
break;
}
});
return () => log.debug('no more subscribers for isAuthenticated');
});

/**
* Readable: updates every time the access or refresh token is changed.
*/
export const accessToken = readable<string | null>(null, (set) => {
set(nhost.auth.getAccessToken() ?? null);
nhost.auth.onTokenChanged((session) => {
log.debug('The access token refreshed:', { session });
set(session?.accessToken ?? null);
});
return () => log.debug('no more subscribers for accessToken');
});

export const elevated = derived([accessToken, user], ([$at, $user]) => {
return $at && $user ? nhost.auth.getHasuraClaim('x-hasura-auth-elevated') === $user.id : false;
});
/**
* Readable: updates when `accessToken` changed.
* e.g., when `nhost.auth.elevateEmailSecurityKey(emmail)` is called or `accessToken` refeshed.
*/
export const elevated = derived(
[accessToken, user],
([$at, $user]) => {
return $at && $user ? nhost.auth.getHasuraClaim('x-hasura-auth-elevated') === $user.id : false;
},
false,
);
/**
* elevate if neededelevateEmailSecurityKey
* @returns error
*/
export async function elevate() {
const $elevated = get(elevated);
const $user = get(user);
if (!$elevated && $user?.id && (await hasSecurityKey($user.id))) {
const { error } = await nhost.auth.elevateEmailSecurityKey(get(user)?.email as string);
if (error) return error;
}
return null;
}
21 changes: 10 additions & 11 deletions apps/console/src/routes/(app)/profile/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script lang="ts">
import { page } from '$app/stores';
import { Meta } from '$lib/components';
import { nhost, user } from '$lib/stores/user';
import { elevate, nhost, user } from '$lib/stores/user';
import type { AuthErrorPayload } from '@nhost/nhost-js';
import { Debug } from '@spectacular/skeleton/components';
import type { PageData } from './$houdini';
Expand All @@ -26,6 +26,11 @@ let error: AuthErrorPayload | null;
// Functions
async function addSecurityKey() {
console.log({ nickname });
error = await elevate()
if (error) {
console.log(error);
return;
}
const { key, error: addKeyError } = await nhost.auth.addSecurityKey(nickname);
// Something unexpected happened
if (error) {
Expand All @@ -38,16 +43,10 @@ async function addSecurityKey() {
}
async function handleElevate() {
const email = $user?.email;
if (email) {
const { elevated, isError } = await nhost.auth.elevateEmailSecurityKey(email);
if (elevated) {
// notify
console.log({ elevated });
}
if (isError) {
console.log({ isError });
}
error = await elevate()
if (!error) {
// TODO notify
console.log('elevated successfully');
}
}
Expand Down

0 comments on commit f0652d2

Please sign in to comment.