I have been looking for a good boilerplate on AngularJs with built-in registration and login and I found one, which works pretty well for my needs:
https://github.com/softwaremill/bootzooka/tree/master/ui
However, I cannot make it work because of line 8 in UserSessionService.js (https://github.com/softwaremill/bootzooka/blob/master/ui/app/session/userSessionService.js)
var loggedUserPromise = $http.get('api/users').then(function (response) {...
I edited it in this way:
var loggedUserPromise = $http.get('http://www.mybackend.com/login').then(function (response) {...
My server has only two routes, mybackend.com/login which gets username and password and retrieves an apikey, and mybackend.com/getuser which gets the apikey and returns various userdata.
The problem is that
var loggedUserPromise = $http.get('http://www.mybackend.com/login').then(function (response) {... always returns a 401 since the params (username and password) are not given.
What could it be the error?
Thank you all! :-)
You should provide the params...
$http.get('http://www.mybackend.com/login', {username: "username", password: "password"}).then(function (response) {
I solved setting var loggedUserPromise = null; at the beginning and then
userSessionService.getLoggedUserPromise = function () {
loggedUserPromise = $http.get("http://mybackend.com/user/getself", {params: {Authorization: sessionStorage.token}}).then(function (response) {
loggedUser = response.data;
});
return loggedUserPromise;
};
Related
Almost there, but for some reason my HTTP post request isn't firing and eventually the function timesout. Completely beside myself and posting my code to see if anyone picks up on any noob moves that I'm completely missing. NOTE: the database write completes so I'm assuming that the HTTP Post request isn't firing, is that a safe assumption? Or JS is a different beast?
exports.stripeConnect = functions.https.onRequest((req, res) => {
var code = req.query.code;
const ref = admin.database().ref(`/stripe_advisors/testing`);
var dataString = `client_secret=sk_test_example&code=${code}&grant_type=authorization_code`;
var options = {
url: 'https://connect.stripe.com/oauth/token',
method: 'POST',
body: dataString
};
function callback(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
}
request(options, callback);
return ref.update({ code: code });
});
I understand that you want to POST to https://connect.stripe.com/oauth/token by using the request library and, on success, you want to write the code value to the database.
You should use promises, in your Cloud Function, to handle asynchronous tasks. By default request does not return promises, so you need to use an interface wrapper for request, like request-promise
Therefore, the following should normally do the trick:
.....
var rp = require('request-promise');
.....
exports.stripeConnect = functions.https.onRequest((req, res) => {
var code = req.query.code;
const ref = admin.database().ref('/stripe_advisors/testing');
var dataString = `client_secret=sk_test_example&code=${code}&grant_type=authorization_code`;
var options = {
url: 'https://connect.stripe.com/oauth/token',
method: 'POST',
body: dataString
};
rp(options)
.then(parsedBody => {
return ref.update({ code: code });
.then(() => {
res.send('Success');
})
.catch(err => {
console.log(err);
res.status(500).send(err);
});
});
I am new to express js. I am working on a project. where i have to send email when the user is updated. but the problem is that once the user is updated. Inside the update success I don't have access to req object or userUpdate. I know its a concept issue. Can you please let me know how to fix this.?
thanks
module.exports.update = function(req, res) {
var body = _.pick(req.body, 'email', 'first_name', 'last_name', 'role', 'clinic_id', 'profile_id');
if (!_.isString(body.email) || !_.isString(body.first_name) || body.email.length == 0 || body.first_name.length == 0) {
res.status(404).send();
} else {
var userUpdate = req.body;
var selector = {
email: userUpdate.email
};
userUpdate.updatedAt = new Date().getTime();
//*********req object and userUpdate have data till this point**************//
db.user.update(userUpdate, { where: selector })
.then(function(result) {
// ****req object and userUpdate are not defined here. WHY??
mailer.sendActivateEmail(result);
// sending response to front end
res.json(result);
}).catch(function(e) {
res.status(500).json(e);
console.log("error updating user:", e);
});
}
};
The problem was in my understanding. I am able to access req object anywhere in the function. The problem occurs in debugging. When i use debugger in my code. I usually don't have access to variables outside of function scope.
When i use console.log to print object before debugger, things work as expected.
Don't have time to actually run your code but I would suggest two things:
Try binding your function call so that the function definitely receives the req object.
db.user.update(userUpdate, { where: selector }).then(updateSuccess.bind(req)))
Define updateSuccess like this
const updateSuccess = (req, result) => { ... }
Try using anonymous functions instead of function, ie.
module.exports.update = (req, res) => {
Could be some weird scoping problem
I'm attempting to make a Web 2.0 API call via AngularJS using $http.post that returns JSON and as weird as this may sound, it worked an hour ago, now it doesn't and I haven't changed a thing. The application continues to work in all other browsers, it just fails in Edge.
var _login = function (loginData) {
var data = "";
var grant = [insert data to authorise user on server];
var deferred = $q.defer();
$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {
_userlogin(response);
deferred.resolve(response);
}).error(function (err, status) {
console.log(err + " " + status);
_logOut();
deferred.reject(err);
});
return deferred.promise;
};
I've had to take some info out there because it's security info, but the functionality should be the same, so, from debugging I know that this is where the application stumbles. I also know that the logindata passed in is valid and I've tried the same call with the same grant on a REST client and that works fine also like I mentioned before the same call with no alterations runs in any other major browser (including IE weirdly).
When that call is run, the front end angular does the following:
$scope.authUser = function (username, password) {
var loginData = { userName: username, password: password, useRefreshTokens: login.useRefreshTokens}
authService.login(loginData).then(function (response) {
console.log(response);
sessionStorage.setItem("status", "User Logged In As: ");
sessionStorage.setItem("username", username);
global.template = "templates/dashboard.html";
login.password = "";
},
function (err) {
console.log(err);
login.message = err.error_description;
$("#passwordError").modal();
});
};
The application stops at login.message = err.error_description;, because it's not returned from the API call. The error is: Network Error 0x2efd, Could not complete the operation due to error 00002efd. and Unable to get property 'error_description' of undefined or null reference.
Edit: Forgot to mention - the application works when Fiddler is open and capturing traffic. That's the strangest part.
Take a look at this post which used the solution mentioned here. They're saying the issue was with interacting between localhost to localhost.
I'm glad I was able to help.
I'm refactoring my angular code from using $http to ngResource.
I used to have code like this in my service:
svc.login = function(username, password) {
return $http.post(apiEndpoint + 'authenticate', {
username: username,
password: password
})
.then(function(val) {
console.log("user token:", val.data);
svc.token = val.data;
});
};
The user token printed will be a jwt token. Now I try to refactor the code to something like this:
svc.login = function(username, password) {
svc.authenticateApi().post(apiEndpoint + 'authenticate', {
username: username,
password: password
},
function(val) {
console.log("user token:", val);
svc.token = val;
},
function(res) {
console.log("error:", res.status + " " + res.statusText);
});
};
However, it doesn't work because the parameter val passed to the first callback is no longer the token itself but a object which contains a string array like this:
What's the standard way to handle data returned from post method? (in this case post is defined the same as save on this resource)
I think the issue comes from transformRespose
transformResponse – {function(data,
headersGetter)|Array.} – transform
function or an array of such functions. The transform function takes
the http response body and headers and returns its transformed
(typically deserialized) version. By default, transformResponse will
contain one function that checks if the response looks like a JSON
string and deserializes it using angular.fromJson. To prevent this
behavior, set transformResponse to an empty array: transformResponse:
[]
try transforming your response into a json:
transformResponse: function (data) {
return { token: angular.fromJson(data) }
ive never used cloud code/javascript and I am trying to write some parse cloud code to find a user using a objectId passed in to the cloud function, and then update that users relation that holds friends and finally save that user.
below is the function im using:
Parse.Cloud.define("addFriendToFriendsRelation", function(request, response) {
Parse.Cloud.useMasterKey();
var fromUserObjectId = request.params.fromUserObjectId;
var acceptingUser = request.params.user;
var query = new Parse.Query(Parse.User);
// find the user the request was from using the objectId
query.get(fromUserObjectId, {
success: function(user) {
var fromUser = user
var relation = fromUser.relation("friends");
relation.add(acceptingUser);
fromUser.save({
success: function() {
response.success("Successfully saved the users relation")
},
error: function() {
response.error("Save failed");
}
});
},
error: function() {
response.error("Save failed");
}
});
});
I managed to piece this together using the Parse docs. but Im really not following it to well. Never used javascript and am finding the syntax confusing.
then im calling the function with
//fromUser is a PFUser object defined further up
[PFCloud callFunctionInBackground:#"addFriendToFriendsRelation" withParameters:#{#"fromUserObjectId" : fromUser.objectId} block:^(id object, NSError *error) {
}
however whenever this function is called I get a success/error was not called error. Though im calling response.success and response.error in the function so I dont know why that is? Can anyone lend a hand?
edit: after doing some more searching it looks like response.success and response.error should only be called once each, so I modified my function to look like this:
arse.Cloud.define("addFriendToFriendsRelation", function(request, response) {
Parse.Cloud.useMasterKey();
var fromUserId = request.params.fromUserObjectId;
console.log("fromUserId:");
console.log(fromUserId);
var acceptingUser = request.params.user;
console.log("acceptingUser:")
console.log(acceptingUser);
var query = new Parse.Query(Parse.User);
query.get(fromUserId, {
success: function(user) {
console.log("found user:");
console.log(user);
var fromUser = user;
var relation = fromUser.relation("friends");
relation.add(acceptingUser);
console.log("added accepting user to relation");
fromUser.save({
success: function() {
response.success("successfully saved user")
},
error: function() {
response.error("error saving user");
}
});
console.log("found a user");
},
error: function() {
console.log("error finding user");
}
});
});
An old question, but since it's been up-voted, maybe answering can help someone else :).
First off, there is an error in how you are saving fromUser.
fromUser.save({ success: ...
If you look at the api you can see that it should be of the form:
fromUser.save(null, { success: ...
But the larger problem that kept you from finding your bug is that errors are getting eaten 'cause you are using the old style method of dealing with async code instead of using promises.
Below, I have re-written to use promises. Note:
I always return promise generating calls (there are other options for catching errors in async code, but start with this.)
Put a .catch at the end. The .catch is effectively the same things as .then(null, response.error) but either way, it is imperative that there is final backstop to catch errors. In your code above, the error was in a success block, that was running async, so when there was an error, it failed with no one to hear it :).
Parse.Cloud.define("addFriendToFriendsRelation", (request, response) => {
const fromUserId = request.params.fromUserObjectId;
console.log("fromUserId:", fromUserId);
const acceptingUser = request.user;
console.log("acceptingUser:", acceptingUser)
new Parse.Query(Parse.User);
.get(fromUserId, { useMasterKey: true })
.then((fromUser) => {
console.log("found fromUser:", fromUser);
const relation = fromUser.relation("friends");
relation.add(acceptingUser);
console.log("added accepting user to relation");
return fromUser.save(null, { useMasterKey: true })
})
.then(response.success)
.catch(response.error);
});