What is the clean way to store information get from web service in angularJS? - web-services

I've got a front-end Angular App which get information from server side on a REST API.
When I make requests, I'd like to do it only once and so, keep the data in the front app.
I found several examples but either:
the logic is in controller -> not a good practice
variables are stored in the root scope -> not a good practice in general
I was told to use services to do this.
For example, from what I understood, I should have a service which GET user profile, and another one which keep these information (a "profile" service) once the GET request has been made.
Could someone show me how to do this if my service to call GET request is something like this:
.factory('userPromise', ['$http', '$q', 'baseUrl',
function ($http, $q, baseUrl) {
return {
getUser: function(usn, uid, key) {
return $http.get(baseUrl + 'business_infos/' + parseInt(uid) + '/'
+ '?format=json&username=' + usn + '&api_key=' + key).then(function(response) {
return response.data;
});
}
};
}])
Note that I don't want to just cache information. I want to create a user profile from what I get that can contain other information.
it would be something like:
{
profile: {
firstname: "Thierry",
lastname: "Chatel"
},
hasRole: function (role) {
return ...
}
}
Thank you!

There is documentation for cacheFactory, you can cahce data and get it.
http://code.angularjs.org/1.2.14/docs/api/ng/service/$cacheFactory

Related

Facebook Matching API - Returns empty data for any other user

I have a problem when I use the Facebook Checkbox Plugin in order to connect my users to a Facebook chatbot. When they click and the checkbox is checked, I get their user reference, and sending him/her a message, I get the user page-scoped id.
Using this user page-scoped id, I should be able to get the user app-scoped id, that I need to get more information from this user.
In order to to this, I use the facebook Matching API, and it works great for my administrator user, but as soon as I login using any other user, even if it is registered as a developer, the data that I get from the matching API is empty.
[https://developers.facebook.com/docs/messenger-platform/identity/id-matching]
Anybody has an idea about what could be happening here? My app is live (not approved), and I believe the permissions and tokens are right... If there is a problem, it should be about tokens, but I'm not sure about this.
Here, some of my code:
const accessToken = config.facebook.unlimitedPageAccessToken;
const clientSecret = config.facebook.clientSecret;
const appsecretProof = CryptoJS.HmacSHA256(accessToken, clientSecret).toString(CryptoJS.enc.Hex);
request({
url: 'https://graph.facebook.com/v2.10/'+ recipientId +'/ids_for_apps',
qs: { access_token: accessToken, appsecret_proof: appsecretProof }
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
body = JSON.parse(body);
console.log("data --> " + JSON.stringify(body, null, 4));
const userAppId = body.data[0].id;
return userAppId;
} else {
console.error("Error trying to translate ID's.");
}
});
As I said, when I log in with any other user than the administrator, I get this:
{
"data": []
}
For every Facebook page, a user has a different psid. So until you get that page scoped id, you won't be able to send them a message. So may be what you can do is link the users to the page first to initialize the conversation.

Identity Server 3 Facebook Login Get Email

Identity server is implemented and working well. Google login is working and is returning several claims including email.
Facebook login is working, and my app is live and requests email permissions when a new user logs in.
The problem is that I can't get the email back from the oauth endpoint and I can't seem to find the access_token to manually request user information. All I have is a "code" returned from the facebook login endpoint.
Here's the IdentityServer setup.
var fb = new FacebookAuthenticationOptions
{
AuthenticationType = "Facebook",
SignInAsAuthenticationType = signInAsType,
AppId = ConfigurationManager.AppSettings["Facebook:AppId"],
AppSecret = ConfigurationManager.AppSettings["Facebook:AppSecret"]
};
fb.Scope.Add("email");
app.UseFacebookAuthentication(fb);
Then of course I've customized the AuthenticateLocalAsync method, but the claims I'm receiving only include name. No email claim.
Digging through the source code for identity server, I realized that there are some claims things happening to transform facebook claims, so I extended that class to debug into it and see if it was stripping out any claims, which it's not.
I also watched the http calls with fiddler, and I only see the following (apologies as code formatting doesn't work very good on urls. I tried to format the querystring params one their own lines but it didn't take)
(facebook.com)
/dialog/oauth
?response_type=code
&client_id=xxx
&redirect_uri=https%3A%2F%2Fidentity.[site].com%2Fid%2Fsignin-facebook
&scope=email
&state=xxx
(facebook.com)
/login.php
?skip_api_login=1
&api_key=xxx
&signed_next=1
&next=https%3A%2F%2Fwww.facebook.com%2Fv2.7%2Fdialog%2Foauth%3Fredirect_uri%3Dhttps%253A%252F%252Fidentity.[site].com%252Fid%252Fsignin-facebook%26state%3Dxxx%26scope%3Demail%26response_type%3Dcode%26client_id%3Dxxx%26ret%3Dlogin%26logger_id%3Dxxx&cancel_url=https%3A%2F%2Fidentity.[site].com%2Fid%2Fsignin-facebook%3Ferror%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied%26state%3Dxxx%23_%3D_
&display=page
&locale=en_US
&logger_id=xxx
(facebook.com)
POST /cookie/consent/?pv=1&dpr=1 HTTP/1.1
(facebook.com)
/login.php
?login_attempt=1
&next=https%3A%2F%2Fwww.facebook.com%2Fv2.7%2Fdialog%2Foauth%3Fredirect_uri%3Dhttps%253A%252F%252Fidentity.[site].com%252Fid%252Fsignin-facebook%26state%3Dxxx%26scope%3Demail%26response_type%3Dcode%26client_id%3Dxxx%26ret%3Dlogin%26logger_id%3Dxxx
&lwv=100
(facebook.com)
/v2.7/dialog/oauth
?redirect_uri=https%3A%2F%2Fidentity.[site].com%2Fid%2Fsignin-facebook
&state=xxx
&scope=email
&response_type=code
&client_id=xxx
&ret=login
&logger_id=xxx
&hash=xxx
(identity server)
/id/signin-facebook
?code=xxx
&state=xxx
I saw the code parameter on that last call and thought that maybe I could use the code there to get the access_token from the facebook API https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow
However when I tried that I get a message from the API telling me the code has already been used.
I also tried to change the UserInformationEndpoint to the FacebookAuthenticationOptions to force it to ask for the email by appending ?fields=email to the end of the default endpoint location, but that causes identity server to spit out the error "There was an error logging into the external provider. The error message is: access_denied".
I might be able to fix this all if I can change the middleware to send the request with response_type=id_token but I can't figure out how to do that or how to extract that access token when it gets returned in the first place to be able to use the Facebook C# sdk.
So I guess any help or direction at all would be awesome. I've spent countless hours researching and trying to solve the problem. All I need to do is get the email address of the logged-in user via IdentityServer3. Doesn't sound so hard and yet I'm stuck.
I finally figured this out. The answer has something to do with Mitra's comments although neither of those answers quite seemed to fit the bill, so I'm putting another one here. First, you need to request the access_token, not code (authorization code) from Facebook's Authentication endpoint. To do that, set it up like this
var fb = new FacebookAuthenticationOptions
{
AuthenticationType = "Facebook",
SignInAsAuthenticationType = signInAsType,
AppId = ConfigurationManager.AppSettings["Facebook:AppId"],
AppSecret = ConfigurationManager.AppSettings["Facebook:AppSecret"],
Provider = new FacebookAuthenticationProvider()
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, ClaimValueTypes.String, "Facebook"));
return Task.FromResult(0);
}
}
};
fb.Scope.Add("email");
app.UseFacebookAuthentication(fb);
Then, you need to catch the response once it's logged in. I'm using the following file from the IdentityServer3 Samples Repository, which overrides (read, provides functionality) for the methods necessary to log a user in from external sites. From this response, I'm using the C# Facebook SDK with the newly returned access_token claim in the ExternalAuthenticationContext to request the fields I need and add them to the list of claims. Then I can use that information to create/log in the user.
public override async Task AuthenticateExternalAsync(ExternalAuthenticationContext ctx)
{
var externalUser = ctx.ExternalIdentity;
var claimsList = ctx.ExternalIdentity.Claims.ToList();
if (externalUser.Provider == "Facebook")
{
var extraClaims = GetAdditionalFacebookClaims(externalUser.Claims.First(claim => claim.Type == "urn:facebook:access_token"));
claimsList.Add(new Claim("email", extraClaims.First(k => k.Key == "email").Value.ToString()));
claimsList.Add(new Claim("given_name", extraClaims.First(k => k.Key == "first_name").Value.ToString()));
claimsList.Add(new Claim("family_name", extraClaims.First(k => k.Key == "last_name").Value.ToString()));
}
if (externalUser == null)
{
throw new ArgumentNullException("externalUser");
}
var user = await userManager.FindAsync(new Microsoft.AspNet.Identity.UserLoginInfo(externalUser.Provider, externalUser.ProviderId));
if (user == null)
{
ctx.AuthenticateResult = await ProcessNewExternalAccountAsync(externalUser.Provider, externalUser.ProviderId, claimsList);
}
else
{
ctx.AuthenticateResult = await ProcessExistingExternalAccountAsync(user.Id, externalUser.Provider, externalUser.ProviderId, claimsList);
}
}
And that's it! If you have any suggestions for simplifying this process, please let me know. I was going to modify this code to do perform the call to the API from FacebookAuthenticationOptions, but the Events property no longer exists apparently.
Edit: the GetAdditionalFacebookClaims method is simply a method that creates a new FacebookClient given the access token that was pulled out and queries the Facebook API for the other user claims you need. For example, my method looks like this:
protected static JsonObject GetAdditionalFacebookClaims(Claim accessToken)
{
var fb = new FacebookClient(accessToken.Value);
return fb.Get("me", new {fields = new[] {"email", "first_name", "last_name"}}) as JsonObject;
}

