Guest User

Untitled

a guest
Aug 14th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. import React, { Component } from 'react';
  2. import awsmobile from '../aws-exports';
  3. import Auth from '@aws-amplify/auth';
  4. import { Hub } from '@aws-amplify/core';
  5. import {withOAuth} from 'aws-amplify-react';
  6.  
  7. const config = Auth.configure(awsmobile) as any;
  8.  
  9. interface State { loggedIn: boolean, user?:{username: string, name:string, email: string} }
  10. class AWSApp extends Component<any, State> {
  11. public state:State = { loggedIn: false }
  12. constructor(props:any) {
  13. super(props);
  14. Hub.listen('auth', this)
  15. }
  16.  
  17. private handleWindowClose = async (e:any) => {
  18. e.preventDefault();
  19. Auth.signOut()
  20. .then()
  21. .catch( (err:any) => console.log(err))
  22. }
  23. public onHubCapsule(capsule:any) {
  24. const { channel, payload } = capsule; // source
  25. Auth.currentSession().then((data) => {
  26. console.log('+++currentSession2', data)
  27. //this.setState( { user:{...data.attributes, username: data.username}, loggedIn: true } )
  28. }).catch( (e:any) => {
  29. console.log('---currentSession2 err:', e)
  30. });
  31.  
  32. if (channel === 'auth' && payload.event === 'signIn') {
  33. Auth.currentAuthenticatedUser().then((data) => {
  34. console.log('+++currentAuthenticatedUser', data)
  35. this.setState( { user:{...data.attributes, username: data.username}, loggedIn: true } )
  36. });
  37.  
  38. }
  39. }
  40.  
  41. public componentWillMount():void {
  42. window.addEventListener('beforeunload', this.handleWindowClose);
  43. }
  44.  
  45. public componentWillUnMount() {
  46. window.removeEventListener('beforeunload', this.handleWindowClose);
  47. }
  48. //hide={[Greetings]}
  49. public render() {
  50. if(this.state.loggedIn)
  51. return (
  52. <div>Welcome {this.state.user!.name}</div>
  53. )
  54. return (
  55. <button onClick={this.props.OAuthSignIn}>
  56. Sign in with AWS
  57. </button>
  58. );
  59. }
  60. }
  61. export default withOAuth(AWSApp);
Add Comment
Please, Sign In to add comment