Implement frontend auth and user features - WIP

This commit is contained in:
Philipinho
2023-08-27 21:38:59 +01:00
parent 3e7c2de9a4
commit 54a748ced7
30 changed files with 765 additions and 6 deletions

View File

@ -10,27 +10,36 @@
"lint": "next lint"
},
"dependencies": {
"@hookform/resolvers": "^3.3.0",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-toast": "^1.1.4",
"@radix-ui/react-tooltip": "^1.0.6",
"@tanstack/react-query": "^4.33.0",
"@types/node": "20.4.8",
"@types/react": "18.2.18",
"@types/react-dom": "18.2.7",
"autoprefixer": "10.4.14",
"axios": "^1.4.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"eslint": "8.46.0",
"eslint-config-next": "13.4.13",
"jotai": "^2.3.1",
"js-cookie": "^3.0.5",
"next": "13.4.13",
"next-themes": "^0.2.1",
"postcss": "8.4.27",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-hook-form": "^7.45.4",
"tailwind-merge": "^1.14.0",
"tailwindcss": "3.3.3",
"tailwindcss-animate": "^1.0.6",
"typescript": "5.1.6"
},
"devDependencies": {
"@types/js-cookie": "^3.0.3"
}
}

View File

@ -0,0 +1,7 @@
interface AuthLayoutProps {
children: React.ReactNode
}
export default function AuthLayout({ children }: AuthLayoutProps) {
return <div className="min-h-screen">{children}</div>
}

View File

@ -0,0 +1,49 @@
"use client"
import Link from "next/link";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button";
import { Icons } from "@/components/icons";
import { ChevronLeftIcon } from "@radix-ui/react-icons";
import { LoginForm } from "@/features/auth/components/login-form";
import LegalTerms from "@/features/auth/components/legal-terms";
export default function LoginPage() {
return (
<div className="container flex h-screen w-screen flex-col items-center justify-center">
<Link
href="/"
className={cn(
buttonVariants({ variant: "ghost" }),
"absolute left-4 top-4 md:left-8 md:top-8")}>
<>
<ChevronLeftIcon className="mr-2 h-4 w-4" />Back
</>
</Link>
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
<div className="flex flex-col space-y-2 text-center">
<Icons.logo className="mx-auto h-6 w-6" />
<h1 className="text-2xl font-semibold tracking-tight">
Welcome back
</h1>
<p className="text-sm text-muted-foreground">
Enter your email and password to continue
</p>
</div>
<LoginForm />
<p className="px-8 text-center text-sm text-muted-foreground">
<Link
href="/signup"
className="hover:text-brand underline underline-offset-4">
Don&apos;t have an account? Sign Up
</Link>
</p>
<LegalTerms />
</div>
</div>
);
}

View File

@ -0,0 +1,52 @@
"use client"
import Link from "next/link";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button";
import { Icons } from "@/components/icons";
import { ChevronLeftIcon } from "@radix-ui/react-icons";
import { SignUpForm } from "@/features/auth/components/sign-up-form";
import LegalTerms from "@/features/auth/components/legal-terms";
export default function SignUpPage() {
return (
<div className="container flex h-screen w-screen flex-col items-center justify-center">
<Link
href="/"
className={cn(
buttonVariants({ variant: "ghost" }),
"absolute left-4 top-4 md:left-8 md:top-8")}>
<>
<ChevronLeftIcon className="mr-2 h-4 w-4" />Back
</>
</Link>
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
<div className="flex flex-col space-y-2 text-center">
<Icons.logo className="mx-auto h-6 w-6" />
<h1 className="text-2xl font-semibold tracking-tight">
Create an account
</h1>
<p className="text-sm text-muted-foreground">
Enter your name, email and password to signup
</p>
</div>
<SignUpForm />
<p className="px-8 text-center text-sm text-muted-foreground">
<Link
href="/login"
className="hover:text-brand underline underline-offset-4">
Already have an account? Sign In
</Link>
</p>
<LegalTerms />
</div>
</div>
);
}

View File

@ -0,0 +1,16 @@
"use client";
import { useAtom } from "jotai";
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
export default function Home() {
const [currentUser] = useAtom(currentUserAtom);
return (
<div className="w-full flex justify-center z-10 flex-shrink-0">
<div className={`w-[900px]`}>
Hello {currentUser && currentUser.user.name}!
</div>
</div>
);
}

View File

@ -0,0 +1,21 @@
"use client"
import dynamic from "next/dynamic";
import { UserProvider } from "@/features/user/user-provider";
const Shell = dynamic(() => import("./shell"), {
ssr: false,
});
export default function DashboardLayout({ children }: {
children: React.ReactNode
}) {
return (
<UserProvider>
<Shell>
{children}
</Shell>
</UserProvider>
);
}

