public void SendMessageToGroup(int groupID, string subject, string message, string sendOnOrAfterDateTime, string expiresAfterDateTime) { ValidateMessage(subject, message); using (DataAccess.CSSDataContext db = new DataAccess.CSSDataContext()) { var login = DataAccess.Login.FindLoginByUsernameOrCallsign(db, HttpContext.Current.User.Identity.Name); // Get the groups the login has rights to send messages to. var availableGroups = DataAccess.Group.GetGroupsForLogin(db, login.Username, false); // Get the target group. var group = availableGroups.FirstOrDefault(p => p.Id == groupID); if (group == null) { throw new Exception("Couldn't find group id: " + groupID); } // Get the GAGR for the login assigned to the group that has the SL or ASL role. var gagrSender = group.Group_Alias_GroupRoles.FirstOrDefault(p => p.Alias.Login.Username.Equals(login.Username, StringComparison.InvariantCultureIgnoreCase) && (p.GroupRole.Name == "Squad Leader" || p.GroupRole.Name == "Assistant Squad Leader" || p.GroupRole.Name == "Zone Lead")); if (gagrSender == null) { throw new Exception(HttpContext.Current.User.Identity.Name + " does not have rights to send this message."); } DateTime dateToSend = DateTime.Parse(sendOnOrAfterDateTime); DateTime dateExpires = DateTime.Parse(expiresAfterDateTime); DataAccess.GroupMessage groupMessage = new ACSSAuth.DataAccess.GroupMessage() { DateCreated = DateTime.Now, DateExpires = dateExpires, DateToSend = dateToSend, GroupId = group.Id, Message = message, SenderAliasId = gagrSender.Alias.Id, Subject = subject }; db.GroupMessages.InsertOnSubmit(groupMessage); db.SubmitChanges(); foreach (var targetAlias in group.Group_Alias_GroupRoles.Select(p => p.Alias).Distinct()) { db.GroupMessage_Alias.InsertOnSubmit(new DataAccess.GroupMessage_Alias() { Alias = targetAlias, DateViewed = null, GroupMessage = groupMessage }); } db.SubmitChanges(); } }
protected void btnSave_Click(object sender, EventArgs e) { using (var db = new DataAccess.CSSDataContext()) { int groupID = Int32.Parse(ddlGroup.SelectedValue); int roleID = Int32.Parse(ddlRole.SelectedValue); if (db.Group_Alias_GroupRoles.FirstOrDefault(p => p.GroupId == groupID && p.GroupRoleId == roleID && p.AliasId == AliasID) != null) { lblErrorMessage.Text = "User is already assigned to this group/role combination."; return; } DataAccess.Group_Alias_GroupRole newGroupRole = new Allegiance.CommunitySecuritySystem.DataAccess.Group_Alias_GroupRole() { AliasId = AliasID, GroupId = groupID, GroupRoleId = roleID }; db.Group_Alias_GroupRoles.InsertOnSubmit(newGroupRole); db.SubmitChanges(); int loginID = db.Alias.FirstOrDefault(p => p.Id == AliasID).LoginId; Response.Redirect(String.Format("~/User/EditUser.aspx?LoginID={0}&AliasID={1}", loginID, AliasID), true); } }
protected void btnSave_Click(object sender, EventArgs e) { int lobbyID = Int32.Parse(ddlLobby.SelectedValue); using (DataAccess.CSSDataContext db = new DataAccess.CSSDataContext()) { var motdSettings = db.Motds.FirstOrDefault(p => p.LobbyId == lobbyID); if (motdSettings == null) { motdSettings = new DataAccess.Motd(); db.Motds.InsertOnSubmit(motdSettings); motdSettings.LobbyId = lobbyID; } motdSettings.Banner = txtBanner.Text; motdSettings.Details = txtDetails.Text; motdSettings.LastUpdated = DateTime.Now; motdSettings.Logo = ddlLogo.SelectedValue; motdSettings.PaddingCrCount = Int32.Parse(txtPaddingCrCount.Text); motdSettings.PrimaryHeading = txtPrimaryHeading.Text; motdSettings.PrimaryText = txtPrimaryText.Text; motdSettings.SecondaryHeading = txtSecondaryHeading.Text; motdSettings.SecondaryText = txtSecondaryText.Text; db.SubmitChanges(); } lblUpdateStatus.Visible = true; }
public override void AddUsersToRoles(string[] usernames, string[] roleNames) { using (var db = new DataAccess.CSSDataContext()) { foreach (string username in usernames) { DataAccess.Login login = db.Logins.FirstOrDefault(p => p.Username == username.Trim()); if (login != null) { foreach (string roleName in roleNames) { DataAccess.Role role = db.Roles.FirstOrDefault(p => p.Name == roleName.Trim()); if (login.Login_Roles.Count(p => p.LoginId == login.Id && p.RoleId == role.Id) > 0) { continue; } db.Login_Roles.InsertOnSubmit(new DataAccess.Login_Role() { Login = login, LoginId = login.Id, Role = role, RoleId = role.Id }); } } } db.SubmitChanges(); } }
private void DeleteAlias(int aliasID) { using (var db = new DataAccess.CSSDataContext()) { var aliasToDelete = db.Alias.FirstOrDefault(p => p.Id == aliasID); if (aliasToDelete != null) { db.PersonalMessages.DeleteAllOnSubmit(aliasToDelete.PersonalMessages); db.GroupMessages.DeleteAllOnSubmit(aliasToDelete.GroupMessages); db.GroupRequests.DeleteAllOnSubmit(aliasToDelete.GroupRequests); db.Group_Alias_GroupRoles.DeleteAllOnSubmit(aliasToDelete.Group_Alias_GroupRoles); db.GroupMessage_Alias.DeleteAllOnSubmit(aliasToDelete.GroupMessage_Alias); db.AliasBanks.DeleteAllOnSubmit(aliasToDelete.AliasBanks); db.Alias.DeleteOnSubmit(aliasToDelete); db.SubmitChanges(); } } if (OnRequiresDataBind != null) { OnRequiresDataBind(); } ForcePageReload = true; }
public override void AddUsersToRoles(string[] usernames, string[] roleNames) { using (var db = new DataAccess.CSSDataContext()) { foreach (string username in usernames) { DataAccess.Login login = db.Logins.FirstOrDefault(p => p.Username == username.Trim()); if (login != null) { foreach(string roleName in roleNames) { DataAccess.Role role = db.Roles.FirstOrDefault(p => p.Name == roleName.Trim()); if (login.Login_Roles.Count(p => p.LoginId == login.Id && p.RoleId == role.Id) > 0) continue; db.Login_Roles.InsertOnSubmit(new DataAccess.Login_Role() { Login = login, LoginId = login.Id, Role = role, RoleId = role.Id }); } } } db.SubmitChanges(); } }
// When the role dropdown changes in the datagrid. protected void ddlRoles_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddlRoles = (DropDownList)sender; GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent; HiddenField txtGroupID = (HiddenField)row.FindControl("txtGroupID"); HiddenField txtAliasID = (HiddenField)row.FindControl("txtAliasID"); int groupID = Int32.Parse(txtGroupID.Value); int aliasID = Int32.Parse(txtAliasID.Value); int roleID = Int32.Parse(ddlRoles.SelectedValue); //((GridViewRow) ((DataControlFieldCell) ((DropDownList)sender).Parent).Parent).Cells[0].Text using (var db = new DataAccess.CSSDataContext()) { var groupRole = db.Group_Alias_GroupRoles.FirstOrDefault(p => p.AliasId == aliasID && p.GroupId == groupID); if (groupRole == null) { throw new Exception("Couldn't set role for group. Group may have been deleted from alias, or role is no longer available."); } groupRole.GroupRoleId = roleID; db.SubmitChanges(); } if (OnRequiresDataBind != null) { OnRequiresDataBind(); } }
protected void OnDataChanged(object sender, EventArgs e) { using (var db = new DataAccess.CSSDataContext()) { var assignedRoles = db.Roles //.Where(p => p.Name != "SuperAdministrator" && p.Name != "Administrator") .Select ( r => new { Id = r.Id, Name = r.Name, Assigned = (r.Login_Roles.Where(p => (p.RoleId == r.Id && p.LoginId == LoginID)).Count() > 0), Login_Role = r.Login_Roles.FirstOrDefault(p => (p.RoleId == r.Id && p.LoginId == LoginID)) } ); foreach (var assignedRole in assignedRoles) { if (cblLoginRoles.Items.FindByValue(assignedRole.Id.ToString()).Selected != assignedRole.Assigned) { if (assignedRole.Assigned == true) { db.Login_Roles.DeleteOnSubmit(assignedRole.Login_Role); } else { db.Login_Roles.InsertOnSubmit(new ACSSAuth.DataAccess.Login_Role() { LoginId = LoginID, RoleId = assignedRole.Id }); } } } var login = db.Logins.FirstOrDefault(p => p.Id == LoginID); if (login == null) { throw new Exception("Couldn't find login for loginID: " + LoginID); } login.Email = txtEmail.Text.Trim(); login.Username = txtUsername.Text.Trim(); login.AllowVirtualMachineLogin = chkAllowVirtualMachine.Checked; // Keep the first alias the same as the user's login name. login.Aliases.OrderBy(p => p.DateCreated).First().Callsign = txtUsername.Text.Trim(); db.SubmitChanges(); lblSaveMessage.Text = "Data saved."; BindData(); } }
public override bool ValidateUser(string username, string password) { using (var db = new DataAccess.CSSDataContext()) { var login = db.Logins.FirstOrDefault(p => p.Username == username.Trim()); if (login == null) { var alias = DataAccess.Alias.GetAliasByCallsign(db, username); if (alias != null) { login = alias.Login; } } if (login == null) { return(false); } if (Settings.Default.UseIPConverge == true) { var connect = new IPConvergeProvider.Connect(); AuthenticationStatus authenticationStatus; string email; connect.Authenticate(login.Username, password, out authenticationStatus, out email); // Always update the user's email to the IPBoard email if the CSS email is different. // This way if the user uses the forgot password features, then the email will go to // their forum email which is the system of record. if (login.Email != email) { login.Email = email; db.SubmitChanges(); } return(authenticationStatus == AuthenticationStatus.Success); } else { try { // Supports calling this provider from both the CSS Server service and the web interface. return(login != null && (PasswordHash.ValidatePassword(password, login.Password) == true || login.Password == password)); } catch (FormatException) { Log.Write(LogType.AuthenticationServer, "LoginId: " + login.Id + ", loginName: " + login.Username + ", Legacy password couldn't be decoded. This is normal for a beta account."); return(false); } } } }
public override void CreateRole(string roleName) { using (var db = new DataAccess.CSSDataContext()) { db.Roles.InsertOnSubmit(new ACSSAuth.DataAccess.Role() { Name = roleName }); db.SubmitChanges(); } }
public override void CreateRole(string roleName) { using (var db = new DataAccess.CSSDataContext()) { db.Roles.InsertOnSubmit(new Allegiance.CommunitySecuritySystem.DataAccess.Role() { Name = roleName }); db.SubmitChanges(); } }
public static void UnlinkLogin(DataAccess.CSSDataContext db, Identity principal, Login loginToUnlink) { Identity newIdentity = new Identity() { DateLastLogin = DateTime.Now, LastGlobalMessageDelivery = DateTime.Now }; db.Identities.InsertOnSubmit(newIdentity); newIdentity.Logins.Add(loginToUnlink); db.SubmitChanges(); }
public override string ResetPassword(string username, string answer) { string newPassword = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters); string hashedPassword = Allegiance.CommunitySecuritySystem.Common.Utility.Encryption.SHA256Hash(newPassword); using (var db = new DataAccess.CSSDataContext()) { var login = db.Logins.FirstOrDefault(p => p.Username == username.Trim()); login.Password = hashedPassword; db.SubmitChanges(); } return(newPassword); }
public override void UpdateUser(System.Web.Security.MembershipUser user) { using (var db = new DataAccess.CSSDataContext()) { var login = db.Logins.FirstOrDefault(p => p.Id == Convert.ToInt32(user.ProviderUserKey)); if (login != null) { login.Email = user.Email; login.Username = user.UserName; db.SubmitChanges(); } } }
public override string ResetPassword(string username, string answer) { string newPassword = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters); string hashedPassword = PasswordHash.CreateHash(newPassword); using (var db = new DataAccess.CSSDataContext()) { var login = db.Logins.FirstOrDefault(p => p.Username == username.Trim()); login.Password = hashedPassword; db.SubmitChanges(); } return(newPassword); }
protected void btnSave_Click(object sender, EventArgs e) { using (var db = new DataAccess.CSSDataContext()) { DataAccess.Lobby lobby = db.Lobbies.FirstOrDefault(p => p.Id == PublicationID); lobby.Host = txtHost.Text.Trim(); lobby.BasePath = txtBasePath.Text.Trim(); lobby.IsEnabled = chkEnabled.Checked; lobby.IsRestrictive = chkRestrictive.Checked; db.SubmitChanges(); } BindData(); }
public override bool DeleteUser(string username, bool deleteAllRelatedData) { using (var db = new DataAccess.CSSDataContext()) { DataAccess.Login login = DataAccess.Login.FindLoginByUsernameOrCallsign(db, username); DataAccess.Identity identity = db.Identities.FirstOrDefault(p => p.Id == login.IdentityId); if (identity != null) { db.Identities.DeleteOnSubmit(identity); db.SubmitChanges(); return(true); } } return(false); }
private void DeleteGroupRole(int aliasID, int groupID) { using (var db = new DataAccess.CSSDataContext()) { var groupRole = db.Group_Alias_GroupRoles.FirstOrDefault(p => p.AliasId == aliasID && p.GroupId == groupID); if (groupRole == null) { return; } db.Group_Alias_GroupRoles.DeleteOnSubmit(groupRole); db.SubmitChanges(); } if (OnRequiresDataBind != null) { OnRequiresDataBind(); } }
public override bool ChangePassword(string username, string oldPassword, string newPassword) { string oldPasswordHash = Allegiance.CommunitySecuritySystem.Common.Utility.Encryption.SHA256Hash(oldPassword); string newPasswordHash = Allegiance.CommunitySecuritySystem.Common.Utility.Encryption.SHA256Hash(newPassword); using (var db = new DataAccess.CSSDataContext()) { DataAccess.Login login = DataAccess.Login.FindLogin(db, username, oldPasswordHash); if (login == null) { return(false); } login.Password = newPasswordHash; db.SubmitChanges(); } return(true); }
public override bool ChangePassword(string username, string oldPassword, string newPassword) { using (var db = new DataAccess.CSSDataContext()) { DataAccess.Login login; if (Settings.Default.UseIPConverge == true) { login = DataAccess.Login.FindLoginByUsernameOrCallsign(db, username); if (login == null) { return(false); } var connect = new IPConvergeProvider.Connect(); // TODO: If IP Converge is to be used ever, then working around IPC's MD5 password hashs will need to be done. //connect.ChangePassword(login.Email, newPasswordHash); } else { login = DataAccess.Login.FindLoginByUsernameOrCallsign(db, username); if (login == null) { return(false); } if (PasswordHash.ValidatePassword(oldPassword, login.Password) == false) { return(false); } } login.Password = PasswordHash.CreateHash(newPassword); db.SubmitChanges(); } return(true); }
public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status) { string passwordHash = Allegiance.CommunitySecuritySystem.Common.Utility.Encryption.SHA256Hash(password); DataAccess.Identity identity = null; using (var db = new DataAccess.CSSDataContext()) { if (DataAccess.Login.FindLoginByUsername(db, username) != null) { status = System.Web.Security.MembershipCreateStatus.DuplicateUserName; return(null); } if (DataAccess.Alias.ListAliases(db, username).Count > 0) { status = System.Web.Security.MembershipCreateStatus.UserRejected; return(null); } if (DataAccess.Identity.TryCreateIdentity(db, username, passwordHash, email, out identity) == true) { db.SubmitChanges(); } if (identity != null) { DataAccess.Login createdLogin = DataAccess.Login.FindLoginByUsername(db, username); if (createdLogin != null) { status = System.Web.Security.MembershipCreateStatus.Success; return(MembershipUserUtility.CreateMembershipUserFromLogin(createdLogin)); } } } status = System.Web.Security.MembershipCreateStatus.ProviderError; return(null); }
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { using (var db = new DataAccess.CSSDataContext()) { var role = db.Roles.FirstOrDefault(p => p.Name == roleName.Trim()); if (role == null) { return(false); } if (role.Login_Roles.Count() > 0 && throwOnPopulatedRole == true) { throw new ProviderException("This role is being used by one or more logins!"); } db.Roles.DeleteOnSubmit(role); db.SubmitChanges(); } return(true); }
public override bool UnlockUser(string userName) { bool result = false; using (var db = new DataAccess.CSSDataContext()) { var login = db.Logins.FirstOrDefault(p => p.Username == userName.Trim()); if (login.IsBanned == true) { foreach (var ban in login.Identity.Bans.Where(p => p.InEffect == true)) { ban.InEffect = false; } result = true; db.SubmitChanges(); } } return(result); }
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { using (var db = new DataAccess.CSSDataContext()) { foreach (string username in usernames) { DataAccess.Login login = db.Logins.FirstOrDefault(p => p.Username == username.Trim()); foreach (DataAccess.Login_Role loginRole in login.Login_Roles) { foreach (string roleName in roleNames) { if (loginRole.Role.Name.Equals(roleName.Trim()) == true) { db.Login_Roles.DeleteOnSubmit(loginRole); } } } } db.SubmitChanges(); } }
public void SendMessageToCallsigns(string [] callsigns, string subject, string message, string sendOnOrAfterDateTime, string expiresAfterDateTime) { ValidateMessage(subject, message); List<string> callsignsToTest = new List<string>(callsigns); using (DataAccess.CSSDataContext db = new DataAccess.CSSDataContext()) { var login = DataAccess.Login.FindLoginByUsernameOrCallsign(db, HttpContext.Current.User.Identity.Name); // Get the groups the login has rights to send messages to. var availableSquads = DataAccess.Group.GetGroupsForLogin(db, login.Username, false); List<int> loginIDsAlreadyMessaged = new List<int>(); foreach(DataAccess.Group group in availableSquads) { // Get the alias assigned to the login that is tied to the group. the alias must be an ASL or SL. var gagrSender = group.Group_Alias_GroupRoles.FirstOrDefault(p => p.Alias.Login.Username.Equals(login.Username, StringComparison.InvariantCultureIgnoreCase) && (p.GroupRole.Name == "Squad Leader" || p.GroupRole.Name == "Assistant Squad Leader" || p.GroupRole.Name == "Zone Lead")); if(gagrSender != null) { // Get all the callsigns assigned to the group that are also in the target list that have not already been messaged. var loginIDsToSendMessageTo = group.Group_Alias_GroupRoles.Where(p => callsigns.Contains(p.Alias.Callsign) == true && loginIDsAlreadyMessaged.Contains(p.Alias.LoginId) == false).Select(p => p.Alias.LoginId).Distinct(); foreach (var loginID in loginIDsToSendMessageTo) { SendMessageToCallsign(db, subject, message, gagrSender.Alias, loginID, sendOnOrAfterDateTime, expiresAfterDateTime); loginIDsAlreadyMessaged.Add(loginID); } } } db.SubmitChanges(); } }
public void SendMessageToCallsigns(string [] callsigns, string subject, string message, string sendOnOrAfterDateTime, string expiresAfterDateTime) { ValidateMessage(subject, message); List <string> callsignsToTest = new List <string>(callsigns); using (DataAccess.CSSDataContext db = new DataAccess.CSSDataContext()) { var login = DataAccess.Login.FindLoginByUsernameOrCallsign(db, HttpContext.Current.User.Identity.Name); // Get the groups the login has rights to send messages to. var availableSquads = DataAccess.Group.GetGroupsForLogin(db, login.Username, false); List <int> loginIDsAlreadyMessaged = new List <int>(); foreach (DataAccess.Group group in availableSquads) { // Get the alias assigned to the login that is tied to the group. the alias must be an ASL or SL. var gagrSender = group.Group_Alias_GroupRoles.FirstOrDefault(p => p.Alias.Login.Username.Equals(login.Username, StringComparison.InvariantCultureIgnoreCase) && (p.GroupRole.Name == "Squad Leader" || p.GroupRole.Name == "Assistant Squad Leader" || p.GroupRole.Name == "Zone Lead")); if (gagrSender != null) { // Get all the callsigns assigned to the group that are also in the target list that have not already been messaged. var loginIDsToSendMessageTo = group.Group_Alias_GroupRoles.Where(p => callsigns.Contains(p.Alias.Callsign) == true && loginIDsAlreadyMessaged.Contains(p.Alias.LoginId) == false).Select(p => p.Alias.LoginId).Distinct(); foreach (var loginID in loginIDsToSendMessageTo) { SendMessageToCallsign(db, subject, message, gagrSender.Alias, loginID, sendOnOrAfterDateTime, expiresAfterDateTime); loginIDsAlreadyMessaged.Add(loginID); } } } db.SubmitChanges(); } }
public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status) { string passwordHash = Allegiance.CommunitySecuritySystem.Common.Utility.Encryption.SHA256Hash(password); DataAccess.Identity identity = null; using (var db = new DataAccess.CSSDataContext()) { if (DataAccess.Login.FindLoginByUsername(db, username) != null) { status = System.Web.Security.MembershipCreateStatus.DuplicateUserName; return null; } if (DataAccess.Alias.ListAliases(db, username).Count > 0) { status = System.Web.Security.MembershipCreateStatus.UserRejected; return null; } if (DataAccess.Identity.TryCreateIdentity(db, username, passwordHash, email, out identity) == true) db.SubmitChanges(); if(identity != null) { DataAccess.Login createdLogin = DataAccess.Login.FindLoginByUsername(db, username); if(createdLogin != null) { status = System.Web.Security.MembershipCreateStatus.Success; return MembershipUserUtility.CreateMembershipUserFromLogin(createdLogin); } } } status = System.Web.Security.MembershipCreateStatus.ProviderError; return null; }
public int SaveGameData(string gameData, bool isCompressedAndBase64Encoded, out string message) { try { Data.GameDataset gameDataset = new Data.GameDataset(); //gameDataset.EnforceConstraints = false; //gameDataset. if (isCompressedAndBase64Encoded == true) { byte[] binaryGameData = Convert.FromBase64String(gameData); MemoryStream memoryStream = new MemoryStream(binaryGameData); ICSharpCode.SharpZipLib.GZip.GZipInputStream zipStream = new ICSharpCode.SharpZipLib.GZip.GZipInputStream(memoryStream); StreamReader streamReader = new StreamReader(zipStream, System.Text.Encoding.Unicode); //string gameDataXml = streamReader.ReadToEnd(); gameDataset.ReadXml(streamReader, System.Data.XmlReadMode.IgnoreSchema); } else { //gameDataset.ReadXml(new StringReader(gameData)); gameDataset.ReadXml(new StringReader(gameData), System.Data.XmlReadMode.IgnoreSchema); } if (String.IsNullOrEmpty(Settings.Default.TagLastGameDataXmlFileLogLocation) == false) File.WriteAllText(Path.Combine(Settings.Default.TagLastGameDataXmlFileLogLocation, Guid.NewGuid().ToString() + ".xml"), gameDataset.GetXml()); string currentIPAddress; if (OperationContext.Current != null) { //http://nayyeri.net/detect-client-ip-in-wcf-3-5 OperationContext context = OperationContext.Current; MessageProperties messageProperties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpointProperty = (RemoteEndpointMessageProperty)messageProperties[RemoteEndpointMessageProperty.Name]; currentIPAddress = endpointProperty.Address; } else currentIPAddress = "127.0.0.1"; // Supports unit tests. int gameID = 0; using (DataAccess.CSSDataContext db = new DataAccess.CSSDataContext()) { using (DataAccess.CSSStatsDataContext statsDB = new DataAccess.CSSStatsDataContext()) { var gameServer = statsDB.GameServers.FirstOrDefault(p => p.GameServerIPs.Where(r => r.IPAddress == currentIPAddress).Count() > 0); if (gameServer == null) throw new Exception("You may not upload data from this address: " + currentIPAddress); try { foreach (Data.GameDataset.GameRow gameRow in gameDataset.Game) gameID = SaveGame(db, statsDB, gameServer, gameRow); } catch (Exception ex) { if (String.IsNullOrEmpty(Settings.Default.TagExceptionLogFileName) == false) File.AppendAllText(Settings.Default.TagExceptionLogFileName, DateTime.Now.ToString() + ": " + ex.ToString() + "\n\n\n"); throw; } statsDB.SubmitChanges(); db.SubmitChanges(); } } // Update AllegSkill rank. AllegSkill.Calculator.UpdateAllegSkillForGame(gameID); // Update Prestige Rank. using (DataAccess.CSSStatsDataContext statsDB = new DataAccess.CSSStatsDataContext()) { var game = statsDB.Games.FirstOrDefault(p => p.GameIdentID == gameID); if (game == null) { Error.Write(new Exception("Tag.SaveGameData(): Couldn't get game for GameID: " + gameID)); } else { PrestigeRankCalculator psc = new PrestigeRankCalculator(); psc.Calculate(statsDB, game); } } message = "Game saved."; return gameID; } catch (Exception ex) { message = ex.ToString(); return -1; } }
public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status) { DataAccess.Identity identity = null; var connect = new Connect(); using (var db = new DataAccess.CSSDataContext()) { if (DataAccess.Login.FindLoginByUsernameOrCallsign(db, username) != null) { status = System.Web.Security.MembershipCreateStatus.DuplicateUserName; return null; } if (DataAccess.Alias.ListAliases(db, username).Count > 0) { status = System.Web.Security.MembershipCreateStatus.UserRejected; return null; } if (Settings.Default.UseIPConverge == true) { if (connect.CheckEmail(email) == false) { status = MembershipCreateStatus.DuplicateEmail; return null; } if (connect.CheckUsername(username) == false) { status = MembershipCreateStatus.DuplicateUserName; return null; } } status = DataAccess.Identity.TryCreateIdentity(db, username, password, email, out identity); if (status == MembershipCreateStatus.Success) { if (Settings.Default.UseIPConverge == true) { string ipAddress = "127.0.0.1"; if (HttpContext.Current != null) ipAddress = HttpContext.Current.Request.UserHostAddress; // TODO: If IP Converge is to be used ever, then working around IPC's MD5 password hashs will need to be done. //if (connect.AddMember(email, username, passwordHash, ipAddress) == false) //{ // status = MembershipCreateStatus.ProviderError; // return null; //} } } db.SubmitChanges(); if(identity != null) { DataAccess.Login createdLogin = DataAccess.Login.FindLoginByUsernameOrCallsign(db, username); if(createdLogin != null) { status = System.Web.Security.MembershipCreateStatus.Success; var memebershipUser = MembershipUserUtility.CreateMembershipUserFromLogin(createdLogin); if (memebershipUser != null) { SendWelcomeEmail(memebershipUser); } return memebershipUser; } } } status = System.Web.Security.MembershipCreateStatus.ProviderError; return null; }
public override string ResetPassword(string username, string answer) { string newPassword = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters); string hashedPassword = PasswordHash.CreateHash(newPassword); using (var db = new DataAccess.CSSDataContext()) { var login = db.Logins.FirstOrDefault(p => p.Username == username.Trim()); login.Password = hashedPassword; db.SubmitChanges(); } return newPassword; }
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { using (var db = new DataAccess.CSSDataContext()) { var role = db.Roles.FirstOrDefault(p => p.Name == roleName.Trim()); if (role == null) return false; if (role.Login_Roles.Count() > 0 && throwOnPopulatedRole == true) throw new ProviderException("This role is being used by one or more logins!"); db.Roles.DeleteOnSubmit(role); db.SubmitChanges(); } return true; }
public override bool ValidateUser(string username, string password) { using (var db = new DataAccess.CSSDataContext()) { var login = db.Logins.FirstOrDefault(p => p.Username == username.Trim()); if (login == null) { var alias = DataAccess.Alias.GetAliasByCallsign(db, username); if (alias != null) login = alias.Login; } if (login == null) return false; if (Settings.Default.UseIPConverge == true) { var connect = new IPConvergeProvider.Connect(); AuthenticationStatus authenticationStatus; string email; connect.Authenticate(login.Username, password, out authenticationStatus, out email); // Always update the user's email to the IPBoard email if the CSS email is different. // This way if the user uses the forgot password features, then the email will go to // their forum email which is the system of record. if (login.Email != email) { login.Email = email; db.SubmitChanges(); } return authenticationStatus == AuthenticationStatus.Success; } else { try { // Supports calling this provider from both the CSS Server service and the web interface. return login != null && (PasswordHash.ValidatePassword(password, login.Password) == true || login.Password == password); } catch(FormatException) { Log.Write(LogType.AuthenticationServer, "LoginId: " + login.Id + ", loginName: " + login.Username + ", Legacy password couldn't be decoded. This is normal for a beta account."); return false; } } } }
public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status) { DataAccess.Identity identity = null; var connect = new Connect(); using (var db = new DataAccess.CSSDataContext()) { if (DataAccess.Login.FindLoginByUsernameOrCallsign(db, username) != null) { status = System.Web.Security.MembershipCreateStatus.DuplicateUserName; return(null); } if (DataAccess.Alias.ListAliases(db, username).Count > 0) { status = System.Web.Security.MembershipCreateStatus.UserRejected; return(null); } if (Settings.Default.UseIPConverge == true) { if (connect.CheckEmail(email) == false) { status = MembershipCreateStatus.DuplicateEmail; return(null); } if (connect.CheckUsername(username) == false) { status = MembershipCreateStatus.DuplicateUserName; return(null); } } status = DataAccess.Identity.TryCreateIdentity(db, username, password, email, out identity); if (status == MembershipCreateStatus.Success) { if (Settings.Default.UseIPConverge == true) { string ipAddress = "127.0.0.1"; if (HttpContext.Current != null) { ipAddress = HttpContext.Current.Request.UserHostAddress; } // TODO: If IP Converge is to be used ever, then working around IPC's MD5 password hashs will need to be done. //if (connect.AddMember(email, username, passwordHash, ipAddress) == false) //{ // status = MembershipCreateStatus.ProviderError; // return null; //} } } db.SubmitChanges(); if (identity != null) { DataAccess.Login createdLogin = DataAccess.Login.FindLoginByUsernameOrCallsign(db, username); if (createdLogin != null) { status = System.Web.Security.MembershipCreateStatus.Success; var memebershipUser = MembershipUserUtility.CreateMembershipUserFromLogin(createdLogin); if (memebershipUser != null) { SendWelcomeEmail(memebershipUser); } return(memebershipUser); } } } status = System.Web.Security.MembershipCreateStatus.ProviderError; return(null); }
public override bool ChangePassword(string username, string oldPassword, string newPassword) { using (var db = new DataAccess.CSSDataContext()) { DataAccess.Login login; if (Settings.Default.UseIPConverge == true) { login = DataAccess.Login.FindLoginByUsernameOrCallsign(db, username); if (login == null) return false; var connect = new IPConvergeProvider.Connect(); // TODO: If IP Converge is to be used ever, then working around IPC's MD5 password hashs will need to be done. //connect.ChangePassword(login.Email, newPasswordHash); } else { login = DataAccess.Login.FindLoginByUsernameOrCallsign(db, username); if (login == null) return false; if (PasswordHash.ValidatePassword(oldPassword, login.Password) == false) return false; } login.Password = PasswordHash.CreateHash(newPassword); db.SubmitChanges(); } return true; }
public static bool DeployPublication(int publicationID) { using (var db = new DataAccess.CSSDataContext()) { DataAccess.Lobby lobby = db.Lobbies.FirstOrDefault(p => p.Id == publicationID); if (lobby == null) { throw new Exception("Couldn't get lobby for publication id: " + publicationID); } if (Directory.Exists(lobby.BasePath) == false) { Directory.CreateDirectory(lobby.BasePath); } List <FileCollision> fileCollisions = new List <FileCollision>(); Dictionary <string, UpdateItem> filesInPublication = new Dictionary <string, UpdateItem>(); // Remove physical files from the directory. Not doing this with a recursive directory delete because // I don't want someone to put in a bad path into the content manager web UI, and then drill the // whole drive. foreach (DataAccess.AutoUpdateFile_Lobby file in db.AutoUpdateFile_Lobbies.Where(p => p.LobbyId == lobby.Id)) { string fileToDelete = Path.Combine(lobby.BasePath, file.AutoUpdateFile.Filename); if (File.Exists(fileToDelete) == true) { File.Delete(fileToDelete); } } // Clear all files for the lobby. db.AutoUpdateFile_Lobbies.DeleteAllOnSubmit(db.AutoUpdateFile_Lobbies.Where(p => p.LobbyId == lobby.Id)); db.SubmitChanges(); if (AutoUpdateManager.TryGetPublicationFiles(publicationID, out filesInPublication, out fileCollisions) == true) { foreach (UpdateItem fileInfo in filesInPublication.Values) { string checksum; using (SHA1 hasher = SHA1.Create()) { using (FileStream fs = new FileStream(fileInfo.FileInfo.FullName, FileMode.Open, FileAccess.Read)) checksum = Convert.ToBase64String(hasher.ComputeHash(fs)); } string fileVersion = String.Empty; FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(fileInfo.FileInfo.FullName); // Doing it this way, as sometimes there is product or vendor info at the // end of the file version spec. ProductVersion may not correctly reflect the actual // version of the file all the time. if (fileVersionInfo != null && fileVersionInfo.FileVersion != null) { fileVersion = String.Format("{0}.{1}.{2}.{3}", fileVersionInfo.FileMajorPart, fileVersionInfo.FileMinorPart, fileVersionInfo.FileBuildPart, fileVersionInfo.FilePrivatePart); } string relativeFilePath = Path.Combine(fileInfo.RelativeDirectory, fileInfo.Name); DataAccess.AutoUpdateFile autoUpdateFile = db.AutoUpdateFiles.FirstOrDefault(p => p.Filename == relativeFilePath); if (autoUpdateFile == null) { autoUpdateFile = new Allegiance.CommunitySecuritySystem.DataAccess.AutoUpdateFile() { Filename = relativeFilePath, IsProtected = fileInfo.IsProtected }; db.AutoUpdateFiles.InsertOnSubmit(autoUpdateFile); db.SubmitChanges(); } else { if (autoUpdateFile.IsProtected != fileInfo.IsProtected) { autoUpdateFile.IsProtected = fileInfo.IsProtected; db.SubmitChanges(); } } DataAccess.AutoUpdateFile_Lobby lobbyFile = db.AutoUpdateFile_Lobbies.FirstOrDefault(p => p.AutoUpdateFileId == autoUpdateFile.Id && p.LobbyId == lobby.Id); if (lobbyFile == null) { lobbyFile = new Allegiance.CommunitySecuritySystem.DataAccess.AutoUpdateFile_Lobby() { AutoUpdateFileId = autoUpdateFile.Id, CurrentVersion = fileVersion, DateCreated = fileInfo.FileInfo.CreationTime, DateModified = fileInfo.FileInfo.LastWriteTime, ValidChecksum = checksum, LobbyId = lobby.Id }; db.AutoUpdateFile_Lobbies.InsertOnSubmit(lobbyFile); db.SubmitChanges(); } string targetFilePath = Path.Combine(lobby.BasePath, relativeFilePath); string targetFileDirectory = Path.GetDirectoryName(targetFilePath); if (Directory.Exists(targetFileDirectory) == false) { Directory.CreateDirectory(targetFileDirectory); } File.Copy(fileInfo.FileInfo.FullName, targetFilePath, true); } GenerateFileListForAutoUpdate(lobby); } // Clean up any unused AutoUpdateFile records. //db.AutoUpdateFiles.DeleteAllOnSubmit(db.AutoUpdateFiles.Where(p => db.AutoUpdateFile_Lobbies.Select(r => r.AutoUpdateFileId).Contains(p.Id) == false)); //db.SubmitChanges(); } return(true); }
private void DeleteGroupRole(int aliasID, int groupID) { using (var db = new DataAccess.CSSDataContext()) { var groupRole = db.Group_Alias_GroupRoles.FirstOrDefault(p => p.AliasId == aliasID && p.GroupId == groupID); if (groupRole == null) return; db.Group_Alias_GroupRoles.DeleteOnSubmit(groupRole); db.SubmitChanges(); } if(OnRequiresDataBind != null) OnRequiresDataBind(); }
private void AddCallsignToGroup(string callsign, int groupID) { Business.GroupRole currentUserGroupRole = GetCurrentUserGroupRole(groupID); if (currentUserGroupRole != Business.GroupRole.AssistantSquadLeader && currentUserGroupRole != Business.GroupRole.SquadLeader && currentUserGroupRole != Business.GroupRole.ZoneLead) { throw new Exception("Access denied."); } using (var db = new DataAccess.CSSDataContext()) { var group = db.Groups.FirstOrDefault(p => p.Id == groupID); if (group == null) { throw new Exception("Invalid groupID"); } var alias = db.Alias.FirstOrDefault(p => p.Callsign == callsign); if (alias == null) { throw new Exception("Invalid callsign"); } var targetRole = db.GroupRoles.FirstOrDefault(p => p.Name == "Pilot"); if (targetRole == null) { throw new Exception("No pilot role."); } DataAccess.Group_Alias_GroupRole gagrTarget = new DataAccess.Group_Alias_GroupRole() { AliasId = alias.Id, GroupId = group.Id, GroupRoleId = targetRole.Id }; db.Group_Alias_GroupRoles.InsertOnSubmit(gagrTarget); // If the group name is the Moderators group, then add the Moderator role to the group member. if (group.Name.Equals("Moderators", StringComparison.InvariantCultureIgnoreCase) == true) { var moderatorRole = db.Roles.FirstOrDefault(p => p.Name == "Moderator"); var loginRole = db.Login_Roles.FirstOrDefault(p => p.LoginId == alias.LoginId && p.RoleId == moderatorRole.Id); if (loginRole == null) { db.Login_Roles.InsertOnSubmit(new DataAccess.Login_Role() { LoginId = alias.LoginId, RoleId = moderatorRole.Id }); } } // If the group is ACS, then bank the original alias, and swap the alias to an ACS_COM_XXX hider. if (group.Tag.Equals("acs", StringComparison.InvariantCultureIgnoreCase) == true) { BankAlias(db, alias); } db.SubmitChanges(); } Response.Redirect("~/Squads/Default.aspx?groupID=" + groupID, true); }
public override bool UnlockUser(string userName) { bool result = false; using (var db = new DataAccess.CSSDataContext()) { var login = db.Logins.FirstOrDefault(p => p.Username == userName.Trim()); if (login.IsBanned == true) { foreach (var ban in login.Identity.Bans.Where(p => p.InEffect == true)) ban.InEffect = false; result = true; db.SubmitChanges(); } } return result; }
protected void OnDataChanged(object sender, EventArgs e) { using (var db = new DataAccess.CSSDataContext()) { var assignedRoles = db.Roles //.Where(p => p.Name != "SuperAdministrator" && p.Name != "Administrator") .Select ( r => new { Id = r.Id, Name = r.Name, Assigned = (r.Login_Roles.Where(p => (p.RoleId == r.Id && p.LoginId == LoginID)).Count() > 0), Login_Role = r.Login_Roles.FirstOrDefault(p => (p.RoleId == r.Id && p.LoginId == LoginID)) } ); foreach (var assignedRole in assignedRoles) { if (cblLoginRoles.Items.FindByValue(assignedRole.Id.ToString()).Selected != assignedRole.Assigned) { if (assignedRole.Assigned == true) db.Login_Roles.DeleteOnSubmit(assignedRole.Login_Role); else db.Login_Roles.InsertOnSubmit(new Allegiance.CommunitySecuritySystem.DataAccess.Login_Role() { LoginId = LoginID, RoleId = assignedRole.Id }); } } var login = db.Logins.FirstOrDefault(p => p.Id == LoginID); if (login == null) throw new Exception("Couldn't find login for loginID: " + LoginID); login.Email = txtEmail.Text.Trim(); login.Username = txtUsername.Text.Trim(); login.AllowVirtualMachineLogin = chkAllowVirtualMachine.Checked; // Keep the first alias the same as the user's login name. login.Aliases.OrderBy(p => p.DateCreated).First().Callsign = txtUsername.Text.Trim(); db.SubmitChanges(); lblSaveMessage.Text = "Data saved."; BindData(); } }
// When the role dropdown changes in the datagrid. protected void ddlRoles_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddlRoles = (DropDownList)sender; GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent; HiddenField txtGroupID = (HiddenField)row.FindControl("txtGroupID"); HiddenField txtAliasID = (HiddenField)row.FindControl("txtAliasID"); int groupID = Int32.Parse(txtGroupID.Value); int aliasID = Int32.Parse(txtAliasID.Value); int roleID = Int32.Parse(ddlRoles.SelectedValue); //((GridViewRow) ((DataControlFieldCell) ((DropDownList)sender).Parent).Parent).Cells[0].Text using (var db = new DataAccess.CSSDataContext()) { var groupRole = db.Group_Alias_GroupRoles.FirstOrDefault(p => p.AliasId == aliasID && p.GroupId == groupID); if (groupRole == null) throw new Exception("Couldn't set role for group. Group may have been deleted from alias, or role is no longer available."); groupRole.GroupRoleId = roleID; db.SubmitChanges(); } if(OnRequiresDataBind != null) OnRequiresDataBind(); }
public static bool DeployPublication(int publicationID) { using (var db = new DataAccess.CSSDataContext()) { DataAccess.Lobby lobby = db.Lobbies.FirstOrDefault(p => p.Id == publicationID); if(lobby == null) throw new Exception("Couldn't get lobby for publication id: " + publicationID); if (Directory.Exists(lobby.BasePath) == false) Directory.CreateDirectory(lobby.BasePath); List<FileCollision> fileCollisions = new List<FileCollision>(); Dictionary<string, UpdateItem> filesInPublication = new Dictionary<string, UpdateItem>(); // Remove physical files from the directory. Not doing this with a recursive directory delete because // I don't want someone to put in a bad path into the content manager web UI, and then drill the // whole drive. foreach (DataAccess.AutoUpdateFile_Lobby file in db.AutoUpdateFile_Lobbies.Where(p => p.LobbyId == lobby.Id)) { string fileToDelete = Path.Combine(lobby.BasePath, file.AutoUpdateFile.Filename); if (File.Exists(fileToDelete) == true) File.Delete(fileToDelete); } // Clear all files for the lobby. db.AutoUpdateFile_Lobbies.DeleteAllOnSubmit(db.AutoUpdateFile_Lobbies.Where(p => p.LobbyId == lobby.Id)); db.SubmitChanges(); if (AutoUpdateManager.TryGetPublicationFiles(publicationID, out filesInPublication, out fileCollisions) == true) { foreach (UpdateItem fileInfo in filesInPublication.Values) { string checksum; using (SHA1 hasher = SHA1.Create()) { using (FileStream fs = new FileStream(fileInfo.FileInfo.FullName, FileMode.Open, FileAccess.Read)) checksum = Convert.ToBase64String(hasher.ComputeHash(fs)); } string fileVersion = String.Empty; FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(fileInfo.FileInfo.FullName); // Doing it this way, as sometimes there is product or vendor info at the // end of the file version spec. ProductVersion may not correctly reflect the actual // version of the file all the time. if (fileVersionInfo != null && fileVersionInfo.FileVersion != null) fileVersion = String.Format("{0}.{1}.{2}.{3}", fileVersionInfo.FileMajorPart, fileVersionInfo.FileMinorPart, fileVersionInfo.FileBuildPart, fileVersionInfo.FilePrivatePart); string relativeFilePath = Path.Combine(fileInfo.RelativeDirectory, fileInfo.Name); DataAccess.AutoUpdateFile autoUpdateFile = db.AutoUpdateFiles.FirstOrDefault(p => p.Filename == relativeFilePath); if (autoUpdateFile == null) { autoUpdateFile = new Allegiance.CommunitySecuritySystem.DataAccess.AutoUpdateFile() { Filename = relativeFilePath, IsProtected = fileInfo.IsProtected }; db.AutoUpdateFiles.InsertOnSubmit(autoUpdateFile); db.SubmitChanges(); } else { if (autoUpdateFile.IsProtected != fileInfo.IsProtected) { autoUpdateFile.IsProtected = fileInfo.IsProtected; db.SubmitChanges(); } } DataAccess.AutoUpdateFile_Lobby lobbyFile = db.AutoUpdateFile_Lobbies.FirstOrDefault(p => p.AutoUpdateFileId == autoUpdateFile.Id && p.LobbyId == lobby.Id); if (lobbyFile == null) { lobbyFile = new Allegiance.CommunitySecuritySystem.DataAccess.AutoUpdateFile_Lobby() { AutoUpdateFileId = autoUpdateFile.Id, CurrentVersion = fileVersion, DateCreated = fileInfo.FileInfo.CreationTime, DateModified = fileInfo.FileInfo.LastWriteTime, ValidChecksum = checksum, LobbyId = lobby.Id }; db.AutoUpdateFile_Lobbies.InsertOnSubmit(lobbyFile); db.SubmitChanges(); } string targetFilePath = Path.Combine(lobby.BasePath, relativeFilePath); string targetFileDirectory = Path.GetDirectoryName(targetFilePath); if (Directory.Exists(targetFileDirectory) == false) Directory.CreateDirectory(targetFileDirectory); File.Copy(fileInfo.FileInfo.FullName, targetFilePath, true); } GenerateFileListForAutoUpdate(lobby); } // Clean up any unused AutoUpdateFile records. //db.AutoUpdateFiles.DeleteAllOnSubmit(db.AutoUpdateFiles.Where(p => db.AutoUpdateFile_Lobbies.Select(r => r.AutoUpdateFileId).Contains(p.Id) == false)); //db.SubmitChanges(); } return true; }
private int SaveGame(DataAccess.CSSDataContext db, DataAccess.CSSStatsDataContext statsDB, DataAccess.GameServer gameServer, Data.GameDataset.GameRow gameRow) { DataAccess.Game game = new Allegiance.CommunitySecuritySystem.DataAccess.Game() { GameDefections = gameRow.AllowDefections, GameDevelopments = gameRow.AllowDevelopments, GameShipyards = gameRow.AllowShipyards, GameConquest = gameRow.Conquest, GameCore = TrimString(gameRow.CoreFile, 50), GameDeathMatch = gameRow.DeathMatch, GameDeathmatchGoal = gameRow.DeathmatchGoal, GameEndTime = gameRow.EndTime, GameFriendlyFire = gameRow.FriendlyFire, GameName = TrimString(gameRow.GameName, 254), GameInvulStations = gameRow.InvulnerableStations, GameMap = TrimString(gameRow.MapName, 49), GameMaxImbalance = gameRow.MaxImbalance, GameResources = gameRow.Resources, GameRevealMap = gameRow.RevealMap, GameSquadGame = gameRow.SquadGame, GameStartingMoney = gameRow.StartingMoney, GameStartTime = gameRow.StartTime, GameStatsCount = gameRow.StatsCount, GameTotalMoney = gameRow.TotalMoney, GameID = gameRow.GameID, GameServer = gameServer.GameServerID }; statsDB.Games.InsertOnSubmit(game); try { statsDB.SubmitChanges(); } catch (Exception ex) { string dbLengthErrors = Utilities.LinqErrorDetector.AnalyzeDBChanges(statsDB); throw new Exception("CSSStats[games]: DB Error, Linq Length Analysis: " + dbLengthErrors + "\r\n", ex); } SaveGameEvents(db, statsDB, gameRow, game.GameIdentID); SaveTeams(db, statsDB, gameRow, game.GameIdentID); SaveChatLog(db, statsDB, gameRow, game.GameIdentID); try { statsDB.SubmitChanges(); } catch (Exception ex) { string dbLengthErrors = Utilities.LinqErrorDetector.AnalyzeDBChanges(statsDB); throw new Exception("CSSStats[game data]: DB Error, Linq Length Analysis: " + dbLengthErrors + "\r\n", ex); } try { db.SubmitChanges(); } catch (Exception ex) { string dbLengthErrors = Utilities.LinqErrorDetector.AnalyzeDBChanges(db); throw new Exception("CSS DB Error, Linq Length Analysis: " + dbLengthErrors + "\r\n", ex); } statsDB.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, game); UpdateLeaderboard(game.GameIdentID); UpdateFactionStats(game.GameIdentID); UpdateMetrics(game.GameIdentID); statsDB.SubmitChanges(); db.SubmitChanges(); return(game.GameIdentID); }
public override bool DeleteUser(string username, bool deleteAllRelatedData) { using (var db = new DataAccess.CSSDataContext()) { DataAccess.Login login = DataAccess.Login.FindLoginByUsernameOrCallsign(db, username); DataAccess.Identity identity = db.Identities.FirstOrDefault(p => p.Id == login.IdentityId); if (identity != null) { db.Identities.DeleteOnSubmit(identity); db.SubmitChanges(); return true; } } return false; }
public int SaveGameData(string gameData, bool isCompressedAndBase64Encoded, out string message) { try { Data.GameDataset gameDataset = new Data.GameDataset(); //gameDataset.EnforceConstraints = false; //gameDataset. if (isCompressedAndBase64Encoded == true) { byte[] binaryGameData = Convert.FromBase64String(gameData); MemoryStream memoryStream = new MemoryStream(binaryGameData); ICSharpCode.SharpZipLib.GZip.GZipInputStream zipStream = new ICSharpCode.SharpZipLib.GZip.GZipInputStream(memoryStream); StreamReader streamReader = new StreamReader(zipStream, System.Text.Encoding.Unicode); //string gameDataXml = streamReader.ReadToEnd(); gameDataset.ReadXml(streamReader, System.Data.XmlReadMode.IgnoreSchema); } else { //gameDataset.ReadXml(new StringReader(gameData)); gameDataset.ReadXml(new StringReader(gameData), System.Data.XmlReadMode.IgnoreSchema); } if (String.IsNullOrEmpty(Settings.Default.TagLastGameDataXmlFileLogLocation) == false) { File.WriteAllText(Path.Combine(Settings.Default.TagLastGameDataXmlFileLogLocation, Guid.NewGuid().ToString() + ".xml"), gameDataset.GetXml()); } string currentIPAddress; if (OperationContext.Current != null) { //http://nayyeri.net/detect-client-ip-in-wcf-3-5 OperationContext context = OperationContext.Current; MessageProperties messageProperties = context.IncomingMessageProperties; RemoteEndpointMessageProperty endpointProperty = (RemoteEndpointMessageProperty)messageProperties[RemoteEndpointMessageProperty.Name]; currentIPAddress = endpointProperty.Address; } else { currentIPAddress = "127.0.0.1"; // Supports unit tests. } int gameID = 0; using (DataAccess.CSSDataContext db = new DataAccess.CSSDataContext()) { using (DataAccess.CSSStatsDataContext statsDB = new DataAccess.CSSStatsDataContext()) { var gameServer = statsDB.GameServers.FirstOrDefault(p => p.GameServerIPs.Where(r => r.IPAddress == currentIPAddress).Count() > 0); if (gameServer == null) { throw new Exception("You may not upload data from this address: " + currentIPAddress); } try { foreach (Data.GameDataset.GameRow gameRow in gameDataset.Game) { gameID = SaveGame(db, statsDB, gameServer, gameRow); } } catch (Exception ex) { if (String.IsNullOrEmpty(Settings.Default.TagExceptionLogFileName) == false) { File.AppendAllText(Settings.Default.TagExceptionLogFileName, DateTime.Now.ToString() + ": " + ex.ToString() + "\n\n\n"); } throw; } statsDB.SubmitChanges(); db.SubmitChanges(); } } // Update AllegSkill rank. AllegSkill.Calculator.UpdateAllegSkillForGame(gameID); // Update Prestige Rank. using (DataAccess.CSSStatsDataContext statsDB = new DataAccess.CSSStatsDataContext()) { var game = statsDB.Games.FirstOrDefault(p => p.GameIdentID == gameID); if (game == null) { Error.Write(new Exception("Tag.SaveGameData(): Couldn't get game for GameID: " + gameID)); } else { PrestigeRankCalculator psc = new PrestigeRankCalculator(); psc.Calculate(statsDB, game); } } message = "Game saved."; return(gameID); } catch (Exception ex) { message = ex.ToString(); return(-1); } }
public override string ResetPassword(string username, string answer) { string newPassword = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters); string hashedPassword = Allegiance.CommunitySecuritySystem.Common.Utility.Encryption.SHA256Hash(newPassword); using (var db = new DataAccess.CSSDataContext()) { var login = db.Logins.FirstOrDefault(p => p.Username == username.Trim()); login.Password = hashedPassword; db.SubmitChanges(); } return newPassword; }
public void SendMessageToGroup(int groupID, string subject, string message, string sendOnOrAfterDateTime, string expiresAfterDateTime) { ValidateMessage(subject, message); using (DataAccess.CSSDataContext db = new DataAccess.CSSDataContext()) { var login = DataAccess.Login.FindLoginByUsernameOrCallsign(db, HttpContext.Current.User.Identity.Name); // Get the groups the login has rights to send messages to. var availableGroups = DataAccess.Group.GetGroupsForLogin(db, login.Username, false); // Get the target group. var group = availableGroups.FirstOrDefault(p => p.Id == groupID); if (group == null) throw new Exception("Couldn't find group id: " + groupID); // Get the GAGR for the login assigned to the group that has the SL or ASL role. var gagrSender = group.Group_Alias_GroupRoles.FirstOrDefault(p => p.Alias.Login.Username.Equals(login.Username, StringComparison.InvariantCultureIgnoreCase) && (p.GroupRole.Name == "Squad Leader" || p.GroupRole.Name == "Assistant Squad Leader" || p.GroupRole.Name == "Zone Lead")); if (gagrSender == null) throw new Exception(HttpContext.Current.User.Identity.Name + " does not have rights to send this message."); DateTime dateToSend = DateTime.Parse(sendOnOrAfterDateTime); DateTime dateExpires = DateTime.Parse(expiresAfterDateTime); DataAccess.GroupMessage groupMessage = new Allegiance.CommunitySecuritySystem.DataAccess.GroupMessage() { DateCreated = DateTime.Now, DateExpires = dateExpires, DateToSend = dateToSend, GroupId = group.Id, Message = message, SenderAliasId = gagrSender.Alias.Id, Subject = subject }; db.GroupMessages.InsertOnSubmit(groupMessage); db.SubmitChanges(); foreach (var targetAlias in group.Group_Alias_GroupRoles.Select(p => p.Alias).Distinct()) { db.GroupMessage_Alias.InsertOnSubmit(new DataAccess.GroupMessage_Alias() { Alias = targetAlias, DateViewed = null, GroupMessage = groupMessage }); } db.SubmitChanges(); } }
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { using (var db = new DataAccess.CSSDataContext()) { foreach (string username in usernames) { DataAccess.Login login = db.Logins.FirstOrDefault(p => p.Username == username.Trim()); foreach (DataAccess.Login_Role loginRole in login.Login_Roles) { foreach(string roleName in roleNames) { if (loginRole.Role.Name.Equals(roleName.Trim()) == true) db.Login_Roles.DeleteOnSubmit(loginRole); } } } db.SubmitChanges(); } }
// When the role dropdown changes in the datagrid. protected void ddlRoles_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddlRoles = (DropDownList)sender; GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent; HiddenField txtGroupID = (HiddenField)row.FindControl("txtGroupID"); HiddenField txtAliasID = (HiddenField)row.FindControl("txtAliasID"); int groupID = Int32.Parse(txtGroupID.Value); int aliasID = Int32.Parse(txtAliasID.Value); int roleID = Int32.Parse(ddlRoles.SelectedValue); bool requiresSquadLeader = false; // Only a SL can grant SL to another user. if (ddlRoles.SelectedItem.Text == "Squad Leader") requiresSquadLeader = true; using (var db = new DataAccess.CSSDataContext()) { var group = db.Groups.FirstOrDefault(p => p.Id == groupID); var groupRole = db.Group_Alias_GroupRoles.FirstOrDefault(p => p.AliasId == aliasID && p.GroupId == groupID); if (groupRole == null) throw new Exception("Couldn't set role for group. Group may have been deleted from alias, or role is no longer available."); var login = DataAccess.Login.FindLoginByUsernameOrCallsign(db, User.Identity.Name); var gagrLogin = groupRole.Group.Group_Alias_GroupRoles.FirstOrDefault(p => p.Alias.LoginId == login.Id); if (group.IsSquad == true) { // Only a SL can remove rights to another SL. if (groupRole.GroupRole.Name.Equals("Squad Leader", StringComparison.InvariantCultureIgnoreCase) == true) requiresSquadLeader = true; bool isSquadLeader = gagrLogin.GroupRole.Name.Equals("Squad Leader", StringComparison.InvariantCultureIgnoreCase); bool isAssistantSquadLeader = gagrLogin.GroupRole.Name.Equals("Assistant Squad Leader", StringComparison.InvariantCultureIgnoreCase); if ((isSquadLeader == false && isAssistantSquadLeader == false) || (requiresSquadLeader == true && isSquadLeader == false)) { lblErrorMessage.Text = "You don't have rights to perform this action."; return; } } else { //var moderatorRole = db.Roles.FirstOrDefault(p => p.Name == "Moderator"); //bool requiresZoneLeader = false; //if (groupRole.GroupRole.Name.Equals("Zone Lead", StringComparison.InvariantCultureIgnoreCase) == true) // requiresZoneLeader = true; bool requiresZoneLeader = true; if (login.HasAnyRole(new Common.Enumerations.RoleType[] { Common.Enumerations.RoleType.ZoneLeader, Common.Enumerations.RoleType.Administrator, Common.Enumerations.RoleType.SuperAdministrator }) == false && requiresZoneLeader == true) { lblErrorMessage.Text = "You must be a Zone Leader or better to perform this action."; return; } } } // Can't use groupRole from above, some of the queries against it cause it to lock to a foreign key. using (var db = new DataAccess.CSSDataContext()) { var groupRoleToUpdate = db.Group_Alias_GroupRoles.FirstOrDefault(p => p.AliasId == aliasID && p.GroupId == groupID); groupRoleToUpdate.GroupRoleId = roleID; // If the group is ACS, then bank the alias if the user is going into the pilot role, // otherwise unbank it if they are going into a token'd role. if (groupRoleToUpdate.Group.Tag.Equals("acs", StringComparison.InvariantCultureIgnoreCase) == true) { if (groupRoleToUpdate.GroupRole.Token == null) BankAlias(db, groupRoleToUpdate.Alias); else UnbankAlias(db, groupRoleToUpdate.Alias); } db.SubmitChanges(); } BindData(groupID); }
private void AddCallsignToGroup(string callsign, int groupID) { Business.GroupRole currentUserGroupRole = GetCurrentUserGroupRole(groupID); if (currentUserGroupRole != Business.GroupRole.AssistantSquadLeader && currentUserGroupRole != Business.GroupRole.SquadLeader && currentUserGroupRole != Business.GroupRole.ZoneLead) throw new Exception("Access denied."); using (var db = new DataAccess.CSSDataContext()) { var group = db.Groups.FirstOrDefault(p => p.Id == groupID); if (group == null) throw new Exception("Invalid groupID"); var alias = db.Alias.FirstOrDefault(p => p.Callsign == callsign); if (alias == null) throw new Exception("Invalid callsign"); var targetRole = db.GroupRoles.FirstOrDefault(p => p.Name == "Pilot"); if (targetRole == null) throw new Exception("No pilot role."); DataAccess.Group_Alias_GroupRole gagrTarget = new DataAccess.Group_Alias_GroupRole() { AliasId = alias.Id, GroupId = group.Id, GroupRoleId = targetRole.Id }; db.Group_Alias_GroupRoles.InsertOnSubmit(gagrTarget); // If the group name is the Moderators group, then add the Moderator role to the group member. if (group.Name.Equals("Moderators", StringComparison.InvariantCultureIgnoreCase) == true) { var moderatorRole = db.Roles.FirstOrDefault(p => p.Name == "Moderator"); var loginRole = db.Login_Roles.FirstOrDefault(p => p.LoginId == alias.LoginId && p.RoleId == moderatorRole.Id); if (loginRole == null) { db.Login_Roles.InsertOnSubmit(new DataAccess.Login_Role() { LoginId = alias.LoginId, RoleId = moderatorRole.Id }); } } // If the group is ACS, then bank the original alias, and swap the alias to an ACS_COM_XXX hider. if (group.Tag.Equals("acs", StringComparison.InvariantCultureIgnoreCase) == true) { BankAlias(db, alias); } db.SubmitChanges(); } Response.Redirect("~/Squads/Default.aspx?groupID=" + groupID, true); }
public override bool ChangePassword(string username, string oldPassword, string newPassword) { string oldPasswordHash = Allegiance.CommunitySecuritySystem.Common.Utility.Encryption.SHA256Hash(oldPassword); string newPasswordHash = Allegiance.CommunitySecuritySystem.Common.Utility.Encryption.SHA256Hash(newPassword); using (var db = new DataAccess.CSSDataContext()) { DataAccess.Login login = DataAccess.Login.FindLogin(db, username, oldPasswordHash); if (login == null) return false; login.Password = newPasswordHash; db.SubmitChanges(); } return true; }
// When the role dropdown changes in the datagrid. protected void ddlRoles_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddlRoles = (DropDownList)sender; GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent; HiddenField txtGroupID = (HiddenField)row.FindControl("txtGroupID"); HiddenField txtAliasID = (HiddenField)row.FindControl("txtAliasID"); int groupID = Int32.Parse(txtGroupID.Value); int aliasID = Int32.Parse(txtAliasID.Value); int roleID = Int32.Parse(ddlRoles.SelectedValue); bool requiresSquadLeader = false; // Only a SL can grant SL to another user. if (ddlRoles.SelectedItem.Text == "Squad Leader") { requiresSquadLeader = true; } using (var db = new DataAccess.CSSDataContext()) { var group = db.Groups.FirstOrDefault(p => p.Id == groupID); var groupRole = db.Group_Alias_GroupRoles.FirstOrDefault(p => p.AliasId == aliasID && p.GroupId == groupID); if (groupRole == null) { throw new Exception("Couldn't set role for group. Group may have been deleted from alias, or role is no longer available."); } var login = DataAccess.Login.FindLoginByUsernameOrCallsign(db, User.Identity.Name); var gagrLogin = groupRole.Group.Group_Alias_GroupRoles.FirstOrDefault(p => p.Alias.LoginId == login.Id); if (group.IsSquad == true) { // Only a SL can remove rights to another SL. if (groupRole.GroupRole.Name.Equals("Squad Leader", StringComparison.InvariantCultureIgnoreCase) == true) { requiresSquadLeader = true; } bool isSquadLeader = gagrLogin.GroupRole.Name.Equals("Squad Leader", StringComparison.InvariantCultureIgnoreCase); bool isAssistantSquadLeader = gagrLogin.GroupRole.Name.Equals("Assistant Squad Leader", StringComparison.InvariantCultureIgnoreCase); if ((isSquadLeader == false && isAssistantSquadLeader == false) || (requiresSquadLeader == true && isSquadLeader == false)) { lblErrorMessage.Text = "You don't have rights to perform this action."; return; } } else { //var moderatorRole = db.Roles.FirstOrDefault(p => p.Name == "Moderator"); //bool requiresZoneLeader = false; //if (groupRole.GroupRole.Name.Equals("Zone Lead", StringComparison.InvariantCultureIgnoreCase) == true) // requiresZoneLeader = true; bool requiresZoneLeader = true; if (login.HasAnyRole(new Common.Enumerations.RoleType[] { Common.Enumerations.RoleType.ZoneLeader, Common.Enumerations.RoleType.Administrator, Common.Enumerations.RoleType.SuperAdministrator }) == false && requiresZoneLeader == true) { lblErrorMessage.Text = "You must be a Zone Leader or better to perform this action."; return; } } } // Can't use groupRole from above, some of the queries against it cause it to lock to a foreign key. using (var db = new DataAccess.CSSDataContext()) { var groupRoleToUpdate = db.Group_Alias_GroupRoles.FirstOrDefault(p => p.AliasId == aliasID && p.GroupId == groupID); groupRoleToUpdate.GroupRoleId = roleID; // If the group is ACS, then bank the alias if the user is going into the pilot role, // otherwise unbank it if they are going into a token'd role. if (groupRoleToUpdate.Group.Tag.Equals("acs", StringComparison.InvariantCultureIgnoreCase) == true) { if (groupRoleToUpdate.GroupRole.Token == null) { BankAlias(db, groupRoleToUpdate.Alias); } else { UnbankAlias(db, groupRoleToUpdate.Alias); } } db.SubmitChanges(); } BindData(groupID); }
private void DeleteAlias(int aliasID) { using (var db = new DataAccess.CSSDataContext()) { var aliasToDelete = db.Alias.FirstOrDefault(p => p.Id == aliasID); if (aliasToDelete != null) { db.PersonalMessages.DeleteAllOnSubmit(aliasToDelete.PersonalMessages); db.GroupMessages.DeleteAllOnSubmit(aliasToDelete.GroupMessages); db.GroupRequests.DeleteAllOnSubmit(aliasToDelete.GroupRequests); db.Group_Alias_GroupRoles.DeleteAllOnSubmit(aliasToDelete.Group_Alias_GroupRoles); db.GroupMessage_Alias.DeleteAllOnSubmit(aliasToDelete.GroupMessage_Alias); db.AliasBanks.DeleteAllOnSubmit(aliasToDelete.AliasBanks); db.Alias.DeleteOnSubmit(aliasToDelete); db.SubmitChanges(); } } if (OnRequiresDataBind != null) OnRequiresDataBind(); ForcePageReload = true; }