PageRenderTime 497ms CodeModel.GetById 259ms app.highlight 6ms RepoModel.GetById 230ms app.codeStats 0ms

/silversupport/secret.py

https://bitbucket.org/ianb/silverlining/
Python | 48 lines | 37 code | 8 blank | 3 comment | 11 complexity | df85cd838f2c0b244703f3d9b258ce68 MD5 | raw file
 1"""Get a secret key"""
 2import os
 3from ConfigParser import ConfigParser
 4from silversupport.env import is_production, local_location
 5
 6__all__ = ['get_secret', 'get_key']
 7
 8if is_production():
 9    secret_file = '/var/lib/silverlining/secret.txt'
10    key_file = '/var/lib/silverlining/keys.ini'
11else:
12    secret_file = local_location('secret.txt')
13    if not os.path.exists(secret_file):
14        import base64
15        fp = open(secret_file, 'wb')
16        secret = base64.b64encode(os.urandom(24), "_-").strip("=")
17        fp.write(secret)
18        fp.close()
19    key_file = os.path.join(
20        os.environ['HOME'], '.silverlining.conf')
21
22
23def get_secret():
24    """Gets the secret, a random/stable ASCII string"""
25    fp = open(secret_file, 'rb')
26    return fp.read().strip()
27
28
29def get_key(name):
30    """Gets a named key, e.g., a Google Map API key"""
31    keys = load_keys()
32    return keys.get(name)
33
34
35def load_keys():
36    parser = ConfigParser()
37    parser.read([key_file])
38    keys = {}
39    if parser.has_section('keys'):
40        for option in parser.options('keys'):
41            keys[option] = parser.get('keys', option)
42    for section in parser.sections():
43        if section.startswith('keys:'):
44            name = section[len('keys:'):]
45            keys[name] = {}
46            for option in parser.options(section):
47                keys[name][option] = parser.get(section, option)
48    return keys