Skip to content
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

Show device token while signing in #3935

Merged
merged 7 commits into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
jtran marked this conversation as resolved.
Show resolved Hide resolved
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 4 additions & 1 deletion interface.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ export interface IElectronAPI {
save: typeof dialog.showSaveDialog
openExternal: typeof shell.openExternal
showInFolder: typeof shell.showItemInFolder
login: (host: string) => Promise<string>
/** Require to be called first before {@link loginWithDeviceFlow} */
startDeviceFlow: (host: string) => Promise<string>
/** Registered by first calling {@link startDeviceFlow}, which sets up the device flow handle */
loginWithDeviceFlow: () => Promise<string>
platform: typeof process.env.platform
arch: typeof process.env.arch
version: typeof process.env.version
Expand Down
43 changes: 28 additions & 15 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ ipcMain.handle('shell.openExternal', (event, data) => {
return shell.openExternal(data)
})

ipcMain.handle('login', async (event, host) => {
ipcMain.handle('startDeviceFlow', async (_, host: string) => {
// Do an OAuth 2.0 Device Authorization Grant dance to get a token.
// We quiet ts because we are not using this in the standard way.
// @ts-ignore
Expand All @@ -178,21 +178,34 @@ ipcMain.handle('login', async (event, host) => {

const handle = await client.deviceAuthorization()

// eslint-disable-next-line @typescript-eslint/no-floating-promises
shell.openExternal(handle.verification_uri_complete)

// Wait for the user to login.
try {
console.log('Polling for token')
const tokenSet = await handle.poll()
console.log('Received token set')
console.log(tokenSet)
return tokenSet.access_token
} catch (e) {
console.log(e)
}
// Register this handle to be used later.
ipcMain.handleOnce('loginWithDeviceFlow', async () => {
if (!handle) {
return Promise.reject(
new Error(
'No handle available. Did you call startDeviceFlow before calling this?'
)
)
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
shell.openExternal(handle.verification_uri_complete)
franknoirot marked this conversation as resolved.
Show resolved Hide resolved

// Wait for the user to login.
try {
console.log('Polling for token')
const tokenSet = await handle.poll()
console.log('Received token set')
console.log(tokenSet)
return tokenSet.access_token
} catch (e) {
console.log(e)
}

return Promise.reject(new Error('No access token received'))
})

return Promise.reject(new Error('No access token received'))
// Return the user code so the app can display it.
return handle.user_code
})

ipcMain.handle('kittycad', (event, data) => {
Expand Down
9 changes: 6 additions & 3 deletions src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ const save = (args: any) => ipcRenderer.invoke('dialog.showSaveDialog', args)
const openExternal = (url: any) => ipcRenderer.invoke('shell.openExternal', url)
const showInFolder = (path: string) =>
ipcRenderer.invoke('shell.showItemInFolder', path)
const login = (host: string): Promise<string> =>
ipcRenderer.invoke('login', host)
const startDeviceFlow = (host: string): Promise<string> =>
ipcRenderer.invoke('startDeviceFlow', host)
const loginWithDeviceFlow = (): Promise<string> =>
ipcRenderer.invoke('loginWithDeviceFlow')

const isMac = os.platform() === 'darwin'
const isWindows = os.platform() === 'win32'
Expand Down Expand Up @@ -61,7 +63,8 @@ const getMachineApiIp = async (): Promise<String | null> =>
ipcRenderer.invoke('find_machine_api')

contextBridge.exposeInMainWorld('electron', {
login,
startDeviceFlow,
loginWithDeviceFlow,
// Passing fs directly is not recommended since it gives a lot of power
// to the browser side / potential malicious code. We restrict what is
// exported.
Expand Down
71 changes: 54 additions & 17 deletions src/routes/SignIn.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,22 @@ import { Themes, getSystemTheme } from '../lib/theme'
import { PATHS } from 'lib/paths'
import { useSettingsAuthContext } from 'hooks/useSettingsAuthContext'
import { APP_NAME } from 'lib/constants'
import { CSSProperties, useCallback } from 'react'
import { CSSProperties, useCallback, useState } from 'react'
import { Logo } from 'components/Logo'
import { CustomIcon } from 'components/CustomIcon'
import { Link } from 'react-router-dom'
import { APP_VERSION } from './Settings'
import { openExternalBrowserIfDesktop } from 'lib/openWindow'
import { toSync } from 'lib/utils'
import { reportRejection } from 'lib/trap'
import toast from 'react-hot-toast'

const subtleBorder =
'border border-solid border-chalkboard-30 dark:border-chalkboard-80'
const cardArea = `${subtleBorder} rounded-lg px-6 py-3 text-chalkboard-70 dark:text-chalkboard-30`

const SignIn = () => {
const [userCode, setUserCode] = useState('')
const {
auth: { send },
settings: {
Expand Down Expand Up @@ -51,12 +53,24 @@ const SignIn = () => {

const signInDesktop = async () => {
// We want to invoke our command to login via device auth.
try {
const token: string = await window.electron.login(VITE_KC_API_BASE_URL)
send({ type: 'Log in', token })
} catch (error) {
console.error('Error with login button', error)
const userCodeToDisplay = await window.electron
.startDeviceFlow(VITE_KC_API_BASE_URL)
.catch(reportError)
if (!userCodeToDisplay) {
console.error('No user code received while trying to log in')
toast.error('Error while trying to log in')
return
}
setUserCode(userCodeToDisplay)

// Now that we have the user code, we can kick off the final login step.
const token = await window.electron.loginWithDeviceFlow().catch(reportError)
if (!token) {
console.error('No token received while trying to log in')
toast.error('Error while trying to log in')
return
}
send({ type: 'Log in', token })
}

return (
Expand Down Expand Up @@ -105,17 +119,40 @@ const SignIn = () => {
.
</p>
{isDesktop() ? (
<button
onClick={toSync(signInDesktop, reportRejection)}
className={
'm-0 mt-8 flex gap-4 items-center px-3 py-1 ' +
'!border-transparent !text-lg !text-chalkboard-10 !bg-primary hover:hue-rotate-15'
}
data-testid="sign-in-button"
>
Sign in to get started
<CustomIcon name="arrowRight" className="w-6 h-6" />
</button>
<div className="flex flex-col gap-2">
{!userCode ? (
<button
onClick={toSync(signInDesktop, reportRejection)}
className={
'm-0 mt-8 w-fit flex gap-4 items-center px-3 py-1 ' +
'!border-transparent !text-lg !text-chalkboard-10 !bg-primary hover:hue-rotate-15'
}
data-testid="sign-in-button"
>
Sign in to get started
<CustomIcon name="arrowRight" className="w-6 h-6" />
</button>
) : (
<>
<p className="text-xs">
You should see the following code in your browser
</p>
<p className="text-lg font-bold inline-flex gap-1">
{userCode.split('').map((char, i) => (
<span
key={i}
className={
'text-xl font-bold p-1 ' +
(char === '-' ? '' : 'border-2 border-solid')
}
>
{char}
</span>
))}
</p>
</>
)}
</div>
) : (
<Link
onClick={openExternalBrowserIfDesktop(signInUrl)}
Expand Down