http_handler.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # -*- coding: utf-8 -*-
  2. from openerp import http
  3. from openerp.http import request
  4. from passlib.context import CryptContext
  5. import werkzeug.wrappers
  6. import jwt
  7. import json
  8. crypt_context = CryptContext(
  9. ['pbkdf2_sha512', 'md5_crypt'],
  10. deprecated=['md5_crypt'],
  11. )
  12. '''
  13. Class for manage authentication
  14. '''
  15. class Auth(http.Controller):
  16. JWT_SECRET_KEY = '@MjSk$2016?'
  17. # --------------------------------------------------------------------------
  18. # Generate JWT token based on username and password field
  19. # --------------------------------------------------------------------------
  20. @http.route(['/api/jwt'], type = 'http', auth = 'none', methods = ['POST'])
  21. def get_jwt(self, **args):
  22. try:
  23. user = request.env['res.users'].sudo().search([('login', '=', args['username']), ('active', '=', True)])
  24. if len(user) != 0 and self.get_crypt_context().verify(args['password'], user.password_crypt):
  25. payload = {
  26. 'uid': user.id,
  27. 'password': args['password']
  28. }
  29. encoded = jwt.encode(payload, self.JWT_SECRET_KEY, algorithm = 'HS256')
  30. user.write({'jwt_token': encoded})
  31. return json.dumps({'token': encoded})
  32. else:
  33. return json.dumps({'error': 'invalid user or password'})
  34. except Exception, e:
  35. return json.dumps({'error': 'fields required'})
  36. # --------------------------------------------------------------------------
  37. # Check JWT token auth
  38. # --------------------------------------------------------------------------
  39. @http.route(['/api/check'], type = 'http', auth = 'none')
  40. def check_token(self, **args):
  41. try:
  42. user = request.env['res.users'].sudo().search([('jwt_token', '=', args['token'])])
  43. if len(user) != 0:
  44. decoded = jwt.decode(args['token'], self.JWT_SECRET_KEY, algorithms = ['HS256'])
  45. if self.get_crypt_context().verify(decoded['password'], user.password_crypt):
  46. return json.dumps({'token': 'valid'})
  47. return json.dumps({'token': 'invalid'})
  48. except Exception, e:
  49. return json.dumps({'error': 'token required'})
  50. # --------------------------------------------------------------------------
  51. # Get context for encryption
  52. # --------------------------------------------------------------------------
  53. def get_crypt_context(self):
  54. return crypt_context
  55. '''
  56. Class for manage rest api interaction
  57. '''
  58. class ApiManager(http.Controller):
  59. @http.route(['/api/customers'], type = 'http', auth = 'none')
  60. def customers(self):
  61. pass