Skip to content

Commit

Permalink
use isloggedin cookie
Browse files Browse the repository at this point in the history
GraemeFulton committed Aug 19, 2024
1 parent 899e1a4 commit 72af79c
Showing 10 changed files with 672 additions and 403 deletions.
49 changes: 49 additions & 0 deletions app/IndexPageComponent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"use client";
import Layout from "@/components/new-index/layoutForIndex";
import IntroBanner from "@/components/v4/hero/IntroBanner2";
import TagsNavRow from "@/components/v4/section/TagsNavRow";
import Container from "@/components/container";
import NewsColumn from "@/components/v4/layout/NewsColumn";
import HeroArticleSection from "@/components/v4/section/HeroArticleSection";
import CardColumn from "@/components/v4/layout/CardColumn";
import NewsletterSection from "@/components/v4/section/NewsletterSection";
import ToolsCarouselSection from "@/components/v4/section/ToolsCarouselSection";
import TwoColumnCards from "@/components/v4/layout/TwoColumnCardsB";
import TopicSectionHome from "@/components/v4/section/TopicSectionHome";
import Footer from "@/components/footer";

import { IntlProvider } from 'react-intl';


export default async function IndexPageComponent({locale,user, data}) {
// const data = await getData(locale);

return (
<IntlProvider locale={locale}>
<>
{!user && <IntroBanner sponsor={data.sponsors?.length ? data.sponsors[0] : null} />}
<TagsNavRow />
<Container>
{/* Your main content here, using data fetched above */}
<NewsColumn
groupedNewsPosts={data.groupedNewsPosts}
sponsor={data.navSponsor}
posts={data.allNews}
/>
<HeroArticleSection
heroPost={data.heroPost}
viewablePosts={data.morePosts}
/>
<CardColumn sponsor={data.navSponsor} tools={data.allTools} />
</Container>
<NewsletterSection />
<ToolsCarouselSection
toolsList={data.allTools}
sponsors={data.sponsors}
/>
{/* ... other sections ... */}
<Footer />
</>
</IntlProvider>
);
}
191 changes: 191 additions & 0 deletions app/page_.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import React from "react";
import IndexPageComponent from "./IndexPageComponent";
import { fetchUser } from "./actions";

import {
getCombinedPostsForHome,
getAllToolsForHome,
// getRandomPostsForHome,
getCommonQuery,
getAllNews,
} from "@/lib/api";
import { createB64WithFallback } from "@/lib/utils/blurHashToDataURL";
import { TAB_ITEMS } from "@/lib/constants";
import { makeAuthorList, shuffleArray } from "@/lib/utils/postUtils";
import getSponsors from "@/lib/utils/getSponsors";
import { groupPostsByDate } from "@/lib/utils/groupPostsByDate";
import { transformPostListOld } from "@/lib/locale/transformLocale";
import { formatAllTools } from "@/lib/utils/formatToolContent";

import Layout from "@/components/new-index/layoutForApp";

export async function generateStaticParams() {
return [{ locale: "en" }, { locale: "es-ES" }];
}

export const metadata = {
title: "Typr Editor - Open-Source Writing Tool by Prototypr",
description:
"A customizable WYSIWYG editor with publishing flows and user state management for React.js. Built with Tiptap and ProseMirror.",
openGraph: {
title: "Typr Editor - Open-Source Writing Tool by Prototypr",
description:
"A customizable WYSIWYG editor with publishing flows and user state management for React.js. Built with Tiptap and ProseMirror.",
images: [
{
url: `${process.env.NEXT_PUBLIC_APP_URL}/static/images/typr-og.jpg`,
width: 1200,
height: 630,
alt: "Tiptypr Editor Preview",
},
],
},
};

