charliewilco / reubin

An RSS service for doomscrollers 🛰📡📰
reubin-site.vercel.app
Other
0 stars 1 forks source link

Signout in Header #43

Open charliewilco opened 1 year ago

charliewilco commented 1 year ago

For the API

import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { Auth } from "$/lib/auth";

export async function POST(request: Request) {
    const authRequest = Auth.handleRequest({ request, cookies });
    const { session } = await authRequest.validateUser();
    if (!session) {
        authRequest.setSession(null); // delete session cookie
        return NextResponse.json(null, {
            status: 401,
        });
    }
    await Auth.invalidateSession(session.sessionId);
    authRequest.setSession(null); // delete session cookie
    return new NextResponse(null, {
        status: 302,
        headers: {
            location: "/login",
        },
    });
}

For the UI

"use client";

import { useCallback, useState } from "react";
import { SuperButton } from "./ui/button";
import { Loader2 } from "lucide-react";

export function SignoutButton() {
    let [isLoading, setIsLoading] = useState(false);
    let handleClick = useCallback(async () => {
        try {
            setIsLoading(true);
            await fetch("/api/signout", {
                method: "POST",
            });
        } catch (error) {
        } finally {
            setIsLoading(false);
        }
    }, []);

    return (
        <SuperButton onClick={handleClick}> {isLoading ? <Loader2 /> : "Sign out"}</SuperButton>
    );
}