Older/Database/Session.cpp

80 lines
2.4 KiB
C++
Raw Normal View History

2024-10-31 19:40:29 +08:00
#include "Session.h"
2024-11-27 19:23:06 +08:00
#include "BoostLog.h"
2024-10-31 19:40:29 +08:00
#include <Wt/Auth/Dbo/UserDatabase.h>
2024-11-27 00:08:24 +08:00
#include <Wt/Dbo/WtJsonSqlTraits.h>
2024-11-27 19:23:06 +08:00
#include <Wt/Dbo/backend/Sqlite3.h>
#include <Wt/Dbo/FixedSqlConnectionPool.h>
#include <Wt/Dbo/SqlConnectionPool.h>
namespace Database {
std::unique_ptr<Wt::Dbo::SqlConnectionPool> sqlConnectionPool;
bool initialize(const std::string &path) {
try {
auto connection = std::make_unique<Wt::Dbo::backend::Sqlite3>(path);
connection->setProperty("show-queries", "true");
connection->setDateTimeStorage(Wt::Dbo::SqlDateTimeType::DateTime,
Wt::Dbo::backend::DateTimeStorage::PseudoISO8601AsText);
sqlConnectionPool = std::make_unique<Wt::Dbo::FixedSqlConnectionPool>(std::move(connection), 10);
session()->createTables();
} catch (const Wt::Dbo::Exception &e) {
LOG(error) << e.code() << ": " << e.what();
}
return true;
}
std::unique_ptr<Session> session() {
if (!sqlConnectionPool) return {};
return std::make_unique<Session>(*sqlConnectionPool);
}
} // namespace Database
2024-10-31 19:40:29 +08:00
2024-11-26 22:58:54 +08:00
Session::Session(Wt::Dbo::SqlConnectionPool &connectionPool) {
setConnectionPool(connectionPool);
mapClass<Task>("task");
mapClass<HomeBox::Item>("homebox_item");
2024-11-27 00:08:24 +08:00
mapClass<VisitorRecord>("visitor_record");
2024-10-31 19:40:29 +08:00
mapClass<User>("user");
mapClass<AuthInfo>("auth_info");
mapClass<AuthInfo::AuthIdentityType>("auth_identity");
mapClass<AuthInfo::AuthTokenType>("auth_token");
m_users = std::make_unique<UserDatabase>(*this);
}
Session::~Session() {
}
2024-11-14 23:06:22 +08:00
Wt::Dbo::ptr<User> Session::user() const {
if (m_login.loggedIn()) {
Wt::Dbo::ptr<AuthInfo> authInfo = m_users->find(m_login.user());
return authInfo->user();
} else
return Wt::Dbo::ptr<User>();
}
2024-10-31 19:40:29 +08:00
Wt::Auth::AbstractUserDatabase &Session::users() {
return *m_users;
}
Wt::Auth::Login &Session::login() {
return m_login;
2024-11-26 22:58:54 +08:00
}
2024-11-27 00:08:24 +08:00
namespace Wt {
namespace Dbo {
template <>
void JsonSerializer::act(FieldRef<std::chrono::system_clock::time_point> field) {
using namespace std::chrono;
writeFieldName(field.name());
fastJsStringLiteral(std::to_string(duration_cast<seconds>(field.value().time_since_epoch()).count()));
}
} // namespace Dbo
} // namespace Wt
2024-11-26 22:58:54 +08:00
DBO_INSTANTIATE_TEMPLATES(User)
DBO_INSTANTIATE_TEMPLATES(Task)
2024-11-27 00:08:24 +08:00
DBO_INSTANTIATE_TEMPLATES(HomeBox::Item)
DBO_INSTANTIATE_TEMPLATES(VisitorRecord)