Skip to content

Instantly share code, notes, and snippets.

@jaraco
Created April 13, 2020 21:43
Show Gist options
  • Save jaraco/e08f25af1e30cc1418705f8162ebffcf to your computer and use it in GitHub Desktop.
Save jaraco/e08f25af1e30cc1418705f8162ebffcf to your computer and use it in GitHub Desktop.
@cherrypy.expose
def login(self, username, password):
"""
Log in the user and set a JWT web token in the cookie.
"""
res = self._login(username, password)
if not res:
raise cherrypy.HTTPError('401 Unauthorized')
self.install_token(models.Member.make_token(res))
@staticmethod
def install_token(token):
cherrypy.response.cookie['token'] = token
cherrypy.response.cookie['token']['path'] = '/'
@cherrypy.expose
def validate_token(self):
token = cherrypy.request.cookie['token'].value
try:
return jwt.decode(token, os.environ['TOKEN_KEY'])
except jwt.ExpiredSignatureError:
raise cherrypy.HTTPError('400 Token Invalid')
@farooqkz
Copy link

May you please explain me a bit about models module?
On line #9.

@jaraco
Copy link
Author

jaraco commented Apr 19, 2020

models is code specific to the application's model of the world, the "models" of an mvc pattern. The code for make_token takes fields from the res and rolls them into a JWT like so:

	@classmethod
	def make_token(cls, member_fields):
		doc = dict(
			email=member_fields['EMAIL'],
			id=member_fields['ID'],
			exp=utc.now() + cls.session_limit,
		)
		token = jwt.encode(doc, os.environ['TOKEN_KEY'])

		return token.decode('ascii')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment