1# Copyright 2014 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Module containing helpers for interacting with oauth2."""
6
7
8import json
9import urllib
10import urllib2
11
12
13DEFAULT_SCOPE = 'https://www.googleapis.com/auth/clouddevices'
14OAUTH_URL = 'https://accounts.google.com/o/oauth2'
15# Constant used in oauth2 protocol for device requests.
16REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
17
18
19def get_oauth2_auth_url(client_id, scope=DEFAULT_SCOPE):
20    auth_url = '%s/%s' % (OAUTH_URL, 'auth')
21    params = dict(client_id=client_id,
22                  scope=scope,
23                  response_type='code',
24                  redirect_uri=REDIRECT_URI)
25    return '%s?%s' % (auth_url, urllib.urlencode(params))
26
27
28def get_oauth2_user_token(client_id, client_secret, code):
29    """Returns the oauth2 token for a user given the auth code."""
30    token_url = '%s/%s' % (OAUTH_URL, 'token')
31    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
32    data = dict(code=code,
33                client_id=client_id,
34                client_secret=client_secret,
35                redirect_uri=REDIRECT_URI,
36                grant_type='authorization_code')
37
38    request = urllib2.Request(token_url, data=urllib.urlencode(data),
39                              headers=headers)
40    url_h = urllib2.urlopen(request)
41    auth_result = json.loads(url_h.read())
42    return '%s %s' % (auth_result['token_type'],
43                      auth_result['access_token'])
44
45
46def get_oauth2_robot_token(client_id, client_secret, code):
47    """Returns the oauth2 token for a robot account to use."""
48    token_url = '%s/%s' % (OAUTH_URL, 'token')
49    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
50    data = dict(code=code,
51                client_id=client_id,
52                client_secret=client_secret,
53                redirect_uri='oob',
54                grant_type='authorization_code')
55
56    request = urllib2.Request(token_url, data=urllib.urlencode(data),
57                              headers=headers)
58    url_h = urllib2.urlopen(request)
59    auth_result = json.loads(url_h.read())
60    return '%s %s' % (auth_result['token_type'],
61                      auth_result['access_token'])
62