Skip to content
Repos

DevPlaceApp

C++ 2.3 KB72 lines Opens in site

Directory Raw Download

#include "store/SessionStore.hpp"

#include "core/AppPaths.hpp"
#include "core/Json.hpp"
#include "core/Log.hpp"
#include "spec/StoreKeys.hpp"
#include "store/AtomicFile.hpp"

namespace dp {

using spec::SessionKeys;

SessionStore& SessionStore::instance() {
  static SessionStore store(AppPaths::prefDirectory());
  return store;
}

SessionStore::SessionStore(std::string directory) { rebind(std::move(directory)); }

void SessionStore::rebind(std::string directory) {
  path_.clear();
  if (!directory.empty()) {
    if (directory.back() != '/') directory.push_back('/');
    path_ = directory + SessionKeys::kFileName;  // empty directory: memory only, nothing is persisted
  }
  reload();
}

void SessionStore::reload() {
  email_.reset();
  password_.reset();
  if (path_.empty()) return;
  auto text = AtomicFile::read(path_, SessionKeys::kMaxFileBytes);
  if (!text) return;
  Json j = Json::parse(*text, nullptr, false);
  if (!j.is_object()) {
    Log::error("session file is not a JSON object, ignored");
    return;
  }
  email_ = JsonRead::opt<std::string>(j, SessionKeys::kEmail);
  password_ = JsonRead::opt<std::string>(j, SessionKeys::kPassword);
}

bool SessionStore::save() {
  if (path_.empty()) return true;
  Json j = Json::object();
  if (email_) j[SessionKeys::kEmail] = *email_;
  if (password_) j[SessionKeys::kPassword] = *password_;
  return AtomicFile::write(path_, j.dump(-1, ' ', false, Json::error_handler_t::replace), SessionKeys::kFileMode,
                           SessionKeys::kMaxFileBytes);
}

bool SessionStore::set(std::optional<std::string>& slot, const std::optional<std::string>& value, const char* key) {
  if (value && value->size() > SessionKeys::kMaxValueBytes) {
    Log::error(std::string("Error: failed to store ") + key + " in session file (too long)");
    return false;
  }
  const std::optional<std::string> previous = slot;
  slot = value;
  if (!save()) {
    slot = previous;
    Log::error(std::string("Error: failed to store ") + key + " in session file");
    return false;
  }
  notifyChanged();
  return true;
}

bool SessionStore::setEmail(const std::optional<std::string>& value) { return set(email_, value, SessionKeys::kEmail); }
bool SessionStore::setPassword(const std::optional<std::string>& value) { return set(password_, value, SessionKeys::kPassword); }

}  // namespace dp
21.8ms