Skip to content

Commit

Permalink
feat: use auth check
Browse files Browse the repository at this point in the history
  • Loading branch information
AntonioErdeljac committed Mar 4, 2023
1 parent 2b81e71 commit 8ddb4da
Show file tree
Hide file tree
Showing 16 changed files with 176 additions and 23 deletions.
7 changes: 4 additions & 3 deletions components/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ import { IoLocationSharp } from 'react-icons/io5';

import useLoginModal from '@/hooks/useLoginModal';
import useRegisterModal from '@/hooks/useRegisterModal';
import useCurrentUser from '@/hooks/useCurrentUser';

import Avatar from './Avatar';
import Button from './Button';

const isLoggedIn = false;

interface FormProps {
placeholder: string;
}
Expand All @@ -18,9 +17,11 @@ const Form: React.FC<FormProps> = ({ placeholder }) => {
const registerModal = useRegisterModal();
const loginModal = useLoginModal();

const { data: currentUser } = useCurrentUser();

return (
<div className="border-b-[1px] border-neutral-800 px-5 py-2">
{isLoggedIn ? (
{currentUser ? (
<div className="flex flex-row gap-4">
<Avatar href="/profiles/123" />
<div className="w-full">
Expand Down
10 changes: 6 additions & 4 deletions components/layout/Sidebar.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { useMemo } from 'react';
import { BsHouseFill, BsBellFill, BsEnvelopeFill } from 'react-icons/bs';
import { signOut, useSession } from 'next-auth/react';
import { BiLogOut } from 'react-icons/bi';
import { BsHouseFill, BsBellFill } from 'react-icons/bs';
import { FaHashtag, FaUser } from 'react-icons/fa';

import SidebarItem from './SidebarItem';
import SidebarLogo from './SidebarLogo';
import SidebarTweetButton from './SidebarTweetButton';

const isLoggedIn = false;

const items = [
{
icon: BsHouseFill,
Expand All @@ -34,6 +33,8 @@ const items = [
]

const Sidebar = () => {
const session = useSession();

return (
<div className="col-span-1 h-full pr-4 md:pr-6">
<div className="flex flex-col items-end">
Expand All @@ -48,6 +49,7 @@ const Sidebar = () => {
label={item.label}
/>
))}
{session.data && <SidebarItem onClick={() => signOut()} icon={BiLogOut} label="Logout" />}
<SidebarTweetButton />
</div>
</div>
Expand Down
22 changes: 15 additions & 7 deletions components/layout/SidebarItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,36 @@ import { IconType } from "react-icons";
import { useRouter } from 'next/router';

import useLoginModal from '@/hooks/useLoginModal';
import useCurrentUser from '@/hooks/useCurrentUser';

interface SidebarItemProps {
label: string;
icon: IconType;
href: string;
href?: string;
onClick?: () => void;
auth?: boolean;
}

const SidebarItem: React.FC<SidebarItemProps> = ({ label, icon: Icon, href, auth }) => {
const SidebarItem: React.FC<SidebarItemProps> = ({ label, icon: Icon, href, auth, onClick }) => {
const router = useRouter();
const loginModal = useLoginModal();

const onClick = useCallback(() => {
if (auth) {
const { data: currentUser } = useCurrentUser();

const handleClick = useCallback(() => {
if (onClick) {
return onClick();
}

if (auth && !currentUser) {
loginModal.onOpen();
} else {
} else if (href) {
router.push(href);
}
}, [router, href, auth, loginModal]);
}, [router, href, auth, loginModal, onClick, currentUser]);

return (
<div onClick={onClick} className="flex flex-row items-center">
<div onClick={handleClick} className="flex flex-row items-center">
<div className="
rounded-full
h-14
Expand Down
15 changes: 14 additions & 1 deletion components/layout/SidebarTweetButton.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
import { useCallback } from "react";
import { FaFeather } from "react-icons/fa";
import { useRouter } from "next/router";

import useLoginModal from "@/hooks/useLoginModal";
import useCurrentUser from "@/hooks/useCurrentUser";

const SidebarTweetButton = () => {
const router = useRouter();
const loginModal = useLoginModal();
const { data: currentUser } = useCurrentUser();

const onClick = useCallback(() => {
if (!currentUser) {
return loginModal.onOpen();
}

router.push('/');
}, [loginModal, router, currentUser]);

return (
<div onClick={loginModal.onOpen}>
<div onClick={onClick}>
<div className="
mt-6
lg:hidden
Expand Down
6 changes: 4 additions & 2 deletions components/modals/LoginModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,18 @@ const LoginModal = () => {

await signIn('credentials', {
email,
password
password,
});

toast.success('Logged in');

loginModal.onClose();
} catch (error) {
toast.error('Something went wrong');
} finally {
setIsLoading(false);
}
}, [email, password]);
}, [email, password, loginModal]);

const onToggle = useCallback(() => {
loginModal.onClose();
Expand Down
2 changes: 1 addition & 1 deletion components/modals/RegisterModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const RegisterModal = () => {

signIn('credentials', {
email,
password
password,
});

registerModal.onClose();
Expand Down
9 changes: 7 additions & 2 deletions components/posts/PostItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import { useCallback } from 'react';
import { AiOutlineHeart, AiOutlineMessage } from 'react-icons/ai';

import useLoginModal from '@/hooks/useLoginModal';
import useCurrentUser from '@/hooks/useCurrentUser';

import Avatar from '../Avatar';

const PostItem = () => {
const router = useRouter();
const loginModal = useLoginModal();
const { data: currentUser } = useCurrentUser();

const goToProfile = useCallback((ev: any) => {
ev.stopPropagation();
Expand All @@ -21,8 +23,11 @@ const PostItem = () => {

const onLike = useCallback((ev: any) => {
ev.stopPropagation();
loginModal.onOpen();
}, [loginModal]);

if (!currentUser) {
loginModal.onOpen();
}
}, [loginModal, currentUser]);

return (
<div
Expand Down
13 changes: 12 additions & 1 deletion components/profiles/ProfileBio.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
import { useCallback } from "react";
import { BiCalendar } from "react-icons/bi";

import useLoginModal from "@/hooks/useLoginModal";
import useCurrentUser from "@/hooks/useCurrentUser";

import Button from "../Button";

const ProfileBio = () => {
const loginModal = useLoginModal();
const { data: currentUser } = useCurrentUser();

const onFollow = useCallback(() => {
if (!currentUser) {
return loginModal.onOpen();
}

return;
}, [currentUser, loginModal]);

return (
<div className="border-b-[1px] border-neutral-800 pb-4">
<div className="flex justify-end p-2">
<Button onClick={loginModal.onOpen} secondary label="Follow" />
<Button onClick={onFollow} secondary label="Follow" />
</div>
<div className="mt-8 px-4">
<div className="flex flex-col">
Expand Down
16 changes: 16 additions & 0 deletions hooks/useCurrentUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import useSWR from 'swr';

import fetcher from '@/libs/fetcher';

const useCurrentUser = () => {
const { data, error, isLoading, mutate } = useSWR('/api/current', fetcher);

return {
data,
error,
isLoading,
mutate
}
};

export default useCurrentUser;
5 changes: 5 additions & 0 deletions libs/fetcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import axios from 'axios';

const fetcher = (url: string) => axios.get(url).then((res) => res.data);

export default fetcher;
26 changes: 26 additions & 0 deletions libs/serverAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { NextApiRequest } from 'next';
import { getSession } from 'next-auth/react';

import prisma from '@/libs/prismadb';

const serverAuth = async (req: NextApiRequest) => {
const session = await getSession({ req });

if (!session?.user?.email) {
throw new Error('Not signed in');
}

const currentUser = await prisma.user.findUnique({
where: {
email: session.user.email,
}
});

if (!currentUser) {
throw new Error('Not signed in');
}

return { currentUser };
};

export default serverAuth;
23 changes: 23 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"react-hot-toast": "^2.4.0",
"react-icons": "^4.7.1",
"react-toastify": "^9.1.1",
"swr": "^2.0.4",
"typescript": "4.9.5",
"zustand": "^4.3.5"
},
Expand Down
5 changes: 3 additions & 2 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { AppProps } from 'next/app'
import { Toaster } from 'react-hot-toast';
import { SessionProvider } from 'next-auth/react';

import Layout from '@/components/Layout'
import LoginModal from '@/components/modals/LoginModal'
Expand All @@ -8,13 +9,13 @@ import '@/styles/globals.css'

export default function App({ Component, pageProps }: AppProps) {
return (
<>
<SessionProvider session={pageProps.session}>
<Toaster />
<RegisterModal />
<LoginModal />
<Layout>
<Component {...pageProps} />
</Layout>
</>
</SessionProvider>
)
}
18 changes: 18 additions & 0 deletions pages/api/current.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { NextApiRequest, NextApiResponse } from 'next';

import serverAuth from '@/libs/serverAuth';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'GET') {
return res.status(405).end();
}

try {
const { currentUser } = await serverAuth(req);

return res.status(200).json(currentUser);
} catch (error) {
console.log(error);
return res.status(400).end();
}
}
21 changes: 21 additions & 0 deletions pages/notifications.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,25 @@
import Header from "@/components/Header";
import { NextPageContext } from "next";
import { getSession } from "next-auth/react";

export async function getServerSideProps(context: NextPageContext) {
const session = await getSession(context);

if (!session) {
return {
redirect: {
destination: '/',
permanent: false,
}
}
}

return {
props: {
session
}
}
}

const Notifications = () => {
return (
Expand Down

0 comments on commit 8ddb4da

Please sign in to comment.