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

POC - login via cli #163

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
6 changes: 5 additions & 1 deletion netlify.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
[build]
publish = './packages/website/dist'
command = 'yarn website:build'
# publish = './packages/website/dist'
publish = './packages/website/.next'

[[plugins]]
package = "@netlify/plugin-nextjs"

[[redirects]]
from = "https://figma-export.netlify.app/*"
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
"test:watch": "yarn test --watch --reporter=dot",
"coverage": "nyc yarn test --reporter=dot",
"coverage:watch": "npx nodemon -e js,mjs,ts --exec yarn coverage",
"website:start": "yarn build && yarn workspace @figma-export/website dev",
"website:dev": "yarn build && yarn workspace @figma-export/website dev",
"website:build": "yarn build && yarn workspace @figma-export/website build",
"website:serve": "yarn dlx serve packages/website/dist/",
"website:start": "yarn workspace @figma-export/website start",
"upgrade:major": "npx npm-check-updates -ws --root -u",
"upgrade:minor": "yarn upgrade:major --target minor",
"ls-engines": "yarn dlx ls-engines",
Expand Down
60 changes: 60 additions & 0 deletions packages/cli/src/commands/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import crypto from 'crypto';
import { Ora } from 'ora';
import { Sade } from 'sade';

import readline from 'readline';

type Auth = {
user_id: number
access_token: string
refresh_token: string
expires_in: number
}

function check(state: string): Promise<Auth | undefined> {
return fetch(`http://127.0.0.1:3000/api/check/${state}`)
.then((response) => response.json() as Promise<Auth>)
.catch(() => undefined);
}

export const addLogin = (prog: Sade, spinner: Ora) => prog
.command('login')
.describe('Login to Figma.')
.example('login')
.action(
() => {
const state = crypto.createHash('md5').update(Math.random().toString()).digest('hex');
spinner.info('Log in on https://figma.com');
console.log(`

Check warning on line 28 in packages/cli/src/commands/login.ts

View workflow job for this annotation

GitHub Actions / test (16.14.0)

Unexpected console statement

Check warning on line 28 in packages/cli/src/commands/login.ts

View workflow job for this annotation

GitHub Actions / test (16.x)

Unexpected console statement

Check warning on line 28 in packages/cli/src/commands/login.ts

View workflow job for this annotation

GitHub Actions / test (18.x)

Unexpected console statement

Check warning on line 28 in packages/cli/src/commands/login.ts

View workflow job for this annotation

GitHub Actions / test (20.x)

Unexpected console statement

Check warning on line 28 in packages/cli/src/commands/login.ts

View workflow job for this annotation

GitHub Actions / test (16.14.0)

Unexpected console statement

Check warning on line 28 in packages/cli/src/commands/login.ts

View workflow job for this annotation

GitHub Actions / test (21.x)

Unexpected console statement

Check warning on line 28 in packages/cli/src/commands/login.ts

View workflow job for this annotation

GitHub Actions / test (16.x)

Unexpected console statement

Check warning on line 28 in packages/cli/src/commands/login.ts

View workflow job for this annotation

GitHub Actions / test (18.x)

Unexpected console statement

Check warning on line 28 in packages/cli/src/commands/login.ts

View workflow job for this annotation

GitHub Actions / test (20.x)

Unexpected console statement

Check warning on line 28 in packages/cli/src/commands/login.ts

View workflow job for this annotation

GitHub Actions / test (21.x)

Unexpected console statement
Login at:
http://127.0.0.1:3000/api/login/${state}
`);

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

rl.question('PIN: ', (pin) => {
check(`${state}:${pin}`).then((response) => {
if (response == null) {
spinner.fail('Failed to login!');
return;
}

spinner.info(JSON.stringify(response, undefined, 2));
spinner.succeed('Logged in on https://figma.com.');
}).catch((error) => {
spinner.fail(error);
});
rl.close();
});

// spinner.start('waiting');

// check(state).then((response) => {
// spinner.info(JSON.stringify(response, undefined, 2));
// spinner.succeed('Logged in on https://figma.com.');
// });
},
);
3 changes: 2 additions & 1 deletion packages/cli/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import ora from 'ora';
import { addComponents } from './commands/components';
import { addStyles } from './commands/styles';
import { addUseConfig } from './commands/use-config';
import { addLogin } from './commands/login';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const pkg = require('../package.json');
Expand All @@ -14,5 +15,5 @@ const spinner = ora({});

