Class: Tickrb::Auth

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client_id: nil, client_secret: nil, redirect_uri: nil, token_store: nil) ⇒ Auth

Returns a new instance of Auth.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/tickrb/auth.rb', line 27

def initialize(client_id: nil, client_secret: nil, redirect_uri: nil, token_store: nil)
  @client_id = if client_id.nil? || client_id.empty?
    ENV["CLIENT_ID"]
  else
    client_id
  end

  @client_secret = if client_secret.nil? || client_secret.empty?
    ENV["CLIENT_SECRET"]
  else
    client_secret
  end

  @redirect_uri = if redirect_uri.nil? || redirect_uri.empty?
    ENV["REDIRECT_URI"]
  else
    redirect_uri
  end

  @token_store = token_store || TokenStore
end

Class Method Details

.run(client_id: nil, client_secret: nil, redirect_uri: nil) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/tickrb/auth.rb', line 17

def run(client_id: nil, client_secret: nil, redirect_uri: nil)
  auth_client = new(
    client_id: client_id,
    client_secret: client_secret,
    redirect_uri: redirect_uri
  )
  auth_client.run_oauth_flow
end

Instance Method Details

#run_oauth_flowObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/tickrb/auth.rb', line 49

def run_oauth_flow
  # Start local server to receive callback
  server = WEBrick::HTTPServer.new(Port: 8080, Logger: WEBrick::Log.new(File::NULL))

  # TODO: Generate a random state parameter for CSRF protection
  auth_params = {
    client_id: client_id,
    scope: scope,
    redirect_uri: redirect_uri,
    response_type: "code"
  }

  auth_url_params = build_auth_url_params(auth_params)
  auth_url = AUTH_URL + auth_url_params

  system("open \"#{auth_url}\"") # macOS, use 'xdg-open' on Linux

  # Handle callback
  server.mount_proc "/callback", ->(req, res) do
    code = req.query["code"]
    # Exchange code for token
    token_info = exchange_code_for_token(code)
    token_store.store_token(token_info)

    res.body = "Authentication successful! You can close this window."
    server.shutdown
  end

  server.start
end