Skip to content

Instantly share code, notes, and snippets.

@vini-guerrero vini-guerrero/authState.js
Last active Oct 12, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.