Skip to content

Instantly share code, notes, and snippets.

@vini-guerrero
Last active October 12, 2018 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vini-guerrero/5fcc0c251f451f32fa14c54a04ab3d84 to your computer and use it in GitHub Desktop.
Save vini-guerrero/5fcc0c251f451f32fa14c54a04ab3d84 to your computer and use it in GitHub Desktop.
import React from 'react'
import { BrowserRouter as Router, Route, Link, Redirect, withRouter } from 'react-router-dom'
import authState from './CoreComponents/authState'
import PrivateRoute from './CoreComponents/privateRoute'
import fakeAuth from './CoreComponents/fakeAuth'
const Public = () => <h3>Public</h3>
const Protected = () => <h3>Protected</h3>
class Login extends React.Component {
state = {
redirectToReferrer: false
}
login = () => {
authState.authenticate((res) => {
console.log(res)
});
fakeAuth.authenticate(() => {
this.setState(() => ({
redirectToReferrer: true
}))
})
// authState.getUsers((res) => {
// console.log(res)
// });
}
render() {
const { from } = this.props.location.state || { from: { pathname: '/' } }
const { redirectToReferrer } = this.state
if (redirectToReferrer === true) {
return <Redirect to={from} />
}
return (
<div>
<p>You must log in to view the page</p>
<button onClick={this.login}>Log in</button>
</div>
)
}
}
const AuthButton = withRouter(({ history }) => (
fakeAuth.isAuthenticated ? (
<p>
Welcome! <button onClick={() => {
fakeAuth.signout(() => history.push('/'))
}}>Sign out</button>
</p>
) : (
<p>You are not logged in.</p>
)
))
export default function AuthExample () {
return (
<Router>
<div>
<AuthButton/>
<ul>
<li><Link to="/public">Public Page</Link></li>
<li><Link to="/protected">Protected Page</Link></li>
</ul>
<Route path="/public" component={Public}/>
<Route path="/login" component={Login}/>
<PrivateRoute path='/protected' component={Protected} />
</div>
</Router>
)
}
module.exports = {
authenticate: function(callback){
var data = { email: "test@test.com", password:"123" }
var url = "https://reqres.in/api/login";
fetch(url, {
method: 'POST',
mode: 'CORS',
body: JSON.stringify(data),
headers: {'Content-Type': 'application/json'}
}).then(res => res.json()).then((result) => {
callback(result);
}, (error) => {
callback(result);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment