locked
Using WebAPI to get User Permissions throws 'undefined' when used on screen created (HTML Client) RRS feed

  • Question

  • After reading Beth's article Using LightSwitch ServerApplicationContext and WebAPI to Get User Permissions, I am getting myapp.permissions = undefined when checking for permissions when the screen is created (as pointed out by Ken Carrier in the comments of the article above mentioned).

    Does anybody know a workaround for this?

    Also it catches my attention that 'permissions' is not shown by Intellisense, even after rebuild all, so 'undefined' makes sense to me.

    However, it works correctly if 'created' finishes loading and you check the permissions elsewhere (for example on _ItemTap_execute).

    Wednesday, April 2, 2014 1:50 PM

Answers

  • Since myapp.permissions is global, you only need to get the JSON once, in your 'created' startup screen. Then it is available througout the application.

    You can't check permissions on the startup screen during 'created', because you will get the 'undefined' exception, but for that case I used the getQuery() with canExecute approach to display what's needed.

    Calling it in post_Render didn't worked, btw.

    Thursday, April 3, 2014 1:38 PM

All replies

  • Maybe the timing has changed from when the blog was written.  You could try putting the code in post_render method of first tab on your home screen.

    Or check this blog for core project with user management for HTML client - no SL client or webapi needed:

    http://blog.ofanitguy.com/2013/11/26/lightswitch-2013-core-project-with-user-management-tile-screens-self-registration/

    HTH,

    Josh


    • Edited by joshbooker Wednesday, April 2, 2014 4:00 PM iphone cant post
    Wednesday, April 2, 2014 3:27 PM
  • Since myapp.permissions is global, you only need to get the JSON once, in your 'created' startup screen. Then it is available througout the application.

    You can't check permissions on the startup screen during 'created', because you will get the 'undefined' exception, but for that case I used the getQuery() with canExecute approach to display what's needed.

    Calling it in post_Render didn't worked, btw.

    Thursday, April 3, 2014 1:38 PM
  • Hi Nicolás,

    Is it possible to provide the source code for this workaround because I don't know what is getQuery() in terms of the HTML client.

    Thank you,

    Martin

    Friday, April 18, 2014 9:19 PM
  • Hi Nicolás,

    Is it possible to provide the source code for this workaround because I don't know what is getQuery() in terms of the HTML client.

    Thank you,

    Martin

    Martin, please check Beth Massi's mentioned article for reference. You gotta replace 'Query' for the name of the corresponding query in your screen (getYourQueryName()...).

    good luck!

    Nico

    Wednesday, April 23, 2014 7:06 PM
  • Hi Nico,

    Thank you for your reply. Just a quick check - the query you are talking about is the web api query that is used to retrieve the permissions, right? Do you still use the myapp.permissions global variable in your approach?

    Thanks,

    Martin

    Wednesday, April 23, 2014 7:28 PM
  • Hi Nico,

    Thank you for your reply. Just a quick check - the query you are talking about is the web api query that is used to retrieve the permissions, right? Do you still use the myapp.permissions global variable in your approach?

    Thanks,

    Martin

    Martin,

    Yes, I am still using myapp.permissions. It works just fine.

    Wednesday, April 23, 2014 7:50 PM
  • Hello Nicolas,

    can you help me please, i have got same problem, and i cannot find what you did exactly?

    I checked this - >

    myapp.Home.created = function (screen) {
        // Write code here.
        screen.getDrivers().then(function success() {
            screen.findContentItem("Drivers").isVisible = true;
        }, function error() {
            screen.findContentItem("Drivers").isVisible = false;
        });
    };

    and this working for the query! but i want do something like this ->

    /* $.getJSON("../UserPerms/UserPermissions/", function (data) {
            myapp.permissions = data;
        });

        if (myapp.permissions["LightSwitchApplication:CanAddDrivers"] || myapp.permissions["LightSwitchApplication:CanDeleteDrivers"] || myapp.permissions["LightSwitchApplication:CanEditDrivers"]) {
            screen.findContentItem("Drivers").isVisible = true;
        } else {
            screen.findContentItem("Drivers").isVisible = false;
        }

    can you help me please?

    Thanks in advance.




    • Edited by Simithie Saturday, June 20, 2015 10:29 AM
    Saturday, June 20, 2015 10:29 AM
  • Please have look on the lsWires project which I think is a much cleaner way of dealing with this:

    lsWires.js - A library of functions for developing applications with Visual Studio LightSwitch.

    If you just need that specific part regarding Security, I could give you that part as I am using that on a daily basis.

    Saturday, June 20, 2015 7:55 PM
  • Thank you for answer!

    It is simple application, i only need this part for security. If you can give me that part i will be grateful to you! 

    Saturday, June 20, 2015 9:32 PM
  • The following code is from the lsWires project by Dale Morisson: 

    Create a folder and name it App_Start (this is for the Web API) (Server):

    using System.Web.Http;
    
    namespace LightSwitchApplication
    {
        public class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.MapHttpAttributeRoutes();
    
                // Create our route for our Web API
                // This route provides a functional RPC
                config.Routes.MapHttpRoute(
                    name: "api",
                    routeTemplate: "api/{controller}/{action}/{id}/{param}",
                    defaults: new
                    {
                        id = RouteParameter.Optional,
                        param = RouteParameter.Optional
                    }
                );
    
    
            }
        }
    }

     Create a folder api/controllers and add the following code: (Server)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http;
    using Microsoft.LightSwitch.Security.Server;
    
    namespace LightSwitchApplication
    {
        public class SecurityController : ApiController
        {
            // GET api/Security/GetUserInfo
            // =========================================================================
            [AcceptVerbs("GET")]
            public Dictionary<string, object> GetUserInfo()
            {
                var userInfo = new Dictionary<string, object>();
    
                using (ServerApplicationContext ctx = ServerApplicationContext.Current ?? ServerApplicationContext.CreateContext())
                {
    
               
                    var currentUser = ctx.Application.User;
                    if (currentUser.IsAuthenticated)
                    {
    
                        userInfo.Add("UserName", currentUser.Name);
                        userInfo.Add("FullName", currentUser.FullName);
                        userInfo.Add("Permissions", getUserPermissions(ctx));
                        userInfo.Add("Roles", getUserRoles(ctx));
                    }
                }
                return userInfo;
            }
    
    
            // GET api/Security/userHasPermission/LightSwitchApplication:Delete
            // =========================================================================
            [AcceptVerbs("GET")]
            public Boolean userHasPermission(string Id)
            {
                var result = false;
    
                using (ServerApplicationContext ctx = ServerApplicationContext.Current ?? ServerApplicationContext.CreateContext())
                {
                    var currentUser = ctx.Application.User;
                    if (currentUser.IsAuthenticated)
                    {
                        result = (from x in currentUser.EffectivePermissions
                                  where x.Split(':')[1].ToLower() == Id.ToLower()
                                  select x).Any();
                    }
                }
                return result;
            }
    
            // GET api/Security/userHasRole/Admin
            // =========================================================================
            [AcceptVerbs("GET")]
            public Boolean userHasRole(string Id)
            {
                var result = false;
    
                using (ServerApplicationContext ctx = ServerApplicationContext.Current ?? ServerApplicationContext.CreateContext())
                {
                    var currentUser = ctx.Application.User;
                    if (currentUser.IsAuthenticated)
                    {
                        result = (from x in currentUser.Roles
                                  where x.ToLower() == Id.ToLower()
                                  select x).Any();
    
                    }
                }
                return result;
            }
    
    
            // GET api/Security/GetAppSecurityObjects
            // =========================================================================
            [AcceptVerbs("GET")]
            public Dictionary<string, object> GetAppSecurityObjects()
            {
                var appSecurityInfo = new Dictionary<string, object>();
    
                using (ServerApplicationContext ctx = ServerApplicationContext.Current ?? ServerApplicationContext.CreateContext())
                {
                    var currentUser = ctx.Application.User;
                    var removeAdminPermission = false;
    
                    if (currentUser.IsAuthenticated)
                    {
                        // Temporarily raise permissions
                        if (!currentUser.HasPermission(Permissions.SecurityAdministration))
                        {
                            removeAdminPermission = true;
                            currentUser.AddPermissions(Permissions.SecurityAdministration);
                        }
    
                        // Get all the roles for this app
                        var roleList = (from Microsoft.LightSwitch.Security.Role role in ctx.DataWorkspace.SecurityData.Roles select role.Name).ToList();
    
                        // Now get all the permissions for the app
                        var permissionList = ctx.DataWorkspace.SecurityData.Permissions.GetQuery().Execute().Select(x => x.Id.Split(':')[1]).ToList();
    
                        // Don't forget to drop permission if necessary
                        if (removeAdminPermission) currentUser.RemovePermissions(Permissions.SecurityAdministration);
    
                        appSecurityInfo.Add("Roles", roleList);
                        appSecurityInfo.Add("Permissions", permissionList);
                    }
    
                }
                return appSecurityInfo;
            }
    
    
            // Internal - Get dictionary of all the roles and whether user is in the role
            // =========================================================================
            private List<string> getUserRoles(ServerApplicationContext ctx)
            {
                var roles = new List<string>();
    
                var currentUser = ctx.Application.User;
                var removeAdminPermission = false;
    
                if (currentUser.IsAuthenticated)
                {
                    // Temporarily raise permissions
                    if (!currentUser.HasPermission(Permissions.SecurityAdministration))
                    {
                        removeAdminPermission = true;
                        currentUser.AddPermissions(Permissions.SecurityAdministration);
                    }
    
                    roles = currentUser.Roles.ToList();
    
                    // Don't forget to drop permission if necessary
                    if (removeAdminPermission) currentUser.RemovePermissions(Permissions.SecurityAdministration);
    
                }
    
                return roles;
            }
    
    
            // Internal - Get a dictionary of permissions and whether use has those permissions
            // =========================================================================
            private List<string> getUserPermissions(ServerApplicationContext ctx)
            {
                var perms = new List<string>();
    
                var currentUser = ctx.Application.User;
                if (currentUser.IsAuthenticated)
                {
                    var removeAdminPermission = false;
    
                    // Temporarily raise permissions
                    if (!currentUser.HasPermission(Permissions.SecurityAdministration))
                    {
                        removeAdminPermission = true;
                        currentUser.AddPermissions(Permissions.SecurityAdministration);
                    }
    
                    perms = currentUser.EffectivePermissions
                        .Where(x => !removeAdminPermission || x.ToLower() != Permissions.SecurityAdministration.ToLower())
                        .Select(x => x.Split(':')[1])
                        .ToList();
    
    
                    // Don't forget to drop permission if necessary
                    if (removeAdminPermission) currentUser.RemovePermissions(Permissions.SecurityAdministration);
    
                }
    
                return perms;
            }
    
        }
    }

    Add the lsWire.js file to your scripts and add a reference to your default.htm. 

    Add a Global.asax file to your project and update the code with the following 

    protected void Application_Start(object sender, EventArgs e)
            {
                // Go configure our Web API
                GlobalConfiguration.Configure(WebApiConfig.Register);
             
            }

    Add the following line to your created metod: 

     lsWire.initializeCore(screen, true);

    To check for a specific permission: 

    lsWire.userHasPermission("DataAdministration"))




    • Edited by Phero_ Monday, June 22, 2015 6:18 AM
    Monday, June 22, 2015 6:12 AM
  • Thank you my friend, i will check this code in my application , i hope it will help me with my job.

    Thanks again!

    Monday, June 22, 2015 6:40 AM