Exemplo n.º 1
0
 /// <summary>
 /// 使用Descriptor,取程序集中所有Action的元数据
 /// </summary>
 /// <returns></returns>
 public static IEnumerable<ApplicationPermission> GetAllActionByAssembly()
 {
     var result = new List<ApplicationPermission>();
     // 取程序集中的全部类型
     var types = Assembly.Load("Kwop.Web").GetTypes();
     // 取控制器
     foreach (var type in types)
     {
         if (type.BaseType == typeof(BaseController)) // 如果是BaseController type.BaseType.Name == "BaseController"
         {
             // 反射控制器
             var controller = new ReflectedControllerDescriptor(type);
             // 取控制器的Action,共有实例方法
             var actions = controller.GetCanonicalActions();
             // 构建权限
             foreach (var action in actions)
             {
                 // 创建权限
                 var ap = new ApplicationPermission()
                 {
                     Action = action.ActionName,
                     Controller = controller.ControllerName,
                     //Params = FormatParams(action),
                     Description = GetDescription(action)
                 };
                 result.Add(ap);
             }
         }
     }
     return result;
 }
Exemplo n.º 2
0
        /// <summary>
        /// Generates ApplicationPermissions based on Permissions Type by iterating over its nested classes and getting constant strings in each class as Value and Name, LocalizedDescriptionAttribute of the constant string as Description, the nested class name as GroupName.
        /// </summary>
        static ApplicationPermissions()
        {
            List <ApplicationPermission> allPermissions    = new List <ApplicationPermission>();
            IEnumerable <object>         permissionClasses = typeof(Permissions).GetNestedTypes(BindingFlags.Static | BindingFlags.Public).Cast <TypeInfo>();

            foreach (TypeInfo permissionClass in permissionClasses)
            {
                IEnumerable <FieldInfo> permissions = permissionClass.DeclaredFields.Where(f => f.IsLiteral);
                foreach (FieldInfo permission in permissions)
                {
                    ApplicationPermission applicationPermission = new ApplicationPermission
                    {
                        Value     = permission.GetValue(null).ToString(),
                        Name      = permission.GetValue(null).ToString().Replace('.', ' '),
                        GroupName = permissionClass.Name
                    };

                    DisplayAttribute[] attributes = (DisplayAttribute[])permission.GetCustomAttributes(typeof(DisplayAttribute), false);

                    applicationPermission.Description = attributes != null && attributes.Length > 0 ? attributes[0].Description : applicationPermission.Name;

                    allPermissions.Add(applicationPermission);
                }
            }

            var entitiesWithPermissionsAttribute = Assembly.GetExecutingAssembly().GetExportedTypes().Where(t => t.GetCustomAttributes <PermissionsAttribute>(inherit: false).Any());

            foreach (Type entity in entitiesWithPermissionsAttribute)
            {
                var requiredPermissions = entity.GetCustomAttribute <PermissionsAttribute>(false);

                foreach (Actions action in Enum.GetValues(typeof(Actions)))
                {
                    if ((requiredPermissions.Actions & action) == action && action != Actions.CRUD)
                    {
                        allPermissions.Add(new ApplicationPermission
                        {
                            Value     = $"{entity.Name}.{action}",
                            Name      = $"{entity.Name} {action}",
                            GroupName = entity.Name
                        });
                    }
                }
            }

            AllPermissions           = allPermissions.AsReadOnly();
            AllPermissionsForTenants = allPermissions.Where(i => !i.Value.StartsWith("Tenant.")).ToList().AsReadOnly();
        }
        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ApplicationPermission applicationPermission = _db.Permissions.Find(id);

            if (applicationPermission == null)
            {
                return(HttpNotFound());
            }
            var view = Mapper.Map <PermissionViewModel>(applicationPermission);

            return(View(view));
        }
Exemplo n.º 4
0
        /// <summary>
        /// 当前请求是否具有访问权限
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        private bool HasPermission(AuthorizationContext filterContext)
        {
            //取当前用户的权限
            var rolePermissions = GetUserPermissions(filterContext.HttpContext);

            //待访问的Action的Permission
            var action = new ApplicationPermission
            {
                Action      = filterContext.ActionDescriptor.ActionName,
                Controller  = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                Description = ActionPermissionService.GetDescription(filterContext.ActionDescriptor)
            };

            //是否授权
            return(rolePermissions.Contains(action, new ApplicationPermissionEqualityComparer()));
        }
