56 lines
1.7 KiB
C++
56 lines
1.7 KiB
C++
#include "google/credentials.h"
|
|||
|
|
|
||
|
|
#include <cstdlib>
|
||
|
|
#include <fstream>
|
||
|
|
#include <sstream>
|
||
|
|
|
||
|
|
#include "clients/body/json.h"
|
||
|
|
|
||
|
|
namespace molo::google {
|
||
|
|
|
||
|
|
std::shared_ptr<clients::Auth> Credentials::api_key(std::string key) {
|
||
|
|
return std::make_shared<clients::ApiKeyAuth>(std::move(key), "x-goog-api-key");
|
||
|
|
}
|
||
|
|
|
||
|
|
std::shared_ptr<clients::Auth> Credentials::bearer(std::string token) {
|
||
|
|
return std::make_shared<clients::BearerAuth>(std::move(token));
|
||
|
|
}
|
||
|
|
|
||
|
|
namespace {
|
||
|
|
constexpr std::size_t kMaxConfigBytes = 64 * 1024;
|
||
|
|
|
||
|
|
// String value of `name` in a flat JSON object file, or empty (missing,
|
||
|
|
// oversized, malformed, or not a string: all treated as "not set").
|
||
|
|
std::string from_json_file(const char* path, const char* name) {
|
||
|
|
std::ifstream in(path, std::ios::binary);
|
||
|
|
if (!in) return "";
|
||
|
|
std::ostringstream text;
|
||
|
|
text << in.rdbuf();
|
||
|
|
if (text.str().size() > kMaxConfigBytes) return "";
|
||
|
|
try {
|
||
|
|
clients::body::Json doc = clients::body::Json::parse(text.str());
|
||
|
|
const clients::body::Json* v = doc.is_object() ? doc.find(name) : nullptr;
|
||
|
|
return v && v->is_string() ? v->as_string() : "";
|
||
|
|
} catch (const std::exception&) {
|
||
|
|
return "";
|
||
|
|
}
|
||
|
|
}
|
||
|
|
} // namespace
|
||
|
|
|
||
|
|
// Order: process environment, then .env.json.local (git-ignored, for
|
||
|
|
// secrets), then .env.json, both in the working directory.
|
||
|
|
std::string Credentials::env(const char* name) {
|
||
|
|
if (const char* v = std::getenv(name); v && *v) return v;
|
||
|
|
std::string local = from_json_file(".env.json.local", name);
|
||
|
|
if (!local.empty()) return local;
|
||
|
|
return from_json_file(".env.json", name);
|
||
|
|
}
|
||
|
|
|
||
|
|
std::shared_ptr<clients::Auth> Credentials::from_env(const char* name) {
|
||
|
|
std::string key = env(name);
|
||
|
|
if (key.empty()) return nullptr;
|
||
|
|
return api_key(std::move(key));
|
||
|
|
}
|
||
|
|
|
||
|
|
} // namespace molo::google
|