public Operator(Rights rights, int id, string name, string lastName) { Rights = rights; Id = id; Name = name; LastName = lastName; }
public MenuLinkStructure(Rights right, string userName, Func<string, Rights, RightOperation, bool> userHasRightFunc) { Right = right; this.userName = userName; this.userHasRightFunc = userHasRightFunc; }
/// <summary> /// Базовый конструктор /// </summary> /// <param name="xml">xml-описание</param> public User(string xml) : base(xml) { var user = new XmlDocument(); user.LoadXml(xml); var priv = user.GetElementsByTagName("privilegies")[0].InnerText; try { UserRights = (Rights)Enum.Parse(typeof(Rights), priv, true); } catch { UserRights = Rights.guest; } }
public AuthorizationFilter(IRightService rightService, ISettingService settingService, IUserService userService, Rights requiredRight, params RightOperation[] requiredRightOperations) { _rightService = rightService; _settingService = settingService; _userService = userService; _requiredRight = requiredRight; _requiredRightOperations = requiredRightOperations; }
/// <summary> /// Задать права пользователю на терминале /// </summary> /// <param name="r"></param> public void SetUserRights(Rights r) { if (SelectedUser == null) Logger.Error("Выберите пользователя на терминале " + id, Log ? LogType.File : LogType.Screen); else { Logger.Info(String.Format("Пользователь {0}, текущие права: {1}",SelectedUser.id,Enum.GetName(typeof(Rights),SelectedUser.UserRights).ToLower()), Log ? LogType.File : LogType.Screen); Users.Find(delegate(User t) { return t.id.ToLower() == SelectedUser.id.ToLower(); }).UserRights = r; Logger.Info(String.Format("Пользователь {0}, новые права: {1}",SelectedUser.id,Enum.GetName(typeof(Rights),SelectedUser.UserRights).ToLower()), Log ? LogType.File : LogType.Screen); } }
public void beforAfterchk(RolesRights roles, Rights right) { for (int m = 0; m < right.beforAfterchk.Length; m++) { if (right.beforAfterchk[m] != "") { string[] parentwithIDs = right.beforAfterchk[m].Split('+'); // connect(); SqlCommand cmd = new SqlCommand("update RoleRights set RowStatus=1 where HospitalID=" + HospitalID + " and LocationID=" + LocationID + " and RowStatus=0 and RoleID=" + roles.RoleID + " and RightCode=" + parentwithIDs[1].ToString() + " and ModuleID=" + parentwithIDs[0].ToString() + "", con); int a = cmd.ExecuteNonQuery(); } } // con.Open(); }
public Entry(ImName _imName, List <ImImage> _imImage, Summary _summary, ImPrice _imPrice, ImContentType _imContentType, Rights _rights, Title _title, Link _link, Id _id, ImArtist _imArtist, Category _category, ImReleaseDate _imReleaseDate) { imName = _imName; imImage = _imImage; summary = _summary; imPrice = _imPrice; imContentType = _imContentType; rights = _rights; title = _title; link = _link; id = _id; imArtist = _imArtist; category = _category; imReleaseDate = _imReleaseDate; }
protected override object ExecuteBody() { var crud = Context.Access((tx) => { var crole = tx.Db[BsonDataModel.GetCollectionName(this.Realm, BsonDataModel.COLLECTION_ROLE)]; var role = new BSONDocument(); role.Set(new BSONStringElement(BsonDataModel._ID, Id)); role.Set(new BSONStringElement(BsonDataModel.FLD_RIGHTS, Rights.ToLaconicString(CodeAnalysis.Laconfig.LaconfigWritingOptions.Compact))); role.Set(new BSONDateTimeElement(BsonDataModel.FLD_CREATEUTC, Context.App.TimeSource.UTCNow)); var cr = crole.Save(role); Aver.IsNull(cr.WriteErrors, cr.WriteErrors?.FirstOrDefault().Message); return(cr); }); return(crud); }
public IActionResult Get(int id) { Rights _right = _rightsRepository.GetSingle(a => a.Id == id); if (_right != null) { RightsViewModel _rightsViewModel = Mapper.Map <Rights, RightsViewModel>(_right); return(new OkObjectResult(_rightsViewModel)); } else { return(NotFound()); } }
/// <summary> /// Get all the rights of an user according to user ID. /// </summary> /// <param name="userId">User Id</param> /// <returns>right information list of an user.</returns> public LinkedList <RightsInfo> getRightsByUserId(int userId) { LinkedList <RightsInfo> rightsInfoList = new LinkedList <RightsInfo>(); IList <Vuserrights> userRightList = this.userRightsDao.DescendOrderFindById(userId); Hashtable infoTable = new Hashtable(); foreach (Vuserrights userRight in userRightList) { RightBasicInfo rightBasicInfo = new RightBasicInfo(); rightBasicInfo.RightUrl = userRight.Righturl; rightBasicInfo.RightName = userRight.Rightname; rightBasicInfo.RightId = userRight.Rightid; rightBasicInfo.RightType = userRight.Righttype; if (infoTable.ContainsKey(userRight.Groupid)) { LinkedList <RightBasicInfo> rightBasicInfoList = infoTable[userRight.Groupid] as LinkedList <RightBasicInfo>; rightBasicInfoList.AddLast(rightBasicInfo); infoTable[userRight.Groupid] = rightBasicInfoList; } else { LinkedList <RightBasicInfo> rightBasicInfoList = new LinkedList <RightBasicInfo>(); rightBasicInfoList.AddLast(rightBasicInfo); infoTable[userRight.Groupid] = rightBasicInfoList; } } foreach (long groupId in infoTable.Keys) { RightsInfo rightsInfo = new RightsInfo(); LinkedList <RightBasicInfo> rightBasicInfoList = infoTable[groupId] as LinkedList <RightBasicInfo>; Rightgroup rightGroup = new Rightgroup(); rightGroup.Id = groupId; rightsInfo.RightGroup = rightGroup; IList <Rights> rightList = new List <Rights>(); foreach (RightBasicInfo rightBasicInfo in rightBasicInfoList) { Rights rightPojo = new Rights(); rightPojo.Rightname = rightBasicInfo.RightName; rightPojo.Righturl = rightBasicInfo.RightUrl; rightPojo.Id = rightBasicInfo.RightId; rightList.Add(rightPojo); } rightsInfo.RightList = rightList; rightsInfoList.AddLast(rightsInfo); } return(rightsInfoList); }
/// <summary> /// <para> /// Validate value is <see cref="Rights"/>. /// </para> /// </summary> /// <param name="value"> /// The <see cref="Rights"/> instance to be validated. /// </param> /// <param name="paramName"> /// The actual parameter name of the argument being checked. /// </param> /// <exception cref="ArgumentException"> /// If the value is not valid <see cref="Rights"/> instance. /// </exception> private static void CheckRights(Rights value, string paramName) { string[] names = Enum.GetNames(typeof(Rights)); Rights values = Rights.Delete; foreach (string name in names) { values |= (Rights)Enum.Parse(typeof(Rights), name); } if (value < Rights.Read || value > values) { throw new ArgumentException( string.Format("{0} is not valid Enum.", paramName), paramName); } }
public IActionResult Create([FromBody] RightsViewModel right) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Rights _newRight = Mapper.Map <RightsViewModel, Rights>(right); _rightsRepository.Add(_newRight); _rightsRepository.Commit(); right = Mapper.Map <Rights, RightsViewModel>(_newRight); return(new OkObjectResult(right)); }
public void Grant(Rights readWrite, string group) { switch(readWrite) { case Rights.ReadWrite: { GrantReadWrite(group); break; } default: { GrantRead(group); break; } } }
public List <Rights> List(int RoleID) { List <Rights> List = new List <Rights>(); try { SqlCon.Open(); var SqlCmd = new SqlCommand("[adm].[uspReadRights]", SqlCon) { CommandType = CommandType.StoredProcedure }; SqlParameter pRoleID = new SqlParameter { ParameterName = "@RoleID", SqlDbType = SqlDbType.Int, Value = RoleID }; SqlCmd.Parameters.Add(pRoleID); using (var dr = SqlCmd.ExecuteReader()) { while (dr.Read()) { var detail = new Rights { WebID = Convert.ToInt32(dr["WebID"]), RoleID = Convert.ToInt32(dr["RoleID"]), DisplayName = dr["DisplayName"].ToString(), RightID = Convert.ToInt32(dr["RightID"]), ReadRight = Convert.ToBoolean(dr["ReadRight"]), WriteRight = Convert.ToBoolean(dr["WriteRight"]) }; List.Add(detail); } } } catch (Exception ex) { throw ex; } if (SqlCon.State == ConnectionState.Open) { SqlCon.Close(); } return(List); }
private static void CreateAccount(List <String> usernames, Rights rights, List <IPAddress> ips) { var accountExists = false; // Check for duplicate usernames. If username exists, add IP. foreach (var username in usernames) { var a = FindAccount(username); if (a != null) { accountExists = true; foreach (var ip in ips) { if (!a.GetIPs( ).Contains(ip)) { a.AddIP(ip); } } a.SetRights(rights); } } // Check for duplicate IPs. If IP exists, add usernames and update rights. if (!accountExists) { foreach (var ip in ips) { var a = FindAccount(ip); if (a != null) { accountExists = true; foreach (var username in usernames) { if (!a.GetUsernames( ).Contains(username)) { a.AddUsername(username); } } a.SetRights(rights); } } } if (!accountExists) { accounts.Add(new Account(usernames, rights, ips)); } }
public void Grant(Rights readWrite, string group) { switch (readWrite) { case Rights.ReadWrite: { GrantReadWrite(group); break; } default: { GrantRead(group); break; } } }
private void _save() { foreach (var aclRightViewmodel in Rights) { if (aclRightViewmodel.IsModified) { aclRightViewmodel.Save(); } } foreach (var right in _originalRights) { if (Rights.All(r => r.Right != right)) { _engine.DeleteRight(right); } } }
/// <summary> /// <para>Initialize _Entities with configuration from given namespace.</para> /// </summary> /// <param name="nameSpace">the namespace to load configuration</param> /// <exception cref="ConfigurationException">if any property value is empty string, /// or if error occurs while reading configuration</exception> private void InitializeEntities(string nameSpace) { string[] entityNames = Helper.GetValues(nameSpace, EntityNamesProperty, false); foreach (string entityName in entityNames) { // for <entityName>_rights string[] rights = Helper.GetValues(nameSpace, entityName + RightsPostfix, false); Rights rightsValue = (Rights)0; foreach (string right in rights) { rightsValue |= (Rights)Enum.Parse(typeof(Rights), right, true); } _Entities[entityName] = rightsValue; } }
/// <summary> /// 权限更新页面 /// </summary> /// <param name="rightID"></param> /// <returns></returns> public ActionResult UpdateRight(string rightID) { Rights data = new Rights(); string resStr = string.Empty; try { UserDbContext udb = new UserDbContext("ConnStr1"); data = udb.GetRights(rightID); } catch (Exception ex) { resStr = MisBase.BaseUT.GetRootException(ex).Message; } return(View(data)); }
/// <summary> /// 加入队列 /// </summary> /// <param name="skewPipe"></param> public void Push(SkewPipe skewPipe) { //这里以X小的为左点,X大的为右点 SkewPipes.Add(skewPipe); var curve = (skewPipe.pipe.Location as LocationCurve).Curve; if (curve.GetEndPoint(0).X < curve.GetEndPoint(1).X) { Lefts.Add(ReferenceCurve.Project(curve.GetEndPoint(0)).XYZPoint); Rights.Add(ReferenceCurve.Project(curve.GetEndPoint(1)).XYZPoint); } else { Lefts.Add(ReferenceCurve.Project(curve.GetEndPoint(1)).XYZPoint); Rights.Add(ReferenceCurve.Project(curve.GetEndPoint(0)).XYZPoint); } }
public async Task <ActionResult <Rights> > Put(Guid id, [FromBody] Rights right) { try { var result = rightRepo.Retrieve().FirstOrDefault(x => x.RightID == id); if (result == null) { return(NotFound()); } await rightRepo.UpdateAsync(id, right); return(Ok(right)); } catch (Exception) { return(BadRequest()); } }
/// <summary> /// Returns whether the SiteMapNode is accessible to the current user. /// </summary> public override bool IsAccessibleToUser(HttpContext context, SiteMapNode node) { // We are only checking Rights here. Roles may also be part of // the SiteMapNode. Let the base class check for that. If false, // return false, otherwise, continue with our check of Rights. if (!base.IsAccessibleToUser(context, node)) { return(false); } if (!Utils.StringIsNullOrWhitespace(node["rights"])) { // By default, all specified Rights must exist. // We allow this to be overridden via the "rightsAuthorizationCheck" // attribute. AuthorizationCheck authCheck = AuthorizationCheck.HasAll; if (!Utils.StringIsNullOrWhitespace(node["rightsAuthorizationCheck"])) { authCheck = Utils.ParseEnum <AuthorizationCheck>(node["rightsAuthorizationCheck"], AuthorizationCheck.HasAll); } string[] rightsRaw = node["rights"].Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries); List <Rights> rightsToCheck = new List <Rights>(); foreach (string r in rightsRaw) { Rights right = Utils.ParseEnum <Rights>(r.Trim(), Rights.None); if (right != Rights.None) { rightsToCheck.Add(right); } } if (rightsToCheck.Count > 0) { return(Security.IsAuthorizedTo(authCheck, rightsToCheck.ToArray())); } } return(true); }
public bool CheckRight(int userId, ContolType type, Rights right) { try { var query = $@"Select [{right}] from setting_policy join users on user_id = {userId} and users.policy_id = setting_policy.policy_id where type_control = {(byte)type}"; Connection.Open(); var outpute = Connection.ExecuteScalar <bool>(query); Connection.Close(); Console.WriteLine($" Succsesful PolicyRepository::CheckRight::Query: {query}"); //log return(outpute); } catch (Exception ex) { Connection.Close(); Console.WriteLine($" Invalide PolicyRepository::CreatePolicy::Query:"); //log Console.WriteLine(ex.Message); return(false); } }
public void HasPrivilege(Rights privilege, Action <bool> callback) { Task.Factory.StartNew(() => { this.GenerateSleep(500, 1500); if (privilege == Rights.ReadOnly) { callback(true); } else if (privilege == Rights.ReadWrite) { callback(true); } else { callback(false); } }); }
/// <summary> /// /// </summary> /// <param name="xml"></param> public UserInfo(string xml) { XmlTextReader xr = new XmlTextReader(new StringReader(xml)); xr.MoveToContent(); while (xr.Read()) { if (xr.Name == "g") { Groups.Add(xr.ReadString()); } else if (xr.Name == "r") { Rights.Add(xr.ReadString()); } } Name = Regex.Match(xml, @"<userinfo name=""(.*?)"">").Groups[1].Value; }
private void InitReaderRights() { var dbr = new DBReader(); DataTable rights = dbr.GetReaderRightsById(this.ID); if (rights.Rows.Count != 0) { foreach (DataRow r in rights.Rows) { switch (r["IDReaderRight"].ToString()) { case "1": this.ReaderRights |= Rights.BRIT; break; case "2": this.ReaderRights |= Rights.HALL; break; case "3": this.ReaderRights |= Rights.EMPL; this.IDDepartment = r["IDOrganization"].ToString(); break; case "4": this.ReaderRights |= Rights.ABON; break; case "5": this.ReaderRights |= Rights.PERS; break; case "6": this.ReaderRights |= Rights.COLL; break; default: this.ReaderRights |= Rights.HALL; break; } } } }
public List <Rights> GetRights() { SqlConnection con = new SqlConnection(ConnectionString); SqlCommand cmd = new SqlCommand("select RightID, RightName from RightsLookupTable", con); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); List <Rights> rightDetails = new List <Rights>(); foreach (DataRow row in dt.Rows) { Rights rights = new Rights(); rights.rightID = Convert.ToInt16(row["RightID"]); rights.rightName = row["RightName"].ToString(); rightDetails.Add(rights); } return(rightDetails); }
public async Task <ActionResult <Rights> > Post([FromBody] Rights right) { try { right.RightID = Guid.NewGuid(); await rightRepo.CreateAsync(right); return(CreatedAtRoute("GetRightByID", new { id = right.RightID }, right)); } catch (Exception) { return(BadRequest()); } }
public void SetListLength(int length) { while (Lefts.Count > length) { Rights.RemoveAt(Lefts.Count - 1); Lefts.RemoveAt(Lefts.Count - 1); Relation.RemoveAt(Lefts.Count - 1); } while (Lefts.Count < length) { Lefts.Add(new QPart { Text = "" }); Rights.Add(new QPart { Text = "" }); Relation.Add(Relation.Count); } }
private void _addRight(object obj) { using (var selector = new SecurityObjectSelectorViewmodel(_authenticationService)) { if (UiServices.ShowDialog <Views.SecurityObjectSelectorView>(selector) != true) { return; } var right = _engine.AddRightFor(selector.SelectedSecurityObject); if (right == null) { return; } var newRightVm = new EngineRightViewmodel(right); Rights.Add(newRightVm); SelectedRight = newRightVm; SelectedRight.Modified += EventRightViewmodel_Modified; IsModified = true; } }
public List <IRights> GetRights() { var lstRepositoryRight = _context.Rights.AsQueryable().ToList(); var lstAbstractRight = new List <IRights>(); if (lstRepositoryRight == null || lstRepositoryRight.Count <= 0) { throw new NullReferenceException(nameof(lstRepositoryRight)); } foreach (Rights right in lstRepositoryRight) { var localRole = new Rights() { RightId = right.RightId, RightName = right.RightName }; lstAbstractRight.Add(localRole); } return(lstAbstractRight); }
private List <Rights> GetRights(XmlNode pageNode) { List <Rights> rightsList = new List <Rights>(); Rights rights; if (pageNode != null && pageNode.ChildNodes.Count > 0) { foreach (XmlNode rightsNode in pageNode.ChildNodes) { foreach (XmlNode rightNode in rightsNode.ChildNodes) { rights = new Rights(); rights.Id = rightNode.Attributes["Key"].Value; rights.Description = rightNode.Attributes["Description"].Value; rightsList.Add(rights); } } } return(rightsList); }
public bool CheckRigth(User user, Rights right) { lock (dataBaseCenter) { MySqlDataAdapter dataAdapter = new MySqlDataAdapter( string.Format( "SELECT {0} FROM Группы WHERE id=(SELECT группа FROM Пользователи WHERE id='{1}')", right, user.id), sqlConnector); DataTable dataTable = new DataTable(); dataAdapter.Fill(dataTable); if (dataTable.Rows.Count > 0 && dataTable.Rows[0].ItemArray[0].ToString() == "1") { return(true); } return(false); } }
/// <summary> /// 增加一个权限,post /// </summary> /// <param name="data"></param> /// <returns></returns> public string AddRight2(Rights data) { try { UserDbContext uc = new UserDbContext("ConnStr1"); uc.AddRight(data); uc.SaveChanges(); //string script = MvcUT.ShowAlertAndHref(this, "增加成功", "AddRight"); return("ok;增加成功"); } catch (Exception ex) { //提示错误信息 string str = MisBase.BaseUT.GetRootException(ex).Message; return("false;" + str); } }
public static Rights MapRightsToRole(string role) { Rights rights = 0; switch (role) { case UserRoles.SYS_ADMIN: rights = Rights.EMPLOYEE | Rights.CUSTOMER; break; case UserRoles.SALES: rights = Rights.SALES | Rights.CUSTOMER; break; case UserRoles.ENGINEER: rights = Rights.PRODUCT | Rights.MANUFACTURE | Rights.REVIEWER; break; case UserRoles.FOLLOW: rights = Rights.SALES | Rights.PRODUCT | Rights.MANUFACTURE; break; case UserRoles.STORAGE: rights = Rights.STORAGE | Rights.PRODUCT; break; case UserRoles.FINANCE: rights = Rights.PRODUCT | Rights.FIN; // TODO 对账单 break; case UserRoles.ADMIN: rights = Rights.EMPLOYEE | Rights.CUSTOMER | Rights.SALES | Rights.STORAGE | Rights.PRODUCT | Rights.MANUFACTURE | Rights.REVIEWER | Rights.FIN; break; case UserRoles.WORKER: default: break; } return(rights); }
public async Task <ActionResult <Rights> > PostRights(Rights rights) { _context.Rights.Add(rights); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { if (RightsExists(rights.RightsId)) { return(Conflict()); } else { throw; } } return(CreatedAtAction("GetRights", new { id = rights.RightsId }, rights)); }
public AuthEntry() { Access = Rights.Read | Rights.Write; }
/// <summary> /// Private constructor for creating a Right instance. /// </summary> /// <param name="Right"></param> /// <param name="RightEnumName"></param> private Right(Rights Right, string RightEnumName) { _flag = Right; _name = RightEnumName; _rolesWithRight = new Dictionary<Guid, List<string>>(); _readOnlyRoles = new Dictionary<Guid, ReadOnlyCollection<string>>(); }
public static extern void WMCreateSyncReader( IntPtr pUnkCert, Rights dwRights, out IWMSyncReader ppSyncReader);
private bool HasRight(Rights rightToAuth, AuthorizationContext filterContext) { #region Original Code kept for ref // helper method to determine ownership, uses factory to get data context, // then check the specified route parameter (property on the attribute) // corresponds to the id of the current user in the database. //using (IAuditableDataContextWrapper dc = this.ContextFactory.GetDataContextWrapper()) //{ // int id = -1; // if (filterContext.RouteData.Values.ContainsKey(this.RouteParameter)) // { // id = Convert.ToInt32(filterContext.RouteData.Values[this.RouteParameter]); // } // string userName = filterContext.HttpContext.User.Identity.Name; // return dc.Table<Participant>().Where(p => p.UserName == userName && p.ParticipantID == id).Any(); //} #endregion switch (rightToAuth) { case Rights.NONE: return true; case Rights.ManageMaster: return _Session.RoleRights.ManageMaster; case Rights.ManageRole: return _Session.RoleRights.ManageRole; case Rights.ManageUser: return _Session.RoleRights.ManageUser; case Rights.DeleteClaim: return _Session.RoleRights.DeleteClaim; case Rights.ViewActivity: return _Session.RoleRights.ViewActivity; case Rights.ManageSetting: return _Session.RoleRights.ManageSetting; case Rights.ArchiveClaim: return _Session.RoleRights.ArchiveClaim; default: return false; } }
/// <summary> /// Returns a Right instance based on the flag. /// </summary> /// <param name="flag"></param> /// <returns></returns> public static Right GetRightByFlag(Rights flag) { Right right = null; if (rightsByFlag.TryGetValue(flag, out right)) { return right; } else { throw new KeyNotFoundException("Unable to find a corresponding right for the given flag"); } }
/// <summary> /// Returns whether or not the current user has the passed in Right. /// </summary> /// <param name="right"></param> /// <returns></returns> public static bool IsAuthorizedTo(Rights right) { return Right.HasRight(right, Security.GetCurrentUserRoles()); }
public static extern SafeFileHandle CreateFile(string lpFileName, Rights dwDesiredAccess, Share dwShareMode, IntPtr lpSecurityAttributes, Disposition dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
/// <summary> /// Sets the permission. /// </summary> /// <param name="right">The right.</param> /// <param name="permission">if set to <c>true</c> [permission].</param> public void SetPermission(Rights right, bool permission) { bitMask.Set((int) right, permission); }
public void Grant(string userName, string environment, Rights rights) { this.client.EnsureLoggedIn(); this.client.Post<BaseResponse>(new { env = environment, user = userName, rights = (int)rights }, "auth/grant/"); }
public void AddUser(string name, Rights r) { if (SelectedTerminal == null) Logger.Error("Сначала необходимо выбрать терминал", log ? LogType.File : LogType.Screen); else { Terminals.Find(delegate(Terminal t) { return t.id.ToLower() == SelectedTerminal.id.ToLower(); }).Users.Add(new User(name, r)); Logger.Info(String.Format("К терминалу {0} подключен пользователь {1} с правами {2}", SelectedTerminal.id, name, Enum.GetName(typeof(Rights),r).ToLower()), log ? LogType.File : LogType.Screen); } }
/// <summary> /// Determines whether the specified right has permission. /// </summary> /// <param name="right">The right.</param> /// <returns> /// <c>true</c> if the specified right has permission; otherwise, <c>false</c>. /// </returns> public bool HasPermission(Rights right) { return bitMask.Get((int) right); }
public static extern int WMCreateReader( IntPtr pUnkCert, Rights dwRights, out IWMReader ppReader );
private static bool CheckAuthentication(AuthenticationResponse response, string salt, out Rights accessRights) { accessRights = 0; if (response.Mode == AuthenticationMode.Guest && Config.AllowUnauthenticatedRead) { accessRights = Rights.Read; if (Config.AllowUnauthenticatedWrite) accessRights |= Rights.Write; return true; } else if (response.Mode == AuthenticationMode.Simple) { var login = Config.GetSimpleLogin(response.IdentifierToken); if (login == null) { string doSomeWork = BCrypt.Net.BCrypt.GenerateSalt(); return false; } else { if (BCrypt.Net.BCrypt.HashPassword(login.Password, salt) == System.Text.ASCIIEncoding.ASCII.GetString(response.Payload)) { accessRights = login.Access; return true; } return false; } } else throw new Exception(string.Format("Unknown authentication mode: {0}", response.Mode)); }
public IsAuthorizeAttribute(Rights rightToAuthenticate) { rightToAuth = rightToAuthenticate; }
public bool IsLinkVisible(Rights right) { return (menuLinkStructs.ContainsKey(right)) ? menuLinkStructs[right].IsVisible : false; }
public bool RoleHasRight(string roleName, Rights right, RightOperation rightOperation) { var userRole = UserRole.GetByName(roleName); foreach (BORoleRightX roleRight in userRole.RoleRights) { if (roleRight.Right.ID == (long)right) { switch (rightOperation) { case RightOperation.Any: return roleRight.CanCreate || roleRight.CanDelete || roleRight.CanExecute || roleRight.CanRead || roleRight.CanUpdate; case RightOperation.Create: return roleRight.CanCreate; case RightOperation.Delete: return roleRight.CanDelete; case RightOperation.Execute: return roleRight.CanExecute; case RightOperation.Read: return roleRight.CanRead; case RightOperation.Update: return roleRight.CanUpdate; default: return false; } } } return false; }
public bool UserHasAnyRight(string userName, Rights right) { return UserHasRight(userName, right, RightOperation.Any); }
public CustomAuthorize(Rights requiredRight, params RightOperation[] requiredRightOperations) { _requiredRight = requiredRight; _requiredRightOperations = requiredRightOperations; }
/// <summary> /// If the current user does not have the requested right, either redirects to the login page, /// or throws a SecurityException. /// </summary> /// <param name="right"></param> /// <param name="redirectToLoginPage"> /// If true and user does not have rights, redirects to the login page. /// If false and user does not have rights, throws a security exception. /// </param> public static void DemandUserHasRight(Rights right, bool redirectToLoginPage) { DemandUserHasRight(AuthorizationCheck.HasAny, redirectToLoginPage, new[] { right }); }
public bool UserHasRight(string userName, Rights right, RightOperation rightOperation) { IEnumerable<BORole> roles = UserRoles(BOUser.GetByGUID(Membership.GetUser(userName).ProviderUserKey.ToString())); foreach (var role in roles) { if (RoleHasRight(role.Name, right, rightOperation)) return true; } return false; }
/// <summary> /// Private constructor for creating a Right instance. /// </summary> /// <param name="Right"></param> /// <param name="RightEnumName"></param> private Right(Rights Right, string RightEnumName) { this._flag = Right; this._name = RightEnumName; this._rolesWithRight = new List<string>(); this._readOnlyRoles = new ReadOnlyCollection<string>(this._rolesWithRight); }
/// <summary> /// Установка прав пользователя на выбранном терминале /// </summary> /// <param name="r">Права пользователя</param> public void SetUserRights(Rights r) { if (SelectedTerminal == null) Logger.Error("Сначала необходимо выбрать терминал", log ? LogType.File : LogType.Screen); else Terminals.Find(delegate(Terminal t) { return t.id.ToLower() == SelectedTerminal.id.ToLower(); }).SetUserRights(r); }
/// <summary> /// Gets whether or not a Right exists within any of the given roles. /// </summary> /// <param name="right"></param> /// <param name="roles"></param> /// <returns> /// /// Use this method instead of GetRights().Contains() as it'll be /// much faster than having to create a new collection of Right instances each time. /// /// </returns> public static bool HasRight(Rights right, IEnumerable<string> roles) { if (roles == null) { throw new ArgumentNullException("roles"); } else if (!roles.Any()) { return false; } else { var validRoles = GetRightByFlag(right).Roles; if (roles.Count() == 1) { // This is faster than intersecting, so this is // special cased. return validRoles.Contains(roles.First(), StringComparer.OrdinalIgnoreCase); } else { return validRoles.Intersect(roles, StringComparer.OrdinalIgnoreCase).Any(); } } }
public bool RoleHasRight(string roleName, Rights permission, RightOperation operation) { BORole userRole = GetRole(roleName); IEnumerable<BORoleRightX> roleRights = GetRoleRights(userRole); foreach (var roleRight in roleRights) { if (roleRight.Right.ID == (long)permission) { switch (operation) { case RightOperation.Any: return roleRight.CanCreate || roleRight.CanDelete || roleRight.CanExecute || roleRight.CanRead || roleRight.CanUpdate; case RightOperation.Create: return roleRight.CanCreate; case RightOperation.Delete: return roleRight.CanDelete; case RightOperation.Execute: return roleRight.CanExecute; case RightOperation.Read: return roleRight.CanRead; case RightOperation.Update: return roleRight.CanUpdate; default: return false; } } } return false; }