using System; using MySqlConnector; using WebApplication.Modules; using WebApplication.Repositorys.Interfaces; namespace WebApplication.Repositorys { public class SessionRepository : ISessionRepository { public SessionRepository() { MySQL.Insert("DELETE FROM Sessions"); } public Session CreateSession(string customer) { Session session = new Session {Guid = GetFreeId(), CustomerId = customer, CreationDate = DateTime.Now}; MySQL.Insert($"INSERT INTO Sessions VALUES (\"{session.Guid}\", \"{session.CustomerId}\", \"{session.CreationDate}\")"); return session; } public void RemoveSession(Session session) { MySQL.Insert($"DELETE FROM Sessions WHERE Guid = \"{session.Guid}\""); } public Session GetSession(string id) { MySqlDataReader reader = MySQL.GetData($"SELECT * FROM Sessions WHERE Guid = \"{id}\""); if (reader.Read()) { Session session = new Session {Guid = id}; session.CustomerId = reader.GetString("CustomerId"); session.CreationDate = DateTime.Parse(reader.GetString("CreationDate")); reader.Close(); return session; } reader.Close(); return null; } public bool ValidateSession(Session session, string customerToAccess) { if (session == null) return false; if (session.CustomerId != customerToAccess) return false; TimeSpan span = DateTime.Now - session.CreationDate; bool valid = span.Minutes <= 30; if (!valid) RemoveSession(session); return valid; } private string GetFreeId() { string guid = Guid.NewGuid().ToString(); while (true) { if (GetSession(guid) is not null) guid = Guid.NewGuid().ToString(); else break; } return guid; } } }