How to keep showing email verification div with local storage jquery - javascript

Suppose you have a form that consists of two separate divs. The first div is for customer registration, and the second div is for OTP verification. I want to address two issues:
If the user enters their registration details but decides to complete the OTP verification later, and then refreshes the page, the second div should still be shown for one hour.
If the user has already entered their registration details but has not yet verified their OTP, you want to know how the unverified registration data can be stored.
As the rule to ask question I have to add code but my code is long so I haven't added here. Little guidance will be helpful.
when data is stored after getting success response I hide registeration div by adding class and add otp verification form

To address the first issue, you can use browser storage, such as session storage or local storage, to store a flag indicating that the user has completed the registration but not the OTP verification. When the page is refreshed, you can check for this flag and show the second div if it's still within the one-hour timeframe.
To address the second issue, you can use browser storage again to store the unverified registration data. When the user completes the OTP verification, you can retrieve the stored data and process it accordingly.
// Store flag indicating registration without OTP verification
sessionStorage.setItem('registrationWithoutOTP', true);
// Store unverified registration data
const registrationData = {
name: 'John Doe',
email: 'johndoe#example.com',
// Other registration details
};
sessionStorage.setItem('unverifiedRegistrationData', JSON.stringify(registrationData));
// Retrieve flag and data
const hasRegistrationWithoutOTP = sessionStorage.getItem('registrationWithoutOTP') === 'true';
const unverifiedRegistrationData = JSON.parse(sessionStorage.getItem('unverifiedRegistrationData'));

Related

How to find original email redirect link from landing page for firebase email link sign in option

In firebase, in order to authenticate a use after they click an email link, firebase needs the original clicked email link.
Example
This link redirects you a few times, and brings you to the page needed (currently set to localhost for dev purposes)
Firebase will only accept the email link, and only for one test per email which makes it difficult to diagnose this.
I need a way to fetch the first link clicked (the email link) from the landing page.
I apolagise if this has been answered anywhere else but I tried several combinations of keywords that did not work
export default function Home() {
return (
<>
boilerplate
<button onClick={bigFunction}>Press me to check if the browser has the email saved</button>
</>
)
}
let signinwithemaillink = "https://ticketme.page.link/qbvQ"
function bigFunction()
{
console.log(window.location.href)
if (isSignInWithEmailLink(auth, signinwithemaillink)) {
// Additional state parameters can also be passed via URL.
// This can be used to continue the user's intended action before triggering
// the sign-in operation.
// Get the email if available. This should be available if the user completes
// the flow on the same device where they started it.
let email = window.localStorage.getItem('emailForSignIn');
if (!email) {
// User opened the link on a different device. To prevent session fixation
// attacks, ask the user to provide the associated email again. For example:
email = 'example#gmail.com';
}
// The client SDK will parse the code from the link for you.
signInWithEmailLink(auth, email, signinwithemaillink)
.then((result) => {
alert("all good")
console.log(result.user)
// Clear email from storage.
window.localStorage.removeItem('emailForSignIn');
// You can access the new user via result.user
// Additional user info profile not available via:
// result.additionalUserInfo.profile == null
// You can check if the user is new or existing:
// result.additionalUserInfo.isNewUser
})
.catch((error) => {
console.log(error.code)
// Some error occurred, you can inspect the code: error.code
// Common errors could be invalid email and invalid or expired OTPs.
});
}
}
As you can tell there is still an incredible amount of comments from the firebase docs, Im just trying to get this to work.
*Amended - I cut out the dynamic link, so the current redirect cycle is as follows:
Email -> Firebase Redirect Link -> Desired Page

Generate recover email link in firebase

Is there any way to create custom recoverEmail link in firebase/firebase-admin?
I've checked the docs and tutorials there's none.
Any help would be great!
From my understanding there is currently no solution for this within the SDK. Instead, we took the approach of using admin.auth().generateSignInWithEmailLink(email, actionCodeSettings) and then replacing the mode within the returned link from signIn to recoverEmail.
const updatedLink = link.replace('signIn', 'recoverEmail');
This allowed us to customise the auth handler action as suggested here Create the email action handler page in the Firbase documentation.
Now we are able to call on admin.auth().updateUser again to reset the email to it's previous, along with update across our databases, merchant and other services. You'll also need to add the original email to a query in the updatedLink too.
const linkWithOriginalEmail = updatedLink.concat(`&email=${email}`)
Hope that helps and if anyone has a better solution we'd love to discuss.
I´m not sure if I understand your problem correctly, but If your goal is to have a custom link in the automatic email sent by Firebase when someone changes his authentication email address with updateEmail then you can define a custom action url in the Firebase console e.g. https://example.com/__/auth/action in the Authentication section and add the following code to the defined url (ref. https://firebase.google.com/docs/auth/custom-email-handler).
function handleRecoverEmail(auth, actionCode, lang) {
// Localize the UI to the selected language as determined by the lang
// parameter.
var restoredEmail = null;
// Confirm the action code is valid.
auth.checkActionCode(actionCode).then(function(info) {
// Get the restored email address.
restoredEmail = info['data']['email'];
// Revert to the old email.
return auth.applyActionCode(actionCode);
}).then(function() {
// Account email reverted to restoredEmail
// TODO: Display a confirmation message to the user.
// You might also want to give the user the option to reset their password
// in case the account was compromised:
auth.sendPasswordResetEmail(restoredEmail).then(function() {
// Password reset confirmation sent. Ask user to check their email.
}).catch(function(error) {
// Error encountered while sending password reset code.
});
}).catch(function(error) {
// Invalid code.
});
}

