Show device token while signing in (#3935)

* Show user code while logging in

* fmt

* A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest)

* @jtran feedback

Co-authored-by: Jonathan Tran <jonnytran@gmail.com>

* Revert "A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest)"

This reverts commit 5ba9e4351a.

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Jonathan Tran <jonnytran@gmail.com>
This commit is contained in:
Frank Noirot
2024-09-23 10:17:56 -04:00
committed by GitHub
parent f1b0e40388
commit 95ea1427bc
4 changed files with 90 additions and 35 deletions

5
interface.d.ts vendored
View File

@ -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

View File

@ -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
@ -178,21 +178,33 @@ 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)
// 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?'
)
)
}
shell.openExternal(handle.verification_uri_complete).catch(reportRejection)
// 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)
}
// 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) => {

View File

@ -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'
@ -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.

View File

@ -5,7 +5,7 @@ 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'
@ -13,12 +13,14 @@ 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: {
@ -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 (
@ -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)}