/// <summary> /// Gets the roles which could be managed by given principal. /// </summary> /// <param name="user">User for which return roles which he could managed.</param> /// <returns>List of roles which could be managed by the user.</returns> public virtual string[] GetManagedRoles(System.Security.Principal.IPrincipal user) { if (user == null) { throw new ArgumentNullException("user"); } if (user.IsInRole(RoleNames.Administrator)) { return(new[] { RoleNames.Administrator, RoleNames.ClientAdministrator, }); } else if (user.IsInRole(RoleNames.ClientAdministrator)) { return(new[] { RoleNames.ClientAdministrator, }); } else { return(new string[0]); } }
public static bool IsInAnyRole(this System.Security.Principal.IPrincipal user, string Role) { try { if (user.IsInRole(Role)) { return(true); } if (Nebulus.AppConfiguration.Settings.SecurityRoles == null) { var AppUserDb = new ApplicationDbContext(); Nebulus.AppConfiguration.Settings.SecurityRoles = AppUserDb.SecurityRoles.ToList(); } foreach (var role in Nebulus.AppConfiguration.Settings.SecurityRoles.Where(role => role.IdentityRole == Role)) { if (user.IsInRole(role.Name)) { return(true); } } } catch (Exception ex) { AppLogging.Instance.Error("Error Checking Users Role: ", ex); } return(false); }
/* * Efecto: Metodo para saber el rol del usuario logueado * Requiere: System.Security.Principal.IPrincipal user . Con los datos del usuario registrado actualmenten * Retorna: un int. Posible valores: * -1 El usuario no tiene rol o tiene uno distinto a los definidos * 0 Soporte y Calidad * 1 Lider * 2 Tester * 3 Cliente */ public int GetRoleUsuario(System.Security.Principal.IPrincipal user) { int rol = -1; if (user.IsInRole("Lider")) { rol = 1; } else { if (user.IsInRole("Tester")) { rol = 2; } else { if (user.IsInRole("Cliente")) { rol = 3; } else { if (user.IsInRole("Soporte") || (user.IsInRole("Calidad"))) { rol = 0; } } } } return(rol); }
public DafIndexModelFilter(System.Security.Principal.IPrincipal User) : this() { if (User.IsInRole(FixedRoles.DafEvaluator)) { this.Status = Daf.Statuses.Open; } else if (User.IsInRole(FixedRoles.DafReviewer) || User.IsInRole(FixedRoles.AgencyUserAndReviewer) || User.IsInRole(FixedRoles.SerAndReviewer)) { this.Status = Daf.Statuses.EvaluatorSigned; } }
protected void Page_Load(object sender, EventArgs e) { TextBox4.Text = user.Identity.Name.ToString(); if (user.IsInRole("admin") || user.IsInRole("secretary")) { SqlDataSource1.SelectCommand = "SELECT * FROM [inventory];"; GridView1.DataBind(); } else { SqlDataSource1.SelectCommand = "SELECT * FROM [inventory] WHERE [ORDERER] = \"" + user.Identity.Name.ToString() + "\";"; GridView1.DataBind(); } }
private static bool EsEditor() { System.Security.Principal.IPrincipal principle = System.Threading.Thread.CurrentPrincipal; bool isInRole = principle.IsInRole("VisualizadorUNOEE_Editor"); return(isInRole); }
public static bool IsReader(string wocName, System.Security.Principal.IPrincipal user) { if (string.IsNullOrEmpty(wocName)) { return(Roles.IsUserInRole(GeneralAdmins)); } // Der Verzeichnisname ist der erste Partikel in einem WocName string[] levels = wocName.Split('.'); Debug.Assert(levels.Length > 0); // Bilden des Rollennamens in Abhängigkeit vom Verzeichnisnamen string ReaderRoleName = levels[0] + "_Reader"; // Wenn die Rolle nicht existiert, dann haben alle Benutzer lesenden // Zugriff if (!Roles.RoleExists(ReaderRoleName)) { return(true); } else { return(user.IsInRole(ReaderRoleName) || IsWriter(wocName, user)); } }
protected override bool AuthorizeCore(System.Security.Principal.IPrincipal user) { return (user.IsInRole( StringResources.AdministrationViewsStrings.SystemAdministratorRoleName )); }
public static bool IsAdmin(string wocName, System.Security.Principal.IPrincipal user) { if (string.IsNullOrEmpty(wocName)) { return(Roles.IsUserInRole(GeneralAdmins)); } // Der Verzeichnisname ist der erste Partikel in einem WocName string[] levels = wocName.Split('.'); Debug.Assert(levels.Length > 0); // Bilden des Rollennamens in Abhängigkeit vom Verzeichnisnamen string AdminRoleName = levels[0] + "_Admin"; Debug.Assert(Roles.RoleExists(AdminRoleName)); return(user.IsInRole(AdminRoleName) || user.IsInRole(GeneralAdmins)); }
public static IEnumerable <ApplicationUser> GetPatients(this System.Security.Principal.IPrincipal sender) { var allRoles = new ApplicationDbContext().ApplicationRoles.ToList(); var drRole = allRoles.Where(r => r.Name.Equals("Doctor", StringComparison.InvariantCultureIgnoreCase)).Single(); var patientRole = allRoles.Where(r => r.Name.Equals("Patient", StringComparison.InvariantCultureIgnoreCase)).Single(); var recepientRole = sender.IsInRole("Doctor") ? patientRole : drRole; return(new ApplicationDbContext().Users.Where( u => u.Roles.Where(r => r.RoleId.Equals(recepientRole.Id, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault() != null) .OrderBy(u => u.FirstName).ThenBy(u => u.LastName).ToList()); }
public String OBTENER() { try { string INFO = ("Iniciando Método OBTENER ROL "); log.Info("CODIGO : CTRUS1, " + INFO); Thread HILO = new Thread(() => TRAZA.DEPURAR_TRAZA("CTRRE2", log.Logger.Name, "OBTENER", INFO)); HILO.Start(); string ROL = ""; if (USUARIO.IsInRole("Jefe")) { ROL = "Jefe," + ROL; } if (USUARIO.IsInRole("BP")) { ROL = "BP," + ROL; } if (USUARIO.IsInRole("Proveedor")) { ROL = "Proveedor," + ROL; } return(ROL); } catch (Exception ex) { log.ErrorFormat("CODIGO : CTRUS1, Método OBTENER ROL, {0} ", ex.StackTrace); ex.HelpLink = (ex.HelpLink == "" || ex.HelpLink == null ? "CTRUS1" : ex.HelpLink); Thread HILO = new Thread(() => ERROR.ERROR_TRAZA(ex.HelpLink, log.Logger.Name, ex.TargetSite.Name, ex.StackTrace)); HILO.Start(); throw ex; } }
/// <summary> /// 验证权限符SId,如果返回大于0或通过,如果等于0表示没有设置过,如果小于0表示没有通过 /// </summary> /// <param name="sid">权限符SId</param> /// <param name="principal">用户身份</param> /// <returns></returns> public static int IsAuthorization(Guid sid, System.Security.Principal.IPrincipal principal) { if (principal == null) { throw new System.ArgumentNullException("principal"); } if (!principal.IsInRole(UMC.Security.Membership.AdminRole)) { AuthManager wMger = new AuthManager(principal);//as WildcardManager; return(wMger.Check(sid.ToString())[0]); } else { return(1); } }
public static bool IsUserInRole(UserRole roles) { bool isAuthenticated = false; IList <UserRole> userRoles = EnumHelper.ToList <UserRole>(); System.Security.Principal.IPrincipal user = HttpContext.Current.User; foreach (var role in userRoles) { if (!role.IsIncludedIn(roles) || !user.IsInRole(role.ToString())) { continue; } isAuthenticated = true; } return(isAuthenticated); }
// 当前用户是否在限定角色列表中 public static bool IsInRoles(string[] roles) { System.Security.Principal.IPrincipal p = HttpContext.Current.User; if (p == null) { return(false); } foreach (string role in roles) { if (p.IsInRole(role)) { return(true); } } return(false); }
/// <summary> /// Determines whether an IPrinciple has Permission to do something within a PermissionContext. /// </summary> /// <param name="user"></param> /// <param name="permission"></param> /// <param name="within"></param> /// <returns></returns> public static bool Has(this System.Security.Principal.IPrincipal user, PermissionTo permission, PermissionContext within) { bool isInRole = false; foreach (PermissionTo pt in EnumHelper.GetOptions <PermissionTo>()) { if (permission.MatchesFilter(pt)) { isInRole = user.IsInRole(string.Format("{0}_{1}", within.GetStringValue(), pt.GetStringValue())); if (isInRole) { break; } } } return(isInRole); }
public static IEnumerable <SelectListItem> GetRecepients(this System.Security.Principal.IPrincipal sender) { var allRoles = new ApplicationDbContext().ApplicationRoles.ToList(); var drRole = allRoles.Where(r => r.Name.Equals("Doctor", StringComparison.InvariantCultureIgnoreCase)).Single(); var patientRole = allRoles.Where(r => r.Name.Equals("Patient", StringComparison.InvariantCultureIgnoreCase)).Single(); var recepientRole = sender.IsInRole("Doctor") ? patientRole : drRole; var recepients = new ApplicationDbContext().Users.Where( u => u.Roles.Where(r => r.RoleId.Equals(recepientRole.Id, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault() != null); return(recepients.Where(u => !u.UserName.Equals(sender.Identity.Name, StringComparison.InvariantCultureIgnoreCase)) .Select(u => new SelectListItem() { Value = u.Id, Text = u.LastName + ", " + u.FirstName }).OrderBy(m => m.Text)); }
public static WebGridColumn[] StationGridColumns(this HtmlHelper htmlHelper, WebGrid grid) { System.Security.Principal.IPrincipal user = htmlHelper.ViewContext.HttpContext.User; var columns = new List <WebGridColumn>(); columns.Add(grid.Column(columnName: "StationName")); columns.Add(grid.Column( header: "Watches", format: item => htmlHelper.ActionLink(linkText: "Watches", actionName: "/Watch/Index/", routeValues: new { id = item.StationId }), style: "column-action" )); if (user.IsInRole(role: "OPCS")) { columns.Add(grid.Column(header: "", format: (item) => htmlHelper.ActionLink(linkText: "Edit", actionName: "Edit", routeValues: new { id = item.StationId }), style: "column-action")); columns.Add(grid.Column(header: "", format: (item) => htmlHelper.ActionLink(linkText: "Delete", actionName: "Delete", routeValues: new { id = item.StationId }, htmlAttributes: new { oneclick = "return confirm('Are you sure that you want to delete " + item.StationName + "?');" }), style: "column-action")); } return(columns.ToArray()); }
public bool UserHasAccess(System.Security.Principal.IPrincipal user) { if (roles.Count == 0) { return(true); } else { foreach (string role in roles) { if (user.IsInRole(role)) { return(true); } } } return(false); }
/// <summary> /// 批量验证权限 /// </summary> /// <param name="wildcards"></param> /// <returns></returns> public static bool[] IsAuthorization(System.Security.Principal.IPrincipal princ, params string[] wildcards) { bool[] rerValue = new bool[wildcards.Length]; if (wildcards.Length > 0) { if (princ.IsInRole(UMC.Security.Membership.AdminRole)) { for (var i = 0; i < rerValue.Length; i++) { rerValue[i] = true; } return(rerValue); } var list = new List <String>(); foreach (var wildcard in wildcards) { list.Add(wildcard); int l = wildcard.Length - 1; while (l > -1) { switch (wildcard[l]) { case '.': list.Add(wildcard.Substring(0, l) + ".*"); break; } l--; } } var wMger = new AuthManager(princ); var vs = wMger.Check(list.ToArray()); int start = 0, end = 0; for (int i = 1; i < wildcards.Length; i++) { end = list.FindIndex(w => wildcards[i] == w); rerValue[i - 1] = IsAuthorization(vs, start, end); start = end; } rerValue[wildcards.Length - 1] = IsAuthorization(vs, start, vs.Length); } return(rerValue); }
public static ConnectionStringSettings GetConnectionString(System.Security.Principal.IPrincipal user) { if (user.Identity is ClaimsIdentity && (user.IsInRole("OrganisationManager") || user.IsInRole("Register"))) { var identity = (ClaimsIdentity)user.Identity; IEnumerable <Claim> claims = identity.Claims; foreach (var claim in claims) { if (claim.Type == "connectionString") { return(new ConnectionStringSettings("KlantDynamicConnection", claim.Value, "System.Data.SqlClient")); } } return(null); } else { return(null); } }
public static bool IsLimited(System.Security.Principal.IPrincipal user, string[] validRoles = null) { validRoles = validRoles ?? defaultRolesWithoutLimitation; if (user?.Identity?.IsAuthenticated == true) { if (validRoles.Count() == 0) { return(false); } foreach (var role in validRoles) { if (user.IsInRole(role.Trim())) { return(false); } } return(true); } return(true); }
public override async Task ProcessAsync(GetKeyAndModelOutput <long, BatchUpdateView <PlatformGroupRole> > input, Action <IActionResult> done) { var isAdmin = principal.IsInRole("Basic.PlatformUser.Admin"); var update = input.Entity.Entities; Expression <Func <PlatformGroupRole, bool> > scope = x => x.PlatformGroupId == input.Key; if (!isAdmin) { var ids = await Context.Set <PlatformGroup>().Where(x => x.PlatformUserGroups.Any(y => y.PlatformUserId == user.Id) || x.CreatedBy == user.Id).Select(x => x.Id).ToArrayAsync(); update = update.Where(x => ids.Contains(x.PlatformGroupId)).ToArray(); scope = x => x.PlatformGroupId == input.Key && ids.Contains(x.PlatformGroupId); } Context.UpdateSet(update, scope, (a, b) => a.FunctionCode == b.FunctionCode && a.FunctionRoleCode == b.FunctionRoleCode, (o, n) => { o.Permission = n.Permission; }); await Context.SaveChangesAsync(); done(new OkResult()); }
//private string[] getResourceRolePermissions(string method) //{ // return AuthUtils.getResourceRolePermissions(Name, method); //} //public bool IsUserInRole(string roleKey) //{ // return AuthUtils.IsUserInRole(roleKey); //} public static bool IsUserInRole(System.Security.Principal.IPrincipal user, string roleKey) { System.Collections.Specialized.NameValueCollection appSettings = System.Configuration.ConfigurationManager.AppSettings; for (int x = 0; x < appSettings.Count; x++) { string thisKey = appSettings.Keys[x]; if (string.Compare(thisKey, roleKey, true) == 0) { string[] roleGroups = Settings.Get(thisKey).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (int y = 0; y < roleGroups.Length; y++) { if (roleGroups[y] != null && roleGroups[y] != string.Empty) { if (user.IsInRole(roleGroups[y])) { return(true); } } } } } return(false); }
public static bool IfInRoles(System.Security.Principal.IPrincipal user, params string[] roles) { bool show = false; if (roles.Count() > 0) { if (user?.Identity?.IsAuthenticated == true) { foreach (var r in roles) { if (user.IsInRole(r)) { show = true; break; } } } } else { show = true; } return(show); }
public IMenuActionLink[] GetMenuItems(string local) { System.Security.Principal.IPrincipal principal = System.Threading.Thread.CurrentPrincipal; return(actionLinks.OrderBy(l => l.DisplayOrder).Where(l => l.MenuLocal == local && (l.Requires == null || l.Requires.Any(r => principal.IsInRole(r)))).ToArray()); }
/// <summary> /// Check Quyền user truy cập từng trang /// </summary> /// <param name="context"></param> /// <param name="node"></param> /// <returns></returns> public override bool IsAccessibleToUser(System.Web.HttpContext context, System.Web.SiteMapNode node) { if (node == null) { throw new System.ArgumentNullException("node"); } if (context == null) { throw new System.ArgumentNullException("context"); } if (!this.SecurityTrimmingEnabled) { return(true); } //add node vao listNode if (!ProviderAllNode.Contains(node)) { ProviderAllNode.Add(node.Clone()); } //check thuong tinh visible bool isVisible; if (bool.TryParse(node["visible"], out isVisible)) { if (isVisible) { return(false); } } SiteMapNodeCollection lstNode = new SiteMapNodeCollection(); System.Collections.IList roles = node.Roles; System.Security.Principal.IPrincipal user = context.User; string strDeny = node["deny"]; //check deny if (strDeny != null) { string[] lstDeny = strDeny.Split(','); for (int i = 0; i < lstDeny.Length; i++) { if (lstDeny[i].Trim() == "*") { return(false); } if (user != null) { if (user.IsInRole(lstDeny[i].Trim())) { return(false); } } else if (lstDeny[i].Trim() == "?") { return(false); } } } if (roles == null || roles.Count == 0) { return(true); } if (user == null) { return(false); } foreach (string role in roles) { if ((role == "*") || user.IsInRole(role)) { return(true); } } return(false); }
public bool IsInRole(System.Security.Principal.IPrincipal user, string role) { return(user.IsInRole(role)); }
public override void ProcessActivity(WebRequest request, WebResponse response) { WebMeta user = this.AsyncDialog(d => { WebMeta sendValue = request.SendValues ?? request.Arguments; if (sendValue.Count > 0) { return(this.DialogValue(sendValue)); } UIFormDialog dialog = new UIFormDialog() { Title = "账户登录" }; dialog.AddText("账户", "Username", ""); dialog.AddPassword("账户密码", "Password", ""); dialog.Submit("确认登录", request, "Cashier"); return(dialog); }, "Login"); String username = user.Get("Username"); String Password = user.Get("Password"); if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(Password)) { this.Prompt("请输入用户名和密码"); } int maxTimes = 5; Membership userManager = Membership.Instance(); int times = userManager.Password(username, Password, maxTimes); switch (times) { case 0: String client = "POSClient"; if (request.IsApp) { client = "Mobile"; } Identity iden = userManager.Identity(username); System.Security.Principal.IPrincipal principal = iden; if (principal.IsInRole(UMC.Security.Membership.UserRole) == false) { this.Prompt("您不是门店内部人员,不能从此登录。"); } AccessToken.Login(iden, AccessToken.Token.Value, client, true); this.Context.OnReset(); this.Prompt("登录成功", false); WebMeta print = new UMC.Web.WebMeta(); print["Alias"] = iden.Alias; print["Src"] = Data.WebResource.Instance().ImageResolve(iden.Id.Value, "1", 5); print["type"] = "Cashier"; this.Context.Send(print, true); //this.Context.Send("Cashier", true); break; case -4: this.Prompt("您的账户已经禁用"); break; case -3: this.Prompt("无此子账户"); break; case -2: this.Prompt("您的用户已经锁定,请您联系管理员解锁"); break; case -1: this.Prompt("您的用户不存在,请确定用户名", false); break; default: this.Prompt(String.Format("您的用户和密码不正确,您还有{0}次机会", maxTimes - times), false); break; } }
public static List <Common.CommModels.Menu> Menus(this System.Security.Principal.IPrincipal p) { var menus = new List <Common.CommModels.Menu>(); if (p.IsInRole(SysRole.UserManageRead) || p.IsInRole(SysRole.EUserManageRead)) { menus.Add(new Common.CommModels.Menu { Name = "用户管理", Title = "用户管理", Url = "~/UserManage/Index", IconImage = "yonghu" }); } if (p.IsInRole(SysRole.RoleManageRead) || p.IsInRole(SysRole.ERoleManageRead)) { menus.Add(new Common.CommModels.Menu { Name = "权限管理", Title = "权限管理", Url = "~/RoleManage/Index", IconImage = "moban" }); } if (p.IsInRole(SysRole.EnterpriseManageRead) || p.IsInRole(SysRole.EEnterpriseManageRead)) { menus.Add(new Common.CommModels.Menu { Name = "企业管理", Title = "企业管理", Url = "~/EnterpriseManage/Index", IconImage = "iconqyxx" }); } //if (p.IsInRole(SysRole.EHomePageModularsManageRead)) //{ // menus.Add(new Common.CommModels.Menu { Name = "公司首页", Title = "公司首页", Url = "~/EnterpriseManage/Info", IconImage = "shouyeshouye" }); //} if (p.IsInRole(SysRole.CardManageRead) || p.IsInRole(SysRole.ECardManageRead)) { menus.Add(new Common.CommModels.Menu { Name = "名片管理", Title = "名片管理", Url = "~/CardManage/Index", IconImage = "mingpianliebiao" }); } if (p.IsInRole(SysRole.EProductKindManageRead)) { menus.Add(new Common.CommModels.Menu { Name = "商品分类管理", Title = "商品分类管理", Url = "~/ProductKindsManage/Index", IconImage = "fenlei-" }); } if (p.IsInRole(SysRole.ProductManageRead) || p.IsInRole(SysRole.EProductManageRead)) { menus.Add(new Common.CommModels.Menu { Name = "商品管理", Title = "商品管理", Url = "~/ProductsManage/Index", IconImage = "shangpin" }); } if (p.IsInRole(SysRole.EHomePageModularsManageRead)) { menus.Add(new Common.CommModels.Menu { Name = "公司主页", Title = "公司主页", Url = "~/HomePageModularsManage/Index", IconImage = "shouyeshouye" }); } if (p.IsInRole(SysRole.ECustomerTabGroupsManageRead)) { menus.Add(new Common.CommModels.Menu { Name = "客户标签分组", Title = "客户标签分组", Url = "~/CustomerTabGroupsManage/Index", IconImage = "fenzu" }); } if (p.IsInRole(SysRole.CustomerTabManageRead) || p.IsInRole(SysRole.ECustomerTabManageRead)) { menus.Add(new Common.CommModels.Menu { Name = "客户标签", Title = "客户标签", Url = "~/CustomerTabsManage/Index", IconImage = "biaoqian" }); } if (p.IsInRole(SysRole.ArticlesManageRead) || p.IsInRole(SysRole.EArticlesManageRead)) { menus.Add(new Common.CommModels.Menu { Name = "动态管理", Title = "动态管理", Url = "~/ArticlesManage/Index", IconImage = "gongsidongtai" }); } return(menus); }
bool Verify(string model, string cmd) { if (this.IsVerify.HasValue == false) { this.IsVerify = this.Session.IsAuthorization(model, cmd); if (this.IsVerify == true) { return(true); } String key = String.Format("{0}.{1}", model, cmd); WebAuthType authType = WebAuthType.Check; if (WebRuntime.authKeys.ContainsKey(key)) { authType = WebRuntime.authKeys[key]; } else if (WebRuntime.authKeys.ContainsKey(model)) { authType = WebRuntime.authKeys[model]; } var user = UMC.Security.Identity.Current; System.Security.Principal.IPrincipal principal = user;// WebADNuke.Security.Identity.Current; switch (authType) { case WebAuthType.All: this.IsVerify = true; return(true); case WebAuthType.User: if (principal.IsInRole(Security.Membership.UserRole)) { this.IsVerify = true; return(true); } break; case WebAuthType.UserCheck: if (principal.IsInRole(Security.Membership.AdminRole)) { this.IsVerify = true; return(true); } else if (principal.IsInRole(Security.Membership.UserRole)) { if (UMC.Security.AuthManager.IsAuthorization(key)) { this.IsVerify = true; return(true); } } break; case WebAuthType.Check: if (principal.IsInRole(Security.Membership.AdminRole)) { this.IsVerify = true; return(true); } else if (user.IsAuthenticated) { if (UMC.Security.AuthManager.IsAuthorization(key)) { this.IsVerify = true; return(true); } } break; case WebAuthType.Admin: if (principal.IsInRole(Security.Membership.AdminRole)) { this.IsVerify = true; return(true); } break; case WebAuthType.Guest: if (user.IsAuthenticated) { this.IsVerify = true; return(true); } else { this.OuterHeaders = new Hashtable(); this.ClientEvent = WebEvent.Prompt | WebEvent.DataEvent; this.OuterHeaders["Prompt"] = new WebMeta().Put("Title", "提示", "Text", "您没有登录,请登录"); this.OuterHeaders["DataEvent"] = new WebMeta().Put("type", "Login"); return(false); } } this.OuterHeaders = new Hashtable(); this.ClientEvent = WebEvent.Prompt; //| WebEvent.DataEvent; if (principal.IsInRole(Security.Membership.UserRole) == false) { this.OuterHeaders["Prompt"] = new WebMeta().Put("Title", "提示", "Text", "您没有登录或权限受限"); this.ClientEvent = WebEvent.Prompt | WebEvent.DataEvent; this.OuterHeaders["DataEvent"] = new WebMeta().Put("type", "Close"); } else { this.OuterHeaders["Prompt"] = new WebMeta().Put("Title", "提示", "Text", "您的权限受限,请与管理员联系"); } return(false); } return(true); }