async function getData(locale) {
console.log("getData", locale);
const preview = false;
let sort = ["featured:desc", "tier:asc", "date:desc"];
if (locale == "es-ES") {
sort = ["esES:desc", "featured:desc", "tier:asc", "date:desc"];
}

let allPosts = (await getCombinedPostsForHome(preview, 12, 0, sort)) || [];

// let randomPosts = (await getRandomPostsForHome()) || [];
let toolCount = 20;
let allTools =
(await getAllToolsForHome(preview, toolCount, 0, [
"featured:desc",
"date:desc",
])) || [];

for (var x = 0; x < allTools?.data?.length; x++) {
//generate blurhash here
allTools.data[x].attributes.logoBase64 = createB64WithFallback(
allTools.data[x]?.attributes?.logo?.data?.attributes?.blurhash
);
allTools.data[x].attributes.base64 = createB64WithFallback(
allTools.data[x]?.attributes?.featuredImage?.data?.attributes?.blurhash
);
}

let allNews = (await getAllNews(preview, 15, 0)) || [];

// let jobs = (await getAllJobs(null, 5, 1)) || [];
// topic sections
let topicRes = {};
for (let index = 0; index < TAB_ITEMS.length; index++) {
const tag = TAB_ITEMS[index].slug;
let res =
(await getCommonQuery(preview, [tag], "article", 12, 0, sort)) || [];

//add blurhash to the images
for (var x = 0; x < res?.data?.length; x++) {
res.data[x].attributes.base64 = createB64WithFallback(
res.data[x]?.attributes?.featuredImage?.data?.attributes?.blurhash
);
}

const topicToolsRes =
(await getCommonQuery(
preview,
[TAB_ITEMS[index].toolSlug],
"tool",
8,
0,
sort
)) || [];

//extract authors from the postss while we don't have an endpoint for it
const authors = makeAuthorList(res);

//shuffle so it's different each time
shuffleArray(res.data);
shuffleArray(authors);
shuffleArray(topicToolsRes.data);

//add blurhash to the images
for (var x = 0; x < topicToolsRes?.data?.length; x++) {
topicToolsRes.data[x].attributes.logoBase64 = createB64WithFallback(
topicToolsRes.data[x]?.attributes?.logo?.data?.attributes?.blurhash
);
topicToolsRes.data[x].attributes.base64 = createB64WithFallback(
topicToolsRes.data[x]?.attributes?.featuredImage?.data?.attributes
?.blurhash
);
}

const topicData = {
authors: authors,
posts: res.data,
tools: topicToolsRes.data,
};
topicRes[tag] = topicData;
}

// const popularTags =
// (await getPopularTopics({ postType: "article", pageSize: 34 })) || [];

allPosts = transformPostListOld(allPosts?.data, locale);
if (locale !== "es-ES") {
// dont shuffle for now
// shuffleArray(allPosts);
}
allTools = transformPostListOld(allTools?.data, locale);

//add blurhash to allPosts images
for (var x = 0; x < allPosts?.length; x++) {
allPosts[x].attributes.base64 = createB64WithFallback(
allPosts[x]?.attributes?.featuredImage?.data?.attributes?.blurhash
);
}

// shuffleArray(allTools)
// await generateCombinedRSS({ allPosts, allTools });
// otherPosts = transformPostListOld(otherPosts.data, locale);
allTools = formatAllTools({ tools: allTools, tagNumber: 1 });
allNews = formatAllTools({ tools: allNews.data, tagNumber: 0 });

const { navSponsor, sponsors } = await getSponsors();

// for(var x = 0; x<allNews.tools.length;x++){
// allNews.tools[x].attributes.base64 = createB64WithFallback(allNews.tools[x]?.attributes?.featuredImage?.data?.blurhash);
// allTools.data[x].attributes.logoBase64 = createB64WithFallback(allTools.data[x]?.attributes?.logo?.data?.blurhash);
// }

let groupedNewsPosts = groupPostsByDate(allNews);

return {
heroPost: allPosts?.length ? allPosts[0] : null,
morePosts: allPosts?.length > 1 ? allPosts.slice(1) : null,
allTools: allTools?.length ? allTools : null,
allNews: allNews?.length ? allNews : null,
groupedNewsPosts: groupedNewsPosts ? groupedNewsPosts : null,
// popularTags,
// otherPosts: otherPosts,
// interviewPosts: interviews.data,
topicRes: topicRes ? topicRes : null,
preview,
// jobs,
// randomPosts: randomPosts.slice(0, 8),
sponsors: sponsors?.length ? sponsors : [],
navSponsor,
// ... other data ...
};
}

