mirror of
https://github.com/khoaliber/LetterFeed.git
synced 2026-03-02 13:18:27 +00:00
feat: authentication
This commit is contained in:
@@ -8,8 +8,7 @@ const customJestConfig = {
|
||||
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
|
||||
testEnvironment: 'jest-environment-jsdom',
|
||||
moduleNameMapper: {
|
||||
'^@/components/(.*)$': '<rootDir>/components/$1',
|
||||
'^@/lib/(.*)$': '<rootDir>/src/lib/$1',
|
||||
'^@/(.*)$': '<rootDir>/src/$1',
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import '@testing-library/jest-dom';
|
||||
import fetchMock from 'jest-fetch-mock';
|
||||
|
||||
fetchMock.enableMocks();
|
||||
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AuthProvider } from "@/contexts/AuthContext"
|
||||
import type { Metadata } from "next"
|
||||
import { Geist, Geist_Mono } from "next/font/google"
|
||||
import "./globals.css"
|
||||
@@ -28,8 +29,10 @@ export default function RootLayout({
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
>
|
||||
{children}
|
||||
<Toaster />
|
||||
<AuthProvider>
|
||||
{children}
|
||||
<Toaster />
|
||||
</AuthProvider>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
|
||||
89
frontend/src/app/login/__tests__/page.test.tsx
Normal file
89
frontend/src/app/login/__tests__/page.test.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
import React from "react"
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react"
|
||||
import "@testing-library/jest-dom"
|
||||
import LoginPage from "@/app/login/page"
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
import { toast } from "sonner"
|
||||
|
||||
jest.mock("@/hooks/useAuth")
|
||||
jest.mock("sonner", () => ({
|
||||
toast: {
|
||||
error: jest.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockedUseAuth = useAuth as jest.Mock
|
||||
const mockedToast = toast as jest.Mocked<typeof toast>
|
||||
|
||||
describe("LoginPage", () => {
|
||||
const login = jest.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
mockedUseAuth.mockReturnValue({ login })
|
||||
})
|
||||
|
||||
it("renders the login page", () => {
|
||||
render(<LoginPage />)
|
||||
expect(screen.getByText("LetterFeed")).toBeInTheDocument()
|
||||
expect(screen.getByLabelText("Username")).toBeInTheDocument()
|
||||
expect(screen.getByLabelText("Password")).toBeInTheDocument()
|
||||
expect(screen.getByRole("button", { name: "Sign In" })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("allows typing in the username and password fields", () => {
|
||||
render(<LoginPage />)
|
||||
const usernameInput = screen.getByLabelText("Username")
|
||||
const passwordInput = screen.getByLabelText("Password")
|
||||
fireEvent.change(usernameInput, { target: { value: "test-user" } })
|
||||
fireEvent.change(passwordInput, { target: { value: "test-password" } })
|
||||
expect(usernameInput).toHaveValue("test-user")
|
||||
expect(passwordInput).toHaveValue("test-password")
|
||||
})
|
||||
|
||||
it("calls login on form submission with username and password", async () => {
|
||||
render(<LoginPage />)
|
||||
const usernameInput = screen.getByLabelText("Username")
|
||||
const passwordInput = screen.getByLabelText("Password")
|
||||
fireEvent.change(usernameInput, { target: { value: "test-user" } })
|
||||
fireEvent.change(passwordInput, { target: { value: "test-password" } })
|
||||
fireEvent.click(screen.getByRole("button", { name: "Sign In" }))
|
||||
await waitFor(() => {
|
||||
expect(login).toHaveBeenCalledWith("test-user", "test-password")
|
||||
})
|
||||
})
|
||||
|
||||
it("does not show an error if login fails, as it is handled by the api layer", async () => {
|
||||
login.mockRejectedValue(new Error("Invalid username or password"))
|
||||
render(<LoginPage />)
|
||||
const usernameInput = screen.getByLabelText("Username")
|
||||
const passwordInput = screen.getByLabelText("Password")
|
||||
fireEvent.change(usernameInput, { target: { value: "wrong-user" } })
|
||||
fireEvent.change(passwordInput, { target: { value: "wrong-password" } })
|
||||
fireEvent.click(screen.getByRole("button", { name: "Sign In" }))
|
||||
await waitFor(() => {
|
||||
expect(login).toHaveBeenCalled()
|
||||
expect(mockedToast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it("shows an error if username is not provided", async () => {
|
||||
render(<LoginPage />)
|
||||
const passwordInput = screen.getByLabelText("Password")
|
||||
fireEvent.change(passwordInput, { target: { value: "test-password" } })
|
||||
fireEvent.click(screen.getByRole("button", { name: "Sign In" }))
|
||||
await waitFor(() => {
|
||||
expect(mockedToast.error).toHaveBeenCalledWith("Please fill in all fields")
|
||||
})
|
||||
})
|
||||
|
||||
it("shows an error if password is not provided", async () => {
|
||||
render(<LoginPage />)
|
||||
const usernameInput = screen.getByLabelText("Username")
|
||||
fireEvent.change(usernameInput, { target: { value: "test-user" } })
|
||||
fireEvent.click(screen.getByRole("button", { name: "Sign In" }))
|
||||
await waitFor(() => {
|
||||
expect(mockedToast.error).toHaveBeenCalledWith("Please fill in all fields")
|
||||
})
|
||||
})
|
||||
})
|
||||
83
frontend/src/app/login/page.tsx
Normal file
83
frontend/src/app/login/page.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
"use client"
|
||||
|
||||
import type React from "react"
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import Image from "next/image"
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
import { toast } from "sonner"
|
||||
|
||||
export default function LoginPage() {
|
||||
const [username, setUsername] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const { login } = useAuth()
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!username || !password) {
|
||||
toast.error("Please fill in all fields")
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await login(username, password)
|
||||
} catch {
|
||||
// The error is already toasted by the API layer,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="max-w-md w-full space-y-8 p-8">
|
||||
<div className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<Image
|
||||
src="/logo.png"
|
||||
alt="LetterFeed Logo"
|
||||
width={48}
|
||||
height={48}
|
||||
className="rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<h2 className="text-3xl font-bold text-gray-900">LetterFeed</h2>
|
||||
<p className="mt-2 text-gray-600">Sign in to your account</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<form onSubmit={handleLogin} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">Username</Label>
|
||||
<Input
|
||||
id="username"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="Enter your username"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="Enter your password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full">
|
||||
Sign In
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useCallback } from "react"
|
||||
|
||||
import withAuth from "@/components/withAuth"
|
||||
import {
|
||||
getNewsletters,
|
||||
getSettings,
|
||||
@@ -15,7 +17,7 @@ import { EmptyState } from "@/components/letterfeed/EmptyState"
|
||||
import { NewsletterDialog } from "@/components/letterfeed/NewsletterDialog"
|
||||
import { SettingsDialog } from "@/components/letterfeed/SettingsDialog"
|
||||
|
||||
export default function LetterFeedApp() {
|
||||
function LetterFeedApp() {
|
||||
const [newsletters, setNewsletters] = useState<Newsletter[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [settings, setSettings] = useState<AppSettings | null>(null)
|
||||
@@ -103,3 +105,5 @@ export default function LetterFeedApp() {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default withAuth(LetterFeedApp)
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { processEmails } from "@/lib/api"
|
||||
import { Mail, Plus, Settings } from "lucide-react"
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
import { LogOut, Mail, Plus, Settings } from "lucide-react"
|
||||
import Image from "next/image"
|
||||
import { toast } from "sonner"
|
||||
|
||||
@@ -12,6 +13,7 @@ interface HeaderProps {
|
||||
}
|
||||
|
||||
export function Header({ onOpenAddNewsletter, onOpenSettings }: HeaderProps) {
|
||||
const { logout } = useAuth()
|
||||
const handleProcessEmails = async () => {
|
||||
try {
|
||||
await processEmails()
|
||||
@@ -59,6 +61,11 @@ export function Header({ onOpenAddNewsletter, onOpenSettings }: HeaderProps) {
|
||||
<Settings className="w-4 h-4 mr-2" />
|
||||
Settings
|
||||
</Button>
|
||||
|
||||
<Button variant="outline" onClick={logout}>
|
||||
<LogOut className="w-4 h-4 mr-2" />
|
||||
Logout
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -3,8 +3,14 @@ import { Header } from "../Header"
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
import { toast } from "sonner"
|
||||
import * as api from "@/lib/api"
|
||||
import { AuthProvider } from "@/contexts/AuthContext"
|
||||
|
||||
jest.mock("@/lib/api")
|
||||
jest.mock("next/navigation", () => ({
|
||||
useRouter: () => ({
|
||||
push: jest.fn(),
|
||||
}),
|
||||
}))
|
||||
const mockedApi = api as jest.Mocked<typeof api>
|
||||
|
||||
// Mock the toast functions
|
||||
@@ -24,6 +30,10 @@ describe("Header", () => {
|
||||
const onOpenSettings = jest.fn()
|
||||
const consoleError = jest.spyOn(console, "error").mockImplementation(() => {})
|
||||
|
||||
const renderWithAuthProvider = (component: React.ReactElement) => {
|
||||
return render(<AuthProvider>{component}</AuthProvider>)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
consoleError.mockClear()
|
||||
@@ -34,7 +44,7 @@ describe("Header", () => {
|
||||
})
|
||||
|
||||
it("renders the header with title and buttons", () => {
|
||||
render(
|
||||
renderWithAuthProvider(
|
||||
<Header
|
||||
onOpenAddNewsletter={onOpenAddNewsletter}
|
||||
onOpenSettings={onOpenSettings}
|
||||
@@ -47,7 +57,7 @@ describe("Header", () => {
|
||||
})
|
||||
|
||||
it('calls onOpenAddNewsletter when "Add Newsletter" button is clicked', () => {
|
||||
render(
|
||||
renderWithAuthProvider(
|
||||
<Header
|
||||
onOpenAddNewsletter={onOpenAddNewsletter}
|
||||
onOpenSettings={onOpenSettings}
|
||||
@@ -58,7 +68,7 @@ describe("Header", () => {
|
||||
})
|
||||
|
||||
it('calls onOpenSettings when "Settings" button is clicked', () => {
|
||||
render(
|
||||
renderWithAuthProvider(
|
||||
<Header
|
||||
onOpenAddNewsletter={onOpenAddNewsletter}
|
||||
onOpenSettings={onOpenSettings}
|
||||
@@ -71,7 +81,7 @@ describe("Header", () => {
|
||||
it('calls the process emails API when "Process Now" button is clicked and shows success toast', async () => {
|
||||
mockedApi.processEmails.mockResolvedValue({ message: "Success" })
|
||||
|
||||
render(
|
||||
renderWithAuthProvider(
|
||||
<>
|
||||
<Header
|
||||
onOpenAddNewsletter={onOpenAddNewsletter}
|
||||
@@ -97,7 +107,7 @@ describe("Header", () => {
|
||||
it("shows an error toast if the process emails API call fails", async () => {
|
||||
mockedApi.processEmails.mockRejectedValue(new Error("Failed to process"))
|
||||
|
||||
render(
|
||||
renderWithAuthProvider(
|
||||
<>
|
||||
<Header
|
||||
onOpenAddNewsletter={onOpenAddNewsletter}
|
||||
31
frontend/src/components/withAuth.tsx
Normal file
31
frontend/src/components/withAuth.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useEffect } from "react"
|
||||
import { LoadingSpinner } from "@/components/letterfeed/LoadingSpinner"
|
||||
|
||||
const withAuth = <P extends object>(
|
||||
WrappedComponent: React.ComponentType<P>
|
||||
) => {
|
||||
const WithAuthComponent = (props: P) => {
|
||||
const { isAuthenticated, isLoading } = useAuth()
|
||||
const router = useRouter()
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && !isAuthenticated) {
|
||||
router.push("/login")
|
||||
}
|
||||
}, [isAuthenticated, isLoading, router])
|
||||
|
||||
if (isLoading || !isAuthenticated) {
|
||||
return <LoadingSpinner />
|
||||
}
|
||||
|
||||
return <WrappedComponent {...props} />
|
||||
}
|
||||
|
||||
return WithAuthComponent
|
||||
}
|
||||
|
||||
export default withAuth
|
||||
74
frontend/src/contexts/AuthContext.tsx
Normal file
74
frontend/src/contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
"use client"
|
||||
|
||||
import { createContext, useState, useEffect, ReactNode } from "react"
|
||||
import { getAuthStatus, login as apiLogin, getSettings } from "@/lib/api"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
interface AuthContextType {
|
||||
isAuthenticated: boolean
|
||||
login: (username: string, password: string) => Promise<void>
|
||||
logout: () => void
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
export const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||
|
||||
export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const router = useRouter()
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const { auth_enabled } = await getAuthStatus();
|
||||
if (!auth_enabled) {
|
||||
setIsAuthenticated(true);
|
||||
} else {
|
||||
const token = localStorage.getItem("authToken");
|
||||
if (token) {
|
||||
// If a token exists, verify it by making a protected API call.
|
||||
// getSettings is a good candidate. If it fails with a 401,
|
||||
// the fetcher will remove the token and throw, which we catch here.
|
||||
await getSettings();
|
||||
setIsAuthenticated(true);
|
||||
} else {
|
||||
setIsAuthenticated(false);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// This will catch errors from getAuthStatus or getSettings.
|
||||
// If it was a 401, the token is already removed by the fetcher.
|
||||
setIsAuthenticated(false);
|
||||
console.error("Authentication check failed", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
const login = async (username: string, password: string) => {
|
||||
try {
|
||||
await apiLogin(username, password)
|
||||
setIsAuthenticated(true)
|
||||
router.push("/")
|
||||
} catch (error) {
|
||||
console.error("Login failed", error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem("authToken")
|
||||
setIsAuthenticated(false)
|
||||
router.push("/login")
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ isAuthenticated, login, logout, isLoading }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
163
frontend/src/contexts/__tests__/AuthContext.test.tsx
Normal file
163
frontend/src/contexts/__tests__/AuthContext.test.tsx
Normal file
@@ -0,0 +1,163 @@
|
||||
import React from "react"
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react"
|
||||
import "@testing-library/jest-dom"
|
||||
import { AuthProvider, AuthContext } from "@/contexts/AuthContext"
|
||||
import * as api from "@/lib/api"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
jest.mock("@/lib/api")
|
||||
jest.mock("next/navigation", () => ({
|
||||
useRouter: jest.fn(),
|
||||
}))
|
||||
|
||||
const mockedApi = api as jest.Mocked<typeof api>
|
||||
const mockedUseRouter = useRouter as jest.Mock
|
||||
|
||||
describe("AuthContext", () => {
|
||||
const push = jest.fn()
|
||||
const consoleError = jest.spyOn(console, "error").mockImplementation(() => {})
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
localStorage.clear()
|
||||
mockedUseRouter.mockReturnValue({ push })
|
||||
consoleError.mockClear()
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
|
||||
it("authenticates if auth is not enabled", async () => {
|
||||
mockedApi.getAuthStatus.mockResolvedValue({ auth_enabled: false })
|
||||
render(
|
||||
<AuthProvider>
|
||||
<AuthContext.Consumer>
|
||||
{(value) => (
|
||||
<span>
|
||||
Is Authenticated: {value?.isAuthenticated.toString()}
|
||||
</span>
|
||||
)}
|
||||
</AuthContext.Consumer>
|
||||
</AuthProvider>
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: true")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it("authenticates if auth is enabled and token is valid", async () => {
|
||||
mockedApi.getAuthStatus.mockResolvedValue({ auth_enabled: true })
|
||||
mockedApi.getSettings.mockResolvedValue({} as api.Settings) // Mock a successful protected call
|
||||
localStorage.setItem("authToken", "valid-token")
|
||||
render(
|
||||
<AuthProvider>
|
||||
<AuthContext.Consumer>
|
||||
{(value) => (
|
||||
<span>
|
||||
Is Authenticated: {value?.isAuthenticated.toString()}
|
||||
</span>
|
||||
)}
|
||||
</AuthContext.Consumer>
|
||||
</AuthProvider>
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: true")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it("does not authenticate if auth is enabled and no token", async () => {
|
||||
mockedApi.getAuthStatus.mockResolvedValue({ auth_enabled: true })
|
||||
render(
|
||||
<AuthProvider>
|
||||
<AuthContext.Consumer>
|
||||
{(value) => (
|
||||
<span>
|
||||
Is Authenticated: {value?.isAuthenticated.toString()}
|
||||
</span>
|
||||
)}
|
||||
</AuthContext.Consumer>
|
||||
</AuthProvider>
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: false")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it("does not authenticate if token is invalid", async () => {
|
||||
mockedApi.getAuthStatus.mockResolvedValue({ auth_enabled: true })
|
||||
mockedApi.getSettings.mockRejectedValue(new Error("Invalid token")) // Mock a failed protected call
|
||||
localStorage.setItem("authToken", "invalid-token")
|
||||
render(
|
||||
<AuthProvider>
|
||||
<AuthContext.Consumer>
|
||||
{(value) => (
|
||||
<span>
|
||||
Is Authenticated: {value?.isAuthenticated.toString()}
|
||||
</span>
|
||||
)}
|
||||
</AuthContext.Consumer>
|
||||
</AuthProvider>
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: false")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it("login works correctly", async () => {
|
||||
mockedApi.getAuthStatus.mockResolvedValue({ auth_enabled: true })
|
||||
mockedApi.login.mockResolvedValue()
|
||||
render(
|
||||
<AuthProvider>
|
||||
<AuthContext.Consumer>
|
||||
{(value) => (
|
||||
<>
|
||||
<span>
|
||||
Is Authenticated: {value?.isAuthenticated.toString()}
|
||||
</span>
|
||||
<button onClick={() => value?.login("testuser", "password")}>Login</button>
|
||||
</>
|
||||
)}
|
||||
</AuthContext.Consumer>
|
||||
</AuthProvider>
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: false")).toBeInTheDocument()
|
||||
})
|
||||
fireEvent.click(screen.getByText("Login"))
|
||||
await waitFor(() => {
|
||||
expect(mockedApi.login).toHaveBeenCalledWith("testuser", "password")
|
||||
expect(screen.getByText("Is Authenticated: true")).toBeInTheDocument()
|
||||
expect(push).toHaveBeenCalledWith("/")
|
||||
})
|
||||
})
|
||||
|
||||
it("logout works correctly", async () => {
|
||||
mockedApi.getAuthStatus.mockResolvedValue({ auth_enabled: true })
|
||||
mockedApi.getSettings.mockResolvedValue({} as api.Settings)
|
||||
localStorage.setItem("authToken", "valid-token")
|
||||
render(
|
||||
<AuthProvider>
|
||||
<AuthContext.Consumer>
|
||||
{(value) => (
|
||||
<>
|
||||
<span>
|
||||
Is Authenticated: {value?.isAuthenticated.toString()}
|
||||
</span>
|
||||
<button onClick={() => value?.logout()}>Logout</button>
|
||||
</>
|
||||
)}
|
||||
</AuthContext.Consumer>
|
||||
</AuthProvider>
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: true")).toBeInTheDocument()
|
||||
})
|
||||
fireEvent.click(screen.getByText("Logout"))
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: false")).toBeInTheDocument()
|
||||
expect(push).toHaveBeenCalledWith("/login")
|
||||
expect(localStorage.getItem("authToken")).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
12
frontend/src/hooks/useAuth.ts
Normal file
12
frontend/src/hooks/useAuth.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
"use client"
|
||||
|
||||
import { useContext } from "react"
|
||||
import { AuthContext } from "@/contexts/AuthContext"
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext)
|
||||
if (context === undefined) {
|
||||
throw new Error("useAuth must be used within an AuthProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
testImapConnection,
|
||||
processEmails,
|
||||
getFeedUrl,
|
||||
login,
|
||||
NewsletterCreate,
|
||||
NewsletterUpdate,
|
||||
SettingsCreate,
|
||||
@@ -25,19 +26,21 @@ jest.mock("sonner", () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
const mockFetch = (data: any, ok = true, statusText = "OK") => { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
const mockFetch = <T,>(data: T, ok = true, statusText = "OK") => {
|
||||
;(fetch as jest.Mock).mockResolvedValueOnce({
|
||||
ok,
|
||||
json: () => Promise.resolve(data),
|
||||
statusText,
|
||||
status: ok ? 200 : 400,
|
||||
})
|
||||
}
|
||||
|
||||
const mockFetchError = (data: any = {}, statusText = "Bad Request") => { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
const mockFetchError = (data: any = {}, statusText = "Bad Request", status = 400) => { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
;(fetch as jest.Mock).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: () => Promise.resolve(data),
|
||||
statusText,
|
||||
status,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -48,37 +51,53 @@ describe("API Functions", () => {
|
||||
// Reset the mock before each test
|
||||
;(fetch as jest.Mock).mockClear()
|
||||
;(toast.error as jest.Mock).mockClear()
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
describe("login", () => {
|
||||
it("should login successfully and store the token", async () => {
|
||||
const mockToken = { access_token: "test-token", token_type: "bearer" }
|
||||
mockFetch(mockToken)
|
||||
|
||||
await login("user", "pass")
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ username: "user", password: "pass" }),
|
||||
})
|
||||
expect(localStorage.getItem("authToken")).toBe("test-token")
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and clear token if login fails", async () => {
|
||||
mockFetchError({ detail: "Incorrect username or password" }, "Unauthorized", 401)
|
||||
localStorage.setItem("authToken", "old-token")
|
||||
|
||||
await expect(login("user", "wrong-pass")).rejects.toThrow("Incorrect username or password")
|
||||
expect(localStorage.getItem("authToken")).toBeNull()
|
||||
expect(toast.error).toHaveBeenCalledWith("Incorrect username or password")
|
||||
})
|
||||
})
|
||||
|
||||
describe("getNewsletters", () => {
|
||||
it("should fetch newsletters successfully", async () => {
|
||||
const mockNewsletters = [
|
||||
{ id: 1, name: "Newsletter 1", is_active: true, senders: [], entries_count: 5 },
|
||||
{ id: 2, name: "Newsletter 2", is_active: false, senders: [], entries_count: 10 },
|
||||
]
|
||||
it("should fetch newsletters successfully with auth token", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const mockNewsletters = [{ id: 1, name: "Newsletter 1" }]
|
||||
mockFetch(mockNewsletters)
|
||||
|
||||
const newsletters = await getNewsletters()
|
||||
expect(newsletters).toEqual(mockNewsletters)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/newsletters`, {})
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/newsletters`, {
|
||||
headers: { Authorization: "Bearer test-token" },
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if fetching newsletters fails with HTTP error", async () => {
|
||||
mockFetchError({}, "Not Found")
|
||||
await expect(getNewsletters()).rejects.toThrow("Failed to fetch newsletters: Not Found")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to fetch newsletters: Not Found")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if fetching newsletters fails with network error", async () => {
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(getNewsletters()).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("createNewsletter", () => {
|
||||
it("should create a newsletter successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const newNewsletter: NewsletterCreate = { name: "New Newsletter", sender_emails: ["test@example.com"], extract_content: false }
|
||||
const createdNewsletter = {
|
||||
id: 3,
|
||||
@@ -93,36 +112,23 @@ describe("API Functions", () => {
|
||||
expect(result).toEqual(createdNewsletter)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/newsletters`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: { "Content-Type": "application/json", Authorization: "Bearer test-token" },
|
||||
body: JSON.stringify(newNewsletter),
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if creating newsletter fails with HTTP error", async () => {
|
||||
const newNewsletter: NewsletterCreate = { name: "New Newsletter", sender_emails: [], extract_content: false }
|
||||
mockFetchError({}, "Conflict")
|
||||
await expect(createNewsletter(newNewsletter)).rejects.toThrow("Failed to create newsletter: Conflict")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to create newsletter: Conflict")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if creating newsletter fails with network error", async () => {
|
||||
const newNewsletter: NewsletterCreate = { name: "New Newsletter", sender_emails: [], extract_content: false }
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(createNewsletter(newNewsletter)).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("updateNewsletter", () => {
|
||||
it("should update a newsletter successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const updatedNewsletter: NewsletterUpdate = { name: "Updated Newsletter", sender_emails: ["updated@example.com"], extract_content: true }
|
||||
const newsletterId = 1
|
||||
const newsletterId = "1"
|
||||
const returnedNewsletter = {
|
||||
id: newsletterId,
|
||||
...updatedNewsletter,
|
||||
is_active: true,
|
||||
senders: [{ id: 1, email: "updated@example.com", newsletter_id: newsletterId }],
|
||||
senders: [{ id: "1", email: "updated@example.com" }],
|
||||
entries_count: 12,
|
||||
}
|
||||
mockFetch(returnedNewsletter)
|
||||
@@ -131,58 +137,31 @@ describe("API Functions", () => {
|
||||
expect(result).toEqual(returnedNewsletter)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/newsletters/${newsletterId}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: { "Content-Type": "application/json", Authorization: "Bearer test-token" },
|
||||
body: JSON.stringify(updatedNewsletter),
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if updating newsletter fails with HTTP error", async () => {
|
||||
const updatedNewsletter: NewsletterUpdate = { name: "Updated Newsletter", sender_emails: [], extract_content: true }
|
||||
const newsletterId = 1
|
||||
mockFetchError({}, "Bad Request")
|
||||
await expect(updateNewsletter(newsletterId, updatedNewsletter)).rejects.toThrow("Failed to update newsletter: Bad Request")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to update newsletter: Bad Request")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if updating newsletter fails with network error", async () => {
|
||||
const updatedNewsletter: NewsletterUpdate = { name: "Updated Newsletter", sender_emails: [], extract_content: true }
|
||||
const newsletterId = 1
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(updateNewsletter(newsletterId, updatedNewsletter)).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("deleteNewsletter", () => {
|
||||
it("should delete a newsletter successfully", async () => {
|
||||
const newsletterId = 1
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const newsletterId = "1"
|
||||
mockFetch({}, true) // Successful deletion might not have a body
|
||||
|
||||
await deleteNewsletter(newsletterId)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/newsletters/${newsletterId}`, {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: "Bearer test-token" },
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if deleting newsletter fails with HTTP error", async () => {
|
||||
const newsletterId = 1
|
||||
mockFetchError({}, "Forbidden")
|
||||
await expect(deleteNewsletter(newsletterId)).rejects.toThrow("Failed to delete newsletter: Forbidden")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to delete newsletter: Forbidden")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if deleting newsletter fails with network error", async () => {
|
||||
const newsletterId = 1
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(deleteNewsletter(newsletterId)).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("getSettings", () => {
|
||||
it("should fetch settings successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const mockSettings = {
|
||||
id: 1,
|
||||
imap_server: "imap.example.com",
|
||||
@@ -198,25 +177,16 @@ describe("API Functions", () => {
|
||||
|
||||
const settings = await getSettings()
|
||||
expect(settings).toEqual(mockSettings)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/settings`, {})
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/settings`, {
|
||||
headers: { Authorization: "Bearer test-token" },
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if fetching settings fails with HTTP error", async () => {
|
||||
mockFetchError({}, "Unauthorized")
|
||||
await expect(getSettings()).rejects.toThrow("Failed to fetch settings: Unauthorized")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to fetch settings: Unauthorized")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if fetching settings fails with network error", async () => {
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(getSettings()).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("updateSettings", () => {
|
||||
it("should update settings successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const newSettings: SettingsCreate = {
|
||||
imap_server: "new.imap.com",
|
||||
imap_username: "newuser@example.com",
|
||||
@@ -234,69 +204,31 @@ describe("API Functions", () => {
|
||||
expect(result).toEqual(updatedSettings)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/settings`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: { "Content-Type": "application/json", Authorization: "Bearer test-token" },
|
||||
body: JSON.stringify(newSettings),
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if updating settings fails with HTTP error", async () => {
|
||||
const newSettings: SettingsCreate = {
|
||||
imap_server: "new.imap.com",
|
||||
imap_username: "newuser@example.com",
|
||||
search_folder: "Archive",
|
||||
mark_as_read: false,
|
||||
email_check_interval: 120,
|
||||
auto_add_new_senders: true,
|
||||
}
|
||||
mockFetchError({}, "Internal Server Error")
|
||||
await expect(updateSettings(newSettings)).rejects.toThrow("Failed to update settings: Internal Server Error")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to update settings: Internal Server Error")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if updating settings fails with network error", async () => {
|
||||
const newSettings: SettingsCreate = {
|
||||
imap_server: "new.imap.com",
|
||||
imap_username: "newuser@example.com",
|
||||
search_folder: "Archive",
|
||||
mark_as_read: false,
|
||||
email_check_interval: 120,
|
||||
auto_add_new_senders: true,
|
||||
}
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(updateSettings(newSettings)).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("getImapFolders", () => {
|
||||
it("should fetch IMAP folders successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const mockFolders = ["INBOX", "Sent", "Archive"]
|
||||
mockFetch(mockFolders)
|
||||
|
||||
const folders = await getImapFolders()
|
||||
expect(folders).toEqual(mockFolders)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/folders`, {})
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/folders`, {
|
||||
headers: { Authorization: "Bearer test-token" },
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should return an empty array and show toast if fetching IMAP folders fails with HTTP error", async () => {
|
||||
mockFetchError({}, "Forbidden")
|
||||
const folders = await getImapFolders()
|
||||
expect(folders).toEqual([])
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to fetch IMAP folders: Forbidden")
|
||||
})
|
||||
|
||||
it("should return an empty array and show toast if fetching IMAP folders fails with network error", async () => {
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
const folders = await getImapFolders()
|
||||
expect(folders).toEqual([])
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("testImapConnection", () => {
|
||||
it("should test IMAP connection successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const mockResponse = { message: "Connection successful" }
|
||||
mockFetch(mockResponse)
|
||||
|
||||
@@ -304,32 +236,15 @@ describe("API Functions", () => {
|
||||
expect(result).toEqual(mockResponse)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/test`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: "Bearer test-token" },
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error with detail and show toast if testing IMAP connection fails with HTTP error", async () => {
|
||||
const errorMessage = "Invalid credentials"
|
||||
mockFetchError({ detail: errorMessage }, "Unauthorized")
|
||||
await expect(testImapConnection()).rejects.toThrow(errorMessage)
|
||||
expect(toast.error).toHaveBeenCalledWith(errorMessage)
|
||||
})
|
||||
|
||||
it("should throw a generic error and show toast if testing IMAP connection fails without detail with HTTP error", async () => {
|
||||
mockFetchError({}, "Bad Gateway")
|
||||
await expect(testImapConnection()).rejects.toThrow("Failed to test IMAP connection: Bad Gateway")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to test IMAP connection: Bad Gateway")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if testing IMAP connection fails with network error", async () => {
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(testImapConnection()).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("processEmails", () => {
|
||||
it("should process emails successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const mockResponse = { message: "Emails processed" }
|
||||
mockFetch(mockResponse)
|
||||
|
||||
@@ -337,43 +252,18 @@ describe("API Functions", () => {
|
||||
expect(result).toEqual(mockResponse)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/process`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: "Bearer test-token" },
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error with detail and show toast if processing emails fails with HTTP error", async () => {
|
||||
const errorMessage = "IMAP not configured"
|
||||
mockFetchError({ detail: errorMessage }, "Bad Request")
|
||||
await expect(processEmails()).rejects.toThrow(errorMessage)
|
||||
expect(toast.error).toHaveBeenCalledWith(errorMessage)
|
||||
})
|
||||
|
||||
it("should throw a generic error and show toast if processing emails fails without detail with HTTP error", async () => {
|
||||
mockFetchError({}, "Service Unavailable")
|
||||
await expect(processEmails()).rejects.toThrow("Failed to process emails: Service Unavailable")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to process emails: Service Unavailable")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if processing emails fails with network error", async () => {
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(processEmails()).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("getFeedUrl", () => {
|
||||
it("should return the correct feed URL", () => {
|
||||
const newsletterId = 123
|
||||
const newsletterId = "123"
|
||||
const expectedUrl = `${API_BASE_URL}/feeds/${newsletterId}`
|
||||
const url = getFeedUrl(newsletterId)
|
||||
expect(url).toBe(expectedUrl)
|
||||
})
|
||||
|
||||
it("should handle newsletterId being 0", () => {
|
||||
const newsletterId = 0
|
||||
const expectedUrl = `${API_BASE_URL}/feeds/0`
|
||||
const url = getFeedUrl(newsletterId)
|
||||
expect(url).toBe(expectedUrl)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -63,6 +63,14 @@ async function fetcher<T>(
|
||||
returnEmptyArrayOnFailure: boolean = false
|
||||
): Promise<T> {
|
||||
try {
|
||||
const token = localStorage.getItem("authToken");
|
||||
if (token) {
|
||||
options.headers = {
|
||||
...options.headers,
|
||||
'Authorization': `Bearer ${token}`,
|
||||
};
|
||||
}
|
||||
|
||||
const response = await fetch(url, options);
|
||||
if (!response.ok) {
|
||||
let errorText = `${errorMessagePrefix}: ${response.statusText}`;
|
||||
@@ -74,12 +82,22 @@ async function fetcher<T>(
|
||||
} catch (e) { // eslint-disable-line @typescript-eslint/no-unused-vars
|
||||
// ignore error if response is not JSON
|
||||
}
|
||||
|
||||
if (response.status === 401) {
|
||||
localStorage.removeItem("authToken");
|
||||
// Do not redirect here. The AuthContext will handle it.
|
||||
}
|
||||
|
||||
toast.error(errorText);
|
||||
if (returnEmptyArrayOnFailure) {
|
||||
return [] as T;
|
||||
}
|
||||
throw new Error(errorText);
|
||||
}
|
||||
// For login or delete, we might not have a body
|
||||
if (response.status === 204) {
|
||||
return {} as T;
|
||||
}
|
||||
return response.json();
|
||||
} catch (error) {
|
||||
if (error instanceof TypeError) {
|
||||
@@ -92,6 +110,34 @@ async function fetcher<T>(
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAuthStatus(): Promise<{ auth_enabled: boolean }> {
|
||||
return fetcher<{ auth_enabled: boolean }>(`${API_BASE_URL}/auth/status`, {}, "Failed to fetch auth status");
|
||||
}
|
||||
|
||||
export async function login(username: string, password: string): Promise<void> {
|
||||
const formData = new URLSearchParams();
|
||||
formData.append('username', username);
|
||||
formData.append('password', password);
|
||||
|
||||
try {
|
||||
const response = await fetcher<{ access_token: string }>(`${API_BASE_URL}/auth/login`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
}, "Login failed");
|
||||
|
||||
if (response.access_token) {
|
||||
localStorage.setItem("authToken", response.access_token);
|
||||
}
|
||||
} catch (error) {
|
||||
localStorage.removeItem("authToken");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export async function getNewsletters(): Promise<Newsletter[]> {
|
||||
return fetcher<Newsletter[]>(`${API_BASE_URL}/newsletters`, {}, "Failed to fetch newsletters");
|
||||
}
|
||||
|
||||
@@ -19,8 +19,7 @@
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"],
|
||||
"@/components/*": ["./components/*"]
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
|
||||
Reference in New Issue
Block a user