Skip to content

Commit

Permalink
Chapter03 and 04/mern-skeleton
Browse files Browse the repository at this point in the history
  • Loading branch information
shamahoque committed Apr 14, 2020
1 parent 8677848 commit 994c6e1
Show file tree
Hide file tree
Showing 38 changed files with 7,569 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Chapter03 and 04/mern-skeleton/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"presets": [
["@babel/preset-env",
{
"targets": {
"node": "current"
}
}
],
"@babel/preset-react"
],
"plugins": [
"react-hot-loader/babel"
]
}
4 changes: 4 additions & 0 deletions Chapter03 and 04/mern-skeleton/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/node_modules/
/dist/
/data/
npm-debug.log
21 changes: 21 additions & 0 deletions Chapter03 and 04/mern-skeleton/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Shama Hoque

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
21 changes: 21 additions & 0 deletions Chapter03 and 04/mern-skeleton/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# MERN Skeleton

A skeleton application with basic user CRUD and auth features - developed using React, Node, Express and MongoDB.

![MERN Skeleton](https://mernbook.s3.amazonaws.com/git+/skeleton2.png "MERN Skeleton")

### [Live Demo](http://skeleton2.mernbook.com/ "MERN Skeleton")

#### What you need to run this code
1. Node (13.12.0)
2. NPM (6.14.4)
3. MongoDB (4.2.0)

#### How to run this code
1. Make sure MongoDB is running on your system
2. Clone this repository
3. Open command line in the cloned folder,
- To install dependencies, run ``` yarn ```
- To run the application for development, run ``` yarn development ```
4. Open [localhost:3000](http://localhost:3000/) in the browser
----
23 changes: 23 additions & 0 deletions Chapter03 and 04/mern-skeleton/client/App.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import React from 'react'
import MainRouter from './MainRouter'
import {BrowserRouter} from 'react-router-dom'
import { ThemeProvider } from '@material-ui/styles'
import theme from './theme'
import { hot } from 'react-hot-loader'

const App = () => {
React.useEffect(() => {
const jssStyles = document.querySelector('#jss-server-side')
if (jssStyles) {
jssStyles.parentNode.removeChild(jssStyles)
}
}, [])
return (
<BrowserRouter>
<ThemeProvider theme={theme}>
<MainRouter/>
</ThemeProvider>
</BrowserRouter>
)}

export default hot(module)(App)
26 changes: 26 additions & 0 deletions Chapter03 and 04/mern-skeleton/client/MainRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import React from 'react'
import {Route, Switch} from 'react-router-dom'
import Home from './core/Home'
import Users from './user/Users'
import Signup from './user/Signup'
import Signin from './auth/Signin'
import EditProfile from './user/EditProfile'
import Profile from './user/Profile'
import PrivateRoute from './auth/PrivateRoute'
import Menu from './core/Menu'

const MainRouter = () => {
return (<div>
<Menu/>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/users" component={Users}/>
<Route path="/signup" component={Signup}/>
<Route path="/signin" component={Signin}/>
<PrivateRoute path="/user/edit/:userId" component={EditProfile}/>
<Route path="/user/:userId" component={Profile}/>
</Switch>
</div>)
}

export default MainRouter
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 18 additions & 0 deletions Chapter03 and 04/mern-skeleton/client/auth/PrivateRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import React, { Component } from 'react'
import { Route, Redirect } from 'react-router-dom'
import auth from './auth-helper'

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
auth.isAuthenticated() ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/signin',
state: { from: props.location }
}}/>
)
)}/>
)

export default PrivateRoute
100 changes: 100 additions & 0 deletions Chapter03 and 04/mern-skeleton/client/auth/Signin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import React, {useState} from 'react'
import Card from '@material-ui/core/Card'
import CardActions from '@material-ui/core/CardActions'
import CardContent from '@material-ui/core/CardContent'
import Button from '@material-ui/core/Button'
import TextField from '@material-ui/core/TextField'
import Typography from '@material-ui/core/Typography'
import Icon from '@material-ui/core/Icon'
import { makeStyles } from '@material-ui/core/styles'
import auth from './../auth/auth-helper'
import {Redirect} from 'react-router-dom'
import {signin} from './api-auth.js'

const useStyles = makeStyles(theme => ({
card: {
maxWidth: 600,
margin: 'auto',
textAlign: 'center',
marginTop: theme.spacing(5),
paddingBottom: theme.spacing(2)
},
error: {
verticalAlign: 'middle'
},
title: {
marginTop: theme.spacing(2),
color: theme.palette.openTitle
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
width: 300
},
submit: {
margin: 'auto',
marginBottom: theme.spacing(2)
}
}))

