Last active
August 14, 2018 21:14
-
-
Save jadbox/b46f23664a2340953129a523ee7734c5 to your computer and use it in GitHub Desktop.
AWS cognito Hosted UI component - typescript - no persistence
This file contains hidden or 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, { Component } from 'react'; | |
import awsmobile from '../aws-exports'; | |
import Auth from '@aws-amplify/auth'; | |
import { Hub } from '@aws-amplify/core'; | |
import {withOAuth} from 'aws-amplify-react'; | |
const config = Auth.configure(awsmobile) as any; | |
interface State { loggedIn: boolean, user?:{username: string, name:string, email: string} } | |
class AWSApp extends Component<any, State> { | |
public state:State = { loggedIn: false } | |
constructor(props:any) { | |
super(props); | |
Hub.listen('auth', this) | |
} | |
private handleWindowClose = async (e:any) => { | |
e.preventDefault(); | |
Auth.signOut() | |
.then() | |
.catch( (err:any) => console.log(err)) | |
} | |
public onHubCapsule(capsule:any) { | |
const { channel, payload } = capsule; // source | |
Auth.currentSession().then((data) => { | |
console.log('+++currentSession2', data) | |
//this.setState( { user:{...data.attributes, username: data.username}, loggedIn: true } ) | |
}).catch( (e:any) => { | |
console.log('---currentSession2 err:', e) | |
}); | |
if (channel === 'auth' && payload.event === 'signIn') { | |
Auth.currentAuthenticatedUser().then((data) => { | |
console.log('+++currentAuthenticatedUser', data) | |
this.setState( { user:{...data.attributes, username: data.username}, loggedIn: true } ) | |
}); | |
} | |
} | |
public componentWillMount():void { | |
window.addEventListener('beforeunload', this.handleWindowClose); | |
} | |
public componentWillUnMount() { | |
window.removeEventListener('beforeunload', this.handleWindowClose); | |
} | |
//hide={[Greetings]} | |
public render() { | |
if(this.state.loggedIn) | |
return ( | |
<div>Welcome {this.state.user!.name}</div> | |
) | |
return ( | |
<button onClick={this.props.OAuthSignIn}> | |
Sign in with AWS | |
</button> | |
); | |
} | |
} | |
export default withOAuth(AWSApp); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment