Module: GoogleCalendarMcp::Auth

Defined in:
lib/google_calendar_mcp/auth.rb

Constant Summary collapse

SCOPE =
Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY

Class Method Summary collapse

Class Method Details

.authorizeObject



22
23
24
25
26
27
28
29
30
31
# File 'lib/google_calendar_mcp/auth.rb', line 22

def authorize
  credentials_json = ENV.fetch("GOOGLE_CREDENTIALS_JSON", nil)
  token_yaml = ENV.fetch("GOOGLE_TOKEN_YAML", nil)

  if credentials_json && !credentials_json.empty? && token_yaml && !token_yaml.empty?
    authorize_from_env(credentials_json, token_yaml)
  else
    authorize_from_file
  end
end

.authorize_from_env(credentials_json, token_yaml) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/google_calendar_mcp/auth.rb', line 33

def authorize_from_env(credentials_json, token_yaml)
  parsed = JSON.parse(credentials_json)
  installed = parsed.fetch("installed") { parsed.fetch("web") }

  token_data = YAML.safe_load(token_yaml)
  token_json = JSON.parse(token_data.fetch("default") { token_data.values.first })

  Google::Auth::UserRefreshCredentials.new(
    client_id: installed.fetch("client_id"),
    client_secret: installed.fetch("client_secret"),
    scope: SCOPE,
    refresh_token: token_json.fetch("refresh_token")
  )
end

.authorize_from_fileObject



48
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
# File 'lib/google_calendar_mcp/auth.rb', line 48

def authorize_from_file
  credentials_path = ENV.fetch("GOOGLE_CREDENTIALS_PATH", "credentials.json")
  token_path = ENV.fetch("GOOGLE_TOKEN_PATH", "token.yaml")

  client_id = Google::Auth::ClientId.from_file(credentials_path)
  token_store = Google::Auth::Stores::FileTokenStore.new(file: token_path)
  authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)

  user_id = "default"
  credentials = authorizer.get_credentials(user_id)

  if credentials.nil?
    url = authorizer.get_authorization_url(base_url: "http://localhost:8080")
    $stderr.puts "Open this URL in your browser to authorize:"
    $stderr.puts url
    $stderr.puts "Enter the authorization code:"
    code = $stdin.gets&.strip
    credentials = authorizer.get_and_store_credentials_from_code(
      user_id: user_id,
      code: code,
      base_url: "http://localhost:8080"
    )
  end

  credentials
end

.build_serviceObject



15
16
17
18
19
20
# File 'lib/google_calendar_mcp/auth.rb', line 15

def build_service
  service = Google::Apis::CalendarV3::CalendarService.new
  service.client_options.application_name = "Google Calendar MCP Server"
  service.authorization = authorize
  service
end