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

Accounts #27

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"@hookform/resolvers": "^3.9.0",
"@marsidev/react-turnstile": "^1.0.2",
"@radix-ui/react-aspect-ratio": "^1.1.0",
"@radix-ui/react-avatar": "^1.1.0",
"@radix-ui/react-collapsible": "^1.1.0",
"@radix-ui/react-dialog": "^1.1.1",
"@radix-ui/react-dropdown-menu": "^2.1.1",
Expand All @@ -33,6 +34,7 @@
"clsx": "^2.1.1",
"epubjs": "^0.3.93",
"input-otp": "^1.2.4",
"jose": "^5.9.2",
"lucide-react": "^0.441.0",
"ofetch": "^1.3.4",
"react": "^18.3.1",
Expand Down
36 changes: 36 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions src/api/backend/auth/signin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,12 @@ export const login = (body: { code: string; ttkn: string }) => {
body,
});
};

export const refresh = (refreshToken: string) => {
return client<LoginResponse>("/_secure/refresh", {
method: "POST",
headers: {
Authorization: `Bearer ${refreshToken}`,
},
});
};
29 changes: 29 additions & 0 deletions src/api/backend/auth/sync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { authClient } from "../base";

export const syncUserData = async ({
username,
bookmarks,
preferences,
readingLists,
}: {
username?: string;
bookmarks?: string[];
preferences?: Record<string, unknown>;
readingLists?: Record<string, unknown>;
}) => {
await authClient<{ message: string }>("/_secure/sync", {
method: "POST",
body: {
username,
bookmarks,
preferences,
reading_lists: readingLists,
},
});
};

export const getUserData = async () => {
return authClient<{ bookmarks: string[]; preferences: Record<string, unknown>; reading_lists: Record<string, unknown> }>("/_secure/get", {
method: "GET",
});
};
50 changes: 49 additions & 1 deletion src/api/backend/base.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { useAuthStore } from "@/stores/auth";
import { useSettingsStore } from "@/stores/settings";
import { ofetch } from "ofetch";
import { refresh } from "./auth/signin";

