| Krzysztof Szukiełojć | 15b62b7 | 2017-02-15 08:58:18 +0100 | [diff] [blame] | 1 | # Copyright 2012 Canonical Ltd.  This software is licensed under the | 
|  | 2 | # GNU Affero General Public License version 3 (see the file LICENSE). | 
|  | 3 |  | 
|  | 4 | """Handling of MAAS API credentials. | 
|  | 5 |  | 
|  | 6 | The API client deals with credentials consisting of 3 elements: consumer | 
|  | 7 | key, resource token, and resource secret.  These are in OAuth, but the | 
|  | 8 | consumer secret is hardwired to the empty string. | 
|  | 9 |  | 
|  | 10 | Credentials are represented internally as tuples of these three elements, | 
|  | 11 | but can also be converted to a colon-separated string format for easy | 
|  | 12 | transport between processes. | 
|  | 13 | """ | 
|  | 14 |  | 
|  | 15 | from __future__ import ( | 
|  | 16 | absolute_import, | 
|  | 17 | print_function, | 
|  | 18 | unicode_literals, | 
|  | 19 | ) | 
|  | 20 |  | 
|  | 21 | str = None | 
|  | 22 |  | 
|  | 23 | __metaclass__ = type | 
|  | 24 | __all__ = [ | 
|  | 25 | 'convert_string_to_tuple', | 
|  | 26 | 'convert_tuple_to_string', | 
|  | 27 | ] | 
|  | 28 |  | 
|  | 29 |  | 
|  | 30 | def convert_tuple_to_string(creds_tuple): | 
|  | 31 | """Represent a MAAS API credentials tuple as a colon-separated string.""" | 
|  | 32 | if len(creds_tuple) != 3: | 
|  | 33 | raise ValueError( | 
|  | 34 | "Credentials tuple does not consist of 3 elements as expected; " | 
|  | 35 | "it contains %d." | 
|  | 36 | % len(creds_tuple)) | 
|  | 37 | return ':'.join(creds_tuple) | 
|  | 38 |  | 
|  | 39 |  | 
|  | 40 | def convert_string_to_tuple(creds_string): | 
|  | 41 | """Recreate a MAAS API credentials tuple from a colon-separated string.""" | 
|  | 42 | creds_tuple = tuple(creds_string.split(':')) | 
|  | 43 | if len(creds_tuple) != 3: | 
|  | 44 | raise ValueError( | 
|  | 45 | "Malformed credentials string.  Expected 3 colon-separated items, " | 
|  | 46 | "got %r." | 
|  | 47 | % creds_string) | 
|  | 48 | return creds_tuple |