Skip to content

Commit

Permalink
#186 convert auth into electron setup
Browse files Browse the repository at this point in the history
  • Loading branch information
neil authored and neil committed Feb 7, 2023
1 parent 680e107 commit 957cba2
Show file tree
Hide file tree
Showing 12 changed files with 159 additions and 153 deletions.
30 changes: 22 additions & 8 deletions modules/desktop/electron/electron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ import path from 'path';
import fs from 'fs';

import { getInstalledPackages } from './libs/teaDir';
try {
//@ts-ignore only used in dev should not be packaged inprod
/* eslint-disable */
const er = require('electron-reloader');
er(module);
} catch (e) {
console.error(e);
}
import { readSessionData, writeSessionData } from './libs/auth';
import type { Session } from '../src/libs/types';

// try {
// //@ts-ignore only used in dev should not be packaged inprod
// /* eslint-disable */
// const er = require('electron-reloader');
// er(module);
// } catch (e) {
// console.error(e);
// }

const serveURL = serve({ directory: '.' });
const port = process.env.PORT || 3000;
Expand Down Expand Up @@ -113,3 +116,14 @@ ipcMain.handle('get-installed-packages', async () => {
const pkgs = await getInstalledPackages();
return pkgs;
});

ipcMain.handle('get-session', async () => {
console.log('get session');
const session = await readSessionData();
console.log('session:', session);
return session;
});

ipcMain.handle('update-session', async (_, data) => {
await writeSessionData(data as Session);
});
41 changes: 41 additions & 0 deletions modules/desktop/electron/libs/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { mkdirp } from 'mkdirp';
import path from 'path';
import fs from 'fs';
import { getTeaPath } from './teaDir';
import type { Session } from '../../src/libs/types';
import * as v1Client from './v1Client';

const sessionFilePath = path.join(getTeaPath(), 'tea.xyz/gui/tmp.dat');
const sessionFolder = path.join(getTeaPath(), 'tea.xyz/gui');

export async function initSessionData() {
fs.readFileSync(sessionFilePath);

await mkdirp(sessionFolder);
const req = await v1Client.get<{ deviceId: string }>('/auth/registerDevice');
}

export async function readSessionData(): Promise<Session> {
try {
const sessionBuffer = await fs.readFileSync(sessionFilePath);
const session = JSON.parse(sessionBuffer.toString()) as Session;
return session;
} catch (error) {
console.error(error);
const req = await v1Client.get<{ deviceId: string }>('/auth/registerDevice');
const data = { device_id: req.deviceId };
await writeSessionData(data);
return data;
}
}

