Last active
October 12, 2018 02:49
-
-
Save vini-guerrero/5fcc0c251f451f32fa14c54a04ab3d84 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: "[email protected]", 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