PageRenderTime 26ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/silversupport/secret.py

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