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

@ -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
}