Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
componentDidMount = async () => {
await Auth.currentAuthenticatedUser()
.then(user => {
this.setState(
{
postOwnerUsername: user.username,
likeOwnerUsername: user.username,
postOwnerId: user.attributes.sub,
likeOwnerId: user.attributes.sub,
}
)
})
.catch(err => console.log(err))
await this.listPosts()
// Update the number of entries in the parent component: ChallengeScreen
await this.props.countPosts()
}
return Promise.resolve().then(function () {
return localStorage.getItem(key) || "anonymous";
});
}
};
export const custom_header = async () => {
try {
return { Authorization: (await Auth.currentSession()).getIdToken().getJwtToken() }
}
catch (e) {
console.warn(e, "Defaulting to stored JWT in localStorage...");
// Get JWT from SAML.
return { Authorization: await asyncLocalStorage.getItem("jwt") }
}
}
Auth.configure({
region: 'us-east-1',
userPoolId: COGNITO_USER_POOL_ID,
userPoolWebClientId: COGNITO_CLIENT_ID,
mandatorySignIn: false
});
API.configure({
endpoints: [
{
name: "treehacks",
endpoint: ENDPOINT_URL,
custom_header: custom_header
}
]
});
const authScreenLabels = {
export const custom_header = async () => {
try {
return { Authorization: (await Auth.currentSession()).getIdToken().getJwtToken() }
}
catch (e) {
console.warn(e, "Defaulting to stored JWT in localStorage...");
// Get JWT from SAML.
return { Authorization: await asyncLocalStorage.getItem("jwt") }
}
}
Auth.configure({
token_use:
website:
*/
// Verify JWT here.
const parsed = parseJwt(jwt);
if (new Date().getTime() / 1000 >= parseInt(parsed.exp)) {
console.log("JWT expired");
localStorage.removeItem("jwt");
let refreshToken = localStorage.getItem("refresh_token");
if (refreshToken) {
dispatch(exchangeRefreshToken(refreshToken));
}
}
else {
Auth.signOut();
let attributes: IUserAttributes = { "name": parsed["name"], "email": parsed["email"], "email_verified": parsed["email_verified"], "cognito:groups": parsed["cognito:groups"] };
return await {
"username": parsed["sub"],
attributes
};
}
}
// If JWT from SAML has expired, or if there is no JWT in the first place, run this code.
// Need to parse our local JWT as well to get cognito:groups attribute, because Auth.currentAuthenticatedUser() does not return user groups.
return Promise.all([
Auth.currentAuthenticatedUser(),
parseJwt((await Auth.currentSession()).getIdToken().getJwtToken())
]).then(([user, token]) => {
user.attributes["cognito:groups"] = token["cognito:groups"];
return user;
async signUp() {
const { username, password, email, phoneNumber } = this.state
// rename variable to conform with Amplify Auth field phone attribute
const phone_number = phoneNumber
await Auth.signUp({
username,
password,
attributes: { email, phone_number }
})
.then(() => {
console.log('sign up successful!')
Alert.alert('Enter the confirmation code you received.')
})
.catch(err => {
if (! err.message) {
console.log('Error when signing up: ', err)
Alert.alert('Error when signing up: ', err)
} else {
console.log('Error when signing up: ', err.message)
Alert.alert('Error when signing up: ', err.message)
}
async confirmSignUp() {
const { username, authCode } = this.state
await Auth.confirmSignUp(username, authCode)
.then(() => {
this.props.navigation.navigate('SignIn')
console.log('Confirm sign up successful')
})
.catch(err => {
if (! err.message) {
console.log('Error when entering confirmation code: ', err)
Alert.alert('Error when entering confirmation code: ', err)
} else {
console.log('Error when entering confirmation code: ', err.message)
Alert.alert('Error when entering confirmation code: ', err.message)
}
})
}
// Resend code if not received already
verify() {
// http://localhost:9000/verify?username=910e6571-c11e-4c83-9e27-cf220bdd6e41&code=315131
const { username, code } = queryString.parse(window.location.search);
Auth.confirmSignUp(username, code, {
// Optional. Force user confirmation irrespective of existing alias. By default set to True.
forceAliasCreation: true
}).then(data => {
console.log(data);
this.setState({ verified: true });
})
.catch(err => {
this.setState({ verified: false, error: err.code + " - " + err.message });
});
}
render() {
async forgotPassword() {
const { username } = this.state
await Auth.forgotPassword(username)
.then(data => console.log('New code sent', data))
.catch(err => {
if (! err.message) {
console.log('Error while setting up the new password: ', err)
Alert.alert('Error while setting up the new password: ', err)
} else {
console.log('Error while setting up the new password: ', err.message)
Alert.alert('Error while setting up the new password: ', err.message)
}
})
}
// Upon confirmation redirect the user to the Sign In page
renderSignOutButton() {
const { federated = {} } = this.props;
const {
google_client_id,
facebook_app_id,
amazon_client_id,
auth0,
} = federated;
// @ts-ignore
const config = Auth.configure();
const { oauth = {} } = config;
// @ts-ignore
const googleClientId = google_client_id || config.googleClientId;
// @ts-ignore
const facebookAppId = facebook_app_id || config.facebookClientId;
// @ts-ignore
const amazonClientId = amazon_client_id || config.amazonClientId;
// @ts-ignore
const auth0_config = auth0 || oauth.auth0;
let SignOutComponent = SignOut;
// @ts-ignore
if (googleClientId) SignOutComponent = withGoogle(SignOut);
// @ts-ignore
if (facebookAppId) SignOutComponent = withFacebook(SignOut);
// @ts-ignore
initialize() {
// @ts-ignore
const { oauth = {} } = Auth.configure();
// @ts-ignore
const config = this.props.auth0 || options || oauth.auth0;
const { onError, onStateChange, authState } = this.props;
if (!config) {
logger.debug('Auth0 is not configured');
return;
}
logger.debug('withAuth0 configuration', config);
if (!this._auth0) {
this._auth0 = new window['auth0'].WebAuth(config);
window.auth0_client = this._auth0;
}
if (authState !== 'signedIn') {