Class: Tinylinks::Auth

Inherits:
Object
  • Object
show all
Defined in:
lib/tinylinks/auth.rb

Constant Summary collapse

CREDENTIALS_DIR =
File.join(Dir.home, ".config", "tinylinks")
CREDENTIALS_FILE =
File.join(CREDENTIALS_DIR, "credentials.json")

Instance Method Summary collapse

Constructor Details

#initialize(client: Client.new) ⇒ Auth

Returns a new instance of Auth.



12
13
14
# File 'lib/tinylinks/auth.rb', line 12

def initialize(client: Client.new)
  @client = client
end

Instance Method Details

#logged_in?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/tinylinks/auth.rb', line 41

def logged_in?
  !token.nil?
end

#login {|:open_browser, grant["verification_url"]| ... } ⇒ Object

Yields:

  • (:open_browser, grant["verification_url"])


16
17
18
19
20
21
# File 'lib/tinylinks/auth.rb', line 16

def 
  grant = @client.post("/device_authorizations")
  yield(:open_browser, grant["verification_url"]) if block_given?

  poll_for_token(grant["device_code"], grant["interval"], grant["expires_in"])
end

#logoutObject



45
46
47
# File 'lib/tinylinks/auth.rb', line 45

def logout
  File.delete(CREDENTIALS_FILE) if File.exist?(CREDENTIALS_FILE)
end

#save_token(token, expires_at) ⇒ Object



36
37
38
39
# File 'lib/tinylinks/auth.rb', line 36

def save_token(token, expires_at)
  FileUtils.mkdir_p(CREDENTIALS_DIR)
  File.write(CREDENTIALS_FILE, JSON.generate(token: token, expires_at: expires_at))
end

#tokenObject



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/tinylinks/auth.rb', line 23

def token
  return nil unless File.exist?(CREDENTIALS_FILE)

  data = JSON.parse(File.read(CREDENTIALS_FILE))
  expires_at = Time.parse(data["expires_at"]) if data["expires_at"]

  if expires_at && expires_at <= Time.now
    nil
  else
    data["token"]
  end
end