export default function Signin(props) {
const classes = useStyles()
const [values, setValues] = useState({
email: '',
password: '',
error: '',
redirectToReferrer: false
})

const clickSubmit = () => {
const user = {
email: values.email || undefined,
password: values.password || undefined
}

signin(user).then((data) => {
if (data.error) {
setValues({ ...values, error: data.error})
} else {
auth.authenticate(data, () => {
setValues({ ...values, error: '',redirectToReferrer: true})
})
}
})
}

const handleChange = name => event => {
setValues({ ...values, [name]: event.target.value })
}

const {from} = props.location.state || {
from: {
pathname: '/'
}
}
const {redirectToReferrer} = values
if (redirectToReferrer) {
return (<Redirect to={from}/>)
}

return (
<Card className={classes.card}>
<CardContent>
<Typography variant="h6" className={classes.title}>
Sign In
</Typography>
<TextField id="email" type="email" label="Email" className={classes.textField} value={values.email} onChange={handleChange('email')} margin="normal"/><br/>
<TextField id="password" type="password" label="Password" className={classes.textField} value={values.password} onChange={handleChange('password')} margin="normal"/>
<br/> {
values.error && (<Typography component="p" color="error">
<Icon color="error" className={classes.error}>error</Icon>
{values.error}
</Typography>)
}
</CardContent>
<CardActions>
<Button color="primary" variant="contained" onClick={clickSubmit} className={classes.submit}>Submit</Button>
</CardActions>
</Card>
)
}
30 changes: 30 additions & 0 deletions Chapter03 and 04/mern-skeleton/client/auth/api-auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const signin = async (user) => {
try {
let response = await fetch('/auth/signin/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify(user)
})
return await response.json()
} catch(err) {
console.log(err)
}
}

const signout = async () => {
try {
let response = await fetch('/auth/signout/', { method: 'GET' })
return await response.json()
} catch(err) {
console.log(err)
}
}

export {
signin,
signout
}
29 changes: 29 additions & 0 deletions Chapter03 and 04/mern-skeleton/client/auth/auth-helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { signout } from './api-auth.js'

const auth = {
isAuthenticated() {
if (typeof window == "undefined")
return false

if (sessionStorage.getItem('jwt'))
return JSON.parse(sessionStorage.getItem('jwt'))
else
return false
},
authenticate(jwt, cb) {
if (typeof window !== "undefined")
sessionStorage.setItem('jwt', JSON.stringify(jwt))
cb()
},
clearJWT(cb) {
if (typeof window !== "undefined")
sessionStorage.removeItem('jwt')
cb()
//optional
signout().then((data) => {
document.cookie = "t=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"
})
}
}

export default auth
51 changes: 51 additions & 0 deletions Chapter03 and 04/mern-skeleton/client/core/Home.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Card from '@material-ui/core/Card'
import CardContent from '@material-ui/core/CardContent'
import CardMedia from '@material-ui/core/CardMedia'
import Typography from '@material-ui/core/Typography'
import unicornbikeImg from './../assets/images/unicornbike.jpg'

const useStyles = makeStyles(theme => ({
card: {
maxWidth: 600,
margin: 'auto',
marginTop: theme.spacing(5),
marginBottom: theme.spacing(5)
},
title: {
padding:`${theme.spacing(3)}px ${theme.spacing(2.5)}px ${theme.spacing(2)}px`,
color: theme.palette.openTitle
},
media: {
minHeight: 400
},
credit: {
padding: 10,
textAlign: 'right',
backgroundColor: '#ededed',
borderBottom: '1px solid #d0d0d0',
'& a':{
color: '#3f4771'
}
}
}))

export default function Home(){
const classes = useStyles()
return (
<Card className={classes.card}>
<Typography variant="h6" className={classes.title}>
Home Page
</Typography>
<CardMedia className={classes.media} image={unicornbikeImg} title="Unicorn Bicycle"/>
<Typography variant="body2" component="p" className={classes.credit} color="textSecondary">Photo by <a href="https://unsplash.com/@boudewijn_huysmans" target="_blank" rel="noopener noreferrer">Boudewijn Huysmans</a> on Unsplash</Typography>
<CardContent>
<Typography variant="body1" component="p">
Welcome to the MERN Skeleton home page.
</Typography>
</CardContent>
</Card>
)
}

Loading

0 comments on commit 994c6e1

Please sign in to comment.