Files
modeling-app/src/machines/authMachine.ts

180 lines
4.5 KiB
TypeScript
Raw Normal View History

import { createMachine, assign } from 'xstate'
import { Models } from '@kittycad/lib'
import withBaseURL from '../lib/withBaseURL'
import { isTauri } from 'lib/isTauri'
Migrate to tauri v2 (#1400) * Fix vite build (tauri build still broken) * Fix yarn builds with a couple of shortcuts * Fix file creation * Fix documentDir behavior * Got stream with default file * Clean up * Clean up * Use 'unstable'; fix devtools callsite The API changed a bit here, which forces us to use the unstable crate feature. The call to open devtools is also new; it's now on the webview not window. Signed-off-by: Paul R. Tagliamonte <paul@kittycad.io> * Bring back read_dir_recursive from v1 * Fix dates * More fixes, incl. conf files * cargo fmt * Add Updater plugin * Fix types * Fix isTauri detection and updater bootup * Schemas * Clean up * Disable devtools * Attempt at fixing builds * WIP Ubuntu dep * WIP Ubuntu dep * WIP keys in debug * Enable updater only on release builds * Reenable webtools on debug * No linux bundles * Typo * Attemp at fixing --bundles none * Manual tauri debug build * Empty commit to trigger the CI * Fix settings * Empty commit to trigger the CI * Merge branch 'main' into pierremtb/issue1349 * Add allow-create perm * tauri-driver no cap * Empty commit to trigger the CI * Clean up * Clean up * Migrate to tauri v2 Fixes #1349 * Fix fmt * Merge branch 'main' into pierremtb/issue1349 * Force BUILD_RELEASE: true * Bump tauri to new beta * Merge branch 'main' into pierremtb/issue1349 * Fix linux tests * Fix types * Add --verbose to tauri-action * Move --verbose to front * Back to tauri-driver@0.1.3 and single \ for win * Back to latest driver, and windows wip * Disable release conf temporarily * Rollback to 2.0.0-beta.2 * Rollback to 2.0.0-beta.1 * Move bundle to root for src-tauri/tauri.release.conf.json * All packages to latest (add http and shell to package.json) * Testing latest commit for tauri-action * Remove tauri action * Add cat * WIP * Update ci.yml * Disable release conf * Disable rust cache * Add tauri-action back for release builds * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * Update .codespellrc * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * Trigger CI * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * Fix type * Clean up * More clean up * Fix path concatenation with join * Attempt at fixing linux tests * Config clean up * Downgrade to tauri-driver@0.1.3 * Looks like tauri v2 is actually doing better with linux package names ah! * Change Linux apt packages * Increase wdio connectionRetryTimeout * Revert connectionRetryTimeout and bump tauri packages * Back to latest tauri-driver * Disable linux e2e tests * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * Trigger CI * Clean up * Update snapshots * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * Trigger CI * Remove @sentry/react * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * Rename migrated.json to desktop.json * A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu) * Trigger CI * Change wasm url to http on Windows --------- Signed-off-by: Paul R. Tagliamonte <paul@kittycad.io> Co-authored-by: Paul R. Tagliamonte <paul@kittycad.io> Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> Co-authored-by: Adam Chalmers <adam.chalmers@zoo.dev>
2024-04-09 08:04:36 -04:00
import { invoke } from '@tauri-apps/api/core'
import { VITE_KC_API_BASE_URL } from 'env'
const SKIP_AUTH =
import.meta.env.VITE_KC_SKIP_AUTH === 'true' && import.meta.env.DEV
const LOCAL_USER: Models['User_type'] = {
id: '8675309',
name: 'Test User',
email: 'kittycad.sidebar.test@example.com',
image: 'https://placekitten.com/200/200',
created_at: 'yesteryear',
updated_at: 'today',
company: 'Test Company',
discord: 'Test User#1234',
github: 'testuser',
phone: '555-555-5555',
first_name: 'Test',
last_name: 'User',
2024-02-29 11:57:47 +11:00
can_train_on_data: false,
is_service_account: false,
}
export interface UserContext {
user?: Models['User_type']
token?: string
}
export type Events =
| {
type: 'Log out'
}
| {
type: 'Log in'
token?: string
}
export const TOKEN_PERSIST_KEY = 'TOKEN_PERSIST_KEY'
const persistedToken =
localStorage?.getItem(TOKEN_PERSIST_KEY) ||
getCookie('__Secure-next-auth.session-token') ||
''
export const authMachine = createMachine<UserContext, Events>(
{
id: 'Auth',
initial: 'checkIfLoggedIn',
states: {
checkIfLoggedIn: {
id: 'check-if-logged-in',
invoke: {
src: 'getUser',
id: 'check-logged-in',
onDone: [
{
target: 'loggedIn',
actions: assign((context, event) => ({
user: event.data.user,
token: event.data.token || context.token,
})),
},
],
onError: [
{
target: 'loggedOut',
actions: assign({
user: () => undefined,
}),
},
],
},
},
loggedIn: {
entry: ['goToIndexPage'],
on: {
'Log out': {
target: 'loggedOut',
},
},
},
loggedOut: {
entry: ['goToSignInPage'],
on: {
'Log in': {
target: 'checkIfLoggedIn',
actions: assign({
token: (_, event) => {
const token = event.token || ''
localStorage.setItem(TOKEN_PERSIST_KEY, token)
return token
},
}),
},
},
},
},
schema: { events: {} as { type: 'Log out' } | { type: 'Log in' } },
predictableActionArguments: true,
preserveActionOrder: true,
context: {
token: persistedToken,
},
},
{
actions: {},
services: { getUser },
guards: {},
delays: {},
}
)
async function getUser(context: UserContext) {
const url = withBaseURL('/user')
const headers: { [key: string]: string } = {
'Content-Type': 'application/json',
}
if (!context.token && isTauri()) throw new Error('No token found')
if (context.token) headers['Authorization'] = `Bearer ${context.token}`
if (SKIP_AUTH) return LOCAL_USER
const userPromise = !isTauri()
? fetch(url, {
method: 'GET',
credentials: 'include',
headers,
})
.then((res) => res.json())
.catch((err) => console.error('error from Browser getUser', err))
: invoke<Models['User_type'] | Record<'error_code', unknown>>('get_user', {
token: context.token,
hostname: VITE_KC_API_BASE_URL,
}).catch((err) => console.error('error from Tauri getUser', err))
const tokenPromise = !isTauri()
? fetch(withBaseURL('/user/api-tokens?limit=1'), {
method: 'GET',
credentials: 'include',
headers,
})
.then(async (res) => {
const result: Models['ApiTokenResultsPage_type'] = await res.json()
return result.items[0].token
})
.catch((err) => console.error('error from Browser getUser', err))
: context.token
const user = await userPromise
const token = await tokenPromise
if ('error_code' in user) throw new Error(user.message)
return {
user,
token,
}
}
function getCookie(cname: string): string {
if (isTauri()) {
return ''
}
let name = cname + '='
let decodedCookie = decodeURIComponent(document.cookie)
let ca = decodedCookie.split(';')
for (let i = 0; i < ca.length; i++) {
let c = ca[i]
while (c.charAt(0) === ' ') {
c = c.substring(1)
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length)
}
}
return ''
}