| #include "remote_credentials.h" |
| |
| #include <string> |
| |
| #include "absl/functional/any_invocable.h" |
| #include "absl/log/check.h" |
| #include "absl/log/log.h" |
| #include "absl/status/status.h" |
| #include "absl/strings/string_view.h" |
| #include "absl/synchronization/mutex.h" |
| |
| namespace milotic { |
| |
| absl::Status CredentialsFileManager::TryLogin( |
| absl::string_view file_path, absl::string_view network_endpoint, |
| LoginFunction& login_func) { |
| LOG(INFO) << "Loading credentials from " << file_path; |
| last_tried_credentials_ = reader_(file_path, network_endpoint); |
| if (!last_tried_credentials_.ok()) { |
| LOG(WARNING) << "Failed to read credentials from " << file_path << ": " |
| << last_tried_credentials_.status(); |
| return last_tried_credentials_.status(); |
| } |
| absl::Status status = |
| login_func(last_tried_credentials_); |
| if (status.ok()) { |
| LOG(INFO) << "Succeeded with credentials from " << file_path; |
| } else { |
| LOG(WARNING) << "Credentials from " << file_path |
| << " did not work: " << status; |
| } |
| return status; |
| } |
| |
| absl::Status CredentialsFileManager::RunLogin( |
| absl::string_view network_endpoint, LoginFunction login_func) { |
| absl::MutexLock lock(credentials_mutex_); |
| if (last_try_result_.ok()) { |
| if (!last_tried_credentials_.ok()) { |
| LOG(DFATAL) << "Last tried credentials are not ok"; |
| return absl::InternalError("Last tried credentials are not ok"); |
| } |
| absl::Status login_status = login_func(last_tried_credentials_); |
| if (login_status.ok()) { |
| return absl::OkStatus(); |
| } |
| LOG(WARNING) << "Previously working credentials failed: " << login_status; |
| } else if (!private_cache_path_.empty()) { |
| last_try_result_ = |
| TryLogin(private_cache_path_, network_endpoint, login_func) |
| ; |
| if (last_try_result_.ok()) { |
| // Already in cache file |
| return absl::OkStatus(); |
| } |
| } |
| absl::string_view last_creds_file; |
| for (const auto& path : source_files_) { |
| last_try_result_ = |
| TryLogin(path, network_endpoint, login_func); |
| if (last_try_result_.ok()) { |
| last_creds_file = path; |
| break; |
| } |
| } |
| |
| // If no credentials could be loaded, make sure the login function is called |
| // once with the last load error. |
| if (!last_tried_credentials_.ok()) { |
| return login_func(last_tried_credentials_); |
| } |
| |
| if (last_try_result_.ok() && !private_cache_path_.empty()) { |
| absl::Status write_cache_status = writer_( |
| private_cache_path_, last_creds_file, *last_tried_credentials_, ""); |
| if (!write_cache_status.ok()) { |
| LOG(ERROR) << "Failed to write credentials to cache: " |
| << write_cache_status; |
| } |
| return absl::OkStatus(); |
| } |
| return last_try_result_; |
| } |
| |
| } // namespace milotic |