export async function writeSessionData(data: Session) {
try {
await mkdirp(sessionFolder);
await fs.writeFileSync(sessionFilePath, JSON.stringify(data), {
encoding: 'utf-8'
});
} catch (error) {
console.error(error);
}
}
10 changes: 8 additions & 2 deletions modules/desktop/electron/libs/teaDir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,15 @@ type Dir = {
path: string;
children?: Dir[];
};
export async function getInstalledPackages() {

export const getTeaPath = () => {
const homePath = app.getPath('home');
const pkgsPath = path.join(homePath, './.tea');
const teaPath = path.join(homePath, './.tea');
return teaPath;
};

export async function getInstalledPackages() {
const pkgsPath = getTeaPath();

const folders = await deepReadDir({
dir: pkgsPath,
Expand Down
17 changes: 17 additions & 0 deletions modules/desktop/electron/libs/v1Client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import axios from 'axios';
import path from 'path';

const base = 'https://api.tea.xyz';
export async function get<T>(urlPath: string) {
const url = new URL(path.join('v1', urlPath), base).toString();
// TODO: add headers
const req = await axios.request<T>({
method: 'GET',
url,
headers: {}
});

return req.data;
}

export default get;
6 changes: 3 additions & 3 deletions modules/desktop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@
"dependencies": {
"@electron/asar": "^3.2.3",
"@types/bcryptjs": "^2.4.2",
"@types/url-join": "^4.0.1",
"@vitest/coverage-c8": "^0.27.1",
"axios": "^1.3.2",
"bcryptjs": "^2.4.3",
"buffer": "^6.0.3",
"electron-context-menu": "^3.6.1",
Expand All @@ -82,11 +82,11 @@
"fuse.js": "^6.6.2",
"lodash": "^4.17.21",
"lorem-ipsum": "^2.0.8",
"mkdirp": "^2.1.3",
"semver": "^7.3.8",
"svelte-markdown": "^0.2.3",
"svelte-watch-resize": "^1.0.3",
"upath": "^2.0.1",
"url-join": "^5.0.0"
"upath": "^2.0.1"
},
"pnpm": {
"onlyBuiltDependencies": [
Expand Down
14 changes: 8 additions & 6 deletions modules/desktop/src/components/TopBar/ProfileNavButton.svelte
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
<script lang="ts">
// import { authStore } from '$libs/stores';
import { authStore } from '$libs/stores';
import type { Developer } from '@tea/ui/types';
// import { baseUrl } from '$libs/v1Client';
import { baseUrl } from '$libs/v1Client';
const { shell } = window.require('electron');
let user: Developer | null = null;
// const deviceId = authStore.deviceIdStore;
const deviceId = authStore.deviceIdStore;
const openGithub = () => {
// open(`${baseUrl}/auth/user?device_id=${$deviceId}`);
shell.openExternal(`${baseUrl}/auth/user?device_id=${$deviceId}`)
try {
// authStore.pollSession();
authStore.pollSession();
} catch (error) {
console.error(error);
}
};
// authStore.subscribe((u) => (user = u));
authStore.subscribe((u) => (user = u));
</script>

{#if user}
Expand Down
21 changes: 5 additions & 16 deletions modules/desktop/src/libs/api/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import type { GUIPackage, Course, Category } from '../types';
import { PackageStates } from '../types';
import { loremIpsum } from 'lorem-ipsum';
import _ from 'lodash';
import { getInstalledPackages } from '$libs/teaDir';
// import { getInstalledPackages } from '$libs/teaDir';
// import { getSession } from '$libs/stores/auth';
import * as v1Client from '$libs/v1Client';

const packages: Package[] = [
{
Expand Down Expand Up @@ -324,21 +326,8 @@ export async function getCategorizedPackages(): Promise<Category[]> {
}

export async function getDeviceAuth(deviceId: string): Promise<any> {
// const data = await get<any>(`/auth/device/${deviceId}`);
return {
status: 'SUCCESS',
user: {
developer_id: 'xxx',
name: 'Neil paul Molina',
login: 'getneil',
avatar_url: 'https://avatars.githubusercontent.com/u/7913978?v=4',
created_at: 'xxx',
updated_at: 'xxx',
country: 'germany',
wallet: 'wallet'
},
key: 'xxx'
};
const data = await v1Client.get<any>(`/auth/device/${deviceId}`);
return data;
}

export async function getPackageBottles(name: string): Promise<Bottle[]> {
Expand Down
63 changes: 8 additions & 55 deletions modules/desktop/src/libs/stores/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,16 @@ import { writable } from 'svelte/store';
// import fs from 'fs';
import { getDeviceAuth, registerDevice } from '@api';
import type { Developer } from '@tea/ui/types';
import type { Session } from '$libs/types';

const { ipcRenderer } = window.require('electron');

const basePath = '.tea/tea.xyz/gui';
export interface Session {
device_id?: string;
key?: string;
user?: Developer;
}

export let session: Session | null = null;
export const getSession = async (): Promise<Session | null> => {
// await app.whenReady();
// if (session && session?.user) return session;
// const homePath = app.getPath('home');
// const sessionFilePath = await join(homePath, basePath, 'tmp.dat');
// try {
// const encryptedData = fs.readFileSync(sessionFilePath, 'utf-8');
// session = JSON.parse(encryptedData || '{}') as Session;
// return session;
// } catch (error) {
// return null;
// }
return null;
session = await ipcRenderer.invoke('get-session');
return session;
};

export default function initAuthStore() {
Expand All @@ -35,7 +23,7 @@ export default function initAuthStore() {
const deviceIdStore = writable<string>('');
let deviceId = '';

initSession().then((sess) => {
getSession().then((sess) => {
if (sess) {
session = sess;
sessionStore.set(sess);
Expand All @@ -52,7 +40,8 @@ export default function initAuthStore() {
key: data.key,
user: data.user
};
saveLocallySessionData(localSession);
console.log('localSession:', localSession);
await ipcRenderer.invoke('update-session', localSession);
sessionStore.set(localSession);
}

Expand Down Expand Up @@ -93,39 +82,3 @@ export default function initAuthStore() {
pollSession
};
}

const initSession = async (): Promise<Session | void> => {
// const homePath = app.getPath('home');
// try {
// await fs.mkdirSync(join(homePath, basePath));
// } catch (error) {
// console.error(error);
// }
// const session = await getLocalSessionData();
// return session;
};

const getLocalSessionData = async (): Promise<Session | void> => {
let data: Session;
try {
const session = await getSession();
if (!session) throw new Error('no session');
data = session;
} catch (error) {
console.error('register device:', error);
const deviceId = await registerDevice();
data = {
device_id: deviceId
};
await saveLocallySessionData(data);
}

return data;
};

const saveLocallySessionData = async (data: Session) => {
// const homePath = app.getPath('home');
// const sessionFilePath = await join(homePath, basePath, 'tmp.dat');
// // TODO: encrypt first
// await fs.writeFileSync(sessionFilePath, JSON.stringify(data), 'utf-8');
};
30 changes: 1 addition & 29 deletions modules/desktop/src/libs/teaDir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,36 +10,8 @@ type Dir = {

const { ipcRenderer } = window.require('electron');
export async function getInstalledPackages() {
console.log('get installed pkgs');
const pkgs = await ipcRenderer.invoke('get-installed-packages');
console.log(pkgs);
// const homePath = app.getPath('home');
// const packageFolders = (await readDir('.tea/', {
// dir: BaseDirectory.Home,
// recursive: true
// })) as Dir[];

// const pkgs = packageFolders
// .filter((p) => p.name !== 'tea.xyz')
// .map(getPkgBottles)
// .filter((pkgBottles) => pkgBottles.length)
// .map((pkgBottles) => {
// const versions = pkgBottles.map((v) => v.split('/v')[1]);
// const full_name = pkgBottles[0].split('/v')[0];

// const isSemverVersion = versions.filter((v) => semverTest.test(v));
// const isNotAsterisk = versions.filter((v) => v !== '*');
// const version =
// (isSemverVersion.length && isSemverVersion[0]) ||
// (isNotAsterisk.length && isNotAsterisk[0]) ||
// '*';
// return {
// version,
// full_name
// };
// });
// return pkgs;
return [];
return pkgs as { version: string; full_name: string };
}

const semverTest =
Expand Down
5 changes: 5 additions & 0 deletions modules/desktop/src/libs/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,8 @@ export type DeviceAuth = {
user: Developer;
key: string;
};
export interface Session {
device_id?: string;
key?: string;
user?: Developer;
}
Loading

0 comments on commit 957cba2

Please sign in to comment.