first version of auth

This commit is contained in:
biersoeckli
2024-10-18 12:24:29 +00:00
parent bcbe8740eb
commit 4a4afd03b1
10 changed files with 297 additions and 11 deletions

17
src/app/auth/actions.ts Normal file
View File

@@ -0,0 +1,17 @@
'use server'
import { authFormInputSchemaZod } from "@/model/auth-form";
import { ServiceException } from "@/model/service.exception.model";
import userService from "@/server/services/user.service";
import { saveFormAction } from "@/server/utils/action-wrapper.utils";
export const registerUser = async (prevState: any, formData: FormData) =>
saveFormAction(formData, authFormInputSchemaZod, async (validatedData) => {
const allUsers = await userService.getAllUsers();
if (allUsers.length !== 0) {
throw new ServiceException("User registration is currently not possible");
}
return await userService.registerUser(validatedData.email, validatedData.password);
});

View File

@@ -0,0 +1,92 @@
'use client'
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod";
import { useFormState } from 'react-dom'
import { useEffect, useState } from "react";
import { FormUtils } from "@/lib/form.utilts";
import { SubmitButton } from "@/components/custom/submit-button";
import SelectFormField from "@/components/custom/select-form-field";
import BottomBarMenu from "@/components/custom/bottom-bar-menu";
import { AuthFormInputSchema, authFormInputSchemaZod } from "@/model/auth-form"
import { registerUser } from "./actions"
import { signIn } from "next-auth/react";
import { cn } from "@/lib/utils"
import { redirect } from "next/navigation"
import LoadingSpinner from "@/components/ui/loading-spinner"
import { Button } from "@/components/ui/button"
export default function UserLoginForm() {
const form = useForm<AuthFormInputSchema>({
resolver: zodResolver(authFormInputSchemaZod)
});
const [errorMessages, setErrorMessages] = useState<string | undefined>(undefined);
const [loading, setLoading] = useState<boolean>(false);
const login = async () => {
setLoading(true);
setErrorMessages(undefined);
try {
await signIn("credentials", {
username: form.getValues().email,
password: form.getValues().password,
redirect: false,
});
redirect('/');
} catch (e) {
console.log(e);
setErrorMessages((e as any).message);
} finally {
setLoading(false);
}
}
return (
<Form {...form}>
<form onSubmit={() => login()} className="space-y-8">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>E-Mail</FormLabel>
<FormControl>
<Input {...field} value={field.value as string | number | readonly string[] | undefined} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input {...field} value={field.value as string | number | readonly string[] | undefined} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" disabled={loading}>{loading ? <LoadingSpinner></LoadingSpinner> : 'Login'}</Button>
<p className="text-red-500">{errorMessages}</p>
</form>
</Form>
)
}

18
src/app/auth/page.tsx Normal file
View File

@@ -0,0 +1,18 @@
import userService from "@/server/services/user.service";
import UserRegistrationForm from "./register-from";
import UserLoginForm from "./login-from";
export default async function AuthPage() {
const allUsers = await userService.getAllUsers();
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<div className="flex gap-4">
<h2 className="text-3xl font-bold tracking-tight flex-1">Login</h2>
</div>
{allUsers.length === 0 ? <UserRegistrationForm /> : <UserLoginForm />}
</div>
)
}

View File

@@ -0,0 +1,81 @@
'use client'
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod";
import { useFormState } from 'react-dom'
import { useEffect, useState } from "react";
import { FormUtils } from "@/lib/form.utilts";
import { SubmitButton } from "@/components/custom/submit-button";
import SelectFormField from "@/components/custom/select-form-field";
import BottomBarMenu from "@/components/custom/bottom-bar-menu";
import { AuthFormInputSchema, authFormInputSchemaZod } from "@/model/auth-form"
import { registerUser } from "./actions"
import { signIn } from "next-auth/react";
export default function UserRegistrationForm() {
const form = useForm<AuthFormInputSchema>({
resolver: zodResolver(authFormInputSchemaZod)
});
const [state, formAction] = useFormState(registerUser, FormUtils.getInitialFormState<typeof authFormInputSchemaZod>());
useEffect(() => {
if (state.status === 'success') {
const formValues = form.getValues();
signIn("credentials", {
username: formValues.email,
password: formValues.password,
redirect: false,
});
}
}, [state]);
return (
<Form {...form}>
<form action={formAction} className="space-y-8">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>E-Mail</FormLabel>
<FormControl>
<Input {...field} value={field.value as string | number | readonly string[] | undefined} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormControl>
<Input {...field} value={field.value as string | number | readonly string[] | undefined} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<SubmitButton>Register</SubmitButton>
<p className="text-red-500">{state?.message}</p>
</form>
</Form>
)
}