export default async function IndexPage({ params: { locale } }) {
const userData = await fetchUser();

const data = await getData(locale);
return (
<Layout sessionUser={userData?.user?.id} background={"#fbfcff"}>
{/* {data ? ( */}
<IndexPageComponent user={userData?.user} locale={locale} data={data} />
{/* ) : (
<div>Loading...</div>
)} */}
</Layout>
);
}
8 changes: 4 additions & 4 deletions components/Navbar/Navbar.jsx
Original file line number Diff line number Diff line change
@@ -40,7 +40,7 @@ const Navbar = ({
navType,
navBackground,
}) => {
const { user, isLoading } = useUser({
const { user, isLoading, isLoggedIn } = useUser({
redirectIfFound: false,
});

@@ -195,7 +195,7 @@ const Navbar = ({
</div>
<div
className={`items-center sm:static sm:inset-auto flex ${
user?.isLoggedin ? "mr-[52px] sm:mr-16" : "lg:mr-0"
(user?.isLoggedIn || isLoggedIn) ? "mr-[52px] sm:mr-16" : "lg:mr-0"
}`}
>
{/* <div className={`hidden mr-2 md:block my-auto`}>
@@ -243,12 +243,12 @@ const Navbar = ({
{/* <MobileActiveLink href={"/web-monetization"}>
Earn Micropayments
</MobileActiveLink> */}
{!user?.isLoggedIn ? (
{!(user?.isLoggedIn || isLoggedIn) ? (
<MobileActiveLink href={"/onboard"}>Sign in</MobileActiveLink>
) : (
""
)}
{user?.isLoggedIn ? (
{(user?.isLoggedIn || isLoggedIn) ? (
<div className="px-2.5 pt-2" onClick={toggleMobileNav}>
<NewPostDialog />
</div>
4 changes: 2 additions & 2 deletions components/people/ProfileCard.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import dynamic from "next/dynamic";
// import dynamic from "next/dynamic";

import Image from "next/image";
import Link from "next/link";
@@ -9,7 +9,7 @@ import { useState } from "react";
import Button from "../Primitives/Button";

import '~/react-kofi/dist/kofi.css';
import {KoFiButton} from "react-kofi";
// import {KoFiButton} from "react-kofi";

// const KoFiButton = dynamic(() => import("@/components/people/KoFiButton"), {
// ssr: true,
6 changes: 3 additions & 3 deletions components/v4/particles/ParticlesContainer.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useEffect } from "react";
// import { useState, useEffect } from "react";
// import { cloneDeep } from "lodash";

import { useCallback } from "react";
@@ -22,12 +22,12 @@ import { loadFull } from "tsparticles";
// import { loadTiltUpdater } from "tsparticles-updater-tilt";
// import { loadTwinkleUpdater } from "tsparticles-updater-twinkle";
// import { loadWobbleUpdater } from "tsparticles-updater-wobble";
import {useRouter} from 'next/router'
// import {useRouter} from 'next/router'
import {particleOptions} from './particleOptionsB'


const ParticlesContainer = () => {
const router = useRouter()
// const router = useRouter()
const options = particleOptions

const particlesLoaded = useCallback(async (container) => {
1 change: 1 addition & 0 deletions components/v4/section/TagsNavRow.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
'use client'
import Container from "@/components/container";
import GiantTag from "../tag/GiantTag";
import {Compass} from '@/components/icons'
13 changes: 13 additions & 0 deletions lib/iron-session/checkLoginCookie.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export function checkLoginCookie(req) {
if (typeof window !== 'undefined') {
// Client-side
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
const [name, value] = cookie.trim().split('=');
if (name === 'isLoggedIn' && value === 'true') {
return true
}
}
return false;
}
}
24 changes: 20 additions & 4 deletions lib/iron-session/useUser.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,33 @@
'use client';

import { useEffect } from 'react'
import { useEffect, useState } from 'react'
import {useRouter} from 'next/navigation'
import useSWR from 'swr'
// import { User } from 'pages/api/auth/user'
import { checkLoginCookie } from './checkLoginCookie'
import Cookies from 'js-cookie'

const fetcher = (url) => fetch(url).then((res) => res.json())

export default function useUser({
redirectTo = '',
redirectIfFound = false,
} = {}) {
const router = useRouter()
const [isLoggedIn, setIsLoggedIn] = useState(() => checkLoginCookie())

const { data: user, mutate: mutateUser, isValidating:isLoading } = useSWR(`/api/auth/user`, fetcher)

useEffect(() => {
if (user) {
setIsLoggedIn(user.isLoggedIn)
if(user.isLoggedIn){
Cookies.set('isLoggedIn', 'true', { expires: 7 }) // Cookie expires in 7 days
}else{
Cookies.remove('isLoggedIn')
}
}
}, [user])

useEffect(() => {
// if no redirect needed, just return (example: already on /dashboard)
// if user data not yet there (fetch in progress, logged in or not) then don't do anything yet
@@ -25,7 +41,7 @@ export default function useUser({
) {
router.push(redirectTo)
}
}, [user, redirectIfFound, redirectTo])
}, [isLoggedIn,user, redirectIfFound, redirectTo])

return { user, mutateUser, isLoading }
return { user, mutateUser, isLoading, isLoggedIn: isLoggedIn }
}
7 changes: 3 additions & 4 deletions pages/index.js
Original file line number Diff line number Diff line change
@@ -7,7 +7,6 @@ import dynamic from "next/dynamic";
import Layout from "@/components/new-index/layoutForIndex";
// import TrendingFullWidth from "@/components/homepage/TrendingFullWidth";
import IntroBanner from "@/components/v4/hero/IntroBanner2";

/**new index components */
// import { BrowserView } from "react-device-detect";
const Footer = dynamic(() => import("@/components/footer"));
@@ -83,7 +82,7 @@ export default function Index({
const titleText = intl.formatMessage({ id: "index.header.title" });
const descriptionText = intl.formatMessage({ id: "intro.description" });

const { user, isLoading } = useUser({
const { user, isLoading, isLoggedIn } = useUser({
redirectIfFound: false,
});
// const HeroPostRandomSection = randomPosts.filter((item, i) => i === 0);
@@ -111,7 +110,7 @@ export default function Index({
url: "https://prototypr.io",
}}
>
{!user?.isLoggedIn ? (
{!isLoggedIn ? (
<>
<IntroBanner sponsor={sponsors?.length ? sponsors[0] : null} />
{/* <SectionDivider
@@ -380,7 +379,7 @@ export default function Index({
<DesignTool allTools={toolsList} />
</BrowserView> */}
</Layout>
{!user?.isLoggedIn && (
{!isLoggedIn && (
<StickyFooterCTA
title="Welcome to Prototypr"
description="Join today to make posts and grow with us."
772 changes: 386 additions & 386 deletions public/sitemap-0.xml

Large diffs are not rendered by default.

0 comments on commit 72af79c

Please sign in to comment.