prog.version(pkg.version);

addUseConfig(addStyles(addComponents(prog, spinner), spinner), spinner)
addLogin(addUseConfig(addStyles(addComponents(prog, spinner), spinner), spinner), spinner)
.parse(process.argv);
3 changes: 3 additions & 0 deletions packages/website/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
FIGMA_APP_CLIENT_SECRET=
FIGMA_APP_CLIENT_ID=
FIGMA_APP_REDIRECT_URI=http://127.0.0.1:3000/api/auth
28 changes: 28 additions & 0 deletions packages/website/lib/auth-storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
type Auth = {
user_id: number
access_token: string
refresh_token: string
expires_in: number
}

const store: Record<string, Auth> = {}

export function hasItem(key: string): boolean {
return key in store
}

export function setItem(key: string, value: Auth): void {
store[key] = value

setTimeout(() => {
removeItem(key)
}, 30 * 1000)
}

export function getItem(key: string): Auth | undefined {
return store[key]
}

export function removeItem(key: string): void {
delete store[key]
}
4 changes: 1 addition & 3 deletions packages/website/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
// https://nextjs.org/docs/api-reference/next.config.js/react-strict-mode
reactStrictMode: true,
output: 'export',
distDir: 'dist'
reactStrictMode: true
}

module.exports = nextConfig;
5 changes: 3 additions & 2 deletions packages/website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@
"next:lint": "next lint",
"next:dev": "next dev",
"next:build": "next build",
"next:export": "next export -o dist/",
"next:start": "next start",
"dev": "run-s export next:dev",
"build": "run-s clean export next:build"
"build": "run-s clean export next:build",
"start": "run-s next:start"
},
"devDependencies": {
"@figma-export/cli": "^5.0.1",
Expand Down
41 changes: 41 additions & 0 deletions packages/website/pages/api/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import { setItem } from '../../lib/auth-storage'

function isValid(cookieState: unknown, queryState: unknown): cookieState is string {
return typeof cookieState === 'string' && typeof queryState === 'string'
&& cookieState !== '' && queryState !== ''
&& cookieState === queryState
}

function rnd(length: number) {
let min = Math.pow(10, length - 1)
let max = Math.pow(10, length) - 1
return Math.floor(Math.random() * (max - min + 1)) + min
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const state = req.query.state
const cookieState = req.cookies.state

// delete `state` cookie
res.setHeader('Set-Cookie', `state=; Path=/api/auth; Max-Age=0`)

if (isValid(state, cookieState)) {
const code = req.query.code

const { FIGMA_APP_CLIENT_ID, FIGMA_APP_CLIENT_SECRET, FIGMA_APP_REDIRECT_URI } = process.env
const auth = await fetch(
`https://www.figma.com/api/oauth/token?client_id=${FIGMA_APP_CLIENT_ID}&client_secret=${FIGMA_APP_CLIENT_SECRET}&redirect_uri=${FIGMA_APP_REDIRECT_URI}&code=${code}&grant_type=authorization_code`,
{
method: 'POST'
}
)
.then(r => r.json())

const pin = rnd(6)
setItem(`${state}:${pin}`, auth)
res.status(307).redirect(`/auth/success#${pin}`)
} else {
res.status(443).json({ message: 'Access denied!' })
}
}
19 changes: 19 additions & 0 deletions packages/website/pages/api/check/[state].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import { getItem, removeItem } from '../../../lib/auth-storage'

export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (typeof req.query.state !== 'string') {
return res.status(404).send('')
}

console.log('invoked', req.query.state)

const auth = getItem(req.query.state)

if (auth == null) {
return res.status(404).send('')
}

removeItem(req.query.state)
res.status(200).json(auth)
}
17 changes: 17 additions & 0 deletions packages/website/pages/api/login/[state].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { NextApiRequest, NextApiResponse } from 'next'

