we used local storage to store data when user login to app
when update storage for name not change in all pages
if close app and open it again it's work
when used ionViewWillEnter when user back to main page and change local storage for name but not called
ionViewWillEnter(){
this.name = localStorage.getItem('name')
this.avatar = localStorage.getItem('avatar')
}
when user update profile
this.service.SendDataFile("users/edite",data).subscribe((res) => {
localStorage.setItem('phone',this.phone)
localStorage.setItem('name',this.name)
this.service.ShowToast(res['msg'])
this.navCtrl.navigateForward('tabs/tab3')
});
try using async await
async ionViewWillEnter(){
this.name = await localStorage.getItem('name')
this.avatar = await localStorage.getItem('avatar')
}
Related
I've been trying to create a .env variable where initially it will be empty but after login process it will store the data to the .env variable for further work, but unfortunately, I am not able to do so.
Before I put my code example, I would like to have some suggestions!!
Yea, in the login process I'm using session storage to store the user token. So, will it be a good work to store the user data into a .env file and later access it for future use or should I just call getToken function every time I need the token to verify if the user is logged in.
login.js:
const getToken = () => {
const tokenString = sessionStorage.getItem('token');
const userToken = JSON.parse(tokenString);
return userToken?.token
}
const saveToken = (userData) => {
sessionStorage.setItem('token', JSON.stringify(userData));
setToken(userData)
}
Tried different techniques to make it work, but I just couldn't get the data from the .env file.
Watched many different YouTube videos and did exactly like them but it was all in vain.
I checked multiple timed if there is any type or bug in my code or not! There was no error. I was getting the token after successful login and by default it was returning null. I was storing the token only when the user login successfully so that no garbage value gets inserted into the value.
Here's my logic:
const handleSubmit = async function (e) {
e.preventDefault();
const response = await loginUser(user);
if (response.status === 200) {
setToken(response.data);
process.env.REACT_APP_USER_TOKEN=response.data;
navigate("/");
} else {
console.error(response)
}
}
ENV files are used to store sensitive Api keys or secrets. which can only be read by the code when needed.
Storing user data in .env file is not the right way. If your user data should not be available easily in frontend, try encryption and store the encryption key in .env file or backend.
I'm a new developer and this is my first time posting to Stack Overflow
I'm using supabase for my db and authentication on my React app. I'm trying to integrate their 'Reset Password' feature (which emails you a link that includes the token in it), but I'm having a hard time recovering the token from the URL when I click on it and am rerouted to my app.
The Supabase documantation says this:
When the user clicks the reset link in the email they will be forwarded to:
<SITE_URL>#access_token=x&refresh_token=y&expires_in=z&token_type=bearer&type=recovery
Your app must detect type=recovery in the fragment and display a password reset form to the user.
When I click the link, it generates a url like this: https://mysupabaseurl/auth/v1/verify?token=zpJG16Xr3kjCUZKUI_WOwQ&type=recovery&redirect_to=http://mysiteurl/
Here is what I have in my code to try to grab that token:
const params = new URLSearchParams(window.location.hash);
const accessToken = params.get("access_token");
console.log(accessToken);
I've also tried:
const params = new URLSearchParams(window.location.search);
const accessToken = params.get("access_token");
console.log(accessToken);
access_token is a fragment and not a query param, you can see how we do it in the javascript client here:
https://github.com/supabase/gotrue-js/blob/8c6373b9fa11982cb5011df0a273498e3196b302/src/GoTrueClient.ts#L111
getParameterByName('access_token')
where https://github.com/supabase/gotrue-js/blob/8c6373b9fa11982cb5011df0a273498e3196b302/src/lib/helpers.ts#L19
export function getParameterByName(name: string, url?: string) {
if (!url) url = window?.location?.href || ''
// eslint-disable-next-line no-useless-escape
name = name.replace(/[\[\]]/g, '\\$&')
const regex = new RegExp('[?&#]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url)
if (!results) return null
if (!results[2]) return ''
return decodeURIComponent(results[2].replace(/\+/g, ' '))
}
I'm trying to integrate Microsoft sso with a Xamarin.Forms app.
I'm using Microsoft.Identity.Client 4.7.1
I struggling to sign in with different accounts on the same device since it seems that the first account is always picked no matter what I do.
User A signs in
User A signs out
User B enters the app opens the webview with the Microsoft login page and prompts the "Use another account" button but even after typing his account, the webview redirects it to back to the mobile app as user A.
Here's the code that handles sign-in and sing-out:
private IPublicClientApplication _publicClientApplication;
public AuthService()
{
_publicClientApplication = PublicClientApplicationBuilder.Create(Constants.MicrosoftAuthConstants.ClientId.Value)
.WithAdfsAuthority(Constants.MicrosoftAuthConstants.Authority.Value)
.WithRedirectUri(Constants.MicrosoftAuthConstants.RedirectUri.Value)
.Build();
}
public async Task<string> SignInAsync()
{
var authScopes = Constants.MicrosoftAuthConstants.Scopes.Value;
AuthenticationResult authResult;
try
{
// call to _publicClientApplication.AcquireTokenSilent
authResult = await GetAuthResultSilentlyAsync();
}
catch (MsalUiRequiredException)
{
authResult = await _publicClientApplication.AcquireTokenInteractive(authScopes)
.WithParentActivityOrWindow(App.ParentWindow)
.ExecuteAsync();
}
return authResult.AccessToken;
}
private async Task<IAccount> GetCachedAccountAsync() => (await _publicClientApplication.GetAccountsAsync()).FirstOrDefault();
public async Task SignOutAsync()
{
var firstCachedAccount = await GetCachedAccountAsync();
await _publicClientApplication.RemoveAsync(firstCachedAccount);
}
A workaround is to use Prompt.ForceLogin but what's the point of sso if you have to type the credentials every time.
The line of code await _publicClientApplication.RemoveAsync(firstCachedAccount); can jsut remove the user from the cache, it doesn't implement a signout method. So you need to do logout manually by the api below:
https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri=https://localhost/myapp/
import * as functions from 'firebase-functions';
console.log('I am a log entry0!');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
console.log('I am a log entry1!');
export const onMessageCreate = functions.database
.ref('/users/{userId}/totalScore')
.onUpdate((change) => {
console.log('I am a log entry2!');
//var a = admin.firestore().collection('/users');
})
I have deployed the function and I can see it in the console. But the function is not executed when totalScore is updated in the database....
Your database is Firestore but you use a Cloud Function that is triggered by an update in the Realtime Database. These are two different Firebase services and you need to change your code accordingly.
The following code will work:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.onMessageCreate = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
// Get an object representing the document
const newValue = change.after.data();
// ...or the previous value before this update
const previousValue = change.before.data();
if (newValue.totalScore !== previousValue.totalScore) {
console.log('NEW TOTAL SCORE');
}
return null;
//I guess you are going to do more than just logging to the console.
//If you do any asynchronous action, you should return the corresponding promise, see point 3 below
//For example:
//if (newValue.totalScore !== previousValue.totalScore) {
// return db.collection("score").doc(newValue.name).set({score: newValue.totalScore});
//}
});
Note that:
You cannot trigger the onUpdate Cloud Function when a specific field of the document changes. The Cloud Function will be triggered when any field of the Firestore document changes. But you can detect which field(s) have changed, as shown in the above code.
Since version 1.0 you have to initialize with admin.initializeApp();, see https://firebase.google.com/docs/functions/beta-v1-diffList
You need to indicate to the platform when the Cloud Function has finished executing: Since you are not executing any asynchronous operation in your Cloud Function you can use return null;. (For more details on this point, I would suggest you watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/).
I think the update is checked on the ref not on the child
Try this
export const onMessageCreate = functions.database
.ref('/users/{userId}')
.onUpdate((change) => {
console.log('I am a log entry2!');
//var a = admin.firestore().collection('/users');
})
You get the old and new values of the snapshot at that location
If you are using Cloud Firestore then your listener is incorrect. In your case, you are specifying a listener for Realtime Database. We extract firestore from the functions and specify the path to the document we want to have a listener on:
import * as functions from 'firebase-functions';
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
export const onMessageCreate = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
console.log(change.before.data()); // shows the document before update
console.log(change.after.data()); // shows the document after change
return;
})
How can i detect when a user logs out of firebase (either facebook, google or password) and trigger the onDisconnect method in the firebase presence system. .unauth() is not working. I would like to show a users online and offline status when they login and out, minimize the app (idle) - not just when the power off their device and remove the app from active applications on the device.
I'm using firebase simple login for angularjs/ angularfire
Im using code based off of this tutorial on the firebase site.
https://www.firebase.com/blog/2013-06-17-howto-build-a-presence-system.html
Please i need help with this!
Presence code:
var connectedRef = new Firebase(fb_connections);
var presenceRef = new Firebase(fb_url + 'presence/');
var presenceUserRef = new Firebase(fb_url + 'presence/'+ userID + '/status');
var currentUserPresenceRef = new Firebase(fb_url + 'users/'+ userID + '/status');
connectedRef.on("value", function(isOnline) {
if (isOnline.val()) {
// If we lose our internet connection, we want ourselves removed from the list.
presenceUserRef.onDisconnect().remove();
currentUserPresenceRef.onDisconnect().set("<span class='balanced'>☆</span>");
// Set our initial online status.
presenceUserRef.set("<span class='balanced'>★</span>");
currentUserPresenceRef.set("<span class='balanced'>★</span>");
}
});
Logout function:
var ref = new Firebase(fb_url);
var usersRef = ref.child('users');
service.logout = function(loginData) {
ref.unauth();
//Firebase.goOffline(); //not working
loggedIn = false;
seedUser = {};
clearLoginFromStorage();
saveLoginToStorage();
auth.logout();
};
The onDisconnect() code that you provide, will run automatically on the Firebase servers when the connection to the client is lost. To force the client to disconnect, you can call Firebase.goOffline().
Note that calling unauth() will simply sign the user out from the Firebase connection. It does not disconnect, since there might be data that the user still has access to.
Update
This works for me:
var fb_url = 'https://yours.firebaseio.com/';
var ref = new Firebase(fb_url);
function connect() {
Firebase.goOnline();
ref.authAnonymously(function(error, authData) {
if (!error) {
ref.child(authData.uid).set(true);
ref.child(authData.uid).onDisconnect().remove();
}
});
setTimeout(disconnect, 5000);
}
function disconnect() {
ref.unauth();
Firebase.goOffline();
setTimeout(connect, 5000);
}
connect();