AngularJS: Value arriving as null in service - angularjs

I am trying to pass an object to my API, but when I do this for some reason the object becomes null. I cannot see the reason for this because I've done a similar process on multiple other occasions.
var promiseGetRole = loginService.GetRole(user);
promiseGetRole.then(function (data, status, headers, config) {
$location.path('/UserManagement').replace();
if (!$scope.$$phase) $scope.$apply()
},
function (errorResult) {
console.log("Unable to log in : " + errorResult);
});
User is correctly populated.
//Get the Role of a given user
this.GetRole = function (user) {
return $http.get(toApiUrl('login'), user);
}
Again, user is correctly populated at this point.
//The user has been validated, now retrieve their role from the server
public string Get(UserLogin user)
{
string role = "";
//TODO: set role
return role;
}
It's at this point when it reaches the API the value for User just becomes null. I am using the same process in a post method (using UserLogin as the object being passed in) and cannot see any difference between them.

I would pass data to the back-end like this(assuming you can retrieve roles by userId).:
var promise = $http.get(toApiUrl('login'), { params:{userId:user.Id}); // Only pass id in queryparams
...
You probably can pass the entire user object in the querystring but it has a length limit.
I don't know what you run back-end either so depending on that you might need to do different things to make it bind to the data.

Related

updateCacheData for specific user only

updateCachedData((draft) => { draft = response; }
I'm using updateCachedData function and through this function i'm updating my cached but problem is when it update cache all the users listen it. But I want to update a specific user only.like sender person and receiver person.
I'm using updateCachedData function within socket.on function and JSON server for API

Firebase: How to get the $id of an object after I authenticate using angularFire

Firebase has the $onAuth method that listens for changes to the client's authentication state. If the client is authenticated, the callback will be passed an object that contains the uid.
Here is my question:
Based on this uid, how can I get the the $id for this object.
This is how my data looks like in firebase:
profile {
-K2a7k9GXodDriEZrM3f {
email: "ale#aol.com"
gravatar: "https://www.gravatar.com/avatar/1d52da55055f0c8..."
uid: "3f9e0d53-4e61-472c-8222-7fc9f663969e"
name: "ale"
}
}
I am using
auth.$onAuth(function (authData) {
if (authData) {
authData.profile = //here I want the $id of the object
}
})
All I see I can do with the authData response is to get the uid of the object by using:
$firebaseObject(ref.child('profile').child(authData.uid));
This authData does not contain the $id (i.e. the -K2a7k9GXodDriEZrM3f) of the object. And that is what I am looking for in order to have the user's information available. Is there a way to achieve this?
Thanks.
If an object has a natural unique ID, you should usually store the object under that ID. Using push IDs in those cases adds no value and only complicates things.
Most developers using Firebase do as the "Storing User Data" section in the documentation illustrates: they store users by their uid. If you follow that guideline, you can find the key as authData.uid.
If you decide to stick to your current course, you can find the key for the user with:
ref.child('profile').orderByChild('uid').equalTo(authData.uid).once('child_added', function(snapshot) {
console.log(snapshot.key());
});
But you will be making it harder for the database to find your user, thus limiting the scalability of your app.

How to let an admin change user properties in Meteor?

Are there any special hoops one has to jump through when modifying user objects in Meteor? I have no problem changing other collections but the users are strangely and persistently resistant to the many suggestions I have found.
I can see that there are some user attributes such as profile that are published and presumably quite easy to change. I need more control over the access so just bunging my data into user.profile won't do. At the moment I'm trying to give users a grant table, so that for example I can write:
var user = Meteor.users.findOne();
var may_eat_popcorn = user.grants.popcorn;
This works:
$ meteor shell
// First check that the user is not allowed to eat popcorn:
> Meteor.users.findOne({_id:"iCTnpqwCR6jj9xxxx"});
....
grants: { popcorn: false } }
// Give the non-gender specific entity access to popcorn:
> Meteor.users.update({_id:"iCTnpqwCR6jj9xxxx"},{$set:{"grants.popcorn":true}}, function(err,res){console.log("grant:",err,res);});
> Meteor.users.findOne({_id:"iCTnpqwCR6jj9xxxx"});
....
grants: { popcorn: true } }
// Hooray.
This doesn't, even though equivalent code works fine with other collections:
Meteor.methods(
{ User_grant_popcorn: function(userId, granted){
// authentication. Then:
var grants = {"grants.popcorn": granted};
console.log(userId,grants);
Meteor.users.update({_id:userId},{$set:grants}, function(err,res){console.log("grant:",err,res);});
// This callback prints that there is no error, yet the database doesn't change on the server.
}
});
// On the client the admin picks the target user and sets their degree of pop:
Meteor.call('User_grant_popcorn', user._id, false);
Do you know how user is different? More importantly, how can I debug issues like this? Winning means getting awesome things done fast. That's meteor's promise. If debugging takes this long the advantage is lost.
Many thanks, Max
Programmatically create $set
Meteor.methods({
User_grant_popcorn: function(userId, granted) {
// authentication. Then:
var grants = {
"grants.popcorn": granted
};
var setHash = {
$set: grants
};
console.log(userId, grants);
Meteor.users.update({_id: userId}, setHash, function(err, res) {
console.log("grant:", err, res);
});
// This callback prints that there is no error, yet the database doesn't change on the server.
}
});

How to store user details for further use in angularjs

