Skip to content

Commit

Permalink
add ServerSideRendering to authenticate users
Browse files Browse the repository at this point in the history
  • Loading branch information
SrTonn committed Jul 19, 2021
1 parent 38ed8e4 commit aa56d32
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
},
"dependencies": {
"datocms-client": "^3.4.11",
"jsonwebtoken": "^8.5.1",
"next": "latest",
"nookies": "^2.5.2",
"prop-types": "^15.7.2",
Expand Down
33 changes: 31 additions & 2 deletions pages/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import React, { useEffect, useState } from 'react'
import PropTypes from 'prop-types'
import nookies from 'nookies'
import jwt from 'jsonwebtoken'
import MainGrid from '../src/components/MainGrid'
import Box from '../src/components/Box'
import ProfileRelationsBoxWrapper from '../src/components/ProfileRelations'
Expand Down Expand Up @@ -89,13 +91,13 @@ function random(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}

export default function Home() {
export default function Home(Props) {
const { githubUser } = Props
const [followers, setFollowers] = useState([])
const [following, setFollowing] = useState([])
const [userStatus, setUserStatus] = useState({})
const [communities, setCommunities] = useState([])
const img404 = 'https://image.freepik.com/vetores-gratis/erro-404-nao-encontrado-efeito-de-falha_8024-4.jpg'
const githubUser = 'SrTonn'

useEffect(() => {
// fetch followers
Expand Down Expand Up @@ -289,3 +291,30 @@ export default function Home() {
</>
)
}

export async function getServerSideProps(ctx) {
const cookies = nookies.get(ctx)
const token = cookies.USER_TOKEN
const { isAuthenticated } = await fetch('https://alurakut.vercel.app/api/auth', {
headers: {
Authorization: token,
},
})
.then((resposta) => resposta.json())

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

const { githubUser } = jwt.decode(token)
return {
props: {
githubUser,
}, // will be passed to the page component as props
}
}

1 comment on commit aa56d32

@vercel
Copy link

@vercel vercel bot commented on aa56d32 Jul 19, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.