46{
47
48 std::shared_ptr<ThreadSafeQueueSPSC<OAuthResult>> queue = std::make_shared<ThreadSafeQueueSPSC<OAuthResult>>();
49
50
51 local_authorization_server.set_request_handler([
this, queue](
const std::string& url) -> std::shared_ptr<HttpServer::Response> {
52 if (boost::contains(url, "/callback")) {
55
56 const auto handle_auth_fail = [this, queue](const std::string& message) -> std::shared_ptr<HttpServer::ResponseRedirect> {
57 queue->push(OAuthResult{false, message});
58 return std::make_shared<HttpServer::ResponseRedirect>(this->
_data.params.auth_fail_redirect_url);
59 };
60
61 if (state !=
_data.params.state) {
62 BOOST_LOG_TRIVIAL(warning) <<
"The provided state was not correct. Got " << state <<
" and expected " <<
_data.params.state;
63 return handle_auth_fail(
_u8L(
"The provided state is not correct."));
64 }
65
66 if (code.empty()) {
68 if (error_code == "user_denied") {
69 BOOST_LOG_TRIVIAL(debug) << "User did not give the required permission when authorizing this application";
70 return handle_auth_fail(
_u8L(
"Please give the required permissions when authorizing this application."));
71 }
72
73 BOOST_LOG_TRIVIAL(warning) << "Unexpected error when logging in. Error_code: " << error_code << ", State: " << state;
74 return handle_auth_fail(
_u8L(
"Something unexpected happened when trying to log in, please try again."));
75 }
76
77
78 OAuthResult r;
79
81 http.timeout_connect(5)
82 .timeout_max(5)
83 .form_add(
"client_id",
_data.params.client_id)
84 .form_add(
"redirect_uri",
_data.params.callback_url)
85 .form_add("grant_type", "authorization_code")
86 .form_add("code", code)
87 .form_add(
"code_verifier",
_data.params.verification_code)
88 .form_add(
"scope",
_data.params.scope)
90 .on_error([&](std::string body, std::string error,
unsigned status) {
parse_token_response(body,
true, r); })
91 .perform_sync();
92
93 queue->push(r);
94 return std::make_shared<HttpServer::ResponseRedirect>(r.success ?
_data.params.auth_success_redirect_url :
95 _data.params.auth_fail_redirect_url);
96 } else {
97 queue->push(OAuthResult{false});
98 return std::make_shared<HttpServer::ResponseNotFound>();
99 }
100 });
101
102
104
105
106 bool received = false;
107 while (!ctl.was_canceled() && !received ) {
108 queue->consume_one(BlockingWait{1000}, [this, &received](const OAuthResult& result) {
109 *
_data.result = result;
110 received = true;
111 });
112 }
113
114
115 if (!received && ctl.was_canceled()) {
116 _data.result->error_message =
_u8L(
"User canceled.");
117 } else {
118
119 std::this_thread::sleep_for(std::chrono::milliseconds(1500));
120 }
121}
static void parse_token_response(const std::string &body, bool error, OAuthResult &result)
Definition OAuthJob.cpp:25
static Http post(std::string url)
Definition Http.cpp:891
std::string url_get_param(const std::string &url, const std::string &key)
Definition HttpServer.cpp:35
@ http
Definition IPrinterAgent.hpp:64