IP Whitelisting in Angular JS - angularjs

I am using AngularJS v1.2.32.
I want to source IP based white-listing to legitimate systems. I have searched but found examples using third party json application.
Need to get client IP in JavaScript , angularjs and restrict access to other users.
Your help is highly appreciated.

Firefox and Chrome have implemented WebRTC that allow requests to STUN servers be made that will return the local and public IP addresses for the user. These request results are available to javascript, so you can now obtain a users local and public IP addresses in javascript. This demo is an example implementation of that.
for more
https://github.com/diafygi/webrtc-ips
How to get client's IP address using JavaScript only?
//get the IP addresses associated with an account
function getIPs(callback){
var ip_dups = {};
//compatibility for firefox and chrome
var RTCPeerConnection = window.RTCPeerConnection
|| window.mozRTCPeerConnection
|| window.webkitRTCPeerConnection;
var useWebKit = !!window.webkitRTCPeerConnection;
//bypass naive webrtc blocking using an iframe
if(!RTCPeerConnection){
//NOTE: you need to have an iframe in the page right above the script tag
//
//<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
//<script>...getIPs called in here...
//
var win = iframe.contentWindow;
RTCPeerConnection = win.RTCPeerConnection
|| win.mozRTCPeerConnection
|| win.webkitRTCPeerConnection;
useWebKit = !!win.webkitRTCPeerConnection;
}
//minimal requirements for data connection
var mediaConstraints = {
optional: [{RtpDataChannels: true}]
};
var servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};
//construct a new RTCPeerConnection
var pc = new RTCPeerConnection(servers, mediaConstraints);
function handleCandidate(candidate){
//match just the IP address
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
var ip_addr = ip_regex.exec(candidate)[1];
//remove duplicates
if(ip_dups[ip_addr] === undefined)
callback(ip_addr);
ip_dups[ip_addr] = true;
}
//listen for candidate events
pc.onicecandidate = function(ice){
//skip non-candidate events
if(ice.candidate)
handleCandidate(ice.candidate.candidate);
};
//create a bogus data channel
pc.createDataChannel("");
//create an offer sdp
pc.createOffer(function(result){
//trigger the stun server request
pc.setLocalDescription(result, function(){}, function(){});
}, function(){});
//wait for a while to let everything done
setTimeout(function(){
//read candidate info from local description
var lines = pc.localDescription.sdp.split('\n');
lines.forEach(function(line){
if(line.indexOf('a=candidate:') === 0)
handleCandidate(line);
});
}, 1000);
}
//Test: Print the IP addresses into the console
getIPs(function(ip){console.log(ip);});

Related

Cannot get local IP address in ReactJS

