Skip to content

Commit

Permalink
Merge branch 'main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
roshanrajeev authored May 2, 2021
2 parents 26dd506 + 5435378 commit e4fa264
Show file tree
Hide file tree
Showing 18 changed files with 246 additions and 175 deletions.
28 changes: 8 additions & 20 deletions components/Header/header.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,31 @@
import {useState, useEffect} from 'react'
import Link from 'next/link'
import styles from './header.module.scss'
import Router from 'next/router'
import { useAuth } from '../../contexts/authContext'
import { clientRedirect } from '../../lib/redirect'

const Header = () => {
const [isAtuenticated, setIsAtuenticated] = useState(false)

useEffect(async () => {
if(localStorage.getItem('macebook-isauth')){
setIsAtuenticated(true)
}else{
setIsAtuenticated(false)
}
})
const [user, setUser] = useAuth()

const handleLogout = async () => {
if(localStorage.getItem('macebook-isauth')){
localStorage.removeItem('macebook-isauth')
}
const res = await fetch(`${process.env.API}/logout`, {
method: 'GET',
credentials: 'include'
})
console.log(res)
Router.replace('/')
return
setUser()
clientRedirect('/')
}

return(
<nav className={styles.navbar}>
<Link href="/"><a className={styles.navbarBrand}>Logo</a></Link>
{isAtuenticated ?
{user ?
<ul className={styles.navbarNav}>
<li className={styles.navbarLink}><Link href="/feeds"><a>Home</a></Link></li>
<li className={styles.navbarLink}><Link href="/messaging"><a>Messaging</a></Link></li>
<li className={styles.navbarLink}><Link href="/notifications"><a>Notifications</a></Link></li>
<li className={styles.navbarLink}><Link href="/profile"><a>User Icon</a></Link></li>
<li className={styles.navbarLink}><Link href="/settings"><a>Settings</a></Link></li>
<li className={styles.navbarLink} onClick={handleLogout}>Logout</li>
<li className={styles.navbarLink} onClick={handleLogout}><a>Logout</a></li>
<li className={styles.navbarLink}><Link href={`/user/${user.username}`}><a><img className={styles.picture} src={user.picture}/></a></Link></li>
</ul> :
<div>
<ul className={styles.navbarNav}>
Expand Down
10 changes: 9 additions & 1 deletion components/Header/header.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,18 @@
padding: 1rem;
background-color: $color-primary;
color: $color-white;

align-items: center;

a{
text-decoration: none;
cursor: pointer;
}
}

.navbarNav{
display: flex;
flex-direction: row;
align-items: center;
list-style-type: none;
padding: 0;
margin: 0;
Expand All @@ -25,4 +28,9 @@
&:not(:last-child){
margin-right: 1rem;
}
}

.picture{
border-radius: 50%;
height: 35px;
}
Empty file removed components/utils.js
Empty file.
29 changes: 29 additions & 0 deletions contexts/authContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import React, { useContext, useEffect, useState } from 'react'

const AuthContext = React.createContext()

export const AuthProvider = ({children}) => {
const [user, setUser] = useState()

useEffect(() => {
if(!user){
fetch(`${process.env.API}/profile`, {
method: 'GET',
credentials: 'include'
})
.then(res => res.json())
.then(user => setUser(user))
.catch(err => console.log(err))
}
}, [user])

return(
<AuthContext.Provider value={[user, setUser]}>
{children}
</AuthContext.Provider>
)
}

export const useAuth = () => {
return useContext(AuthContext)
}
10 changes: 10 additions & 0 deletions lib/redirect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import Router from "next/router"

export const clientRedirect = (slug) => {
Router.replace(slug)
}

export const serverRedirect = (ctx, slug) => {
ctx.res.writeHead(301, {Location: slug})
ctx.res.end()
}
5 changes: 5 additions & 0 deletions mock/package-lock.json

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

3 changes: 2 additions & 1 deletion mock/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"cookie": "^0.4.1",
"cors": "^2.8.5",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1"
"jsonwebtoken": "^8.5.1",
"routes": "^2.1.0"
}
}
27 changes: 26 additions & 1 deletion mock/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const router = express.Router()
const cookie = require('cookie')

const auth = require('./auth')

const {getUserData, generateToken} = require('./utils')

const users = [
Expand Down Expand Up @@ -68,7 +69,7 @@ router.post('/login', (req, res) => {
domain: 'localhost',
expires: new Date(Date.now() + 6.048e+8)
}))
res.status(200).json({username})
res.status(200).json({user})
})

