Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

suggestions dialog works #44

Merged
merged 9 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 35 additions & 12 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,50 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Toaster } from '@/components/Toaster';

import LandingPage from './pages/LandingPage';
import DeveloperPage from './pages/DeveloperPage';
import LoginPage from './pages/LoginPage';
import NotfoundPage from './pages/NotfoundPage';
import UnauthorizedPage from './pages/UnauthorizedPage';
import AuthenticatedAdminPage from './pages/admin/AdminPage';
import AuthenticatedSuggestionsPage from './pages/admin/SuggestionsPage';

import './App.css';
import Background from './components/Background';
import { useAuth } from './context/useAuth';

const queryClient = new QueryClient()

function App() {
const { user } = useAuth();

return (
<QueryClientProvider client={queryClient}>
<Toaster />
<Router>
<Routes>
{/* public routes */}
<Route path="/" element={<LandingPage />} />
<Route path="/login" element={<LoginPage />} />

{/* protected routes */}
<Route path="/dev" element={<DeveloperPage />} />
</Routes>
</Router>
<Toaster />
<Router>
<Routes>
{/* public routes */}
<Route path="/" element={<LandingPage />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/unauthorized" element={<UnauthorizedPage />} />

{/* admin routes */}
<Route path="/admin" element={<AuthenticatedAdminPage />} />
<Route path="/admin/suggestions" element={<AuthenticatedSuggestionsPage />} />
<Route path="/admin/quests" element={<div>Admin Quests</div>} />
<Route path="/admin/users" element={<div>Admin Users</div>} />

{/* user routes */}
<Route path="*" element={<NotfoundPage />} />
</Routes>
</Router>

{
user &&
<div className="fixed top-0 right-0 flex flex-col justify-end m-4 text-white">
<span className="text-right">{user.username} ({user.role})</span>
</div>
}

<Background />
</QueryClientProvider>
)
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/LoginPanel/LoginPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
import { Input } from "../ui/input";

import AuthService from "@/service/authService";
import useAuth from "@/hooks/useAuth";
import { useAuth } from "@/context/useAuth";

interface LoginPanelProps {
onLoginSuccess: () => void;
Expand Down
145 changes: 62 additions & 83 deletions src/components/SuggestionsPanel/SuggestionsPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,121 +1,100 @@
import React, { useEffect, useState } from "react";

import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "../ui/input";
import { Textarea } from "../ui/textarea";
import { useMutation } from "@tanstack/react-query";
import React, { useState } from "react";

import CreateSuggestionRequest from "@/models/SuggestionModels/CreateSuggestionRequest";
import suggestionService from "@/service/suggestionService";
import useAuth from "@/hooks/useAuth";
import { toast } from "../Toaster";
import { AxiosError } from "axios";
import { useAuth } from "@/context/useAuth";

const SuggestionsPanel = () => {
const [open, setOpen] = useState(false);
const [suggestion, setSuggestion] = useState("");
const [title, setTitle] = useState("");
type SuggestionsPanelProps = {
onClose: () => void;
};

const SuggestionsPanel: React.FC<SuggestionsPanelProps> = (props) => {
const {
onClose,
} = props;
const { accessToken } = useAuth();
const [error, setError] = useState<string | null>(null);

const mutation = useMutation({
mutationFn: (newSuggestion: CreateSuggestionRequest) => {
return suggestionService.createSuggestion(newSuggestion, accessToken!);
},
onSuccess: () => {
setOpen(false);
},
});

useEffect(() => {
if (!open) {
setTitle("");
setSuggestion("");
}
}, [open]);

const handleSubmit = (event: React.FormEvent) => {
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
const form = event.target as HTMLFormElement;

try {
const newSuggestion = {
title: (form.elements.namedItem("title") as HTMLInputElement).value,
description: (form.elements.namedItem("description") as HTMLTextAreaElement).value,
} as CreateSuggestionRequest;

mutation.mutateAsync({ title, description: suggestion });
await suggestionService.createSuggestion(newSuggestion, accessToken!);
toast.success("Suggestion submitted successfully!");
onClose();
} catch (error: unknown) {
if (error instanceof AxiosError && error.response) {
setError(error.response.data.error);
} else {
setError("An unexpected error occurred.");
}
}
};


return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<button
className=""
onClick={() => setOpen(true)}
>
SUGGESTIONS
</button>
</DialogTrigger>
<DialogContent
className="bg-slate-100"
onCloseAutoFocus={(event) => {
event.preventDefault();
}}
>
<DialogHeader>
<DialogTitle className='text-muted-foreground'>Suggestions</DialogTitle>
<DialogDescription>
Suggest a quest or feature for the app
</DialogDescription>
</DialogHeader>
<div className="fixed inset-0 z-50 flex items-center justify-center">
<div className="w-full max-w-md p-4 rounded-md shadow-lg bg-slate-100">
<div className="mb-4">
<h2 className="text-lg font-semibold text-muted-foreground">Suggestions</h2>
<p className="text-sm text-gray-600">
Suggest a quest or feature
</p>
</div>
<form className="flex flex-col" onSubmit={handleSubmit}>
<div className="p-2">
<label htmlFor="title" className="sr-only">
Title"
</label>
<Input
<label htmlFor="title" className="sr-only">Title</label>
<input
id="title"
name="title"
type="text"
placeholder="Title"
value={title}
onChange={(e) => setTitle(e.target.value)}
className="w-full p-2 border border-gray-300 rounded-md"
/>
</div>
<div className="p-2">
<label htmlFor="suggestion" className="sr-only">
Suggestion
</label>
<Textarea
id="suggestion"
placeholder="Suggestion"
value={suggestion}
onChange={(e) => setSuggestion(e.target.value)}
<label htmlFor="description" className="sr-only">Suggestion</label>
<textarea
id="description"
name="description"
placeholder="Details of Suggestion, if this is a quest, please include the quest details and potential objectives"
className="w-full p-2 border border-gray-300 rounded-md"
/>
</div>

{
mutation.isError && (
<span className="pb-2 text-red-500 text-end">
{mutation.error?.message}
</span>
)
error &&
<div className="text-sm text-red-500 text-end">
{error}
</div>
}
<DialogFooter>

<div className="flex justify-end mt-2 space-x-2">
<button
type="button"
className="p-2 transition-colors rounded-md text-slate-500 hover:bg-slate-400 hover:text-white"
onClick={() => setOpen(false)}
onClick={onClose}
>
Cancel
</button>
<button
type="submit"
className="p-2 text-white transition-colors rounded-md bg-slate-500 hover:bg-slate-400"
>
{mutation.isPending ? "Submitting..." : "Submit"}
Submit
</button>
</DialogFooter>
</div>
</form>
</DialogContent>
</Dialog>
</div>
</div>
);
}

Expand Down
3 changes: 3 additions & 0 deletions src/components/SuggestionsPanel/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import SuggestionsPanel from './SuggestionsPanel';

export default SuggestionsPanel;
2 changes: 1 addition & 1 deletion src/components/Toaster/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const Toaster: React.FC = () => {
}

return (
<div className={`${toastStyle} text-2xl font-bold font-roboto px-6 py-3 ${index !== 0 ? "mt-4" : ""}`} key={toast.id}>
<div className={`${toastStyle} font-bold font-roboto px-4 py-2 ${index !== 0 ? "mt-4" : ""}`} key={toast.id}>
<span>{toast.message}</span>
</div>)
})
Expand Down
34 changes: 17 additions & 17 deletions src/hooks/useAuth.ts → src/context/AuthenticationProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import { useState, useEffect } from "react";
import React, { createContext, useState, useEffect } from "react";
import { UserToken } from "@/models/AuthModels/userToken";

const TOKEN_STORAGE_KEY = "token";

interface User {
userId: number;
username: string;
role: string;
iat: number;
export interface AuthContextProps {
accessToken: string | null;
user: UserToken | null;
saveToken: (token: string) => void;
clearToken: () => void;
}

const useAuth = () => {
export const AuthContext = createContext<AuthContextProps | undefined>(undefined);

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [accessToken, setAccessToken] = useState<string | null>(null);
const [user, setUser] = useState<User | null>(null);
const [user, setUser] = useState<UserToken | null>(null);

useEffect(() => {
const storedToken = localStorage.getItem(TOKEN_STORAGE_KEY);
Expand All @@ -37,12 +40,9 @@ const useAuth = () => {
setAccessToken(null);
};

return {
accessToken,
saveToken,
clearToken,
user,
};
};

export default useAuth;
return (
<AuthContext.Provider value={{ accessToken, user, saveToken, clearToken }}>
{children}
</AuthContext.Provider>
);
};
10 changes: 10 additions & 0 deletions src/context/useAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { useContext } from "react";
import { AuthContext, AuthContextProps } from "./AuthenticationProvider";

export const useAuth = (): AuthContextProps => {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
};
3 changes: 0 additions & 3 deletions src/hocs/WithAuth/index.ts

This file was deleted.

3 changes: 3 additions & 0 deletions src/hocs/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import withAuth from "./withAuth";

export default withAuth;
14 changes: 11 additions & 3 deletions src/hocs/WithAuth/WithAuth.tsx → src/hocs/withAuth.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { UserToken } from "@/models/AuthModels/userToken";
import React, { useEffect, useState, ComponentType } from "react";
import { useNavigate } from "react-router-dom";

const withAuth = <P extends object>(WrappedComponent: ComponentType<P>) => {
const withAuth = <P extends object>(WrappedComponent: ComponentType<P>, requiredRole?: "admin") => {
const ComponentWithAuth: React.FC<P> = (props) => {
const navigate = useNavigate();
const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
const [user, setUser] = useState<UserToken | null>(null);

useEffect(() => {
const token = localStorage.getItem("token");
Expand All @@ -13,10 +15,16 @@ const withAuth = <P extends object>(WrappedComponent: ComponentType<P>) => {
return;
}

setUser({ ...JSON.parse(atob(token.split(".")[1])) });
setIsAuthenticated(true);
}, [navigate]);

if (!isAuthenticated) {
if (!isAuthenticated || !user) {
return null;
}

if (requiredRole && user.role !== requiredRole) {
navigate("/unauthorized");
return null;
}

Expand All @@ -26,4 +34,4 @@ const withAuth = <P extends object>(WrappedComponent: ComponentType<P>) => {
return ComponentWithAuth;
};

export default withAuth;
export default withAuth;
5 changes: 4 additions & 1 deletion src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import { AuthProvider } from './context/AuthenticationProvider.tsx'

createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
<AuthProvider>
<App />
</AuthProvider>
</StrictMode>,
)
Loading