Skip to content

Instantly share code, notes, and snippets.

@hardikmodi1
Last active May 6, 2018 03:28
Show Gist options
  • Select an option

  • Save hardikmodi1/d348e9bb33f0be66c618709e7210850b to your computer and use it in GitHub Desktop.

Select an option

Save hardikmodi1/d348e9bb33f0be66c618709e7210850b to your computer and use it in GitHub Desktop.
import React from 'react';
import {Input,Card,ProgressBar} from 'react-materialize';
import { Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {setToken,getToken} from '../../actions/userAction';
import Error from '../messages/Error';
import google from '../social/GoogleLogin/google.png';
import facebook from '../social/FacebookLogin/facebook.png'
import linkedin from '../social/LinkedinLogin/linkedin.png'
class Login extends React.Component{
constructor(props){
super(props);
this.state={
data:{
email:'',
password:''
},
message:"",
loading:false,
success:'',
token:'',
url:''
};
}
componentDidMount(){
(function() {
var e = document.createElement("script");
e.type = "text/javascript";
e.async = true;
e.src = "http://platform.linkedin.com/in.js?async=true";
var t = document.getElementsByTagName("script")[0];
t.parentNode.insertBefore(e, t)
})();
(function() {
var e = document.createElement("script");
e.type = "text/javascript";
e.async = true;
e.src = "https://apis.google.com/js/client:platform.js?onload=gPOnLoad";
var t = document.getElementsByTagName("script")[0];
t.parentNode.insertBefore(e, t)
})();
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function() {
window.FB.init({
appId : '706009833122516',
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page
version : 'v2.8' // use version 2.1
});
};
}
//Trigger Login for LinkedIn
linkedinLogin = () => {
window.IN.init({
api_key : '81t0sfdemt3ddn',
scope: 'r_emailaddress'
});
setTimeout(function(){
this.getUserDetails()
}.bind(this),1000);
console.log( "Loaded" )
}
linkedlogin=email=>{
console.log(email);
}
getUserDetails = () => {
this.setState({
...this.state,
loading:true
})
var that=this;
this.setState({
...this.state,
loading:true
})
if(window.IN.User.isAuthorized){
window.IN.User.authorize( function(){
window.IN.API.Profile("me")
.fields(["id", "email-address", "firstName", "lastName", "pictureUrl", "publicProfileUrl"])
.result(function(result) {
console.log(result);
that.setState({
...that.state,
loading:true
},()=>{
fetch('/api/google/login',{
method: 'POST',
headers:{
'content-type': 'application/json'
},
body: JSON.stringify({email:result.values[0].emailAddress})
})
.then(res=>res.json())
.then(data=>{
if(data.success){
that.props.setToken(data.token)
.then(()=>{
that.setState({
...that.state,
loading:false,
success:"true",
url:'/dashboard',
message:data.message
})
})
}
else{
that.setState({
...that.state,
loading:false,
success:"false",
message:data.message
})
}
})
})
})
.error(function(err) {
console.log('Import error - Error occured while importing data')
});
});
}
else{
console.log("Ds");
}
}
//Triggering login for google
googleLogin = () => {
// let response = null;
window.gapi.auth.signIn({
callback: function(authResponse) {
this.googleSignInCallback( authResponse )
}.bind( this ),
clientid: '169005465504-lbb3lia2nf2qpvoifv6dkrhv563je15n.apps.googleusercontent.com', //Google client Id
cookiepolicy: "single_host_origin",
requestvisibleactions: "http://schema.org/AddAction",
scope: "https://www.googleapis.com/auth/plus.login email"
})
}
facebookLogin = () => {
/*window.FB.login(
this.checkLoginState(),
{ scope : 'email, public_profile' } //Add scope whatever you need about the facebook user
); */
window.FB.login(
function(resp){
this.statusChangeCallback(resp);
}.bind(this),{ scope : 'email,user_work_history,user_education_history,user_location,public_profile' });
}
googleSignInCallback = (e) => {
if (e["status"]["signed_in"]) {
window.gapi.client.load("plus", "v1", function() {
if (e["access_token"]) {
this.getUserGoogleProfile( e["access_token"] )
} else if (e["error"]) {
console.log('Import error', 'Error occured while importing data')
}
}.bind(this));
} else {
console.log('Oops... Error occured while importing data')
}
}
checkLoginState() {
alert("Checking Login Status")
console.log( "Checking login status..........." );
window.FB.getLoginStatus(function(response) {
alert("FB Callback")
console.log("----------->")
console.log(response)
this.statusChangeCallback(response);
}.bind(this));
}
statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
alert( "Connected to facebook. Retriving user from fb" );
// Logged into your app and Facebook.
this.fetchDataFacebook();
} else if (response.status === 'not_authorized') {
console.log('Import error', 'Authorize app to import data', 'error')
} else {
console.log('Import error', 'Error occured while importing data', 'error')
}
}
fetchDataFacebook = () => {
console.log('Welcome! Fetching your information.... ');
window.FB.api('/me', function(user) {
console.log( user );
console.log('Successful login from facebook : ' + user.name);
alert( 'Successful login for: ' + user.name );
});
}
getUserGoogleProfile = accesstoken => {
var e = window.gapi.client.plus.people.get({
userId: "me"
});
e.execute(function(e) {
if (e.error) {
console.log(e.message);
console.log('Import error - Error occured while importing data')
return
} else if (e.id) {
//Profile data
this.setState({
...this.state,
loading:true
},()=>{
fetch('/api/google/login',{
method: 'POST',
headers:{
'content-type': 'application/json'
},
body: JSON.stringify({email:e.emails[0].value})
})
.then(res=>res.json())
.then(data=>{
if(data.success){
this.props.setToken(data.token)
.then(()=>{
this.setState({
...this.state,
loading:false,
success:"true",
url:'/dashboard',
message:data.message
})
})
}
else{
this.setState({
...this.state,
loading:false,
success:"false",
message:data.message
})
}
})
})
return;
}
}.bind(this));
}
onSubmit=function(e){
e.preventDefault();
if(this.state.data.email!=="" && this.state.data.firstname!=="" && this.state.data.lastname!=="" && this.state.data.intrest!==""){
this.setState({
...this.state,
loading:true
},()=>{
setTimeout(()=>{
fetch('https://vizack-203204/api/authenticate',{
method: 'POST',
headers:{
'content-type': 'application/json'
},
body: JSON.stringify(this.state.data)
})
.then(res=>res.json())
.then(data=>{
if(data.success==="warning"){
this.setState({
...this.state,
loading:false,
success:"warning",
message:data.message
})
}
else if(data.success){
this.props.setToken(data.token)
.then(()=>{
this.setState({
...this.state,
token:data.token,
url:'/dashboard',
loading:false,
success:"true",
message:data.message
})
})
}
else{
this.setState({
...this.state,
loading:false,
success:"false",
message:data.message
})
}
})
},2000)
});
}
}
onChange=function(e){
this.setState({
data: { ...this.state.data, [e.target.name]: e.target.value }
});
}
render(){
return(
<div>
{this.state.url && <Redirect to="/dashboard" />}
{this.state.loading ? <ProgressBar className="progressBar" /> : ""}
<Card className="card">
<div className="card-body">
<h1 className="signup">Login</h1>
{this.state.success==="warning"? (<div><Error text={this.state.message} class1={"errornormal"} /><br /><a href="/resend">Resend activation link</a></div>) : (this.state.success==="true" ? <Error text={this.state.message} class1={"successnormal"} /> : <Error text={this.state.message} class1={"errornormal"} />) }
<form onSubmit={this.onSubmit.bind(this)}>
<div className="form-group">
<Input
type="email"
className="form-control"
id="email"
name="email"
label="Email"
value={this.state.data.email}
onChange={this.onChange.bind(this)} />
</div>
<div className="form-group">
<Input
type="password"
className="form-control"
id="password"
name="password"
label="Password"
value={this.state.data.password}
onChange={this.onChange.bind(this)} />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
<a className="forget" href="/forgotpassword">Forgot Password? </a>
<br />
<img className="responsive-img btn google" src={google} title="google login" alt="google" onClick={ () => this.googleLogin() }/>
<br />
<img className="responsive-img btn google" src={facebook} title="facebook login" alt="facebook" onClick={ () => this.facebookLogin() } />
<br />
<img className="responsive-img btn google" src={linkedin} title="linkedin login" alt="linkedin" onClick={ () => this.linkedinLogin() }/>
</Card>
</div>
);
}
}
Login.propTypes={
getToken: PropTypes.func.isRequired,
setToken: PropTypes.func.isRequired
};
const mapStateToProps=state=>({
token:state.user.token
});
export default connect(mapStateToProps,{setToken,getToken})(Login);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment