aws-amplify#Auth JavaScript Examples

The following examples show how to use aws-amplify#Auth. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: App.js    From ecs-apigateway-sample with MIT License 6 votes vote down vote up
MyPropsMethods.invokeAPI = ( e, enableFormSubmission, selectedMethod, selectedAPI, selectedVariable, selectedPayload, authState ) => {

  e.preventDefault()
  if( !enableFormSubmission ) return alert("Error: All fields are mandatory.")

  if( authState == 'signedin' ){
    Auth.currentSession().then( tokens => {
          MyPropsMethods.AjaxCall( selectedMethod, selectedAPI, selectedVariable, selectedPayload, tokens.accessToken.jwtToken )
    })
  } else{
          MyPropsMethods.AjaxCall( selectedMethod, selectedAPI, selectedVariable, selectedPayload )
  }

}
Example #2
Source File: ScreenSharing.js    From allscreens with GNU General Public License v3.0 6 votes vote down vote up
async componentDidMount() {
        const user = await Auth.currentAuthenticatedUser();
        const email = user.attributes.email;
        console.log(email);

        this.onCreateScreenSharingTicketSubscription = API.graphql(
            graphqlOperation(subscriptions.onCreateScreenSharingTicket, { email })
        ).subscribe({
            next: data => {
                const ticket = data.value.data.onCreateScreenSharingTicket;
                console.log(ticket);
                this.setState({ ticket });
            }
        });
    }
Example #3
Source File: ClassRoom.js    From allscreens with GNU General Public License v3.0 6 votes vote down vote up
async componentDidMount() {
        const { username } = await Auth.currentAuthenticatedUser();

        let { data } = await API.graphql(graphqlOperation(queries.listClassRooms, { owner: username }));
        console.log(data);
        this.setState({ classrooms: data.listClassRooms.items });

        this.onDeleteClassRoomSubscription = API.graphql(
            graphqlOperation(subscriptions.onDeleteClassRoom, { owner: username })
        ).subscribe({
            next: data => {
                console.log(data);
                const classroom = data.value.data.onDeleteClassRoom;
                const classrooms = [
                    ...this.state.classrooms.filter(r => {
                        return r.name !== classroom.name;
                    })
                ];
                this.setState({ classrooms });
            }
        });

        this.onCreateClassRoomSubscription = API.graphql(
            graphqlOperation(subscriptions.onCreateClassRoom, { owner: username })
        ).subscribe({
            next: data => {
                console.log(data);
                const classroom = data.value.data.onCreateClassRoom;
                const classrooms = [
                    ...this.state.classrooms,
                    classroom
                ];
                this.setState({ classrooms });
            }
        });
    }
Example #4
Source File: S3Store.js    From aws-perspective with Apache License 2.0 6 votes vote down vote up
uploadTemplate = async (key, content, type) => {
  return Storage.put(key, content, {
    acl: 'public-read',
    contentType: type,
    metadata: {
      username: `${await Auth.currentAuthenticatedUser().then(
        (response) => response.username
      )}`,
    },
  });
}
Example #5
Source File: S3Store.js    From aws-perspective with Apache License 2.0 6 votes vote down vote up
uploadObject = async (key, content, level, type) => {
  return Storage.put(key, content, {
    level: level,
    contentType: type,
    metadata: {
      username: `${await Auth.currentAuthenticatedUser().then(
        (response) => response.username
      )}`,
    },
  });
}
Example #6
Source File: APIHandler.js    From aws-perspective with Apache License 2.0 6 votes vote down vote up
sendDrawioPostRequest = async (query, processor) => {
  let apiName = 'PerspectiveDrawioWebRestAPI';
  let path = `/resources`;
  let myInit = {
    body: query.body,
    headers: {
      Authorization: `Bearer ${(await Auth.currentSession())
        .getIdToken()
        .getJwtToken()}`,
    },
  };

  return API.post(apiName, path, myInit)
    .then((response) => {
      return wrapResponse(processor(response, query.params), false);
    })
    .catch((error) => {
      return wrapResponse(error, true);
    });
}
Example #7
Source File: APIHandler.js    From aws-perspective with Apache License 2.0 6 votes vote down vote up
sendPostRequest = async (query, processor) => {
  let apiName = 'PerspectiveWebRestAPI';
  let path = `/resources`;
  let myInit = {
    body: query.body,
    headers: {
      Authorization: `Bearer ${(await Auth.currentSession())
        .getIdToken()
        .getJwtToken()}`,
    },
  };
  return API.post(apiName, path, myInit)
    .then((response) => {
      return wrapResponse(processor(response, query.params), false);
    })
    .catch((error) => {
      return wrapResponse(error, true);
    });
}
Example #8
Source File: APIHandler.js    From aws-perspective with Apache License 2.0 6 votes vote down vote up
sendGetRequest = async (query, processor) => {
  let apiName = 'PerspectiveWebRestAPI';
  let path = `/resources${query.command}`;
  let myInit = {
    headers: {
      Authorization: `Bearer ${(await Auth.currentSession())
        .getIdToken()
        .getJwtToken()}`,
    },
  };

  return API.get(apiName, path, myInit)
    .then((response) => {
      return wrapResponse(processor(response, query.params), false);
    })
    .catch((error) => {
      return wrapResponse(error, true);
    });
}
Example #9
Source File: handleIdpLogin.js    From aws-amplify-identity-broker with MIT License 6 votes vote down vote up
async function handleIdpLogin(identity_provider) {
	const queryStringParams = new URLSearchParams(window.location.search);
	const redirect_uri = queryStringParams.get("redirect_uri");
	const authorization_code = queryStringParams.get("authorization_code");
	const clientState = queryStringParams.get("state");

	if (redirect_uri) {
		localStorage.setItem(`client-redirect-uri`, redirect_uri);
	}
	if (authorization_code) {
		localStorage.setItem(`authorization_code`, authorization_code);
	}
	if (clientState) {
		localStorage.setItem(`client-state`, clientState);
	}

	await Auth.federatedSignIn({ provider: identity_provider });
}
Example #10
Source File: checkForceAuth.js    From aws-amplify-identity-broker with MIT License 6 votes vote down vote up
checkForceAuth = async () => {
	const forceAuth = new URLSearchParams(window.location.search).get("forceAuth") || false;

	if (forceAuth) {
		eraseCookie("id_token");
		eraseCookie("access_token");
		eraseCookie("refresh_token");

		localStorage.removeItem("client-id");

		await Auth.signOut();
	}
}
Example #11
Source File: ForgotPasswordForm.js    From vch-mri with MIT License 6 votes vote down vote up
async handleSubmit(e) {
        e.preventDefault();
        const { history } = this.props;
        try {
            await Auth.forgotPassword(this.state.email.trim());
            sendSuccessToast("Request received! Please check your email for a verification code and enter a new password.");
            history.push('/reset');
        } catch (e) {
            console.log(e);
            this.setState({ error: e.message });
        }
    }
Example #12
Source File: transcript.js    From chime-voiceconnector-agent-assist with MIT No Attribution 6 votes vote down vote up
export function mergeAndComprehendTranscript(segments) {
  const mergedSegments = mergeTranscript(segments);
  Auth.currentCredentials().then(credentials => {
    const Comprehend = new AWS.Comprehend({
      region: defaultRegion,
      credentials: Auth.essentialCredentials(credentials),
    });
    mergedSegments.forEach((segment, i) => {
      if (segment.Speaker !== 'spk_0') {
        const params = {
          LanguageCode: 'en',
          Text: segment.Transcript,
        };
        Comprehend.detectSentiment(params, (error, sentimentResponse) => {
          showSentiment(error, segment, i, sentimentResponse);
        });
        Comprehend.detectKeyPhrases(params, (error, keyphraseResponse) => {
          showKeyphrases(error, segment, i, keyphraseResponse);
        });
      }
    });
  });
  return mergedSegments;
}
Example #13
Source File: sts.js    From chime-voiceconnector-agent-assist with MIT No Attribution 6 votes vote down vote up
export function getAWSAccountId() {
  return Auth.currentCredentials().then(creds => {
    const sts = new AWS.STS({
      region: defaultRegion,
      credentials: Auth.essentialCredentials(creds),
    });
    return sts.getCallerIdentity({}).promise();
  });
}
Example #14
Source File: elasticsearch.js    From chime-voiceconnector-agent-assist with MIT No Attribution 6 votes vote down vote up
export function retrieveTranscriptForTransactionId(transactionId) {
  return Auth.currentCredentials().then(creds => {
    const ddb = new AWS.DynamoDB.DocumentClient({
      region: defaultRegion,
      credentials: Auth.essentialCredentials(creds),
    });

    const params = {
      TableName: config.transcriptTableName,
      KeyConditionExpression: '#id = :id',
      ExpressionAttributeNames: {
        '#id': TRANSCRIPT_TABLE_KEYS.TRANSACTION_ID,
      },
      ExpressionAttributeValues: {
        ':id': transactionId,
      },
    };

    return ddb
      .query(params)
      .promise()
      .then((data) => {
        if (data.Count === 0) {
          return [];
        }

        return data.Items.filter(item => item.IsFinal !== true);
      });
  });
}
Example #15
Source File: RegisterForm.js    From vch-mri with MIT License 6 votes vote down vote up
async handleSubmit(e) {
        e.preventDefault();
        const { history } = this.props;
        try {
            await Auth.signUp({
                username: this.state.email.trim(),
                password: this.state.password.trim(),
                attributes: {
                    email: this.state.email.trim(),
                    name: this.state.name.trim()
                }
            });
            sendSuccessToast("Registration Successful! Please check your email for a verification code.");
            history.push('/verify');
        } catch (e) {
            console.log(e);
            this.setState({ error: e.message });
        }

    }
Example #16
Source File: ResetPasswordForm.js    From vch-mri with MIT License 6 votes vote down vote up
async handleSubmit(e) {
        e.preventDefault();
        const { history } = this.props;
        try {
            await Auth.forgotPasswordSubmit(this.state.email.trim(), this.state.code.trim(), this.state.password.trim());
            sendSuccessToast("Password change successful!");
            history.push('/login');
        } catch (e) {
            console.log(e);
            this.setState({ error: e.message });
        }
    }
Example #17
Source File: elasticsearch.js    From chime-voiceconnector-agent-assist with MIT No Attribution 6 votes vote down vote up
export function getSignedUrl(bucket, objectKey) {
  return Auth.currentCredentials().then(creds => {
    const s3 = new AWS.S3({
      region: defaultRegion,
      credentials: Auth.essentialCredentials(creds),
      signatureVersion: 'v4',
    });

    return s3.getSignedUrlPromise('getObject', { Bucket: bucket, Key: objectKey });
  });
}
Example #18
Source File: audio.js    From chime-voiceconnector-agent-assist with MIT No Attribution 6 votes vote down vote up
export function getMergedAudioURL(bucket, oneAudioObject, otherAudioObject, transactionId) {
  return Auth.currentCredentials().then(creds => {
    const lambda = new AWS.Lambda({
      region: defaultRegion,
      credentials: Auth.essentialCredentials(creds),
    });

    const params = {
      FunctionName: MERGE_AUDIO_LAMBDA_FUNCTION_NAME,
      InvocationType: 'RequestResponse',
    };

    params['Payload'] = Buffer.from(
      JSON.stringify({
        bucket: bucket,
        oneAudioObject: oneAudioObject,
        otherAudioObject: otherAudioObject,
        transactionId: transactionId,
      })
    );
    return lambda
      .invoke(params)
      .promise()
      .then(data => {
        const body = JSON.parse(data.Payload).body;
        if (body !== undefined) {
          const urlFromLambda = body.url;

          if (urlFromLambda === undefined) {
            return '';
          }
          return urlFromLambda;
        } else {
          return '';
        }
      });
  });
}
Example #19
Source File: VerifyForm.js    From vch-mri with MIT License 6 votes vote down vote up
async handleSubmit(e) {
        e.preventDefault();
        const { history } = this.props;
        try {
            await Auth.confirmSignUp(this.state.email.trim(), this.state.code.trim());
            sendSuccessToast("Verification Successful!");
            history.push('/login');
        } catch (e) {
            console.log(e);
            this.setState({ error: e.message });
        }
    }
Example #20
Source File: Screens.js    From aws-amplify-quick-notes with MIT No Attribution 6 votes vote down vote up
Screens = () => {
  const [tabIndex, setTabIndex] = useState(0);

  return (
    <>
      <Header>
        <Title>Quick Notes</Title>
        <SignOutButton
          onClick={() => {
            Auth.signOut().then(() => window.location.reload());
          }}
        >
          Sign Out
        </SignOutButton>
      </Header>
      <StyledTabs index={tabIndex} onChange={index => setTabIndex(index)}>
        <StyledTabList>
          <StyledTab>Notes</StyledTab>
          <StyledTab>Record</StyledTab>
        </StyledTabList>
        <StyledTabPanels>
          <StyledTabPanel>
            {tabIndex === 0 && <Notes setTabIndex={setTabIndex} />}
          </StyledTabPanel>
          <StyledTabPanel>
            {tabIndex === 1 && <Record setTabIndex={setTabIndex} />}
          </StyledTabPanel>
        </StyledTabPanels>
      </StyledTabs>
    </>
  );
}
Example #21
Source File: Navbar.js    From vch-mri with MIT License 6 votes vote down vote up
async handleLogout() {
        const { history } = this.props;
        try {
            await Auth.signOut({global: true});
            Cache.removeItem(AUTH_USER_ACCESS_TOKEN_KEY);
            Cache.removeItem(AUTH_USER_ID_TOKEN_KEY);
            this.props.logout();
            history.push('/login');
        } catch (e) {
            console.log('error signing out: ', e);
        }
    }
Example #22
Source File: App.js    From aws-amplify-quick-notes with MIT No Attribution 6 votes vote down vote up
function App() {
  const [state, setState] = useState({ isLoggedIn: false, user: null });

  const checkLoggedIn = () => {
    Auth.currentAuthenticatedUser()
      .then(data => {
        const user = { username: data.username, ...data.attributes };
        setState({ isLoggedIn: true, user });
      })
      .catch(error => console.log(error));
  };

  useEffect(() => {
    checkLoggedIn();
  }, []);

  return state.isLoggedIn ? (
    <Screens />
  ) : (
    <>
      <Title>Quick Notes</Title>
      <Authenticator
        onStateChange={authState => {
          if (authState === "signedIn") {
            checkLoggedIn();
          }
        }}
        amplifyConfig={awsExports}
        theme={theme}
      />
    </>
  );
}
Example #23
Source File: CognitoAuth.js    From voicemail-for-amazon-connect with Apache License 2.0 6 votes vote down vote up
componentDidMount() {
    // we only want to do this if code isn't
    if (!this.props.location || !this.props.location.search.startsWith("?code=")) {
      Auth.currentAuthenticatedUser().then(user => {
        history.push('/agents');
      }).catch(e => {
        Auth.federatedSignIn();
      });
    }
  }
Example #24
Source File: header.js    From aws-amplify-gatsby-auth with MIT License 6 votes vote down vote up
Header = ({ siteTitle }) => (
  <div
    style={{
      background: 'rebeccapurple',
      marginBottom: '1.45rem',
    }}
  >
    <div
      style={{
        margin: '0 auto',
        maxWidth: 960,
        padding: '1.45rem 1.0875rem',
      }}
    >
      <h1 style={{ margin: 0 }}>
        <Link
          to="/"
          style={styles.headerTitle}
        >
          {siteTitle}
        </Link>
      </h1>
      {
        isLoggedIn() && (
          <p
            onClick={
              () => Auth.signOut().then(logout(() => navigate('/app/login'))).catch(err => console.log('eror:', err))
            }
            style={styles.link}
          >Sign Out</p>
        )
      }
    </div>
  </div>
)
Example #25
Source File: CCPData.js    From aws-amplify-connect with MIT No Attribution 6 votes vote down vote up
componentDidMount() {
    this._isMounted = true;
    let group = ''

    Auth.currentAuthenticatedUser().then(user => {
      //console.log(user);
      group = user['signInUserSession']['idToken']['payload']['cognito:groups'][0]
      console.log('Primary Group: ' + group)
      if (this._isMounted) {
        this.setState({ primarygroup: group })
      }
    }).catch(e => {
      console.log(e);
      if (this._isMounted) {
        this.setState({ primarygroup: group })
      }
    });

    // eslint-disable-next-line no-undef
    connect.agent(function(agent) {
      agent.onRoutable(function(agent) {
        this.setState({ activeIndex: 0 }); 
      }.bind(this));
    }.bind(this))
  }
Example #26
Source File: elasticsearch.js    From chime-voiceconnector-agent-assist with MIT No Attribution 6 votes vote down vote up
export function retrieveBucketAndKey(transactionid) {
  return Auth.currentCredentials().then(creds => {
    const lambda = new AWS.Lambda({
      region: defaultRegion,
      credentials: Auth.essentialCredentials(creds),
    });
    const params = {
      FunctionName: config.searchFunctionName,
      InvocationType: 'RequestResponse',
    };

    const esParams = {
      index: ELASTIC_SEARCH_INDEX_NAMES.WAVFILE,
      type: '_doc',
      body: {
        size: 2,
        query: {
          query_string: {
            default_field: TRANSCRIPT_TABLE_KEYS.TRANSACTION_ID,
            query: transactionid,
          },
        },
      },
      output: ['Bucket', 'Key', 'Time'],
    };
    params['Payload'] = Buffer.from(JSON.stringify(esParams));

    return lambda
      .invoke(params)
      .promise()
      .then((data) => {
        const body = JSON.parse(data.Payload).body;
        if (body === undefined || body === []) {
          return [];
        }
        return JSON.parse(data.Payload).body.Records;
      });
  });
}
Example #27
Source File: ProtectedRoute.js    From aws-amplify-identity-broker with MIT License 5 votes vote down vote up
componentDidMount() {
		Auth.currentAuthenticatedUser()
			.then(() => {
				this.setState({ isAuthenticated: true });
				this.props.setAuth(true);

				Auth.currentUserInfo()
					.then((user) => {
						this.props.setUser(user);
						this.props.setLang(user.attributes.locale);

						/*
						 * Check if the user need to "Sign" or "Resign" the ToS
						 * For reasons of simplicity we load the current ToS version from 'i18n - VERSION_ID'
						 */
						const tosSigned = (user.attributes['custom:tos_signed'] === "true") || false;
						const tosSignedVersionInt = parseInt(user.attributes['custom:tos_version']) || 0;
						const tosCurrentVersionInt = I18n.get('TERMS_OF_SERVICE_VERSION_ID') || 0

						/*
						 * If the current ToS are newer or the actual ToS are not sigened we redirect the user to '/tos'
						 * To redirect the user back to '/settings' after sign the ToS we add Query Param 'redirect'
						 */
						if ((tosCurrentVersionInt > tosSignedVersionInt) || !tosSigned)
							this.setState({ resignToS: true })
					})
					.catch(err => {
						console.log(err);

						this.setState({ isAuthenticated: false })
						this.props.setAuth(false);
						this.props.setUser(null);
					});
			})
			.catch(err => {
				if (err !== "not authenticated") console.log(err)

				this.setState({ isAuthenticated: false })
				this.props.setAuth(false);
				this.props.setUser(null);
			});
	}
Example #28
Source File: App.js    From allscreens with GNU General Public License v3.0 5 votes vote down vote up
async componentDidMount() {
    const user = await Auth.currentAuthenticatedUser();
    const group = user.signInUserSession.accessToken.payload["cognito:groups"][0];
    console.log(group);
    this.setState({ isTeacher: "teachers" === group });
  }
Example #29
Source File: requiresAuth.js    From voicemail-for-amazon-connect with Apache License 2.0 5 votes vote down vote up
export default function (ComposedComponent, UnauthedComponent) {
    class Authenticate extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                authState: 'loading'
            }
        }

        componentDidMount() {
            this._checkAndRedirect();
        }

        componentDidUpdate() {
            this._checkAndRedirect();
        }

        _checkAndRedirect() {
            if (this.state.authState === "loading") {
                Auth.currentAuthenticatedUser().then(user => {
                    this.props.auth(user);
                    this.setState({authState: 'valid'});
                }).catch(e => {
                    this.setState({authState: 'invalid'});
                    this.props.redirect();
                });
            }
        }

        render() {
            return this.state.authState === 'valid' ?
                <ComposedComponent {...this.props} /> : <UnauthedComponent {...this.props}/>;
        }
    }

    const mapStateToProps = (state) => {
        return {
            auth: state.auth
        };
    };

    const mapDispatchToProps = (dispatch) => {
        return {
            redirect: () => dispatch(() => {history.push("/login")}),
            auth: (user) => dispatch(AuthAction.auth(user))
        }
    };

    return connect(
        mapStateToProps,
        mapDispatchToProps
    )(Authenticate);
}