aboutsummaryrefslogtreecommitdiff
path: root/oauth2client/clientsecrets.py
blob: 1598142e878fada921d15aa783ea101258f71297 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Utilities for reading OAuth 2.0 client secret files.

A client_secrets.json file contains all the information needed to interact with
an OAuth 2.0 protected service.
"""

import json

import six


# Properties that make a client_secrets.json file valid.
TYPE_WEB = 'web'
TYPE_INSTALLED = 'installed'

VALID_CLIENT = {
    TYPE_WEB: {
        'required': [
            'client_id',
            'client_secret',
            'redirect_uris',
            'auth_uri',
            'token_uri',
        ],
        'string': [
            'client_id',
            'client_secret',
        ],
    },
    TYPE_INSTALLED: {
        'required': [
            'client_id',
            'client_secret',
            'redirect_uris',
            'auth_uri',
            'token_uri',
        ],
        'string': [
            'client_id',
            'client_secret',
        ],
    },
}


class Error(Exception):
    """Base error for this module."""


class InvalidClientSecretsError(Error):
    """Format of ClientSecrets file is invalid."""


def _validate_clientsecrets(clientsecrets_dict):
    """Validate parsed client secrets from a file.

    Args:
        clientsecrets_dict: dict, a dictionary holding the client secrets.

    Returns:
        tuple, a string of the client type and the information parsed
        from the file.
    """
    _INVALID_FILE_FORMAT_MSG = (
        'Invalid file format. See '
        'https://developers.google.com/api-client-library/'
        'python/guide/aaa_client_secrets')

    if clientsecrets_dict is None:
        raise InvalidClientSecretsError(_INVALID_FILE_FORMAT_MSG)
    try:
        (client_type, client_info), = clientsecrets_dict.items()
    except (ValueError, AttributeError):
        raise InvalidClientSecretsError(
            _INVALID_FILE_FORMAT_MSG + ' '
            'Expected a JSON object with a single property for a "web" or '
            '"installed" application')

    if client_type not in VALID_CLIENT:
        raise InvalidClientSecretsError(
            'Unknown client type: {0}.'.format(client_type))

    for prop_name in VALID_CLIENT[client_type]['required']:
        if prop_name not in client_info:
            raise InvalidClientSecretsError(
                'Missing property "{0}" in a client type of "{1}".'.format(
                    prop_name, client_type))
    for prop_name in VALID_CLIENT[client_type]['string']:
        if client_info[prop_name].startswith('[['):
            raise InvalidClientSecretsError(
                'Property "{0}" is not configured.'.format(prop_name))
    return client_type, client_info


def load(fp):
    obj = json.load(fp)
    return _validate_clientsecrets(obj)


def loads(s):
    obj = json.loads(s)
    return _validate_clientsecrets(obj)


def _loadfile(filename):
    try:
        with open(filename, 'r') as fp:
            obj = json.load(fp)
    except IOError as exc:
        raise InvalidClientSecretsError('Error opening file', exc.filename,
                                        exc.strerror, exc.errno)
    return _validate_clientsecrets(obj)


def loadfile(filename, cache=None):
    """Loading of client_secrets JSON file, optionally backed by a cache.

    Typical cache storage would be App Engine memcache service,
    but you can pass in any other cache client that implements
    these methods:

    * ``get(key, namespace=ns)``
    * ``set(key, value, namespace=ns)``

    Usage::

        # without caching
        client_type, client_info = loadfile('secrets.json')
        # using App Engine memcache service
        from google.appengine.api import memcache
        client_type, client_info = loadfile('secrets.json', cache=memcache)

    Args:
        filename: string, Path to a client_secrets.json file on a filesystem.
        cache: An optional cache service client that implements get() and set()
        methods. If not specified, the file is always being loaded from
                 a filesystem.

    Raises:
        InvalidClientSecretsError: In case of a validation error or some
                                   I/O failure. Can happen only on cache miss.

    Returns:
        (client_type, client_info) tuple, as _loadfile() normally would.
        JSON contents is validated only during first load. Cache hits are not
        validated.
    """
    _SECRET_NAMESPACE = 'oauth2client:secrets#ns'

    if not cache:
        return _loadfile(filename)

    obj = cache.get(filename, namespace=_SECRET_NAMESPACE)
    if obj is None:
        client_type, client_info = _loadfile(filename)
        obj = {client_type: client_info}
        cache.set(filename, obj, namespace=_SECRET_NAMESPACE)

    return next(six.iteritems(obj))