I'm create a website using ReactJS and I want get my local IP address. I've tried few ways to do that but I was confused with result.
First, I use module on npm is local-ip-url, then use localIpUrl() to get my ip address and display with console.log(). If i use a terminal to run this .js file (eg: node index.js), it print exact result i want (192.168.x.x). But if i use browser to see console log, it shows a different result 127.0.0.0.
I've tried another ways, create my own function:
const os = require('os');
function getAvailableIp() {
let ifaces = os.networkInterfaces();
let result = {};
for (let ifname in ifaces) {
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal !== false) return;
result[ifname] = iface.address;
});
};
return result;
}
function getIp() {
let ips = getAvailableIp();
return ips.WiFi || 'localhost';
}
Same like above, when I ran code in terminal, it showed perfect result. But on browser, function os.networkInterfaces() return a empty object {}(It has a property is proto, i think it doesn't cause problem). So, it always return localhost.
Anyone can explain?

Loading a new window from local files and accessing it's contents

I am setting up a local webpage which shows videos in a HTML5 video tag. I just want to be able to do database search from a PHP request and show the results from which I can click on and show the video I want. The problem I have is that hte videos load WAY faster when loading from a "file:///" link than from the "http://" link. Server works flawlessly when in "HTTP" mode but nothing works in "file:///" mode which is normal as PHP codes only execute on the server side when requested to the server.
I have spent my full day trying soo much stuff. I changed my server to accept CORS, I tried window.open, storing the reference in a variable, local or global but I lose this as soon as I get out of my javascript function. I tried window.open in a function which is called from another function but no matter what I do, the window reference gets lost as soon as I leave the functions, or once the functions have finished. Since my browser is used as my main browser, I do not want to disable the security arround CORS but since my webpage's link comes from "file:///" requesting to "HTTP" on the same computer, CORS blocks me and wants an HTTP request which I can't give.
I have done all the searching for retrieving information from another webpage but I am always stuck with the "same domain" problem. I tried AJAX HTTPRequest, I just have no more solution for this simple problem which finished way more complicated than expected. The initial problem was just my videos not loading fast enough in HTTP mode (The speed difference is extreme, for 10 min videos, I can wait 5-10 seconds to skip through it while as in FILE:/// urls, It's almost instant, no waiting. longer videos of 1h, I can wait up to 20 and 30 seconds while as in file:/// mode, almost instant.) and I had to learn all that Allow cross domains stuff which ended up with no success either. I figure that maybe a few other heads may have better ideas than mine now.
#In my httpd.conf file from Apache
DocumentRoot "e:/mainwebfolder"
Alias "/lp" "d:/whatever"
//////////////////////////////////////
// index.php file that does not contain PHP contents
// window.location.href: file://d:/whatever/index.php
//////////////////////////////////////
<head>
<script src="html/servcom.js" type="text/javascript"></script>
</head>
<video id="vplayer" width="1280" height="720" controls></video>
<div id="search-form">
<input id="srch" name="srch" type="text">
<button class="bbut" onclick="ServInfo('search-results','http://127.0.0.1/lp/html/db.php','mode=s','search-form');">Search</button>
</div>
<div id='search-results'></div>
<script>
var dplay = document.getElementById("vplayer");
ShowVideo('MyVideo.mp4');
function ShowVideo (vidUrl) {
dplay = document.getElementById("vplayer");
dplay.src = vidUrl;
dplay.load;
}
</script>
//////////////////////////////////////
// Now this is in my javascript file servcom.js
//////////////////////////////////////
var win_ref = -1;
function ServInfo(pop_field_id,web_page,params="",form_id="",exec_string = "") {
var sparams = params;
var swpage = web_page;
var eobj = document.getElementById(pop_field_id);
var moreparams = "";
// If we entered extra parameters including form fields,
// add the the "&" before the form field list
if (sparams != "") {moreparams = "&";}
// Get form field values if a form id is specified
if (form_id != "") {
var efrm = document.getElementById(form_id);
sparams += moreparams+GetDivFields(form_id);
}
// Add the question mark if there is any parameters to pass
if (sparams != "") {
sparams = "?"+sparams;
// Add recieving objects reference
sparams += "&srco="+pop_field_id;
}
// If HTML element to populate does not exist, exit
if (typeof(eobj) == "!undefined" || eobj == null) {return;}
win_ref = window.open(swpage+sparams,"_blank");
//////////////////////////////////////
// right here win_ref will never be available once the code from this function has been finished executing although the variable is global. The problem starts here.
//////////////////////////////////////
// Execute a string if a user defined one
if (exec_string != "") {eval(exec_string);}
}
// Build a parameter string with div fields of type text, hidden or password
function GetDivFields(div_id) {
var ediv = document.getElementById(div_id);
var elem = ediv.children;
var retval = "";
var ssep = "";
for (var i = 0; i < elem.length; i++) {
if (elem[i].type == "text" || elem[i].type == "hidden" || elem[i].type == "password") {
retval += ssep+elem[i].name+"="+pURL(elem[i].value);
ssep = "&";
}
if (elem[i].type == "checkbox") {
if (elem[i].checked == true) {
retval += ssep+elem[i].name+"="+elem[i].value;
ssep = "&";
}
}
}
return retval;
}
//////////////////////////////////////
// And this is a brief overview of my db.php page
//////////////////////////////////////
<?php // Search Database code ?>
<div id="output"></div>
<script>
document.getElementById('output').innerHTML = "<?php echo $search_results; ?>";
// I actually want to retrieve the info from this div element once it has been populated from the initial page that called window.open for this page. BUT again. window.opener becomes empty once my initial window.open script finishes.
</script>
Access my newly loaded page's "output" div innerHTML OR loading videos through local HTTP as fast as "FILE:///".
Well, I fanally found a solution. Since this is for local and presentation use only, I could bypass some securities. Basically, doing what we would normally NOT do in a website but all this WITHOUT modifying your webserver config or touching any .htaccess file. Basically, no security restrictions, just a plain old hack that poses no security breaches for your browser or your server.
To be noted:
2 different websites exist (so 2 different folders at very different locations), 1 for developpement and serious releases, one for internal and/or presentation purposes.
Every file is local abd inside the presentation folder.
No PHP code can be ran from a "file:///" link.
Access to the mysql database is done through PHP and server is on Apach24
Reading video locally from a "file:///" link are WAY faster than from an "http://" link
Searching needs to be done in MySQL database frm a "http://" link and results need to be displayed on a webpage opened from a "file:///" link.
No changes must be made in the Browser's configuration so disabling CORS is not a solution.
Bypassing cors with methods proposed by many site won't work because of security reasons or because CORS bypass does not accept "file:///" links
PHP can write files on the server which is where I decided to bypass CORS. Since XML requests through AJAX can be done on the same origin domain an thus, purely in javascript. If a file exists which contains no PHP code AND resides on the same domaine i/e "file:///", the contents can the be read wothout any problems.
So I simply do the following in my db.php file:
$s_mode = "";
$s_text = "";
$sres = "";
if (isset($_REQUEST["srch"])) {$s_text=$_REQUEST["srch"];}
if (isset($_REQUEST["mode"])) {$s_mode=$_REQUEST["mode"];}
if ($s_mode == "s") {
$sres = SearchDB($s_text);
WriteFile("D:/whatever/my_path/dbres.html",$sres);
}
// Writes the contents of the search in a specified file
function WriteFile($faddress,$fcontents) {
$ifile = fopen($faddress,"w");
fwrite($ifile,$fcontents);
fclose($ifile);
}
Now using a normal AJAX request, I do 2 things. I opted to use an iframe with a "display:none" style to not bother seeing another tab openup.
Do the actual request which opens the "cross-doamin" link in the iframe WHICH executes my db.php code. I basically open "http://127.0.0.1/whatever/db.php?param1=data&parma2=data" inside my iframe.
Once my search is done and I have the results, my db.php will save an html file with the results as it's contents in my "file:///" direct location's path so: "D:/whatever/my_path/dbres.html".
I added a new function in my servcom.js. So my new file's contents looks like this:
// Show page info in another page element or window with parameters (for local use only)
function ServInfoLocal(dest_frame,web_page,params="",form_id="") {
var sparams = params;
var swpage = web_page;
var iweb = document.getElementById(dest_frame);
var moreparams = "";
// If we entered extra parameters including form fields,
// add the the "&" before the form field list
if (sparams != "") {moreparams = "&";}
// Get form field values if a form id is specified
if (form_id != "") {
var efrm = document.getElementById(form_id);
sparams += moreparams+GetDivFields(form_id);
}
// If destination frame does not exist, exit
if (typeof(iweb) == "!undefined" || iweb == null) {return;}
// Add the question mark if there is any parameters to pass
if (sparams != "") {sparams = "?"+sparams;}
// Show results in iframe
iweb.src = swpage+sparams;
}
// AJAX simple HTTP GET request
function ServInfo(pop_field_id,web_page,params="",form_id="",append_data_to_output = "",exec_string = "",dont_show_results = "") {
var sparams = params;
var swpage = web_page;
var eobj = document.getElementById(pop_field_id);
var moreparams = "";
// If we entered extra parameters including form fields,
// add the the "&" before the form field list
if (sparams != "") {moreparams = "&";}
// Get form field values if a form id is specified
if (form_id != "") {
var efrm = document.getElementById(form_id);
sparams += moreparams+GetDivFields(form_id);
}
// If HTML element to populate does not exist, exit
if (typeof(eobj) == "!undefined" || eobj == null) {return;}
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// IE6-
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Do not show any results if requested
if (dont_show_results == "") {
if (append_data_to_output == "y") {
document.getElementById(pop_field_id).innerHTML += this.responseText;
}
if (append_data_to_output == "") {
document.getElementById(pop_field_id).innerHTML = this.responseText;
}
}
// Execute a string if a user defined one
if (exec_string != "") {
eval(exec_string);
}
}
};
// Add the question mark if there is any parameters to pass
if (sparams != "") {swpage += "?";}
xmlhttp.open("GET",swpage+sparams,true);
xmlhttp.send();
}
// Build a parameter string with div fields of type text, hidden or password
function GetDivFields(div_id) {
var ediv = document.getElementById(div_id);
var elem = ediv.children;
var retval = "";
var ssep = "";
for (var i = 0; i < elem.length; i++) {
if (elem[i].type == "text" || elem[i].type == "hidden" || elem[i].type == "password") {
retval += ssep+elem[i].name+"="+pURL(elem[i].value);
ssep = "&";
}
if (elem[i].type == "checkbox") {
if (elem[i].checked == true) {
retval += ssep+elem[i].name+"="+elem[i].value;
ssep = "&";
}
}
}
return retval;
}
Now, my dbres.html file will contain just the div elements and all the information I need to show up in my "file:///" page from which the search request came from. So I simply have this inside my page:
<div id="search-form" style="color:white;font-weight:bold;">
<input id="srch" name="srch" type="text">
<button class="bbut" onclick="ServInfoLocal('iweb','http://127.0.0.1/whatever/html/db.php','mode=s','search-form');">Search</button>
<button class="bbut" onclick="ServInfo('search-results','dbres.html');">Click here</button>
</div>
<div id="search-results">Results here</div>
<iframe id="iweb" style="display:none;" src=""></iframe>
For now I have 2 buttons, one for the search and one to show the results from my newly created file. Now, I can show my local videos which will load in my video container with "file:///" source directly without passing through http. I'll make my results display automatic which I will be able to do myself from here on.
So, if someone on planet earth wants to be able to do cross-domain searches in a MySQL database from a local file ran directly from the Windows explorer, there's not too many solutions, actually, I found none so here is at least one for who would ever need this solution.
For the curious ones out there, my next step will be to loop my folder until my dbres file is present using another js function. Once my file has been fetched, call another php file which wil destroy the created file and I'll be ready for another database request from my webpage situated in a "file:///" location.

