Using AngularJS Service to Check if User has Admin Permissions - angularjs

I am building an SharePoint App using AngularJS and am attempting to define a service that retrieves if the user is an Admin or not. The service itself is successfully logging/working as expected, but I am not sure how to use this in a controller. My end goal is that when a page loads that is tied to a controller, that this service checks if they are an admin or not. From that point, I can do all sorts of magic (ex. redirect, etc.). Here is my service:
// Check if user is an admin
appServices.factory('appAdminCheck', ['$resource', 'appCurrentUserProfile', 'appAdmins', function ($resource, appCurrentUserProfile, appAdmins) {
var userAdmin = [];
appCurrentUserProfile.query(function (usercheck) {
var userID = usercheck.Id;
appAdmins.query(function (admins) {
var admins = admins.value; // Data is within an object of "value", so this pushes the server side array into the $scope array
// Foreach type, push values into types array
angular.forEach(admins, function (adminvalue, adminkey) {
if (adminvalue.Admin_x0020_NameId == userID) {
userAdmin = true;
console.log("I'm an Admin" + userAdmin);
}
});
});
});
return userAdmin;
}]);
Update: Upon closer inspection, I would like to return the array of values, but it keeps stating that the array length is 0. I am sure it is because I am not "returning" properly.
Here is my updated service:
appServices.factory('appAdminCheck', ['$resource', 'appCurrentUserProfile', 'appAdmins', function ($resource, appCurrentUserProfile, appAdmins) {
var userAdmin = [];
var checkUser = function() {
appCurrentUserProfile.query(function (usercheck) {
var userID = usercheck.Id;
appAdmins.query(function (admins) {
var admins = admins.value; // Data is within an object of "value", so this pushes the server side array into the $scope array
// Foreach type, push values into types array
angular.forEach(admins, function (adminvalue, adminkey) {
if (adminvalue.Admin_x0020_NameId == userID) {
userAdmin.push({
isAdmin: 'Yes',
role: adminvalue.Role,
});
}
});
});
});
return userAdmin;
}
return {
checkUser: checkUser
};
}]);
Here is a logging call in a controller:
var test = appAdminCheck.checkUser();
console.log(test);

Seeing as there appears to be some asynchronous actions happening, you'll want to return a promise. You can do this by chaining the then promise resolution callbacks from your other services (assuming they're $resource instances or similar). For example...
appServices.factory('appAdminCheck', function (appCurrentUserProfile, appAdmins) {
return function() {
return appCurrentUserProfile.query().$promise.then(function(usercheck) {
return appAdmins.query().$promise.then(function(admins) {
// this needs to change if admins.value is not an array
for (var i = 0, l = admins.value.length; i < l; i++) {
if (admins.value[i].Admin_x0020_NameId === usercheck.Id) {
return true;
}
}
return false;
});
});
};
});
Then, you can use this promise resolution in your controller, eg
appAdminCheck().then(function(isAdmin) {
// isAdmin is true or false
});

Related

Angular chat client - 2 views with one controller

