add logout button

This commit is contained in:
2025-12-23 15:42:02 +03:00
parent 797c53bfca
commit 869a513773
3 changed files with 76 additions and 1 deletions

View File

@@ -247,6 +247,31 @@ func main() {
sendJSON(w, AuthResponse{token}, 200) sendJSON(w, AuthResponse{token}, 200)
}) })
mux.HandleFunc("GET /user", func(w http.ResponseWriter, r *http.Request) {
userId, err := getUserIdFromRequest(r)
if err != nil {
sendApiError(w, "invalid token", err, 401)
return
}
row := db.QueryRowx("SELECT * FROM users WHERE id = ?", userId)
if row.Err() != nil {
sendApiError(w, "user not found", row.Err(), 401)
return
}
var user User
if err := row.StructScan(&user); err != nil {
sendApiError(w, "user not found", err, 401)
return
}
if err := sendJSON(w, user, 200); err != nil {
sendApiError(w, "user not found", err, 401)
return
}
})
mux.HandleFunc("GET /articles", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("GET /articles", func(w http.ResponseWriter, r *http.Request) {
userId, err := getUserIdFromRequest(r) userId, err := getUserIdFromRequest(r)
if err != nil { if err != nil {

View File

@@ -0,0 +1,19 @@
import { $axios } from "@/lib/axios";
import { useQuery } from "@tanstack/react-query";
export type User = {
id: number;
email: string;
created_at: string;
updated_at: string;
};
export const useUserQuery = () => {
return useQuery({
queryKey: ["user"],
queryFn: async () => {
const resp = await $axios.get<User>("/user");
return resp.data;
},
});
};

View File

@@ -1,7 +1,38 @@
"use client";
import { useUserQuery } from "@/api/auth/useUserQuery";
import { Button } from "@/components/ui/Button";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
export const Header = () => { export const Header = () => {
const queryClient = useQueryClient();
const router = useRouter();
const { data: user, error } = useUserQuery();
useEffect(() => {
if (error) {
document.cookie = `access_token=; SameSite=None; Secure; Expires=${new Date(0)}; Path=/`;
router.push("/login");
}
}, [error, router]);
const handleLogout = () => {
document.cookie = `access_token=; SameSite=None; Secure; Expires=${new Date(0)}; Path=/`;
queryClient.clear();
router.push("/login");
};
return ( return (
<header className="py-5 px-4 bg-accent"> <header className="py-5 px-4 bg-accent flex justify-between items-center">
<h1 className="text-3xl font-semibold text-secondary">archive.local</h1> <h1 className="text-3xl font-semibold text-secondary">archive.local</h1>
<div>
<Button size="small" onClick={handleLogout}>
Log out
</Button>
</div>
</header> </header>
); );
}; };