Checking authentication in Laravel via Angular - javascript

In my Angular app I created a service:
.factory('Auth', function($http) {
return {
is_authenticated: function() {
return $http.get('/api/users/is_authenticated');
}
}
});
My method in my API backed by Laravel:
public function is_authenticated()
{
if(Auth::check())
{
return Response::json(array('authenticated' => true));
}
return Response::json(array('authenticated' => false));
}
And then in my controller:
Auth.is_authenticated()
.success(function(data) {
$scope.is_authenticated = data.authenticated;
if(data.authenticated)
console.log('yes');
});
When I go to /api/users/is_authenticated I see nothing on the page, however, when I echo Auth::check() there is a 1 on the page.
In my view I have a list with ng-show="is_authenticated" but it's not working.
What am I doing wrong here? I'm failing to see the problem. Why is 'yes' not being logged to the console?
And yes, I have injected the Auth service into my controller.

Related

How to execute Run function before any controller

I'm using AngularJS to make my first application, I want to the run function to be executed before any controller.
My run function looks like :
.run(function ($rootScope,authentification)
{
teamsFactory.sendAuthent().then(function(response)
{
$rootScope.authentdata=response.data;
});
})
My service where I make the authentication :
teams.sendAuthent= function(DeviceID) {
return $http({method:"POST",url:http://myserver.com/authentification",headers: {'X-SocialAPI-Service-Name': 'auth'}})
.then(function(aResponse)
{
var deferred=$q.defer();
deferred.resolve({data:aResponse.data});
return deferred.promise;
});
}
And this is my controller where I use the rootScope data :
.controller('home', function($rootScope,$scope, $http,)
{
alert($rootScope.authentdata.token);
})
But this is not working it says that autehndata is undefined, so the controller is executed before the run function how to resolve that ?
you can try this,
$rootScope.$watch('authentdata', function(n, o) {
if(angular.isDefined(n) {
alert($rootScope.authentdata.token);
// or alert(n.token);
}
}

Angular.JS API using a factory

I've written a backend service which is used by a Angular.JS frontend using a factory, like so:
angular.module('app.social', ['ngResource'])
.factory('Social', function($http) {
return {
me: function() {
return $http.get('http://localhost:3000/me');
},
likeVideo: function(link) {
return $http.post('http://localhost:3000/like/video', { link : link });
},
post: function(link) {
return $http.post('http://localhost:3000/post', { link : link });
},
postVideo: function(link) {
return $http.post('http://localhost:3000/post/video', { link : link });
},
friends: function() {
return $http.get('http://localhost:3000/friends');
},
taggableFriends: function() {
return $http.get('http://localhost:3000/friends/taggable');
},
videos: function() {
return $http.get('http://localhost:3000/videos');
}
};
});
The Social.me endpoint receives profile information from the REST backend. This function is used in various Angular controllers, however (profile page, item detail page, header account button etc.). This means that for every view, profile information is requested from http://localhost:3000/me. Is this good practice, or is it a better idea to cache the information within the factory?
EDIT: Updated code (based on answer from #Rebornix):
angular.module('app.social', ['ngResource'])
.service('SocialService', function() {
var serviceData = {
me: null
};
return serviceData;
})
.factory('Social', function($http, SocialService) {
return {
me: function() {
if (SocialService.me === null) {
return $http.get('http://localhost:3000/me').then(function(response) {
SocialService.me = response.data;
return SocialService.me;
});
} else {
return SocialService.me;
}
}
}
};
});
In the controller, I use:
angular.module('app.profile', [])
.controller('ProfileCtrl', ['$window', '$scope', 'Social', function($window, $scope, Social) {
$scope.me = Social.me();
}])
And the view:
<div ng-controller="ProfileCtrl">
<h1 class="profile-name">{{ me.name }}</h1>
</div>
But the view is not updated as the Facebook.me value get initialized on the first request. I guess I have to manually trigger $scope.$apply() somehow?
You can create a service as storage across controllers like
angular.module('app.social', ['ngResource'])
.service("SocialService", function() {
var info = {
me: null,
friends: []
};
return info;
})
.factory('Social', function($http, SocialService) {
return {
me: function() {
$http.get('http://localhost:3000/me').then(function(response){
SocialService.me = response.data;
});
},
Then in all your controllers, reference infoService instead of calling API again. What you need to is fetching latest data and refresh infoService, all controllers scope will be notified with this change.
In your controller
angular.module('app.profile', [])
.controller('ProfileCtrl', ['$window', '$scope', 'SocialService', 'Social', function($window, $scope, SocialService, Social) {
$scope.SocialService = SocialService;
// Kick off social factory to update user info, you can move it into
// any other functions like `ng-click`.
Social.me();
}])
Then in your view
{{SocialService.me}}
(function (app) {
'use strict';
app.factory('myService', MyService);
MyService.$inject = ['$q', 'serviceResource'];
function MyService($q, serviceResource) {
var jobs = [];
var service = {
getJobs: getJobs
};
return service;
//////////////////////////////////////
function getJobs(refresh) {
if (refresh) {
return serviceResource.autosysJobs().$promise.then(function (data) {
jobs = data;
return jobs;
}, function (err) {
throw err;
});
}
else {
var deferrer = $q.defer();
deferrer.resolve(jobs);
return deferrer.promise;
}
}
}
}(angular.module('app')));
you can pass a bool argument to tell weather to get local copy or fresh copy
It all depends upon the frequency of data change in back end data change and degree of tolerance of data inconsistency in your application. if the source data is changing too frequently and you can't afford inconsistent data then you have no choice other than to get fresh copy every time, but if that's not the case then you can cash data locally

Automatic "proxy" creation for ASP.NET MVC Controller for AngularJs service

When I'm using a ASP.NET MVC controller with AngularJS, then my controller mostly contains JSON result functions. And then when I create my AngularJs service its allways the same code to write the service for Get or POST calls to my ASP.NET controller functions.
MVC Home Controller Functions:
[AngularCreateProxy]
public JsonResult InitUnitTestPersonEntry()
{
return Json(new PersonEntry(), JsonRequestBehavior.AllowGet);
}
[AngularCreateProxy]
public JsonResult InitUnitTestSearchModel()
{
PersonSearchModel searchModel = new PersonSearchModel() {Name = String.Empty};
return Json(searchModel, JsonRequestBehavior.AllowGet);
}
[AngularCreateProxy]
public JsonResult AddUnitTestPerson(PersonEntry entry)
{
PersonEntries.Add(entry);
return Json(entry, JsonRequestBehavior.AllowGet);
}
My automaticly created AngularJS Home Service:
function homePSrv($http, $log) {
this.log = $log, this.http = $http;
}
homePSrv.prototype.InitUnitTestPersonEntry = function () {
return this.http.get('/Home/InitUnitTestPersonEntry').then(function (result) {
return result.data;
});
}
homePSrv.prototype.InitUnitTestSearchModel = function () {
return this.http.get('/Home/InitUnitTestSearchModel').then(function (result) {
return result.data;
});
}
homePSrv.prototype.AddUnitTestPerson = function (entry) {
return this.http.post('/Home/AddUnitTestPerson',entry).then(function (result) {
return result.data;
});
}
angular.module("app.homePSrv", [])
.service("homePSrv", ['$http', '$log', homePSrv]);
I've written my own little "proxy" (don't know if this is the right naming) which automaticly creates a angularJS service for my controller JSON result functions as new javaScript file - that works fine so far.
my question are:
Whats the right way to handle this task is there some GitHub Projekt out there which supports this allready or how are you solving this "problem"?
Whats the right naming because I can't find anything about this solution and I don't know if "proxy" is right?
I've created my own GitHub Repo Using T4 Template to create the Proxy Functions
https://github.com/squadwuschel/MvcControllerToProxyGenerator

How to use AngularJS to store a 'Token' for the lifetime of the app?

I'm using AngularJS to login a user (using Restangular). The login controller gets returned a 'Token' which I then need to use on every request thereafter.
My question is, what is the best way to store this Token using AngularJS? It needs to exist for the lifetime of the app.
I was looking at services but I have to keep injecting it into the controllers on to keep it alive.
lifetime is not promise as far as you are using web apps, but if you want you can use localstorage,
here is an example service how to use localstorage in angular, you can add it to service.js file:
var storeService = innovidServices.factory('storeService', function() {
var service =
{
setClientData:function(client_details)
{
window.localStorage.setItem( "client_data", JSON.stringify(client_details) );
client_data = client_details;
},
getClientData:function()
{
if (client_data == null)
{
client_data = JSON.parse(window.localStorage.getItem("client_data"));
}
return client_data;
}
}
var client_data = null;
return service;
});
I think the best way is store this 'Token' in the $rootScope.
myapp.controller('loginCtrl', function($scope, $rootScope) {
...
$rootScope.token = Token;
...
});
Then use http interceptor to inject this as for example GET parameter to every query
myapp.factory('httpTokenInterceptor', function ($rootScope) {
return {
request: function (config) {
var token = $rootScope.token;
if (token) {
config.url = URI(config.url).addSearch({'token':token}).toString();
}
return config;
}
};
});
myapp.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpTokenInterceptor');
});

firebase simple login tutorial missing user

Tutorial: http://www.thinkster.io/angularjs/wBhtRLWHIR/6-authenticating-users-with-a-service
I'm following this tutorial and it seems like I'm losing my user as soon as they register.
Here is my auth.js factory:
'use strict';
app.factory('Auth', function($firebaseSimpleLogin, FIREBASE_URL, $rootScope){
var ref = new Firebase(FIREBASE_URL);
var auth = $firebaseSimpleLogin(ref);
var Auth = {
register : function(user) {
return auth.$createUser(user.email, user.password);
},
signedIn : function() {
// PROBLEM: authUser is always null
console.log(auth.user);
return auth.user !== null;
},
logout : function () {
auth.$logout();
}
};
$rootScope.signedIn = function () {
return Auth.signedIn();
};
return Auth;
});
Here is my auth.js controller:
'use strict';
app.controller('AuthCtrl', function($scope, $location, Auth){
if (Auth.signedIn()) {
$location.path('/');
}
$scope.register = function () {
Auth.register($scope.user).then(function (authUser) {
console.log(authUser);
$location.path('/');
});
};
});
The console.log under signedIn in the factory is always null. Any idea where the disconnect is? The registration itself is working fine, and authUser is populated in the console.log in the controller when registering.
The latest documentation for Angularfire says that the $createUser method of $firebaseSimpleLogin returns a promise but it doesn't mention any parameters being passed to the then callback.
You can use the $getCurrentUser method to get the current user after the user registers.
The tutorial needs to be updated and you should always be checking the documentation for whatever libraries you're using yourself.
Your code for signedIn should look like this:
Auth.signedIn = function() {
auth.$getCurrentUser().then(function(currentUser) {
console.log(currentUser);
}, function() {
console.log('error');
});
};
I found a very similar question that is further along in the tutorial :can't show logout button after $createUser
In the answer I learned that angularfire used to automatically log the user in after it was created. Apparently now it no longer does that which is why the auth.user in signedIn was null.
I am now doing the same tutorial. This code (in auth controller) worked for me:
$scope.register = function () {
Auth.register($scope.user).then(function (authUser) {
console.log(authUser);
Auth.login($scope.user);
$location.path('/');
});
};
I'm a total n00b, but what (I think) this is doing is authenticating the user, then running a function that logs the user in right after. Logout button is now functioning as expected.

Categories