private void Page_Load(object sender, System.EventArgs e) { bool showInfo = true; if (Request.QueryString["username"] != null) { UserAccounts.UserInfo user = null; try { user = UserAccounts.getUserInfo(Request.QueryString["username"]); if (user != null) { if (user.Role == UserRole.Canceled) { // If user has canceled his/her membership, only show the // info to users with Admin privileges ErrorMessage.Text = User.Identity.Name + " has canceled his/her membership."; if (!(User.Identity.IsAuthenticated && User.IsInRole(UserRole.Admin.ToString()))) { showInfo = false; } } else if (user.Role == UserRole.Disabled) { // If the user's account has been disabled, only show the // info to users with Admin privileges ErrorMessage.Text = User.Identity.Name + "'s account has been disabled."; if (!(User.Identity.IsAuthenticated && User.IsInRole(UserRole.Admin.ToString()))) { showInfo = false; } } } else { ErrorMessage.Text = "User not found."; showInfo = false; } } catch (Exception ex) { ErrorMessage.Text = "An error occurred while obtaining the user's information."; showInfo = false; } if (showInfo) { ViewUserInfoControl1.UserInfo = user; } else { ViewUserInfoControl1.Visible = false; } } else { ErrorMessage.Text = "An error has occurred. " + "No user was selected."; } }
private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { UserAccounts.UserInfo user = UserAccounts.getUserInfo(Context.User.Identity.Name); NameTxt.Text = user.Name; EmailTxt.Text = user.Email; } }
/// <summary> /// Handles the 'Yes' button click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void YesButton_Click(object sender, System.EventArgs e) { // If the user clicked Yes, update their user account to "Canceled" // and redirect them to the default page. UserAccounts.UserInfo user = UserAccounts.getUserInfo(User.Identity.Name); user.Role = UserRole.Canceled; // Updates the user's role and sends them an email telling them // about the change. UsersControl.updateUserRole(user); UsersControl.logoutUser(); Response.Redirect("default.aspx", true); }
protected void SelectionChanged(object source, System.EventArgs e) { // Get a reference to the DropDownList; DropDownList ddl = (DropDownList)source; DataGridItem dgi = (DataGridItem)ddl.Parent.Parent; UserAccounts.UserInfo user = new UserAccounts.UserInfo(); user.Username = ((HyperLink)dgi.Cells[0].FindControl("UserLink")).Text; user.Role = (UserRole)(Convert.ToInt32(ddl.SelectedValue)); UsersControl.updateUserRole(user); bindGrid(); }
/// <summary> /// Approve a user's request for submitter status. /// </summary> /// <param name="username">The username of the user to approve.</param> public static void approveFaculty(string username) { UserAccounts.UserInfo user = new UserAccounts.UserInfo(); user.Username = username; user.Role = UserRole.Faculty; UserAccounts.updateUserRole(user); FacultyRequestInfo fri = FacultyRequests.getFacultyRequest(username); FacultyRequests.remove(username); }
/// <summary> /// Approve a user's request for submitter status. /// </summary> /// <param name="username">The username of the user to approve.</param> public static void approveSubmitter(string username) { UserAccounts.UserInfo user = new UserAccounts.UserInfo(); user.Username = username; user.Role = UserRole.Submitter; UserAccounts.updateUserRole(user); SubmitterRequestInfo sri = SubmitterRequests.getSubmitterRequest(username); UserAccounts.setSubmitterId(username, sri.SubmitterId); SubmitterRequests.remove(username); }
/// <summary> /// Register the supplied user in the system. /// </summary> /// <param name="user">The user information to register.</param> public static void registerUser(UserAccounts.UserInfo user) { // First create forums user with an empty password. Passwords // are stored in the Swenet user database. User forumsUser = new User(); forumsUser.Username = user.Username; forumsUser.Password = user.Username; // Not used, but needed so it won't send an email. forumsUser.Email = user.Email; CreateUserStatus status = Users.CreateNewUser(forumsUser, false); // Determine if the account was created successfully // -- from AspNetForums\Controls\User\CreateUser.cs switch (status) { // Username already exists! case CreateUserStatus.DuplicateUsername: throw new Exception("A user with this username already exists."); break; // Email already exists! case CreateUserStatus.DuplicateEmailAddress: throw new Exception("A user with this email address already exists."); break; // Unknown failure has occurred! case CreateUserStatus.UnknownFailure: throw new Exception("An unexpected failure has occurred. Please notify the Web site administrator of this error."); break; // Everything went off fine, good case CreateUserStatus.Created: string salt = CreateSalt(SALT_SIZE); string passwordHash = CreatePasswordHash(user.Password, salt); try { UserAccounts.addUser(user.Username, passwordHash, salt, UserRole.User); try { UserAccounts.addUserInfo(user); } catch (SqlException e1) { // TODO: Should delete user from swenet user database. // Rethrow to delete from forums database in outer catch. throw; } } catch (SqlException e2) { // TODO: Should delete user from Forums database here. throw new Exception("User not created."); } break; } }
/// <summary> /// Handles Login button-click events. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void LoginBtn_Click(object sender, System.EventArgs e) { bool passwordVerified = false; try { // Verify password and set authorization cookie, if valid. passwordVerified = UserAccounts.VerifyPassword(txtUserName.Text, txtPassword.Text); UserAccounts.UserInfo user = UserAccounts.getUserInfo(txtUserName.Text); if (!passwordVerified) { // First, see if the username exists and if the password // is correct. If the username doesn't exist, or if // the password is incorrect, reset the fields and notify // user of the problem. lblMessage.Text = "Invalid username or password."; txtUserName.Text = ""; txtPassword.Text = ""; } else if (user.Role == UserRole.Disabled) { // If the username exists and the password was correct, // check to see if the account has been disabled. If so, // notify the user and reset the fields. lblMessage.Text = "That account has been disabled."; txtUserName.Text = ""; txtPassword.Text = ""; } else { // Keep track of redirection information string url = Request.QueryString["ReturnUrl"] == null ? "MyAccount.aspx" : FormsAuthentication.GetRedirectUrl(txtUserName.Text, false); if (user.Role == UserRole.Canceled) { // If this account had been Canceled, reset them to User status, // and redirect them to a page with the appropriate information. user.Role = UserRole.User; UsersControl.updateUserRole(user); Session["CancelType"] = "Reactivate"; url = "AccountCanceled.aspx?ReturnUrl=" + url; } Response.Redirect(url); } } catch (Exception ex) { lblMessage.Text = ex.Message; } }
private void Page_Load(object sender, System.EventArgs e) { //Get the materialID for the material that is currently being viewed string strMaterialID = Request.Params["materialID"]; if (strMaterialID != null) { materialID = int.Parse(Request.Params["materialID"]); } //Obtain the material that is associated with the materialID and setup the header Materials.MaterialInfo mi = Materials.getMaterialInfo(materialID); RatingImage.ImageUrl = mi.RatingImage; NumericalRating.Text = string.Format("{0:0.00}", mi.Rating); MaterialLabel.Text = mi.IdentInfo; NumberOfRatings.Text = "" + Materials.getNumberOfRatings(materialID); MaterialLink.NavigateUrl = "Materials/" + Materials.getModuleOfMaterial(materialID) + "/" + mi.Link; //Identify the user and their access level int role = -1; if (Context.User.Identity.IsAuthenticated) { UserAccounts.UserInfo cui = UserAccounts.getUserInfo(Context.User.Identity.Name); role = (int)cui.Role; } //If the user does not have the needed access level then do not allow them to download the material if ((role < mi.AccessFlag) || (role > 5)) { MaterialLink.Enabled = false; } //Setup the material download link and then display format of it int position = mi.Link.LastIndexOf('.'); if (position == -1) { MaterialLink.Text = "(" + mi.Link + ")"; } else { MaterialLink.Text = "(" + mi.Link.Substring((position + 1)) + ")"; } MaterialLink.Text = MaterialLink.Text.ToUpper(); IList tempComment = MaterialComments.getAll(materialID); CommentRepeater.DataSource = tempComment; CommentRepeater.DataBind(); }
private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { SEEKAreaRepeater.DataSource = Globals.SEEKAreas; SEEKAreaRepeater.DataBind(); FacultyGrid.DataSource = FacultyRequests.getFacultyRequests(); FacultyGrid.DataBind(); SubmitterGrid.DataSource = SubmitterRequests.getSubmitterRequests(); SubmitterGrid.DataBind(); DataTable table = new DataTable(); table.Columns.Add(new DataColumn("Id", typeof(int))); table.Columns.Add(new DataColumn("Title", typeof(string))); table.Columns.Add(new DataColumn("Date", typeof(DateTime))); table.Columns.Add(new DataColumn("ApproveUrl", typeof(string))); table.Columns.Add(new DataColumn("RejectUrl", typeof(string))); IList modules = Modules.getAll(ModuleStatus.PendingApproval); foreach (Modules.ModuleInfo module in modules) { DataRow row = table.NewRow(); row["Id"] = module.Id; row["Title"] = module.Title; row["Date"] = module.Date; row["ApproveUrl"] = "editorActionEmail.aspx?type=2&username="******"&approved=true&moduleID=" + module.Id; row["RejectUrl"] = "editorActionEmail.aspx?type=2&username="******"&moduleID=" + module.Id + "&approved=false"; table.Rows.Add(row); } ModulesGrid.DataSource = table; ModulesGrid.DataBind(); } userRole = -1; if (Context.User.Identity.IsAuthenticated) { UserAccounts.UserInfo cui = UserAccounts.getUserInfo(Context.User.Identity.Name); userRole = (int)cui.Role; } }
/// <summary> /// Log a user into the system. /// </summary> /// <param name="user">User to login.</param> /// <returns>True if the login was successful, false otherwise.</returns> public static bool loginUser(UserAccounts.UserInfo user) { bool retVal = UserAccounts.VerifyPassword(user.Username, user.Password); // If the password is verified, the code below is needed for // proper functioning of the forums. if (retVal) { User forumsUser = new User(); forumsUser.Username = user.Username; forumsUser.Password = ""; Users.ValidUser(forumsUser); } return(retVal); }
/// <summary> /// Handles Register button-click events /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RegisterBtn_Click(object sender, System.EventArgs e) { Page.Validate(); if (Page.IsValid) { UserAccounts.UserInfo ui = EditUserInfoControl1.UserInfo; try { UsersControl.registerUser(ui); FormsAuthentication.RedirectFromLoginPage(ui.Username, false); } catch (Exception ex) { lblMessage.Text = "<p>Error registering user. " + ex.Message + "</p>"; } } }
private void SubmitBtn_Click(object sender, System.EventArgs e) { // Try to retrieve user information with the given username UserAccounts.UserInfo user = UserAccounts.getUserInfo(txtUserName.Text); // Check if the user actually exists if (user == null) { lblMessage.Text = "Username not found."; } else { int index = secretQuestion.getQuestionID(); // Check that the secret question and answer were right if (user.QuestionID != index || user.QuestionAnswer != secretQuestion.getAnswer()) { lblMessage.Text = "Some or all of the data you entered was " + "incorrect. Please revise your answers and try again. "; } else { // generate a password string newPwd = generatePassword(); // set the password in the database user.Password = newPwd; UsersControl.updateUser(user); // send it to their email Email email = Emails.getEmail(EmailType.PasswordReset); Emails.formatEmail(email, user.Username, newPwd); MailMessage msg = Emails.constructMailMessage(email, user.Username, Globals.AdminsEmail); SmtpMail.SmtpServer = AspNetForums.Components.Globals.SmtpServer; SmtpMail.Send(msg); // give them further instructions and set the visibility // of the command buttons accordingly lblMessage.Text = "An email has been sent to: " + user.Email + ". Please check your email for your new password. " + "You may change this password after you log in. " + "Click Continue to go to the login page. "; SubmitBtn.Visible = false; ContinueBtn.Visible = true; } } }
private void Page_Load(object sender, System.EventArgs e) { if (!Context.User.IsInRole(UserRole.Faculty.ToString())) { initRequestInfo(); if (!IsPostBack) { UserAccounts.UserInfo user = UserAccounts.getUserInfo(Context.User.Identity.Name); NameBox.Text = user.Name; AffiliationTxt.Text = user.Affiliation; } } else { Visible = false; } }
public static void updateUserRole(UserAccounts.UserInfo user) { UserAccounts.updateUserRole(user); // Update forums roles try { if (user.Role == UserRole.Submitter) { UserAccounts.setSubmitterId(user.Username, user.Username); } if (user.Role == UserRole.Editor) { UserRoles.AddUserToRole(user.Username, "Forum-Moderators"); UserRoles.RemoveUserFromRole(user.Username, "Forum-Administrators"); UserAccounts.setSubmitterId(user.Username, user.Username); } else if (user.Role == UserRole.Admin) { UserRoles.AddUserToRole(user.Username, "Forum-Moderators"); UserRoles.AddUserToRole(user.Username, "Forum-Administrators"); UserAccounts.setSubmitterId(user.Username, user.Username); } else { UserRoles.RemoveUserFromRole(user.Username, "Forum-Moderators"); UserRoles.RemoveUserFromRole(user.Username, "Forum-Administrators"); } } catch (ArgumentException e) { } if (Globals.EmailsEnabled) { Email email = Emails.getEmail(EmailType.UserRoleChanged); Emails.formatEmail(email, user.Username); MailMessage msg = Emails.constructMailMessage(email, user.Username, Globals.AdminsEmail); SmtpMail.SmtpServer = AspNetForums.Components.Globals.SmtpServer; SmtpMail.Send(msg); } }
public static void updateUser(UserAccounts.UserInfo user) { // Update password, if necessary if (user.Password != string.Empty) { string salt = CreateSalt(SALT_SIZE); string hash = CreatePasswordHash(user.Password, salt); UserAccounts.changePassword(user.Username, hash, salt); } // Update Secret Question info only if they provided info this time if (user.QuestionAnswer == "") { user.QuestionID = UserAccounts.getUserInfo(user.Username).QuestionID; user.QuestionAnswer = UserAccounts.getUserInfo(user.Username).QuestionAnswer; } // Update user role and info UserAccounts.updateUserInfo(user); }
private void Page_Load(object sender, System.EventArgs e) { //Get the materialID for the material being rated string strMaterialID = Request.Params["materialID"]; if (strMaterialID != null) { //Obtain the material that is associated with the materialID and setup the header materialID = int.Parse(Request.Params["materialID"]); Materials.MaterialInfo mi = Materials.getMaterialInfo(materialID); MaterialIdent.Text = mi.IdentInfo; MaterialLink.NavigateUrl = "Materials/" + Materials.getModuleOfMaterial(mi.MatID) + "/" + mi.Link; //Identify the user and their access level int role = -1; if (Context.User.Identity.IsAuthenticated) { UserAccounts.UserInfo cui = UserAccounts.getUserInfo(Context.User.Identity.Name); role = (int)cui.Role; } //If the user does not have the needed access level then do not allow them to download the material if ((role < mi.AccessFlag) || (role > 5)) { MaterialLink.Enabled = false; } //Setup the material download link and then setup the display format for it int position = mi.Link.LastIndexOf('.'); if (position == -1) { MaterialLink.Text = " (" + mi.Link + ")"; } else { MaterialLink.Text = "(" + mi.Link.Substring((position + 1)) + ")"; } MaterialLink.Text = MaterialLink.Text.ToUpper(); } }
/// <summary> /// Gets all of the materials that the user has the right to access in the module /// </summary> /// <param name="moduleID">The moduleID of the associated module</param> /// <returns>Returns all the materials that the user has access level rights to</returns> private string[] getAccessLevelFiles(int moduleID) { IList accessMaterials = Materials.getAll(moduleID); string[] accessAuthorizedMaterials; int role = -1; int size = 0; int index = 0; if (Context.User.Identity.IsAuthenticated) { UserAccounts.UserInfo cui = UserAccounts.getUserInfo(Context.User.Identity.Name); role = (int)cui.Role; } //Determine how many files the user has access rights to foreach (Materials.MaterialInfo material in accessMaterials) { if ((role >= material.AccessFlag) && (role < 5)) { size++; } } accessAuthorizedMaterials = new string[size]; //Add each of the materials the user has rights to foreach (Materials.MaterialInfo material in accessMaterials) { if ((role >= material.AccessFlag) && (role < 5)) { accessAuthorizedMaterials[index] = material.Link; index++; } } return(accessAuthorizedMaterials); }
/// <summary> /// Gets all of the materials that the user has the right to access in the module /// </summary> /// <param name="moduleID">The module that the materials are in</param> /// <returns>All of the materials the user has access rights to</returns> private IList getAccessLevelFilesList(int moduleID) { IList accessMaterials = Materials.getAll(moduleID); IList accessAuthorizedMaterials = new ArrayList(); int role = -1; if (Context.User.Identity.IsAuthenticated) { UserAccounts.UserInfo cui = UserAccounts.getUserInfo(Context.User.Identity.Name); role = (int)cui.Role; } //Add each of the materials the user has rights to foreach (Materials.MaterialInfo material in accessMaterials) { if ((role >= material.AccessFlag) && (role < 5)) { accessAuthorizedMaterials.Add(material); } } return(accessAuthorizedMaterials); }
/// <summary> /// Handles "Download Zip" button-click events /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MaterialsZipButton_Click(object sender, System.EventArgs e) { string path = ConfigurationSettings.AppSettings["MaterialsDir"] + ModInfo.Id + "\\"; string[] filenames = getAccessLevelFiles(ModInfo.Id); //string[] filenames = Directory.GetFiles( path ); string userAccessLevel = "All"; if (Context.User.Identity.IsAuthenticated) { UserAccounts.UserInfo zui = UserAccounts.getUserInfo(Context.User.Identity.Name); if (((int)zui.Role) == 0) { userAccessLevel = "Users"; } else if (((int)zui.Role) >= 1 && ((int)zui.Role) < 5) { userAccessLevel = "Faculty"; } } userAccessLevel = leastAccessLevel(ModInfo.Id, userAccessLevel); string fileWithoutPath = "materials-" + userAccessLevel + "-" + ModInfo.Id + ".zip"; string fileWithPath = path + fileWithoutPath; // Once the zip file is created, it is stored and not created again. // If this module is in the 'InProgress' or 'PendingApproval' states, // we need to delete the zip file if it exists, because the submitter // can edit the materials before the module has been approved. If the // Zip file is not deleted, it may contain links to Materials that don't // exist, and it may be missing links to Materials that do exist. if (ModInfo.Status == ModuleStatus.InProgress || ModInfo.Status == ModuleStatus.PendingApproval) { // Need to store file under different file name than the usual filename // since the submitter may create the zip file before submission, // submit the module (turning the status potentially to approved), // and having an incorrect zip file exist later fileWithPath = path + "tempMaterials-" + userAccessLevel + "-" + ModInfo.Id + ".zip"; if (File.Exists(fileWithPath)) { File.Delete(fileWithPath); } } // If the zip file does not already exist, create it if (!File.Exists(fileWithPath)) { ZipOutputStream s = new ZipOutputStream(File.Create(fileWithPath)); //*****************************************************************************// //********** NOTE: Code taken from \samples\cs\CreateZipFile\Main.cs **********// //********** from file: 050SharpZipLib_SourceSamples.zip **********// //********** made available by SharpDevelop at: **********// //********** http://www.icsharpcode.net/OpenSource/SD/Download **********// //*****************************************************************************// // Modified to use MaterialInfo objects instead of strings Crc32 crc = new Crc32(); s.SetLevel(6); // 0 - store only to 9 - means best compression foreach (string file in filenames) { if (file != null) { //string filepath = ConfigurationSettings.AppSettings["MaterialsDir"] + file.ModuleID + "\\" + file.Link; FileStream fs = File.OpenRead(path + file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); // our code - hides our internal file structure ZipEntry entry = new ZipEntry(file); // end of our code entry.DateTime = DateTime.Now; // set Size and the crc, because the information // about the size and crc should be stored in the header // if it is not set it is automatically written in the footer. // (in this case size == crc == -1 in the header) // Some ZIP programs have problems with zip files that don't store // the size and crc in the header. entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } s.Finish(); s.Close(); //*****************************************************************************// //*************************** End of Borrowed Code ****************************// //*****************************************************************************// } // Redirect them directly to the file for downloading/opening Response.Redirect("Materials/" + ModInfo.Id + "/" + fileWithoutPath); }