Meteor share sessions data between client and server

I'm building a restricted signup. I want user with a specific code passed in a url to be able to signup and not others. I'm using the accounts package.
I can prevent account creation in the Accounts.onCreateUser method. I'm looking for a way to tell the server if the client had an authorised signup code. With a classic form (email+password) I can just add an extra hidden field. How can I achieve the same result if the user signs up with let's say Facebook?
Since Meteor doesn't use cookies, I can't store this info in a cookie that the server would access. Session variable are not accessible server side. And since I'm not controlling what got send with the account-facebook creation, I can't use a Session variable on the client side that I'd pass along when the user presses sign up.
Any idea"?
Just add the special token to the user object being passed to Accounts.createUser():
var user = {
email: email,
password: password,
profile: {
token: token
}
};
Accounts.createUser(user, function (error, result) {
if (error) {
console.log(error)
}
});
On the server side you can access this in the Accounts.onCreateUser():
Accounts.onCreateUser(function(options, user) {
console.log(options);
console.log(user);
});
I think it's in the options variable that you will find your token, so it would be options.profile.token.
for me, the best option here was passing in custom parameters to loginbuttons.
see the package docs:
https://github.com/ianmartorell/meteor-accounts-ui-bootstrap-3
Where it outlines the below:
accountsUIBootstrap3.setCustomSignupOptions = function() {
return {
mxpDistinctId: Session.get('mxpdid'),
leadSource: Session.get('leadSource')
}
};

Django Rest Framework + React + Reflux: Can't GET new objects

I'm trying to post a new object via a React form using a Reflux action. That part is working fine. The object is posting as expected, however, when I try to GET that object programmatically, it doesn't seem to be accessible unless I log out, restart my local server, or sometimes even simply visit the api page manually.
I can't seem to get consistent behavior as to when I can get the object and when I can't. It does seem that viewing the api page and then returning to my app page has some kind of effect, but I'm at a loss as to why. Perhaps someone can shed a little light onto this for me.
One thing that's for sure is that the POST request is working properly, as the object is always there when I check for it manually.
Also, if you notice in the code below, I check to see what the last object on the api page is, and the console responds with what previously was the last item. So I'm able to access the api page programmatically, but the object I created is not there (though it is if I visit the page manually). Note, too, that refreshing produces the same results.
Any ideas where the issue could be or why this might happen?
Here's the action:
MainActions.getUserProfile.listen(function(user) {
request.get('/api/page/').accept('application/json').end( (err, res) => {
if (res.ok) {
var profiles = res.body;
var filteredData = profiles.filter(function (profile) {
if (profile) {
return profile.user === user
}
else {
console.log('No Profile yet.')
}
});
if (filteredData[0]) {
var data = {
user: filteredData[0].user,
...
};
... // other actions
} else {
console.log(profiles[profiles.length - 1].user)
}
} else {
console.log(res.text);
}
});
});
The problem ended up being with the Cache-Control header of the response having a max-age=600. Changing that to max-age=0 solved the issue. In this situation, it doesn't make much sense to provide a cached response, so this I added this to my serializer's ViewSet:
def finalize_response(self, request, *args, **kwargs):
response = super(MyApiViewSet, self).finalize_response(request, *args, **kwargs)
response['Cache-Control'] = 'max-age=0'
return response

In Ember.js, how do you make requests to an API that are outside of the REST convention?

I would like to request a 'reset password' endpoint e.g GET -> user/password/reset on an API. What is the best way to map this request in ember.js? It doesn't seem appropriate to setup a full ember.js model for this kind of request, as it doesn't have a proper ID and is not really a request for a record, but a triggered event with a success/fail response. Am I incorrectly implementing the REST convention or is there another way to do this?
You can use a simple ember-object to represent password reset and then basic ajax. Something like this:
App.User.reopenClass({
resetPassword: function(subreddit) {
return $.getJSON("user/password/reset").then(
function(response) {
console.log('it worked');
return true;
},
function(response) {
console.log('fail');
return false;
}
);
}
});
See http://eviltrout.com/2013/03/23/ember-without-data.html
That said, this could be a sign that the API endpoint should change. Ideally GET requests should not have side effects, so a GET that resets a password is not recommended. If you think of reset as a password reset request, the reset password endpoint that makes the most sense is POST -> user/password/reset to create a new request.