I am working on web application using angularjs. I need the user's email address throughout my application, how can I store it for further use?
Currently what I am doing is:
I have created a user service
'use strict';
var module = angular.module('moduleName');
module.factory('UserService',['$resource',function($resource){
var currentUserEmail = null;
return {
getUserResource : function(){
return $resource('users',{email:'#email'});
},
saveCurrentUserEmail : function (email){
currentUserEmail = email;
},
getCurrentUserEmail : function (){
return currentUserEmail;
}
};
}]);
At login, I store the user email address using the user service:
UserService.saveCurrentUserEmail($scope.username);
Now, when I go to another view, in the controller, the user email is what I expect.
console.debug("Current User email "+UserService.getCurrentUserEmail());
Which prints the user's email address
But when I refresh the page with (ctrl+f5). then the current user email is null.
Current User email null
What I am doing wrong, or what should I do to save this email address for further use?
You are getting printed user email because before printing it you called your service UserService.saveCurrentUserEmail($scope.username);
Now when you refresh your page(ctrl+f5),this service is not called, so it is printed as null because its initialize with null value.
So you need to call saveCurrentUserEmail when your page gets load.
On Page refresh you need to make a call to server to check if your is login and update the
$scope.username
and store it using
UserService.saveCurrentUserEmail($scope.username);
Or
You can use client side store in browser or use cookie to http://docs.angularjs.org/api/ngCookies.$cookieStore to store user info
Instead of using service, use $cookieStore.
http://docs.angularjs.org/api/ngCookies.$cookieStore
emailAddress for example is - "a#a.com"
//That's how i am assigning value
$cookieStore.put('emailAddress', $scope.user.emailAddress);
//thats how i am retrieving it
addr = $cookieStore.get('emailAddress');

Phpunit password comparison

I would like to test a login function that one of the developers produced. What I would like to do is have test-users be created in my setUp and then I would like to use these users to test the login function. I would like to see that it returns the correct boolean when username and password are equal to the ones stored in our database. My problem is that when I am inserting my users at the moment I am giving the passwords in plain-text hence they are being stored in the database in plain-text, however there is an issue here. The login function hashes the password as you are trying to log in as the passwords in the database are hashed when registration is done. So basically the plain-text password I just inserted will never be matched since the login function hashes the password in an attempt to find a match. So what I would need to do is hash the test-user's password as I insert it. How would I go about doing this? This is what my code looks like at the moment:
<?php
include 'functions.php';
class Test extends PHPUnit_Framework_TestCase {
protected function setUp(){
global $mysqli;
$mysqli = new mysqli('localhost', 'xxx', 'xxxxx', 'xxxxx');
$mysqli->query("INSERT INTO members (id, username, pnumber, password) VALUES ('200', 'testbrute', '920314', 'xxxxx')");
}
public function testLogin(){
global $mysqli;
$correctPass = Login('920314','xxxxxx', $mysqli);
$this->assertTrue($correctPass);
$wrongPass = Login('920314','xxxxxxxxx', $mysqli);
$this->assertFalse($wrongPass);
$NoUserExists = Login("980611-5298","--..--..--", $mysqli);
$this->assertFalse($NoUserExists);
}
protected function tearDown(){
$mysqli = new mysqli('localhost', 'xxx', 'xxxxx', 'xxxxx');
$mysqli->query("DELETE FROM members WHERE id IN (200)");
}
}
?>
This is what the login function looks like:
function login($pnumber, $password, $mysqli) {
// Using prepared Statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt FROM members WHERE pnumber = ? LIMIT 1")) {
$stmt->bind_param('s', $pnumber); // Bind "$pnumber" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password, $salt); // get variables from result.
$stmt->fetch();
$password = hash('sha512', $password.$salt); // hash the password with the unique salt.
if($stmt->num_rows == 1) { // If the user exists
// We check if the account is locked from too many login attempts
if(checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return "account locked";
} else {
if($db_password == $password) { // Check if the password in the database matches the password the user submitted.
// Password is correct!
$ip_address = $_SERVER['REMOTE_ADDR']; // Get the IP address of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
$user_id = preg_replace("/[^0-9]+/", "", $user_id); // XSS protection as we might print this value
$_SESSION['user_id'] = $user_id;
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username); // XSS protection as we might print this value
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password.$ip_address.$user_browser);
// Login successful.
return "login successful";
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts (user_id, time) VALUES ('$user_id', '$now')");
return 'pass incorrect';
}
}
} else {
// No user exists.
return 'no exist';
}
}
}
I am new to phpunit and testing in general so please be overly-descriptive.
Forget trying to test against the actual database. As a general rule, you don't want to have your tests dependent on external services if you can help it.
You can inject a mock mysqli object and specify it's behavior. Then you don't have to worry about any values being added to the database or are dependent on having the database even exist.
So in your test rather than declaring a global $mysqli do:
$mockMysqli = $this->getMockBuilder('mysqli')
->disableOriginalConstructor()
->setMethods(array('prepare'))
->getMock();
$mockMysqli->expects($this->once())
->method('prepare')
->will($this->returnValue($mockStmt) //Have to also create a mock mysqli_stmt object
Based on how your function is, you will end up with a few mock objects returning other mock objects which is a code smell that you function is doing too much. Because of this, you would be better off breaking it up into smaller pieces that can then be mocked and tested separately. I find that generally speaking if the function is hard to test, that it is not a good design and should be refactored. Most good designs end up being easy to test with one or two mock objects.

Resources