Older/WebApplication/Restful.cpp

66 lines
2.2 KiB
C++
Raw Normal View History

2024-11-01 19:05:20 +08:00
#include "Restful.h"
2024-12-26 23:10:41 +08:00
#include "Application.h"
2024-11-26 22:58:54 +08:00
#include "Database/Session.h"
2024-12-26 23:10:41 +08:00
#include <Wt/Auth/AuthService.h>
#include <Wt/Auth/Identity.h>
2024-11-01 19:05:20 +08:00
#include <Wt/Dbo/Impl.h>
#include <Wt/Dbo/Json.h>
#include <Wt/Dbo/backend/Sqlite3.h>
#include <Wt/Http/Response.h>
2024-12-26 23:10:41 +08:00
#include <boost/scope/scope_exit.hpp>
2024-11-01 19:05:20 +08:00
DBO_INSTANTIATE_TEMPLATES(MyMessage)
DbStruct *m_dbStruct;
2024-11-14 21:53:18 +08:00
void AuthenticationResource::handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) {
2024-12-26 23:10:41 +08:00
auto app = Amass::Singleton<WebToolkit::Server>::instance();
2024-11-27 19:23:06 +08:00
auto session = Database::session();
2024-12-26 23:10:41 +08:00
auto &service = app->authService();
2024-11-01 19:05:20 +08:00
2024-12-26 23:10:41 +08:00
auto enabled = service.authTokenUpdateEnabled();
boost::scope::scope_exit raii([&enabled, &service] { service.setAuthTokenUpdateEnabled(enabled); });
service.setAuthTokenUpdateEnabled(false);
Wt::Auth::AuthTokenState state;
Wt::Auth::User user;
if (service.authTokensEnabled()) {
const std::string *token = request.getCookieValue(service.authTokenCookieName());
if (token != nullptr) {
Wt::Auth::AuthTokenResult result = service.processAuthToken(*token, session->users());
state = result.state();
if (state == Wt::Auth::AuthTokenState::Valid) {
user = result.user();
}
}
}
2024-11-01 19:05:20 +08:00
MyMessage message;
2024-12-26 23:10:41 +08:00
if (user.isValid()) {
message.user = user.identity(Wt::Auth::Identity::LoginName).toUTF8();
}
LOG(info) << "state: " << (int)state << " " << message.user;
response.setMimeType("application/json");
response.addHeader("Server", "Wt");
2024-11-01 19:05:20 +08:00
message.message = "Hello, World!";
Wt::Dbo::JsonSerializer writer(response.out());
writer.serialize(message);
}
void PlaintextResource::handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) {
response.setMimeType("text/plain");
response.addHeader("Server", "Wt");
response.out() << "Hello, World!";
}
int DbStruct::rand() {
return distribution(rng);
}
2024-11-26 22:58:54 +08:00
AuthenticationResource::AuthenticationResource() {
2024-11-14 23:06:22 +08:00
}
2024-11-01 19:05:20 +08:00
DbStruct::DbStruct(const std::string &db) : rng(clock()), distribution(1, 10000) {
session.setConnection(std::make_unique<Wt::Dbo::backend::Sqlite3>(db));
session.mapClass<World>("world");
session.mapClass<Fortune>("fortune");
}