Document Utils.cs & UserManager.cs

Deprecated Utils.Random()
This commit is contained in:
Lucas Nicodemus 2015-04-19 20:37:38 -06:00
parent ce4585d151
commit 342921b3ed
2 changed files with 147 additions and 42 deletions

View file

@ -29,28 +29,33 @@ 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>
public class UserManager public class UserManager
{ {
/// <summary>database - The database object to use for connections.</summary>
private IDbConnection database; private IDbConnection database;
/// <summary>UserManager - Creates a UserManager object. During instantiation, this method will verify the table structure against the format below.</summary>
/// <param name="db">db - The database to connect to.</param>
/// <returns>A UserManager object.</returns>
public UserManager(IDbConnection db) public UserManager(IDbConnection db)
{ {
database = db; database = db;
var table = new SqlTable("Users", var table = new SqlTable("Users",
new SqlColumn("ID", MySqlDbType.Int32) {Primary = true, AutoIncrement = true}, new SqlColumn("ID", MySqlDbType.Int32) {Primary = true, AutoIncrement = true},
new SqlColumn("Username", MySqlDbType.VarChar, 32) {Unique = true}, new SqlColumn("Username", MySqlDbType.VarChar, 32) {Unique = true},
new SqlColumn("Password", MySqlDbType.VarChar, 128), new SqlColumn("Password", MySqlDbType.VarChar, 128),
new SqlColumn("UUID", MySqlDbType.VarChar, 128), new SqlColumn("UUID", MySqlDbType.VarChar, 128),
new SqlColumn("Usergroup", MySqlDbType.Text), new SqlColumn("Usergroup", MySqlDbType.Text),
new SqlColumn("Registered", MySqlDbType.Text), new SqlColumn("Registered", MySqlDbType.Text),
new SqlColumn("LastAccessed", MySqlDbType.Text), new SqlColumn("LastAccessed", MySqlDbType.Text),
new SqlColumn("KnownIPs", MySqlDbType.Text) new SqlColumn("KnownIPs", MySqlDbType.Text)
); );
var creator = new SqlTableCreator(db, var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator() ? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator()); : new MysqlQueryCreator());
creator.EnsureTableStructure(table); creator.EnsureTableStructure(table);
} }
@ -67,7 +72,7 @@ namespace TShockAPI.DB
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);", user.Name,
user.Password, user.UUID, user.Group, DateTime.UtcNow.ToString("s")); user.Password, user.UUID, user.Group, DateTime.UtcNow.ToString("s"));
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -173,19 +178,24 @@ namespace TShockAPI.DB
} }
} }
public void UpdateLogin(User user) /// <summary>UpdateLogin - Updates the last accessed time for a database user to the current time.</summary>
{ /// <param name="user">user - The user object to modify.</param>
try public void UpdateLogin(User user)
{ {
if (database.Query("UPDATE Users SET LastAccessed = @0, KnownIps = @1 WHERE Username = @2;", DateTime.UtcNow.ToString("s"), user.KnownIps, user.Name) == 0) try
throw new UserNotExistException(user.Name); {
} if (database.Query("UPDATE Users SET LastAccessed = @0, KnownIps = @1 WHERE Username = @2;", DateTime.UtcNow.ToString("s"), user.KnownIps, user.Name) == 0)
catch (Exception ex) throw new UserNotExistException(user.Name);
{ }
throw new UserManagerException("UpdateLogin SQL returned an error", ex); catch (Exception ex)
} {
} throw new UserManagerException("UpdateLogin SQL returned an error", ex);
}
}
/// <summary>GetUserID - Gets the database ID of a given user object from the database.</summary>
/// <param name="username">username - The username of the user to query for.</param>
/// <returns>int - The user's ID</returns>
public int GetUserID(string username) public int GetUserID(string username)
{ {
try try
@ -205,6 +215,9 @@ namespace TShockAPI.DB
return -1; return -1;
} }
/// <summary>GetUserByName - Gets a user object by name.</summary>
/// <param name="name">name - The user's name.</param>
/// <returns>User - The user object returned from the search.</returns>
public User GetUserByName(string name) public User GetUserByName(string name)
{ {
try try
@ -217,6 +230,9 @@ namespace TShockAPI.DB
} }
} }
/// <summary>GetUserByID - Gets a user object by their user ID.</summary>
/// <param name="id">id - The user's ID.</param>
/// <returns>User - The user object returned from the search.</returns>
public User GetUserByID(int id) public User GetUserByID(int id)
{ {
try try
@ -229,6 +245,9 @@ namespace TShockAPI.DB
} }
} }
/// <summary>GetUser - Gets a user object by a user object.</summary>
/// <param name="user">user - The user object to search by.</param>
/// <returns>User - The user object that is returned from the search.</returns>
public User GetUser(User user) public User GetUser(User user)
{ {
bool multiple = false; bool multiple = false;
@ -272,6 +291,8 @@ namespace TShockAPI.DB
throw new UserNotExistException(user.Name); throw new UserNotExistException(user.Name);
} }
/// <summary>GetUsers - Gets all users from the database.</summary>
/// <returns>List - The users from the database.</returns>
public List<User> GetUsers() public List<User> GetUsers()
{ {
try try
@ -293,31 +314,60 @@ namespace TShockAPI.DB
return null; return null;
} }
/// <summary>LoadUserFromResult - Fills out the fields of a User object with the results from a QueryResult object.</summary>
/// <param name="user">user - The user to add data to.</param>
/// <param name="result">result - The QueryResult object to add data from.</param>
/// <returns>User - The 'filled out' user object.</returns>
private User LoadUserFromResult(User user, QueryResult result) private User LoadUserFromResult(User user, QueryResult result)
{ {
user.ID = result.Get<int>("ID"); user.ID = result.Get<int>("ID");
user.Group = result.Get<string>("Usergroup"); user.Group = result.Get<string>("Usergroup");
user.Password = result.Get<string>("Password"); user.Password = result.Get<string>("Password");
user.UUID = result.Get<string>("UUID"); user.UUID = result.Get<string>("UUID");
user.Name = result.Get<string>("Username"); user.Name = result.Get<string>("Username");
user.Registered = result.Get<string>("Registered"); user.Registered = result.Get<string>("Registered");
user.LastAccessed = result.Get<string>("LastAccessed"); user.LastAccessed = result.Get<string>("LastAccessed");
user.KnownIps = result.Get<string>("KnownIps"); user.KnownIps = result.Get<string>("KnownIps");
return user; return user;
} }
} }
/// <summary>User - A database user.</summary>
public class User public class User
{ {
/// <summary>ID - The database ID of the user.</summary>
public int ID { get; set; } public int ID { get; set; }
/// <summary>Name - The user's name.</summary>
public string Name { get; set; } public string Name { get; set; }
/// <summary>Password - The hashed password for the user.</summary>
public string Password { get; internal set; } public string Password { get; internal set; }
/// <summary>UUID - The user's saved Univerally Unique Identifier token.</summary>
public string UUID { get; set; } public string UUID { get; set; }
/// <summary>Group - The group object that the user is a part of.</summary>
public string Group { get; set; } public string Group { get; set; }
/// <summary>Registered - The unix epoch corresponding to the registration date of the user.</summary>
public string Registered { get; set; } public string Registered { get; set; }
/// <summary>LastAccessed - The unix epoch corresponding to the last access date of the user.</summary>
public string LastAccessed { get; set; } public string LastAccessed { get; set; }
/// <summary>KnownIps - A JSON serialized list of known IP addresses for a user.</summary>
public string KnownIps { get; set; } public string KnownIps { get; set; }
/// <summary>User - Constructor for the user object, assuming you define everything yourself.</summary>
/// <param name="name">name - The user's name.</param>
/// <param name="pass">pass - The user's password hash.</param>
/// <param name="uuid">uuid - The user's UUID.</param>
/// <param name="group">group - The user's group name.</param>
/// <param name="registered">registered - The unix epoch for the registration date.</param>
/// <param name="last">last - The unix epoch for the last access date.</param>
/// <param name="known">known - The known IPs for the user, serialized as a JSON object</param>
/// <returns>A completed user object.</returns>
public User(string name, string pass, string uuid, string group, string registered, string last, string known) public User(string name, string pass, string uuid, string group, string registered, string last, string known)
{ {
Name = name; Name = name;
@ -329,6 +379,8 @@ namespace TShockAPI.DB
KnownIps = known; KnownIps = known;
} }
/// <summary>User - Default constructor for a user object; holds no data.</summary>
/// <returns>A user object.</returns>
public User() public User()
{ {
Name = ""; Name = "";
@ -517,41 +569,61 @@ namespace TShockAPI.DB
} }
/// <summary>UserManagerException - An exception generated by the user manager.</summary>
[Serializable] [Serializable]
public class UserManagerException : Exception public class UserManagerException : Exception
{ {
/// <summary>UserManagerException - Creates a new UserManagerException object.</summary>
/// <param name="message">message - The message for the object.</param>
/// <returns>public - a new UserManagerException object.</returns>
public UserManagerException(string message) public UserManagerException(string message)
: base(message) : base(message)
{ {
} }
/// <summary>UserManagerException - Creates a new UserManagerObject with an internal exception.</summary>
/// <param name="message">message - The message for the object.</param>
/// <param name="inner">inner - The inner exception for the object.</param>
/// <returns>public - a nwe UserManagerException with a defined inner exception.</returns>
public UserManagerException(string message, Exception inner) public UserManagerException(string message, Exception inner)
: base(message, inner) : base(message, inner)
{ {
} }
} }
/// <summary>UserExistsException - A UserExistsException object, used when a user already exists when attempting to create a new one.</summary>
[Serializable] [Serializable]
public class UserExistsException : UserManagerException public class UserExistsException : UserManagerException
{ {
/// <summary>UserExistsException - Creates a new UserExistsException object.</summary>
/// <param name="name">name - The name of the user that already exists.</param>
/// <returns>public - a UserExistsException object with the user's name passed in the message.</returns>
public UserExistsException(string name) public UserExistsException(string name)
: base("User '" + name + "' already exists") : base("User '" + name + "' already exists")
{ {
} }
} }
/// <summary>UserNotExistException - 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 UserNotExistException : UserManagerException
{ {
/// <summary>UserNotExistException - Creates a new UserNotExistException object, with the user's name in the message.</summary>
/// <param name="name">name - The user's name to be pasesd in the message.</param>
/// <returns>public - a new UserNotExistException object with a message containing the user's name that does not exist.</returns>
public UserNotExistException(string name) public UserNotExistException(string name)
: base("User '" + name + "' does not exist") : base("User '" + name + "' does not exist")
{ {
} }
} }
/// <summary>GroupNotExistsException - A GroupNotExistsException, used when a group does not exist.</summary>
[Serializable] [Serializable]
public class GroupNotExistsException : UserManagerException public class GroupNotExistsException : UserManagerException
{ {
/// <summary>GroupNotExistsException - Creates a new GroupNotExistsException object with the group's name in the message.</summary>
/// <param name="group">group - The group name.</param>
/// <returns>public - a new GroupNotExistsException with the group that does not exist's name in the message.</returns>
public GroupNotExistsException(string group) public GroupNotExistsException(string group)
: base("Group '" + group + "' does not exist") : base("Group '" + group + "' does not exist")
{ {

View file

@ -46,13 +46,19 @@ namespace TShockAPI
/// </summary> /// </summary>
private const int LastItemPrefix = 83; private const int LastItemPrefix = 83;
// Utils is a Singleton /// <summary>instance - an instance of the utils class</summary>
private static readonly Utils instance = new Utils(); private static readonly Utils instance = new Utils();
/// <summary>Utils - Creates a utilities object.</summary>
private Utils() {} private Utils() {}
/// <summary>Instance - An instance of the utils class.</summary>
/// <value>value - the Utils instance</value>
public static Utils Instance { get { return instance; } } public static Utils Instance { get { return instance; } }
/// <summary>Random - An instance of random for generating random data.</summary>
[Obsolete("Please create your own random objects; this will be removed in the next version of TShock.")]
public Random Random = new Random(); public Random Random = new Random();
//private static List<Group> groups = new List<Group>();
/// <summary> /// <summary>
/// Provides the real IP address from a RemoteEndPoint string that contains a port and an IP /// Provides the real IP address from a RemoteEndPoint string that contains a port and an IP
@ -130,13 +136,18 @@ namespace TShockAPI
} }
/// <summary> /// <summary>
/// Saves the map data /// Saves the map data by calling the SaveManager and instructing it to save the world.
/// </summary> /// </summary>
public void SaveWorld() public void SaveWorld()
{ {
SaveManager.Instance.SaveWorld(); SaveManager.Instance.SaveWorld();
} }
/// <summary>Broadcast - Broadcasts a message to all players on the server, as well as the server console, and the logs.</summary>
/// <param name="msg">msg - The message to send</param>
/// <param name="red">red - The amount of red (0-255) in the color for supported destinations.</param>
/// <param name="green">green - The amount of green (0-255) in the color for supported destinations.</param>
/// <param name="blue">blue - The amount of blue (0-255) in the color for the supported destinations.</param>
public void Broadcast(string msg, byte red, byte green, byte blue) public void Broadcast(string msg, byte red, byte green, byte blue)
{ {
TSPlayer.All.SendMessage(msg, red, green, blue); TSPlayer.All.SendMessage(msg, red, green, blue);
@ -144,19 +155,22 @@ namespace TShockAPI
TShock.Log.Info(string.Format("Broadcast: {0}", msg)); TShock.Log.Info(string.Format("Broadcast: {0}", msg));
} }
/// <summary>>Broadcast - Broadcasts a message to all players on the server, as well as the server console, and the logs.</summary>
/// <param name="msg">msg - The message to send</param>
/// <param name="color">color - The color object for supported destinations.</param>
public void Broadcast(string msg, Color color) public void Broadcast(string msg, Color color)
{ {
Broadcast(msg, color.R, color.G, color.B); Broadcast(msg, color.R, color.G, color.B);
} }
/// <summary> /// <summary>
/// Broadcasts a message from a player, not TShock /// Broadcasts a message from a Terraria playerplayer, not TShock
/// </summary> /// </summary>
/// <param name="ply">TSPlayer ply - the player that will send the packet</param> /// <param name="ply">ply - the Terraria player index that will send the packet</param>
/// <param name="msg">string msg - the message</param> /// <param name="msg">msg - The message to send</param>
/// <param name="red">r</param> /// <param name="red">red - The amount of red (0-255) in the color for supported destinations.</param>
/// <param name="green">g</param> /// <param name="green">green - The amount of green (0-255) in the color for supported destinations.</param>
/// <param name="blue">b</param> /// <param name="blue">blue - The amount of blue (0-255) in the color for the supported destinations.</param>
public void Broadcast(int ply, string msg, byte red, byte green, byte blue) public void Broadcast(int ply, string msg, byte red, byte green, byte blue)
{ {
TSPlayer.All.SendMessageFromPlayer(msg, red, green, blue, ply); TSPlayer.All.SendMessageFromPlayer(msg, red, green, blue, ply);
@ -183,9 +197,9 @@ namespace TShockAPI
} }
/// <summary> /// <summary>
/// The number of active players on the server. /// Gets the number of active players on the server.
/// </summary> /// </summary>
/// <returns>int playerCount</returns> /// <returns>The number of active players on the server.</returns>
public int ActivePlayers() public int ActivePlayers()
{ {
return Main.player.Where(p => null != p && p.active).Count(); return Main.player.Where(p => null != p && p.active).Count();
@ -195,7 +209,7 @@ namespace TShockAPI
/// Finds a TSPlayer based on name or ID /// Finds a TSPlayer based on name or ID
/// </summary> /// </summary>
/// <param name="plr">Player name or ID</param> /// <param name="plr">Player name or ID</param>
/// <returns></returns> /// <returns>A list of matching players</returns>
public List<TSPlayer> FindPlayer(string plr) public List<TSPlayer> FindPlayer(string plr)
{ {
var found = new List<TSPlayer>(); var found = new List<TSPlayer>();
@ -249,9 +263,9 @@ namespace TShockAPI
tileY = startTileY; tileY = startTileY;
break; break;
} }
Random r = new Random();
tileX = startTileX + Random.Next(tileXRange*-1, tileXRange); tileX = startTileX + r.Next(tileXRange*-1, tileXRange);
tileY = startTileY + Random.Next(tileYRange*-1, tileYRange); tileY = startTileY + r.Next(tileYRange*-1, tileYRange);
j++; j++;
} while (TilePlacementValid(tileX, tileY) && TileSolid(tileX, tileY)); } while (TilePlacementValid(tileX, tileY) && TileSolid(tileX, tileY));
} }
@ -611,6 +625,10 @@ namespace TShockAPI
return false; return false;
} }
/// <summary>HasBanExpired - Returns whether or not a ban has expired or not.</summary>
/// <param name="ban">ban - The ban object to check.</param>
/// <param name="byName">byName - Defines whether or not the ban should be checked by name.</param>
/// <returns>bool - True if the ban has expired.</returns>
public bool HasBanExpired(Ban ban, bool byName = false) public bool HasBanExpired(Ban ban, bool byName = false)
{ {
DateTime exp; DateTime exp;
@ -903,6 +921,9 @@ namespace TShockAPI
} }
} }
/// <summary>EncodeColor - Encodes a color as an int.</summary>
/// <param name="color">color - The color to encode</param>
/// <returns>int? - The encoded color</returns>
public int? EncodeColor(Color? color) public int? EncodeColor(Color? color)
{ {
if (color == null) if (color == null)
@ -911,6 +932,9 @@ namespace TShockAPI
return BitConverter.ToInt32(new[] { color.Value.R, color.Value.G, color.Value.B, color.Value.A }, 0); return BitConverter.ToInt32(new[] { color.Value.R, color.Value.G, color.Value.B, color.Value.A }, 0);
} }
/// <summary>DecodeColor - Decodes a color encoded by the EncodeColor function.</summary>
/// <param name="encodedColor">encodedColor - The encoded color</param>
/// <returns>Color? - The decoded color</returns>
public Color? DecodeColor(int? encodedColor) public Color? DecodeColor(int? encodedColor)
{ {
if (encodedColor == null) if (encodedColor == null)
@ -920,6 +944,9 @@ namespace TShockAPI
return new Color(data[0], data[1], data[2], data[3]); return new Color(data[0], data[1], data[2], data[3]);
} }
/// <summary>EncodeBitsByte - Encodes a BitsByte as a byte.</summary>
/// <param name="bitsByte">bitsByte - The BitsByte object</param>
/// <returns>byte? - The converted byte</returns>
public byte? EncodeBitsByte(BitsByte? bitsByte) public byte? EncodeBitsByte(BitsByte? bitsByte)
{ {
if (bitsByte == null) if (bitsByte == null)
@ -933,6 +960,9 @@ namespace TShockAPI
return result; return result;
} }
/// <summary>DecodeBitsByte - Decodes a bitsbyte from an int.</summary>
/// <param name="encodedBitsByte">encodedBitsByte - The encoded bitsbyte object.</param>
/// <returns>BitsByte? - The decoded bitsbyte object</returns>
public BitsByte? DecodeBitsByte(int? encodedBitsByte) public BitsByte? DecodeBitsByte(int? encodedBitsByte)
{ {
if (encodedBitsByte == null) if (encodedBitsByte == null)
@ -945,6 +975,9 @@ namespace TShockAPI
return result; return result;
} }
/// <summary>GetResponseNoException - Gets a web response without generating an exception.</summary>
/// <param name="req">req - The request to send.</param>
/// <returns>HttpWebResponse - The response object.</returns>
public HttpWebResponse GetResponseNoException(HttpWebRequest req) public HttpWebResponse GetResponseNoException(HttpWebRequest req)
{ {
try try