feat: handle login from deeplink

This commit is contained in:
Zamitto 2024-06-16 13:58:24 -03:00
parent 55c214eae6
commit 32566e5dfc
17 changed files with 243 additions and 62 deletions

View File

@ -229,6 +229,10 @@
"amount_hours": "{{amount}} hours", "amount_hours": "{{amount}} hours",
"amount_minutes": "{{amount}} minutes", "amount_minutes": "{{amount}} minutes",
"play_time": "Played for {{amount}}", "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}}"
} }
} }

View File

@ -230,6 +230,10 @@
"amount_hours": "{{amount}} horas", "amount_hours": "{{amount}} horas",
"amount_minutes": "{{amount}} minutos", "amount_minutes": "{{amount}} minutos",
"play_time": "Jogado por {{amount}}", "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}}"
} }
} }

View File

@ -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<void> => {
await Promise.all([
userAuthRepository.delete({ id: 1 }),
HydraApi.post("/auth/logout"),
]).finally(() => {
if (WindowManager.mainWindow) {
WindowManager.mainWindow.webContents.send("on-signout");
}
});
};
registerEvent("signout", signout);

View File

@ -40,7 +40,8 @@ import "./download-sources/validate-download-source";
import "./download-sources/add-download-source"; import "./download-sources/add-download-source";
import "./download-sources/remove-download-source"; import "./download-sources/remove-download-source";
import "./download-sources/sync-download-sources"; import "./download-sources/sync-download-sources";
import "./profile/get-user-profile"; import "./auth/signout";
import "./user/get-user";
import "./profile/get-me"; import "./profile/get-me";
ipcMain.handle("ping", () => "pong"); ipcMain.handle("ping", () => "pong");

View File

@ -5,7 +5,7 @@ import { UserProfile } from "@types";
import { convertSteamGameToCatalogueEntry } from "../helpers/search-games"; import { convertSteamGameToCatalogueEntry } from "../helpers/search-games";
import { getSteamAppAsset } from "@main/helpers"; import { getSteamAppAsset } from "@main/helpers";
const getUserProfile = async ( const getUser = async (
_event: Electron.IpcMainInvokeEvent, _event: Electron.IpcMainInvokeEvent,
username: string username: string
): Promise<UserProfile | null> => { ): Promise<UserProfile | null> => {
@ -53,4 +53,4 @@ const getUserProfile = async (
} }
}; };
registerEvent("getUserProfile", getUserProfile); registerEvent("getUser", getUser);

View File

