SNode.C
Loading...
Searching...
No Matches
ResourceServer.cpp
Go to the documentation of this file.
1/*
2 * SNode.C - A Slim Toolkit for Network Communication
3 * Copyright (C) Volker Christian <me@vchrist.at>
4 * 2020, 2021, 2022, 2023, 2024, 2025
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20/*
21 * MIT License
22 *
23 * Permission is hereby granted, free of charge, to any person obtaining a copy
24 * of this software and associated documentation files (the "Software"), to deal
25 * in the Software without restriction, including without limitation the rights
26 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27 * copies of the Software, and to permit persons to whom the Software is
28 * furnished to do so, subject to the following conditions:
29 *
30 * The above copyright notice and this permission notice shall be included in
31 * all copies or substantial portions of the Software.
32 *
33 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 * THE SOFTWARE.
40 */
41
42#include "express/legacy/in/WebApp.h"
43#include "express/middleware/JsonMiddleware.h"
44#include "log/Logger.h"
45#include "web/http/legacy/in/Client.h"
46
47#include <nlohmann/json.hpp>
48#include <string>
49
50// IWYU pragma: no_include <nlohmann/detail/json_ref.hpp>
51// IWYU pragma: no_include <nlohmann/json_fwd.hpp>
52
53int main(int argc, char* argv[]) {
54 express::WebApp::init(argc, argv);
55
56 const express::legacy::in::WebApp app("OAuth2ResourceServer");
57
58 const std::string authorizationServerUri{"http://localhost:8082"};
59
60 app.use(express::middleware::JsonMiddleware());
61
62 app.get("/access", [authorizationServerUri] APPLICATION(req, res) {
63 res->set("Access-Control-Allow-Origin", "*");
64 const std::string queryAccessToken{req->query("access_token")};
65 const std::string queryClientId{req->query("client_id")};
66 if (queryAccessToken.empty() || queryClientId.empty()) {
67 VLOG(1) << "Missing access_token or client_id in body";
68 res->sendStatus(401);
69 return;
70 }
71
72 const web::http::legacy::in::Client legacyClient(
73 [](web::http::legacy::in::Client::SocketConnection* socketConnection) {
74 VLOG(1) << "OnConnect";
75
76 VLOG(1) << "\tServer: " + socketConnection->getRemoteAddress().toString();
77 VLOG(1) << "\tClient: " + socketConnection->getLocalAddress().toString();
78 },
79 []([[maybe_unused]] web::http::legacy::in::Client::SocketConnection* socketConnection) {
80 VLOG(1) << "OnConnected";
81 },
82 [](web::http::legacy::in::Client::SocketConnection* socketConnection) {
83 VLOG(1) << "OnDisconnect";
84
85 VLOG(1) << "\tServer: " + socketConnection->getRemoteAddress().toString();
86 VLOG(1) << "\tClient: " + socketConnection->getLocalAddress().toString();
87 },
88 [queryAccessToken, queryClientId, res](const std::shared_ptr<web::http::client::Request>& request) {
89 VLOG(1) << "OnRequestBegin";
90 request->url = "/oauth2/token/validate?client_id=" + queryClientId;
91 request->method = "POST";
92 VLOG(1) << "ClientId: " << queryClientId;
93 VLOG(1) << "AccessToken: " << queryAccessToken;
94 const nlohmann::json requestJson = {{"access_token", queryAccessToken}, {"client_id", queryClientId}};
95 const std::string requestJsonString{requestJson.dump(4)};
96 request->send(requestJsonString,
97 [res]([[maybe_unused]] const std::shared_ptr<web::http::client::Request>& request,
98 const std::shared_ptr<web::http::client::Response>& response) {
99 VLOG(1) << "OnResponse";
100 VLOG(1) << "Response: " << std::string(response->body.begin(), response->body.end());
101 if (std::stoi(response->statusCode) != 200) {
102 const nlohmann::json errorJson = {{"error", "Invalid access token"}};
103 res->status(401).send(errorJson.dump(4));
104 } else {
105 const nlohmann::json successJson = {{"content", "🦆"}};
106 res->status(200).send(successJson.dump(4));
107 }
108 });
109 },
110 []([[maybe_unused]] const std::shared_ptr<web::http::client::Request>& req) {
111 LOG(INFO) << " -- OnRequestEnd";
112 });
113
114 legacyClient.connect(
115 "localhost", 8082, [](const web::http::legacy::in::Client::SocketAddress& socketAddress, const core::socket::State& state) {
116 switch (state) {
117 case core::socket::State::OK:
118 VLOG(1) << "OAuth2ResourceServer: connected to '" << socketAddress.toString() << "'";
119 break;
120 case core::socket::State::DISABLED:
121 VLOG(1) << "OAuth2ResourceServer: disabled";
122 break;
123 case core::socket::State::ERROR:
124 VLOG(1) << "OAuth2ResourceServer: error occurred";
125 break;
126 case core::socket::State::FATAL:
127 VLOG(1) << "OAuth2ResourceServer: fatal error occurred";
128 break;
129 }
130 });
131 });
132
133 app.listen(8083, [](const express::legacy::in::WebApp::SocketAddress& socketAddress, const core::socket::State& state) {
134 switch (state) {
135 case core::socket::State::OK:
136 VLOG(1) << "app: listening on '" << socketAddress.toString() << "'";
137 break;
138 case core::socket::State::DISABLED:
139 VLOG(1) << "app: disabled";
140 break;
141 case core::socket::State::ERROR:
142 VLOG(1) << "app: error occurred";
143 break;
144 case core::socket::State::FATAL:
145 VLOG(1) << "app: fatal error occurred";
146 break;
147 }
148 });
149 return express::WebApp::start();
150}
#define APPLICATION(req, res)
Definition Router.h:68
static constexpr int DISABLED
Definition State.h:56
static constexpr int ERROR
Definition State.h:57
static constexpr int FATAL
Definition State.h:58
static constexpr int OK
Definition State.h:55
const SocketAddress & getRemoteAddress() const final
const SocketAddress & getLocalAddress() const final
const std::string & query(const std::string &key) const
Definition Request.cpp:107
Response & set(const std::string &field, const std::string &value, bool overwrite=true)
Definition Response.cpp:125
void send(const std::string &chunk)
Definition Response.cpp:165
Response & status(int status)
Definition Response.cpp:113
void sendStatus(int state)
Definition Response.cpp:91
WebAppT(const std::string &name)
Definition WebAppT.h:76
static void init(int argc, char *argv[])
Definition WebApp.cpp:56
static int start(const utils::Timeval &timeOut={LONG_MAX, 0})
Definition WebApp.cpp:60
std::string toString(bool expanded=true) const override
void connect(const std::string &ipOrHostname, uint16_t port, const std::function< void(const SocketAddress &, core::socket::State)> &onStatus) const
void listen(uint16_t port, const std::function< void(const SocketAddress &, core::socket::State)> &onStatus) const
Client(const std::function< void(SocketConnection *)> &onConnect, const std::function< void(SocketConnection *)> &onConnected, const std::function< void(SocketConnection *)> &onDisconnect, std::function< void(const std::shared_ptr< Request > &)> &&onRequestBegin, std::function< void(const std::shared_ptr< Request > &)> &&onRequestEnd)
Definition Client.h:93
bool send(const std::string &chunk, const std::function< void(const std::shared_ptr< Request > &, const std::shared_ptr< Response > &)> &onResponseReceived, const std::function< void(const std::shared_ptr< Request > &, const std::string &)> &onResponseParseError=responseParseError)
Definition Request.cpp:291
std::vector< char > body
Definition Response.h:86
int main(int argc, char *argv[])
Definition Client.h:52