From 32566e5dfc2da08ce28e19fd0286de9e1996786b Mon Sep 17 00:00:00 2001 From: Zamitto <167933696+zamitto@users.noreply.github.com> Date: Sun, 16 Jun 2024 13:58:24 -0300 Subject: [PATCH] feat: handle login from deeplink --- src/locales/en/translation.json | 6 +- src/locales/pt/translation.json | 6 +- src/main/events/auth/signout.ts | 17 +++++ src/main/events/index.ts | 3 +- .../get-user-profile.ts => user/get-user.ts} | 4 +- src/main/index.ts | 12 ++- src/main/services/hydra-api.ts | 49 ++++++++++--- src/preload/index.ts | 18 ++++- .../components/sidebar/sidebar-profile.tsx | 35 +++------ .../src/components/sidebar/sidebar.tsx | 5 +- .../context/user-auth/user-auth.context.tsx | 73 +++++++++++++++++++ .../user-auth/user-auth.context.types.ts | 8 ++ src/renderer/src/declaration.d.ts | 9 ++- src/renderer/src/pages/user/user-content.tsx | 26 +++++-- src/renderer/src/pages/user/user-skeleton.tsx | 5 +- src/renderer/src/pages/user/user.tsx | 23 +++--- src/types/index.ts | 6 ++ 17 files changed, 243 insertions(+), 62 deletions(-) create mode 100644 src/main/events/auth/signout.ts rename src/main/events/{profile/get-user-profile.ts => user/get-user.ts} (95%) create mode 100644 src/renderer/src/context/user-auth/user-auth.context.tsx create mode 100644 src/renderer/src/context/user-auth/user-auth.context.types.ts diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json index c4022a93..bbab5670 100644 --- a/src/locales/en/translation.json +++ b/src/locales/en/translation.json @@ -229,6 +229,10 @@ "amount_hours": "{{amount}} hours", "amount_minutes": "{{amount}} minutes", "play_time": "Played for {{amount}}", - "last_time_played": "Last played {{period}}" + "last_time_played": "Last played {{period}}", + "sign_out": "Sign out", + "activity": "Recent Activity", + "games": "Games", + "total_play_time": "Total playtime: {{amount}}" } } diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json index 8a2d7c6a..1ccc675f 100644 --- a/src/locales/pt/translation.json +++ b/src/locales/pt/translation.json @@ -230,6 +230,10 @@ "amount_hours": "{{amount}} horas", "amount_minutes": "{{amount}} minutos", "play_time": "Jogado por {{amount}}", - "last_time_played": "Jogou {{period}}" + "last_time_played": "Jogou {{period}}", + "sign_out": "Sair da conta", + "activity": "Atividade Recente", + "games": "Jogos", + "total_play_time": "Tempo total de jogo: {{amount}}" } } diff --git a/src/main/events/auth/signout.ts b/src/main/events/auth/signout.ts new file mode 100644 index 00000000..fc8b9567 --- /dev/null +++ b/src/main/events/auth/signout.ts @@ -0,0 +1,17 @@ +import { userAuthRepository } from "@main/repository"; +import { registerEvent } from "../register-event"; +import { HydraApi } from "@main/services/hydra-api"; +import { WindowManager } from "@main/services"; + +const signout = async (_event: Electron.IpcMainInvokeEvent): Promise => { + await Promise.all([ + userAuthRepository.delete({ id: 1 }), + HydraApi.post("/auth/logout"), + ]).finally(() => { + if (WindowManager.mainWindow) { + WindowManager.mainWindow.webContents.send("on-signout"); + } + }); +}; + +registerEvent("signout", signout); diff --git a/src/main/events/index.ts b/src/main/events/index.ts index 8371b60d..d7348618 100644 --- a/src/main/events/index.ts +++ b/src/main/events/index.ts @@ -40,7 +40,8 @@ import "./download-sources/validate-download-source"; import "./download-sources/add-download-source"; import "./download-sources/remove-download-source"; import "./download-sources/sync-download-sources"; -import "./profile/get-user-profile"; +import "./auth/signout"; +import "./user/get-user"; import "./profile/get-me"; ipcMain.handle("ping", () => "pong"); diff --git a/src/main/events/profile/get-user-profile.ts b/src/main/events/user/get-user.ts similarity index 95% rename from src/main/events/profile/get-user-profile.ts rename to src/main/events/user/get-user.ts index 4cbe7f55..2a2eec9d 100644 --- a/src/main/events/profile/get-user-profile.ts +++ b/src/main/events/user/get-user.ts @@ -5,7 +5,7 @@ import { UserProfile } from "@types"; import { convertSteamGameToCatalogueEntry } from "../helpers/search-games"; import { getSteamAppAsset } from "@main/helpers"; -const getUserProfile = async ( +const getUser = async ( _event: Electron.IpcMainInvokeEvent, username: string ): Promise => { @@ -53,4 +53,4 @@ const getUserProfile = async ( } }; -registerEvent("getUserProfile", getUserProfile); +registerEvent("getUser", getUser); diff --git a/src/main/index.ts b/src/main/index.ts index e2333789..3e74ea49 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -7,6 +7,7 @@ import { DownloadManager, logger, WindowManager } from "@main/services"; import { dataSource } from "@main/data-source"; import * as resources from "@locales"; import { userPreferencesRepository } from "@main/repository"; +import { HydraApi } from "./services/hydra-api"; const { autoUpdater } = updater; @@ -71,7 +72,7 @@ app.on("browser-window-created", (_, window) => { optimizer.watchWindowShortcuts(window); }); -app.on("second-instance", (_event, commandLine) => { +app.on("second-instance", async (_event, commandLine) => { // Someone tried to run a second instance, we should focus our window. if (WindowManager.mainWindow) { if (WindowManager.mainWindow.isMinimized()) @@ -83,7 +84,14 @@ app.on("second-instance", (_event, commandLine) => { } const [, path] = commandLine.pop()?.split("://") ?? []; - if (path) WindowManager.redirect(path); + if (path) { + if (path.startsWith("auth")) { + //hydralauncher://auth?payload=responsedaapiembase64 + await HydraApi.handleExternalAuth(path.split("=")[1]); + } else { + WindowManager.redirect(path); + } + } }); app.on("open-url", (_event, url) => { diff --git a/src/main/services/hydra-api.ts b/src/main/services/hydra-api.ts index 41e7a39f..39a6d633 100644 --- a/src/main/services/hydra-api.ts +++ b/src/main/services/hydra-api.ts @@ -1,5 +1,6 @@ import { userAuthRepository } from "@main/repository"; import axios, { AxiosError, AxiosInstance } from "axios"; +import { WindowManager } from "./window-manager"; export class HydraApi { private static instance: AxiosInstance; @@ -16,6 +17,38 @@ export class HydraApi { return this.userAuth.authToken !== ""; } + static async handleExternalAuth(auth: string) { + const decodedBase64 = atob(auth); + const jsonData = JSON.parse(decodedBase64); + + const { accessToken, expiresIn, refreshToken } = jsonData; + + const now = new Date(); + + const tokenExpirationTimestamp = + now.getTime() + expiresIn - this.EXPIRATION_OFFSET_IN_MS; + + this.userAuth = { + authToken: accessToken, + refreshToken: refreshToken, + expirationTimestamp: tokenExpirationTimestamp, + }; + + await userAuthRepository.upsert( + { + id: 1, + accessToken, + tokenExpirationTimestamp, + refreshToken, + }, + ["id"] + ); + + if (WindowManager.mainWindow) { + WindowManager.mainWindow.webContents.send("on-signin"); + } + } + static async setupApi() { this.instance = axios.create({ baseURL: import.meta.env.MAIN_VITE_API_URL, @@ -33,6 +66,8 @@ export class HydraApi { } private static async revalidateAccessTokenIfExpired() { + if (!this.userAuth.authToken) throw new Error("user is not logged in"); + const now = new Date(); if (this.userAuth.expirationTimestamp < now.getTime()) { try { @@ -64,15 +99,11 @@ export class HydraApi { this.userAuth.authToken = ""; this.userAuth.expirationTimestamp = 0; - userAuthRepository.upsert( - { - id: 1, - accessToken: "", - refreshToken: "", - tokenExpirationTimestamp: 0, - }, - ["id"] - ); + if (WindowManager.mainWindow) { + WindowManager.mainWindow.webContents.send("on-signout"); + } + + userAuthRepository.delete({ id: 1 }); } throw err; diff --git a/src/preload/index.ts b/src/preload/index.ts index 2f837167..dda0b0f4 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -128,7 +128,21 @@ contextBridge.exposeInMainWorld("electron", { restartAndInstallUpdate: () => ipcRenderer.invoke("restartAndInstallUpdate"), /* Profile */ - getUserProfile: (username: string) => - ipcRenderer.invoke("getUserProfile", username), getMe: () => ipcRenderer.invoke("getMe"), + + /* User */ + getUser: (username: string) => ipcRenderer.invoke("getUser", username), + + /* Auth */ + signout: () => ipcRenderer.invoke("signout"), + onSignIn: (cb: () => void) => { + const listener = (_event: Electron.IpcRendererEvent) => cb(); + ipcRenderer.on("on-signin", listener); + return () => ipcRenderer.removeListener("on-signin", listener); + }, + onSignOut: (cb: () => void) => { + const listener = (_event: Electron.IpcRendererEvent) => cb(); + ipcRenderer.on("on-signout", listener); + return () => ipcRenderer.removeListener("on-signout", listener); + }, }); diff --git a/src/renderer/src/components/sidebar/sidebar-profile.tsx b/src/renderer/src/components/sidebar/sidebar-profile.tsx index c454c348..d1fc8301 100644 --- a/src/renderer/src/components/sidebar/sidebar-profile.tsx +++ b/src/renderer/src/components/sidebar/sidebar-profile.tsx @@ -1,38 +1,25 @@ -import { useEffect, useState } from "react"; +import { useContext } from "react"; import { useNavigate } from "react-router-dom"; -import { type UserProfile } from "@types"; -import * as styles from "./sidebar.css"; import { PersonIcon } from "@primer/octicons-react"; +import { userAuthContext } from "@renderer/context/user-auth/user-auth.context"; +import * as styles from "./sidebar.css"; export function SidebarProfile() { const navigate = useNavigate(); - const [userProfile, setUserProfile] = useState(null); - const [isUserProfileLoading, setIsUserProfileLoading] = useState(true); + const { userAuth, isLoading } = useContext(userAuthContext); const handleClickProfile = () => { - navigate(`/user/${userProfile!.id}`); + navigate(`/user/${userAuth!.id}`); }; const handleClickLogin = () => { window.electron.openExternal("https://losbroxas.org"); }; - useEffect(() => { - setIsUserProfileLoading(true); - window.electron.isUserLoggedIn().then(async (isLoggedIn) => { - if (isLoggedIn) { - const userProfile = await window.electron.getMe(); - setUserProfile(userProfile); - } + if (isLoading) return null; - setIsUserProfileLoading(false); - }); - }, []); - - if (isUserProfileLoading) return null; - - if (userProfile == null) { + if (userAuth == null) { return ( <> diff --git a/src/renderer/src/components/sidebar/sidebar.tsx b/src/renderer/src/components/sidebar/sidebar.tsx index 5fb20577..1bc254e6 100644 --- a/src/renderer/src/components/sidebar/sidebar.tsx +++ b/src/renderer/src/components/sidebar/sidebar.tsx @@ -14,6 +14,7 @@ import { buildGameDetailsPath } from "@renderer/helpers"; import SteamLogo from "@renderer/assets/steam-logo.svg?react"; import { SidebarProfile } from "./sidebar-profile"; +import { UserAuthContextProvider } from "@renderer/context/user-auth/user-auth.context"; const SIDEBAR_MIN_WIDTH = 200; const SIDEBAR_INITIAL_WIDTH = 250; @@ -154,7 +155,9 @@ export function Sidebar() { maxWidth: sidebarWidth, }} > - + + +
({ + userAuth: null, + isLoading: false, + signout: async () => {}, + updateMe: async () => {}, +}); + +const { Provider } = userAuthContext; +export const { Consumer: UserAuthContextConsumer } = userAuthContext; + +export interface UserAuthContextProps { + children: React.ReactNode; +} + +export function UserAuthContextProvider({ children }: UserAuthContextProps) { + const [userAuth, setUserAuth] = useState(null); + const [isLoading, setIsLoading] = useState(false); + + const updateMe = () => { + setIsLoading(true); + + return window.electron + .getMe() + .then((user) => { + setUserAuth(user); + }) + .finally(() => { + setIsLoading(false); + }); + }; + + useEffect(() => { + updateMe(); + }, []); + + useEffect(() => { + const listeners = [ + window.electron.onSignIn(() => { + updateMe(); + }), + window.electron.onSignOut(() => { + setUserAuth(null); + }), + ]; + + return () => { + listeners.forEach((unsubscribe) => unsubscribe()); + }; + }, []); + + const signout = () => { + return window.electron.signout().finally(() => { + setUserAuth(null); + }); + }; + + return ( + + {children} + + ); +} diff --git a/src/renderer/src/context/user-auth/user-auth.context.types.ts b/src/renderer/src/context/user-auth/user-auth.context.types.ts new file mode 100644 index 00000000..389da1eb --- /dev/null +++ b/src/renderer/src/context/user-auth/user-auth.context.types.ts @@ -0,0 +1,8 @@ +import { UserAuth } from "@types"; + +export interface UserAuthContext { + userAuth: UserAuth | null; + isLoading: boolean; + updateMe: () => Promise; + signout: () => Promise; +} diff --git a/src/renderer/src/declaration.d.ts b/src/renderer/src/declaration.d.ts index befe0350..3ae7fbfc 100644 --- a/src/renderer/src/declaration.d.ts +++ b/src/renderer/src/declaration.d.ts @@ -112,8 +112,15 @@ declare global { checkForUpdates: () => Promise; restartAndInstallUpdate: () => Promise; + /* Authg */ + signout: () => Promise; + onSignIn: (cb: () => void) => () => Electron.IpcRenderer; + onSignOut: (cb: () => void) => () => Electron.IpcRenderer; + + /* User */ + getUser: (username: string) => Promise; + /* Profile */ - getUserProfile: (username: string) => Promise; getMe: () => Promise; } diff --git a/src/renderer/src/pages/user/user-content.tsx b/src/renderer/src/pages/user/user-content.tsx index d738bb57..4c9a4c8e 100644 --- a/src/renderer/src/pages/user/user-content.tsx +++ b/src/renderer/src/pages/user/user-content.tsx @@ -2,7 +2,7 @@ import { ProfileGame, UserProfile } from "@types"; import cn from "classnames"; import * as styles from "./user.css"; import { SPACING_UNIT, vars } from "@renderer/theme.css"; -import { useMemo } from "react"; +import { useContext, useMemo } from "react"; import { useTranslation } from "react-i18next"; import SteamLogo from "@renderer/assets/steam-logo.svg?react"; import { useDate } from "@renderer/hooks"; @@ -10,6 +10,7 @@ import { useNavigate } from "react-router-dom"; import { buildGameDetailsPath } from "@renderer/helpers"; import { PersonIcon } from "@primer/octicons-react"; import { Button } from "@renderer/components"; +import { userAuthContext } from "@renderer/context/user-auth/user-auth.context"; const MAX_MINUTES_TO_SHOW_IN_PLAYTIME = 120; export interface ProfileContentProps { @@ -19,6 +20,8 @@ export interface ProfileContentProps { export const UserContent = ({ userProfile }: ProfileContentProps) => { const { t, i18n } = useTranslation("user_profile"); + const { userAuth, signout } = useContext(userAuthContext); + const navigate = useNavigate(); const numberFormatter = useMemo(() => { @@ -50,6 +53,11 @@ export const UserContent = ({ userProfile }: ProfileContentProps) => { navigate(buildGameDetailsPath(game)); }; + const handleSignout = async () => { + await signout(); + navigate("/"); + }; + return ( <>
{

{userProfile.displayName}

-
- -
+ {userAuth && userAuth.id == userProfile.id && ( +
+ +
+ )}
-

Atividade

+

{t("activity")}

{ gap: `${SPACING_UNIT * 2}px`, }} > -

Games

+

{t("games")}

{ {userProfile.libraryGames.length}
- Tempo total de jogo: {formatPlayTime()} + {t("total_play_time", { amount: formatPlayTime() })}
{ return ( <> - +
+ + +
); }; diff --git a/src/renderer/src/pages/user/user.tsx b/src/renderer/src/pages/user/user.tsx index 80f6125c..6ff48474 100644 --- a/src/renderer/src/pages/user/user.tsx +++ b/src/renderer/src/pages/user/user.tsx @@ -8,6 +8,7 @@ import { UserContent } from "./user-content"; import { SkeletonTheme } from "react-loading-skeleton"; import { vars } from "@renderer/theme.css"; import * as styles from "./user.css"; +import { UserAuthContextProvider } from "@renderer/context/user-auth/user-auth.context"; export const User = () => { const { username } = useParams(); @@ -16,7 +17,7 @@ export const User = () => { const dispatch = useAppDispatch(); useEffect(() => { - window.electron.getUserProfile(username!).then((userProfile) => { + window.electron.getUser(username!).then((userProfile) => { if (userProfile) { dispatch(setHeaderTitle(userProfile.displayName)); setUserProfile(userProfile); @@ -25,14 +26,16 @@ export const User = () => { }, [dispatch, username]); return ( - -
- {userProfile ? ( - - ) : ( - - )} -
-
+ + +
+ {userProfile ? ( + + ) : ( + + )} +
+
+
); }; diff --git a/src/types/index.ts b/src/types/index.ts index 47251dd2..c95f16d7 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -244,6 +244,12 @@ export interface RealDebridUser { expiration: string; } +export interface UserAuth { + id: string; + displayName: string; + profileImageUrl: string | null; +} + export interface UserProfile { id: string; displayName: string;