Class: GcalMapper::Authentification::Oauth2

Inherits:
Base
  • Object
show all
Defined in:
lib/gcal_mapper/authentification/oauth2.rb

Overview

make the authentification with Oauth2 and request data from google calendar.

Instance Method Summary collapse

Constructor Details

#initialize(yaml_file) ⇒ Oauth2

intialize client info needed for connection to Oauth2.

Parameters:

  • yaml_file (String)

    path to the yaml file which contains acess token, …



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/gcal_mapper/authentification/oauth2.rb', line 14

def initialize (yaml_file)
  begin
    oauth_yaml = YAML.load_file(yaml_file)
    @client_id = oauth_yaml["client_id"]
    @client_secret = oauth_yaml["client_secret"]
    @scope = oauth_yaml["scope"]
    @refresh_token = oauth_yaml["refresh_token"]
    @access_token = oauth_yaml["access_token"]
    @validity = Time.now.getutc.to_i
  rescue
    raise GcalMapper::AuthFileError
  end
end

Instance Method Details

#access_tokenString

give the acess token for th application and refresh if it is outdated

Returns:

  • (String)

    access token



31
32
33
34
35
36
37
# File 'lib/gcal_mapper/authentification/oauth2.rb', line 31

def access_token
  if (Time.now.getutc.to_i - @validity) > 3600
    refresh_token
  end

  @access_token
end

#refresh_tokenString

refresh the token by using refresh token

Returns:

  • (String)

    access token



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/gcal_mapper/authentification/oauth2.rb', line 42

def refresh_token
  data = {
    'client_id' => @client_id,
    'client_secret' => @client_secret,
    'refresh_token' => @refresh_token,
    'grant_type' => 'refresh_token'
  }
  options = {
    :method => :post,
    :headers => {'Content-Type' => 'application/x-www-form-urlencoded'},
    :parameters => data
  }
  req = GcalMapper::RestRequest.new(Authentification::REQUEST_URL, options)
  begin
    response = req.execute
  rescue
    raise GcalMapper::AuthentificationError
  end
  @validity = Time.now.getutc.to_i

  @access_token = response['access_token']
  response
end