Merge branch 'dev/cedric' into dev/guerby

This commit is contained in:
gom-by
2025-01-17 15:40:06 +01:00
26 changed files with 515 additions and 97 deletions

View File

@@ -1,8 +1,15 @@
import { GalleryVerticalEnd } from "lucide-react";
import Image from "next/image";
import { LoginForm } from "@/components/login-form";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
export default async function LoginPage() {
const cookiesObj = await cookies();
const token = cookiesObj.get("auth_token")?.value;
if (token) redirect("/dashboard");
export default function LoginPage() {
return (
<div className="grid min-h-svh lg:grid-cols-2">
<div className="flex flex-col gap-4 p-6 md:p-10">
@@ -13,7 +20,9 @@ export default function LoginPage() {
</div>
</div>
<div className="relative hidden bg-muted lg:block">
<img
<Image
width={20}
height={20}
src="/placeholder.svg"
alt="Image"
className="absolute inset-0 h-full w-full object-cover dark:brightness-[0.2] dark:grayscale"

View File

@@ -1,7 +1,7 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "@/app/globals.css";
import { SWRConfig } from "swr";
import SWRLayout from "@/components/layouts/swr-layout";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -24,19 +24,12 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
//<SWRConfig
// value={{
// fetcher: (url: string) => fetch(url).then((res) => res.json()),
// revalidateOnFocus: false,
// }}
//>
<html lang="fr">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html>
//</SWRConfig>
<html lang="fr">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<SWRLayout>{children}</SWRLayout>
</body>
</html>
);
}

View File

@@ -10,6 +10,7 @@ import {
GalleryVerticalEnd,
Settings2,
Calendar,
Loader2,
} from "lucide-react";
import { NavMain } from "@/components/nav-main";
@@ -23,6 +24,8 @@ import {
SidebarHeader,
SidebarRail,
} from "@/components/ui/sidebar";
import useMe from "@/hooks/use-me";
import { useEffect } from "react";
// This is sample data.
const data = {
@@ -93,6 +96,8 @@ const data = {
};
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const { user, isLoading, success, error } = useMe();
return (
<Sidebar collapsible="icon" {...props}>
<SidebarHeader>
@@ -102,7 +107,11 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
<NavMain items={data.navMain} />
</SidebarContent>
<SidebarFooter>
<NavUser user={data.user} />
{isLoading ? (
<Loader2 className="flex w-full min-w-0 flex-col gap-1 justify-center animate-spin" />
) : (
<NavUser user={user!} />
)}
</SidebarFooter>
<SidebarRail />
</Sidebar>

View File

@@ -0,0 +1,27 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Hammed Abass. <3 All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
"use client";
import { SWRConfig } from "swr";
interface SWRLayoutProps {
children: React.ReactNode;
}
const SWRLayout: React.FC<SWRLayoutProps> = ({ children }) => (
<SWRConfig
value={{
fetcher: (url: string) =>
fetch(url, { credentials: "include" }).then((res) =>
res.json(),
),
revalidateOnFocus: false,
}}
>
{children}
</SWRConfig>
);
export default SWRLayout;

View File

@@ -1,14 +1,39 @@
"use client";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useState } from "react";
import { useRouter } from "next/navigation";
import useLogin from "@/hooks/use-login";
import { Loader2 } from "lucide-react";
export function LoginForm({
className,
...props
}: React.ComponentPropsWithoutRef<"form">) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const { login, loading, isSuccess } = useLogin();
const router = useRouter();
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
try {
const res = await login({ email, password });
if (res.status === "Success") router.push("/dashboard");
console.log(res);
} catch (err: any) {
console.log(err.message);
}
};
return (
<form className={cn("flex flex-col gap-6", className)} {...props}>
<form
onSubmit={handleSubmit}
className={cn("flex flex-col gap-6", className)}
{...props}
>
<div className="flex flex-col items-center gap-2 text-center">
<h1 className="text-2xl font-bold">
Connectez-vous à votre compte.
@@ -23,6 +48,9 @@ export function LoginForm({
<Input
id="email"
type="email"
value={email}
disabled={loading}
onChange={(e) => setEmail(e.currentTarget.value)}
placeholder="m@example.com"
required
/>
@@ -37,9 +65,21 @@ export function LoginForm({
Forgot your password?
</a>
</div>
<Input id="password" type="password" required />
<Input
value={password}
onChange={(e) => setPassword(e.currentTarget.value)}
disabled={loading}
id="password"
type="password"
required
/>
</div>
<Button type="submit" className="w-full">
<Button
disabled={loading}
type="submit"
className="w-full transition-all ease-in-out"
>
{loading && <Loader2 className="animate-spin" />}
Se connecter
</Button>
<div className="relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t after:border-border">

View File

@@ -68,7 +68,7 @@ const subMenuItemsTwo = [
const Navbar = () => {
return (
<section className="p-4 bg-white top-0 sticky z-[100]">
<section className="p-4 bg-white top-0 sticky z-50">
<div>
<nav className="hidden justify-between lg:flex">
<div className="flex items-center gap-6">
@@ -103,8 +103,9 @@ const Navbar = () => {
variant: "ghost",
}),
)}
href="/">
Planning
href="/"
>
Planning
</a>
<a
className={cn(

View File

@@ -25,17 +25,16 @@ import {
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar";
import { deleteCookie } from "cookies-next";
import { useRouter } from "next/navigation";
import IUser from "@/interfaces/IUser";
export function NavUser({
user,
}: {
user: {
name: string;
email: string;
avatar: string;
};
}) {
export const NavUser: React.FC<{ user: IUser }> = ({ user }) => {
const { isMobile } = useSidebar();
const router = useRouter();
const name = `${user.firstname} ${user.lastname}`;
const image = `https://avatar.vercel.sh/${name}`;
return (
<SidebarMenu>
@@ -47,17 +46,14 @@ export function NavUser({
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
>
<Avatar className="h-8 w-8 rounded-lg">
<AvatarImage
src={user.avatar}
alt={user.name}
/>
<AvatarImage src={image} alt={name} />
<AvatarFallback className="rounded-lg">
CN
</AvatarFallback>
</Avatar>
<div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-semibold">
{user.name}
{name}
</span>
<span className="truncate text-xs">
{user.email}
@@ -75,17 +71,14 @@ export function NavUser({
<DropdownMenuLabel className="p-0 font-normal">
<div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
<Avatar className="h-8 w-8 rounded-lg">
<AvatarImage
src={user.avatar}
alt={user.name}
/>
<AvatarImage src={image} alt={name} />
<AvatarFallback className="rounded-lg">
CN
</AvatarFallback>
</Avatar>
<div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-semibold">
{user.name}
{name}
</span>
<span className="truncate text-xs">
{user.email}
@@ -116,7 +109,12 @@ export function NavUser({
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem>
<DropdownMenuItem
onClick={async () => {
await deleteCookie("auth_token");
router.push("/");
}}
>
<LogOut />
Log out
</DropdownMenuItem>
@@ -125,4 +123,4 @@ export function NavUser({
</SidebarMenuItem>
</SidebarMenu>
);
}
};

109
frontend/hooks/use-api.tsx Normal file
View File

@@ -0,0 +1,109 @@
"use client";
import { API_URL } from "@/lib/constants";
import { getCookie } from "cookies-next";
import useSWR, { SWRConfiguration } from "swr";
import useSWRMutation, { type SWRMutationConfiguration } from "swr/mutation";
export interface ApiResponse<T> {
status: "Error" | "Success";
message: string;
data?: T;
}
async function request<T>(
url: string,
options: {
method?: "GET" | "POST" | "PATCH" | "DELETE";
body?: any;
requiresAuth?: boolean;
} = {},
): Promise<ApiResponse<T>> {
const { method = "GET", body, requiresAuth = true } = options;
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (requiresAuth) {
const authToken = getCookie("auth_token");
if (!authToken) {
throw new Error("User is not authenticated");
}
headers.Authorization = `Bearer ${authToken}`;
}
const response = await fetch(`${API_URL}${url}`, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
});
const apiResponse: ApiResponse<T> = await response.json();
if (apiResponse.status === "Error") {
throw new Error(apiResponse.message || "An unexpected error occurred");
}
return apiResponse;
}
async function fetcher<T>(
url: string,
requiresAuth: boolean = true,
): Promise<ApiResponse<T>> {
return request(url, { requiresAuth });
}
async function mutationHandler<T, A>(
url: string,
{
arg,
method,
requiresAuth,
}: {
arg: A;
method: "GET" | "POST" | "PATCH" | "DELETE";
requiresAuth: boolean;
},
): Promise<ApiResponse<T>> {
return request(url, { method, body: arg, requiresAuth });
}
export function useApi<T>(
url: string,
config?: SWRConfiguration,
requiresAuth: boolean = true,
) {
const swr = useSWR<ApiResponse<T>>(
url,
() => fetcher(url, requiresAuth),
config,
);
return {
...swr,
data: swr.data?.data,
isLoading: swr.isLoading || swr.isValidating,
success: swr.data?.status === "Success",
};
}
export default function useApiMutation<T, A>(
endpoint: string,
config?: SWRMutationConfiguration<ApiResponse<T>, Error, string, A>,
method: "GET" | "POST" | "PATCH" | "DELETE" = "GET",
requiresAuth: boolean = false,
) {
const mutation = useSWRMutation<ApiResponse<T>, Error, string, A>(
endpoint,
(url, { arg }) => mutationHandler(url, { arg, method, requiresAuth }),
config,
);
return {
...mutation,
trigger: mutation.trigger as (
arg: A,
) => Promise<ApiResponse<T> | undefined>,
data: mutation.data?.data,
isSuccess: mutation.data?.status === "Success",
};
}

View File

@@ -0,0 +1,31 @@
"use client";
import { setCookie } from "cookies-next";
import useApiMutation from "./use-api";
export interface LoginArgs {
email: string;
password: string;
}
export default function useLogin() {
const {
trigger,
isMutating: loading,
isSuccess,
} = useApiMutation<string, LoginArgs>("/users/login", undefined, "POST");
const login = async (inputs: LoginArgs) => {
try {
const res = await trigger(inputs);
if (!res) throw new Error("The server hasn't responded.");
if (res.status === "Error") throw new Error(res.message);
if (res.data) setCookie("auth_token", res.data);
return res;
} catch (error: any) {
throw new Error(error.message);
}
};
return { login, loading, isSuccess };
}

16
frontend/hooks/use-me.tsx Normal file
View File

@@ -0,0 +1,16 @@
"use client";
import IUser from "@/interfaces/IUser";
import { useApi } from "./use-api";
export default function useMe() {
const {
data: user,
isLoading,
mutate,
error,
success,
} = useApi<IUser>("/users/me", undefined, true);
return { user, isLoading, success, error, mutate };
}

View File

@@ -0,0 +1,10 @@
export default interface IUser {
userId: string;
firstname: string;
lastname: string;
email: string;
phone: string;
role: string;
createdAt: Date;
updatedAt: Date;
}

View File

@@ -0,0 +1 @@
export const API_URL = `http://localhost:${process.env.NEXT_PUBLIC_BACKEND_PORT}`;

43
frontend/middleware.ts Normal file
View File

@@ -0,0 +1,43 @@
import { NextRequest, NextResponse } from "next/server";
import { ApiResponse } from "./hooks/use-api";
import { API_URL } from "./lib/constants";
import IUser from "./interfaces/IUser";
export async function middleware(request: NextRequest) {
const sessionCookie = request.cookies.get("auth_token")?.value;
if (!sessionCookie) {
return NextResponse.redirect(
new URL(
`/login?redirectTo=${encodeURIComponent(request.url)}`,
request.url,
),
);
}
try {
const res = await fetch(`${API_URL}/users/me`, {
headers: { Authorization: `Bearer ${sessionCookie}` },
});
const js: ApiResponse<IUser> = await res.json();
if (js.status === "Error")
return NextResponse.redirect(
new URL(
`/login?redirectTo=${encodeURIComponent(request.url)}`,
request.url,
),
);
} catch (e: any) {
return NextResponse.redirect(
new URL(
`/login?redirectTo=${encodeURIComponent(request.url)}`,
request.url,
),
);
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"],
};

View File

@@ -3,19 +3,16 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
output: "standalone",
async redirects() {
if (!process.env.BACKEND_PORT) {
throw new Error(
"Environment variable BACKEND_PORT is not defined.",
);
}
return [
images: {
remotePatterns: [
{
source: "/api/:path",
destination: `http://localhost:${process.env.BACKEND_PORT}/:path`,
permanent: false,
protocol: "https",
hostname: "avatar.vercel.sh",
},
];
],
},
env: {
NEXT_PUBLIC_BACKEND_PORT: process.env.BACKEND_PORT,
},
};

View File

@@ -22,6 +22,7 @@
"@radix-ui/react-tooltip": "^1.1.6",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cookies-next": "^5.1.0",
"embla-carousel-react": "^8.5.2",
"lucide-react": "^0.471.1",
"next": "15.1.4",
@@ -2734,6 +2735,28 @@
"dev": true,
"license": "MIT"
},
"node_modules/cookie": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz",
"integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/cookies-next": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/cookies-next/-/cookies-next-5.1.0.tgz",
"integrity": "sha512-9Ekne+q8hfziJtnT9c1yDUBqT0eDMGgPrfPl4bpR3xwQHLTd/8gbSf6+IEkP/pjGsDZt1TGbC6emYmFYRbIXwQ==",
"license": "MIT",
"dependencies": {
"cookie": "^1.0.1"
},
"peerDependencies": {
"next": ">=15.0.0",
"react": ">= 16.8.0"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",

View File

@@ -23,6 +23,7 @@
"@radix-ui/react-tooltip": "^1.1.6",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cookies-next": "^5.1.0",
"embla-carousel-react": "^8.5.2",
"lucide-react": "^0.471.1",
"next": "15.1.4",