How to use Ext.state.Manager with localStorage instead cookies?

Ext JS Ext.state.Manager has only Coockie provider. Cookie can hold only 4096 bites and if my grid or tree has many columns - it overflow 4096 bites and cant save state.
one else issue - every request to server sends all cookies in request, so Apache or anoter web server can not permit huge cookies.
I want to use Provider to save data in localStorage. Is any ready solution? Or I have to write it ?
Here is workaround that I use for now, but may be any more complex solution?
Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
setCookie : function(name, value){
var me = this;
localStorage.setItem(me.prefix+name,me.encodeValue(value));
},
clearCookie : function(name){
var me = this;
localStorage.removeItem(me.prefix+name);
},
readCookies : function(){
var prefix = this.prefix,
len = prefix.length,
cookies = {};
keys = Object.keys(localStorage),
i = 0;
for (; i < keys.length; i++) {
console.log(keys[i].substring(0, len));
if (keys[i] && keys[i].substring(0, len) == prefix){
cookies[keys[i].substr(len)]= this.decodeValue(localStorage.getItem(keys[i]));
}
}
return cookies;
}
}));
The class Ext.state.LocalStorageProvider has been added to ExtJS in Ext JS 4 Beta 1 released on March 30, 2011. See original Docs and Implementation and current Docs and Implementation as of March 11, 2022.
Ext.state.Manager.setProvider(new Ext.state.LocalStorageProvider());