Firebase - Check Password

I have a scenario that requires checking an entered password against the user's firebase password before the user does an irreversible task. This is different from creating an account or signing in. How can you check against a firebase password? It doesn't look like there's a password property in firebase.auth().currentUser.
Update:
The user must verify their password and the Delete button will run a function to check it. If it matches the firebase password, the Delete button will succeed in triggering a pretty modal to pop up.
I would suggest you to store the user password somewhere if you need to check against it at some point.
Instead of storing it inside your database (which wouldn't be safe) I would personally store it on user's device using UserDefaults so that you can access it easily whenever you need to perform your sensible tasks.
Update:
Another possibility would be using the reauthenticateWithCredential method. If the method return success then, perform your sensitive task. If it fails, ask your user to type the correct password.
As per your request, this is how you would reauthenticate the user using his email & password :
// First you get your current user using Auth :
let currentUser = Auth.auth()?.currentUser
// Then you build up your credential using the current user's current email and password :
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
// use the reauthenticate method using the credential :
currentUser?.reauthenticate(with: credential, completion: { (error) in
guard error == nil else {
return
}
// If there is no error, you're good to go
// ...Do something interesting here
})
You can find some more explanation inside the Firebase documentation here : https://firebase.google.com/docs/auth/ios/manage-users

How to fix whenever I click on a page link within site, I get logged out?

I have an intranet site with multiple page links linking to other pages within the site on each page. The issue is that if I login to my profile for example I have no problem, but if I click on a link to say my index page or recent news page or whatever it takes me to the page but I get logged out and I have to login again. I've found out that linking between pages out works if the user's password is "something"
I have two versions of this site, the only difference is that they connect to different databases. On one domain everything works fine, on the other is when I get this issue.
This is at the top of every page for connections to the database and checking to see if the user has the right credentials and just some functions. I think the issue should be with the code checking the user credentials and or starting the session.
<?php
// Connect To Secure Login
$cfgProgDir = 'phpSecurePages/';
include($cfgProgDir . "secure.php");
//These are the includes needed to make the php page run
// this file connects to the database
include("includes/connect.inc.php");
// This file holds all the custom functions
include("includes/functions.inc.php");
This is the config file
$cfgIndexpage = '/index.php';
$cfgServerHost = '********************'; // MySQL hostname
$cfgServerPort = ''; // MySQL port - leave blank for default port
$cfgServerUser = '*********'; // MySQL user
$cfgServerPassword = '**********'; // MySQL password
$cfgDbDatabase = '******'; // MySQL database name containing phpSecurePages table
$cfgDbTableUsers = 'members'; // MySQL table name containing phpSecurePages user fields
$cfgDbLoginfield = 'firstName'; // MySQL field name containing login word
$cfgDbPasswordfield = 'password'; // MySQL field name containing password
$cfgDbUserLevelfield = 'permission'; // MySQL field name containing user level
// Choose a number which represents the category of this users authorization level.
// Leave empty if authorization levels are not used.
$cfgDbUserIDfield = 'id'; // MySQL field name containing user
/****** Data ******/
/* this data is necessary if no database is used */
$cfgLogin[1] = ''; // login word (username)
$cfgPassword[1] = ''; // password
$cfgUserLevel[1] = '0'; // user level
and the connect file ($connect) just connects the my DB
Any suggestions on what the issue could be? :)
It probably means your session is getting destroyed somewhere or cookies aren't being set.
I didn't dwelve much into the code (It's a bit messy) but... secure.php include checklogin.php on line 67. On checklogin.php file, Line 37, session_start() is called and it is called again on your config file.
It should raise a warning so, if you haven't seen it, you're either using an old version of PHP or you don't have error reporting enabled.
You should enable error reporting and check for any notice or warning.

Updating rails model objects in Javascript

Okay.
Google API gives you the javascript for the Google Plus signup/login button.
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
IF a user successfully logs in with Google Plus, I want to use the form attributes/variables to create a new user. A user has a username and a password. The Google Plus login gives the google plus user a fullname and a gplus id. I want to create a user in the database with a username equal to their gplus fullname and a password equal to their gplus id. How would I go about using ruby with my javascript to save them to the model. I reviewed this link
Section four seems to be the right direction. I'm just having trouble grasping it.
If you think there would be a better way to do this. Please let me know! I read up on Devise with google plus, but it seemed too risky to implement during a time crunch. I might try it anyway depending on how long this takes me.

Categories

Resources