import tornado.httpserver
import tornado.ioloop
import tornado.iostream
import tornado.web
import tornado.httpclient

import traceback
import threading
from univention.management.console.pam import PamAuth


class Server(tornado.web.RequestHandler):

	@tornado.gen.coroutine
	def get(self):
		self.write('GET\n')
		self.finish()

	@tornado.gen.coroutine
	def post(self):
		pam = PamAuth()
		username = self.get_argument('username')
		password = self.get_argument('password')
		print('Logging in')
		thread = threading.Thread(None, self.authenticate, args=(pam, username, password))
		thread.start()
		self.write('Done\n')
		self.finish()

	def authenticate(self, pam, username, password):
		print('In thread')
		result = None
		try:
			result = pam.authenticate(username, password)
		except:
			print traceback.format_exc()
		print('authenticated', result)

	@classmethod
	def main(cls):
		app = tornado.web.Application([
			(r'.*', cls),
		], debug=False, serve_traceback=True,
		)
		app.listen(6671)
		ioloop = tornado.ioloop.IOLoop.instance()
		ioloop.start()


Server.main()
