utils.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """ibt2 utils
  2. Miscellaneous utilities.
  3. Copyright 2016 Davide Alberani <da@erlug.linux.it>
  4. RaspiBO <info@raspibo.org>
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. """
  14. import json
  15. import string
  16. import random
  17. import hashlib
  18. import datetime
  19. from bson.objectid import ObjectId
  20. def hash_password(password, salt=None):
  21. """Hash a password.
  22. :param password: the cleartext password
  23. :type password: str
  24. :param salt: the optional salt (randomly generated, if None)
  25. :type salt: str
  26. :returns: the hashed password
  27. :rtype: str"""
  28. if salt is None:
  29. salt_pool = string.ascii_letters + string.digits
  30. salt = ''.join(random.choice(salt_pool) for x in range(32))
  31. pass_and_salt = '%s%s' % (salt, password)
  32. pass_and_salt = pass_and_salt.encode('utf-8', 'ignore')
  33. hash_ = hashlib.sha512(pass_and_salt)
  34. return '$%s$%s' % (salt, hash_.hexdigest())
  35. class ImprovedEncoder(json.JSONEncoder):
  36. """Enhance the default JSON encoder to serialize datetime and ObjectId instances."""
  37. def default(self, o):
  38. if isinstance(o, bytes):
  39. try:
  40. return o.decode('utf-8')
  41. except:
  42. pass
  43. elif isinstance(o, (datetime.datetime, datetime.date,
  44. datetime.time, datetime.timedelta, ObjectId)):
  45. try:
  46. return str(o)
  47. except:
  48. pass
  49. elif isinstance(o, set):
  50. return list(o)
  51. return json.JSONEncoder.default(self, o)
  52. # Inject our class as the default encoder.
  53. json._default_encoder = ImprovedEncoder()