Exemplo n.º 5
0
        public Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var permissionAttribute = request.GetType()
                                      .GetCustomAttribute <RequirePermissionAttribute>();

            if (permissionAttribute != null)
            {
                ApplicationPermission permission = permissionAttribute.Permission;
                if (!authService.HasPermission(this.principal, permission))
                {
                    throw new UnauthorizedAccessException($"Principal {this.principal.UserId()} does not have permission {permission}.");
                }
            }

            return(next());
        }
Exemplo n.º 6
0
        private ApplicationPermission CreateOrUpdatePermission(string name, string description, bool isCustom, Repository repo)
        {
            if (_applicationPermissionDictionary == null)
            {
                _applicationPermissionDictionary = new ConcurrentDictionary <string, ApplicationPermission>();
                var applicationPermissions = repo.Get <ApplicationPermission>(a => a.Name != null);
                foreach (var item in applicationPermissions)
                {
                    if (!_applicationPermissionDictionary.ContainsKey(item.Name))
                    {
                        _applicationPermissionDictionary.TryAdd(item.Name, item);
                    }
                }
            }
            bool update             = false;
            ApplicationPermission p = null;

            if (_applicationPermissionDictionary.ContainsKey(name))
            {
                p = _applicationPermissionDictionary[name];
                if (p.IsCustom != isCustom)
                {
                    p.IsCustom = isCustom;
                    update     = true;
                }
                if (p.Description != description)
                {
                    p.Description = description;
                    update        = true;
                }
            }
            else
            {
                update        = true;
                p             = new ApplicationPermission();
                p.Name        = name;
                p.IsCustom    = isCustom;
                p.Description = description;
            }
            if (update)
            {
                repo.Save(p);
            }
            return(p);
        }
Exemplo n.º 7
0
        public void SetUserPermission(ApplicationPermission perm)
        {
            CheckIsAdmin();
            UserApplication up = db.SelectObjectWhere <UserApplication> ("UserId={0} AND ApplicationId={1}", user.Id, application.Id);

            if (up == null)
            {
                up = new UserApplication()
                {
                    UserId = user.Id, ApplicationId = application.Id, Permissions = perm
                };
                db.InsertObject <UserApplication> (up);
            }
            else
            {
                up.Permissions |= perm;
                db.UpdateObject(up);
            }
        }
Exemplo n.º 8
0
        public async Task <ActionResult> Delete(string roleId, string permissionId)
        {
            if (string.IsNullOrWhiteSpace(roleId) || string.IsNullOrWhiteSpace(permissionId))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ApplicationPermission applicationPermission = _db.Permissions.Find(permissionId);
            var role = await _roleManager.FindByIdAsync(roleId);

            if (applicationPermission == null)
            {
                return(HttpNotFound());
            }
            //创建viewModel
            var view = Mapper.Map <PermissionViewModel>(applicationPermission);

            view.RoleId   = roleId;
            view.RoleName = role.Name;

            return(View(view));
        }
Exemplo n.º 9
0
        private static void AddRolePermissions(SecurityDbContext db, string roleId)
        {
            var resources = db.Resources.ToList();

            foreach (var resource in resources)
            {
                var permission = db.Permissions.FirstOrDefault(x => x.ResourceId == resource.Id && x.RoleId == roleId);
                if (permission == null || permission.Id == new Guid().ToString())
                {
                    permission = new ApplicationPermission()
                    {
                        Id         = Guid.NewGuid().ToString(),
                        ResourceId = resource.Id,
                        IsAllowed  = true,
                        RoleId     = roleId,
                    };
                    db.Permissions.Add(permission);
                }
                db.SaveChanges();
            }
        }
