diff --git a/CHANGELOG.md b/CHANGELOG.md index 14bce826..2999805e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ This is the rolling changelog for TShock for Terraria. Use past tense when addin * Fixed /savessc not bothering to save ssc data for people who bypass ssc. (@hakusaro) * Default permission sets for new databases are more modern. (@hakusaro) * Added the ability to ban by account name instead of just banning a character name assuming its an account name. (@hakusaro) +* Renamed TShock.DB.User to TShock.DB.UserAccount, including all the related methods, classes and events. (@Ryozuki) ## TShock 4.3.24 * Updated OpenTerraria API to 1.3.5.3 (@DeathCradle) diff --git a/TShockAPI/Commands.cs b/TShockAPI/Commands.cs index 72cddc6a..592177cf 100644 --- a/TShockAPI/Commands.cs +++ b/TShockAPI/Commands.cs @@ -193,11 +193,17 @@ namespace TShockAPI public static List ChatCommands = new List(); public static ReadOnlyCollection TShockCommands = new ReadOnlyCollection(new List()); + /// + /// The command specifier, defaults to "/" + /// public static string Specifier { get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSpecifier) ? "/" : TShock.Config.CommandSpecifier; } } + /// + /// The silent command specifier, defaults to "." + /// public static string SilentSpecifier { get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSilentSpecifier) ? "." : TShock.Config.CommandSilentSpecifier; } @@ -787,7 +793,7 @@ namespace TShockAPI return; } - User user = TShock.Users.GetUserByName(args.Player.Name); + UserAccount account = TShock.UserAccounts.GetUserAccountByName(args.Player.Name); string password = ""; bool usingUUID = false; if (args.Parameters.Count == 0 && !TShock.Config.DisableUUIDLogin) @@ -813,7 +819,7 @@ namespace TShockAPI if (PlayerHooks.OnPlayerPreLogin(args.Player, args.Parameters[0], args.Parameters[1])) return; - user = TShock.Users.GetUserByName(args.Parameters[0]); + account = TShock.UserAccounts.GetUserAccountByName(args.Parameters[0]); password = args.Parameters[1]; } else @@ -826,21 +832,21 @@ namespace TShockAPI } try { - if (user == null) + if (account == null) { - args.Player.SendErrorMessage("A user by that name does not exist."); + args.Player.SendErrorMessage("A user account by that name does not exist."); } - else if (user.VerifyPassword(password) || - (usingUUID && user.UUID == args.Player.UUID && !TShock.Config.DisableUUIDLogin && + else if (account.VerifyPassword(password) || + (usingUUID && account.UUID == args.Player.UUID && !TShock.Config.DisableUUIDLogin && !String.IsNullOrWhiteSpace(args.Player.UUID))) { - args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, user.ID); + args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, account.ID); - var group = TShock.Utils.GetGroup(user.Group); + var group = TShock.Utils.GetGroup(account.Group); args.Player.Group = group; args.Player.tempGroup = null; - args.Player.User = user; + args.Player.Account = account; args.Player.IsLoggedIn = true; args.Player.IgnoreActionsForInventory = "none"; @@ -861,9 +867,9 @@ namespace TShockAPI if (args.Player.HasPermission(Permissions.usebanneditem)) args.Player.IgnoreActionsForDisabledArmor = "none"; - args.Player.SendSuccessMessage("Authenticated as " + user.Name + " successfully."); + args.Player.SendSuccessMessage("Authenticated as " + account.Name + " successfully."); - TShock.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user: " + user.Name + "."); + TShock.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user: " + account.Name + "."); if ((args.Player.LoginHarassed) && (TShock.Config.RememberLeavePos)) { if (TShock.RememberedPos.GetLeavePos(args.Player.Name, args.Player.IP) != Vector2.Zero) @@ -874,7 +880,7 @@ namespace TShockAPI args.Player.LoginHarassed = false; } - TShock.Users.SetUserUUID(user, args.Player.UUID); + TShock.UserAccounts.SetUserAccountUUID(account, args.Player.UUID); Hooks.PlayerHooks.OnPlayerPostLogin(args.Player); } @@ -888,7 +894,7 @@ namespace TShockAPI { args.Player.SendErrorMessage("Invalid password!"); } - TShock.Log.Warn(args.Player.IP + " failed to authenticate as user: " + user.Name + "."); + TShock.Log.Warn(args.Player.IP + " failed to authenticate as user: " + account.Name + "."); args.Player.LoginAttempts++; } } @@ -922,14 +928,14 @@ namespace TShockAPI if (args.Player.IsLoggedIn && args.Parameters.Count == 2) { string password = args.Parameters[0]; - if (args.Player.User.VerifyPassword(password)) + if (args.Player.Account.VerifyPassword(password)) { try { args.Player.SendSuccessMessage("You changed your password!"); - TShock.Users.SetUserPassword(args.Player.User, args.Parameters[1]); // SetUserPassword will hash it for you. + TShock.UserAccounts.SetUserAccountPassword(args.Player.Account, args.Parameters[1]); // SetUserPassword will hash it for you. TShock.Log.ConsoleInfo(args.Player.IP + " named " + args.Player.Name + " changed the password of account " + - args.Player.User.Name + "."); + args.Player.Account.Name + "."); } catch (ArgumentOutOfRangeException) { @@ -940,7 +946,7 @@ namespace TShockAPI { args.Player.SendErrorMessage("You failed to change your password!"); TShock.Log.ConsoleError(args.Player.IP + " named " + args.Player.Name + " failed to change password for account: " + - args.Player.User.Name + "."); + args.Player.Account.Name + "."); } } else @@ -948,7 +954,7 @@ namespace TShockAPI args.Player.SendErrorMessage("Not logged in or invalid syntax! Proper syntax: {0}password ", Specifier); } } - catch (UserManagerException ex) + catch (UserAccountManagerException ex) { args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + "."); TShock.Log.ConsoleError("PasswordUser returned an error: " + ex); @@ -959,15 +965,15 @@ namespace TShockAPI { try { - var user = new User(); + var account = new UserAccount(); string echoPassword = ""; if (args.Parameters.Count == 1) { - user.Name = args.Player.Name; + account.Name = args.Player.Name; echoPassword = args.Parameters[0]; try { - user.CreateBCryptHash(args.Parameters[0]); + account.CreateBCryptHash(args.Parameters[0]); } catch (ArgumentOutOfRangeException) { @@ -977,11 +983,11 @@ namespace TShockAPI } else if (args.Parameters.Count == 2 && TShock.Config.AllowRegisterAnyUsername) { - user.Name = args.Parameters[0]; + account.Name = args.Parameters[0]; echoPassword = args.Parameters[1]; try { - user.CreateBCryptHash(args.Parameters[1]); + account.CreateBCryptHash(args.Parameters[1]); } catch (ArgumentOutOfRangeException) { @@ -995,24 +1001,24 @@ namespace TShockAPI return; } - user.Group = TShock.Config.DefaultRegistrationGroupName; // FIXME -- we should get this from the DB. --Why? - user.UUID = args.Player.UUID; + account.Group = TShock.Config.DefaultRegistrationGroupName; // FIXME -- we should get this from the DB. --Why? + account.UUID = args.Player.UUID; - if (TShock.Users.GetUserByName(user.Name) == null && user.Name != TSServerPlayer.AccountName) // Cheap way of checking for existance of a user + if (TShock.UserAccounts.GetUserAccountByName(account.Name) == null && account.Name != TSServerPlayer.AccountName) // Cheap way of checking for existance of a user { - args.Player.SendSuccessMessage("Account \"{0}\" has been registered.", user.Name); + args.Player.SendSuccessMessage("Account \"{0}\" has been registered.", account.Name); args.Player.SendSuccessMessage("Your password is {0}.", echoPassword); - TShock.Users.AddUser(user); - TShock.Log.ConsoleInfo("{0} registered an account: \"{1}\".", args.Player.Name, user.Name); + TShock.UserAccounts.AddUserAccount(account); + TShock.Log.ConsoleInfo("{0} registered an account: \"{1}\".", args.Player.Name, account.Name); } else { - args.Player.SendErrorMessage("Sorry, " + user.Name + " was already taken by another person."); + args.Player.SendErrorMessage("Sorry, " + account.Name + " was already taken by another person."); args.Player.SendErrorMessage("Please try a different username."); - TShock.Log.ConsoleInfo(args.Player.Name + " failed to register an existing account: " + user.Name); + TShock.Log.ConsoleInfo(args.Player.Name + " failed to register an existing account: " + account.Name); } } - catch (UserManagerException ex) + catch (UserAccountManagerException ex) { args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + "."); TShock.Log.ConsoleError("RegisterUser returned an error: " + ex); @@ -1033,57 +1039,57 @@ namespace TShockAPI // Add requires a username, password, and a group specified. if (subcmd == "add" && args.Parameters.Count == 4) { - var user = new User(); + var account = new UserAccount(); - user.Name = args.Parameters[1]; + account.Name = args.Parameters[1]; try { - user.CreateBCryptHash(args.Parameters[2]); + account.CreateBCryptHash(args.Parameters[2]); } catch (ArgumentOutOfRangeException) { args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters."); return; } - user.Group = args.Parameters[3]; + account.Group = args.Parameters[3]; try { - TShock.Users.AddUser(user); - args.Player.SendSuccessMessage("Account " + user.Name + " has been added to group " + user.Group + "!"); - TShock.Log.ConsoleInfo(args.Player.Name + " added Account " + user.Name + " to group " + user.Group); + TShock.UserAccounts.AddUserAccount(account); + args.Player.SendSuccessMessage("Account " + account.Name + " has been added to group " + account.Group + "!"); + TShock.Log.ConsoleInfo(args.Player.Name + " added Account " + account.Name + " to group " + account.Group); } catch (GroupNotExistsException) { - args.Player.SendErrorMessage("Group " + user.Group + " does not exist!"); + args.Player.SendErrorMessage("Group " + account.Group + " does not exist!"); } - catch (UserExistsException) + catch (UserAccountExistsException) { - args.Player.SendErrorMessage("User " + user.Name + " already exists!"); + args.Player.SendErrorMessage("User " + account.Name + " already exists!"); } - catch (UserManagerException e) + catch (UserAccountManagerException e) { - args.Player.SendErrorMessage("User " + user.Name + " could not be added, check console for details."); + args.Player.SendErrorMessage("User " + account.Name + " could not be added, check console for details."); TShock.Log.ConsoleError(e.ToString()); } } // User deletion requires a username else if (subcmd == "del" && args.Parameters.Count == 2) { - var user = new User(); - user.Name = args.Parameters[1]; + var account = new UserAccount(); + account.Name = args.Parameters[1]; try { - TShock.Users.RemoveUser(user); + TShock.UserAccounts.RemoveUserAccount(account); args.Player.SendSuccessMessage("Account removed successfully."); TShock.Log.ConsoleInfo(args.Player.Name + " successfully deleted account: " + args.Parameters[1] + "."); } - catch (UserNotExistException) + catch (UserAccountNotExistException) { - args.Player.SendErrorMessage("The user " + user.Name + " does not exist! Deleted nobody!"); + args.Player.SendErrorMessage("The user " + account.Name + " does not exist! Deleted nobody!"); } - catch (UserManagerException ex) + catch (UserAccountManagerException ex) { args.Player.SendErrorMessage(ex.Message); TShock.Log.ConsoleError(ex.ToString()); @@ -1093,22 +1099,22 @@ namespace TShockAPI // Password changing requires a username, and a new password to set else if (subcmd == "password" && args.Parameters.Count == 3) { - var user = new User(); - user.Name = args.Parameters[1]; + var account = new UserAccount(); + account.Name = args.Parameters[1]; try { - TShock.Users.SetUserPassword(user, args.Parameters[2]); - TShock.Log.ConsoleInfo(args.Player.Name + " changed the password of account " + user.Name); - args.Player.SendSuccessMessage("Password change succeeded for " + user.Name + "."); + TShock.UserAccounts.SetUserAccountPassword(account, args.Parameters[2]); + TShock.Log.ConsoleInfo(args.Player.Name + " changed the password of account " + account.Name); + args.Player.SendSuccessMessage("Password change succeeded for " + account.Name + "."); } - catch (UserNotExistException) + catch (UserAccountNotExistException) { - args.Player.SendErrorMessage("User " + user.Name + " does not exist!"); + args.Player.SendErrorMessage("User " + account.Name + " does not exist!"); } - catch (UserManagerException e) + catch (UserAccountManagerException e) { - args.Player.SendErrorMessage("Password change for " + user.Name + " failed! Check console!"); + args.Player.SendErrorMessage("Password change for " + account.Name + " failed! Check console!"); TShock.Log.ConsoleError(e.ToString()); } catch (ArgumentOutOfRangeException) @@ -1119,26 +1125,26 @@ namespace TShockAPI // Group changing requires a username or IP address, and a new group to set else if (subcmd == "group" && args.Parameters.Count == 3) { - var user = new User(); - user.Name = args.Parameters[1]; + var account = new UserAccount(); + account.Name = args.Parameters[1]; try { - TShock.Users.SetUserGroup(user, args.Parameters[2]); - TShock.Log.ConsoleInfo(args.Player.Name + " changed account " + user.Name + " to group " + args.Parameters[2] + "."); - args.Player.SendSuccessMessage("Account " + user.Name + " has been changed to group " + args.Parameters[2] + "!"); + TShock.UserAccounts.SetUserGroup(account, args.Parameters[2]); + TShock.Log.ConsoleInfo(args.Player.Name + " changed account " + account.Name + " to group " + args.Parameters[2] + "."); + args.Player.SendSuccessMessage("Account " + account.Name + " has been changed to group " + args.Parameters[2] + "!"); } catch (GroupNotExistsException) { args.Player.SendErrorMessage("That group does not exist!"); } - catch (UserNotExistException) + catch (UserAccountNotExistException) { - args.Player.SendErrorMessage("User " + user.Name + " does not exist!"); + args.Player.SendErrorMessage("User " + account.Name + " does not exist!"); } - catch (UserManagerException e) + catch (UserAccountManagerException e) { - args.Player.SendErrorMessage("User " + user.Name + " could not be added. Check console for details."); + args.Player.SendErrorMessage("User " + account.Name + " could not be added. Check console for details."); TShock.Log.ConsoleError(e.ToString()); } } @@ -1198,8 +1204,8 @@ namespace TShockAPI { var message = new StringBuilder(); message.Append("IP Address: ").Append(players[0].IP); - if (players[0].User != null && players[0].IsLoggedIn) - message.Append(" | Logged in as: ").Append(players[0].User.Name).Append(" | Group: ").Append(players[0].Group.Name); + if (players[0].Account != null && players[0].IsLoggedIn) + message.Append(" | Logged in as: ").Append(players[0].Account.Name).Append(" | Group: ").Append(players[0].Group.Name); args.Player.SendSuccessMessage(message.ToString()); } } @@ -1215,28 +1221,28 @@ namespace TShockAPI string username = String.Join(" ", args.Parameters); if (!string.IsNullOrWhiteSpace(username)) { - var user = TShock.Users.GetUserByName(username); - if (user != null) + var account = TShock.UserAccounts.GetUserAccountByName(username); + if (account != null) { DateTime LastSeen; string Timezone = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours.ToString("+#;-#"); - if (DateTime.TryParse(user.LastAccessed, out LastSeen)) + if (DateTime.TryParse(account.LastAccessed, out LastSeen)) { - LastSeen = DateTime.Parse(user.LastAccessed).ToLocalTime(); - args.Player.SendSuccessMessage("{0}'s last login occured {1} {2} UTC{3}.", user.Name, LastSeen.ToShortDateString(), + LastSeen = DateTime.Parse(account.LastAccessed).ToLocalTime(); + args.Player.SendSuccessMessage("{0}'s last login occured {1} {2} UTC{3}.", account.Name, LastSeen.ToShortDateString(), LastSeen.ToShortTimeString(), Timezone); } if (args.Player.Group.HasPermission(Permissions.advaccountinfo)) { - List KnownIps = JsonConvert.DeserializeObject>(user.KnownIps?.ToString() ?? string.Empty); + List KnownIps = JsonConvert.DeserializeObject>(account.KnownIps?.ToString() ?? string.Empty); string ip = KnownIps?[KnownIps.Count - 1] ?? "N/A"; - DateTime Registered = DateTime.Parse(user.Registered).ToLocalTime(); + DateTime Registered = DateTime.Parse(account.Registered).ToLocalTime(); - args.Player.SendSuccessMessage("{0}'s group is {1}.", user.Name, user.Group); - args.Player.SendSuccessMessage("{0}'s last known IP is {1}.", user.Name, ip); - args.Player.SendSuccessMessage("{0}'s register date is {1} {2} UTC{3}.", user.Name, Registered.ToShortDateString(), Registered.ToShortTimeString(), Timezone); + args.Player.SendSuccessMessage("{0}'s group is {1}.", account.Name, account.Group); + args.Player.SendSuccessMessage("{0}'s last known IP is {1}.", account.Name, ip); + args.Player.SendSuccessMessage("{0}'s register date is {1} {2} UTC{3}.", account.Name, Registered.ToShortDateString(), Registered.ToShortTimeString(), Timezone); } } else @@ -1303,7 +1309,7 @@ namespace TShockAPI // Effective ban target assignment List players = TShock.Utils.FindPlayer(args.Parameters[1]); - User offlineUser = TShock.Users.GetUserByName(args.Parameters[1]); + UserAccount offlineUserAccount = TShock.UserAccounts.GetUserAccountByName(args.Parameters[1]); // Storage variable to determine if the command executor is the server console // If it is, we assume they have full control and let them override permission checks @@ -1365,7 +1371,7 @@ namespace TShockAPI } targetGeneralizedName = target.Name; - success = TShock.Bans.AddBan2(target.IP, target.Name, target.UUID, target.User.Name, banReason, false, args.Player.User.Name, + success = TShock.Bans.AddBan2(target.IP, target.Name, target.UUID, target.Account.Name, banReason, false, args.Player.Account.Name, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s")); // Since this is an online ban, we need to dc the player and tell them now. @@ -1396,8 +1402,8 @@ namespace TShockAPI if (r.IsMatch(args.Parameters[1])) { targetGeneralizedName = "IP: " + args.Parameters[1]; success = TShock.Bans.AddBan2(args.Parameters[1], "", "", "", banReason, - false, args.Player.User.Name, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s")); - if (success && offlineUser != null) + false, args.Player.Account.Name, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s")); + if (success && offlineUserAccount != null) { args.Player.SendSuccessMessage("Target IP {0} was banned successfully.", targetGeneralizedName); args.Player.SendErrorMessage("Note: An account named with this IP address also exists."); @@ -1407,7 +1413,7 @@ namespace TShockAPI // Apparently there is no way to not IP ban someone // This means that where we would normally just ban a "character name" here // We can't because it requires some IP as a primary key. - if (offlineUser == null) + if (offlineUserAccount == null) { args.Player.SendErrorMessage("Unable to ban target {0}.", args.Parameters[1]); args.Player.SendErrorMessage("Target is not a valid IP address, a valid online player, or a known offline user."); @@ -1418,33 +1424,33 @@ namespace TShockAPI } // Case: Offline ban - if (players.Count == 0 && offlineUser != null) + if (players.Count == 0 && offlineUserAccount != null) { // Catch: we don't know an offline player's last login character name // This means that we're banning their *user name* on the assumption that // user name == character name // (which may not be true) // This needs to be fixed in a future implementation. - targetGeneralizedName = offlineUser.Name; + targetGeneralizedName = offlineUserAccount.Name; - if (TShock.Groups.GetGroupByName(offlineUser.Group).HasPermission(Permissions.immunetoban) && + if (TShock.Groups.GetGroupByName(offlineUserAccount.Group).HasPermission(Permissions.immunetoban) && !callerIsServerConsole) { args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", targetGeneralizedName); return; } - if (offlineUser.KnownIps == null) + if (offlineUserAccount.KnownIps == null) { args.Player.SendErrorMessage("Unable to ban target {0} because they have no valid IP to ban.", targetGeneralizedName); return; } - string lastIP = JsonConvert.DeserializeObject>(offlineUser.KnownIps).Last(); + string lastIP = JsonConvert.DeserializeObject>(offlineUserAccount.KnownIps).Last(); success = TShock.Bans.AddBan2(lastIP, - "", offlineUser.UUID, offlineUser.Name, banReason, false, args.Player.User.Name, + "", offlineUserAccount.UUID, offlineUserAccount.Name, banReason, false, args.Player.Account.Name, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s")); } @@ -1458,12 +1464,12 @@ namespace TShockAPI if (banLengthInSeconds == 0) { TSPlayer.All.SendErrorMessage("{0} was permanently banned by {1} for: {2}", - targetGeneralizedName, args.Player.User.Name, banReason); + targetGeneralizedName, args.Player.Account.Name, banReason); } else { TSPlayer.All.SendErrorMessage("{0} was temp banned for {1} seconds by {2} for: {3}", - targetGeneralizedName, banLengthInSeconds, args.Player.User.Name, banReason); + targetGeneralizedName, banLengthInSeconds, args.Player.Account.Name, banReason); } } } @@ -1780,7 +1786,7 @@ namespace TShockAPI if (ply.Count > 1) { - TShock.Utils.SendMultipleMatchError(args.Player, ply.Select(p => p.User.Name)); + TShock.Utils.SendMultipleMatchError(args.Player, ply.Select(p => p.Account.Name)); } if (!TShock.Groups.GroupExists(args.Parameters[1])) @@ -4187,7 +4193,7 @@ namespace TShockAPI var width = Math.Abs(args.Player.TempPoints[0].X - args.Player.TempPoints[1].X); var height = Math.Abs(args.Player.TempPoints[0].Y - args.Player.TempPoints[1].Y); - if (TShock.Regions.AddRegion(x, y, width, height, regionName, args.Player.User.Name, + if (TShock.Regions.AddRegion(x, y, width, height, regionName, args.Player.Account.Name, Main.worldID.ToString())) { args.Player.TempPoints[0] = Point.Zero; @@ -4276,7 +4282,7 @@ namespace TShockAPI regionName = regionName + " " + args.Parameters[i]; } } - if (TShock.Users.GetUserByName(playerName) != null) + if (TShock.UserAccounts.GetUserAccountByName(playerName) != null) { if (TShock.Regions.AddNewUser(regionName, playerName)) { @@ -4311,7 +4317,7 @@ namespace TShockAPI regionName = regionName + " " + args.Parameters[i]; } } - if (TShock.Users.GetUserByName(playerName) != null) + if (TShock.UserAccounts.GetUserAccountByName(playerName) != null) { if (TShock.Regions.RemoveUser(regionName, playerName)) { @@ -4452,9 +4458,9 @@ namespace TShockAPI { IEnumerable sharedUsersSelector = region.AllowedIDs.Select(userId => { - User user = TShock.Users.GetUserByID(userId); - if (user != null) - return user.Name; + UserAccount account = TShock.UserAccounts.GetUserAccountByID(userId); + if (account != null) + return account.Name; return string.Concat("{ID: ", userId, "}"); }); diff --git a/TShockAPI/DB/CharacterManager.cs b/TShockAPI/DB/CharacterManager.cs index 2c264138..1a399da8 100644 --- a/TShockAPI/DB/CharacterManager.cs +++ b/TShockAPI/DB/CharacterManager.cs @@ -120,7 +120,7 @@ namespace TShockAPI.DB return playerData; } - public bool SeedInitialData(User user) + public bool SeedInitialData(UserAccount account) { var inventory = new StringBuilder(); @@ -132,7 +132,7 @@ namespace TShockAPI.DB try { database.Query("INSERT INTO tsCharacter (Account, Health, MaxHealth, Mana, MaxMana, Inventory, spawnX, spawnY, questsCompleted) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8);", - user.ID, + account.ID, TShock.ServerSideCharacterConfig.StartingHealth, TShock.ServerSideCharacterConfig.StartingHealth, TShock.ServerSideCharacterConfig.StartingMana, @@ -165,17 +165,17 @@ namespace TShockAPI.DB if (player.HasPermission(Permissions.bypassssc) && !fromCommand) { - TShock.Log.ConsoleInfo("Skipping SSC Backup for " + player.User.Name); // Debug code + TShock.Log.ConsoleInfo("Skipping SSC Backup for " + player.Account.Name); // Debug code return false; } - if (!GetPlayerData(player, player.User.ID).exists) + if (!GetPlayerData(player, player.Account.ID).exists) { try { database.Query( "INSERT INTO tsCharacter (Account, Health, MaxHealth, Mana, MaxMana, Inventory, extraSlot, spawnX, spawnY, skinVariant, hair, hairDye, hairColor, pantsColor, shirtColor, underShirtColor, shoeColor, hideVisuals, skinColor, eyeColor, questsCompleted) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17, @18, @19, @20);", - player.User.ID, playerData.health, playerData.maxHealth, playerData.mana, playerData.maxMana, String.Join("~", playerData.inventory), playerData.extraSlot, player.TPlayer.SpawnX, player.TPlayer.SpawnY, player.TPlayer.skinVariant, player.TPlayer.hair, player.TPlayer.hairDye, TShock.Utils.EncodeColor(player.TPlayer.hairColor), TShock.Utils.EncodeColor(player.TPlayer.pantsColor),TShock.Utils.EncodeColor(player.TPlayer.shirtColor), TShock.Utils.EncodeColor(player.TPlayer.underShirtColor), TShock.Utils.EncodeColor(player.TPlayer.shoeColor), TShock.Utils.EncodeBoolArray(player.TPlayer.hideVisual), TShock.Utils.EncodeColor(player.TPlayer.skinColor),TShock.Utils.EncodeColor(player.TPlayer.eyeColor), player.TPlayer.anglerQuestsFinished); + player.Account.ID, playerData.health, playerData.maxHealth, playerData.mana, playerData.maxMana, String.Join("~", playerData.inventory), playerData.extraSlot, player.TPlayer.SpawnX, player.TPlayer.SpawnY, player.TPlayer.skinVariant, player.TPlayer.hair, player.TPlayer.hairDye, TShock.Utils.EncodeColor(player.TPlayer.hairColor), TShock.Utils.EncodeColor(player.TPlayer.pantsColor),TShock.Utils.EncodeColor(player.TPlayer.shirtColor), TShock.Utils.EncodeColor(player.TPlayer.underShirtColor), TShock.Utils.EncodeColor(player.TPlayer.shoeColor), TShock.Utils.EncodeBoolArray(player.TPlayer.hideVisual), TShock.Utils.EncodeColor(player.TPlayer.skinColor),TShock.Utils.EncodeColor(player.TPlayer.eyeColor), player.TPlayer.anglerQuestsFinished); return true; } catch (Exception ex) @@ -189,7 +189,7 @@ namespace TShockAPI.DB { database.Query( "UPDATE tsCharacter SET Health = @0, MaxHealth = @1, Mana = @2, MaxMana = @3, Inventory = @4, spawnX = @6, spawnY = @7, hair = @8, hairDye = @9, hairColor = @10, pantsColor = @11, shirtColor = @12, underShirtColor = @13, shoeColor = @14, hideVisuals = @15, skinColor = @16, eyeColor = @17, questsCompleted = @18, skinVariant = @19, extraSlot = @20 WHERE Account = @5;", - playerData.health, playerData.maxHealth, playerData.mana, playerData.maxMana, String.Join("~", playerData.inventory), player.User.ID, player.TPlayer.SpawnX, player.TPlayer.SpawnY, player.TPlayer.hair, player.TPlayer.hairDye, TShock.Utils.EncodeColor(player.TPlayer.hairColor), TShock.Utils.EncodeColor(player.TPlayer.pantsColor), TShock.Utils.EncodeColor(player.TPlayer.shirtColor), TShock.Utils.EncodeColor(player.TPlayer.underShirtColor), TShock.Utils.EncodeColor(player.TPlayer.shoeColor), TShock.Utils.EncodeBoolArray(player.TPlayer.hideVisual), TShock.Utils.EncodeColor(player.TPlayer.skinColor), TShock.Utils.EncodeColor(player.TPlayer.eyeColor), player.TPlayer.anglerQuestsFinished, player.TPlayer.skinVariant, player.TPlayer.extraAccessory ? 1 : 0); + playerData.health, playerData.maxHealth, playerData.mana, playerData.maxMana, String.Join("~", playerData.inventory), player.Account.ID, player.TPlayer.SpawnX, player.TPlayer.SpawnY, player.TPlayer.hair, player.TPlayer.hairDye, TShock.Utils.EncodeColor(player.TPlayer.hairColor), TShock.Utils.EncodeColor(player.TPlayer.pantsColor), TShock.Utils.EncodeColor(player.TPlayer.shirtColor), TShock.Utils.EncodeColor(player.TPlayer.underShirtColor), TShock.Utils.EncodeColor(player.TPlayer.shoeColor), TShock.Utils.EncodeBoolArray(player.TPlayer.hideVisual), TShock.Utils.EncodeColor(player.TPlayer.skinColor), TShock.Utils.EncodeColor(player.TPlayer.eyeColor), player.TPlayer.anglerQuestsFinished, player.TPlayer.skinVariant, player.TPlayer.extraAccessory ? 1 : 0); return true; } catch (Exception ex) @@ -235,17 +235,17 @@ namespace TShockAPI.DB if (player.HasPermission(Permissions.bypassssc)) { - TShock.Log.ConsoleInfo("Skipping SSC Backup for " + player.User.Name); // Debug code + TShock.Log.ConsoleInfo("Skipping SSC Backup for " + player.Account.Name); // Debug code return true; } - if (!GetPlayerData(player, player.User.ID).exists) + if (!GetPlayerData(player, player.Account.ID).exists) { try { database.Query( "INSERT INTO tsCharacter (Account, Health, MaxHealth, Mana, MaxMana, Inventory, extraSlot, spawnX, spawnY, skinVariant, hair, hairDye, hairColor, pantsColor, shirtColor, underShirtColor, shoeColor, hideVisuals, skinColor, eyeColor, questsCompleted) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17, @18, @19, @20);", - player.User.ID, + player.Account.ID, playerData.health, playerData.maxHealth, playerData.mana, @@ -284,7 +284,7 @@ namespace TShockAPI.DB playerData.mana, playerData.maxMana, String.Join("~", playerData.inventory), - player.User.ID, + player.Account.ID, playerData.spawnX, playerData.spawnX, playerData.skinVariant, diff --git a/TShockAPI/DB/RegionManager.cs b/TShockAPI/DB/RegionManager.cs index f94b2a48..608f691d 100644 --- a/TShockAPI/DB/RegionManager.cs +++ b/TShockAPI/DB/RegionManager.cs @@ -447,7 +447,7 @@ namespace TShockAPI.DB Region r = GetRegionByName(regionName); if (r != null) { - if (!r.RemoveID(TShock.Users.GetUserID(userName))) + if (!r.RemoveID(TShock.UserAccounts.GetUserAccountID(userName))) { return false; } @@ -479,7 +479,7 @@ namespace TShockAPI.DB mergedIDs = reader.Get("UserIds"); } - string userIdToAdd = Convert.ToString(TShock.Users.GetUserID(userName)); + string userIdToAdd = Convert.ToString(TShock.UserAccounts.GetUserAccountID(userName)); string[] ids = mergedIDs.Split(','); // Is the user already allowed to the region? if (ids.Contains(userIdToAdd)) @@ -788,7 +788,7 @@ namespace TShockAPI.DB return false; } - return ply.HasPermission(Permissions.editregion) || AllowedIDs.Contains(ply.User.ID) || AllowedGroups.Contains(ply.Group.Name) || Owner == ply.User.Name; + return ply.HasPermission(Permissions.editregion) || AllowedIDs.Contains(ply.Account.ID) || AllowedGroups.Contains(ply.Group.Name) || Owner == ply.Account.Name; } /// diff --git a/TShockAPI/DB/UserManager.cs b/TShockAPI/DB/UserManager.cs index 07662b2b..757fa6f7 100644 --- a/TShockAPI/DB/UserManager.cs +++ b/TShockAPI/DB/UserManager.cs @@ -28,16 +28,16 @@ using System.Security.Cryptography; namespace TShockAPI.DB { - /// UserManager - Methods for dealing with database users and other user functionality within TShock. - public class UserManager + /// UserAccountManager - Methods for dealing with database user accounts and other related functionality within TShock. + public class UserAccountManager { /// database - The database object to use for connections. private IDbConnection _database; - /// Creates a UserManager object. During instantiation, this method will verify the table structure against the format below. + /// Creates a UserAccountManager object. During instantiation, this method will verify the table structure against the format below. /// The database to connect to. - /// A UserManager object. - public UserManager(IDbConnection db) + /// A UserAccountManager object. + public UserAccountManager(IDbConnection db) { _database = db; @@ -59,145 +59,145 @@ namespace TShockAPI.DB } /// - /// Adds a given username to the database + /// Adds the given user account to the database /// - /// User user - public void AddUser(User user) + /// The user account to be added + public void AddUserAccount(UserAccount account) { - if (!TShock.Groups.GroupExists(user.Group)) - throw new GroupNotExistsException(user.Group); + if (!TShock.Groups.GroupExists(account.Group)) + throw new GroupNotExistsException(account.Group); int ret; try { - ret = _database.Query("INSERT INTO Users (Username, Password, UUID, UserGroup, Registered) VALUES (@0, @1, @2, @3, @4);", user.Name, - user.Password, user.UUID, user.Group, DateTime.UtcNow.ToString("s")); + ret = _database.Query("INSERT INTO Users (Username, Password, UUID, UserGroup, Registered) VALUES (@0, @1, @2, @3, @4);", account.Name, + account.Password, account.UUID, account.Group, DateTime.UtcNow.ToString("s")); } catch (Exception ex) { // Detect duplicate user using a regexp as Sqlite doesn't have well structured exceptions if (Regex.IsMatch(ex.Message, "Username.*not unique")) - throw new UserExistsException(user.Name); - throw new UserManagerException("AddUser SQL returned an error (" + ex.Message + ")", ex); + throw new UserAccountExistsException(account.Name); + throw new UserAccountManagerException("AddUser SQL returned an error (" + ex.Message + ")", ex); } if (1 > ret) - throw new UserExistsException(user.Name); + throw new UserAccountExistsException(account.Name); - Hooks.AccountHooks.OnAccountCreate(user); + Hooks.AccountHooks.OnAccountCreate(account); } /// - /// Removes a given username from the database + /// Removes all user accounts from the database whose usernames match the given user account /// - /// User user - public void RemoveUser(User user) + /// The user account + public void RemoveUserAccount(UserAccount account) { try { - var tempuser = GetUser(user); - int affected = _database.Query("DELETE FROM Users WHERE Username=@0", user.Name); + var tempuser = GetUserAccount(account); + int affected = _database.Query("DELETE FROM Users WHERE Username=@0", account.Name); if (affected < 1) - throw new UserNotExistException(user.Name); + throw new UserAccountNotExistException(account.Name); Hooks.AccountHooks.OnAccountDelete(tempuser); } catch (Exception ex) { - throw new UserManagerException("RemoveUser SQL returned an error", ex); + throw new UserAccountManagerException("RemoveUser SQL returned an error", ex); } } /// /// Sets the Hashed Password for a given username /// - /// User user - /// string password - public void SetUserPassword(User user, string password) + /// The user account + /// The user account password to be set + public void SetUserAccountPassword(UserAccount account, string password) { try { - user.CreateBCryptHash(password); + account.CreateBCryptHash(password); if ( - _database.Query("UPDATE Users SET Password = @0 WHERE Username = @1;", user.Password, - user.Name) == 0) - throw new UserNotExistException(user.Name); + _database.Query("UPDATE Users SET Password = @0 WHERE Username = @1;", account.Password, + account.Name) == 0) + throw new UserAccountNotExistException(account.Name); } catch (Exception ex) { - throw new UserManagerException("SetUserPassword SQL returned an error", ex); + throw new UserAccountManagerException("SetUserPassword SQL returned an error", ex); } } /// /// Sets the UUID for a given username /// - /// User user - /// string uuid - public void SetUserUUID(User user, string uuid) + /// The user account + /// The user account uuid to be set + public void SetUserAccountUUID(UserAccount account, string uuid) { try { if ( _database.Query("UPDATE Users SET UUID = @0 WHERE Username = @1;", uuid, - user.Name) == 0) - throw new UserNotExistException(user.Name); + account.Name) == 0) + throw new UserAccountNotExistException(account.Name); } catch (Exception ex) { - throw new UserManagerException("SetUserUUID SQL returned an error", ex); + throw new UserAccountManagerException("SetUserUUID SQL returned an error", ex); } } /// /// Sets the group for a given username /// - /// User user - /// string group - public void SetUserGroup(User user, string group) + /// The user account + /// The user account group to be set + public void SetUserGroup(UserAccount account, string group) { Group grp = TShock.Groups.GetGroupByName(group); if (null == grp) throw new GroupNotExistsException(group); - if (_database.Query("UPDATE Users SET UserGroup = @0 WHERE Username = @1;", group, user.Name) == 0) - throw new UserNotExistException(user.Name); + if (_database.Query("UPDATE Users SET UserGroup = @0 WHERE Username = @1;", group, account.Name) == 0) + throw new UserAccountNotExistException(account.Name); try { // Update player group reference for any logged in player - foreach (var player in TShock.Players.Where(p => p != null && p.User != null && p.User.Name == user.Name)) + foreach (var player in TShock.Players.Where(p => p != null && p.Account != null && p.Account.Name == account.Name)) { player.Group = grp; } } catch (Exception ex) { - throw new UserManagerException("SetUserGroup SQL returned an error", ex); + throw new UserAccountManagerException("SetUserGroup SQL returned an error", ex); } } - /// Updates the last accessed time for a database user to the current time. - /// The user object to modify. - public void UpdateLogin(User user) + /// Updates the last accessed time for a database user account to the current time. + /// The user account object to modify. + public void UpdateLogin(UserAccount account) { try { - if (_database.Query("UPDATE Users SET LastAccessed = @0, KnownIps = @1 WHERE Username = @2;", DateTime.UtcNow.ToString("s"), user.KnownIps, user.Name) == 0) - throw new UserNotExistException(user.Name); + if (_database.Query("UPDATE Users SET LastAccessed = @0, KnownIps = @1 WHERE Username = @2;", DateTime.UtcNow.ToString("s"), account.KnownIps, account.Name) == 0) + throw new UserAccountNotExistException(account.Name); } catch (Exception ex) { - throw new UserManagerException("UpdateLogin SQL returned an error", ex); + throw new UserAccountManagerException("UpdateLogin SQL returned an error", ex); } } - /// Gets the database ID of a given user object from the database. - /// The username of the user to query for. - /// The user's ID - public int GetUserID(string username) + /// Gets the database ID of a given user account object from the database. + /// The username of the user account to query for. + /// The user account ID + public int GetUserAccountID(string username) { try { @@ -216,55 +216,55 @@ namespace TShockAPI.DB return -1; } - /// Gets a user object by name. + /// Gets a user account object by name. /// The user's name. - /// The user object returned from the search. - public User GetUserByName(string name) + /// The user account object returned from the search. + public UserAccount GetUserAccountByName(string name) { try { - return GetUser(new User {Name = name}); + return GetUserAccount(new UserAccount {Name = name}); } - catch (UserManagerException) + catch (UserAccountManagerException) { return null; } } - /// Gets a user object by their user ID. + /// Gets a user account object by their user account ID. /// The user's ID. - /// The user object returned from the search. - public User GetUserByID(int id) + /// The user account object returned from the search. + public UserAccount GetUserAccountByID(int id) { try { - return GetUser(new User {ID = id}); + return GetUserAccount(new UserAccount {ID = id}); } - catch (UserManagerException) + catch (UserAccountManagerException) { return null; } } - /// Gets a user object by a user object. - /// The user object to search by. + /// Gets a user account object by a user account object. + /// The user account object to search by. /// The user object that is returned from the search. - public User GetUser(User user) + public UserAccount GetUserAccount(UserAccount account) { bool multiple = false; string query; string type; object arg; - if (0 != user.ID) + if (account.ID != 0) { query = "SELECT * FROM Users WHERE ID=@0"; - arg = user.ID; + arg = account.ID; type = "id"; } else { query = "SELECT * FROM Users WHERE Username=@0"; - arg = user.Name; + arg = account.Name; type = "name"; } @@ -274,38 +274,38 @@ namespace TShockAPI.DB { if (result.Read()) { - user = LoadUserFromResult(user, result); + account = LoadUserAccountFromResult(account, result); // Check for multiple matches if (!result.Read()) - return user; + return account; multiple = true; } } } catch (Exception ex) { - throw new UserManagerException("GetUser SQL returned an error (" + ex.Message + ")", ex); + throw new UserAccountManagerException("GetUser SQL returned an error (" + ex.Message + ")", ex); } if (multiple) - throw new UserManagerException(String.Format("Multiple users found for {0} '{1}'", type, arg)); + throw new UserAccountManagerException(String.Format("Multiple user accounts found for {0} '{1}'", type, arg)); - throw new UserNotExistException(user.Name); + throw new UserAccountNotExistException(account.Name); } - /// Gets all users from the database. - /// The users from the database. - public List GetUsers() + /// Gets all the user accounts from the database. + /// The user accounts from the database. + public List GetUserAccounts() { try { - List users = new List(); + List accounts = new List(); using (var reader = _database.QueryReader("SELECT * FROM Users")) { while (reader.Read()) { - users.Add(LoadUserFromResult(new User(), reader)); + accounts.Add(LoadUserAccountFromResult(new UserAccount(), reader)); } - return users; + return accounts; } } catch (Exception ex) @@ -316,26 +316,26 @@ namespace TShockAPI.DB } /// - /// Gets all users from the database with a username that starts with or contains + /// Gets all user accounts from the database with a username that starts with or contains /// /// Rough username search. "n" will match "n", "na", "nam", "name", etc /// If is not the first part of the username. If true then "name" would match "name", "username", "wordsnamewords", etc /// Matching users or null if exception is thrown - public List GetUsersByName(string username, bool notAtStart = false) + public List GetUserAccountsByName(string username, bool notAtStart = false) { try { - List users = new List(); + List accounts = new List(); string search = notAtStart ? string.Format("%{0}%", username) : string.Format("{0}%", username); using (var reader = _database.QueryReader("SELECT * FROM Users WHERE Username LIKE @0", search)) { while (reader.Read()) { - users.Add(LoadUserFromResult(new User(), reader)); + accounts.Add(LoadUserAccountFromResult(new UserAccount(), reader)); } } - return users; + return accounts; } catch (Exception ex) { @@ -344,61 +344,61 @@ namespace TShockAPI.DB return null; } - /// Fills out the fields of a User object with the results from a QueryResult object. - /// The user to add data to. + /// Fills out the fields of a User account object with the results from a QueryResult object. + /// The user account to add data to. /// The QueryResult object to add data from. /// The 'filled out' user object. - private User LoadUserFromResult(User user, QueryResult result) + private UserAccount LoadUserAccountFromResult(UserAccount account, QueryResult result) { - user.ID = result.Get("ID"); - user.Group = result.Get("Usergroup"); - user.Password = result.Get("Password"); - user.UUID = result.Get("UUID"); - user.Name = result.Get("Username"); - user.Registered = result.Get("Registered"); - user.LastAccessed = result.Get("LastAccessed"); - user.KnownIps = result.Get("KnownIps"); - return user; + account.ID = result.Get("ID"); + account.Group = result.Get("Usergroup"); + account.Password = result.Get("Password"); + account.UUID = result.Get("UUID"); + account.Name = result.Get("Username"); + account.Registered = result.Get("Registered"); + account.LastAccessed = result.Get("LastAccessed"); + account.KnownIps = result.Get("KnownIps"); + return account; } } - /// A database user. - public class User : IEquatable + /// A database user account. + public class UserAccount : IEquatable { - /// The database ID of the user. + /// The database ID of the user account. public int ID { get; set; } /// The user's name. public string Name { get; set; } - /// The hashed password for the user. + /// The hashed password for the user account. public string Password { get; internal set; } /// The user's saved Univerally Unique Identifier token. public string UUID { get; set; } - - /// The group object that the user is a part of. + + /// The group object that the user account is a part of. public string Group { get; set; } - /// The unix epoch corresponding to the registration date of the user. + /// The unix epoch corresponding to the registration date of the user account. public string Registered { get; set; } - /// The unix epoch corresponding to the last access date of the user. + /// The unix epoch corresponding to the last access date of the user account. public string LastAccessed { get; set; } - /// A JSON serialized list of known IP addresses for a user. + /// A JSON serialized list of known IP addresses for a user account. public string KnownIps { get; set; } - /// Constructor for the user object, assuming you define everything yourself. + /// Constructor for the user account object, assuming you define everything yourself. /// The user's name. /// The user's password hash. /// The user's UUID. /// The user's group name. /// The unix epoch for the registration date. /// The unix epoch for the last access date. - /// The known IPs for the user, serialized as a JSON object - /// A completed user object. - public User(string name, string pass, string uuid, string group, string registered, string last, string known) + /// The known IPs for the user account, serialized as a JSON object + /// A completed user account object. + public UserAccount(string name, string pass, string uuid, string group, string registered, string last, string known) { Name = name; Password = pass; @@ -409,9 +409,9 @@ namespace TShockAPI.DB KnownIps = known; } - /// Default constructor for a user object; holds no data. - /// A user object. - public User() + /// Default constructor for a user account object; holds no data. + /// A user account object. + public UserAccount() { Name = ""; Password = ""; @@ -428,7 +428,7 @@ namespace TShockAPI.DB /// If the password is stored using BCrypt, it will be re-saved if the work factor in the config /// is greater than the existing work factor with the new work factor. /// - /// The password to check against the user object. + /// The password to check against the user account object. /// bool true, if the password matched, or false, if it didn't. public bool VerifyPassword(string password) { @@ -459,7 +459,7 @@ namespace TShockAPI.DB } /// Upgrades a password to BCrypt, from an insecure hashing algorithm. - /// The raw user password (unhashed) to upgrade + /// The raw user account password (unhashed) to upgrade protected void UpgradePasswordToBCrypt(string password) { // Save the old password, in the event that we have to revert changes. @@ -467,9 +467,9 @@ namespace TShockAPI.DB try { - TShock.Users.SetUserPassword(this, password); + TShock.UserAccounts.SetUserAccountPassword(this, password); } - catch (UserManagerException e) + catch (UserAccountManagerException e) { TShock.Log.ConsoleError(e.ToString()); Password = oldpassword; // Revert changes @@ -477,7 +477,7 @@ namespace TShockAPI.DB } /// Upgrades a password to the highest work factor available in the config. - /// The raw user password (unhashed) to upgrade + /// The raw user account password (unhashed) to upgrade protected void UpgradePasswordWorkFactor(string password) { // If the destination work factor is not greater, we won't upgrade it or re-hash it @@ -496,16 +496,16 @@ namespace TShockAPI.DB { try { - TShock.Users.SetUserPassword(this, password); + TShock.UserAccounts.SetUserAccountPassword(this, password); } - catch (UserManagerException e) + catch (UserAccountManagerException e) { TShock.Log.ConsoleError(e.ToString()); } } } - /// Creates a BCrypt hash for a user and stores it in this object. + /// Creates a BCrypt hash for a user account and stores it in this object. /// The plain text password to hash public void CreateBCryptHash(string password) { @@ -524,7 +524,7 @@ namespace TShockAPI.DB } } - /// Creates a BCrypt hash for a user and stores it in this object. + /// Creates a BCrypt hash for a user account and stores it in this object. /// The plain text password to hash /// The work factor to use in generating the password hash public void CreateBCryptHash(string password, int workFactor) @@ -583,29 +583,29 @@ namespace TShockAPI.DB #region IEquatable - /// Indicates whether the current is equal to another . - /// true if the is equal to the parameter; otherwise, false. - /// An to compare with this . - public bool Equals(User other) + /// Indicates whether the current is equal to another . + /// true if the is equal to the parameter; otherwise, false. + /// An to compare with this . + public bool Equals(UserAccount other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return ID == other.ID && string.Equals(Name, other.Name); } - /// Indicates whether the current is equal to another object. - /// true if the is equal to the parameter; otherwise, false. - /// An to compare with this . + /// Indicates whether the current is equal to another object. + /// true if the is equal to the parameter; otherwise, false. + /// An to compare with this . public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; - return Equals((User)obj); + return Equals((UserAccount)obj); } /// Serves as the hash function. - /// A hash code for the current . + /// A hash code for the current . public override int GetHashCode() { unchecked @@ -615,86 +615,87 @@ namespace TShockAPI.DB } /// - /// Compares equality of two objects. + /// Compares equality of two objects. /// /// Left hand of the comparison. /// Right hand of the comparison. - /// true if the objects are equal; otherwise, false. - public static bool operator ==(User left, User right) + /// true if the objects are equal; otherwise, false. + public static bool operator ==(UserAccount left, UserAccount right) { return Equals(left, right); } /// - /// Compares equality of two objects. + /// Compares equality of two objects. /// /// Left hand of the comparison. /// Right hand of the comparison. - /// true if the objects aren't equal; otherwise, false. - public static bool operator !=(User left, User right) + /// true if the objects aren't equal; otherwise, false. + public static bool operator !=(UserAccount left, UserAccount right) { return !Equals(left, right); } #endregion - public override string ToString() - { - return Name; - } + /// + /// Converts the UserAccount to it's string representation + /// + /// Returns the UserAccount string representation + public override string ToString() => Name; } - /// UserManagerException - An exception generated by the user manager. + /// UserAccountManagerException - An exception generated by the user account manager. [Serializable] - public class UserManagerException : Exception + public class UserAccountManagerException : Exception { - /// Creates a new UserManagerException object. + /// Creates a new UserAccountManagerException object. /// The message for the object. - /// A new UserManagerException object. - public UserManagerException(string message) + /// A new UserAccountManagerException object. + public UserAccountManagerException(string message) : base(message) { } - /// Creates a new UserManagerObject with an internal exception. + /// Creates a new UserAccountManager Object with an internal exception. /// The message for the object. /// The inner exception for the object. - /// A new UserManagerException with a defined inner exception. - public UserManagerException(string message, Exception inner) + /// A new UserAccountManagerException with a defined inner exception. + public UserAccountManagerException(string message, Exception inner) : base(message, inner) { } } - /// A UserExistsException object, used when a user already exists when attempting to create a new one. + /// A UserExistsException object, used when a user account already exists when attempting to create a new one. [Serializable] - public class UserExistsException : UserManagerException + public class UserAccountExistsException : UserAccountManagerException { - /// Creates a new UserExistsException object. - /// The name of the user that already exists. - /// A UserExistsException object with the user's name passed in the message. - public UserExistsException(string name) - : base("User '" + name + "' already exists") + /// Creates a new UserAccountExistsException object. + /// The name of the user account that already exists. + /// A UserAccountExistsException object with the user's name passed in the message. + public UserAccountExistsException(string name) + : base("User account '" + name + "' already exists") { } } /// A UserNotExistException, used when a user does not exist and a query failed as a result of it. [Serializable] - public class UserNotExistException : UserManagerException + public class UserAccountNotExistException : UserAccountManagerException { - /// Creates a new UserNotExistException object, with the user's name in the message. - /// The user's name to be pasesd in the message. - /// A new UserNotExistException object with a message containing the user's name that does not exist. - public UserNotExistException(string name) - : base("User '" + name + "' does not exist") + /// Creates a new UserAccountNotExistException object, with the user account name in the message. + /// The user account name to be pasesd in the message. + /// A new UserAccountNotExistException object with a message containing the user account name that does not exist. + public UserAccountNotExistException(string name) + : base("User account '" + name + "' does not exist") { } } /// A GroupNotExistsException, used when a group does not exist. [Serializable] - public class GroupNotExistsException : UserManagerException + public class GroupNotExistsException : UserAccountManagerException { /// Creates a new GroupNotExistsException object with the group's name in the message. /// The group name. diff --git a/TShockAPI/GetDataHandlers.cs b/TShockAPI/GetDataHandlers.cs index 2fa9cbd0..f3dc33e5 100644 --- a/TShockAPI/GetDataHandlers.cs +++ b/TShockAPI/GetDataHandlers.cs @@ -1518,25 +1518,25 @@ namespace TShockAPI private static bool HandleConnecting(GetDataHandlerArgs args) { - var user = TShock.Users.GetUserByName(args.Player.Name); + var account = TShock.UserAccounts.GetUserAccountByName(args.Player.Name); args.Player.DataWhenJoined = new PlayerData(args.Player); args.Player.DataWhenJoined.CopyCharacter(args.Player); - if (user != null && !TShock.Config.DisableUUIDLogin) + if (account != null && !TShock.Config.DisableUUIDLogin) { - if (user.UUID == args.Player.UUID) + if (account.UUID == args.Player.UUID) { if (args.Player.State == 1) args.Player.State = 2; NetMessage.SendData((int)PacketTypes.WorldInfo, args.Player.Index); - args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, user.ID); + args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, account.ID); - var group = TShock.Utils.GetGroup(user.Group); + var group = TShock.Utils.GetGroup(account.Group); args.Player.Group = group; args.Player.tempGroup = null; - args.Player.User = user; + args.Player.Account = account; args.Player.IsLoggedIn = true; args.Player.IgnoreActionsForInventory = "none"; @@ -1557,13 +1557,13 @@ namespace TShockAPI if (args.Player.HasPermission(Permissions.usebanneditem)) args.Player.IgnoreActionsForDisabledArmor = "none"; - args.Player.SendSuccessMessage("Authenticated as " + user.Name + " successfully."); + args.Player.SendSuccessMessage("Authenticated as " + account.Name + " successfully."); TShock.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user " + args.Player.Name + "."); Hooks.PlayerHooks.OnPlayerPostLogin(args.Player); return true; } } - else if (user != null && !TShock.Config.DisableLoginBeforeJoin) + else if (account != null && !TShock.Config.DisableLoginBeforeJoin) { args.Player.RequiresPassword = true; NetMessage.SendData((int)PacketTypes.PasswordRequired, args.Player.Index); @@ -1592,23 +1592,23 @@ namespace TShockAPI if (Hooks.PlayerHooks.OnPlayerPreLogin(args.Player, args.Player.Name, password)) return true; - var user = TShock.Users.GetUserByName(args.Player.Name); - if (user != null && !TShock.Config.DisableLoginBeforeJoin) + var account = TShock.UserAccounts.GetUserAccountByName(args.Player.Name); + if (account != null && !TShock.Config.DisableLoginBeforeJoin) { - if (user.VerifyPassword(password)) + if (account.VerifyPassword(password)) { args.Player.RequiresPassword = false; - args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, user.ID); + args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, account.ID); if (args.Player.State == 1) args.Player.State = 2; NetMessage.SendData((int)PacketTypes.WorldInfo, args.Player.Index); - var group = TShock.Utils.GetGroup(user.Group); + var group = TShock.Utils.GetGroup(account.Group); args.Player.Group = group; args.Player.tempGroup = null; - args.Player.User = user; + args.Player.Account = account; args.Player.IsLoggedIn = true; args.Player.IgnoreActionsForInventory = "none"; @@ -1632,7 +1632,7 @@ namespace TShockAPI args.Player.SendMessage("Authenticated as " + args.Player.Name + " successfully.", Color.LimeGreen); TShock.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user " + args.Player.Name + "."); - TShock.Users.SetUserUUID(user, args.Player.UUID); + TShock.UserAccounts.SetUserAccountUUID(account, args.Player.UUID); Hooks.PlayerHooks.OnPlayerPostLogin(args.Player); return true; } @@ -2963,9 +2963,9 @@ namespace TShockAPI if (args.TPlayer.difficulty == 2 && Main.ServerSideCharacter && args.Player.IsLoggedIn) { - if (TShock.CharacterDB.RemovePlayer(args.Player.User.ID)) + if (TShock.CharacterDB.RemovePlayer(args.Player.Account.ID)) { - TShock.CharacterDB.SeedInitialData(args.Player.User); + TShock.CharacterDB.SeedInitialData(args.Player.Account); } } @@ -3029,9 +3029,9 @@ namespace TShockAPI if (args.TPlayer.difficulty == 2 && Main.ServerSideCharacter && args.Player.IsLoggedIn) { - if (TShock.CharacterDB.RemovePlayer(args.Player.User.ID)) + if (TShock.CharacterDB.RemovePlayer(args.Player.Account.ID)) { - TShock.CharacterDB.SeedInitialData(args.Player.User); + TShock.CharacterDB.SeedInitialData(args.Player.Account); } } diff --git a/TShockAPI/Hooks/AccountHooks.cs b/TShockAPI/Hooks/AccountHooks.cs index 1a7e1cc8..356a90c1 100644 --- a/TShockAPI/Hooks/AccountHooks.cs +++ b/TShockAPI/Hooks/AccountHooks.cs @@ -21,21 +21,21 @@ namespace TShockAPI.Hooks { public class AccountDeleteEventArgs { - public User User { get; private set; } + public UserAccount Account { get; private set; } - public AccountDeleteEventArgs(User user) + public AccountDeleteEventArgs(UserAccount account) { - this.User = user; + this.Account = account; } } public class AccountCreateEventArgs { - public User User { get; private set; } + public UserAccount Account { get; private set; } - public AccountCreateEventArgs(User user) + public AccountCreateEventArgs(UserAccount account) { - this.User = user; + this.Account = account; } } @@ -44,7 +44,7 @@ namespace TShockAPI.Hooks public delegate void AccountCreateD(AccountCreateEventArgs e); public static event AccountCreateD AccountCreate; - public static void OnAccountCreate(User u) + public static void OnAccountCreate(UserAccount u) { if (AccountCreate == null) return; @@ -55,7 +55,7 @@ namespace TShockAPI.Hooks public delegate void AccountDeleteD(AccountDeleteEventArgs e); public static event AccountDeleteD AccountDelete; - public static void OnAccountDelete(User u) + public static void OnAccountDelete(UserAccount u) { if (AccountDelete == null) return; diff --git a/TShockAPI/Rest/RestManager.cs b/TShockAPI/Rest/RestManager.cs index 9c2c818a..01341d46 100644 --- a/TShockAPI/Rest/RestManager.cs +++ b/TShockAPI/Rest/RestManager.cs @@ -482,7 +482,7 @@ namespace TShockAPI [Token] private object UserActiveListV2(RestRequestArgs args) { - return new RestObject() { { "activeusers", string.Join("\t", TShock.Players.Where(p => null != p && null != p.User && p.Active).Select(p => p.User.Name)) } }; + return new RestObject() { { "activeusers", string.Join("\t", TShock.Players.Where(p => null != p && null != p.Account && p.Active).Select(p => p.Account.Name)) } }; } [Description("Lists all user accounts in the TShock database.")] @@ -491,7 +491,7 @@ namespace TShockAPI [Token] private object UserListV2(RestRequestArgs args) { - return new RestObject() { { "users", TShock.Users.GetUsers().Select(p => new Dictionary(){ + return new RestObject() { { "users", TShock.UserAccounts.GetUserAccounts().Select(p => new Dictionary(){ {"name", p.Name}, {"id", p.ID}, {"group", p.Group}, @@ -520,11 +520,11 @@ namespace TShockAPI return RestMissingParam("password"); // NOTE: ip can be blank - User user = new User(username, "", "", group, "", "", ""); + UserAccount account = new UserAccount(username, "", "", group, "", "", ""); try { - user.CreateBCryptHash(password); - TShock.Users.AddUser(user); + account.CreateBCryptHash(password); + TShock.UserAccounts.AddUserAccount(account); } catch (Exception e) { @@ -553,13 +553,13 @@ namespace TShockAPI if (string.IsNullOrWhiteSpace(group) && string.IsNullOrWhiteSpace(password)) return RestMissingParam("group", "password"); - User user = (User)ret; + UserAccount account = (UserAccount)ret; var response = new RestObject(); if (!string.IsNullOrWhiteSpace(password)) { try { - TShock.Users.SetUserPassword(user, password); + TShock.UserAccounts.SetUserAccountPassword(account, password); response.Add("password-response", "Password updated successfully"); } catch (Exception e) @@ -572,7 +572,7 @@ namespace TShockAPI { try { - TShock.Users.SetUserGroup(user, group); + TShock.UserAccounts.SetUserGroup(account, group); response.Add("group-response", "Group updated successfully"); } catch (Exception e) @@ -598,7 +598,7 @@ namespace TShockAPI try { - TShock.Users.RemoveUser((User)ret); + TShock.UserAccounts.RemoveUserAccount((UserAccount)ret); } catch (Exception e) { @@ -620,8 +620,8 @@ namespace TShockAPI if (ret is RestObject) return ret; - User user = (User)ret; - return new RestObject() { { "group", user.Group }, { "id", user.ID.ToString() }, { "name", user.Name } }; + UserAccount account = (UserAccount)ret; + return new RestObject() { { "group", account.Group }, { "id", account.ID.ToString() }, { "name", account.Name } }; } #endregion @@ -938,10 +938,10 @@ namespace TShockAPI return new RestObject() { {"nickname", player.Name}, - {"username", player.User?.Name}, + {"username", player.Account?.Name}, {"ip", player.IP}, {"group", player.Group.Name}, - {"registered", player.User?.Registered}, + {"registered", player.Account?.Registered}, {"muted", player.mute }, {"position", player.TileX + "," + player.TileY}, {"inventory", string.Join(", ", inventory.Select(p => (p.Name + ":" + p.stack)))}, @@ -979,10 +979,10 @@ namespace TShockAPI return new RestObject { {"nickname", player.Name}, - {"username", player.User?.Name}, + {"username", player.Account?.Name}, {"ip", player.IP}, {"group", player.Group.Name}, - {"registered", player.User?.Registered}, + {"registered", player.Account?.Registered}, {"muted", player.mute }, {"position", player.TileX + "," + player.TileY}, {"items", items}, @@ -1283,7 +1283,7 @@ namespace TShockAPI if (string.IsNullOrWhiteSpace(name)) return RestMissingParam("user"); - User user; + UserAccount account; string type = parameters["type"]; try { @@ -1292,10 +1292,10 @@ namespace TShockAPI case null: case "name": type = "name"; - user = TShock.Users.GetUserByName(name); + account = TShock.UserAccounts.GetUserAccountByName(name); break; case "id": - user = TShock.Users.GetUserByID(Convert.ToInt32(name)); + account = TShock.UserAccounts.GetUserAccountByID(Convert.ToInt32(name)); break; default: return RestError("Invalid Type: '" + type + "'"); @@ -1306,10 +1306,10 @@ namespace TShockAPI return RestError(e.Message); } - if (null == user) + if (null == account) return RestError(String.Format("User {0} '{1}' doesn't exist", type, name)); - return user; + return account; } private object BanFind(IParameterCollection parameters) @@ -1359,7 +1359,7 @@ namespace TShockAPI var player = new Dictionary { {"nickname", tsPlayer.Name}, - {"username", tsPlayer.User == null ? "" : tsPlayer.User.Name}, + {"username", tsPlayer.Account == null ? "" : tsPlayer.Account.Name}, {"group", tsPlayer.Group.Name}, {"active", tsPlayer.Active}, {"state", tsPlayer.State}, diff --git a/TShockAPI/Rest/SecureRest.cs b/TShockAPI/Rest/SecureRest.cs index ee76fd67..4000efab 100644 --- a/TShockAPI/Rest/SecureRest.cs +++ b/TShockAPI/Rest/SecureRest.cs @@ -131,7 +131,7 @@ namespace Rests tokenBucket.Add(context.RemoteEndPoint.Address.ToString(), 1); // First time request, set to one and process request } - User userAccount = TShock.Users.GetUserByName(username); + UserAccount userAccount = TShock.UserAccounts.GetUserAccountByName(username); if (userAccount == null) { AddTokenToBucket(context.RemoteEndPoint.Address.ToString()); @@ -216,4 +216,4 @@ namespace Rests return result; } } -} \ No newline at end of file +} diff --git a/TShockAPI/TSPlayer.cs b/TShockAPI/TSPlayer.cs index e2eedd1a..c43669f7 100644 --- a/TShockAPI/TSPlayer.cs +++ b/TShockAPI/TSPlayer.cs @@ -218,10 +218,10 @@ namespace TShockAPI public Vector2 LastNetPosition = Vector2.Zero; /// - /// User object associated with the player. + /// UserAccount object associated with the player. /// Set when the player logs in. /// - public User User { get; set; } + public UserAccount Account { get; set; } /// /// Whether the player performed a valid login attempt (i.e. entered valid user name and password) but is still blocked @@ -448,7 +448,7 @@ namespace TShockAPI { if (HasPermission(Permissions.bypassssc)) { - TShock.Log.ConsoleInfo("Skipping SSC Backup for " + User.Name); // Debug Code + TShock.Log.ConsoleInfo("Skipping SSC Backup for " + Account.Name); // Debug Code return true; } PlayerData.CopyCharacter(this); @@ -656,7 +656,7 @@ namespace TShockAPI { tempGroupTimer.Stop(); } - User = null; + Account = null; IsLoggedIn = false; } diff --git a/TShockAPI/TSServerPlayer.cs b/TShockAPI/TSServerPlayer.cs index b811e9a8..b9906c6a 100644 --- a/TShockAPI/TSServerPlayer.cs +++ b/TShockAPI/TSServerPlayer.cs @@ -36,7 +36,7 @@ namespace TShockAPI : base("Server") { Group = new SuperAdminGroup(); - User = new User { Name = AccountName }; + Account = new UserAccount { Name = AccountName }; } public override void SendErrorMessage(string msg) diff --git a/TShockAPI/TShock.cs b/TShockAPI/TShock.cs index e4fdf0ff..ee403eab 100644 --- a/TShockAPI/TShock.cs +++ b/TShockAPI/TShock.cs @@ -94,7 +94,7 @@ namespace TShockAPI /// Groups - Static reference to the group manager for accessing the group system. public static GroupManager Groups; /// Users - Static reference to the user manager for accessing the user database system. - public static UserManager Users; + public static UserAccountManager UserAccounts; /// Itembans - Static reference to the item ban system. public static ItemManager Itembans; /// ProjectileBans - Static reference to the projectile ban system. @@ -312,7 +312,7 @@ namespace TShockAPI Bans = new BanManager(DB); Warps = new WarpManager(DB); Regions = new RegionManager(DB); - Users = new UserManager(DB); + UserAccounts = new UserAccountManager(DB); Groups = new GroupManager(DB); Itembans = new ItemManager(DB); ProjectileBans = new ProjectileManagager(DB); @@ -391,7 +391,7 @@ namespace TShockAPI { foreach (TSPlayer player in TShock.Players) { - player.User = null; + player.Account = null; } } @@ -447,9 +447,9 @@ namespace TShockAPI private void OnPlayerLogin(PlayerPostLoginEventArgs args) { List KnownIps = new List(); - if (!string.IsNullOrWhiteSpace(args.Player.User.KnownIps)) + if (!string.IsNullOrWhiteSpace(args.Player.Account.KnownIps)) { - KnownIps = JsonConvert.DeserializeObject>(args.Player.User.KnownIps); + KnownIps = JsonConvert.DeserializeObject>(args.Player.Account.KnownIps); } if (KnownIps.Count == 0) @@ -470,16 +470,16 @@ namespace TShockAPI } } - args.Player.User.KnownIps = JsonConvert.SerializeObject(KnownIps, Formatting.Indented); - Users.UpdateLogin(args.Player.User); + args.Player.Account.KnownIps = JsonConvert.SerializeObject(KnownIps, Formatting.Indented); + UserAccounts.UpdateLogin(args.Player.Account); - Ban potentialBan = Bans.GetBanByAccountName(args.Player.User.Name); + Ban potentialBan = Bans.GetBanByAccountName(args.Player.Account.Name); if (potentialBan != null) { // A user just signed in successfully despite being banned by account name. // We should fix the ban database so that all of their ban info is up to date. - Bans.AddBan2(args.Player.IP, args.Player.Name, args.Player.UUID, args.Player.User.Name, + Bans.AddBan2(args.Player.IP, args.Player.Name, args.Player.UUID, args.Player.Account.Name, potentialBan.Reason, false, potentialBan.BanningUser, potentialBan.Expiration); // And then get rid of them. @@ -500,14 +500,14 @@ namespace TShockAPI /// args - The AccountDeleteEventArgs object. private void OnAccountDelete(Hooks.AccountDeleteEventArgs args) { - CharacterDB.RemovePlayer(args.User.ID); + CharacterDB.RemovePlayer(args.Account.ID); } /// OnAccountCreate - Internal hook fired on account creation. /// args - The AccountCreateEventArgs object. private void OnAccountCreate(Hooks.AccountCreateEventArgs args) { - CharacterDB.SeedInitialData(Users.GetUser(args.User)); + CharacterDB.SeedInitialData(UserAccounts.GetUserAccount(args.Account)); } /// OnPlayerPreLogin - Internal hook fired when on player pre login. @@ -535,7 +535,7 @@ namespace TShockAPI } if (player.IsLoggedIn) { - var ips = JsonConvert.DeserializeObject>(player.User.KnownIps); + var ips = JsonConvert.DeserializeObject>(player.Account.KnownIps); if (ips.Contains(ip)) { Netplay.Clients[player.Index].PendingTermination = true; @@ -857,7 +857,7 @@ namespace TShockAPI } // Disable the auth system if "auth.lck" is present or a superadmin exists - if (File.Exists(Path.Combine(SavePath, "auth.lck")) || Users.GetUsers().Exists(u => u.Group == new SuperAdminGroup().Name)) + if (File.Exists(Path.Combine(SavePath, "auth.lck")) || UserAccounts.GetUserAccounts().Exists(u => u.Group == new SuperAdminGroup().Name)) { AuthToken = 0; diff --git a/TShockAPI/Utils.cs b/TShockAPI/Utils.cs index 9626d556..050515a6 100644 --- a/TShockAPI/Utils.cs +++ b/TShockAPI/Utils.cs @@ -90,7 +90,7 @@ namespace TShockAPI { if (includeIDs) { - players.Add(String.Format("{0} (IX: {1}{2})", ply.Name, ply.Index, ply.User != null ? ", ID: " + ply.User.ID : "")); + players.Add(String.Format("{0} (IX: {1}{2})", ply.Name, ply.Index, ply.Account != null ? ", ID: " + ply.Account.ID : "")); } else {