How to detect browser using angularjs?

I am new to angularjs. How can I detect userAgent in angularjs. Is it possible to use that in controller? Tried something like below but no luck!
var browserVersion = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
I need to detect IE9 specifically!
Like Eliran Malka asked, why do you need to check for IE 9?
Detecting browser make and version is generally a bad smell. This generally means that you there is a bigger problem with the code if you need JavaScript to detect specific versions of browser.
There are genuine cases where a feature won't work, like say WebSockets isn't supported in IE 8 or 9. This should be solved by checking for WebSocket support, and applying a polyfill if there is no native support.
This should be done with a library like Modernizr.
That being said, you can easily create service that would return the browser. There are valid cases where a feature exists in a browser but the implementation is outdated or broken. Modernizr is not appropriate for these cases.
app.service('browser', ['$window', function($window) {
return function() {
var userAgent = $window.navigator.userAgent;
var browsers = {chrome: /chrome/i, safari: /safari/i, firefox: /firefox/i, ie: /internet explorer/i};
for(var key in browsers) {
if (browsers[key].test(userAgent)) {
return key;
}
};
return 'unknown';
}
}]);
Fixed typo broswers
Note: This is just an example of how to create a service in angular that will sniff the userAgent string. This is just a code example that is not expected to work in production and report all browsers in all situations.
UPDATE
It is probably best to use a third party library like https://github.com/ded/bowser or https://github.com/darcyclarke/Detect.js. These libs place an object on the window named bowser or detect respectively.
You can then expose this to the Angular IoC Container like this:
angular.module('yourModule').value('bowser', bowser);
Or
detectFactory.$inject = ['$window'];
function detectFactory($window) {
return detect.parse($window.navigator.userAgent);
}
angular.module('yourModule').factory('detect', detectFactory);
You would then inject one of these the usual way, and use the API provided by the lib. If you choose to use another lib that instead uses a constructor method, you would create a factory that instantiates it:
function someLibFactory() {
return new SomeLib();
}
angular.module('yourModule').factory('someLib', someLibFactory);
You would then inject this into your controllers and services the normal way.
If the library you are injecting does not exactly match your requirements, you may want to employ the Adapter Pattern where you create a class/constructor with the exact methods you need.
In this example we just need to test for IE 9, and we are going to use the bowser lib above.
BrowserAdapter.$inject = ['bowser']; // bring in lib
function BrowserAdapter(bowser) {
this.bowser = bowser;
}
BrowserAdapter.prototype.isIe9 = function() {
return this.bowser.msie && this.browser.version == 9;
}
angular.module('yourModule').service('browserAdapter', BrowserAdapter);
Now in a controller or service you can inject the browserAdapter and just do if (browserAdapter.isIe9) { // do something }
If later you wanted to use detect instead of bowser, the changes in your code would be isolated to the BrowserAdapter.
UPDATE
In reality these values never change. IF you load the page in IE 9 it will never become Chrome 44. So instead of registering the BrowserAdapter as a service, just put the result in a value or constant.
angular.module('app').value('isIe9', broswerAdapter.isIe9);
Angular library uses document.documentMode to identify IE . It holds major version number for IE, or NaN/undefined if User Agent is not IE.
/**
* documentMode is an IE-only property
* http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
*/
var msie = document.documentMode;
https://github.com/angular/angular.js/blob/v1.5.0/src/Angular.js#L167-L171
Example with $document (angular wrapper for window.document)
// var msie = document.documentMode;
var msie = $document[0].documentMode;
// if is IE (documentMode contains IE version)
if (msie) {
// IE logic here
if (msie === 9) {
// IE 9 logic here
}
}
you should use conditional comments
<!--[if IE 9]>
<script type="text/javascript">
window.isIE9 = true;
</script>
<![endif]-->
You can then check for $window.isIE9 in your controllers.
Not sure why you specify that it has to be within Angular. It's easily accomplished through JavaScript. Look at the navigator object.
Just open up your console and inspect navigator. It seems what you're specifically looking for is .userAgent or .appVersion.
I don't have IE9 installed, but you could try this following code
//Detect if IE 9
if(navigator.appVersion.indexOf("MSIE 9.")!=-1)
You can easily use the "ng-device-detector" module.
https://github.com/srfrnk/ng-device-detector
var app = angular.module('myapp', ["ng.deviceDetector"]);
app.controller('DeviceCtrl', ["$scope","deviceDetector",function($scope,deviceDetector) {
console.log("browser: ", deviceDetector.browser);
console.log("browser version: ", deviceDetector.browser_version);
console.log("device: ", deviceDetector.device);
}]);
So, you can declare more utilities for angular by create file with content (I follow RGraph Library)
(function(window, angular, undefined) {'use strict';
var agl = angular || {};
var ua = navigator.userAgent;
agl.ISFF = ua.indexOf('Firefox') != -1;
agl.ISOPERA = ua.indexOf('Opera') != -1;
agl.ISCHROME = ua.indexOf('Chrome') != -1;
agl.ISSAFARI = ua.indexOf('Safari') != -1 && !agl.ISCHROME;
agl.ISWEBKIT = ua.indexOf('WebKit') != -1;
agl.ISIE = ua.indexOf('Trident') > 0 || navigator.userAgent.indexOf('MSIE') > 0;
agl.ISIE6 = ua.indexOf('MSIE 6') > 0;
agl.ISIE7 = ua.indexOf('MSIE 7') > 0;
agl.ISIE8 = ua.indexOf('MSIE 8') > 0;
agl.ISIE9 = ua.indexOf('MSIE 9') > 0;
agl.ISIE10 = ua.indexOf('MSIE 10') > 0;
agl.ISOLD = agl.ISIE6 || agl.ISIE7 || agl.ISIE8; // MUST be here
agl.ISIE11UP = ua.indexOf('MSIE') == -1 && ua.indexOf('Trident') > 0;
agl.ISIE10UP = agl.ISIE10 || agl.ISIE11UP;
agl.ISIE9UP = agl.ISIE9 || agl.ISIE10UP;
})(window, window.angular);
after that, in your function use can use it like
function SampleController($scope){
$scope.click = function () {
if(angular.ISCHROME) {
alert("is chrome");
}
}
I modified the above technique which was close to what I wanted for angular and turned it into a service :-). I included ie9 because I was having some issues in my angularjs app, but could be something I'm doing, so feel free to take it out.
angular.module('myModule').service('browserDetectionService', function() {
return {
isCompatible: function () {
var browserInfo = navigator.userAgent;
var browserFlags = {};
browserFlags.ISFF = browserInfo.indexOf('Firefox') != -1;
browserFlags.ISOPERA = browserInfo.indexOf('Opera') != -1;
browserFlags.ISCHROME = browserInfo.indexOf('Chrome') != -1;
browserFlags.ISSAFARI = browserInfo.indexOf('Safari') != -1 && !browserFlags.ISCHROME;
browserFlags.ISWEBKIT = browserInfo.indexOf('WebKit') != -1;
browserFlags.ISIE = browserInfo.indexOf('Trident') > 0 || navigator.userAgent.indexOf('MSIE') > 0;
browserFlags.ISIE6 = browserInfo.indexOf('MSIE 6') > 0;
browserFlags.ISIE7 = browserInfo.indexOf('MSIE 7') > 0;
browserFlags.ISIE8 = browserInfo.indexOf('MSIE 8') > 0;
browserFlags.ISIE9 = browserInfo.indexOf('MSIE 9') > 0;
browserFlags.ISIE10 = browserInfo.indexOf('MSIE 10') > 0;
browserFlags.ISOLD = browserFlags.ISIE6 || browserFlags.ISIE7 || browserFlags.ISIE8 || browserFlags.ISIE9; // MUST be here
browserFlags.ISIE11UP = browserInfo.indexOf('MSIE') == -1 && browserInfo.indexOf('Trident') > 0;
browserFlags.ISIE10UP = browserFlags.ISIE10 || browserFlags.ISIE11UP;
browserFlags.ISIE9UP = browserFlags.ISIE9 || browserFlags.ISIE10UP;
return !browserFlags.ISOLD;
}
};
});
There is a library ng-device-detector which makes detecting entities like browser, os easy.
Here is tutorial that explains how to use this library. Detect OS, browser and device in AngularJS
ngDeviceDetector
You need to add re-tree.js and ng-device-detector.js scripts into your html
Inject "ng.deviceDetector" as dependency in your module.
Then inject "deviceDetector" service provided by the library into your controller or factory where ever you want the data.
"deviceDetector" contains all data regarding browser, os and device.
Why not use document.documentMode only available under IE:
var doc = $window.document;
if (!!doc.documentMode)
{
if (doc.documentMode === 10)
{
doc.documentElement.className += ' isIE isIE10';
}
else if (doc.documentMode === 11)
{
doc.documentElement.className += ' isIE isIE11';
}
// etc.
}
Browser sniffing should generally be avoided, feature detection is much better, but sometimes you have to do it. For instance in my case Windows 8 Tablets overlaps the browser window with a soft keyboard; Ridiculous I know, but sometimes you have to deal with reality.
So you would measure 'navigator.userAgent' as with regular JavaScript (Please don't sink into the habit of treating Angular as something distinct from JavaScript, use plain JavaScript if possible it will lead to less future refactoring).
However for testing you want to use injected objects rather than global ones. Since '$location' doesn't contain the userAgent the simple trick is to use '$window.location.userAgent'. You can now write tests that inject a $window stub with whatever userAgent you wan't to simulate.
I haven't used it for years, but Modernizr's a good source of code for checking features. https://github.com/Modernizr/Modernizr/issues/878#issuecomment-41448059
Detection ie9+
var userAgent, ieReg, ie;
userAgent = $window.navigator.userAgent;
ieReg = /msie|Trident.*rv[ :]*11\./gi;
ie = ieReg.test(userAgent);
if (ie) {
// js for ie9,10 and 11
}

Is there anyway to know which user is calling the WCF Ria service on server side, using silverlight on clientside?

Is there anyway to know which user is calling the WCF Ria service on server side? Client side is siverlight, user has to be authenticated first in order to use the system.
I need to know which user is actually calling the service in my current task, thanks, i searched a lot, but seems no good findings.
Once the client side has successfully cleared your authentication challenge, the server can issue a token to the caller on the client side. In subsequent calls to the server, the client would send the token as one of the arguments and the server would verify the token and respond accordingly.
The token can contain a segment of information that identifies a given user, and implementing this will provide the functionality you are seeking.
The only guidelines for generating tokens is that they are unique, non-predictable and expirable. I have always encrypted my tokens so that they appear as gibberish, but step this is optional.
I've also done very much "googleing" and got a lot of headache before I got the solution.
I don't use RIA-Services - but it should be (hopefully) the same...:
The SL-Client sends a "login-request" to the server.
On the (WCF) server-side, I do the following (LoginData = Return-Info for SL-Client):
public LoginData LoginRequest() {
(...)
OperationContext context = OperationContext.Current;
System.ServiceModel.Channels.MessageProperties prp = context.IncomingMessageProperties;
System.ServiceModel.Channels.RemoteEndpointMessageProperty endPrp = prp[System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name] as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
(...)
try {
clientIP = endPrp.Address;
System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse(clientIP);
System.Net.IPHostEntry ipHostEntry = System.Net.Dns.GetHostEntry(ipAddress);
(...)
If you want to check the users WindowsPrincipal, you can do the following (securityGroup = server-side setting, which users can login):
(...)
switch (securityGroup) {
case SecurityGroup.AllClientsCanAccess: {
clientCanLogin = true;
} break;
case SecurityGroup.UseWindowsCredentials: {
if (OperationContext.Current.ServiceSecurityContext != null && OperationContext.Current.ServiceSecurityContext.WindowsIdentity != null) {
if (OperationContext.Current.ServiceSecurityContext.WindowsIdentity.IsAuthenticated) {
if (subSecurityInfo1 == true) { // only clients in specific roles can log in
bool userRoleFound = false;
WindowsPrincipal userPrincipal = new WindowsPrincipal(OperationContext.Current.ServiceSecurityContext.WindowsIdentity);
if (userPrincipal == null)
break;
foreach (string userRoleToPass in subSecurityList) { // subSecurityList = settings, which roles can pass
loginError.ErrorInfo += string.Format("{0}\n", userRoleToPass);
if (userPrincipal.IsInRole(userRoleToPass)) {
clientCanLogin = userRoleFound = true;
break;
}
}
if (userRoleFound) {
loginError.ErrorInfo = string.Empty;
break;
}
else {
loginError.ErrorNo = LoginErrorCodeNoEnum.UserIsNotInRole;
}
}
(...)
Hope it helps...

Resources