Renamed TShockAPI.DB 'User' to 'UserAccount'

This commit is contained in:
Edgar Luque 2017-12-08 01:38:15 +01:00
parent 27ac4c6318
commit 6589531868
12 changed files with 335 additions and 328 deletions

View file

@ -193,11 +193,17 @@ namespace TShockAPI
public static List<Command> ChatCommands = new List<Command>(); public static List<Command> ChatCommands = new List<Command>();
public static ReadOnlyCollection<Command> TShockCommands = new ReadOnlyCollection<Command>(new List<Command>()); public static ReadOnlyCollection<Command> TShockCommands = new ReadOnlyCollection<Command>(new List<Command>());
/// <summary>
/// The command specifier, defaults to "/"
/// </summary>
public static string Specifier public static string Specifier
{ {
get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSpecifier) ? "/" : TShock.Config.CommandSpecifier; } get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSpecifier) ? "/" : TShock.Config.CommandSpecifier; }
} }
/// <summary>
/// The silent command specifier, defaults to "."
/// </summary>
public static string SilentSpecifier public static string SilentSpecifier
{ {
get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSilentSpecifier) ? "." : TShock.Config.CommandSilentSpecifier; } get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSilentSpecifier) ? "." : TShock.Config.CommandSilentSpecifier; }
@ -787,7 +793,7 @@ namespace TShockAPI
return; return;
} }
User user = TShock.Users.GetUserByName(args.Player.Name); UserAccount account = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
string password = ""; string password = "";
bool usingUUID = false; bool usingUUID = false;
if (args.Parameters.Count == 0 && !TShock.Config.DisableUUIDLogin) 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])) if (PlayerHooks.OnPlayerPreLogin(args.Player, args.Parameters[0], args.Parameters[1]))
return; return;
user = TShock.Users.GetUserByName(args.Parameters[0]); account = TShock.UserAccounts.GetUserAccountByName(args.Parameters[0]);
password = args.Parameters[1]; password = args.Parameters[1];
} }
else else
@ -826,21 +832,21 @@ namespace TShockAPI
} }
try 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) || else if (account.VerifyPassword(password) ||
(usingUUID && user.UUID == args.Player.UUID && !TShock.Config.DisableUUIDLogin && (usingUUID && account.UUID == args.Player.UUID && !TShock.Config.DisableUUIDLogin &&
!String.IsNullOrWhiteSpace(args.Player.UUID))) !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.Group = group;
args.Player.tempGroup = null; args.Player.tempGroup = null;
args.Player.User = user; args.Player.Account = account;
args.Player.IsLoggedIn = true; args.Player.IsLoggedIn = true;
args.Player.IgnoreActionsForInventory = "none"; args.Player.IgnoreActionsForInventory = "none";
@ -861,9 +867,9 @@ namespace TShockAPI
if (args.Player.HasPermission(Permissions.usebanneditem)) if (args.Player.HasPermission(Permissions.usebanneditem))
args.Player.IgnoreActionsForDisabledArmor = "none"; 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 ((args.Player.LoginHarassed) && (TShock.Config.RememberLeavePos))
{ {
if (TShock.RememberedPos.GetLeavePos(args.Player.Name, args.Player.IP) != Vector2.Zero) if (TShock.RememberedPos.GetLeavePos(args.Player.Name, args.Player.IP) != Vector2.Zero)
@ -874,7 +880,7 @@ namespace TShockAPI
args.Player.LoginHarassed = false; args.Player.LoginHarassed = false;
} }
TShock.Users.SetUserUUID(user, args.Player.UUID); TShock.UserAccounts.SetUserAccountUUID(account, args.Player.UUID);
Hooks.PlayerHooks.OnPlayerPostLogin(args.Player); Hooks.PlayerHooks.OnPlayerPostLogin(args.Player);
} }
@ -888,7 +894,7 @@ namespace TShockAPI
{ {
args.Player.SendErrorMessage("Invalid password!"); 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++; args.Player.LoginAttempts++;
} }
} }
@ -922,14 +928,14 @@ namespace TShockAPI
if (args.Player.IsLoggedIn && args.Parameters.Count == 2) if (args.Player.IsLoggedIn && args.Parameters.Count == 2)
{ {
string password = args.Parameters[0]; string password = args.Parameters[0];
if (args.Player.User.VerifyPassword(password)) if (args.Player.Account.VerifyPassword(password))
{ {
try try
{ {
args.Player.SendSuccessMessage("You changed your password!"); 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 " + 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) catch (ArgumentOutOfRangeException)
{ {
@ -940,7 +946,7 @@ namespace TShockAPI
{ {
args.Player.SendErrorMessage("You failed to change your password!"); 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: " + 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 else
@ -948,7 +954,7 @@ namespace TShockAPI
args.Player.SendErrorMessage("Not logged in or invalid syntax! Proper syntax: {0}password <oldpassword> <newpassword>", Specifier); args.Player.SendErrorMessage("Not logged in or invalid syntax! Proper syntax: {0}password <oldpassword> <newpassword>", Specifier);
} }
} }
catch (UserManagerException ex) catch (UserAccountManagerException ex)
{ {
args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + "."); args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + ".");
TShock.Log.ConsoleError("PasswordUser returned an error: " + ex); TShock.Log.ConsoleError("PasswordUser returned an error: " + ex);
@ -959,15 +965,15 @@ namespace TShockAPI
{ {
try try
{ {
var user = new User(); var account = new UserAccount();
string echoPassword = ""; string echoPassword = "";
if (args.Parameters.Count == 1) if (args.Parameters.Count == 1)
{ {
user.Name = args.Player.Name; account.Name = args.Player.Name;
echoPassword = args.Parameters[0]; echoPassword = args.Parameters[0];
try try
{ {
user.CreateBCryptHash(args.Parameters[0]); account.CreateBCryptHash(args.Parameters[0]);
} }
catch (ArgumentOutOfRangeException) catch (ArgumentOutOfRangeException)
{ {
@ -977,11 +983,11 @@ namespace TShockAPI
} }
else if (args.Parameters.Count == 2 && TShock.Config.AllowRegisterAnyUsername) else if (args.Parameters.Count == 2 && TShock.Config.AllowRegisterAnyUsername)
{ {
user.Name = args.Parameters[0]; account.Name = args.Parameters[0];
echoPassword = args.Parameters[1]; echoPassword = args.Parameters[1];
try try
{ {
user.CreateBCryptHash(args.Parameters[1]); account.CreateBCryptHash(args.Parameters[1]);
} }
catch (ArgumentOutOfRangeException) catch (ArgumentOutOfRangeException)
{ {
@ -995,24 +1001,24 @@ namespace TShockAPI
return; return;
} }
user.Group = TShock.Config.DefaultRegistrationGroupName; // FIXME -- we should get this from the DB. --Why? account.Group = TShock.Config.DefaultRegistrationGroupName; // FIXME -- we should get this from the DB. --Why?
user.UUID = args.Player.UUID; 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); args.Player.SendSuccessMessage("Your password is {0}.", echoPassword);
TShock.Users.AddUser(user); TShock.UserAccounts.AddUserAccount(account);
TShock.Log.ConsoleInfo("{0} registered an account: \"{1}\".", args.Player.Name, user.Name); TShock.Log.ConsoleInfo("{0} registered an account: \"{1}\".", args.Player.Name, account.Name);
} }
else 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."); 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 + "."); args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + ".");
TShock.Log.ConsoleError("RegisterUser returned an error: " + ex); TShock.Log.ConsoleError("RegisterUser returned an error: " + ex);
@ -1033,57 +1039,57 @@ namespace TShockAPI
// Add requires a username, password, and a group specified. // Add requires a username, password, and a group specified.
if (subcmd == "add" && args.Parameters.Count == 4) 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 try
{ {
user.CreateBCryptHash(args.Parameters[2]); account.CreateBCryptHash(args.Parameters[2]);
} }
catch (ArgumentOutOfRangeException) catch (ArgumentOutOfRangeException)
{ {
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters."); args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
return; return;
} }
user.Group = args.Parameters[3]; account.Group = args.Parameters[3];
try try
{ {
TShock.Users.AddUser(user); TShock.UserAccounts.AddUserAccount(account);
args.Player.SendSuccessMessage("Account " + user.Name + " has been added to group " + user.Group + "!"); args.Player.SendSuccessMessage("Account " + account.Name + " has been added to group " + account.Group + "!");
TShock.Log.ConsoleInfo(args.Player.Name + " added Account " + user.Name + " to group " + user.Group); TShock.Log.ConsoleInfo(args.Player.Name + " added Account " + account.Name + " to group " + account.Group);
} }
catch (GroupNotExistsException) 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()); TShock.Log.ConsoleError(e.ToString());
} }
} }
// User deletion requires a username // User deletion requires a username
else if (subcmd == "del" && args.Parameters.Count == 2) else if (subcmd == "del" && args.Parameters.Count == 2)
{ {
var user = new User(); var account = new UserAccount();
user.Name = args.Parameters[1]; account.Name = args.Parameters[1];
try try
{ {
TShock.Users.RemoveUser(user); TShock.UserAccounts.RemoveUserAccount(account);
args.Player.SendSuccessMessage("Account removed successfully."); args.Player.SendSuccessMessage("Account removed successfully.");
TShock.Log.ConsoleInfo(args.Player.Name + " successfully deleted account: " + args.Parameters[1] + "."); 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); args.Player.SendErrorMessage(ex.Message);
TShock.Log.ConsoleError(ex.ToString()); TShock.Log.ConsoleError(ex.ToString());
@ -1093,22 +1099,22 @@ namespace TShockAPI
// Password changing requires a username, and a new password to set // Password changing requires a username, and a new password to set
else if (subcmd == "password" && args.Parameters.Count == 3) else if (subcmd == "password" && args.Parameters.Count == 3)
{ {
var user = new User(); var account = new UserAccount();
user.Name = args.Parameters[1]; account.Name = args.Parameters[1];
try try
{ {
TShock.Users.SetUserPassword(user, args.Parameters[2]); TShock.UserAccounts.SetUserAccountPassword(account, args.Parameters[2]);
TShock.Log.ConsoleInfo(args.Player.Name + " changed the password of account " + user.Name); TShock.Log.ConsoleInfo(args.Player.Name + " changed the password of account " + account.Name);
args.Player.SendSuccessMessage("Password change succeeded for " + user.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()); TShock.Log.ConsoleError(e.ToString());
} }
catch (ArgumentOutOfRangeException) catch (ArgumentOutOfRangeException)
@ -1119,26 +1125,26 @@ namespace TShockAPI
// Group changing requires a username or IP address, and a new group to set // Group changing requires a username or IP address, and a new group to set
else if (subcmd == "group" && args.Parameters.Count == 3) else if (subcmd == "group" && args.Parameters.Count == 3)
{ {
var user = new User(); var account = new UserAccount();
user.Name = args.Parameters[1]; account.Name = args.Parameters[1];
try try
{ {
TShock.Users.SetUserGroup(user, args.Parameters[2]); TShock.UserAccounts.SetUserGroup(account, args.Parameters[2]);
TShock.Log.ConsoleInfo(args.Player.Name + " changed account " + user.Name + " to group " + args.Parameters[2] + "."); TShock.Log.ConsoleInfo(args.Player.Name + " changed account " + account.Name + " to group " + args.Parameters[2] + ".");
args.Player.SendSuccessMessage("Account " + user.Name + " has been changed to group " + args.Parameters[2] + "!"); args.Player.SendSuccessMessage("Account " + account.Name + " has been changed to group " + args.Parameters[2] + "!");
} }
catch (GroupNotExistsException) catch (GroupNotExistsException)
{ {
args.Player.SendErrorMessage("That group does not exist!"); 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()); TShock.Log.ConsoleError(e.ToString());
} }
} }
@ -1198,8 +1204,8 @@ namespace TShockAPI
{ {
var message = new StringBuilder(); var message = new StringBuilder();
message.Append("IP Address: ").Append(players[0].IP); message.Append("IP Address: ").Append(players[0].IP);
if (players[0].User != null && players[0].IsLoggedIn) if (players[0].Account != null && players[0].IsLoggedIn)
message.Append(" | Logged in as: ").Append(players[0].User.Name).Append(" | Group: ").Append(players[0].Group.Name); message.Append(" | Logged in as: ").Append(players[0].Account.Name).Append(" | Group: ").Append(players[0].Group.Name);
args.Player.SendSuccessMessage(message.ToString()); args.Player.SendSuccessMessage(message.ToString());
} }
} }
@ -1215,28 +1221,28 @@ namespace TShockAPI
string username = String.Join(" ", args.Parameters); string username = String.Join(" ", args.Parameters);
if (!string.IsNullOrWhiteSpace(username)) if (!string.IsNullOrWhiteSpace(username))
{ {
var user = TShock.Users.GetUserByName(username); var account = TShock.UserAccounts.GetUserAccountByName(username);
if (user != null) if (account != null)
{ {
DateTime LastSeen; DateTime LastSeen;
string Timezone = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours.ToString("+#;-#"); 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(); LastSeen = DateTime.Parse(account.LastAccessed).ToLocalTime();
args.Player.SendSuccessMessage("{0}'s last login occured {1} {2} UTC{3}.", user.Name, LastSeen.ToShortDateString(), args.Player.SendSuccessMessage("{0}'s last login occured {1} {2} UTC{3}.", account.Name, LastSeen.ToShortDateString(),
LastSeen.ToShortTimeString(), Timezone); LastSeen.ToShortTimeString(), Timezone);
} }
if (args.Player.Group.HasPermission(Permissions.advaccountinfo)) if (args.Player.Group.HasPermission(Permissions.advaccountinfo))
{ {
List<string> KnownIps = JsonConvert.DeserializeObject<List<string>>(user.KnownIps?.ToString() ?? string.Empty); List<string> KnownIps = JsonConvert.DeserializeObject<List<string>>(account.KnownIps?.ToString() ?? string.Empty);
string ip = KnownIps?[KnownIps.Count - 1] ?? "N/A"; 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 group is {1}.", account.Name, account.Group);
args.Player.SendSuccessMessage("{0}'s last known IP is {1}.", user.Name, ip); 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}.", user.Name, Registered.ToShortDateString(), Registered.ToShortTimeString(), Timezone); args.Player.SendSuccessMessage("{0}'s register date is {1} {2} UTC{3}.", account.Name, Registered.ToShortDateString(), Registered.ToShortTimeString(), Timezone);
} }
} }
else else
@ -1303,7 +1309,7 @@ namespace TShockAPI
// Effective ban target assignment // Effective ban target assignment
List<TSPlayer> players = TShock.Utils.FindPlayer(args.Parameters[1]); List<TSPlayer> 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 // 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 // If it is, we assume they have full control and let them override permission checks
@ -1365,7 +1371,7 @@ namespace TShockAPI
} }
targetGeneralizedName = target.Name; 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")); banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
// Since this is an online ban, we need to dc the player and tell them now. // 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])) { if (r.IsMatch(args.Parameters[1])) {
targetGeneralizedName = "IP: " + args.Parameters[1]; targetGeneralizedName = "IP: " + args.Parameters[1];
success = TShock.Bans.AddBan2(args.Parameters[1], "", "", "", banReason, success = TShock.Bans.AddBan2(args.Parameters[1], "", "", "", banReason,
false, args.Player.User.Name, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s")); false, args.Player.Account.Name, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
if (success && offlineUser != null) if (success && offlineUserAccount != null)
{ {
args.Player.SendSuccessMessage("Target IP {0} was banned successfully.", targetGeneralizedName); args.Player.SendSuccessMessage("Target IP {0} was banned successfully.", targetGeneralizedName);
args.Player.SendErrorMessage("Note: An account named with this IP address also exists."); 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 // Apparently there is no way to not IP ban someone
// This means that where we would normally just ban a "character name" here // 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. // 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("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."); 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 // 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 // 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 // This means that we're banning their *user name* on the assumption that
// user name == character name // user name == character name
// (which may not be true) // (which may not be true)
// This needs to be fixed in a future implementation. // 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) !callerIsServerConsole)
{ {
args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", targetGeneralizedName); args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", targetGeneralizedName);
return; 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); args.Player.SendErrorMessage("Unable to ban target {0} because they have no valid IP to ban.", targetGeneralizedName);
return; return;
} }
string lastIP = JsonConvert.DeserializeObject<List<string>>(offlineUser.KnownIps).Last(); string lastIP = JsonConvert.DeserializeObject<List<string>>(offlineUserAccount.KnownIps).Last();
success = success =
TShock.Bans.AddBan2(lastIP, 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")); banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
} }
@ -1458,12 +1464,12 @@ namespace TShockAPI
if (banLengthInSeconds == 0) if (banLengthInSeconds == 0)
{ {
TSPlayer.All.SendErrorMessage("{0} was permanently banned by {1} for: {2}", TSPlayer.All.SendErrorMessage("{0} was permanently banned by {1} for: {2}",
targetGeneralizedName, args.Player.User.Name, banReason); targetGeneralizedName, args.Player.Account.Name, banReason);
} }
else else
{ {
TSPlayer.All.SendErrorMessage("{0} was temp banned for {1} seconds by {2} for: {3}", 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) 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])) 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 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); 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())) Main.worldID.ToString()))
{ {
args.Player.TempPoints[0] = Point.Zero; args.Player.TempPoints[0] = Point.Zero;
@ -4276,7 +4282,7 @@ namespace TShockAPI
regionName = regionName + " " + args.Parameters[i]; regionName = regionName + " " + args.Parameters[i];
} }
} }
if (TShock.Users.GetUserByName(playerName) != null) if (TShock.UserAccounts.GetUserAccountByName(playerName) != null)
{ {
if (TShock.Regions.AddNewUser(regionName, playerName)) if (TShock.Regions.AddNewUser(regionName, playerName))
{ {
@ -4311,7 +4317,7 @@ namespace TShockAPI
regionName = regionName + " " + args.Parameters[i]; regionName = regionName + " " + args.Parameters[i];
} }
} }
if (TShock.Users.GetUserByName(playerName) != null) if (TShock.UserAccounts.GetUserAccountByName(playerName) != null)
{ {
if (TShock.Regions.RemoveUser(regionName, playerName)) if (TShock.Regions.RemoveUser(regionName, playerName))
{ {
@ -4452,9 +4458,9 @@ namespace TShockAPI
{ {
IEnumerable<string> sharedUsersSelector = region.AllowedIDs.Select(userId => IEnumerable<string> sharedUsersSelector = region.AllowedIDs.Select(userId =>
{ {
User user = TShock.Users.GetUserByID(userId); UserAccount account = TShock.UserAccounts.GetUserAccountByID(userId);
if (user != null) if (account != null)
return user.Name; return account.Name;
return string.Concat("{ID: ", userId, "}"); return string.Concat("{ID: ", userId, "}");
}); });

View file

@ -120,7 +120,7 @@ namespace TShockAPI.DB
return playerData; return playerData;
} }
public bool SeedInitialData(User user) public bool SeedInitialData(UserAccount user)
{ {
var inventory = new StringBuilder(); var inventory = new StringBuilder();
@ -165,17 +165,17 @@ namespace TShockAPI.DB
if (player.HasPermission(Permissions.bypassssc) && !fromCommand) 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; return false;
} }
if (!GetPlayerData(player, player.User.ID).exists) if (!GetPlayerData(player, player.Account.ID).exists)
{ {
try try
{ {
database.Query( 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);", "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; return true;
} }
catch (Exception ex) catch (Exception ex)
@ -189,7 +189,7 @@ namespace TShockAPI.DB
{ {
database.Query( 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;", "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; return true;
} }
catch (Exception ex) catch (Exception ex)
@ -235,17 +235,17 @@ namespace TShockAPI.DB
if (player.HasPermission(Permissions.bypassssc)) 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; return true;
} }
if (!GetPlayerData(player, player.User.ID).exists) if (!GetPlayerData(player, player.Account.ID).exists)
{ {
try try
{ {
database.Query( 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);", "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.health,
playerData.maxHealth, playerData.maxHealth,
playerData.mana, playerData.mana,
@ -284,7 +284,7 @@ namespace TShockAPI.DB
playerData.mana, playerData.mana,
playerData.maxMana, playerData.maxMana,
String.Join("~", playerData.inventory), String.Join("~", playerData.inventory),
player.User.ID, player.Account.ID,
playerData.spawnX, playerData.spawnX,
playerData.spawnX, playerData.spawnX,
playerData.skinVariant, playerData.skinVariant,

View file

@ -447,7 +447,7 @@ namespace TShockAPI.DB
Region r = GetRegionByName(regionName); Region r = GetRegionByName(regionName);
if (r != null) if (r != null)
{ {
if (!r.RemoveID(TShock.Users.GetUserID(userName))) if (!r.RemoveID(TShock.UserAccounts.GetUserAccountID(userName)))
{ {
return false; return false;
} }
@ -479,7 +479,7 @@ namespace TShockAPI.DB
mergedIDs = reader.Get<string>("UserIds"); mergedIDs = reader.Get<string>("UserIds");
} }
string userIdToAdd = Convert.ToString(TShock.Users.GetUserID(userName)); string userIdToAdd = Convert.ToString(TShock.UserAccounts.GetUserAccountID(userName));
string[] ids = mergedIDs.Split(','); string[] ids = mergedIDs.Split(',');
// Is the user already allowed to the region? // Is the user already allowed to the region?
if (ids.Contains(userIdToAdd)) if (ids.Contains(userIdToAdd))
@ -788,7 +788,7 @@ namespace TShockAPI.DB
return false; 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;
} }
/// <summary> /// <summary>

View file

@ -28,16 +28,16 @@ using System.Security.Cryptography;
namespace TShockAPI.DB namespace TShockAPI.DB
{ {
/// <summary>UserManager - Methods for dealing with database users and other user functionality within TShock.</summary> /// <summary>UserAccountManager - Methods for dealing with database user accounts and other related functionality within TShock.</summary>
public class UserManager public class UserAccountManager
{ {
/// <summary>database - The database object to use for connections.</summary> /// <summary>database - The database object to use for connections.</summary>
private IDbConnection _database; private IDbConnection _database;
/// <summary>Creates a UserManager object. During instantiation, this method will verify the table structure against the format below.</summary> /// <summary>Creates a UserAccountManager object. During instantiation, this method will verify the table structure against the format below.</summary>
/// <param name="db">The database to connect to.</param> /// <param name="db">The database to connect to.</param>
/// <returns>A UserManager object.</returns> /// <returns>A UserAccountManager object.</returns>
public UserManager(IDbConnection db) public UserAccountManager(IDbConnection db)
{ {
_database = db; _database = db;
@ -59,145 +59,145 @@ namespace TShockAPI.DB
} }
/// <summary> /// <summary>
/// Adds a given username to the database /// Adds the given user account to the database
/// </summary> /// </summary>
/// <param name="user">User user</param> /// <param name="account">The user account to be added</param>
public void AddUser(User user) public void AddUserAccount(UserAccount account)
{ {
if (!TShock.Groups.GroupExists(user.Group)) if (!TShock.Groups.GroupExists(account.Group))
throw new GroupNotExistsException(user.Group); throw new GroupNotExistsException(account.Group);
int ret; int ret;
try try
{ {
ret = _database.Query("INSERT INTO Users (Username, Password, UUID, UserGroup, Registered) VALUES (@0, @1, @2, @3, @4);", user.Name, ret = _database.Query("INSERT INTO Users (Username, Password, UUID, UserGroup, Registered) VALUES (@0, @1, @2, @3, @4);", account.Name,
user.Password, user.UUID, user.Group, DateTime.UtcNow.ToString("s")); account.Password, account.UUID, account.Group, DateTime.UtcNow.ToString("s"));
} }
catch (Exception ex) catch (Exception ex)
{ {
// Detect duplicate user using a regexp as Sqlite doesn't have well structured exceptions // Detect duplicate user using a regexp as Sqlite doesn't have well structured exceptions
if (Regex.IsMatch(ex.Message, "Username.*not unique")) if (Regex.IsMatch(ex.Message, "Username.*not unique"))
throw new UserExistsException(user.Name); throw new UserAccountExistsException(account.Name);
throw new UserManagerException("AddUser SQL returned an error (" + ex.Message + ")", ex); throw new UserAccountManagerException("AddUser SQL returned an error (" + ex.Message + ")", ex);
} }
if (1 > ret) if (1 > ret)
throw new UserExistsException(user.Name); throw new UserAccountExistsException(account.Name);
Hooks.AccountHooks.OnAccountCreate(user); Hooks.AccountHooks.OnAccountCreate(account);
} }
/// <summary> /// <summary>
/// Removes a given username from the database /// Removes all user accounts from the database whose usernames match the given user account
/// </summary> /// </summary>
/// <param name="user">User user</param> /// <param name="account">The user account</param>
public void RemoveUser(User user) public void RemoveUserAccount(UserAccount account)
{ {
try try
{ {
var tempuser = GetUser(user); var tempuser = GetUserAccount(account);
int affected = _database.Query("DELETE FROM Users WHERE Username=@0", user.Name); int affected = _database.Query("DELETE FROM Users WHERE Username=@0", account.Name);
if (affected < 1) if (affected < 1)
throw new UserNotExistException(user.Name); throw new UserAccountNotExistException(account.Name);
Hooks.AccountHooks.OnAccountDelete(tempuser); Hooks.AccountHooks.OnAccountDelete(tempuser);
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new UserManagerException("RemoveUser SQL returned an error", ex); throw new UserAccountManagerException("RemoveUser SQL returned an error", ex);
} }
} }
/// <summary> /// <summary>
/// Sets the Hashed Password for a given username /// Sets the Hashed Password for a given username
/// </summary> /// </summary>
/// <param name="user">User user</param> /// <param name="account">The user account</param>
/// <param name="password">string password</param> /// <param name="password">The user account password to be set</param>
public void SetUserPassword(User user, string password) public void SetUserAccountPassword(UserAccount account, string password)
{ {
try try
{ {
user.CreateBCryptHash(password); account.CreateBCryptHash(password);
if ( if (
_database.Query("UPDATE Users SET Password = @0 WHERE Username = @1;", user.Password, _database.Query("UPDATE Users SET Password = @0 WHERE Username = @1;", account.Password,
user.Name) == 0) account.Name) == 0)
throw new UserNotExistException(user.Name); throw new UserAccountNotExistException(account.Name);
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new UserManagerException("SetUserPassword SQL returned an error", ex); throw new UserAccountManagerException("SetUserPassword SQL returned an error", ex);
} }
} }
/// <summary> /// <summary>
/// Sets the UUID for a given username /// Sets the UUID for a given username
/// </summary> /// </summary>
/// <param name="user">User user</param> /// <param name="account">The user account</param>
/// <param name="uuid">string uuid</param> /// <param name="uuid">The user account uuid to be set</param>
public void SetUserUUID(User user, string uuid) public void SetUserAccountUUID(UserAccount account, string uuid)
{ {
try try
{ {
if ( if (
_database.Query("UPDATE Users SET UUID = @0 WHERE Username = @1;", uuid, _database.Query("UPDATE Users SET UUID = @0 WHERE Username = @1;", uuid,
user.Name) == 0) account.Name) == 0)
throw new UserNotExistException(user.Name); throw new UserAccountNotExistException(account.Name);
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new UserManagerException("SetUserUUID SQL returned an error", ex); throw new UserAccountManagerException("SetUserUUID SQL returned an error", ex);
} }
} }
/// <summary> /// <summary>
/// Sets the group for a given username /// Sets the group for a given username
/// </summary> /// </summary>
/// <param name="user">User user</param> /// <param name="account">The user account</param>
/// <param name="group">string group</param> /// <param name="group">The user account group to be set</param>
public void SetUserGroup(User user, string group) public void SetUserGroup(UserAccount account, string group)
{ {
Group grp = TShock.Groups.GetGroupByName(group); Group grp = TShock.Groups.GetGroupByName(group);
if (null == grp) if (null == grp)
throw new GroupNotExistsException(group); throw new GroupNotExistsException(group);
if (_database.Query("UPDATE Users SET UserGroup = @0 WHERE Username = @1;", group, user.Name) == 0) if (_database.Query("UPDATE Users SET UserGroup = @0 WHERE Username = @1;", group, account.Name) == 0)
throw new UserNotExistException(user.Name); throw new UserAccountNotExistException(account.Name);
try try
{ {
// Update player group reference for any logged in player // 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; player.Group = grp;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new UserManagerException("SetUserGroup SQL returned an error", ex); throw new UserAccountManagerException("SetUserGroup SQL returned an error", ex);
} }
} }
/// <summary>Updates the last accessed time for a database user to the current time.</summary> /// <summary>Updates the last accessed time for a database user account to the current time.</summary>
/// <param name="user">The user object to modify.</param> /// <param name="account">The user account object to modify.</param>
public void UpdateLogin(User user) public void UpdateLogin(UserAccount account)
{ {
try try
{ {
if (_database.Query("UPDATE Users SET LastAccessed = @0, KnownIps = @1 WHERE Username = @2;", DateTime.UtcNow.ToString("s"), user.KnownIps, user.Name) == 0) if (_database.Query("UPDATE Users SET LastAccessed = @0, KnownIps = @1 WHERE Username = @2;", DateTime.UtcNow.ToString("s"), account.KnownIps, account.Name) == 0)
throw new UserNotExistException(user.Name); throw new UserAccountNotExistException(account.Name);
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new UserManagerException("UpdateLogin SQL returned an error", ex); throw new UserAccountManagerException("UpdateLogin SQL returned an error", ex);
} }
} }
/// <summary>Gets the database ID of a given user object from the database.</summary> /// <summary>Gets the database ID of a given user account object from the database.</summary>
/// <param name="username">The username of the user to query for.</param> /// <param name="username">The username of the user account to query for.</param>
/// <returns>The user's ID</returns> /// <returns>The user account ID</returns>
public int GetUserID(string username) public int GetUserAccountID(string username)
{ {
try try
{ {
@ -216,55 +216,55 @@ namespace TShockAPI.DB
return -1; return -1;
} }
/// <summary>Gets a user object by name.</summary> /// <summary>Gets a user account object by name.</summary>
/// <param name="name">The user's name.</param> /// <param name="name">The user's name.</param>
/// <returns>The user object returned from the search.</returns> /// <returns>The user account object returned from the search.</returns>
public User GetUserByName(string name) public UserAccount GetUserAccountByName(string name)
{ {
try try
{ {
return GetUser(new User {Name = name}); return GetUserAccount(new UserAccount {Name = name});
} }
catch (UserManagerException) catch (UserAccountManagerException)
{ {
return null; return null;
} }
} }
/// <summary>Gets a user object by their user ID.</summary> /// <summary>Gets a user account object by their user account ID.</summary>
/// <param name="id">The user's ID.</param> /// <param name="id">The user's ID.</param>
/// <returns>The user object returned from the search.</returns> /// <returns>The user account object returned from the search.</returns>
public User GetUserByID(int id) public UserAccount GetUserAccountByID(int id)
{ {
try try
{ {
return GetUser(new User {ID = id}); return GetUserAccount(new UserAccount {ID = id});
} }
catch (UserManagerException) catch (UserAccountManagerException)
{ {
return null; return null;
} }
} }
/// <summary>Gets a user object by a user object.</summary> /// <summary>Gets a user account object by a user account object.</summary>
/// <param name="user">The user object to search by.</param> /// <param name="account">The user account object to search by.</param>
/// <returns>The user object that is returned from the search.</returns> /// <returns>The user object that is returned from the search.</returns>
public User GetUser(User user) public UserAccount GetUserAccount(UserAccount account)
{ {
bool multiple = false; bool multiple = false;
string query; string query;
string type; string type;
object arg; object arg;
if (0 != user.ID) if (account.ID != 0)
{ {
query = "SELECT * FROM Users WHERE ID=@0"; query = "SELECT * FROM Users WHERE ID=@0";
arg = user.ID; arg = account.ID;
type = "id"; type = "id";
} }
else else
{ {
query = "SELECT * FROM Users WHERE Username=@0"; query = "SELECT * FROM Users WHERE Username=@0";
arg = user.Name; arg = account.Name;
type = "name"; type = "name";
} }
@ -274,38 +274,38 @@ namespace TShockAPI.DB
{ {
if (result.Read()) if (result.Read())
{ {
user = LoadUserFromResult(user, result); account = LoadUserAccountFromResult(account, result);
// Check for multiple matches // Check for multiple matches
if (!result.Read()) if (!result.Read())
return user; return account;
multiple = true; multiple = true;
} }
} }
} }
catch (Exception ex) 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) 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);
} }
/// <summary>Gets all users from the database.</summary> /// <summary>Gets all the user accounts from the database.</summary>
/// <returns>The users from the database.</returns> /// <returns>The user accounts from the database.</returns>
public List<User> GetUsers() public List<UserAccount> GetUserAccounts()
{ {
try try
{ {
List<User> users = new List<User>(); List<UserAccount> accounts = new List<UserAccount>();
using (var reader = _database.QueryReader("SELECT * FROM Users")) using (var reader = _database.QueryReader("SELECT * FROM Users"))
{ {
while (reader.Read()) while (reader.Read())
{ {
users.Add(LoadUserFromResult(new User(), reader)); accounts.Add(LoadUserAccountFromResult(new UserAccount(), reader));
} }
return users; return accounts;
} }
} }
catch (Exception ex) catch (Exception ex)
@ -316,26 +316,26 @@ namespace TShockAPI.DB
} }
/// <summary> /// <summary>
/// Gets all users from the database with a username that starts with or contains <see cref="username"/> /// Gets all user accounts from the database with a username that starts with or contains <see cref="username"/>
/// </summary> /// </summary>
/// <param name="username">Rough username search. "n" will match "n", "na", "nam", "name", etc</param> /// <param name="username">Rough username search. "n" will match "n", "na", "nam", "name", etc</param>
/// <param name="notAtStart">If <see cref="username"/> is not the first part of the username. If true then "name" would match "name", "username", "wordsnamewords", etc</param> /// <param name="notAtStart">If <see cref="username"/> is not the first part of the username. If true then "name" would match "name", "username", "wordsnamewords", etc</param>
/// <returns>Matching users or null if exception is thrown</returns> /// <returns>Matching users or null if exception is thrown</returns>
public List<User> GetUsersByName(string username, bool notAtStart = false) public List<UserAccount> GetUserAccountsByName(string username, bool notAtStart = false)
{ {
try try
{ {
List<User> users = new List<User>(); List<UserAccount> accounts = new List<UserAccount>();
string search = notAtStart ? string.Format("%{0}%", username) : string.Format("{0}%", username); string search = notAtStart ? string.Format("%{0}%", username) : string.Format("{0}%", username);
using (var reader = _database.QueryReader("SELECT * FROM Users WHERE Username LIKE @0", using (var reader = _database.QueryReader("SELECT * FROM Users WHERE Username LIKE @0",
search)) search))
{ {
while (reader.Read()) while (reader.Read())
{ {
users.Add(LoadUserFromResult(new User(), reader)); accounts.Add(LoadUserAccountFromResult(new UserAccount(), reader));
} }
} }
return users; return accounts;
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -344,61 +344,61 @@ namespace TShockAPI.DB
return null; return null;
} }
/// <summary>Fills out the fields of a User object with the results from a QueryResult object.</summary> /// <summary>Fills out the fields of a User account object with the results from a QueryResult object.</summary>
/// <param name="user">The user to add data to.</param> /// <param name="account">The user account to add data to.</param>
/// <param name="result">The QueryResult object to add data from.</param> /// <param name="result">The QueryResult object to add data from.</param>
/// <returns>The 'filled out' user object.</returns> /// <returns>The 'filled out' user object.</returns>
private User LoadUserFromResult(User user, QueryResult result) private UserAccount LoadUserAccountFromResult(UserAccount account, QueryResult result)
{ {
user.ID = result.Get<int>("ID"); account.ID = result.Get<int>("ID");
user.Group = result.Get<string>("Usergroup"); account.Group = result.Get<string>("Usergroup");
user.Password = result.Get<string>("Password"); account.Password = result.Get<string>("Password");
user.UUID = result.Get<string>("UUID"); account.UUID = result.Get<string>("UUID");
user.Name = result.Get<string>("Username"); account.Name = result.Get<string>("Username");
user.Registered = result.Get<string>("Registered"); account.Registered = result.Get<string>("Registered");
user.LastAccessed = result.Get<string>("LastAccessed"); account.LastAccessed = result.Get<string>("LastAccessed");
user.KnownIps = result.Get<string>("KnownIps"); account.KnownIps = result.Get<string>("KnownIps");
return user; return account;
} }
} }
/// <summary>A database user.</summary> /// <summary>A database user account.</summary>
public class User : IEquatable<User> public class UserAccount : IEquatable<UserAccount>
{ {
/// <summary>The database ID of the user.</summary> /// <summary>The database ID of the user account.</summary>
public int ID { get; set; } public int ID { get; set; }
/// <summary>The user's name.</summary> /// <summary>The user's name.</summary>
public string Name { get; set; } public string Name { get; set; }
/// <summary>The hashed password for the user.</summary> /// <summary>The hashed password for the user account.</summary>
public string Password { get; internal set; } public string Password { get; internal set; }
/// <summary>The user's saved Univerally Unique Identifier token.</summary> /// <summary>The user's saved Univerally Unique Identifier token.</summary>
public string UUID { get; set; } public string UUID { get; set; }
/// <summary>The group object that the user is a part of.</summary> /// <summary>The group object that the user account is a part of.</summary>
public string Group { get; set; } public string Group { get; set; }
/// <summary>The unix epoch corresponding to the registration date of the user.</summary> /// <summary>The unix epoch corresponding to the registration date of the user account.</summary>
public string Registered { get; set; } public string Registered { get; set; }
/// <summary>The unix epoch corresponding to the last access date of the user.</summary> /// <summary>The unix epoch corresponding to the last access date of the user account.</summary>
public string LastAccessed { get; set; } public string LastAccessed { get; set; }
/// <summary>A JSON serialized list of known IP addresses for a user.</summary> /// <summary>A JSON serialized list of known IP addresses for a user account.</summary>
public string KnownIps { get; set; } public string KnownIps { get; set; }
/// <summary>Constructor for the user object, assuming you define everything yourself.</summary> /// <summary>Constructor for the user account object, assuming you define everything yourself.</summary>
/// <param name="name">The user's name.</param> /// <param name="name">The user's name.</param>
/// <param name="pass">The user's password hash.</param> /// <param name="pass">The user's password hash.</param>
/// <param name="uuid">The user's UUID.</param> /// <param name="uuid">The user's UUID.</param>
/// <param name="group">The user's group name.</param> /// <param name="group">The user's group name.</param>
/// <param name="registered">The unix epoch for the registration date.</param> /// <param name="registered">The unix epoch for the registration date.</param>
/// <param name="last">The unix epoch for the last access date.</param> /// <param name="last">The unix epoch for the last access date.</param>
/// <param name="known">The known IPs for the user, serialized as a JSON object</param> /// <param name="known">The known IPs for the user account, serialized as a JSON object</param>
/// <returns>A completed user object.</returns> /// <returns>A completed user account object.</returns>
public User(string name, string pass, string uuid, string group, string registered, string last, string known) public UserAccount(string name, string pass, string uuid, string group, string registered, string last, string known)
{ {
Name = name; Name = name;
Password = pass; Password = pass;
@ -409,9 +409,9 @@ namespace TShockAPI.DB
KnownIps = known; KnownIps = known;
} }
/// <summary>Default constructor for a user object; holds no data.</summary> /// <summary>Default constructor for a user account object; holds no data.</summary>
/// <returns>A user object.</returns> /// <returns>A user account object.</returns>
public User() public UserAccount()
{ {
Name = ""; Name = "";
Password = ""; 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 /// 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. /// is greater than the existing work factor with the new work factor.
/// </summary> /// </summary>
/// <param name="password">The password to check against the user object.</param> /// <param name="password">The password to check against the user account object.</param>
/// <returns>bool true, if the password matched, or false, if it didn't.</returns> /// <returns>bool true, if the password matched, or false, if it didn't.</returns>
public bool VerifyPassword(string password) public bool VerifyPassword(string password)
{ {
@ -459,7 +459,7 @@ namespace TShockAPI.DB
} }
/// <summary>Upgrades a password to BCrypt, from an insecure hashing algorithm.</summary> /// <summary>Upgrades a password to BCrypt, from an insecure hashing algorithm.</summary>
/// <param name="password">The raw user password (unhashed) to upgrade</param> /// <param name="password">The raw user account password (unhashed) to upgrade</param>
protected void UpgradePasswordToBCrypt(string password) protected void UpgradePasswordToBCrypt(string password)
{ {
// Save the old password, in the event that we have to revert changes. // Save the old password, in the event that we have to revert changes.
@ -467,9 +467,9 @@ namespace TShockAPI.DB
try try
{ {
TShock.Users.SetUserPassword(this, password); TShock.UserAccounts.SetUserAccountPassword(this, password);
} }
catch (UserManagerException e) catch (UserAccountManagerException e)
{ {
TShock.Log.ConsoleError(e.ToString()); TShock.Log.ConsoleError(e.ToString());
Password = oldpassword; // Revert changes Password = oldpassword; // Revert changes
@ -477,7 +477,7 @@ namespace TShockAPI.DB
} }
/// <summary>Upgrades a password to the highest work factor available in the config.</summary> /// <summary>Upgrades a password to the highest work factor available in the config.</summary>
/// <param name="password">The raw user password (unhashed) to upgrade</param> /// <param name="password">The raw user account password (unhashed) to upgrade</param>
protected void UpgradePasswordWorkFactor(string password) protected void UpgradePasswordWorkFactor(string password)
{ {
// If the destination work factor is not greater, we won't upgrade it or re-hash it // 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 try
{ {
TShock.Users.SetUserPassword(this, password); TShock.UserAccounts.SetUserAccountPassword(this, password);
} }
catch (UserManagerException e) catch (UserAccountManagerException e)
{ {
TShock.Log.ConsoleError(e.ToString()); TShock.Log.ConsoleError(e.ToString());
} }
} }
} }
/// <summary>Creates a BCrypt hash for a user and stores it in this object.</summary> /// <summary>Creates a BCrypt hash for a user account and stores it in this object.</summary>
/// <param name="password">The plain text password to hash</param> /// <param name="password">The plain text password to hash</param>
public void CreateBCryptHash(string password) public void CreateBCryptHash(string password)
{ {
@ -524,7 +524,7 @@ namespace TShockAPI.DB
} }
} }
/// <summary>Creates a BCrypt hash for a user and stores it in this object.</summary> /// <summary>Creates a BCrypt hash for a user account and stores it in this object.</summary>
/// <param name="password">The plain text password to hash</param> /// <param name="password">The plain text password to hash</param>
/// <param name="workFactor">The work factor to use in generating the password hash</param> /// <param name="workFactor">The work factor to use in generating the password hash</param>
public void CreateBCryptHash(string password, int workFactor) public void CreateBCryptHash(string password, int workFactor)
@ -583,29 +583,29 @@ namespace TShockAPI.DB
#region IEquatable #region IEquatable
/// <summary>Indicates whether the current <see cref="User"/> is equal to another <see cref="User"/>.</summary> /// <summary>Indicates whether the current <see cref="UserAccount"/> is equal to another <see cref="UserAccount"/>.</summary>
/// <returns>true if the <see cref="User"/> is equal to the <paramref name="other" /> parameter; otherwise, false.</returns> /// <returns>true if the <see cref="UserAccount"/> is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
/// <param name="other">An <see cref="User"/> to compare with this <see cref="User"/>.</param> /// <param name="other">An <see cref="UserAccount"/> to compare with this <see cref="UserAccount"/>.</param>
public bool Equals(User other) public bool Equals(UserAccount other)
{ {
if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true; if (ReferenceEquals(this, other)) return true;
return ID == other.ID && string.Equals(Name, other.Name); return ID == other.ID && string.Equals(Name, other.Name);
} }
/// <summary>Indicates whether the current <see cref="User"/> is equal to another object.</summary> /// <summary>Indicates whether the current <see cref="UserAccount"/> is equal to another object.</summary>
/// <returns>true if the <see cref="User"/> is equal to the <paramref name="obj" /> parameter; otherwise, false.</returns> /// <returns>true if the <see cref="UserAccount"/> is equal to the <paramref name="obj" /> parameter; otherwise, false.</returns>
/// <param name="obj">An <see cref="object"/> to compare with this <see cref="User"/>.</param> /// <param name="obj">An <see cref="object"/> to compare with this <see cref="UserAccount"/>.</param>
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true; if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false; if (obj.GetType() != this.GetType()) return false;
return Equals((User)obj); return Equals((UserAccount)obj);
} }
/// <summary>Serves as the hash function. </summary> /// <summary>Serves as the hash function. </summary>
/// <returns>A hash code for the current <see cref="User"/>.</returns> /// <returns>A hash code for the current <see cref="UserAccount"/>.</returns>
public override int GetHashCode() public override int GetHashCode()
{ {
unchecked unchecked
@ -615,86 +615,87 @@ namespace TShockAPI.DB
} }
/// <summary> /// <summary>
/// Compares equality of two <see cref="User"/> objects. /// Compares equality of two <see cref="UserAccount"/> objects.
/// </summary> /// </summary>
/// <param name="left">Left hand of the comparison.</param> /// <param name="left">Left hand of the comparison.</param>
/// <param name="right">Right hand of the comparison.</param> /// <param name="right">Right hand of the comparison.</param>
/// <returns>true if the <see cref="User"/> objects are equal; otherwise, false.</returns> /// <returns>true if the <see cref="UserAccount"/> objects are equal; otherwise, false.</returns>
public static bool operator ==(User left, User right) public static bool operator ==(UserAccount left, UserAccount right)
{ {
return Equals(left, right); return Equals(left, right);
} }
/// <summary> /// <summary>
/// Compares equality of two <see cref="User"/> objects. /// Compares equality of two <see cref="UserAccount"/> objects.
/// </summary> /// </summary>
/// <param name="left">Left hand of the comparison.</param> /// <param name="left">Left hand of the comparison.</param>
/// <param name="right">Right hand of the comparison.</param> /// <param name="right">Right hand of the comparison.</param>
/// <returns>true if the <see cref="User"/> objects aren't equal; otherwise, false.</returns> /// <returns>true if the <see cref="UserAccount"/> objects aren't equal; otherwise, false.</returns>
public static bool operator !=(User left, User right) public static bool operator !=(UserAccount left, UserAccount right)
{ {
return !Equals(left, right); return !Equals(left, right);
} }
#endregion #endregion
public override string ToString() /// <summary>
{ /// Converts the UserAccount to it's string representation
return Name; /// </summary>
} /// <returns>Returns the UserAccount string representation</returns>
public override string ToString() => Name;
} }
/// <summary>UserManagerException - An exception generated by the user manager.</summary> /// <summary>UserAccountManagerException - An exception generated by the user account manager.</summary>
[Serializable] [Serializable]
public class UserManagerException : Exception public class UserAccountManagerException : Exception
{ {
/// <summary>Creates a new UserManagerException object.</summary> /// <summary>Creates a new UserAccountManagerException object.</summary>
/// <param name="message">The message for the object.</param> /// <param name="message">The message for the object.</param>
/// <returns>A new UserManagerException object.</returns> /// <returns>A new UserAccountManagerException object.</returns>
public UserManagerException(string message) public UserAccountManagerException(string message)
: base(message) : base(message)
{ {
} }
/// <summary>Creates a new UserManagerObject with an internal exception.</summary> /// <summary>Creates a new UserAccountManager Object with an internal exception.</summary>
/// <param name="message">The message for the object.</param> /// <param name="message">The message for the object.</param>
/// <param name="inner">The inner exception for the object.</param> /// <param name="inner">The inner exception for the object.</param>
/// <returns>A new UserManagerException with a defined inner exception.</returns> /// <returns>A new UserAccountManagerException with a defined inner exception.</returns>
public UserManagerException(string message, Exception inner) public UserAccountManagerException(string message, Exception inner)
: base(message, inner) : base(message, inner)
{ {
} }
} }
/// <summary>A UserExistsException object, used when a user already exists when attempting to create a new one.</summary> /// <summary>A UserExistsException object, used when a user account already exists when attempting to create a new one.</summary>
[Serializable] [Serializable]
public class UserExistsException : UserManagerException public class UserAccountExistsException : UserAccountManagerException
{ {
/// <summary>Creates a new UserExistsException object.</summary> /// <summary>Creates a new UserAccountExistsException object.</summary>
/// <param name="name">The name of the user that already exists.</param> /// <param name="name">The name of the user account that already exists.</param>
/// <returns>A UserExistsException object with the user's name passed in the message.</returns> /// <returns>A UserAccountExistsException object with the user's name passed in the message.</returns>
public UserExistsException(string name) public UserAccountExistsException(string name)
: base("User '" + name + "' already exists") : base("User account '" + name + "' already exists")
{ {
} }
} }
/// <summary>A UserNotExistException, used when a user does not exist and a query failed as a result of it.</summary> /// <summary>A UserNotExistException, used when a user does not exist and a query failed as a result of it.</summary>
[Serializable] [Serializable]
public class UserNotExistException : UserManagerException public class UserAccountNotExistException : UserAccountManagerException
{ {
/// <summary>Creates a new UserNotExistException object, with the user's name in the message.</summary> /// <summary>Creates a new UserAccountNotExistException object, with the user account name in the message.</summary>
/// <param name="name">The user's name to be pasesd in the message.</param> /// <param name="name">The user account name to be pasesd in the message.</param>
/// <returns>A new UserNotExistException object with a message containing the user's name that does not exist.</returns> /// <returns>A new UserAccountNotExistException object with a message containing the user account name that does not exist.</returns>
public UserNotExistException(string name) public UserAccountNotExistException(string name)
: base("User '" + name + "' does not exist") : base("User account '" + name + "' does not exist")
{ {
} }
} }
/// <summary>A GroupNotExistsException, used when a group does not exist.</summary> /// <summary>A GroupNotExistsException, used when a group does not exist.</summary>
[Serializable] [Serializable]
public class GroupNotExistsException : UserManagerException public class GroupNotExistsException : UserAccountManagerException
{ {
/// <summary>Creates a new GroupNotExistsException object with the group's name in the message.</summary> /// <summary>Creates a new GroupNotExistsException object with the group's name in the message.</summary>
/// <param name="group">The group name.</param> /// <param name="group">The group name.</param>

View file

@ -1518,7 +1518,7 @@ namespace TShockAPI
private static bool HandleConnecting(GetDataHandlerArgs args) private static bool HandleConnecting(GetDataHandlerArgs args)
{ {
var user = TShock.Users.GetUserByName(args.Player.Name); var user = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
args.Player.DataWhenJoined = new PlayerData(args.Player); args.Player.DataWhenJoined = new PlayerData(args.Player);
args.Player.DataWhenJoined.CopyCharacter(args.Player); args.Player.DataWhenJoined.CopyCharacter(args.Player);
@ -1536,7 +1536,7 @@ namespace TShockAPI
args.Player.Group = group; args.Player.Group = group;
args.Player.tempGroup = null; args.Player.tempGroup = null;
args.Player.User = user; args.Player.Account = user;
args.Player.IsLoggedIn = true; args.Player.IsLoggedIn = true;
args.Player.IgnoreActionsForInventory = "none"; args.Player.IgnoreActionsForInventory = "none";
@ -1592,7 +1592,7 @@ namespace TShockAPI
if (Hooks.PlayerHooks.OnPlayerPreLogin(args.Player, args.Player.Name, password)) if (Hooks.PlayerHooks.OnPlayerPreLogin(args.Player, args.Player.Name, password))
return true; return true;
var user = TShock.Users.GetUserByName(args.Player.Name); var user = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
if (user != null && !TShock.Config.DisableLoginBeforeJoin) if (user != null && !TShock.Config.DisableLoginBeforeJoin)
{ {
if (user.VerifyPassword(password)) if (user.VerifyPassword(password))
@ -1608,7 +1608,7 @@ namespace TShockAPI
args.Player.Group = group; args.Player.Group = group;
args.Player.tempGroup = null; args.Player.tempGroup = null;
args.Player.User = user; args.Player.Account = user;
args.Player.IsLoggedIn = true; args.Player.IsLoggedIn = true;
args.Player.IgnoreActionsForInventory = "none"; args.Player.IgnoreActionsForInventory = "none";
@ -1632,7 +1632,7 @@ namespace TShockAPI
args.Player.SendMessage("Authenticated as " + args.Player.Name + " successfully.", Color.LimeGreen); 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.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user " + args.Player.Name + ".");
TShock.Users.SetUserUUID(user, args.Player.UUID); TShock.UserAccounts.SetUserAccountUUID(user, args.Player.UUID);
Hooks.PlayerHooks.OnPlayerPostLogin(args.Player); Hooks.PlayerHooks.OnPlayerPostLogin(args.Player);
return true; return true;
} }
@ -2963,9 +2963,9 @@ namespace TShockAPI
if (args.TPlayer.difficulty == 2 && Main.ServerSideCharacter && args.Player.IsLoggedIn) 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 (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);
} }
} }

View file

@ -21,9 +21,9 @@ namespace TShockAPI.Hooks
{ {
public class AccountDeleteEventArgs public class AccountDeleteEventArgs
{ {
public User User { get; private set; } public UserAccount User { get; private set; }
public AccountDeleteEventArgs(User user) public AccountDeleteEventArgs(UserAccount user)
{ {
this.User = user; this.User = user;
} }
@ -31,9 +31,9 @@ namespace TShockAPI.Hooks
public class AccountCreateEventArgs public class AccountCreateEventArgs
{ {
public User User { get; private set; } public UserAccount User { get; private set; }
public AccountCreateEventArgs(User user) public AccountCreateEventArgs(UserAccount user)
{ {
this.User = user; this.User = user;
} }
@ -44,7 +44,7 @@ namespace TShockAPI.Hooks
public delegate void AccountCreateD(AccountCreateEventArgs e); public delegate void AccountCreateD(AccountCreateEventArgs e);
public static event AccountCreateD AccountCreate; public static event AccountCreateD AccountCreate;
public static void OnAccountCreate(User u) public static void OnAccountCreate(UserAccount u)
{ {
if (AccountCreate == null) if (AccountCreate == null)
return; return;
@ -55,7 +55,7 @@ namespace TShockAPI.Hooks
public delegate void AccountDeleteD(AccountDeleteEventArgs e); public delegate void AccountDeleteD(AccountDeleteEventArgs e);
public static event AccountDeleteD AccountDelete; public static event AccountDeleteD AccountDelete;
public static void OnAccountDelete(User u) public static void OnAccountDelete(UserAccount u)
{ {
if (AccountDelete == null) if (AccountDelete == null)
return; return;

View file

@ -482,7 +482,7 @@ namespace TShockAPI
[Token] [Token]
private object UserActiveListV2(RestRequestArgs args) 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.")] [Description("Lists all user accounts in the TShock database.")]
@ -491,7 +491,7 @@ namespace TShockAPI
[Token] [Token]
private object UserListV2(RestRequestArgs args) private object UserListV2(RestRequestArgs args)
{ {
return new RestObject() { { "users", TShock.Users.GetUsers().Select(p => new Dictionary<string,object>(){ return new RestObject() { { "users", TShock.UserAccounts.GetUserAccounts().Select(p => new Dictionary<string,object>(){
{"name", p.Name}, {"name", p.Name},
{"id", p.ID}, {"id", p.ID},
{"group", p.Group}, {"group", p.Group},
@ -520,11 +520,11 @@ namespace TShockAPI
return RestMissingParam("password"); return RestMissingParam("password");
// NOTE: ip can be blank // NOTE: ip can be blank
User user = new User(username, "", "", group, "", "", ""); UserAccount user = new UserAccount(username, "", "", group, "", "", "");
try try
{ {
user.CreateBCryptHash(password); user.CreateBCryptHash(password);
TShock.Users.AddUser(user); TShock.UserAccounts.AddUserAccount(user);
} }
catch (Exception e) catch (Exception e)
{ {
@ -553,13 +553,13 @@ namespace TShockAPI
if (string.IsNullOrWhiteSpace(group) && string.IsNullOrWhiteSpace(password)) if (string.IsNullOrWhiteSpace(group) && string.IsNullOrWhiteSpace(password))
return RestMissingParam("group", "password"); return RestMissingParam("group", "password");
User user = (User)ret; UserAccount user = (UserAccount)ret;
var response = new RestObject(); var response = new RestObject();
if (!string.IsNullOrWhiteSpace(password)) if (!string.IsNullOrWhiteSpace(password))
{ {
try try
{ {
TShock.Users.SetUserPassword(user, password); TShock.UserAccounts.SetUserAccountPassword(user, password);
response.Add("password-response", "Password updated successfully"); response.Add("password-response", "Password updated successfully");
} }
catch (Exception e) catch (Exception e)
@ -572,7 +572,7 @@ namespace TShockAPI
{ {
try try
{ {
TShock.Users.SetUserGroup(user, group); TShock.UserAccounts.SetUserGroup(user, group);
response.Add("group-response", "Group updated successfully"); response.Add("group-response", "Group updated successfully");
} }
catch (Exception e) catch (Exception e)
@ -598,7 +598,7 @@ namespace TShockAPI
try try
{ {
TShock.Users.RemoveUser((User)ret); TShock.UserAccounts.RemoveUserAccount((UserAccount)ret);
} }
catch (Exception e) catch (Exception e)
{ {
@ -620,7 +620,7 @@ namespace TShockAPI
if (ret is RestObject) if (ret is RestObject)
return ret; return ret;
User user = (User)ret; UserAccount user = (UserAccount)ret;
return new RestObject() { { "group", user.Group }, { "id", user.ID.ToString() }, { "name", user.Name } }; return new RestObject() { { "group", user.Group }, { "id", user.ID.ToString() }, { "name", user.Name } };
} }
@ -938,10 +938,10 @@ namespace TShockAPI
return new RestObject() return new RestObject()
{ {
{"nickname", player.Name}, {"nickname", player.Name},
{"username", player.User?.Name}, {"username", player.Account?.Name},
{"ip", player.IP}, {"ip", player.IP},
{"group", player.Group.Name}, {"group", player.Group.Name},
{"registered", player.User?.Registered}, {"registered", player.Account?.Registered},
{"muted", player.mute }, {"muted", player.mute },
{"position", player.TileX + "," + player.TileY}, {"position", player.TileX + "," + player.TileY},
{"inventory", string.Join(", ", inventory.Select(p => (p.Name + ":" + p.stack)))}, {"inventory", string.Join(", ", inventory.Select(p => (p.Name + ":" + p.stack)))},
@ -979,10 +979,10 @@ namespace TShockAPI
return new RestObject return new RestObject
{ {
{"nickname", player.Name}, {"nickname", player.Name},
{"username", player.User?.Name}, {"username", player.Account?.Name},
{"ip", player.IP}, {"ip", player.IP},
{"group", player.Group.Name}, {"group", player.Group.Name},
{"registered", player.User?.Registered}, {"registered", player.Account?.Registered},
{"muted", player.mute }, {"muted", player.mute },
{"position", player.TileX + "," + player.TileY}, {"position", player.TileX + "," + player.TileY},
{"items", items}, {"items", items},
@ -1283,7 +1283,7 @@ namespace TShockAPI
if (string.IsNullOrWhiteSpace(name)) if (string.IsNullOrWhiteSpace(name))
return RestMissingParam("user"); return RestMissingParam("user");
User user; UserAccount user;
string type = parameters["type"]; string type = parameters["type"];
try try
{ {
@ -1292,10 +1292,10 @@ namespace TShockAPI
case null: case null:
case "name": case "name":
type = "name"; type = "name";
user = TShock.Users.GetUserByName(name); user = TShock.UserAccounts.GetUserAccountByName(name);
break; break;
case "id": case "id":
user = TShock.Users.GetUserByID(Convert.ToInt32(name)); user = TShock.UserAccounts.GetUserAccountByID(Convert.ToInt32(name));
break; break;
default: default:
return RestError("Invalid Type: '" + type + "'"); return RestError("Invalid Type: '" + type + "'");
@ -1359,7 +1359,7 @@ namespace TShockAPI
var player = new Dictionary<string, object> var player = new Dictionary<string, object>
{ {
{"nickname", tsPlayer.Name}, {"nickname", tsPlayer.Name},
{"username", tsPlayer.User == null ? "" : tsPlayer.User.Name}, {"username", tsPlayer.Account == null ? "" : tsPlayer.Account.Name},
{"group", tsPlayer.Group.Name}, {"group", tsPlayer.Group.Name},
{"active", tsPlayer.Active}, {"active", tsPlayer.Active},
{"state", tsPlayer.State}, {"state", tsPlayer.State},

View file

@ -131,7 +131,7 @@ namespace Rests
tokenBucket.Add(context.RemoteEndPoint.Address.ToString(), 1); // First time request, set to one and process request 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) if (userAccount == null)
{ {
AddTokenToBucket(context.RemoteEndPoint.Address.ToString()); AddTokenToBucket(context.RemoteEndPoint.Address.ToString());
@ -216,4 +216,4 @@ namespace Rests
return result; return result;
} }
} }
} }

View file

@ -218,10 +218,10 @@ namespace TShockAPI
public Vector2 LastNetPosition = Vector2.Zero; public Vector2 LastNetPosition = Vector2.Zero;
/// <summary> /// <summary>
/// User object associated with the player. /// UserAccount object associated with the player.
/// Set when the player logs in. /// Set when the player logs in.
/// </summary> /// </summary>
public User User { get; set; } public UserAccount Account { get; set; }
/// <summary> /// <summary>
/// Whether the player performed a valid login attempt (i.e. entered valid user name and password) but is still blocked /// 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)) 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; return true;
} }
PlayerData.CopyCharacter(this); PlayerData.CopyCharacter(this);
@ -656,7 +656,7 @@ namespace TShockAPI
{ {
tempGroupTimer.Stop(); tempGroupTimer.Stop();
} }
User = null; Account = null;
IsLoggedIn = false; IsLoggedIn = false;
} }

View file

@ -36,7 +36,7 @@ namespace TShockAPI
: base("Server") : base("Server")
{ {
Group = new SuperAdminGroup(); Group = new SuperAdminGroup();
User = new User { Name = AccountName }; Account = new UserAccount { Name = AccountName };
} }
public override void SendErrorMessage(string msg) public override void SendErrorMessage(string msg)

View file

@ -94,7 +94,7 @@ namespace TShockAPI
/// <summary>Groups - Static reference to the group manager for accessing the group system.</summary> /// <summary>Groups - Static reference to the group manager for accessing the group system.</summary>
public static GroupManager Groups; public static GroupManager Groups;
/// <summary>Users - Static reference to the user manager for accessing the user database system.</summary> /// <summary>Users - Static reference to the user manager for accessing the user database system.</summary>
public static UserManager Users; public static UserAccountManager UserAccounts;
/// <summary>Itembans - Static reference to the item ban system.</summary> /// <summary>Itembans - Static reference to the item ban system.</summary>
public static ItemManager Itembans; public static ItemManager Itembans;
/// <summary>ProjectileBans - Static reference to the projectile ban system.</summary> /// <summary>ProjectileBans - Static reference to the projectile ban system.</summary>
@ -312,7 +312,7 @@ namespace TShockAPI
Bans = new BanManager(DB); Bans = new BanManager(DB);
Warps = new WarpManager(DB); Warps = new WarpManager(DB);
Regions = new RegionManager(DB); Regions = new RegionManager(DB);
Users = new UserManager(DB); UserAccounts = new UserAccountManager(DB);
Groups = new GroupManager(DB); Groups = new GroupManager(DB);
Itembans = new ItemManager(DB); Itembans = new ItemManager(DB);
ProjectileBans = new ProjectileManagager(DB); ProjectileBans = new ProjectileManagager(DB);
@ -391,7 +391,7 @@ namespace TShockAPI
{ {
foreach (TSPlayer player in TShock.Players) foreach (TSPlayer player in TShock.Players)
{ {
player.User = null; player.Account = null;
} }
} }
@ -447,9 +447,9 @@ namespace TShockAPI
private void OnPlayerLogin(PlayerPostLoginEventArgs args) private void OnPlayerLogin(PlayerPostLoginEventArgs args)
{ {
List<String> KnownIps = new List<string>(); List<String> KnownIps = new List<string>();
if (!string.IsNullOrWhiteSpace(args.Player.User.KnownIps)) if (!string.IsNullOrWhiteSpace(args.Player.Account.KnownIps))
{ {
KnownIps = JsonConvert.DeserializeObject<List<String>>(args.Player.User.KnownIps); KnownIps = JsonConvert.DeserializeObject<List<String>>(args.Player.Account.KnownIps);
} }
if (KnownIps.Count == 0) if (KnownIps.Count == 0)
@ -470,16 +470,16 @@ namespace TShockAPI
} }
} }
args.Player.User.KnownIps = JsonConvert.SerializeObject(KnownIps, Formatting.Indented); args.Player.Account.KnownIps = JsonConvert.SerializeObject(KnownIps, Formatting.Indented);
Users.UpdateLogin(args.Player.User); UserAccounts.UpdateLogin(args.Player.Account);
Ban potentialBan = Bans.GetBanByAccountName(args.Player.User.Name); Ban potentialBan = Bans.GetBanByAccountName(args.Player.Account.Name);
if (potentialBan != null) if (potentialBan != null)
{ {
// A user just signed in successfully despite being banned by account name. // 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. // 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); potentialBan.Reason, false, potentialBan.BanningUser, potentialBan.Expiration);
// And then get rid of them. // And then get rid of them.
@ -507,7 +507,7 @@ namespace TShockAPI
/// <param name="args">args - The AccountCreateEventArgs object.</param> /// <param name="args">args - The AccountCreateEventArgs object.</param>
private void OnAccountCreate(Hooks.AccountCreateEventArgs args) private void OnAccountCreate(Hooks.AccountCreateEventArgs args)
{ {
CharacterDB.SeedInitialData(Users.GetUser(args.User)); CharacterDB.SeedInitialData(UserAccounts.GetUserAccount(args.User));
} }
/// <summary>OnPlayerPreLogin - Internal hook fired when on player pre login.</summary> /// <summary>OnPlayerPreLogin - Internal hook fired when on player pre login.</summary>
@ -535,7 +535,7 @@ namespace TShockAPI
} }
if (player.IsLoggedIn) if (player.IsLoggedIn)
{ {
var ips = JsonConvert.DeserializeObject<List<string>>(player.User.KnownIps); var ips = JsonConvert.DeserializeObject<List<string>>(player.Account.KnownIps);
if (ips.Contains(ip)) if (ips.Contains(ip))
{ {
Netplay.Clients[player.Index].PendingTermination = true; 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 // 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; AuthToken = 0;

View file

@ -90,7 +90,7 @@ namespace TShockAPI
{ {
if (includeIDs) 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 else
{ {