utils.py 2.1 KB

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