Exemplo n.º 10
0
        public async Task <IActionResult> AllPermissionList(int offset, int limit, string order, string search)
        {
            PermissionList plist = new PermissionList();
            //List<Claim> claims =new List<Claim>();
            List <ApplicationPermission> aplist = new List <ApplicationPermission>();

            var allroles = _roleMangeer.Roles;

            foreach (var role in allroles)
            {
                foreach (var claims in await _roleMangeer.GetClaimsAsync(role))
                {
                    ApplicationPermission ap = new ApplicationPermission();
                    ap.RoleName        = role.Name;
                    ap.PermissionType  = claims.Type;
                    ap.PermissionValue = claims.Value;
                    aplist.Add(ap);
                }

                //claims.AddRange(_roleMangeer.GetClaimsAsync(role).Result.ToList());
            }
            if (!string.IsNullOrEmpty(search))
            {
                aplist = aplist.Where(c => c.PermissionValue.Contains(search)).ToList();
            }
            plist.total = aplist.Count();
            if (limit != 0)
            {
                if (order.Equals("desc"))
                {
                    aplist = aplist.OrderByDescending(c => c.PermissionType).Skip(offset).Take(limit).ToList();
                }
                else
                {
                    aplist = aplist.OrderBy(c => c.PermissionType).Skip(offset).Take(limit).ToList();
                }
            }
            plist.rows = aplist;
            return(Json(plist));
        }
Exemplo n.º 11
0
        private static void CreatePermissions(SecurityDbContext context, ILogger <DbInitializer> logger)
        {
            var readAllText = File.ReadAllText("./Resources/permissions.json");
            var permissions = JsonConvert.DeserializeObject <List <ApplicationPermission> >(readAllText);

            foreach (var permission in permissions)
            {
                logger.LogInformation($"Create the permission for resource `{permission.Resource.Name}` and role `{permission.Role.Name} ");

                var role     = context.ApplicationRoles.FirstOrDefault(x => x.Name == permission.Role.Name);
                var resource = context.Resources.FirstOrDefault(x => x.Name == permission.Resource.Name);

                var any = context.Permissions.Include(x => x.Role).Include(x => x.Resource).AsEnumerable()
                          .Any(x => string.Equals(x.RoleId, role.Id, StringComparison.CurrentCultureIgnoreCase) &&
                               string.Equals(x.ResourceId, resource.Id, StringComparison.CurrentCultureIgnoreCase));
                if (!any)
                {
                    var appPermission = new ApplicationPermission()
                    {
                        IsAllowed  = permission.IsAllowed,
                        ResourceId = resource.Id,
                        RoleId     = role.Id
                    };
                    context.Permissions.Add(appPermission);
                    var i = context.SaveChanges();
                    if (i > 0)
                    {
                        logger.LogDebug($"Created the permission for resource `{permission.Resource.Name}` and role `{permission.Role.Name}");
                    }
                    else
                    {
                        ApplicationException exception =
                            new ApplicationException($"Default resource `{permission.Resource.Name}` & role `{permission.Role.Name} cannot be created");
                        logger.LogError(exception, $"Exception occurred. {exception.Message}");
                        throw exception;
                    }
                }
            }
        }
        public async Task <IHttpActionResult> Post(ApplicationPermission permission)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            ApplicationPermission applicationPermission = db.Permissions.FirstOrDefault(x => x.ResourceId == permission.ResourceId && x.RoleId == permission.RoleId);

            if (applicationPermission == null)
            {
                permission.Id = Guid.NewGuid().ToString();
                db.Permissions.Add(permission);
                await db.SaveChangesAsync();
            }
            else
            {
                ModelState.AddModelError("Duplicate", "This resource is already assigned with this role");
            }

            return(Ok(permission.Id));
        }
Exemplo n.º 13
0
        /// <summary>
        /// 使用反射,获取Action的信息
        /// </summary>
        /// <returns></returns>
        public static IEnumerable <ApplicationPermission> GetAllActionByAssembly_01()
        {
            var result = new List <ApplicationPermission>();
            //取程序集中的全部类型
            var types = Assembly.Load("AspNetIdentity2Permission.Mvc").GetTypes();

            foreach (var type in types)
            {
                if (type.BaseType.Name == "BaseController")//如果是BaseController
                {
                    //取类型的方法,类型为实例方法,公共方法
                    var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public);
                    foreach (var method in methods)
                    {
                        //因存在异步与同步方法,所以统一用返回类型的tostring方法
                        var returnType = method.ReturnType.ToString();

                        if (returnType.Contains("ActionResult"))//如果是ActionResult
                        {
                            var ap = new ApplicationPermission()
                            {
                                Action     = method.Name,
                                Controller = method.DeclaringType.Name.Substring(0, method.DeclaringType.Name.Length - 10), /* 去掉“Controller”后缀*/
                                Params     = FormatParams(method)
                            };
                            //取Action的描述
                            var attrs = method.GetCustomAttributes(typeof(DescriptionAttribute), true);
                            if (attrs.Length > 0)
                            {
                                ap.Description = (attrs[0] as DescriptionAttribute).Description;
                            }

                            result.Add(ap);
                        }
                    }
                }
            }
            return(result);
        }
