Amplify w/Cognito: How do I get the Current User's Email? - javascript

I am using AWS Amplify, with Cognito for user Auth.
Users go into a user pool, and register and sign in just with email address and password.
When a user that has signed in through Cognito navigates to a certain page, I want to be retrieve their email address. How can I do this?
I am able to retrieve some user data with this code (I am using javascript/Angular):
import Auth from '#aws-amplify/auth';
...
ngOnInit(){
Auth.currentAuthenticatedUser().then((user)=>{
console.log('user = ' + JSON.stringify(user.pool))
})
}
The email does appear on the response, but I haven't yet been able to isolate the email from the returned JSON.
I've tried going through the docs, but I haven't yet found info on stuff like the attribute options I can add to currentAuthenticatedUser(), or if there is another method that is cleaner (which I assume there is).
EDIT: It looks like the following works:
Auth.currentAuthenticatedUser().then((user) => {
console.log('user email = ' + user.attributes.email);
});
But I am still hoping to understand the documentation better. I found this solution in a random github question, not the official docs. Where would I find this solution in the AWS Amplify / Cognito documentation?

import cognito from "../path/to/your/config/cognito.json";
import Amplify, { Auth, Hub } from 'aws-amplify';
...
...
useEffect(() => {
Amplify.configure({ Auth: cognito });
Hub.listen('auth', ({ payload: { event, data } }) => {
switch (event) {
case 'signIn':
console.log('Event name -> ', event, data)
// here is your name, email e.t.c.
console.log(data.signInUserSession.idToken.payload);
break
case 'signOut':
console.log('sign out')
// this.setState({ user: null })
break
default:
console.log('Unhandled use case - ' + event)
}
})
}, [])

You can check this one from the official documentation
and enable read access
General settings -> App clients -> Show details -> Set attribute read and write permissions link
and then to make sure you are fetching the updated attributes
Auth.currentAuthenticatedUser({ bypassCache: true })

Auth.currentSession()
.then((data) => {
// this data has user details in accessToken
}).catch(err => console.log(err));

The following works for me after the user is logged in...
import { Auth, Amplify } from 'aws-amplify'
console.log(Auth.user.attributes.email)

Related

Firebase auth + firestore (what is the proper way to "link" users)