I build chat function in my web app and i am about to create chat functionality between logged clients. Here is my screen from application to show exactly what i want to solve
Screen of my app
As you can see i got list of online users stored in scope in sidebar. Its created as partial view in my Asp.Net with .cshtml and i render content in "white box" using angular routing.
Problem is i use same controller twice and it creates new scope for each html so i got data in my sidebar, but in my content view i dont have any data. I am thinking about passing my data to rootscope, but i dont know if its good idea.
So my question is. Is there anything how i can clone my data from one controller to another or how i can solve this without changing functionality and if i can keep my views controlled with one controller.
Here is my PrivateChatController.js
(function () {
'use strict';
app.controller('PrivateChatController', ['$rootScope', '$scope', 'SignalRService', '$location', 'PrivateChatService', PrivateChatController]);
function PrivateChatController($rootScope, $scope, SignalRService, $location, PrivateChatService) {
//angular stuff
$scope.online_users = [];
$scope.isChatHidden = false;
$scope.openPrivateChatWindow = function (index) {
// $scope.isChatHidden = true;
angular.forEach($scope.online_users, function (value, key) {
if (index == key) {
$rootScope.currentPrivateChatUser = ({
UserName: value.UserName,
ConnectionId: value.connectionId,
});
$location.path("/details/" + value.UserName);
}
});
};
$scope.closePrivateChatWindow = function (index) {
$scope.isChatHidden = false
};
//signalR stuff
var chatHub = $.connection.chatHub;
$.connection.hub.logging = true;
chatHub.client.foo = function () { };
registerClientMethods(chatHub);
$.connection.hub.start()
.done(function(){ console.log('Now connected, connection ID=' + $.connection.hub.id); })
.fail(function () { console.log('Could not Connect!'); });
function registerClientMethods(chatHub) {
//user object
chatHub.client.newOnlineUser = function (user) {
var newUser = ({
connectionId: user.ConnectionId,
UserName: user.UserName
});
$scope.online_users.push(newUser);
$scope.$apply();
};
//compare scope online users with server list of online users
chatHub.client.getOnlineUsers = function (onlineUsers) {
//loop through scope
angular.forEach($scope.online_users, function (scopeValue, scopeKey) {
//loop through received list of online users from server
angular.forEach(onlineUsers, function (serverListValue, serverListKey) {
if (!(serverListValue.ConnectionId == scopeValue.connectionId)) {
var newUser = ({
connectionId: serverListValue.ConnectionId,
UserName: serverListValue.UserName
});
$scope.online_users.push(newUser);
$scope.$apply();
}
})
})
};
chatHub.client.onUserDisconnected = function (id, user) {
var index = 0;
//find out index of user
angular.forEach($scope.online_users, function (value, key) {
if (value.connectionId == id) {
index = key;
}
})
$scope.online_users.splice(index, 1);
$scope.$apply();
};
}};})();
Consider using services as a layer for data sharing. It should also contain chat related logic, in my opinion controllers should be as thin as possible.
Move chatHub.client.getOnlineUsers function to the service and create getter for users.
Further read

How to return widgetDefinitions with data service in malhar-angular-dashboard?

