I'm trying to build an app for shopify and I'm interested if I can get the current logged user ID using javascript api or something similar.
I was looking at the ajax api: http://docs.shopify.com/support/your-website/themes/can-i-use-ajax-api and I can see you can get the current products that the current user has added to his shopping cart, but nothing about the user ID.
Is it possible, or am I missing something?
You can try __st.cid in JavaScript for getting customer id.
I've found the __st variables unreliable (__st_uniqToken for one).
I believe the proper way to do this in Javascript is using the following call:
ShopifyAnalytics.lib.user().id()
You can also get the unique user id (non-logged in id) with:
ShopifyAnalytics.lib.user().properties().uniqToken
This is also the only reliable way to get it on the checkout page. I previously used __st_uniqToken, but it has since stopped working.
NOTE This is no longer 100% fool-proof. Shopify have AGAIN changed how their site works on the landing and thank-you pages.
I've had to resort to the following function to get a user id 'reliably'.
var user_id = function() {
try {
return ShopifyAnalytics.lib.user().id();
} catch(e) {}
try {
return ShopifyAnalytics.lib.user().properties().uniqToken;
} catch(e) {}
try {
return ShopifyAnalytics.lib.user().anonymousId();
} catch(e) {}
return __st_uniqToken;
};
Developing for Shopify is a true nightmare. I spend 50% of my time un-breaking my product every few weeks because them.
In layout.liquid file you can add this code to define global customerId variable
{% if customer %}
<script type="text/javascript">
window.customerId = "{{ customer.id }}";
</script>
{% endif %}
Just get it from ShopifyAnalytics.meta.page.customerId is your script
Your best bet would be to create an App that installs a simple ScriptTag in the shop. That script can then report the customer ID back to the App securely. Very simple to do that. Forget the front-end API as there is no secure way to call your App using that.
It seems that Shopify API was again changed, I see that now the user Id is in ShopifyAnalytics.lib.user().traits().uniqToken. Also, it may take time for this value to be loaded.
I use this code snippet to perform the job once the value available.
<script type="text/javascript">
actOnUser = function(retry, func){
if (ShopifyAnalytics && ShopifyAnalytics.lib && ShopifyAnalytics.lib.user) {
console.log(ShopifyAnalytics.lib.user().traits().uniqToken); // Do your work here.
} else {
if (retry > 0) {
setTimeout(function() {
func(retry - 1, func);
}, 1000);
}
console.log('User not ready'); // Can be removed - just for debug
}
}
console.log('Starting');
setTimeout(function() {
actOnUser(10, actOnUser);
}, 1000);
</script>
This solution is not 100% about getting user_id, but about detecting if current user is logged in as admin. You can use typeof Shopify.AdminBar to check if the admin bar exists. It's automatically created by Shopify if the current user is admin. Maybe this will help someone.
Related
I have a web app where the client side is developed in Javascript. I have already enabled Azure AD login for my app by configuring it at portal.azure.com. Then, every time when this app loads, users are required to log in, if they have not.
I would like to have some Javascript in my client side so the app knows the user name. Here is the code I have.
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.11/js/adal.min.js"></script>
<script type="text/javascript">
var authContext = new AuthenticationContext({
clientId: 'xxxx-xxx-xxxx',
postLogoutRedirectUri: window.location
});
var user = authContext.getCachedUser();
if (user) {
window.alert("Signed in as " + user.userName);
} else{
window.alert("Failed to get the user information");
}
</script>
However, the variable user is always null. Can anybody help?
That seems you are using "Authentication / Authorization" feature of azure app service and the identity provide is azure ad . If you want to access the tokens from a client (like JavaScript in a browser), or if you want to get a richer set of information about the logged in user, you can also send an authenticated GET request to the /.auth/me endpoint. Javascript code below to get user claims is for your reference:
<script type="text/javascript">
$(document).ready(function ()
{
$.get("https://xxxxxx.azurewebsites.net/.auth/me", function (data, status) {
for (var key in data[0]["user_claims"]) {
var obj = data[0]["user_claims"][key];
alert(obj["typ"]); //claim type in user_claims
alert(obj["val"]) //claim value in user_claims
}
});
});
</script>
Thanks, Yan. That pretty solves my problem, only with little revision to your code. My situation is that I need to retrieve the user name first before generating the later part of my app. So, I removed the outer wrapper $(document).ready(function(){}. Correct me if I am wrong. Probably this out wrapper is telling this chunk of code to run after the entire app is loaded. Then, the final code is like this:
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$.get("https://xxxxx.azurewebsites.net/.auth/me", function (data) {
labeler = data[0]['user_id'];
window.alert("You logged in as " + data[0]['user_id']);
});
</script>
I've got following code for user authorization using Firebase but I'm not able to understand the code. Below the code I've mentioned the doubts I'm facing. Plase someone clarify them.
var ref = new Firebase("https://prj_name.firebaseio.com");
var loggedInUser = [];
$(document).ready(function() {
authData=ref.getAuth();
if(authData == null){
//TODO find an elegant way to manage authorization
// window.location = "../index.html";
}else{
ref.child("users").child(authData.uid).on("value", function(snapshot){
$( "span.user-name").html(snapshot.val().displayName);
loggedInUser.displayName = snapshot.val().displayName;
});
}
$("#cPassword").focusout(function() {
validatePassword($("#cPassword"), $("#password"));
});
$(document).on("click", ".clickable-row" ,function(){
window.document.location = $(this).data("href");
});
});
function validatePassword(password, cPassword) {
if (cPassword.val() != password.val()) {
cPassword.css('border-color', 'red');
password.css('border-color', 'red');
return false;
}
return true;
}
All the necessary libraries like firebase have been included and above code is working absolutely fine, the only concern is I'm not able to understand it.
My doubts are as follows :
What does the line authData=ref.getAuth(); do and what authData contains after it get execute?
In else block, what is value and snapshot. I didn't understand at all the line. ref.child("users").child(authData.uid).on("value", function(snapshot)
Can someone please clarify my doubts? Thanks.
Ok here goes:
Firstly you should update your firebase security rules first if you haven't already: Firebase security rules guide
ref.getAuth() returns a value that will either be null if you haven't been authorised yet or it will contain an object with some info about how the user was authorised (custom token, facebook id, email etc.)
This line: ref.child("users").child(authData.uid).on("value", function(snapshot). Here you're basically requesting some data from your users collection: '/users/{some unique id}'. When you request the data from firebase, as soon as the data is ready to be used, Firebase triggers the "value" callback and passes the data (snapshot) using this callback.
The firebase docs are very good, I would advise reading through the entire web guide. Firebase web guide
I hope I've been able to clear some things up for you!
I am building a webpage using AngularJS and Firebase. I want to use facebook login to connect information on the webpage with the user. Firebase has a version of simple login which I guess is supposed to simplify the login process.
My problem is that I want to access information about the logged in user in a lot of places on my webpage but I can't find a good way to do it.
This is how I started out:
var userInfo = null;
var ref = new Firebase('https://<yourfirebase>.firebaseIO.com/');
var auth = new FirebaseSimpleLogin(ref, function(error, user) {
if(error)
alert("You are not logged in");
else if(user)
{
//store userinfo in variable
userInfo = user;
}
else
//user logged out
});
//do something with userInfo
alert(userInfo.name);
My first thought was to run this at the top of my page and then use the info about the user. The problem is that the code using userInfo (as in e.g. the alert) will always run before the userInfo variable has been filled and userInfo will return undefined/null.
I then proceeded to always create a new firebasesimplelogin object when i want to retrieve user data. Which of course isn't very good. Especially since every created FirebaseSimpleLogin object will be called again whenever another is called or a user logs out, for example.
So my question is, how do I use FirebaseSimpleLogin to handle and use my user information in the best way?
I would have liked some function to getUserInfo() or check isLoggedIn() for example. How do you do this properly?
You can take a look at this example for thinkster. It's based on using simple login with userid/password. http://www.thinkster.io/angularjs/4DYrJRxTyT/7-creating-your-own-user-data-using-firebase.
You can create a function like getLoggedinUser that runs in $rootScope that will allow you to find the user throughout the application.
UPDATE:
Around the middle of October 2014, firebase made some big changes. This method might still work, but it's better to take advantage of the newer version of firebase, specifically getauth and onauth. These methods will allow you to do the same thing without running on the rootScope. https://www.firebase.com/docs/web/guide/user-auth.html#section-login
Please make a constant to use it everywhere in your App like that
.constant('facebookUrl', 'https://rjrestaurantapp.firebaseio.com');
Then in the controller inject this constant "facebookUrl & "$state" as shown below...
.controller('loginCtrl', function($scope,facebookUrl,$state){
and then you only need to give name of the state where you want to redirect after facebook authentication..
var ref = new Firebase(facebookUrl);
$scope.fbLogin = function () {
ref.authWithOAuthPopup("facebook", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
$state.go('restaurant');
}
})
}})
You can see the information in authData object after successfull authentication using facebook ....
please read this doc carefully https://www.firebase.com/docs/web/guide/login/facebook.html
The above is the example of simple login using firebase and for retrieving data for each logged in user, you have to store user information at the time of signin as you know that firebase makes every child with a unique ID .. then you only need to use the offline features of firebase that will find which user is offline and according to that remove the node with the same ID which one is offline, you can find examples in the MANAGING PRESENCE section of the below link ..
https://www.firebase.com/docs/web/guide/offline-capabilities.html
I'm having trouble getting a logged in facebook user in my parse.com application to log out. What is wrong with the code below?
function logOff() {
function thisSuccess(e) {
console.log(1);
}
function thisError(e) {
console.log(0);
}
var u = Parse.User.current();
Parse.FacebookUtils.unlink(u, {success: thisSuccess,error: thisError});
u.logOut();
}
I've searched everywhere, the best response I got was that the facebook account linked to the user needs to be unlinked as well - I'm not entirely sure whether this is so.
All you need is Parse.User.logOut();
Don't unlink the Facebook account, as that use won't be able to log in again. Next time they try to log in with Facebook Parse will create a new user for them.
I have a facebook likebox on my site (not an iframe app) where I need to create gated content. I understand the FB.Event.subscribe using edge.create and edge.remove but what I really need is to know if a user already likes the page not simply if they became a fan or stopped being a fan. Is there anything I can see as a callback maybe from the xfbml.render?
I am limited (by my company) to using front end languages, meaning javascript is really my only option at this point. I would gladly use the "signed_request" option but best I can tell that seems to be only accessible via server side languages.
Is there any way for me to determine whether someone already "Likes" a page using only javascript?
Yes, you can do this completely in javascript using the FB Javascript sdk.
function RunLikeCheck() {
var likeId = 'yourLikeIdHere';
FB.api({
method: 'fql.query',
query: 'SELECT uid FROM page_fan WHERE page_id = ' + likeId + ' AND uid = me()'
},
function (response) {
if (response.length == 1) {
$("#HasLiked").val('true');
$('#frmAllow').submit();
}
else {
$("#HasLiked").val('false');
$('#frmAllow').submit();
}
}
);
}
Now this is assuming that you already have the user logged in and have the correct permissions.
Here is some additional sample javascript code for implementing a like gate that does not require the FB.api call (but does require the user to re-like every time they visit the page).
http://linksy.me/viral-gate