Exemplo n.º 14
0
        public override async Task <ICollection <PermisoDto> > HandleCommand(CreatePermisoRequest request, CancellationToken cancellationToken)
        {
            var vm = new List <PermisoDto>();
            ApplicationPermission permiso = new ApplicationPermission
            {
                Detalle    = request.Detalle,
                Slug       = request.Slug,
                MenuRoleId = request.MenuRoleId
            };

            _context.permissions.Add(permiso);
            try
            {
                await _context.SaveChangesAsync(cancellationToken);
            }
            catch (DbUpdateConcurrencyException)
            {
                _context.RollbackTransaction();
                _context.DetachAll();
                return(await HandleCommand(request, cancellationToken));
            }
            vm.Add(_mapper.Map <PermisoDto>(permiso));
            return(vm);
        }
Exemplo n.º 15
0
 public RequirePermissionAttribute(ApplicationPermission permission)
 {
     this.permission = permission;
 }
Exemplo n.º 16
0
 public void SetUserApplicationPermission(int userId, ApplicationPermission perms, bool enable)
 {
     UserApplication up = db.SelectObjectWhere<UserApplication> ("UserId={0} AND ApplicationId={1}", userId, application.Id);
     if (up == null) {
         if (enable) {
             up = new UserApplication () { UserId = userId, ApplicationId = application.Id, Permissions = perms };
             db.InsertObject (up);
         }
     }
     else {
         if (enable)
             up.Permissions |= ApplicationPermission.Administer;
         else
             up.Permissions &= ~ApplicationPermission.Administer;
         db.UpdateObject (up);
     }
 }
Exemplo n.º 17
0
 public void SetUserPermission(ApplicationPermission perm)
 {
     CheckIsAdmin ();
     UserApplication up = db.SelectObjectWhere<UserApplication> ("UserId={0} AND ApplicationId={1}", user.Id, application.Id);
     if (up == null) {
         up = new UserApplication () { UserId = user.Id, ApplicationId = application.Id, Permissions = perm };
         db.InsertObject<UserApplication> (up);
     }
     else {
         up.Permissions |= perm;
         db.UpdateObject (up);
     }
 }
Exemplo n.º 18
0
 public async Task<ActionResult> Create(IEnumerable<PermissionViewModel> data)
 {
     if (data == null)
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "参数不能为空");
     }
     foreach (var item in data)
     {
         // 创建权限
         var permission = new ApplicationPermission
         {
             Controller = item.Controller,
             Action = item.Action,
             Description = item.Description
         };
         db.Permissions.Add(permission);
     }
     await db.SaveChangesAsync();
     // 使用Newtonsoft.Json序列化结果对象
     // 格式为json字符串,客户端需要解析,即反序列化
     var result = JsonConvert.SerializeObject(new { Success = true });
     return new JsonResult { Data = result };
 }
Exemplo n.º 19
0
 public void ResetUserPermission(ApplicationPermission perm)
 {
     CheckIsAdmin ();
     UserApplication up = db.SelectObjectWhere<UserApplication> ("UserId={0} AND ApplicationId={1}", user.Id, application.Id);
     if (up != null) {
         up.Permissions &= ~perm;
         db.UpdateObject (up);
     }
 }
