Friday, October 11, 2013

How to get a currently logged in username with Domain name using Javascript

I got a situation in my classic ASP application in which i need to restrict users to some pages based on their active directory username. Initially, i implemented this like, created a new asp page and their i got the logon user name and based on that user name i'm setting the session variables to set the permission. So, when a particular page is accessed (before that i have included my newly created authentication asp file), i check the session variable and let user to access the page.

   The problem with this approach is, My client don't want to add include file in each and every page where we need to check the condition. He wanted to include this file in global.asa. But the problem is, we cant include a asp file which has <% or %> derivatives. We can include only files which has only script functions.

So, i had to find a way to get the logged in username with scripts and finally i came up with a solution as below,


    var WinNetwork = new ActiveXObject("WScript.Network");
 
    Session("user") = WinNetwork.Domain ;


This works perfectly, but the problem is its retrieves only the user name, but not the domain name.

For example : lets say my domain name is  XYZ and my userid is Mathi, the above code returning my user name as "Mathi", instead of "XYZ/Mathi"


Well, i struggled a lot to find the user name with domain using javascript and finally end up with the below code.


    var wmi = GetObject("winmgmts:{impersonationLevel=Impersonate}\\\\.\\root\\cimv2");
    var query = "Select * From win32_computersystem";
    e = new Enumerator(wmi.ExecQuery(query));
    var data = e.item();

    var strUser = data.UserName;



this code returned the result as expected.