Older/WebApplication/Restful.cpp
amass 25bc92a45d
All checks were successful
Deploy / Build (push) Successful in 5m44s
add auth verify api.
2025-01-03 22:17:45 +08:00

61 lines
2.5 KiB
C++

#include "Restful.h"
#include "Application.h"
#include "Database/Session.h"
#include "model/AuthModel.h"
#include <Wt/Auth/AuthService.h>
#include <Wt/Auth/Identity.h>
#include <Wt/Dbo/Impl.h>
#include <Wt/Dbo/Json.h>
#include <Wt/Dbo/backend/Sqlite3.h>
#include <Wt/Http/Response.h>
#include <boost/scope/scope_exit.hpp>
#include <format>
DBO_INSTANTIATE_TEMPLATES(MyMessage)
void AuthenticationResource::handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response) {
auto tag = request.urlParam("tag");
LOG(info) << "path: " << request.path() << ", tag: " << tag;
response.setMimeType("application/json");
MyMessage message;
auto app = Amass::Singleton<WebToolkit::Server>::instance();
auto &service = app->authService();
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();
}
}
}
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));
}
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!";
}
AuthenticationResource::AuthenticationResource() {
}