/lib/corkscrew/auth.py

https://github.com/marchon/corkscrew · Python · 77 lines · 51 code · 12 blank · 14 comment · 9 complexity · a516b3c5eddd86c07548553fbec69c4f MD5 · raw file

  1. """ corkscrew.auth
  2. """
  3. from werkzeug import check_password_hash, generate_password_hash
  4. import jinja2
  5. from flask import render_template, g, flash
  6. from flask import request, session, redirect
  7. from corkscrew import View
  8. import report as reporting
  9. report = reporting.report
  10. class AuthCommon(View):
  11. def auth_redirect(self):
  12. _next = request.referrer
  13. if not _next or self.url in _next:
  14. _next = self%'corkscrew.default_auth_next'
  15. return redirect(_next)
  16. class Logout(AuthCommon):
  17. """Logs the user out."""
  18. url = '/logout'
  19. methods = ["GET"]
  20. def main(self):
  21. flash('You were logged out')
  22. session.pop('user_id', None)
  23. return self.auth_redirect()
  24. class Login(AuthCommon):
  25. """ Logs the user in.
  26. TODO: send them back where they came from, and not to /
  27. """
  28. url = '/login'
  29. methods = methods = ["GET", "POST"]
  30. template = 'login.html'
  31. def template_literal(self, t):
  32. self._template = t
  33. def __invert__(self):
  34. """ give the template literal if present. """
  35. return self._template
  36. def render_template(self, *args, **kargs):
  37. """ variation of View.render_template that prefers
  38. ``self.template`` on the filesystem, and failing
  39. that will use an embedded template literal at
  40. ``self._template``
  41. """
  42. try:
  43. return super(self.__class__,self).render_template(*args, **kargs)
  44. except jinja2.exceptions.TemplateNotFound, e:
  45. from flask.templating import render_template_string
  46. report("template {T} not found, using literal",T=self.template)
  47. return render_template_string(self._template, **kargs)
  48. def main(self):
  49. """ """
  50. if self.authorized:
  51. report('already authorized', self.user)
  52. return self.auth_redirect()
  53. if request.method == 'POST':
  54. users = self.settings%'users'
  55. user = self['username']
  56. if user not in users:
  57. return self.render_template(error='Invalid username')
  58. if not check_password_hash(users[user],self['password']):
  59. return self.render_template(error='Invalid password')
  60. else:
  61. flash('You were logged in')
  62. session['user_id'] = user
  63. return self.auth_redirect()
  64. return self.render_template()