Exemplo n.º 20
0
        public static void InitializeIdentity(ApplicationDbContext context)
        {
            #region Contracts

            if (context == null) throw new ArgumentNullException();

            #endregion

            // Default - User
            const string adminUserName = "******";
            const string adminUserPassword = "******";

            const string guestUserName = "******";
            const string guestUserPassword = "******";

            // Default - Role
            const string adminRoleName = "Admin";
            const string guestRoleName = "Guest";

            // Default - Permission
            const string aboutPermissionName = "AboutAccess";
            const string contactPermissionName = "ContactAccess";


            // Manager
            var userManager = HttpContext.Current.GetOwinContext().Get<ApplicationUserManager>();
            var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
            var permissionManager = HttpContext.Current.GetOwinContext().Get<ApplicationPermissionManager>();


            // User
            var adminUser = userManager.FindByName(adminUserName);
            if (adminUser == null)
            {
                adminUser = new ApplicationUser { UserName = adminUserName, Email = adminUserName };
                userManager.Create(adminUser, adminUserPassword);
                userManager.SetLockoutEnabled(adminUser.Id, false);
            }

            var guestUser = userManager.FindByName(guestUserName);
            if (guestUser == null)
            {
                guestUser = new ApplicationUser { UserName = guestUserName, Email = guestUserName };
                userManager.Create(guestUser, guestUserPassword);
                userManager.SetLockoutEnabled(guestUser.Id, false);
            }

            // Role
            var adminRole = roleManager.FindByName(adminRoleName);
            if (adminRole == null)
            {
                adminRole = new ApplicationRole(adminRoleName);
                roleManager.Create(adminRole);
            }

            var guestRole = roleManager.FindByName(guestRoleName);
            if (guestRole == null)
            {
                guestRole = new ApplicationRole(guestRoleName);
                roleManager.Create(guestRole);
            }

            // Permission
            var aboutPermission = permissionManager.FindByName(aboutPermissionName);
            if (aboutPermission == null)
            {
                aboutPermission = new ApplicationPermission(aboutPermissionName);
                permissionManager.Create(aboutPermission);
            }

            var contactPermission = permissionManager.FindByName(contactPermissionName);
            if (contactPermission == null)
            {
                contactPermission = new ApplicationPermission(contactPermissionName);
                permissionManager.Create(contactPermission);
            }


            // UserAddToRole 
            IList<string> rolesForUser = null;

            rolesForUser = userManager.GetRoles(adminUser.Id);
            if (rolesForUser.Contains(adminRole.Name) == false)
            {
                userManager.AddToRole(adminUser.Id, adminRole.Name);
            }

            rolesForUser = userManager.GetRoles(guestUser.Id);
            if (rolesForUser.Contains(guestRole.Name) == false)
            {
                userManager.AddToRole(guestUser.Id, guestRole.Name);
            }


            // PermissionAddToRole 
            IList<string> rolesForPermission = null;

            rolesForPermission = permissionManager.GetRolesById(aboutPermission.Id);
            if (rolesForPermission.Contains(adminRole.Name) == false)
            {
                permissionManager.AddToRole(aboutPermission.Id, adminRole.Name);
            }

            rolesForPermission = permissionManager.GetRolesById(contactPermission.Id);
            if (rolesForPermission.Contains(adminRole.Name) == false)
            {
                permissionManager.AddToRole(contactPermission.Id, adminRole.Name);
            }
        }