View File

@@ -3,6 +3,9 @@ import { Inter } from "next/font/google";
import { cn } from "@/lib/utils"
import { Toaster } from "@/components/ui/sonner"
import "./globals.css";
import { NavBar } from "./nav-bar";
import { Suspense } from "react";
import FullLoadingSpinner from "@/components/ui/full-loading-spinnter";
const inter = Inter({
subsets: ["latin"],
@@ -25,9 +28,19 @@ export default function RootLayout({
"min-h-screen bg-background font-sans antialiased",
inter.variable
)}>
<main>{children}</main>
<Toaster/>
<NavBar />
<main className="flex w-full flex-col items-center">
<div className="w-full max-w-8xl px-4 lg:px-8">
<div className="p-4 hidden flex-col md:flex">
<Suspense fallback={<FullLoadingSpinner />}>
{children}
</Suspense>
</div>
</div>
</main>
<Toaster />
</body>
</html>
);
}

56
src/app/nav-bar.tsx Normal file
View File

@@ -0,0 +1,56 @@
'use client'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { User } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation"
export function NavBar() {
const pathname = usePathname();
const activeCss = "text-sm font-medium transition-colors hover:text-primary";
const inactiveCss = "text-sm font-medium text-muted-foreground transition-colors hover:text-primary";
return (
<>
<div className="border-b flex w-full flex-col items-center top-0 fixed bg-white z-50">
<div className="w-full max-w-8xl px-4 lg:px-8">
<div className="flex h-16 items-center px-4">
<nav className="flex items-center space-x-4 lg:space-x-6 mx-6">
<Link href="/" className={pathname === '/' ? activeCss : inactiveCss}>Meine Checklisten</Link>
<Link href="/reviewer-checklists" className={pathname === '/reviewer-checklists' ? activeCss : inactiveCss}>Reviewer Checklisten</Link>
<Link href="/customers" className={pathname.startsWith('/customers') ? activeCss : inactiveCss}>Kunden</Link>
<Link href="/text-modules" className={pathname.startsWith('/text-modules') ? activeCss : inactiveCss}>Textbausteine</Link>
</nav>
<div className="ml-auto flex items-center space-x-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="inline-flex items-center justify-center whitespace-nowrap text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 hover:bg-accent hover:text-accent-foreground px-4 py-2 relative h-8 w-8 rounded-full" type="button" id="radix-:reh:" aria-haspopup="menu" aria-expanded="false" data-state="closed" control-id="ControlID-46">
<span className="relative flex shrink-0 overflow-hidden rounded-full h-8 w-8">
<User className="pt-2 pl-2" />
</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56">
<Link href="/profile">
<DropdownMenuItem>
Profil
</DropdownMenuItem>
</Link>
<DropdownMenuSeparator />
<Link href="/.auth/logout">
<DropdownMenuItem className="text-red-500">
Logout
</DropdownMenuItem>
</Link>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</div>
</div>
<div className="h-16"></div>
</>
)
}

View File

@@ -8,13 +8,7 @@ import dataAccess from "@/server/data-access/data-access.client";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcrypt";
import userService from "@/server/services/user.service";
/*
const response: any = await signIn("credentials", {
email,
password,
redirect: false,
});
*/
const saltRounds = 10;
@@ -22,6 +16,9 @@ export const authOptions: NextAuthOptions = {
session: {
strategy: "jwt",
},
pages: {
signIn: "/auth",
},
providers: [
CredentialsProvider({
// The name to display on the sign in form (e.g. "Sign in with...")

View File

@@ -1,3 +1,6 @@
export { default } from "next-auth/middleware"
export const config = { matcher: ["/"] }
export const config = {
matcher: ["/"],
exclude: ["/auth"]
}

9
src/model/auth-form.ts Normal file
View File

@@ -0,0 +1,9 @@
import { z } from "zod";
export const authFormInputSchemaZod = z.object({
email: z.string().email(),
password: z.string().min(1)
});
export type AuthFormInputSchema = z.infer<typeof authFormInputSchemaZod>;

View File

@@ -52,7 +52,7 @@ export class UserService {
}
}
async getUsers() {
async getAllUsers() {
return await unstable_cache(async () => await dataAccess.client.user.findMany(),
[Tags.users()], {
tags: [Tags.users()]