Skip to content

Commit

Permalink
logout, ui
Browse files Browse the repository at this point in the history
  • Loading branch information
ceddybi committed Jan 31, 2024
1 parent 52d4014 commit 9e9d093
Show file tree
Hide file tree
Showing 11 changed files with 181 additions and 32 deletions.
3 changes: 2 additions & 1 deletion forge.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { AutoUnpackNativesPlugin } from '@electron-forge/plugin-auto-unpack-natives';
import type { ForgeConfig } from '@electron-forge/shared-types';
import { MakerDeb } from '@electron-forge/maker-deb';
import { MakerRpm } from '@electron-forge/maker-rpm';
import { MakerSquirrel } from '@electron-forge/maker-squirrel';
import { MakerZIP } from '@electron-forge/maker-zip';
Expand Down Expand Up @@ -34,6 +33,7 @@ const config: ForgeConfig = {
new AutoUnpackNativesPlugin({}),
new WebpackPlugin({
mainConfig,
devContentSecurityPolicy: "default-src 'self' 'unsafe-eval' 'unsafe-inline' static: http: https: ws:",
renderer: {
config: rendererConfig,
entryPoints: [
Expand All @@ -48,6 +48,7 @@ const config: ForgeConfig = {
],
},
}),

],
publishers: [
{
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"description": "My Electron application description",
"main": ".webpack/main",
"scripts": {
"start": "electron-forge start",
"start": "APP_DEV=true electron-forge start",
"package": "electron-forge package",
"make": "electron-forge make",
"publish": "electron-forge publish",
Expand Down Expand Up @@ -55,6 +55,7 @@
"@tremor/react": "^3.13.3",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
"copy-webpack-plugin": "^12.0.2",
"electron-squirrel-startup": "^1.0.0",
"lodash": "^4.17.21",
"postcss": "^8.4.33",
Expand Down
49 changes: 41 additions & 8 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
// api with axios

import { getState, setState } from "../utils/state";
import { getResume, getState, setState } from "../utils/state";

import _get from "lodash/get";
import axios from 'axios';
import { isEmpty } from "lodash";

const isDev = process.env.APP_DEV ? (process.env.APP_DEV.trim() == "true") : false;

export const baseURL = isDev ? "http://localhost:3001" : "https://aij.vercel.app";
const api = axios.create({
baseURL: 'http://localhost:3331',
baseURL,
});


interface IResponse {
status: number;
// data: any;
Expand All @@ -30,12 +32,12 @@ interface GetAuthApiRes {


export const getAuthApi = async (args: GetAuth): Promise<any> => {
let state = await getState();
try {
const response = await api.post<GetAuthApiRes>('/api/auth', args);
if (response.status !== 200) {
throw new Error("error");
}
const state = await getState();
const data = response.data;
if (data.success !== true) {
const message = _get(data, "message");
Expand All @@ -50,18 +52,19 @@ export const getAuthApi = async (args: GetAuth): Promise<any> => {
if (isEmpty(access_token) || isEmpty(refresh_token)) {
throw new Error("error getting tokens");
};

const email = _get(data, "data.auth.user.email", "");
const credits = _get(data, "data.credits", 0);
const newAuth = { access_token, refresh_token, email, credits, res: { success: true } };
await setState({ ...state, auth: newAuth });
return newAuth;
}


}
catch (error) {
console.error("Error getAuthApi", error);
const newAuth = { ...state.auth, res: { message: error.message || "", success: false } };
await setState({ ...state, auth: newAuth });
return null;
}

Expand All @@ -74,9 +77,24 @@ interface IMainResponse extends IResponse {

export const getMainApi = async (): Promise<any> => {
try {
const data = {
const state = await getState();
const resume = await getResume();
const access_token = _get(state, "auth.access_token");
const refresh_token = _get(state, "auth.refresh_token");
if (isEmpty(access_token) || isEmpty(refresh_token)) {
throw new Error("error getting tokens");
};

if (isEmpty(resume)) {
throw new Error("error getting resume");
}

const data = {
access_token,
refresh_token,
resume
};

const response = await api.post<IMainResponse>('/api/main', data);
if (response.status !== 200) {
throw new Error("error");
Expand All @@ -93,9 +111,24 @@ export const getMainApi = async (): Promise<any> => {

export const getAppApi = async (): Promise<any> => {
try {
const data = {
const state = await getState();
const resume = await getResume();
const access_token = _get(state, "auth.access_token");
const refresh_token = _get(state, "auth.refresh_token");
if (isEmpty(access_token) || isEmpty(refresh_token)) {
throw new Error("error getting tokens");
};

if (isEmpty(resume)) {
throw new Error("error getting resume");
}

const data = {
access_token,
refresh_token,
resume
};

const response = await api.post<IMainResponse>('/api/app', data);
if (response.status !== 200) {
throw new Error("error");
Expand Down
36 changes: 30 additions & 6 deletions src/app/auth/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,39 @@
import { LayoutPageProps } from "../layout";
import React from "react";
import _get from "lodash/get";
import { isEmpty } from "lodash";
// import logo from "../../assets/icon.png";

export const AuthPage = ({ state }: LayoutPageProps) => {
const authMessage = _get(state, "auth.res.message", "");

export const AuthPage = () => {

const openAuthLink = async () => {
await (window as any).api.invoke("open:link", "http://localhost:3001/signin/app");
await (window as any).api.invoke("open:link", null);
};

return (
<div>
<h1>Auth Page</h1>
<button onClick={openAuthLink}>Login / Signup</button>
<div
className="flex justify-center items-center flex-col"
style={{ height: "100vh", width: "100vw" }}
>
<img
src={"static://assets/icon.png"}
style={{ width: "100px", padding: "5px", marginBottom: "20px" }}
/>

{!isEmpty(authMessage) && (
<div className="flex justify-center">
<div className="text-2xl font-bold">{authMessage}</div>
</div>
)}
<div className="flex justify-center mt-2">
<button
onClick={openAuthLink}
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
>
Login / Signup
</button>
</div>
</div>
);
};
Expand Down
2 changes: 1 addition & 1 deletion src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export const Layout = () => {
if (!isAuth) {
return (
<div className="h-full bg-gray-50 w-full">
<AuthPage />
<AuthPage state={state} />
</div>
);
}
Expand Down
16 changes: 16 additions & 0 deletions src/app/settings/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import React from "react";
export const SettingsPage = ({ state }: LayoutPageProps) => {
const auth = state.auth;

const handleSignout = async () => {
await (window as any).api.invoke("logout", null);
};

if (!auth) {
// TODO login
return null;
Expand All @@ -23,6 +27,18 @@ export const SettingsPage = ({ state }: LayoutPageProps) => {
<Bold>Email: </Bold>
<Bold>{email}</Bold>
</div>

<div className="p-2 flex justify-between">
<Bold></Bold>
<div className="flex justify-center mt-2">
<button
onClick={handleSignout}
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-2 rounded"
>
Logout
</button>
</div>
</div>
</Card>
);
};
Expand Down
10 changes: 7 additions & 3 deletions src/config/app.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as cheerio from "cheerio";

import { APPEVENTS, AppEvents } from "../events";
import { AppJob, addJob, getQuestion, getState, saveQuestion, setState } from "../utils/state";
import _, { debounce } from "lodash";
import { AppJob, addJob, getQuestion, getResume, getState, saveQuestion, setState } from "../utils/state";
import _, { debounce, isEmpty } from "lodash";
import { getAppApi, getMainApi } from "../api";

import _get from "lodash/get";
Expand Down Expand Up @@ -56,6 +56,7 @@ export const gotoMainPage = async (url: string) => {
export const gotoAppPage = async (job: AppJob) => {
try {

const resume = await getResume();
const browser = await getBrowser();
const page = await browser.newPage();

Expand All @@ -64,6 +65,7 @@ export const gotoAppPage = async (job: AppJob) => {
};

const ctx = {
resume,
cheerio,
_,
browser,
Expand All @@ -80,12 +82,14 @@ export const gotoAppPage = async (job: AppJob) => {
};

const getAppRes = await getAppApi();
if (!getAppRes) {
if (isEmpty(getAppRes && getAppRes.data)) {
throw new Error("Error getApp api");
}

const mainFunc = getAppRes.data;

console.log("mainFunc", mainFunc);

return await new Promise((resolve, reject) => {

appEvents.on(APPEVENTS.APP_STOP, (jobId: string) => {
Expand Down
26 changes: 19 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { APPEVENTS, AppEvents } from './events';
import { AppJob, BEState, addApplied, getAllQuestion, getResume, getState, readQuestion, saveQuestion, saveResume, setState } from "./utils/state";
import { BrowserWindow, app, dialog, ipcMain, shell } from 'electron';
import { BrowserWindow, app, dialog, ipcMain, session, shell } from 'electron';
import { baseURL, getAuthApi } from './api';
import { gotoAppPage, gotoMainPage } from './config/app';

import { getAuthApi } from './api';
import packageJson from '../package.json';
import path from 'node:path';
import { updateElectronApp } from "update-electron-app";
Expand Down Expand Up @@ -50,14 +50,13 @@ const getAppAuth = async (urlLinking?: string) => {
if (access_token && refresh_token) {
const getAuth = await getAuthApi({ access_token, refresh_token });
if (!getAuth) {
throw new Error("Error logging in, please try again");
throw new Error("Error logging in");
}
dialog.showErrorBox('Success signin', JSON.stringify(getAuth));
}
}
catch (error) {
console.error("Error", error);
dialog.showErrorBox('Error opening', error.message || "Error opening app");
dialog.showErrorBox(error.message || "Error opening app", "Please try again");
}
}
if (!gotTheLock) {
Expand Down Expand Up @@ -119,6 +118,12 @@ const createWindow = (): void => {
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', () => {
session.defaultSession.protocol.registerFileProtocol('static', (request, callback) => {
const fileUrl = request.url.replace('static://', '');
const filePath = path.join(app.getAppPath(), '.webpack/renderer', fileUrl);
console.log("filePath", filePath);
callback(filePath);
});
createWindow();
getAppAuth();
});
Expand Down Expand Up @@ -274,12 +279,19 @@ ipcMain.handle('resume:save', async (event, resume) => {
return savedResume;
});

ipcMain.handle('open:link', async (event, link) => {
if (!link) return;
ipcMain.handle('open:link', async (event, ogLink) => {
const link = `${baseURL}/signin/app`;
await shell.openExternal(link);
return true;
});

ipcMain.handle('logout', async (event, ogLink) => {
const state = await getState();
const newState = { ...state, auth: {} as any };
await setState(newState);
return true;
});

ipcMain.handle('my-invokable-ipc', async (event, ...args) => {
const state = await getState();
// const browser = await getBrowser();
Expand Down
1 change: 1 addition & 0 deletions src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ let validChannels = ["my-invokable-ipc",
"questions:getall", "questions:save", "questions:read",
"resume:get", "resume:save",
"open:link",
"logout"
]; // list of ipcMain.handle channels you want access in frontend to
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
Expand Down
13 changes: 13 additions & 0 deletions webpack.renderer.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { Configuration } from 'webpack';
import CopyWebpackPlugin from 'copy-webpack-plugin';
import path from 'path';
import { plugins } from './webpack.plugins';
import { rules } from './webpack.rules';

Expand All @@ -7,6 +9,17 @@ rules.push({
use: ['style-loader', 'css-loader', 'postcss-loader'],
});

const assets = ['assets'];
const copyPlugins = new CopyWebpackPlugin(
{
patterns: assets.map((asset) => ({
from: path.resolve(__dirname, 'src', asset),
to: path.resolve(__dirname, '.webpack/renderer', asset)
}))
}
);

plugins.push(copyPlugins as any);

export const rendererConfig: Configuration = {
module: {
Expand Down
Loading

0 comments on commit 9e9d093

Please sign in to comment.