Archived
Private
Public Access
1
0
This repository has been archived on 2026-02-04. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
ProjectBackup/C#/WebApplication/Repositorys/SessionRepository.cs
2022-09-04 12:45:01 +02:00

54 lines
2.0 KiB
C#

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;
}
}
}