Added /users/me route, and handling auth in frontend

This commit is contained in:
cdricms
2025-01-17 15:37:01 +01:00
parent 5405cc50d9
commit eb9883a1c3
20 changed files with 453 additions and 68 deletions

View File

@@ -135,8 +135,10 @@ func AuthJWT(next http.Handler) http.Handler {
return
}
ctx := context.WithValue(r.Context(), "token", token)
// Call the next handler if the JWT is valid
next.ServeHTTP(w, r)
next.ServeHTTP(w, r.WithContext(ctx))
})
}

33
backend/api/get_me.go Normal file
View File

@@ -0,0 +1,33 @@
package api
import (
"net/http"
"fr.latosa-escrima/api/core"
"github.com/golang-jwt/jwt/v5"
)
func HandleGetMe(w http.ResponseWriter, r *http.Request) {
token, ok := r.Context().Value("token").(*jwt.Token)
if !ok {
core.JSONError{
Status: core.Error,
Message: "Couldn't retrieve your JWT.",
}.Respond(w, http.StatusInternalServerError)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
core.JSONError{
Status: core.Error,
Message: "Invalid token claims.",
}.Respond(w, http.StatusInternalServerError)
return
}
uuid := claims["user_id"].(string)
r.SetPathValue("user_uuid", uuid)
HandleGetUser(w, r)
}

View File

@@ -17,6 +17,21 @@ import (
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<html><body><h1>Hello, World!</h1></body></html>")
}
func Cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Allow all origins (can restrict to specific origins)
w.Header().Set("Access-Control-Allow-Origin", "*")
// Allow certain HTTP methods (you can customize these as needed)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
// Allow certain headers (you can add more as needed)
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// Handle OPTIONS pre-flight request
if r.Method == http.MethodOptions {
return
}
next.ServeHTTP(w, r)
})
}
func main() {
err := godotenv.Load()
@@ -52,10 +67,13 @@ func main() {
core.HandleRoutes(mux, map[string]core.Handler{
"/": {
Handler: handler,
Middlewares: []core.Middleware{api.Methods("post")}},
Middlewares: []core.Middleware{api.Methods("get")}},
"/users/login": {
Handler: api.HandleLogin,
Middlewares: []core.Middleware{api.Methods("POST")}},
"/users/me": {
Handler: api.HandleGetMe,
Middlewares: []core.Middleware{api.Methods("GET"), api.AuthJWT}},
"/users": {
Handler: api.HandleGetUsers,
Middlewares: []core.Middleware{api.Methods("GET"), api.AuthJWT}},
@@ -80,7 +98,7 @@ func main() {
})
fmt.Printf("Serving on port %s\n", port)
err = http.ListenAndServe(fmt.Sprintf(":%s", port), mux)
err = http.ListenAndServe(fmt.Sprintf(":%s", port), Cors(mux))
if err != nil {
fmt.Printf("Error starting server: %s\n", err)
}

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}
<SWRLayout>{children}</SWRLayout>
</body>
</html>
//</SWRConfig>
);
}

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,7 +103,8 @@ const Navbar = () => {
variant: "ghost",
}),
)}
href="/">
href="/"
>
Planning
</a>
<a

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

@@ -21,12 +21,14 @@
"@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",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-icons": "^5.4.0",
"swr": "^2.3.0",
"tailwind-merge": "^2.6.0",
"tailwindcss-animate": "^1.0.7"
},
@@ -2678,6 +2680,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",
@@ -2833,6 +2857,15 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/dequal": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
"integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/detect-libc": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz",
@@ -6321,6 +6354,19 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/swr": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/swr/-/swr-2.3.0.tgz",
"integrity": "sha512-NyZ76wA4yElZWBHzSgEJc28a0u6QZvhb6w0azeL2k7+Q1gAzVK+IqQYXhVOC/mzi+HZIozrZvBVeSeOZNR2bqA==",
"license": "MIT",
"dependencies": {
"dequal": "^2.0.3",
"use-sync-external-store": "^1.4.0"
},
"peerDependencies": {
"react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/tailwind-merge": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.0.tgz",
@@ -6670,6 +6716,15 @@
}
}
},
"node_modules/use-sync-external-store": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.4.0.tgz",
"integrity": "sha512-9WXSPC5fMv61vaupRkCKCxsPxBocVnwakBEkMIHHpkTTg6icbJtg6jzgtLDm4bl3cSHAca52rYWih0k4K3PfHw==",
"license": "MIT",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",

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",

View File

@@ -8,12 +8,4 @@ server {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /api {
proxy_pass http://localhost:BACKEND_PORT; # Set backend port based on what you have exposed
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}