I have installed the malhar-angular-dashboard module. I do not want to hard code my widgetDefinitions, so I created a service witch will return the array with the widget objects. I am using a rest service to return data such as the widget names, titles, etc. The problem is I get this error and do not know how to resolve :
TypeError: widgetDefs.map is not a function
SERVICE DATA
.factory('widgetRestService',['$http','UrlService','$log','$q',
function($http,UrlService,$log,$q){
var serviceInstance = {};
serviceInstance.getInfo = function(){
var request = $http({method: 'GET', url: '/rest/widgets/getListInfoDashboards'})
.then(function(success){
serviceInstance.widgets = success.data;
$log.debug('serviceInstance.widgets SUCCESS',serviceInstance.widgets);
},function(error){
$log.debug('Error ', error);
$log.debug('serviceInstance.widgets ERROR',serviceInstance.widgets);
});
return request;
};
serviceInstance.getAllWidgets = function () {
if (serviceInstance.widgets) {
return serviceInstance.widgets;
} else {
return [];
}
};
return serviceInstance;
}]);
widgetDefinitions service
.factory('widgetDefinitions',['widgetRestService','$log','$q','$http',function(widgetRestService,$log,$q,$http) {
var widgetDefinitions = [];
return widgetRestService.getInfo().then(function (data) {
var widgets = widgetRestService.getAllWidgets();
$log.debug('widgetsDefs ', widgets);
for (var i = 0; i < widgets.length; i++) {
widgetDefinitions.push(widgets[i]);
}
$log.debug('widgetDefinitions ', widgetDefinitions);
return widgetDefinitions;
});
});
Console
TypeError: widgetDefs.map is not a function
widgetDefs: [Object,Object,Object]
widgetDefinitions: [Object,Object,Object]
Note
If I hard-code my widgetDefinitions-service returned array like this it works, if I returned with my rest service doesn`t work(widgetDefs.map is not a function):
[
{
name:'widgetList',
title:'title1'
},
{
name:'widgetPie',
title:'title2'
},
{
name:'widgetTable',
title:'title3'
}
]
Original issue in github has been commented on and closed.
Here's the comment from github:
#pitong Make sure the dashboard options contains a property named widgetDefinitions and it's an array, even if it's empty. Also make sure the the browser version you're using supports the map function for arrays. This map function for array became the ECMA-262 standard in the 5th edition so your browser version might not have it supported.

Array populated witin 'service' but empty when referenced by any 'controller'

I have an AngularJS service which should get a JSON object and create three arrays based on differing criteria (all, searchable and has coordinates). These arrays need to be referenced by more than one controller, hence the use of a service.
When I test any of the three arrays the array within the service itself (as below), all three are correctly populated.
However, all three of my arrays are empty when referenced by any controller.
What am I missing here?
app.service('$stationsList', ['$http', function($http){
var stationsList = [],
searchableStations = [],
locatableStations = [];
$http.get('stations.json').then(function(res){ // Grab the JSON list of all stations
[].map.call(res.data || [], function(elm){ // Map all stations...
stationsList = res.data; // Set all stations to 'stationsList'
if(elm.link.indexOf(".xml") > -1) // Check to see if the station is searchable (has a full link)
searchableStations.push(elm); // It does - add the station to 'searchableStations'
if( // Check to see if the station can be checked as the closest station (has coordinates)
isFinite(parseFloat(elm.latitude)) &&
isFinite(parseFloat(elm.longitude))
)
locatableStations.push(elm); // It does - add the station to 'locatableStations'
});
console.log(stationsList);
console.log(searchableStations);
console.log(locatableStations);
});
return{
getList: function(){
return stationsList;
},
setList: function(value){
stationsList = value;
},
getSearchable: function(){
return searchableStations;
},
setSearchable: function(value){
searchableStations = value;
},
getLocatable: function(){
return locatableStations;
},
setLocatable: function(value){
locatableStations = value;
}
};
}]);
Example of how I'm referencing service -
app.controller('searchCtrl', ['$scope', '$http', '$localStorage', '$stationsList', function($scope, $http, $localStorage, $stationsList){
$scope.stationsList = $stationsList.getSearchable(); // Grab a list of all stations
$scope.selectStation = click_selectStation; // Handle clicks of a station within the 'searchCtrl' controller
$scope.localStorage = $localStorage.$default({ // Grab the local storage (so that it can be updated when the user selects a station)
recentStations: [] // Set a default value of '[]' for recentStations in case it doesn't exist
});
}]);
Edit
Derived from the answer posted by PankajParkar below, here is the service that will return the three arrays that I require.
However, my issue here is that every call to a method within the service triggers another async call to $http.get my JSON data. This is exactly what I was trying to avoid by using a service.
My desired outcome is one JSON call per page load, with my 3 arrays being created from that JSON call and then accessible to my controllers as and when required. If a service is not the correct answer, I am certainly open to other suggestions.
app.service('$stationsList', ['$http', function($http){
var searchableStations = [],
locatableStations = [];
/**
* Grab all stations (for the master list)
*/
var getAllStations = function(){
return $http.get('stations.json').then(function(res){ // Grab the JSON list of all stations
return res.data;
});
};
/**
* Grab only searchable stations (those with full links)
*/
var getSearchableStations = function(){
return $http.get('stations.json').then(function(res){ // Grab the JSON list of all stations
[].map.call(res.data || [], function(elm){ // Map all stations...
if (elm.link.indexOf(".xml") > -1) // Check to see if the station is searchable
searchableStations.push(elm); // It is - add the station to 'searchableStations'
});
return searchableStations;
});
};
/**
* Grab only locatable stations (those with coordinates)
*/
var getLocatableStations = function(){
return $http.get('stations.json').then(function(res){ // Grab the JSON list of all stations
[].map.call(res.data || [], function(elm){ // Map all stations...
if(
isFinite(parseFloat(elm.latitude)) &&
isFinite(parseFloat(elm.longitude))
) // Check to see if the station is locatable
locatableStations.push(elm); // It is - add the station to 'locatableStations'
});
return locatableStations;
});
};
return{
getAll: getAllStations,
getSearchable: getSearchableStations,
getLocatable: getLocatableStations
};
}]);
Your current code is failing because you made asynchronous ajax call & accepting value as soon as it made. That's why you are getting your values as undefined.
You need to wait till your ajax gets completed, that could be implemented using returning ajax promise to controller from service. So i'd suggest you to create a new method which will do $http ajax and will return promise from that function & that will execute .then function of controller that called the getSearchableStations. Below snippet will give you an Idea what I wanted to say.
Service
app.service('$stationsList', ['$http', function($http) {
var stationsList = [],
searchableStations = [],
locatableStations = [];
var getSearchableStations = function() {
return $http.get('stations.json').then(function(res) { // Grab the JSON list of all stations
[].map.call(res.data || [], function(elm) { // Map all stations...
stationsList = res.data; // Set all stations to 'stationsList'
if (elm.link.indexOf(".xml") > -1) // Check to see if the station is searchable (has a full link)
searchableStations.push(elm); // It does - add the station to 'searchableStations'
if ( // Check to see if the station can be checked as the closest station (has coordinates)
isFinite(parseFloat(elm.latitude)) &&
isFinite(parseFloat(elm.longitude))
)
locatableStations.push(elm); // It does - add the station to 'locatableStations'
});
console.log(stationsList);
console.log(searchableStations);
console.log(locatableStations);
return locatableStations; //return data from here.
});
};
return {
getList: function() {
return stationsList;
},
setList: function(value) {
stationsList = value;
},
getSearchable: function() {
return searchableStations;
},
setSearchable: function(value) {
searchableStations = value;
},
getLocatable: function() {
return locatableStations;
},
setLocatable: function(value) {
locatableStations = value;
},
//added new function
getSearchableStations: getSearchableStations
};
}]);
Inside you controller you will call service getSearchableStations method that does return promise, You will use .then function that would get called when promise get resolved. Same has been shown below with code.
Controller
app.controller('searchCtrl', ['$scope', '$http', '$localStorage', '$stationsList',
function($scope, $http, $localStorage, $stationsList){
$stationsList.getSearchableStations().then(function(data){
$scope.stationsList = data;
$scope.selectStation = click_selectStation; // Handle clicks of a station within the 'searchCtrl' controller
$scope.localStorage = $localStorage.$default({ // Grab the local storage (so that it can be updated when the user selects a station)
recentStations: [] // Set a default value of '[]' for recentStations in case it doesn't exist
});
}); // Grab a list of all stations
}]);

Firebase - Filter by a column

I'm using Firebase for my Angular.js application.
I'm looking for the equivalent of SQL's WHERE statement for Firebase.
I have an array of TV series stored in Firebase, and I want to fetch only these that has the name that the user entered (in the example searchQuery).
Does Firebase support it? Does it have something like this?
var seriesRef = new Firebase('http://{app}.firebaseio.com/series');
var seriesObject = $firebaseObject(seriesRef.query({ name: searchQuery }));
I have some suggestions that may help here:
Check out the Firebase Query documentation. Specifically,
.orderByChild()
.equalTo()
You can use queries in conjunction with .$ref() to get the desired record.
Example
Check out this working CodePen demo.
I replicated your data in one of my public Firebase instances.
The query that you're looking for is seriesCollectionRef.orderByChild('name').equalTo(seriesName)
If you enter 'Avatar: The Last Airbender' in the input and click "Find", you'll get the matching series object.
In my example, I extended the $firebaseArray service to include a method for finding a specific series by name.
See the documentation for extending AngularFire services.
You can accomplish the same thing without extending the service, see last code snippet.
Factories
app.factory('SeriesFactory', function(SeriesArrayFactory, fbUrl) {
return function() {
const ref = new Firebase(`${fbUrl}/series`);
return new SeriesArrayFactory(ref);
}
});
app.factory('SeriesArrayFactory', function($firebaseArray, $q) {
return $firebaseArray.$extend({
findSeries: function(seriesName) {
const deferred = $q.defer();
// query by 'name'
this.$ref()
.orderByChild('name')
.equalTo(seriesName)
.once('value', function(dataSnapshot) {
if (dataSnapshot.exists()) {
const value = dataSnapshot.val();
deferred.resolve(value);
} else {
deferred.reject('Not found');
}
})
return deferred.promise;
}
});
});
Controller
app.controller('HomeController',function($scope, SeriesFactory, fbUrl) {
$scope.seriesName = '';
$scope.findSeries = function() {
const seriesCollection = new SeriesFactory();
seriesCollection
.findSeries($scope.seriesName)
.then(function(data) {
$scope.series = data;
})
.catch(function(error) {
console.error(error);
});
};
});
Without Extended Service
Here is what a controller function would look like if you weren't using the factories:
$scope.findSeriesWithoutFactory = function() {
const seriesRef = new Firebase(`${fbUrl}/series`);
const seriesCollection = $firebaseArray(seriesRef);
seriesCollection.$ref()
.orderByChild('name')
.equalTo($scope.seriesName)
.once('value', function(dataSnapshot) {
if (dataSnapshot.exists()){
$scope.series = dataSnapshot.val();
} else {
console.error('Not found.');
}
});
};
Rules
Note: It's important to note that you should add ".indexOn": "name" to your Firebase rules so that the query runs efficiently. See the Indexing Your Data portion of the Firebase Security & Rules Guide for more information. Below is an example:
"yourfirebaseapp": {
".read": "...",
".write": "...",
"series": {
".indexOn": "name"
}
}

Assign value to the Factory variable through http

I have two controllers and one Factory. I am using angular-devise module for authentication.
UserFactory.js
myApp.factory('Userfactory', function(Auth,$location){
var Userfactory = {}
Userfactory.user = []
Userfactory.active = false
Userfactory.isLogged = function(){
if(!Userfactory.active[0]){
return Auth.currentUser().then(function(user) {
Userfactory.user.push(user)
Userfactory.active = angular.copy(true)
}, function(error) {
});
}
}
return Userfactory;
})
UserController.js
myApp.controller("userController",function($scope,Userfactory){
Userfactory.isLogged().then(function(){
$scope.active = Userfactory.active;
})
}
NavController.js
myApp.controller("navController", function navController(Userfactory){
this.user = Userfactory.user;
this.active = Userfactory.active;
})
UserFactory.active in nav controller is not updating when isLogged updates the value , since the value is getting resetted (which breaks binding) , where as in user controller the value is assigned through promise , so its getting the latest value. My doubt is how to manage to get it working in both places, meaning how to assign value without breaking the binding.
One workaround is declaring Userfactory.active as an array and pushing the value to it as true or false, but looking for better way of doing it, any help will be useful.
I would recommend you to use a model Object to wrap all the variables/properties you need to be bindable.
myApp.factory('Userfactory', function(Auth,$location){
var Userfactory = {}
Userfactory.model = {
user: undefined,
active: false
};
Userfactory.isLogged = function(){
if(!Userfactory.active[0]){
return Auth.currentUser().then(function(user) {
Userfactory.model.user = user;
Userfactory.model.active = true;
}, function(error) {
});
}
}
return Userfactory;
})
And then on your controllers:
myApp.controller("userController",function($scope,Userfactory){
Userfactory.isLogged().then(function(){
$scope.userModel = Userfactory.model;
// and on the UI use: userModel.active
})
}
myApp.controller("navController", function navController(Userfactory){
this.userModel = Userfactory.model;
// then access it like: this.userModel.active
})

Resources