View File

@ -0,0 +1,18 @@
"use client"
export default function Shell({ children }: {
children: React.ReactNode
}) {
return (
<div className="flex justify-start min-h-screen">
<div className="flex flex-col w-full overflow-hidden">
<main className="overflow-y-auto overscroll-none w-full p-8" style={{ height: "calc(100vh - 50px)" }}>
{children}
</main>
</div>
</div>
);
}

View File

@ -4,6 +4,7 @@ import { Inter } from 'next/font/google'
import { cn } from "@/lib/utils";
import { ThemeProvider } from "@/components/providers/theme-provider";
import { Toaster } from "@/components/ui/toaster";
import { TanstackProvider } from "@/components/providers/tanstack-provider";
const inter = Inter({ subsets: ['latin'] })
@ -12,6 +13,7 @@ export const metadata: Metadata = {
description: 'Generated by create next app',
}
export default function RootLayout({
children,
}: {
@ -22,8 +24,10 @@ export default function RootLayout({
<html lang="en" suppressHydrationWarning>
<body className={cn("min-h-screen bg-background antialiased", inter.className)}>
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
{children}
<Toaster />
<TanstackProvider>
{children}
<Toaster />
</TanstackProvider>
</ThemeProvider>
</body>
</html>

View File

@ -8,10 +8,8 @@ export default function Home() {
Get started by editing&nbsp;
<code className="font-mono font-bold">src/app/page.tsx</code>
</p>
<div className="fixed bottom-0 left-0 flex h-48 w-full items-end justify-center bg-gradient-to-t from-white via-white dark:from-black dark:via-black lg:static lg:h-auto lg:w-auto lg:bg-none">
<div className="fixed bottom-0 left-z0 flex h-48 w-full items-end justify-center bg-gradient-to-t from-white via-white dark:from-black dark:via-black lg:static lg:h-auto lg:w-auto lg:bg-none">
<ThemeToggle />
</div>
</div>

View File

@ -0,0 +1,48 @@
type IconProps = React.HTMLAttributes<SVGElement>
export const Icons = {
logo: (props: IconProps) => (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" {...props}>
<rect width="256" height="256" fill="none" />
<line
x1="208"
y1="128"
x2="128"
y2="208"
fill="none"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="16"
/>
<line
x1="192"
y1="40"
x2="40"
y2="192"
fill="none"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="16"
/>
</svg>
),
spinner: (props: IconProps) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
{...props}
>
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
),
}

View File

@ -0,0 +1,14 @@
"use client"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import React from "react";
const queryClient = new QueryClient();
export function TanstackProvider({ children }: React.PropsWithChildren) {
return (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);
}

View File

@ -0,0 +1,25 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

View File

@ -0,0 +1,26 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

View File

@ -0,0 +1,14 @@
import Cookies from "js-cookie";
import { createJSONStorage, atomWithStorage } from "jotai/utils";
import { ITokens } from "@/features/auth/types/auth.types";
const cookieStorage = createJSONStorage<ITokens>(() => {
return {
getItem: () => Cookies.get("authTokens"),
setItem: (key, value) => Cookies.set(key, value),
removeItem: (key) => Cookies.remove(key),
};
});
export const authTokensAtom = atomWithStorage<ITokens | null>("authTokens", null, cookieStorage);

View File

@ -0,0 +1,12 @@
import Link from "next/link";
export default function LegalTerms(){
return (
<p className="px-8 text-center text-sm text-muted-foreground">
By clicking continue, you agree to our{" "}
<Link href="#" className="underline underline-offset-4 hover:text-primary">
Terms of Service</Link>{" "} and{" "}
<Link href="#" className="underline underline-offset-4 hover:text-primary">Privacy Policy</Link>.
</p>
)
}

View File

@ -0,0 +1,92 @@
"use client";
import * as React from "react";
import * as z from "zod";
import { cn } from "@/lib/utils";
import { Button, buttonVariants } from "@/components/ui/button";
import { Icons } from "@/components/icons";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import useAuth from "@/features/auth/hooks/use-auth";
import { ILogin } from "@/features/auth/types/auth.types";
const formSchema = z.object({
email: z.string({ required_error: "email is required" }).email({ message: "Invalid email address" }),
password: z.string({ required_error: "password is required" }),
});
interface UserAuthFormProps extends React.HTMLAttributes<HTMLDivElement> {
}
export function LoginForm({ className, ...props }: UserAuthFormProps) {
const { register, handleSubmit, formState: { errors } }
= useForm<ILogin>({ resolver: zodResolver(formSchema) });
const { signIn, isLoading } = useAuth();
async function onSubmit(data: ILogin) {
await signIn(data);
}
return (
<>
<div className={cn("grid gap-6 space-y-5", className)} {...props}>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="grid gap-2">
<div className="space-y-2">
<Label className="" htmlFor="email">
Email
</Label>
<Input
id="email"
placeholder="name@example.com"
type="email"
autoCapitalize="none"
autoComplete="email"
autoCorrect="off"
required
disabled={isLoading}
{...register("email")} />
{errors?.email && (
<p className="px-1 text-xs text-red-600">
{errors.email.message}
</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="password">
Password
</Label>
<Input
id="password"
placeholder="Enter your password"
type="password"
autoComplete="off"
required
disabled={isLoading}
{...register("password")} />
{errors?.password && (
<p className="px-1 text-xs text-red-600">
{errors.password.message}
</p>
)}
</div>
<Button className={cn(buttonVariants(), "mt-2")} disabled={isLoading}>
{isLoading && (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
)}
Sign In
</Button>
</div>
</form>
</div>
</>
);
}

View File

@ -0,0 +1,92 @@
"use client";
import * as React from "react";
import * as z from "zod";
import { cn } from "@/lib/utils";
import { Button, buttonVariants } from "@/components/ui/button";
import { Icons } from "@/components/icons";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import useAuth from "@/features/auth/hooks/use-auth";
import { IRegister } from "@/features/auth/types/auth.types";
const formSchema = z.object({
email: z.string({ required_error: "email is required" }).email({ message: "Invalid email address" }),
password: z.string({ required_error: "password is required" }),
});
interface UserAuthFormProps extends React.HTMLAttributes<HTMLDivElement> {
}
export function SignUpForm({ className, ...props }: UserAuthFormProps) {
const { register, handleSubmit, formState: { errors } }
= useForm<IRegister>({ resolver: zodResolver(formSchema) });
const { signUp, isLoading } = useAuth();
async function onSubmit(data: IRegister) {
await signUp(data);
}
return (
<>
<div className={cn("grid gap-6 space-y-5", className)} {...props}>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="grid gap-2">
<div className="space-y-2">
<Label className="" htmlFor="email">
Email
</Label>
<Input
id="email"
placeholder="name@example.com"
type="email"
autoCapitalize="none"
autoComplete="email"
autoCorrect="off"
required
disabled={isLoading}
{...register("email")} />
{errors?.email && (
<p className="px-1 text-xs text-red-600">
{errors.email.message}
</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="password">
Password
</Label>
<Input
id="password"
placeholder="Enter your password"
type="password"
autoComplete="off"
required
disabled={isLoading}
{...register("password")} />
{errors?.password && (
<p className="px-1 text-xs text-red-600">
{errors.password.message}
</p>
)}
</div>
<Button className={cn(buttonVariants(), "mt-2")} disabled={isLoading}>
{isLoading && (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
)}
Sign Up
</Button>
</div>
</form>
</div>
</>
);
}

View File

@ -0,0 +1,65 @@
import { useState } from "react";
import { toast } from "@/components/ui/use-toast";
import { login, register } from "@/features/auth/services/auth-service";
import { useRouter } from "next/navigation";
import { useAtom } from "jotai";
import { authTokensAtom } from "@/features/auth/atoms/auth-tokens-atom";
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
import { ILogin, IRegister } from "@/features/auth/types/auth.types";
import { RESET } from "jotai/vanilla/utils/constants";
export default function useAuth() {
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
const [, setCurrentUser] = useAtom(currentUserAtom);
const [authToken, setAuthToken] = useAtom(authTokensAtom);
const handleSignIn = async (data: ILogin) => {
setIsLoading(true);
try {
const res = await login(data);
setIsLoading(false);
await setAuthToken(res.tokens);
router.push("/home");
} catch (err) {
setIsLoading(false);
toast({
description: err.response?.data.message,
variant: "destructive",
});
}
};
const handleSignUp = async (data: IRegister) => {
setIsLoading(true);
try {
const res = await register(data);
setIsLoading(false);
await setAuthToken(res.tokens);
router.push("/home");
} catch (err) {
setIsLoading(false);
toast({
description: err.response?.data.message,
variant: "destructive",
});
}
};
const hasTokens = () => {
return !!authToken;
};
const handleLogout = async () => {
await setAuthToken(RESET);
setCurrentUser('');
}
return { signIn: handleSignIn, signUp: handleSignUp, isLoading, hasTokens };
}

View File

@ -0,0 +1,12 @@
import api from "@/lib/api-client";
import { ILogin, IRegister, ITokenResponse, ITokens } from "@/features/auth/types/auth.types";
export async function login(data: ILogin): Promise<ITokenResponse>{
const req = await api.post<ITokens>("/auth/login", data);
return req.data as ITokenResponse;
}
export async function register(data: IRegister): Promise<ITokenResponse>{
const req = await api.post<ITokens>("/auth/register", data);
return req.data as ITokenResponse;
}

View File

@ -0,0 +1,18 @@
export interface ILogin {
email: string,
password: string
}
export interface IRegister {
email: string,
password: string
}
export interface ITokens {
accessToken: string,
refreshToken: string
}
export interface ITokenResponse {
tokens: ITokens
}

View File

@ -0,0 +1,4 @@
import { atom } from "jotai";
import { ICurrentUserResponse } from "@/features/user/types/user.types";
export const currentUserAtom = atom<ICurrentUserResponse | null>(null);

View File

@ -0,0 +1,13 @@
import { useQuery, UseQueryResult } from "@tanstack/react-query";
import { getUserInfo } from "@/features/user/services/user-service";
import { ICurrentUserResponse } from "@/features/user/types/user.types";
export default function useCurrentUser(): UseQueryResult<ICurrentUserResponse> {
return useQuery({
queryKey: ["currentUser"],
queryFn: async () => {
return await getUserInfo();
},
});
}

View File

@ -0,0 +1,12 @@
import api from "@/lib/api-client";
import { ICurrentUserResponse, IUser } from "@/features/user/types/user.types";
export async function getMe(): Promise<IUser>{
const req = await api.get<IUser>("/user/me");
return req.data as IUser;
}
export async function getUserInfo(): Promise<ICurrentUserResponse>{
const req = await api.get<ICurrentUserResponse>("/user/info");
return req.data as ICurrentUserResponse;
}

View File

@ -0,0 +1,20 @@
import { IWorkspace } from "@/features/workspace/types/workspace.types";
export interface IUser {
id: string;
name: string;
email: string;
emailVerifiedAt: Date;
avatarUrl: string;
timezone: string;
settings: any;
lastLoginAt: string;
lastLoginIp: string;
createdAt: Date;
updatedAt: Date;
}
export interface ICurrentUserResponse {
user: IUser,
workspace: IWorkspace
}

View File

@ -0,0 +1,25 @@
"use client"
import { useAtom } from "jotai";
import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
import { useEffect } from "react";
import useCurrentUser from "@/features/user/hooks/use-current-user";
export function UserProvider({ children }: React.PropsWithChildren) {
const [, setCurrentUser] = useAtom(currentUserAtom);
const { data, isLoading, error } = useCurrentUser();
useEffect(() => {
if (data && data.user){
setCurrentUser(data);
}
}, [data, isLoading, setCurrentUser]);
if (isLoading) return <></>;
if (error){
return <>an error occurred</>
}
return <>{children}</>
}

View File

@ -0,0 +1,14 @@
export interface IWorkspace {
id: string;
name: string;
description: string;
logo: string;
hostname: string;
customDomain: string;
enableInvite: boolean;
inviteCode: string;
settings: any;
creatorId: string;
createdAt: Date;
updatedAt: Date;
}

View File

@ -0,0 +1,53 @@
import axios, { AxiosInstance } from "axios";
import Cookies from "js-cookie";
import Routes from "@/lib/routes";
const api: AxiosInstance = axios.create({
baseURL: process.env.NEXT_PUBLIC_BACKEND_API_URL,
});
api.interceptors.request.use(config => {
const tokenData = Cookies.get("authTokens");
const accessToken = tokenData && JSON.parse(tokenData)?.accessToken;
if (accessToken) {
config.headers.Authorization = `Bearer ${accessToken}`;
}
return config;
},
error => {
return Promise.reject(error);
},
);
api.interceptors.response.use(
response => {
return response.data;
},
error => {
if (error.response) {
switch (error.response.status) {
case 401:
// Handle unauthorized error
if (window.location.pathname != Routes.AUTH.LOGIN){
window.location.href = Routes.AUTH.LOGIN;
}
break;
case 403:
// Handle forbidden error
break;
case 404:
// Handle not found error
break;
case 500:
// Handle internal server error
break;
default:
break;
}
}
return Promise.reject(error);
},
);
export default api;

View File

@ -0,0 +1,17 @@
import { atom } from "jotai";
export function atomWithWebStorage<Value>(key: string, initialValue: Value, storage = localStorage) {
const storedValue = localStorage.getItem(key);
const isString = typeof initialValue === "string";
const storageValue = storedValue ? isString ? storedValue : storedValue === "true" : undefined;
const baseAtom = atom(storageValue ?? initialValue);
return atom(
get => get(baseAtom) as Value,
(_get, set, nextValue: Value) => {
set(baseAtom, nextValue);
storage.setItem(key, nextValue!.toString());
},
);
}

View File

@ -0,0 +1,9 @@
const ROUTES = {
HOME: '/home',
AUTH: {
LOGIN: '/login',
SIGNUP: '/signup',
},
};
export default ROUTES;

View File

@ -4,7 +4,7 @@
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,