function isValid(state: unknown): state is string {
return typeof state === 'string' && state !== ''
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { FIGMA_APP_CLIENT_ID, FIGMA_APP_REDIRECT_URI } = process.env
const state = req.query.state

if (!isValid(state)) {
return res.status(443).json({ message: 'Access denied!' })
}

res.setHeader('Set-Cookie', `state=${state}; Path=/api/auth`)
res.redirect(307, `https://www.figma.com/oauth?client_id=${FIGMA_APP_CLIENT_ID}&redirect_uri=${FIGMA_APP_REDIRECT_URI}&scope=file_read&state=${state}&response_type=code`)
}
80 changes: 80 additions & 0 deletions packages/website/pages/auth/success.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import Link from 'next/link'
import GitHubLink from '../../src/GitHubLink'
import { useEffect, useRef, useState } from 'react'

export default function HomePage() {
const [pin, setPin] = useState<number>(NaN)
const [timer, setTimer] = useState<number>(30)
const interval = useRef<number>()

useEffect(function handleTimer() {
if (interval.current == null && !isNaN(pin)) {
const endTimeString = window.sessionStorage.getItem(pin.toString())
if (endTimeString == null) {
window.sessionStorage.setItem(pin.toString(), (Date.now() + 30 * 1000).toString())
} else {
const endTime = parseInt(endTimeString ?? '0')
setTimer(Math.round((endTime - Date.now()) / 1000))
}

/** @ts-expect-error Interval is a number */
interval.current = setInterval(() => setTimer((t) => t - 1), 1000);
}

() => clearInterval(interval.current)
}, [pin])

useEffect(function clearTimer() {
if (timer < 0) {
clearInterval(interval.current)
setTimer(0)
}
}, [timer])


useEffect(function readPin() {
setPin(parseInt(window.location.hash.slice(1)))
}, [])

if (isNaN(pin)) {
return (
<>
<div className="container hero figma-gradient with-opacity-05">
<section>
<h1 className="title">
<Link href="/"><a className="figma-gradient text">
@figma-export
</a></Link>
</h1>
</section>
</div>
<GitHubLink />
</>
)
}

return (
<>
<div className="container hero figma-gradient with-opacity-05">
<section>
<h1 className="title">
<Link href="/"><a className="figma-gradient text">
@figma-export
</a></Link>
</h1>
<p>
<code className="figma-gradient with-opacity-10" style={{ fontSize: '36px', textDecoration: timer > 0 ? undefined : 'line-through' }}>{pin}</code>
</p>
{
timer > 0 ? (
<p>Copy this <code>pin</code> in your terminal window in {timer} seconds.</p>
) : (
<p>This <code>pin</code> expired.</p>
)
}
</section>
</div>
<GitHubLink />
</>
)
}
6 changes: 4 additions & 2 deletions packages/website/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ export default function HomePage({ icons, monochromeIcons }: Props) {
<div className="svgstore" dangerouslySetInnerHTML={{ __html: icons }} />
<div className="svgstore" dangerouslySetInnerHTML={{ __html: monochromeIcons }} />

<Title />
<GitHubLink />
<div className='mb-25px'>
<Title />
<GitHubLink />
</div>

<OutputComponents />
<OutputStyles />
Expand Down
6 changes: 5 additions & 1 deletion packages/website/scss/index.scss
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ pre[class*=language-] {

.hero {
text-align: center;
margin-bottom: 25px;
// margin-bottom: 25px;

&:last-child {
margin-bottom: 0;
Expand Down Expand Up @@ -343,4 +343,8 @@ h2 {
max-width: 700px;
display: block;
margin: 0 -15px;
}

.mb-25px {
margin-bottom: 25px;
}
Loading