87 lines
2.4 KiB
C++
87 lines
2.4 KiB
C++
#pragma once
|
|
#include <map>
|
|
#include <set>
|
|
#include <mutex>
|
|
#include <chrono>
|
|
#include "Export.h"
|
|
#include "HTTPObjects.h"
|
|
|
|
namespace Json
|
|
{
|
|
class Value;
|
|
}
|
|
|
|
class UNSWSC_DLL_EXPORT SessionManager
|
|
{
|
|
public:
|
|
using systime = std::chrono::system_clock::time_point;
|
|
|
|
class UNSWSC_DLL_EXPORT Session
|
|
{
|
|
private:
|
|
int uid;
|
|
std::string cookie;
|
|
systime expiry_date;
|
|
|
|
static const std::chrono::hours max_age;
|
|
|
|
public:
|
|
Session();
|
|
Session(const Session& obj);
|
|
Session(const std::string& cookie); //构造仅用于比较的临时Session对象
|
|
Session(const Json::Value& json_obj); //从JSON反序列化
|
|
Session(int uid, const std::string& cookie);
|
|
|
|
public:
|
|
int GetUID() const;
|
|
bool Expired() const;
|
|
std::string GetCookie() const;
|
|
systime GetExpiryDate() const;
|
|
bool NeedExpiryDateRefresh() const; //使用超过一天且在活跃的cookie将被刷新。此处仅作时间判断
|
|
|
|
public:
|
|
void SetUID(int uid);
|
|
void RefreshExpiryDate();
|
|
void SetCookie(const std::string& cookie);
|
|
void SetExpiryDate(const systime& expiry_time);
|
|
|
|
public:
|
|
bool operator<(const Session& obj) const; //For std::map/std::set/...
|
|
operator Json::Value() const; //JSON序列化
|
|
|
|
static int GetMaxAgeSeconds();
|
|
};
|
|
|
|
private:
|
|
std::mutex pool_mutex;
|
|
//Key: Cookie Pair(oreo=xxxxx), Value: UID
|
|
std::map<std::string, int> cookie_storage;
|
|
//Key: UID, Value: Cookie Lists
|
|
std::map<int, std::set<Session>> reverse_cookie_storage;
|
|
|
|
const std::string prefix = "oreo=";
|
|
//const std::string cookie_template = prefix + "{}; HttpOnly; Path=/; SameSite=Lax; Max-Age={}";
|
|
const std::string cookie_template = prefix + "{}; HttpOnly; Secure; Path=/; SameSite=None; Max-Age={}";
|
|
|
|
public:
|
|
SessionManager();
|
|
SessionManager(const SessionManager& obj) = delete;
|
|
|
|
public:
|
|
static std::string Random();
|
|
static std::string ISO8601_TimeString();
|
|
|
|
public:
|
|
void AutoCleanCookiePool();
|
|
std::string GenerateCookieForUser(int uid, bool cookie_only = false);
|
|
std::string DeleteCookie(const std::string& cookie);
|
|
bool CheckRequestCookie(uns::RequestPtr request, int& uid);
|
|
std::string DeleteAllCookieForUser(int uid, const std::string& current_cookie);
|
|
|
|
bool HasDumpedCookie(const std::string& path);
|
|
bool LoadDumpedCookie(const std::string& path);
|
|
bool DumpAllValidCookies(const std::string& path);
|
|
};
|
|
|
|
extern UNSWSC_DLL_EXPORT SessionManager GlobalSessionManager;
|