Exemplo n.º 21
0
        public async Task <ActionResult <ApplicationPermission> > PostApplicationPermission(ApplicationPermission applicationPermission)
        {
            _context.Permissions.Add(applicationPermission);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ApplicationPermissionExists(applicationPermission.Id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetApplicationPermission", new { id = applicationPermission.Id }, applicationPermission));
        }
Exemplo n.º 22
0
 public async Task<ActionResult> Edit([Bind(Include = "Controller, Action, Description")] PermissionViewModel view)
 {
     if (ModelState.IsValid)
     {
         // 对象映射
         ApplicationPermission permission = new ApplicationPermission
         {
             Controller = view.Controller,
             Action = view.Action,
             Description = view.Description
         };
         db.Entry(permission).State = EntityState.Modified;
         await db.SaveChangesAsync();
     }
     return View(view);
 }
 /// <summary>
 /// 当前请求是否具有访问权限
 /// </summary>
 /// <param name="filterContext"></param>
 /// <returns></returns>
 private bool HasPermission(AuthorizationContext filterContext)
 {
     //取当前用户的权限
     var rolePermissions = GetUserPermissions(filterContext.HttpContext);
     //待访问的Action的Permission
     var action = new ApplicationPermission
     {
         Action = filterContext.ActionDescriptor.ActionName,
         Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
         Description = ActionPermissionService.GetDescription(filterContext.ActionDescriptor)
     };
     //是否授权
     return rolePermissions.Contains(action, new ApplicationPermissionEqualityComparer());
 }
        /// <summary>
        /// 使用反射,获取Action的信息
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApplicationPermission> GetAllActionByAssembly_01()
        {
            var result = new List<ApplicationPermission>();
            //取程序集中的全部类型
            var types = Assembly.Load("AspNetIdentity2Permission.Mvc").GetTypes();

            foreach (var type in types)
            {
                if (type.BaseType.Name == "BaseController")//如果是BaseController
                {
                    //取类型的方法,类型为实例方法,公共方法
                    var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public);
                    foreach (var method in methods)
                    {
                        //因存在异步与同步方法,所以统一用返回类型的tostring方法
                        var returnType = method.ReturnType.ToString();

                        if (returnType.Contains("ActionResult"))//如果是ActionResult
                        {
                            var ap = new ApplicationPermission()
                            {
                                Action = method.Name,
                                Controller = method.DeclaringType.Name.Substring(0, method.DeclaringType.Name.Length - 10), /* 去掉“Controller”后缀*/
                                Params = FormatParams(method)
                            };
                            //取Action的描述
                            var attrs = method.GetCustomAttributes(typeof(DescriptionAttribute), true);
                            if (attrs.Length > 0)
                                ap.Description = (attrs[0] as DescriptionAttribute).Description;

                            result.Add(ap);
                        }
                    }
                }
            }
            return result;
        }
        public async Task<ActionResult> Create(PermissionViewModel permissionViewModel, params string[] selectedRoles)
        {
            if (ModelState.IsValid)
            {
                var permission = new ApplicationPermission(permissionViewModel.Name);
                var permissionresult = await PermissionManager.CreateAsync(permission);
                //Add Permission to the selected Roles 
                if (permissionresult.Succeeded)
                {
                    if (selectedRoles != null)
                    {
                        var result = await PermissionManager.AddToRolesAsync(permission.Id, selectedRoles);
                        if (!result.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First());
                            ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
                            return View();
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", permissionresult.Errors.First());
                    ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
                    return View();

                }
                return RedirectToAction("Index");
            }
            ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
            return View();
        }
Exemplo n.º 26
0
        public static void Initialize(ApplicationDbContext context)
        {
            #region Contracts

            if (context == null)
            {
                throw new ArgumentNullException();
            }

            #endregion

            #region 產生人員權限管理物件(Manager)
            #region 使用者物件
            ApplicationUserManager userManager = ApplicationUserManager.Create(context);
            #endregion
            #region 角色物件
            ApplicationRoleManager roleManager = ApplicationRoleManager.Create(context);
            #endregion
            #region 讀取權限物件
            ApplicationPermissionManager permissionManager = ApplicationPermissionManager.Create(context);
            #endregion
            #endregion

            #region 初始化人員權限管理(Initialize)
            try
            {
                ReadJsonFile rjf = new ReadJsonFile();
                rjf.Action(JsonFile, out string[] UserName, out string[] UserPassword, out string[] Role, out string[] Permission);
                #region 預設的使用者(Default - User)
                string adminUserName     = UserName[0];
                string adminUserPassword = UserPassword[0];

                string guestUserName     = UserName[1];
                string guestUserPassword = UserPassword[1];
                #endregion
                #region 預設的角色(Default - Role)
                string adminRoleName = Role[0];
                string guestRoleName = Role[1];
                #endregion
                #region 預設的讀取權限(Default - Permission)
                string accessPermissionName        = Permission[0];
                string contactPermissionName       = Permission[1];
                string productAddPermissionName    = Permission[2];
                string productRemovePermissionName = Permission[3];
                #endregion
                #region 新增預設的使用者(Setup Default - User)
                var adminUser = userManager.FindByName(adminUserName);
                if (adminUser == null)
                {
                    adminUser = new ApplicationUser {
                        UserName = adminUserName, Email = adminUserName
                    };
                    userManager.Create(adminUser, adminUserPassword);
                    userManager.SetLockoutEnabled(adminUser.Id, false);
                }

                var guestUser = userManager.FindByName(guestUserName);
                if (guestUser == null)
                {
                    guestUser = new ApplicationUser {
                        UserName = guestUserName, Email = guestUserName
                    };
                    userManager.Create(guestUser, guestUserPassword);
                    userManager.SetLockoutEnabled(guestUser.Id, false);
                }
                #endregion
                #region 新增預設的角色(Setup Default - Role)
                var adminRole = roleManager.FindByName(adminRoleName);
                if (adminRole == null)
                {
                    adminRole = new ApplicationRole(adminRoleName);
                    roleManager.Create(adminRole);
                }

                var guestRole = roleManager.FindByName(guestRoleName);
                if (guestRole == null)
                {
                    guestRole = new ApplicationRole(guestRoleName);
                    roleManager.Create(guestRole);
                }
                #endregion
                #region 新增預設的讀取權限(Setup Default - Permission)
                var accessPermission = permissionManager.FindByName(accessPermissionName);
                if (accessPermission == null)
                {
                    accessPermission = new ApplicationPermission(accessPermissionName);
                    permissionManager.Create(accessPermission);
                }

                var contactPermission = permissionManager.FindByName(contactPermissionName);
                if (contactPermission == null)
                {
                    contactPermission = new ApplicationPermission(contactPermissionName);
                    permissionManager.Create(contactPermission);
                }

                var productAddPermission = permissionManager.FindByName(productAddPermissionName);
                if (productAddPermission == null)
                {
                    productAddPermission = new ApplicationPermission(productAddPermissionName);
                    permissionManager.Create(productAddPermission);
                }

                var productRemovePermission = permissionManager.FindByName(productRemovePermissionName);
                if (productRemovePermission == null)
                {
                    productRemovePermission = new ApplicationPermission(productRemovePermissionName);
                    permissionManager.Create(productRemovePermission);
                }
                #endregion
                #region 導入角色給預設的使用者(UserAddToRole)
                IList <string> rolesForUser = null;

                rolesForUser = userManager.GetRoles(adminUser.Id);
                if (rolesForUser.Contains(adminRole.Name) == false)
                {
                    userManager.AddToRole(adminUser.Id, adminRole.Name);
                }

                rolesForUser = userManager.GetRoles(guestUser.Id);
                if (rolesForUser.Contains(guestRole.Name) == false)
                {
                    userManager.AddToRole(guestUser.Id, guestRole.Name);
                }
                #endregion
                #region 導入讀取權限給角色(PermissionAddToRole)
                IList <string> rolesForPermission = null;

                rolesForPermission = permissionManager.GetRolesById(accessPermission.Id);
                if (rolesForPermission.Contains(adminRole.Name) == false)
                {
                    permissionManager.AddToRole(accessPermission.Id, adminRole.Name);
                }

                rolesForPermission = permissionManager.GetRolesById(contactPermission.Id);
                if (rolesForPermission.Contains(adminRole.Name) == false)
                {
                    permissionManager.AddToRole(contactPermission.Id, adminRole.Name);
                }

                rolesForPermission = permissionManager.GetRolesById(productAddPermission.Id);
                if (rolesForPermission.Contains(adminRole.Name) == false)
                {
                    permissionManager.AddToRole(productAddPermission.Id, adminRole.Name);
                }

                rolesForPermission = permissionManager.GetRolesById(productRemovePermission.Id);
                if (rolesForPermission.Contains(adminRole.Name) == false)
                {
                    permissionManager.AddToRole(productRemovePermission.Id, adminRole.Name);
                }
                #endregion
            }
            finally
            {
                // Dispose
                userManager.Dispose();
                roleManager.Dispose();
                permissionManager.Dispose();
            }
            #endregion
        }
Exemplo n.º 27
0
        /*  public List<ApolloUser> GetAllUsersBasedOnUserType(Domain.Enum.UserType userType)
         * {
         *   return _userRepository.FindSupportUsers(user => user.UserTypeId == (int)userType).ToList();
         *  // return _userRepository.GetSupportUsers();
         * }
         */
        public UserDetails GetUserDetails(Guid id)
        {
            var user        = _userRepository.Get(id);
            var userDetails = new UserDetails()
            {
                Id          = user.Id,
                Email       = user.Email,
                UserName    = user.UserName,
                FirstName   = user.FirstName,
                LastName    = user.LastName,
                IsActive    = user.IsActive,
                UserTypeId  = user.UserTypeId,
                PhoneNumber = user.PhoneNumber,
            };
            var applicationPermissions = new List <ApplicationPermission>();

            foreach (var userAppRole in user.UserAppRoleMappings)
            {
                List <RolePrivilege> roleDetails = new List <RolePrivilege>();

                if (userDetails.UserTypeId == (int)Apollo.Domain.Enum.UserType.SupportUser)
                {
                    roleDetails =
                        _roleRepository.GetRelatedPrivilegesForRoleAndApp(userAppRole.RoleId, userAppRole.ApplicationId);
                }
                else if (userDetails.UserTypeId == (int)Apollo.Domain.Enum.UserType.SocietyUser)
                {
                    roleDetails =
                        _roleRepository.GetRelatedPrivilegesForRoleAppAndSociety
                            (userAppRole.RoleId, userAppRole.ApplicationId, userAppRole.SocietyId);
                }

                if (roleDetails.Count > 0)
                {
                    var applicationPermission = new ApplicationPermission();
                    applicationPermission.Id     = userAppRole.ApplicationId;
                    applicationPermission.Name   = roleDetails[0].ApplicationName;
                    applicationPermission.RoleId = userAppRole.Role.Id;
                    applicationPermission.Role   = roleDetails[0].RoleName;

                    Dictionary <int, FeaturePermission> featurePermissions = new Dictionary <int, FeaturePermission>();
                    foreach (var roleDetail in roleDetails)
                    {
                        FeaturePermission featurePermission = new FeaturePermission();
                        featurePermission.FeatureTypeId   = roleDetail.FeatureTypeId;
                        featurePermission.TypeName        = roleDetail.FeatureTypeName;
                        featurePermission.Label           = roleDetail.FeatureLabel;
                        featurePermission.ParentFeatureId = roleDetail.ParentFeatureId;
                        featurePermission.Order           = roleDetail.Order;
                        featurePermission.Privileges      = roleDetail.Privileges;

                        applicationPermission.FeaturesList.Add(featurePermission);
                    }

                    applicationPermissions.Add(applicationPermission);
                }
            }

            userDetails.ApplicationPermissions = applicationPermissions;
            return(userDetails);
        }
Exemplo n.º 28
0
        public static async Task InitializeDb(ApplicationDbContext context, UserManager <ApplicationUser> userManager, RoleManager <ApplicationRole> roleManager)
        {
            //context.Database.Migrate();
            //context.Database.EnsureCreated();
            // Add roles
            if (!await context.Roles.AnyAsync(r => string.Equals(r.Name, "System Administrator", StringComparison.OrdinalIgnoreCase)))
            {
                await roleManager.CreateAsync(new ApplicationRole { Name = "System Administrator", IsSysAdmin = true });
            }
            // Add Admin user
            var adminUser = userManager.Users.FirstOrDefault(u => string.Equals(u.UserName, "*****@*****.**", StringComparison.OrdinalIgnoreCase));

            if (adminUser == null)
            {
                adminUser = new ApplicationUser
                {
                    UserName  = "******",
                    Email     = "*****@*****.**",
                    FirstName = "Super",
                    LastName  = "Admin"
                };
                var result = await userManager.CreateAsync(adminUser, "P@ssword1");

                if (result != IdentityResult.Success)
                {
                    throw new Exception($"Unable to create '{adminUser.UserName}' account: {result}");
                }
            }
            await userManager.SetLockoutEnabledAsync(adminUser, false);

            // Check AdminUserRoles
            var adminRoles = await userManager.GetRolesAsync(adminUser);

            if (!adminRoles.Any(r => string.Equals(r, "System Administrator")))
            {
                await userManager.AddToRoleAsync(adminUser, "System Administrator");
            }


            #region [STI Seed]

            var AJMPUserRolePermission = new string[] { "Administrator", "User" };

            foreach (var rolePermission in AJMPUserRolePermission)
            {
                if (!await context.Roles.AnyAsync(r => string.Equals(r.Name, rolePermission, StringComparison.OrdinalIgnoreCase)))
                {
                    var userRole = new ApplicationRole {
                        Name = rolePermission, IsSysAdmin = false, CreatedBy = adminUser.Id
                    };
                    await roleManager.CreateAsync(userRole);

                    if (!await context.ApplicationPermission.AnyAsync(r => string.Equals(r.ApplicationPermission_Id, rolePermission, StringComparison.OrdinalIgnoreCase)))
                    {
                        var role = context.ApplicationRole.Where(x => x.Name == userRole.Name).FirstOrDefault();
                        if (role != null)
                        {
                            var permission = new ApplicationPermission {
                                ApplicationPermission_Id = rolePermission, CreatedBy = adminUser.Id
                            };
                            context.ApplicationPermission.Add(permission);
                            await context.SaveChangesAsync();

                            if (!context.ApplicationRole_ApplicationPermission.Where(x => x.RoleId == userRole.Id && x.ApplicationPermissionId == permission.Id).Any())
                            {
                                context.ApplicationRole_ApplicationPermission.Add(new ApplicationRole_ApplicationPermission {
                                    ApplicationPermissionId = permission.Id, RoleId = userRole.Id
                                });
                                await context.SaveChangesAsync();
                            }
                        }
                    }
                }
            }
            #endregion
        }