Updating rails model objects in Javascript - 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.

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.
});
}

Sending push notification to specific device knowing phone number, parse.com

I would just to get things clear here or get other suggestions if possible if it is better.
This is how my application works now:
1) Anonymous user is created if its the first time the user open the application
2) Phone verification is needed to be done. If verified, i save the phone number in a custom field in user object ( do i need to make this user a real user after this or can i still go with anonymous user?)( verification is one time only of course)
3) The user will be able to pick a friend from his contact list(ABPeoplePicker) and then send a push notification to that friend's device.
Now i have set up a relationship with the User and the installation object with this code:
PFInstallation *installation = [PFInstallation currentInstallation];
installation[#"user"] = [PFUser currentUser];
[installation saveInBackground];
And this created a pointer to the users ObjectId
So my question is how would i create a query and send a push notification to a number retrieved from that Users friend list?. I am having a hard time to connect how i can get from a phone number to the installation device that i need to send the notification to. If you could provide help in javascript since i read it is safer to send it through cloud code!
Also a subquestion mentioned above if i need to make the anonymous user to a real user.
many thanks!!
I'd recommend subscribing each user to their own channel where the channel name is equal to their phone number (Subscription can't be done in Javascript):
NSString *userPhoneNumber = ...
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
// "x" added to the beginning of the userPhoneNumber since
// Parse doesn't allow channels to begin with a number
[currentInstallation addUniqueObject:[NSString stringWithFormat:#"x%#", userPhoneNumber] forKey:#"channels"];
[currentInstallation saveInBackground];
That way no query is required before pushing the notification:
var friendPhoneNumber = ...
var friendChannel = "x" + friendPhoneNumber;
Parse.Push.send({
channels: [ friendChannel ],
data: {
alert: message
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});

Implement Google Analytics With Userid in Open Cart

i want to track every customer how could i do it the documentation on google analytics have this code
ga(‘set’, ‘&uid’, {{USER_ID}}); // Set the user ID using signed-in user_id.
how do i pass userid in this as open cart have an admin panel setup to enter google analytics and ehat if my customer is not logged in what should i do.
Opencart uses a setting in administration where you insert your whole GA code. You can use it as well for user tracking. The only change you'd do is to add this line of JS code into that field in administration:
ga('set', '&uid', #CUSTOMER_ID#);
This string will be then parsed by PHP in catalog/controller/common/header.php like this - find this line
$this->data['google_analytics'] = html_entity_decode( ... );
and after this line put this code:
if ($this->customer->isLogged()) {
// replace %s with customer ID
$this->data['google_analytics'] = str_replace('#CUSTOMER_ID#', $this->customer->getId(), $this->data['google_analytics']);
} else {
// customer is not logged in, remove the user tracking part
$this->data['google_analytics'] = str_replace("ga('set', '&uid', #CUSTOMER_ID#);", "", $this->data['google_analytics']);
}
This should do it - also with the check if customer is logged in.

Facebook client side authorization flow and get access_token for all scenarios like when scope for an app changes, etc

I am trying to do 3 simple things using JS thru a client side authorization flow :
Check if the user is logged in. If not, display the login dialog with proper scope.
If user is already logged into Facebook on the browser, then ensure the app has been authorized (if not, display the Authorize dialog).
If user has already authorized the app then ensure that the access_token on the authResponse has the right scope (permissions) required by the app. (if not, redisplay the authorize dialog for the new permissions).
I am trying to leverage js sdk for this, without wanting to write any hand-coded dialog's etc, since the sdk handles the browsers/devices nuances automagically.
I could not find this properly described anywhere either on FB documentation or otherwise. (no documentation around the fact that the permissions/scope for the app can change post authorization).
Thanks you in advance.
After an arduous attempt I have this working and here are the steps to do this with the minimum amount of code.
*The Approach *
Use fb-login-button to facilitate login. Login Button is the only thing that is displayed when the user first arrives on the page. All other forms are 'hidden', forcing the user to click on this button before being able to go forward.
setup onlogin="function();" on the fb-login-button - so that you can hide the login-button and display the rest of the forms/etc for the user to proceed on your app. Please note that onlogin is called only once (either when the user logs in or authorizes the app with the new scope) - so it is safe to always hide the login-button and display the remaining of the page/form for the user to proceed.
The most important step : use the same fb-login-button to also do the authorization with the right scope : so even if the user is logged in - force the user to click the login-button. fb-login-button in this case, will check if the scope of existing access_token (for already logged in fb user), is a subset of that requested on the fb-login-button attribute. fb-login-button will display the authorize dialog for you automatically in this case. In any case the onLogin callback is triggered (when the login-button should be hidden() and the remaining page/forms be shown()).
Subscribe to the FB.events to get the authResponses and the corresponding access_token every time it is set, which happens 2 times :
a. When the fetch is first displayed for already logged in user
b. After the user authorizes the app first time or second time with the new scope.
This allows you to keep the authResponse and access_token fresh to be used for all subsequent graph calls/etc..
*Implementation Steps *
fb-login-button must be created with onlogin callback :
<div class="fb-login-button" onLogin="onLogin();" scope="publish_actions"
data-size="large">Use This App</div>
Please note that the text does not say Login, but 'Use this App', since the button is displayed for authorization in addition to just logging in.
Subscribe to the Events.
// authRepsonse Change is needed when the user hits the UseApp button
// and permissions are re-fetched - then a new token needs to be refreshed
FB.Event.subscribe('auth.authResponseChange', handleResponseChange);
// when the user logins and all permissions are all set, clicking on the
// use-app will not do anything and authResponse will always be null.
// so this subscription is necessary
FB.Event.subscribe('auth.statusChange', handleResponseChange);
Login Function to hide Login button and display form.
function onLogin () {
hideLogin();
showMain();
}
Handle Status Changes to save Token.
// global variable that contains the access_token
// for use in graph calls/etc.
var authResponse = null;
function handleResponseChange(response) {
if (response && response.authResponse) {
authResponse = response.authResponse
if (response.status == 'connected') {
updateUserInfo(response);
return;
}
}
else {
authResponse = null;
}
hideMain();
showLogin();
}
Hope this helps and I believe that this is probably the most optimal way of handling client side authentication flow without doing any extra authorization/login dialog and let FB sdk do the trick.

Categories

Resources