@ -7,6 +7,7 @@ import { DownloadManager, logger, WindowManager } from "@main/services";
import { dataSource } from "@main/data-source"; import { dataSource } from "@main/data-source";
import * as resources from "@locales"; import * as resources from "@locales";
import { userPreferencesRepository } from "@main/repository"; import { userPreferencesRepository } from "@main/repository";
import { HydraApi } from "./services/hydra-api";
const { autoUpdater } = updater; const { autoUpdater } = updater;
@ -71,7 +72,7 @@ app.on("browser-window-created", (_, window) => {
optimizer.watchWindowShortcuts(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. // Someone tried to run a second instance, we should focus our window.
if (WindowManager.mainWindow) { if (WindowManager.mainWindow) {
if (WindowManager.mainWindow.isMinimized()) if (WindowManager.mainWindow.isMinimized())
@ -83,7 +84,14 @@ app.on("second-instance", (_event, commandLine) => {
} }
const [, path] = commandLine.pop()?.split("://") ?? []; 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) => { app.on("open-url", (_event, url) => {

View File

@ -1,5 +1,6 @@
import { userAuthRepository } from "@main/repository"; import { userAuthRepository } from "@main/repository";
import axios, { AxiosError, AxiosInstance } from "axios"; import axios, { AxiosError, AxiosInstance } from "axios";
import { WindowManager } from "./window-manager";
export class HydraApi { export class HydraApi {
private static instance: AxiosInstance; private static instance: AxiosInstance;
@ -16,6 +17,38 @@ export class HydraApi {
return this.userAuth.authToken !== ""; 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() { static async setupApi() {
this.instance = axios.create({ this.instance = axios.create({
baseURL: import.meta.env.MAIN_VITE_API_URL, baseURL: import.meta.env.MAIN_VITE_API_URL,
@ -33,6 +66,8 @@ export class HydraApi {
} }
private static async revalidateAccessTokenIfExpired() { private static async revalidateAccessTokenIfExpired() {
if (!this.userAuth.authToken) throw new Error("user is not logged in");
const now = new Date(); const now = new Date();
if (this.userAuth.expirationTimestamp < now.getTime()) { if (this.userAuth.expirationTimestamp < now.getTime()) {
try { try {
@ -64,15 +99,11 @@ export class HydraApi {
this.userAuth.authToken = ""; this.userAuth.authToken = "";
this.userAuth.expirationTimestamp = 0; this.userAuth.expirationTimestamp = 0;
userAuthRepository.upsert( if (WindowManager.mainWindow) {
{ WindowManager.mainWindow.webContents.send("on-signout");
id: 1, }
accessToken: "",
refreshToken: "", userAuthRepository.delete({ id: 1 });
tokenExpirationTimestamp: 0,
},
["id"]
);
} }
throw err; throw err;

View File

@ -128,7 +128,21 @@ contextBridge.exposeInMainWorld("electron", {
restartAndInstallUpdate: () => ipcRenderer.invoke("restartAndInstallUpdate"), restartAndInstallUpdate: () => ipcRenderer.invoke("restartAndInstallUpdate"),
/* Profile */ /* Profile */
getUserProfile: (username: string) =>
ipcRenderer.invoke("getUserProfile", username),
getMe: () => ipcRenderer.invoke("getMe"), 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);
},
}); });

View File

@ -1,38 +1,25 @@
import { useEffect, useState } from "react"; import { useContext } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { type UserProfile } from "@types";
import * as styles from "./sidebar.css";
import { PersonIcon } from "@primer/octicons-react"; 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() { export function SidebarProfile() {
const navigate = useNavigate(); const navigate = useNavigate();
const [userProfile, setUserProfile] = useState<UserProfile | null>(null); const { userAuth, isLoading } = useContext(userAuthContext);
const [isUserProfileLoading, setIsUserProfileLoading] = useState(true);
const handleClickProfile = () => { const handleClickProfile = () => {
navigate(`/user/${userProfile!.id}`); navigate(`/user/${userAuth!.id}`);
}; };
const handleClickLogin = () => { const handleClickLogin = () => {
window.electron.openExternal("https://losbroxas.org"); window.electron.openExternal("https://losbroxas.org");
}; };
useEffect(() => { if (isLoading) return null;
setIsUserProfileLoading(true);
window.electron.isUserLoggedIn().then(async (isLoggedIn) => {
if (isLoggedIn) {
const userProfile = await window.electron.getMe();
setUserProfile(userProfile);
}
setIsUserProfileLoading(false); if (userAuth == null) {
});
}, []);
if (isUserProfileLoading) return null;
if (userProfile == null) {
return ( return (
<> <>
<button <button
@ -60,11 +47,11 @@ export function SidebarProfile() {
onClick={handleClickProfile} onClick={handleClickProfile}
> >
<div className={styles.profileAvatar}> <div className={styles.profileAvatar}>
{userProfile.profileImageUrl ? ( {userAuth.profileImageUrl ? (
<img <img
className={styles.profileAvatar} className={styles.profileAvatar}
src={userProfile.profileImageUrl} src={userAuth.profileImageUrl}
alt={userProfile.displayName} alt={userAuth.displayName}
/> />
) : ( ) : (
<PersonIcon /> <PersonIcon />
@ -72,7 +59,7 @@ export function SidebarProfile() {
</div> </div>
<div className={styles.profileButtonInformation}> <div className={styles.profileButtonInformation}>
<p style={{ fontWeight: "bold" }}>{userProfile.displayName}</p> <p style={{ fontWeight: "bold" }}>{userAuth.displayName}</p>
</div> </div>
</button> </button>
</> </>

View File

@ -14,6 +14,7 @@ import { buildGameDetailsPath } from "@renderer/helpers";
import SteamLogo from "@renderer/assets/steam-logo.svg?react"; import SteamLogo from "@renderer/assets/steam-logo.svg?react";
import { SidebarProfile } from "./sidebar-profile"; import { SidebarProfile } from "./sidebar-profile";
import { UserAuthContextProvider } from "@renderer/context/user-auth/user-auth.context";
const SIDEBAR_MIN_WIDTH = 200; const SIDEBAR_MIN_WIDTH = 200;
const SIDEBAR_INITIAL_WIDTH = 250; const SIDEBAR_INITIAL_WIDTH = 250;
@ -154,7 +155,9 @@ export function Sidebar() {
maxWidth: sidebarWidth, maxWidth: sidebarWidth,
}} }}
> >
<SidebarProfile /> <UserAuthContextProvider>
<SidebarProfile />
</UserAuthContextProvider>
<div <div
className={styles.content({ className={styles.content({

View File

@ -0,0 +1,73 @@
import { createContext, useEffect, useState } from "react";
import { UserAuthContext } from "./user-auth.context.types";
import { UserAuth } from "@types";
export const userAuthContext = createContext<UserAuthContext>({
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<UserAuth | null>(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 (
<Provider
value={{
userAuth,
signout,
updateMe,
isLoading,
}}
>
{children}
</Provider>
);
}

View File

@ -0,0 +1,8 @@
import { UserAuth } from "@types";
export interface UserAuthContext {
userAuth: UserAuth | null;
isLoading: boolean;
updateMe: () => Promise<void>;
signout: () => Promise<void>;
}

View File

@ -112,8 +112,15 @@ declare global {
checkForUpdates: () => Promise<boolean>; checkForUpdates: () => Promise<boolean>;
restartAndInstallUpdate: () => Promise<void>; restartAndInstallUpdate: () => Promise<void>;
/* Authg */
signout: () => Promise<void>;
onSignIn: (cb: () => void) => () => Electron.IpcRenderer;
onSignOut: (cb: () => void) => () => Electron.IpcRenderer;
/* User */
getUser: (username: string) => Promise<UserProfile | null>;
/* Profile */ /* Profile */
getUserProfile: (username: string) => Promise<UserProfile | null>;
getMe: () => Promise<UserProfile | null>; getMe: () => Promise<UserProfile | null>;
} }

View File

@ -2,7 +2,7 @@ import { ProfileGame, UserProfile } from "@types";
import cn from "classnames"; import cn from "classnames";
import * as styles from "./user.css"; import * as styles from "./user.css";
import { SPACING_UNIT, vars } from "@renderer/theme.css"; import { SPACING_UNIT, vars } from "@renderer/theme.css";
import { useMemo } from "react"; import { useContext, useMemo } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import SteamLogo from "@renderer/assets/steam-logo.svg?react"; import SteamLogo from "@renderer/assets/steam-logo.svg?react";
import { useDate } from "@renderer/hooks"; import { useDate } from "@renderer/hooks";
@ -10,6 +10,7 @@ import { useNavigate } from "react-router-dom";
import { buildGameDetailsPath } from "@renderer/helpers"; import { buildGameDetailsPath } from "@renderer/helpers";
import { PersonIcon } from "@primer/octicons-react"; import { PersonIcon } from "@primer/octicons-react";
import { Button } from "@renderer/components"; import { Button } from "@renderer/components";
import { userAuthContext } from "@renderer/context/user-auth/user-auth.context";
const MAX_MINUTES_TO_SHOW_IN_PLAYTIME = 120; const MAX_MINUTES_TO_SHOW_IN_PLAYTIME = 120;
export interface ProfileContentProps { export interface ProfileContentProps {
@ -19,6 +20,8 @@ export interface ProfileContentProps {
export const UserContent = ({ userProfile }: ProfileContentProps) => { export const UserContent = ({ userProfile }: ProfileContentProps) => {
const { t, i18n } = useTranslation("user_profile"); const { t, i18n } = useTranslation("user_profile");
const { userAuth, signout } = useContext(userAuthContext);
const navigate = useNavigate(); const navigate = useNavigate();
const numberFormatter = useMemo(() => { const numberFormatter = useMemo(() => {
@ -50,6 +53,11 @@ export const UserContent = ({ userProfile }: ProfileContentProps) => {
navigate(buildGameDetailsPath(game)); navigate(buildGameDetailsPath(game));
}; };
const handleSignout = async () => {
await signout();
navigate("/");
};
return ( return (
<> <>
<section <section
@ -72,15 +80,19 @@ export const UserContent = ({ userProfile }: ProfileContentProps) => {
<h2 style={{ fontWeight: "bold" }}>{userProfile.displayName}</h2> <h2 style={{ fontWeight: "bold" }}>{userProfile.displayName}</h2>
</div> </div>
<div style={{ flex: 1, display: "flex", justifyContent: "end" }}> {userAuth && userAuth.id == userProfile.id && (
<Button theme="danger">Sair da conta</Button> <div style={{ flex: 1, display: "flex", justifyContent: "end" }}>
</div> <Button theme="danger" onClick={handleSignout}>
{t("sign_out")}
</Button>
</div>
)}
</section> </section>
<div className={styles.profileContent}> <div className={styles.profileContent}>
<div className={styles.profileGameSection}> <div className={styles.profileGameSection}>
<div> <div>
<h2>Atividade</h2> <h2>{t("activity")}</h2>
</div> </div>
<div <div
style={{ style={{
@ -130,7 +142,7 @@ export const UserContent = ({ userProfile }: ProfileContentProps) => {
gap: `${SPACING_UNIT * 2}px`, gap: `${SPACING_UNIT * 2}px`,
}} }}
> >
<h2>Games</h2> <h2>{t("games")}</h2>
<div <div
style={{ style={{
@ -143,7 +155,7 @@ export const UserContent = ({ userProfile }: ProfileContentProps) => {
{userProfile.libraryGames.length} {userProfile.libraryGames.length}
</h3> </h3>
</div> </div>
<small>Tempo total de jogo: {formatPlayTime()}</small> <small>{t("total_play_time", { amount: formatPlayTime() })}</small>
<div <div
style={{ style={{
display: "grid", display: "grid",

View File

@ -5,7 +5,10 @@ export const UserSkeleton = () => {
return ( return (
<> <>
<Skeleton className={styles.profileHeaderSkeleton} /> <Skeleton className={styles.profileHeaderSkeleton} />
<Skeleton width={135} /> <div className={styles.profileContent}>
<Skeleton height={140} style={{ flex: 1 }} />
<Skeleton width={300} className={styles.contentSidebar} />
</div>
</> </>
); );
}; };

View File

@ -8,6 +8,7 @@ import { UserContent } from "./user-content";
import { SkeletonTheme } from "react-loading-skeleton"; import { SkeletonTheme } from "react-loading-skeleton";
import { vars } from "@renderer/theme.css"; import { vars } from "@renderer/theme.css";
import * as styles from "./user.css"; import * as styles from "./user.css";
import { UserAuthContextProvider } from "@renderer/context/user-auth/user-auth.context";
export const User = () => { export const User = () => {
const { username } = useParams(); const { username } = useParams();
@ -16,7 +17,7 @@ export const User = () => {
const dispatch = useAppDispatch(); const dispatch = useAppDispatch();
useEffect(() => { useEffect(() => {
window.electron.getUserProfile(username!).then((userProfile) => { window.electron.getUser(username!).then((userProfile) => {
if (userProfile) { if (userProfile) {
dispatch(setHeaderTitle(userProfile.displayName)); dispatch(setHeaderTitle(userProfile.displayName));
setUserProfile(userProfile); setUserProfile(userProfile);
@ -25,14 +26,16 @@ export const User = () => {
}, [dispatch, username]); }, [dispatch, username]);
return ( return (
<SkeletonTheme baseColor={vars.color.background} highlightColor="#444"> <UserAuthContextProvider>
<div className={styles.wrapper}> <SkeletonTheme baseColor={vars.color.background} highlightColor="#444">
{userProfile ? ( <div className={styles.wrapper}>
<UserContent userProfile={userProfile} /> {userProfile ? (
) : ( <UserContent userProfile={userProfile} />
<UserSkeleton /> ) : (
)} <UserSkeleton />
</div> )}
</SkeletonTheme> </div>
</SkeletonTheme>
</UserAuthContextProvider>
); );
}; };

View File

@ -244,6 +244,12 @@ export interface RealDebridUser {
expiration: string; expiration: string;
} }
export interface UserAuth {
id: string;
displayName: string;
profileImageUrl: string | null;
}
export interface UserProfile { export interface UserProfile {
id: string; id: string;
displayName: string; displayName: string;