Older/WebApplication/Restful.cpp

61 lines
2.5 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"
2025-01-03 22:17:45 +08:00
#include "model/AuthModel.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>
2025-01-03 22:17:45 +08:00
#include <format>
2024-11-01 19:05:20 +08:00
DBO_INSTANTIATE_TEMPLATES(MyMessage)
2024-11-14 21:53:18 +08:00
void AuthenticationResource::handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) {
2025-01-03 22:17:45 +08:00
auto tag = request.urlParam("tag");
LOG(info) << "path: " << request.path() << ", tag: " << tag;
response.setMimeType("application/json");
MyMessage message;
2024-12-26 23:10:41 +08:00
auto app = Amass::Singleton<WebToolkit::Server>::instance();
auto &service = app->authService();
2025-01-03 22:17:45 +08:00
if (tag == "verify") {
auto session = Database::session();
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-12-26 23:10:41 +08:00
}
}
2025-01-03 22:17:45 +08:00
if (user.isValid()) {
message.user = user.identity(Wt::Auth::Identity::LoginName).toUTF8();
}
LOG(info) << "state: " << (int)state << " " << message.user;
message.message = "Hello, World!";
message.status = state == Wt::Auth::AuthTokenState::Valid ? 0 : 404;
} else { // logout
response.addHeader("Set-Cookie", std::format("{}=; path={}; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT",
service.authTokenCookieName(), AuthModel::CookiePath));
2024-12-26 23:10:41 +08:00
}
2024-11-01 19:05:20 +08:00
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!";
}
2024-11-26 22:58:54 +08:00
AuthenticationResource::AuthenticationResource() {
2025-01-03 22:17:45 +08:00
}