public GestioneErrore(string nomeFileLog, UserRoles utente) { try { if(utente != null) _utente = utente; FileInfo fileLog = new FileInfo(nomeFileLog); if (!fileLog.Exists) { //Crea il file if(!fileLog.Directory.Exists) { fileLog = new FileInfo(Path.GetTempPath() + "\\AppDown.log"); } _writerLog = fileLog.CreateText(); _writerLog.WriteLine("-----------------------------------------------------------"); _writerLog.WriteLine("Log di verifica della Application. Creato il:" + DateTime.Now.ToShortDateString() + " alle: " + DateTime.Now.ToShortTimeString()); _writerLog.WriteLine("-----------------------------------------------------------"); } else { _writerLog = fileLog.AppendText(); } } catch { _errore = true; } }
public bool HasRole(UserRoles ur) { bool hasrole = false; if (AssignedUserRole == ur) hasrole = true; return hasrole; }
public int EvaluateMediaRequestStatus(MediaRequestLevel levelOfRequest, UserRoles userRole) { if (levelOfRequest == MediaRequestLevel.Initiate && userRole == UserRoles.agency) return (int)MediaRequestStatus.SentToOwner; else if (levelOfRequest == MediaRequestLevel.Initiate && (userRole == UserRoles.user || userRole == UserRoles.mediaAdmin)) return (int)MediaRequestStatus.SentToOriginator; else return 0; }
private Account(string firstName, string lastName, string email, string userName, string password, UserRoles accountType) { this.FirstName = firstName; this.LastName = lastName; this.Email = email; this.UserName = userName; this.Password = password; //this.AddRole(accountType); }
/// <summary> /// Creates new credentials instance. /// </summary> /// <param name="id">User Id.</param> /// <param name="userName">User Name.</param> /// <param name="email">User Email Address.</param> /// <param name="role">User role.</param> /// <param name="password">User Password.</param> /// <param name="salt">Password salt.</param> /// <param name="enabled">Sets if user credentials are enabled.</param> public DbCredentials(int id, string userName, string email, UserRoles role, byte[] password, byte[] salt, bool enabled) { this.UserId = id; this.UserName = userName; this.Email = email; this.Role = role; this.Password = password; this.Salt = salt; this.Enabled = enabled; }
public void AssignAccountToRole( string userName, UserRoles role) { var rawRoleList = role.ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var rawRole in rawRoleList) { if (!Roles.RoleExists(rawRole.Trim())) { Roles.CreateRole(rawRole); } if (!Roles.IsUserInRole(userName, rawRole)) { Roles.AddUserToRole(userName, rawRole); } } }
protected bool IsRole(UserRoles role) { var user = User.Identity.Name; var username = db.Teachers.SingleOrDefault(t => t.Username == user && t.Role == role); if (username != null) { return true; } return false; }
/// <summary> /// Set access depending of userRole /// </summary> /// <param name="userRole"></param> public void SetAccess(UserRoles userRole) { DisableAllControls(); bool hasLoggedUser = false; switch (userRole) { case UserRoles.Patient: { EnableAllControls(); menuItemAdmin.Visible = false; menuItemCurrentPatient.Visible = true; menuItemCurrentDoctor.Visible = false; menuItemPatients.Visible = false; hasLoggedUser = true; }; break; case UserRoles.Doctor: { throw new NotSupportedException("Влизането на потребители от тип \"Лекар\" \n не се поддържа от тази версия на системата!"); EnableAllControls(); menuItemAdmin.Visible = false; menuItemDoctors.Visible = false; menuItemCurrentPatient.Visible = false; hasLoggedUser = true; }; break; case UserRoles.Admin: { throw new NotSupportedException("Влизането на потребители от тип \"Админ\" \n не се поддържа от тази версия на системата!"); EnableAllControls(); menuItemCurrentPatient.Visible = true; menuItemCurrentDoctor.Visible = false; hasLoggedUser = true; }; break; default: { DisableAllControls(); hasLoggedUser = false; } break; } if (hasLoggedUser) { string currentUserName = Membership.CurrentUser.UserName; labelStatusLoggedUser.Text = currentUserName; } SetLoginMenuItemCaption(hasLoggedUser); }
protected void Save_Click(object sender, EventArgs e) { if (this.IsValid) { TopRockUser _user = new TopRockUser(this.ConnectionString); UserRoles _role; if (ViewState["UserId"] != null) { _user.LitePopulate(Convert.ToInt32(ViewState["UserId"]), true); _role = (UserRoles)_user.Roles[0]; } else { _role = new UserRoles(this.ConnectionString); _user.Roles.Add(_role); } _role.RoleId = Convert.ToInt32(dd_Role.SelectedValue); _user.Email = txt_Email.Text; _user.FirstName = txt_Fname.Text; _user.LastName = txt_Lname.Text; if (!String.IsNullOrEmpty(txt_NewPassword.Text)) { _user.Password = txt_NewPassword.Text; } _user.Active = ch_Active.Checked; TopRockUser.enumRegisterStatus _ret = _user.SaveUser(true, null); if (_ret == TopRockUser.enumRegisterStatus.Error) { lbl_Error.Text = "An unexpected error has occurred. Please try again."; lbl_Error.Visible = true; } else if (_ret == TopRockUser.enumRegisterStatus.EmailExists) { lbl_Error.Text = "That email is already in use under another username."; lbl_Error.Visible = true; } else { this.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", "alert('" + txt_Email.Text + " profile has been updated successfully.');self.location = 'employeelist.aspx';", true); } } }
public static void GetRange(this UserRoles role, out UserRoles min, out UserRoles? max) { if (role >= UserRoles.Admin) { min = UserRoles.Admin; max = null; } else if(role >= UserRoles.Agent) { min = UserRoles.Agent; max = UserRoles.Admin; } else { min = UserRoles.User; max = UserRoles.Agent; } }
public static string GetRoleDescription(UserRoles role) { switch (role) { case UserRoles.Customer: return "Vendedor"; case UserRoles.Salesman: return "Dependiente"; case UserRoles.Manager: return "Gerente"; case UserRoles.SuperUser: return "Super User"; case UserRoles.Administrator: return "Administrador"; default: return role.ToStringValue(); } }
public bool Delete(UserRoles userRoles) { return(this.roleBl.DeleteUserRole(userRoles)); }
public User(string login, string password, UserRoles role) { this.login = login; this.password = password; this.role = role; }
//public void DoesNotNeedToConfirmEmail() //{ // this.EmailConfirmed = true; //} //public void ConfirmEmail() //{ // this.EmailConfirmed = true; //} public void AddRole(UserRoles accountType) { switch (accountType) { case UserRoles.Owner: IsOwner = true; break; case UserRoles.Witness: IsWitness = true; break; case UserRoles.Dataheir: IsDataheir = true; break; } }
/// <summary> /// Gets the list of data for use by the jqgrid plug-in /// </summary> public IActionResult OnGetGridDataWithFilters(string sidx, string sord, int _page, int rows, string filters) { int? userRoleId = null; int? userId = null; int? roleId = null; bool?status = null; if (!String.IsNullOrEmpty(filters)) { // deserialize json and get values being searched var jsonResult = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(filters); foreach (var rule in jsonResult["rules"]) { if (rule["field"].Value.ToLower() == "userroleid") { userRoleId = Convert.ToInt32(rule["data"].Value); } if (rule["field"].Value.ToLower() == "userid") { userId = Convert.ToInt32(rule["data"].Value); } if (rule["field"].Value.ToLower() == "roleid") { roleId = Convert.ToInt32(rule["data"].Value); } if (rule["field"].Value.ToLower() == "status") { status = Convert.ToBoolean(rule["data"].Value); } } // sometimes jqgrid assigns a -1 to numeric fields when no value is assigned // instead of assigning a null, we'll correct this here if (userRoleId == -1) { userRoleId = null; } if (userId == -1) { userId = null; } if (roleId == -1) { roleId = null; } } int totalRecords = UserRoles.GetRecordCountDynamicWhere(userRoleId, userId, roleId, status); int startRowIndex = ((_page * rows) - rows); List <UserRoles> objUserRolesCol = UserRoles.SelectSkipAndTakeDynamicWhere(userRoleId, userId, roleId, status, rows, startRowIndex, sidx + " " + sord); int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows); if (objUserRolesCol is null) { return(new JsonResult("{ total = 0, page = 0, records = 0, rows = null }")); } var jsonData = new { total = totalPages, _page, records = totalRecords, rows = ( from objUserRoles in objUserRolesCol select new { id = objUserRoles.UserRoleId, cell = new string[] { objUserRoles.UserRoleId.ToString(), objUserRoles.UserId.HasValue ? objUserRoles.UserId.Value.ToString() : "", objUserRoles.RoleId.HasValue ? objUserRoles.RoleId.Value.ToString() : "", objUserRoles.Status.ToString() } }).ToArray() }; return(new JsonResult(jsonData)); }
public override bool RoleExists(string roleName) { return(UserRoles.GetRole(roleName) != Role.None); }
public UserRoleSelectDataParameters(UserRoles val) { UserRoles = val; Build(); }
public int Post(UserRoles userRoles) { return(this.roleBl.InsertUserRole(userRoles)); }
public AuthUser(UserName name, UserDisplayName displayName, UserRoles roles) { Name = Guard.NotNull(name, nameof(name)); DisplayName = Guard.NotNull(displayName, nameof(displayName)); Roles = Guard.NotNull(roles, nameof(roles)); }
public bool IsInRole(UserRoleType role) { return(UserRoles.Any(r => r.RoleType == role)); }
public void SaveShops(DataContext DB, FormCollection collection) { var shops = (from key in collection.AllKeys where key.StartsWith("Shop_") select(int) collection.GetValue(key).ConvertTo(typeof(int))).ToList(); if (this.UserRoles.Contains("Manager")) { var forDel = DB.ShopManagers.Where(x => x.Manager.ManagerUserID == ID && !shops.Contains(x.ShopID ?? 0)); DB.ShopManagers.DeleteAllOnSubmit(forDel); DB.SubmitChanges(); var forAdd = shops.Where(x => !DB.ShopManagers.Any(z => z.Manager.ManagerUserID == ID && z.ShopID == x)); foreach (var shid in forAdd) { var shop = DB.Shops.FirstOrDefault(x => x.ID == shid); if (shop != null) { var manager = DB.Managers.FirstOrDefault( x => x.ManagerUserID == ID && x.ShopOwnerID == shop.Owner) ?? new Manager() { ManagerUserID = ID, ShopOwnerID = shop.Owner }; DB.ShopManagers.InsertOnSubmit(new ShopManager() { Manager = manager, Shop = shop }); } } DB.SubmitChanges(); } if (UserRoles.Contains("Operator")) { var forDel = DB.OperatorShops.Where(x => x.UserID == ID && !shops.Contains(x.ShopID)); DB.OperatorShops.DeleteAllOnSubmit(forDel); DB.SubmitChanges(); var forAdd = shops.Where(x => !DB.OperatorShops.Any(z => z.UserID == ID && z.ShopID == x)); foreach (var shid in forAdd) { var shop = DB.Shops.FirstOrDefault(x => x.ID == shid); if (shop != null) { var op = new OperatorShop() { Shop = shop, UserID = ID }; DB.OperatorShops.InsertOnSubmit(op); } } DB.SubmitChanges(); } }
public bool HasRole(string rolename) { return(UserRoles.Any(r => r.Role.Name == rolename)); }
public override string[] GetAllRoles() { return(UserRoles.GetRoles().Select(r => r.ToString()).ToArray()); }
public override string[] GetUsersInRole(string roleName) { var role = UserRoles.GetRole(roleName); return(this.userStorage.GetUsersInRole(role).Select(u => u.Username).ToArray()); }
public List<Member> GetMembersByRoleAndStatus(UserRoles role, MemberStatus status) { string strStatus = status.ToString(); string strRole = role.ToString(); return _repository.GetQuery<Member>(m => m.Status == strStatus && m.Roles.Any(r => r.Name == strRole)) .Include(m => m.Login) .ToList(); }
public List<User> FindAllByRole(UserRoles role) { List<User> result = new List<User>(); using (var conn = sqlConnection.Connection) { conn.Open(); using (var command = new SQLiteCommand(sqlFindByRole, conn)) { command.Parameters.AddWithValue("@Role", role.ToString()); using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { result.Add(ToUser(reader)); } } } } return result; }
/// <summary> /// Initialise a new instance of <see cref="ValidRoleOnExamination"/>. /// </summary> /// <param name="requiredRole">Role Required.</param> public ValidRoleOnExamination(UserRoles requiredRole) { _requiredRole = requiredRole; }
public UserIdentity(string name, int userId, UserRoles role) : base(name) { this.UserId = userId; this.Role = role; }
public List <string> Get() { return(UserRoles.GetRoles()); }
protected void Page_Load(object sender, EventArgs e) { string email = Request.Cookies["loginUser"]["email"].ToString(); string firstName = Request.Cookies["loginUser"]["firstName"].ToString(); string lastName = Request.Cookies["loginUser"]["lastName"].ToString(); UserInfoLbl.Text = email + ": " + lastName + ", " + firstName; const string MESSAGE_ROLE = "VIEW_MESSAGE"; UserRoles userRole = new UserRoles(new User(email)); if (userRole.Role.HasFeature(new SysFeature(MESSAGE_ROLE))) { if (IsPostBack && messageView.GetActiveView() == messages) { usersMessages.Columns[3].Visible = true; usersMessages.Columns[4].Visible = true; } else if (!IsPostBack) { messageView.SetActiveView(messages); usersMessages.Columns[3].Visible = true; usersMessages.Columns[4].Visible = true; usersMessages.DataSource = DisplayMessages(email).Tables[0]; usersMessages.DataBind(); foreach (GridViewRow row in usersMessages.Rows) { formatNewMessages(row); } CapitalizeCase(usersMessages); usersMessages.Columns[3].Visible = false; usersMessages.Columns[4].Visible = false; } } else messageView.Visible = false; }
public virtual void GetHtmlOfAction(StringBuilder sb, string selectedKey, object row, bool forCell) { using (var textWriter = new StringWriter(sb)) using (var htmlWriter = new HtmlTextWriter(textWriter)) { var actions = (row != null ? GetActions(row) : GetActions(selectedKey)) .Where(r => r.Roles == null || r.Roles.Length == 0 || UserRoles.IsInAnyRoles(r.Roles)) .OrderBy(r => r.OrderIndex) .ThenBy(r => r.ActionName); foreach (var action in actions) { action.Render(htmlWriter, this, forCell, selectedKey, row); } htmlWriter.Flush(); textWriter.Flush(); } }
protected void SubmitNameLog_Click(object sender, EventArgs e) { const string LOGIN_ROLE = "LOGIN"; if (userExists(EmailLogTB.Text)) { User existingUser = new User(EmailLogTB.Text); existingUser.GetUserInfo(); if (passwordMatches(PasswordLogTB.Text)) { UserRoles userRole = new UserRoles(existingUser); if (userRole.Role.HasFeature(new SysFeature(LOGIN_ROLE))) { if (existingUser.ResetPassword) { PasswordLogTB.Text = ""; Label ResetPasswordConfirm = new Label(); ResetPasswordConfirm.Text = "<br> Confirm Password:"******"F"); Label SignInLabel = new Label(); SignInLabel.Text = "<br> Password Reset Successful, please enter password above to sign in."; loginView.Controls.Add(SignInLabel); } else { HttpCookie loginUser = new HttpCookie("loginUser"); loginUser.Values["email"] = existingUser.Email; loginUser.Values["firstName"] = existingUser.FirstName; loginUser.Values["lastName"] = existingUser.LastName; loginUser.Expires = DateTime.Now.AddDays(7); loginUser.Path = "/"; Response.Cookies.Add(loginUser); Response.Redirect("/UserHomePage.aspx"); } } else { Label InsufficientLoginLabel = new Label(); InsufficientLoginLabel.Text = "<br> Unable to login, insufficient rights. please contact your system administrator."; loginView.Controls.Add(InsufficientLoginLabel); } } } }
public virtual void GetStaticHtmlOfAction(StringBuilder sb) { using (var textWriter = new StringWriter(sb)) using (var htmlWriter = new HtmlTextWriter(textWriter)) { var actions = GetActions() .Where(r => r.Roles == null || r.Roles.Length == 0 || UserRoles.IsInAnyRoles(r.Roles)) .OrderBy(r => r.OrderIndex) .ThenBy(r => r.ActionName); foreach (var action in actions) { action.RenderStaticHtml(htmlWriter, this); } htmlWriter.Flush(); textWriter.Flush(); } }
public static Stream GetReport(bool useReturnStream, string pluginName, string guid, StorageValues storageValues, string culture, Page page, string format, string command, LogMonitor logMonitor, bool expToWord, Dictionary <string, object> constants, StiWebViewer report, out string fileNameExtention, bool RoleCheck) { var originalUICulture = Thread.CurrentThread.CurrentUICulture; var originalCulture = Thread.CurrentThread.CurrentCulture; try { if (string.IsNullOrEmpty(culture)) { culture = "ru-ru"; } Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo(culture == "ru" ? "ru-ru" : (culture == "kz" ? "kk-kz" : culture)); fileNameExtention = ""; WebInitializer.Initialize(); var webReportManager = new WebReportManager(new TreeView()); if (string.IsNullOrEmpty(pluginName)) { return(null); } webReportManager.RoleCheck = RoleCheck; webReportManager.Plugin = webReportManager.GetPlugins()[pluginName]; if (webReportManager.Plugin != null) { webReportManager.Plugin.InitializeReportCulture(culture); var values = storageValues; var webReportPlugin = (IWebReportPlugin)webReportManager.Plugin; var stiPlugin = (IStimulsoftReportPlugin)webReportPlugin; webReportPlugin.Page = page; webReportManager.CreateView(); if (!string.IsNullOrEmpty(webReportManager.Plugin.CultureParameter)) { values.SetStorageValues( webReportManager.Plugin.CultureParameter, webReportManager.Plugin.InitializedKzCulture); } webReportManager.InitValues(values, webReportPlugin.InitSavedValuesInvisibleConditions); webReportPlugin.Constants = constants; if (!string.IsNullOrEmpty(webReportManager.Plugin.CultureParameter) && stiPlugin.Report.Dictionary.Variables.Contains(webReportManager.Plugin.CultureParameter)) { if (webReportManager.Plugin.SupportRuKz) { stiPlugin.Report[webReportManager.Plugin.CultureParameter] = webReportManager.Plugin.InitializedKzCulture; } else { stiPlugin.Report[webReportManager.Plugin.CultureParameter] = webReportManager.Plugin.InitializedCulture; } } try { webReportManager.ShowReport(); } catch (ConstraintException e) { var allErrors = webReportManager.Plugin.Table.DataSet?.GetAllErrors(); if (!string.IsNullOrEmpty(allErrors)) { throw new Exception(allErrors, e); } var errors = webReportManager.Plugin.Table.GetErrors(); if (errors.Length > 0) { throw new Exception(errors.Select(r => r.RowError).Aggregate((v1, v2) => v1 + "; " + v2), e); } throw; } var section = ReportInitializerSection.GetReportInitializerSection(); if (section != null && !string.IsNullOrEmpty(section.PropSaveDataFile)) { if (webReportManager.Plugin.Table.DataSet != null) { webReportManager.Plugin.Table.DataSet.WriteXml(section.PropSaveDataFile); } else { webReportManager.Plugin.Table.WriteXml(section.PropSaveDataFile); } } if (HttpContext.Current != null && HttpContext.Current.Request.QueryString["GetDataSet"] == "on" && UserRoles.IsInRole(UserRoles.ADMIN)) { using (var stream = new MemoryStream()) { if (webReportManager.Plugin.Table.DataSet != null) { webReportManager.Plugin.Table.DataSet.WriteXml(stream); } else { webReportManager.Plugin.Table.WriteXml(stream); } stream.Position = 0; PageHelper.DownloadFile(stream, "data.xml", HttpContext.Current.Response); } } var autoExport = webReportPlugin as IReportAutoExport; DBDataContext.AddViewReports( Tools.Security.User.GetSID(), HttpContext.Current?.User.Identity.Name ?? "anonymous", HttpContext.Current?.User.Identity.Name ?? "anonymous", ReportInitializerSection.GetReportInitializerSection().ReportPageViewer + "?ClassName=" + pluginName, HttpContext.Current?.Request.Url.GetLeftPart(UriPartial.Authority) ?? "https://maxat", Environment.MachineName, useReturnStream || autoExport != null || expToWord || stiPlugin.AutoExportTo != null, webReportManager.Plugin.GetType()); Log(logMonitor, guid, webReportManager); if (useReturnStream) { StiExportFormat stiExportFormat; try { stiExportFormat = (StiExportFormat)Enum.Parse(typeof(StiExportFormat), format); } catch (Exception) { var stiCustomExportType = (CustomExportType)Enum.Parse(typeof(CustomExportType), format); return(ExportWithoutShow( webReportManager.Report, stiCustomExportType, true, out fileNameExtention)); } fileNameExtention = WebReportManager.GetFileExtension(stiExportFormat); return(ExportWithoutShow(webReportManager.Report, stiExportFormat, true)); } //webReportManager.Report.EndRender += (sender, args) => LogMessages(webReportManager.Report, logMonitor); if (autoExport != null) { autoExport.Export(); } if (!expToWord && stiPlugin.AutoExportTo == null) { report.Report = webReportManager.Report; page.Cache.Insert(report.Report.ReportName, report.Report, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0), CacheItemPriority.NotRemovable, null); report.ResetCurrentPage(); } else if (webReportPlugin.CustomExportType != CustomExportType.None) { return(ExportWithoutShow( webReportManager.Report, webReportPlugin.CustomExportType, false, out fileNameExtention)); } else if (stiPlugin.AutoExportTo != null) { return(ExportWithoutShow(webReportManager.Report, stiPlugin.AutoExportTo.Value, false)); } else { return(ExportWithoutShow(webReportManager.Report, StiExportFormat.Word2007, false)); } } } finally { Thread.CurrentThread.CurrentUICulture = originalUICulture; Thread.CurrentThread.CurrentCulture = originalCulture; } return(null); }
public EditUserInfoForm(NetConnection connection, int userId, string login, string name, string surname, string group, UserRoles role) { InitializeComponent(); this.connection = connection; this.userId = userId; labelLogin.Text = "Логин: " + login; textBoxSurname.Text = surname; textBoxFirstname.Text = name; textBoxGroup.Text = group; if (role == UserRoles.Student) { textBoxGroup.Visible = true; labelGroup.Visible = true; } }
public bool Put(UserRoles userRoles) { return(this.roleBl.UpdateUserRole(userRoles)); }
public IEnumerable <Role> GetRolesAvailableToUser(User user) { var roles = GetUserRoles(user.Username); return(UserRoles.GetRoles().Where(r => !roles.Contains(r))); }
public bool IsInRole(string systemKeyword) { return(UserRoles.Any(u => u.Role.SystemKeyword == systemKeyword)); }
public bool IsInRole(int roleId) { return(UserRoles.Any(u => u.RoleId == roleId)); }
public void UsersLock(IDictionary<int, string> users, UserRoles role) { if (role == UserRoles.Master) { foreach (var user in users) { this._userRepository.LockUserById(user.Key); } } else { foreach (var user in users.Where(user => user.Value == UserRoles.User.ToString())) { this._userRepository.LockUserById(user.Key); } } }
public AuthenticateAttribute(UserRoles accessRole) { AccessRole = accessRole; }
public bool isExist(UserRoles role) { bool result = false; using (var conn = sqlConnection.Connection) { conn.Open(); using (var command = new SQLiteCommand(sqlFindByRole, conn)) { command.Parameters.AddWithValue("@Role", role.ToString()); using (SQLiteDataReader reader = command.ExecuteReader()) { result = reader.Read(); } } } return result; }
public void CreateUser() { string connection = ConfigurationManager.ConnectionStrings["EVENTSConnectionString"].ToString(); SqlConnection dbConnection = new SqlConnection(connection); try { dbConnection.Open(); SqlParameter EmailParam = new SqlParameter("@EMAIL", System.Data.SqlDbType.NVarChar, 50); EmailParam.Value = this.email; SqlParameter FirstNameParam = new SqlParameter("@FIRST_NAME", System.Data.SqlDbType.NVarChar, 70); FirstNameParam.Value = this.firstName; SqlParameter LastNameParam = new SqlParameter("@LAST_NAME", System.Data.SqlDbType.NVarChar, 70); LastNameParam.Value = this.lastName; SqlParameter PasswordParam = new SqlParameter("@PASSWORD", System.Data.SqlDbType.NVarChar, 70); PasswordParam.Value = Security.HashSHA1(this.password); SqlParameter[] CreateUserParameters = new SqlParameter[] { EmailParam, LastNameParam, FirstNameParam, PasswordParam }; string createUserCommand = "INSERT INTO APPLICATION_USERS (EMAIL, FIRST_NAME, LAST_NAME, PASSWORD) VALUES (@EMAIL, @FIRST_NAME, @LAST_NAME, @PASSWORD);"; SqlCommand createUser = new SqlCommand(null, dbConnection); createUser.Parameters.AddRange(CreateUserParameters); createUser.CommandText = createUserCommand; createUser.Prepare(); createUser.ExecuteNonQuery(); dbConnection.Close(); UserRoles createRole = new UserRoles(this); } catch (SqlException exception) { // "<p> Error Code " + exception.Number + ": " + exception.Message + "</p>"; } }
public bool IsAccountAssignedToRole( string userName, UserRoles role) { if (!Roles.RoleExists(role.ToString())) { Roles.CreateRole(role.ToString()); } if (string.IsNullOrEmpty(userName)) { return Roles.IsUserInRole(role.ToString()); } return Roles.IsUserInRole( userName, role.ToString()); }
public AuthorizeUserAttribute(ClaimType countryClaim, ClaimType roleClaim, UserRoles countryRole, params UserRoles[] roles) { _roles = roles; _countryClaim = countryClaim; _roleClaim = roleClaim; }
public bool IsInRole(UserRoles role) { return Roles.Contains(role); }
/// <summary> /// Inserts a record /// </summary> public int Insert() { UserRoles objUserRoles = (UserRoles)this; return(UserRolesDataLayer.Insert(objUserRoles)); }
static public void adminMenu() { int choice; Dictionary <string, int> allUsers = UserData.AllUsersUsernames(); do { //Console.Clear(); Console.WriteLine("Admin Menu:"); Console.WriteLine("0. Exit"); Console.WriteLine("1. Change user activity"); Console.WriteLine("2. Change user role"); Console.WriteLine("3. Show list of users"); Console.WriteLine("4. Show log file"); Console.WriteLine("5. Show current session activities"); do { Console.Write("Choose option: "); choice = Convert.ToInt32(Console.ReadLine()); } while (choice < 0 || choice > 5); switch (choice) { case 0: break; case 1: Console.Write("Enter username: "******"Enter date[MM/DD/YYYY or YYYY/MM/DD]: "); string dateString = Console.ReadLine(); DateTime dateChangeActive = DateTime.Parse(dateString); UserData.setUserActiveTo(allUsers[usernameChangeActive], dateChangeActive); break; case 2: Console.Write("Enter username: "******"1. Admin"); Console.WriteLine("2. Inspector"); Console.WriteLine("3. Professor"); Console.WriteLine("4. Student"); do { Console.Write("Choose new role: "); newRoleChoice = Convert.ToInt32(Console.ReadLine()); } while (newRoleChoice < 1 || newRoleChoice > 4); switch (newRoleChoice) { case 1: newRole = UserRoles.ADMIN; break; case 2: newRole = UserRoles.INSPECTOR; break; case 3: newRole = UserRoles.PROFESSOR; break; case 4: newRole = UserRoles.STUDENT; break; default: newRole = UserRoles.ANONYMOUS; break; } UserData.assignUserRole(allUsers[usernameChangeRole], newRole); break; case 3: foreach (KeyValuePair <string, int> user in allUsers) { Console.WriteLine(user.Key); } break; case 4: Logger.showLogFile(); break; case 5: Console.Write("Enter filter: "); string filter = Console.ReadLine(); string activities = Logger.GetCurrentSessionActivities(filter); Console.WriteLine(activities); break; default: break; } } while (choice != 0); }
protected unsafe void btnAdd_Click(object sender, EventArgs e) { UserInfo info; UserInfo info2; int num; int num2; UserRoles[] rolesArray; UserRoles roles; UserRoles roles2; string str; string[] strArray; bool flag; int num3; UserRoles[] rolesArray2; int num4; if (PageUtil.CheckValid(this, new string[] { "txt_UserName#请输入用户名" }) != null) { goto Label_0025; } goto Label_01CF; Label_0025: if ((string.IsNullOrEmpty(this.txt_OrderId.Value) == 0) != null) { goto Label_005D; } this.txt_OrderId.Value = &UserInfo.GetNextId(SitePortal.GetCurrentPortalId()).ToString(); Label_005D: info = UserInfo.GetUserInfoByUserName(SitePortal.GetCurrentPortalId(), this.txt_UserName.Value); if (((info == null) ? 1 : (info.Id == this.nId)) != null) { goto Label_00B0; } PageUtil.WriteAlertAndFocus(this.Page, "该用户名已存在,请检查!", this.txt_UserName.ClientID); goto Label_01CF; Label_00B0: info2 = UserInfo.Get(this.nId); if (((info2 == null) == 0) != null) { goto Label_00CF; } info2 = new UserInfo(); Label_00CF: info2.PortalId = SitePortal.GetCurrentPortalId(); info2.IsActive = 1; info2.IsSystemUser = 1; info2.Status = 1; info2.IsDelete = 2; num = PageUtil.CommonModify(this, info2, info2.Id, "", "创建失败,请与系统管理员联系!", ""); if (((num > 0) == 0) != null) { goto Label_01CF; } num2 = Util.pasteInt(this.sel_Role.SelectedValue, -1); rolesArray = UserRoles.GetUserRolesByUser(num); rolesArray2 = rolesArray; num4 = 0; goto Label_0164; Label_0148: roles = rolesArray2[num4]; UserRoles.Del(roles.get_id()); num4 += 1; Label_0164: if ((num4 < ((int)rolesArray2.Length)) != null) { goto Label_0148; } roles2 = new UserRoles(); roles2.RoleID = num2; roles2.UserID = num; roles2.DepartmentID = -1; CommonClassDB.Instance(roles2).set(roles2); UserInfo.ClearAllUsersHash(); UserInfo.CleanOnlineUsers(); str = this.GetRefreshUrl(1, 1); PageUtil.WriteAlertAndRet(this.Page, "", str, ""); Label_01CF: return; }
public bool IsUserInRole(UserRoles role) { return HttpContext.Current.User.IsInRole(role.ToString()); }
protected unsafe void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e) { UserInfo info; HtmlInputCheckBox box; Label label; int num; UserRoles[] rolesArray; string str; UserRoles roles; string str2; string str3; string str4; bool flag; UserRoles[] rolesArray2; int num2; if (((e.Item.ItemType == 2) ? 0 : ((e.Item.ItemType == 3) == 0)) != null) { goto Label_0249; } info = (UserInfo)e.Item.DataItem; PageUtil.CommonFill(e.Item, info); box = (HtmlInputCheckBox)e.Item.FindControl("cbSel"); if ((box == null) != null) { goto Label_0080; } box.Value = &info.Id.ToString(); Label_0080: label = (Label)e.Item.FindControl("lbl_Id"); if ((label == null) != null) { goto Label_00D8; } num = (e.Item.ItemIndex + 1) + ((this.PaginationBar1.PageIndex - 1) * this.PaginationBar1.PageSize); label.Text = &num.ToString(); Label_00D8: label = (Label)e.Item.FindControl("lbl_DisplayRole"); if ((label == null) != null) { goto Label_014E; } rolesArray = UserRoles.GetUserRolesByUser(info.get_id()); str = ""; rolesArray2 = rolesArray; num2 = 0; goto Label_0136; Label_0117: roles = rolesArray2[num2]; str = str + roles.get_RoleName(); num2 += 1; Label_0136: if ((num2 < ((int)rolesArray2.Length)) != null) { goto Label_0117; } label.Text = str; Label_014E: label = (Label)e.Item.FindControl("lbl_Info"); if ((label == null) != null) { goto Label_0192; } label.Text = string.Format("<a href='#' onclick=\"fnChangePwd({0}, '{1}');return false;\">设置用户密码</a>", (int)info.get_id(), info.UserName); Label_0192: label = (Label)e.Item.FindControl("lbl_Operation"); if ((label == null) != null) { goto Label_0248; } if (((this.nId > 0) == 0) != null) { goto Label_01D8; } label.Text = " "; goto Label_0247; Label_01D8: str2 = this.GetRefreshUrl(1, 1); str3 = str2 + "&act=mdy&id=" + &info.Id.ToString(); str4 = str2 + "&act=del&id=" + &info.Id.ToString(); label.Text = string.Format("<input type='button' value='修改' onclick=\"fnGo('{0}');return false;\" /> ", str3); label.Text = label.Text + string.Format("<input type='button' value='删除' onclick=\"fnDel('{0}');return false;\" /> ", str4); Label_0247 :; Label_0248 :; Label_0249: return; }
public RoleBasedSecurityDecorator(IFileReader fileReader, IRoleBasedSecuritySystem securitySystem, UserRoles userRole) { this.fileReader = fileReader ?? throw new ArgumentNullException("fileReader"); this.securitySystem = securitySystem ?? throw new ArgumentNullException("securitySystem"); this.userRole = userRole; }
/// <summary> /// Updates a record /// </summary> public void Update() { UserRoles objUserRoles = (UserRoles)this; UserRolesDataLayer.Update(objUserRoles); }
public ActionResult Create([Bind(Include = "UserId,RoleId")] CreateUserRoleViewModel cUserRoles) { if (ModelState.IsValid) { if (cUserRoles.RoleId == null) { return RedirectToAction("Index", new { Message = UserRolesMessageId.CreateRoleFail }); } UserRoles ur = null; foreach (var item in db.IdentityUserRoles.ToList()) { if (cUserRoles.UserId == item.UserId) { ur = new UserRoles { UserId = cUserRoles.UserId, RoleId = cUserRoles.RoleId }; break; } } if (ur == null) { ur = new UserRoles { UserId = cUserRoles.UserId, RoleId = cUserRoles.RoleId }; db.IdentityUserRoles.Add(ur); db.SaveChanges(); return RedirectToAction("Index"); } return RedirectToAction("Index", new { Message = UserRolesMessageId.CreateUserRoleFail }); } return View(cUserRoles); }
public static void EnsureDatabaseSeeded(this DataContext dbContext) { if (!dbContext.UploadFileTypeEntities.Any()) { dbContext.AddRange(new UploadFileType[] { new UploadFileType() { Description = "სამომხმარებლოს სესხის ანალიზის ფორმა", FilesPath = "/Files/ConsumerLoan" }, new UploadFileType() { Description = "ბიზნეს ანალიზის ფორმა", FilesPath = "/Files/Busines" }, new UploadFileType() { Description = "აგრო რეზიუმეს ფორმა", FilesPath = "/Files/Agro" }, }); dbContext.SaveChanges(); } if (!dbContext.VariableTypes.Any()) { dbContext.AddRange( new VariableType[] { new VariableType() { Description = "Int", }, new VariableType() { Description = "Decimal" }, new VariableType() { Description = "Nvarchar" } } ); dbContext.SaveChanges(); } if (!dbContext.ReadFileStatuses.Any()) { dbContext.AddRange(new ReadFileStatus[] { new ReadFileStatus { Description = "Success" }, new ReadFileStatus { Description = "Faild" } }); dbContext.SaveChanges(); } if (!dbContext.User.Any()) { dbContext.AddRange(new User[] { new User { FirstName = "Daviti", LastName = "Chivadze", BirthDate = new DateTime(1996, 7, 10), PIN = "35001122068", Address = "Dadiani 56", IsDeleted = false, UserName = "******", Password = "******" } }); dbContext.SaveChanges(); } if (!dbContext.Roles.Any()) { dbContext.AddRange(new Roles[] { new Roles { RoleName = "Home", Description = "Home Page" }, new Roles { RoleName = "ExcelLoan", Description = "Excel Data Reader" } }); dbContext.SaveChanges(); } if (!dbContext.UserRoles.Any()) { var Roles = dbContext.Roles.ToList(); var User = dbContext.User.FirstOrDefault(); UserRoles[] RolesForUser = new UserRoles[Roles.Count]; for (int i = 0; i < Roles.Count; i++) { RolesForUser[i] = new UserRoles { UserID = User.ID, RoleID = Roles[i].ID }; } dbContext.AddRange(RolesForUser); dbContext.SaveChanges(); } }
public static bool Can(UserRoles role, string controller, string action) { if (role == UserRoles.Admin) { return true; } if (!rightsByRoles.ContainsKey(role)) { return false; } return rightsByRoles[role].Can(controller, action); }
public static void CreateCpSPRDDisposeNotificationByUserRoleWhileNewLotArrived(Lot_Transformed lot, UserRoles role, string message) { int recordCount = 0; foreach (User user in UserService.GetUsersByRole(role, 0, 0x270f, out recordCount, "CP")) { CreateCPDisposeNotification(lot, message, user); } }
public IHttpActionResult UpdateUserRole([FromBody] UserRoles userRole) { activities.SaveUpdateUserRole(userRole); return(Ok("Successfully updated")); }
public User(string UserName, UserRoles role) { this.UserName = UserName; this.Role = role; }