Class: Tempest::SessionStore

Inherits:
Object
  • Object
show all
Defined in:
lib/tempest/session_store.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path:) ⇒ SessionStore

Returns a new instance of SessionStore.



18
19
20
# File 'lib/tempest/session_store.rb', line 18

def initialize(path:)
  @path = path
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



22
23
24
# File 'lib/tempest/session_store.rb', line 22

def path
  @path
end

Class Method Details

.default_path(env = ENV) ⇒ Object



9
10
11
12
13
14
15
16
# File 'lib/tempest/session_store.rb', line 9

def self.default_path(env = ENV)
  explicit = env["TEMPEST_SESSION_PATH"]
  return explicit if explicit && !explicit.empty?

  base = env["XDG_CONFIG_HOME"]
  base = File.join(env["HOME"].to_s, ".config") if base.nil? || base.empty?
  File.join(base, "tempest", "session.json")
end

Instance Method Details

#clearObject



62
63
64
# File 'lib/tempest/session_store.rb', line 62

def clear
  File.delete(@path) if File.exist?(@path)
end

#load(identifier: nil, pds_host: nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/tempest/session_store.rb', line 41

def load(identifier: nil, pds_host: nil)
  return nil unless File.exist?(@path)

  raw = File.read(@path)
  data = JSON.parse(raw)
  return nil unless data.is_a?(Hash)
  return nil if identifier && data["identifier"] != identifier
  return nil if pds_host && data["pds_host"] != pds_host

  Tempest::Session.new(
    access_jwt: data.fetch("access_jwt"),
    refresh_jwt: data.fetch("refresh_jwt"),
    did: data.fetch("did"),
    handle: data.fetch("handle"),
    pds_host: data.fetch("pds_host"),
    identifier: data["identifier"],
  )
rescue JSON::ParserError, KeyError
  nil
end

#save(session, identifier:) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/tempest/session_store.rb', line 24

def save(session, identifier:)
  payload = {
    "identifier" => identifier,
    "pds_host" => session.pds_host,
    "did" => session.did,
    "handle" => session.handle,
    "access_jwt" => session.access_jwt,
    "refresh_jwt" => session.refresh_jwt,
  }

  FileUtils.mkdir_p(File.dirname(@path))
  File.open(@path, File::WRONLY | File::CREAT | File::TRUNC, 0o600) do |io|
    io.write(JSON.generate(payload))
  end
  File.chmod(0o600, @path)
end