export type BaseRequest<T> = {
export type BaseResponse<T> = {
results: T[];
};

Expand All @@ -10,3 +12,49 @@ const backendURL = useSettingsStore.getState().backendURL;
export const client = ofetch.create({
baseURL: backendURL + `/api`,
});

export const authClient = ofetch.create({
baseURL: backendURL + `/api`,
async onRequest(context) {
const { accessToken, refreshToken, tokenInfo } = useAuthStore.getState();

let accessTokenToSend = accessToken;

if (!tokenInfo) {
useAuthStore.getState().reset();
return;
}

const currentTime = Math.floor(Date.now() / 1000);
const expirationTime = tokenInfo.exp;
const timeLeft = expirationTime - currentTime;

if (timeLeft <= 10) {
try {
const response = await refresh(refreshToken);
if (response.access_token && response.refresh_token) {
const valid = useAuthStore.getState().setTokens(response.access_token, response.refresh_token);

if (!valid) {
useAuthStore.getState().reset();
return;
}
}
accessTokenToSend = response.access_token;
} catch {
useAuthStore.getState().reset();
return;
}
}

context.options.headers = {
...context.options.headers,
Authorization: `Bearer ${accessTokenToSend}`,
};
},
onResponseError(context) {
if (context.response?.status === 401) {
useAuthStore.getState().reset();
}
},
});
19 changes: 19 additions & 0 deletions src/api/backend/search/books.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { queryOptions } from "@tanstack/react-query";
import { BaseResponse, client } from "../base";
import { BookItem } from "../types";

export const searchBooksByMd5 = async (md5s: string[]) => {
if (!md5s.length) return null;
return client<BaseResponse<BookItem>>("/_secure/translate", {
query: {
md5: md5s.join(","),
},
});
};

export const searchBooksByMd5QueryOptions = (md5s: string[]) =>
queryOptions({
queryKey: ["search", "books", md5s],
queryFn: () => searchBooksByMd5(md5s),
enabled: !!md5s.length,
});
4 changes: 2 additions & 2 deletions src/api/backend/search/search.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { useQuery } from "@tanstack/react-query";
import { BaseRequest, client } from "../base";
import { BaseResponse, client } from "../base";
import { BookItem } from "../types";
import { SearchParams } from "./types";
import { getExternalDownloads } from "../downloads/external";

export const getBooks = (params: SearchParams) => {
return client<BaseRequest<BookItem>>("/books", {
return client<BaseResponse<BookItem>>("/books", {
query: params,
});
};
Expand Down
4 changes: 2 additions & 2 deletions src/components/books/bookmark.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ export function BookmarkButton({ book }: { book: BookItem }) {
const addBookmark = useBookmarksStore((state) => state.addBookmark);
const removeBookmark = useBookmarksStore((state) => state.removeBookmark);

const bookMarkedBook = useMemo(() => bookmarks.find((b) => b.md5 === book.md5), [bookmarks, book.md5]);
const bookMarkedBook = useMemo(() => bookmarks.find((b) => b === book.md5), [bookmarks, book.md5]);

return (
<TooltipProvider delayDuration={0}>
<Tooltip>
<TooltipTrigger asChild>
<Button size="icon" onClick={() => (bookMarkedBook ? removeBookmark(bookMarkedBook.md5) : addBookmark(book))} className="flex items-center gap-2">
<Button size="icon" onClick={() => (bookMarkedBook ? removeBookmark(bookMarkedBook) : addBookmark(book.md5))} className="flex items-center gap-2">
{bookMarkedBook ? <BookmarkMinus className="h-5 w-5" /> : <BookmarkPlus className="h-5 w-5" />}
</Button>
</TooltipTrigger>
Expand Down
2 changes: 1 addition & 1 deletion src/components/layout/clipboard-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function ClipBoardButton(props: ClipBoardButtonProps) {
navigator.clipboard.writeText(props.content);
setClickedOnClipBoard(true);
props.onClick?.();
toast.success("Link copied to clipboard");
toast.success("Copied to clipboard");

setTimeout(() => {
setClickedOnClipBoard(false);
Expand Down
28 changes: 25 additions & 3 deletions src/components/layout/menu.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import React from "react";
import { Ellipsis } from "lucide-react";
import { Ellipsis, LogOut } from "lucide-react";

import { cn } from "@/lib/utils";
import { useLayout } from "@/hooks/use-layout";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from "@/components/ui/tooltip";
import { Link } from "@tanstack/react-router";
import { Link, useRouteContext } from "@tanstack/react-router";
import { CollapseMenuButton } from "./collapse-menu-button";
import { useAuth } from "@/hooks/auth/use-auth";

interface MenuProps {
isOpen: boolean | undefined;
Expand All @@ -16,6 +16,10 @@ interface MenuProps {

export function Menu({ isOpen, closeSheetMenu }: MenuProps) {
const { menuList } = useLayout();
const { handleLogout } = useAuth();
const routeContext = useRouteContext({
from: "__root__",
});

return (
<ScrollArea className="[&>div>div[style]]:!block">
Expand Down Expand Up @@ -78,6 +82,24 @@ export function Menu({ isOpen, closeSheetMenu }: MenuProps) {
)}
</li>
))}

{routeContext.auth.isLoggedIn ? (
<li className="flex w-full grow items-end">
<TooltipProvider disableHoverableContent>
<Tooltip delayDuration={100}>
<TooltipTrigger asChild>
<Button onClick={handleLogout} variant="outline" className="mt-5 h-10 w-full justify-center">
<span className={cn(isOpen === false ? "" : "mr-4")}>
<LogOut size={18} />
</span>
<p className={cn("whitespace-nowrap", isOpen === false ? "hidden opacity-0" : "opacity-100")}>Log out</p>
</Button>
</TooltipTrigger>
{isOpen === false && <TooltipContent side="right">Log out</TooltipContent>}
</Tooltip>
</TooltipProvider>
</li>
) : null}
</ul>
</nav>
</ScrollArea>
Expand Down
2 changes: 2 additions & 0 deletions src/components/layout/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { SheetMenu } from "./sheet-menu";
import { useLayout } from "@/hooks/use-layout";
import { useLayoutStore } from "@/stores/layout";
import { ThemeToggle } from "./theme-toggle";
import { UserNav } from "./user-nav";

export function Navbar() {
const { pageTitle } = useLayout();
Expand All @@ -21,6 +22,7 @@ export function Navbar() {
<h1 className="font-bold">{pageTitle ?? pageTitleFromStore}</h1>
</div>
<div className="flex flex-1 items-center justify-end space-x-2">
<UserNav />
<ThemeToggle />
</div>
</div>
Expand Down
69 changes: 69 additions & 0 deletions src/components/layout/user-nav.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { LogOut } from "lucide-react";
import { useEffect } from "react";
import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuTrigger } from "../ui/dropdown-menu";
import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "../ui/tooltip";
import { Button } from "../ui/button";
import { useAuth } from "@/hooks/auth/use-auth";
import { useAuthStore } from "@/stores/auth";
import Logo from "@/assets/logo.svg";
import { useRouteContext } from "@tanstack/react-router";

export function UserNav() {
const { handleLogout } = useAuth();
const displayName = useAuthStore((state) => state.displayName);

const routeContext = useRouteContext({
from: "__root__",
});

useEffect(() => {
window.addEventListener("keydown", (e) => {
if (e.key === "q" && (e.ctrlKey || e.metaKey)) {
handleLogout();
}
});

return () => {
window.removeEventListener("keydown", () => {});
};
});

if (!routeContext.auth.isLoggedIn) return null;

return (
<DropdownMenu>
<TooltipProvider disableHoverableContent>
<Tooltip delayDuration={100}>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="relative h-8 w-8 rounded-full">
<Avatar className="h-8 w-8">
<AvatarImage src={Logo} />
<AvatarFallback>BR</AvatarFallback>
</Avatar>
</Button>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent side="bottom">Profile</TooltipContent>
</Tooltip>
</TooltipProvider>

<DropdownMenuContent className="w-56" align="end" forceMount>
<DropdownMenuLabel className="font-normal">
<div className="flex flex-col space-y-1">
<p className="text-sm font-medium leading-none">{displayName}</p>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem className="hover:cursor-pointer" onClick={handleLogout}>
<LogOut className="mr-3 h-4 w-4 text-muted-foreground" />
<span>Log out</span>
<DropdownMenuShortcut>⇧⌘Q</DropdownMenuShortcut>
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
);
}
Loading
Loading