I'm making smth with backed for the first time in my life, so I'm sorry in advance, I'm making a web chat app. I think I managed to deal with authentication (it seems to be working) and now I want to make connect somehow the authentication user names with chat users... so I tried to
const docRef = await addDoc(collection(database, 'users'), {
name: user.displayName,
});
console.log('Document written with ID: ', docRef.id);
} catch (e) {
console.error('Error adding document: ', e);
}
but it says user not defined because userCredentials is in the scope of authentications functions...
If I paste this code into some function where userCredentials can be found, it says there is some problem with await word...
I want to take userCredential that logged in and use it in the chat app... so I need to link somehow the auth db and the firestore db? or is it done completely differently? Thank you
Could you give a bit of advice? Thank you (edited)
If you want to use the user's name, you first need to make sure that your code only runs once the user is signed in. In Firebase you can do that as shown in the documentation on getting the currently signed in user:
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// 👇 your application specific code is below
const docRef = await addDoc(collection(database, 'users'), {
name: user.displayName,
});
console.log('Document written with ID: ', docRef.id);
} else {
// User is signed out
// ...
}
})
I'd actually recommend not using addDoc, but basing the document ID on the UID of the user, like this:
if (user) {
// 👇 get UID from user
const uid = user.uid;
// Use as document ID 👇 👇 👇
const docRef = await setDoc(doc(database, 'users', uid), {
name: user.displayName,
});
Since document IDs are unique within a collection, this automatically ensures that each user can only have one document in the users collection. It also makes it easier to find a user's document when needed, and makes it easier to ensure users can only edit their own document.

Firebase - check if user created with Google Account is signing up or logging in?

I'm trying to create a web application, where you can log-in and register an account with a google account. I have managed to make it so they can log-in with the signInWithPopup(provider), but not sure how to Implement the sign-up. Any suggestions? or know of any functions in firebase i can use?
There aren't any separate methods to login and sign up when using Google Sign-In or any other provider. If a user with that credential exists then user will be logged in else a new user account will be created. You can then use additionalUserInfo.isNewUser property from the result received from signInWithPopUp method to check if the user is new.
firebase.auth().signInWithPopup(provider).then(function (result) {
const {additionalUserInfo: {isNewUser}} = result;
console.log(isNewUser ? "This user just registered" : "Existing User")
})
For the new Modular SDK (V9.0.0+), the same can be written as:
import { signInWithPopup, getAdditionalUserInfo } from "firebase/auth"
const result = await signInWithPopup(auth, googleProvider);
// Pass the UserCredential
const { isNewUser } = getAdditionalUserInfo(result)
So far, as I understood, you have two options to log in to your website: one is to make a local username/password account on your website, and the other option is to use your google account. I suppose the best way would be to check if the Google account is linked to any existing user using additionalUserInfo.isNewUser, and then linking up your google account with the account that is created via your website locally by following this article: https://firebase.google.com/docs/auth/web/account-linking?hl=lt
Once you have Firebase dependency inside your application. You can use createUserWithEmailAndPassword method to do that.
firebase
.auth()
.createUserWithEmailAndPassword("email#domain.com", "123123")
.then(data => {
data.user.updateProfile({
displayName: this.form.name
}).then(() => {});
})
.catch(err => {
this.error = err.message;
});

Firebase Auth setCustomClaims() not working

I am facing a problem with setting custom claims for Firebase Authentication service's token. I am using Cloud function to set the custom claims for Hasura. The cloud function executes upon new user create event to set the custom claims. Here's my code running in cloud function
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.processSignup = functions.auth.user().onCreate(user => {
// create custom claims for hasura
const hasuraClaims = {
"x-hasura-default-role": "user",
"x-hasura-allowed-roles": ["user"],
"x-hasura-user-id": user.uid
}
// attach claims to user auth object
return admin.auth().setCustomUserClaims(user.uid, hasuraClaims)
.then(_ => {
functions.logger.info('SUCCESS: Custom claims attached');
})
.catch(err => {
console.log('ERROR: ', err);
})
})
In my frontend web page, I am running the following code to get the idToken
// subscribe to user state change
firebase.auth().onAuthStateChanged(async user => {
console.log('Firebase auth state changed');
if (user) {
// User is signed in.
window.User = user;
let idToken = await user.getIdTokenResult();
console.log('idToken: ', idToken);
}
})
I don't know what I'm doing wrong, but the token doesn't contain the custom claims that I've set in my Cloud function processSignup(). I know that the function executed without error because I can check my function logs and find the info entry SUCCESS: Custom claims attached.
Can anyone please help me solve this problem?
Updating claims does not trigger an onAuthStateChanged (the auth state of being logged in or not has not changed, but the users' claims have) and tokens are minted and then used for ~1h.
You are calling getIdTokenResult but not forcing a refresh, try:
let idToken = await user.getIdTokenResult(true);
which will force a new token to be fetched from the server and will (hopefully) include your custom claims.

Keeping user logged in after refresh/using refresh token with Google OAuth2 in React app

I’m building a React app where a key part of the functionality is a user can sign into their Google account and then access a feed of their most recent Google Drive/Docs mentions and notifications. A user arrives at my site where I load the Google OAuth2 client with my client_id, apiKey, scope and discoveryDocs, and they can click a button to sign in. For convenience, I’d like the user to not have to re-login and re-auth with their Google account every time they use the app or the app refreshes, I’d like the login information to be saved across sessions. For this I’ll use localStorage to start but eventually integrate a database like Firebase.
After looking through the JavaScript client Google OAuth2 docs I understand how most things work - understand the data and methods stored in the GoogleUser, GoogleAuth, etc objects. I’m having a little trouble with access and refresh tokens. I recognize that you can get the authenticated user’s information through gapi.auth2.getAuthInstance().currentUser.get() and gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse() returns an object with a lot of what I think I need like id_token, access_token and metadata like expires_at and token_type. I also see the grantOfflineAccess() method from which I extract response.code, but I’m not quite sure which of these tokenized strings is the right one to use and how I need to use it.
This FAQ from Google (https://developers.google.com/api-client-library/javascript/help/faq) is somewhat helpful but advises to Refresh the token by calling gapi.auth.authorize with the client ID, the scope and immediate:true as parameters., but gapi.auth.authorize is noted by Google in the client JS OAuth2 library as being incompatible with the more widely used and heavily documented api.auth2.init and signIn.
I also have a vague idea from posts like Google OAuth2 API Refresh Tokens that I need to follow server-side OAuth2 instructions and I can only get this refresh_token through a server-side call, but I’m still at a bit of a loss. I’ll caveat and say I’m more of a front end developer/designer so I'm shaky on my node and server-side skills.
TL;dr: I don't know how to keep my users who signed in via Google OAuth2 signed in after a refresh. I have an idea it's due to refresh_token and access_token and I have access to them but I don't know what to do after that, in terms of sending data to Google servers, getting information back, and setting the token information for the given user when they return.
Here's my method that calls on componentDidMount (basically when my app first loads):
loadGoogleClient = () => {
gapi.load("client:auth2", () => {
gapi.auth2.init({
'client_id': my-client-id,
'apiKey': my-key,
'scope': "https://www.googleapis.com/auth/drive.readonly",
'discoveryDocs': ['https://content.googleapis.com/discovery/v1/apis/drive/v3/rest']
})
// Listen for sign-in state changes.
console.log(`User is signed in: ${gapi.auth2.getAuthInstance().isSignedIn.get()}`);
gapi.client.load("https://content.googleapis.com/discovery/v1/apis/drive/v3/rest")
.then(() => { console.log("GAPI client loaded for API");
}, (error) => { console.error("Error loading GAPI client for API", error);
});
console.log('Init should have worked');
});
}
And here's my code that's onClick on my Signin button:
authGoogle = () => {
gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/drive.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
If you are using the client lib (the gapi api) there is no need for a refresh token... Once logged in it should persist across sessions and refreshes... The issue is the code...
1) Include this in your index.html in the head section:
<script src="https://apis.google.com/js/api.js"></script>
2) Here is a component that will handle auth using the gapi lib and render a button conditionally (The code is self-explanatory but if you have a question just ask...)
import React from 'react';
class GoogleAuth extends React.Component {
state = { isSignedIn: null };
componentDidMount() {
window.gapi.load('client:auth2', () => {
window.gapi.client
.init({
clientId: '<your client id here...>',
scope: 'email', // and whatever else passed as a string...
})
.then(() => {
this.auth = window.gapi.auth2.getAuthInstance();
this.handleAuthChange();
this.auth.isSignedIn.listen(this.handleAuthChange);
});
});
}
handleAuthChange = () => {
this.setState({ isSignedIn: this.auth.isSignedIn.get() });
};
handleSignIn = () => {
this.auth.signIn();
};
handleSignOut = () => {
this.auth.signOut();
};
renderAuthButton() {
if (this.state.isSignedIn === null) {
return null;
} else if (this.state.isSignedIn) {
return <button onClick={this.handleSignOut}>Sign Out</button>;
} else {
return <button onClick={this.handleSignIn}>Sign in with Google</button>;
}
}
render() {
return <div>{this.renderAuthButton()}</div>;
}
}
export default GoogleAuth;
Now you can simply use this component/button anywhere in your app... Meaning if you have a Navigation component simply import it there and use it as a button login / log out...

React + Firebase "sign-in provider disabled" despite it being enabled

In my Authentication -> Sign-in Method - it's Email & Password set to 'Enabled'.
I have a handler for an onSubmit calling this:
createUser(e){
e.preventDefault();
const email = this.createEmail.value
const password = this.createPassword.value
const confirm = this.confirmPassword.value
if(password === confirm) {
firebase.auth()
.createUserWithEmailAndPassword(email, password)
.then((res) => {
this.showCreate(e)
})
.catch((error) => {
alert(error.message)
})
}
else {
alert('Passwords must match')
}
}
And it shoots this error "The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section."
I'm using the firebase npm package. It's a note-taking application and it's successfully communicating with the database.
But I have it Enabled. Is anyone aware of how to fix this, or if there's a setting I seem to be missing?
SOLUTION: I fixed this by removing the environment variable and using the raw API string. Weird.
I fixed this by removing the environment variable and using the raw API string.

Categories

Resources