router.get('/profile', auth, (req, res) => {
Expand Down Expand Up @@ -116,4 +117,28 @@ router.post('/registration',(req,res)=>{

})

router.post('/registration',(req,res)=>{
let newuserdetails =new user({
name:req.body.name,
username:req.body.username,
phone:req.body.phonenumber,
location:req.body.location,
email:req.body.email,
password:req.body.password
})


newuserdetails.save((err)=> {
if(err){
res.json({msg: 'failed to add details'});
console.log(err);
res.status(401).send()
}
else{
res.json({msg:'details added'});
res.status(200).send()
}
})
})

module.exports = router
7 changes: 5 additions & 2 deletions mock/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const cors = require('cors')
const app = express()
const PORT = 5001


const corsOptions = {
origin: 'http://localhost:3000',
credentials: true
Expand All @@ -12,9 +13,11 @@ const corsOptions = {
app.use(cors(corsOptions))
app.use(express.json())

const routes = require('./routes')

const routes =require('./routes')

app.use('/api', routes)

app.listen(PORT, () => {
console.log("Mock Server Running of Port " + PORT)
})
})
11 changes: 11 additions & 0 deletions pages/500.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import Layout from '../components/Layout/layout'
import SEO from '../components/seo'

export default function Custom500() {
return (
<Layout>
<SEO title="Internal Server Error | Macebook"/>
<h1>500 - Internal Server Error</h1>
</Layout>
)
}
7 changes: 6 additions & 1 deletion pages/_app.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import '../styles/globals.scss'
import 'bootstrap/dist/css/bootstrap-grid.min.css'
import {AuthProvider} from '../contexts/authContext'

function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
return (
<AuthProvider>
<Component {...pageProps} />
</AuthProvider>
)
}

export default MyApp
14 changes: 8 additions & 6 deletions pages/feeds.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import Layout from '../components/Layout/layout'
import SEO from '../components/seo'
import Router from 'next/router'
import styles from '../styles/pages/feeds.module.scss'
import {clientRedirect, serverRedirect} from '../lib/redirect'

const Feeds = ({feeds}) => {
return(
Expand All @@ -14,20 +13,23 @@ const Feeds = ({feeds}) => {
}

Feeds.getInitialProps = async (ctx) => {
const res = await fetch(`${process.env.API}/feeds`, {
return handleFetch(ctx, `${process.env.API}/feeds`)
}

const handleFetch = async (ctx, route) => {
const res = await fetch(route, {
method: 'GET',
credentials: 'include',
headers: ctx.req ? {cookie: ctx.req.headers.cookie} : undefined
})

if(res.status === 401 && !ctx.req){
Router.replace('/login')
clientRedirect('/login')
return {}
}

if(res.status === 401 && ctx.req){
ctx.res.writeHead(301, {Location: '/login'})
ctx.res.end()
serverRedirect(ctx, '/login')
return {}
}

Expand Down
35 changes: 28 additions & 7 deletions pages/login.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import {useState} from 'react'
import {useState, useEffect} from 'react'
import SEO from '../components/seo'
import Layout from '../components/Layout/layout'
import Router from 'next/router'
import {useAuth} from '../contexts/authContext'
import {clientRedirect, serverRedirect} from '../lib/redirect'

const Login = () => {
const [username, updateUsername] = useState("charlotteli")
const [password, updatePassword] = useState("charlotteli")
const [user, setUser] = useAuth()

useEffect(() => {
if(user) clientRedirect('/feeds')
}, [user])

const handleClick = async (e) => {
e.preventDefault()
Expand All @@ -21,11 +27,10 @@ const Login = () => {
return alert("Invalid Username or Password")
}

if(res.status == 200){
console.log("You're Logged In!")
localStorage.setItem('macebook-isauth', true)
return Router.replace('/feeds')
}
console.log("You're Logged In!")
localStorage.setItem('macebook-isauth', true)
const data = await res.json()
setUser(data.user)
} catch (error) {
console.log("Server not responding!")
}
Expand Down Expand Up @@ -59,4 +64,20 @@ const Login = () => {
)
}

Login.getInitialProps = async (ctx) => {
if(ctx.res){
const res = await fetch(`${process.env.API}/feeds`, {
method: 'GET',
credentials: 'include',
headers: ctx.req ? {cookie: ctx.req.headers.cookie} : undefined
})

if(res.ok){
serverRedirect(ctx, '/feeds')
return {}
}
}
return {}
}

export default Login
13 changes: 8 additions & 5 deletions pages/messaging.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Layout from '../components/Layout/layout'
import SEO from '../components/seo'
import Router from 'next/router'
import styles from '../styles/pages/messaging.module.scss'
import { clientRedirect, serverRedirect } from '../lib/redirect'

const Messaging = ({messages}) => {
return(
Expand All @@ -14,20 +14,23 @@ const Messaging = ({messages}) => {
}

Messaging.getInitialProps = async (ctx) => {
const res = await fetch(`${process.env.API}/messages`, {
return handleFetch(ctx, `${process.env.API}/messages`)
}

const handleFetch = async (ctx, route) => {
const res = await fetch(route, {
method: 'GET',
credentials: 'include',
headers: ctx.req ? {cookie: ctx.req.headers.cookie} : undefined
})

if(res.status === 401 && !ctx.req){
Router.replace('/login')
clientRedirect('/login')
return {}
}

if(res.status === 401 && ctx.req){
ctx.res.writeHead(301, {Location: '/login'})
ctx.res.end()
serverRedirect(ctx, '/login')
return {}
}

Expand Down
Loading

0 comments on commit e4fa264

Please sign in to comment.