from aiohttp import web
import aiohttp_security

import security

def init_app(app):
	routes = web.RouteTableDef()

	@routes.get('/in')
	async def get_login(request):
		status = request.query.get('status', '401')
		if status == '401':
			message = "Please enter the password.<br><code>userpass</code> for regular access,<br><code>adminpass</code> for elevated permissions."
		elif status == '403':
			message = "Elevated permissions required.<br><code>adminpass</code> for elevated permissions."
		else:
			message = "This shouldn't happen."
		response = request.config_dict['templates']["login.html"].safe_substitute({
			'title': 'Log in to try the demo',
			'message': message,
			'url': request.query.get('url', '/')
		})
		return web.Response(text=response, content_type="text/html")

	@routes.post('/in')
	async def post_login(request):
		postdata = await request.post()
		url = postdata.get('url', '/')
		identity = security.try_password(postdata["password"])
		if identity:
			redirect_response = web.HTTPFound(url)
			await aiohttp_security.remember(request, redirect_response, identity)
			raise redirect_response
		else:
			response = request.config_dict['templates']["login.html"].safe_substitute({
				'title': 'Log in to try the demo',
				'message': "Incorrect password.<br><code>userpass</code> for regular access,<br><code>adminpass</code> for elevated permissions.",
				'url': url
			})
			return web.Response(text=response, content_type="text/html")

	@routes.get('/out')
	async def get_logout(request):
		redirect_response = web.HTTPFound('/')
		await aiohttp_security.forget(request, redirect_response)
		raise redirect_response

	app.add_routes(routes)