# Path: authserver.py
# class AuthHandler(BaseHandler):
#     '''AuthHandler authenticates a user and sets a session in the database.
# 
#     .. http:post:: /login
# 
#         Creates a User in the AuthenticationServer's database.
# 
#         **Example request**:
# 
#         .. sourcecode:: http
# 
#             POST /login HTTP/1.1
# 
#             username=asdf&password=asdf
# 
#         **Example response**:
# 
#         .. sourcecode:: http
# 
#             HTTP/1.1 200 OK
#             Set-Cookie: user="VXNlcm5hbWU=|1341639882|ec1af42349272b09f4f7ebb1be4da826500d1f6c"; expires=Mon, 06 Aug 2012 05:44:42 GMT; Path=/
# 
#             Login successful.
# 
# 
#         :param username: The name of the user to log in as.
#         :param password: The password to use for authenticating the user.
# 
#         :status 200: Login successful.
#         :status 401: Login failed due to bad username and/or password
#         '''
#     def post(self):
#         username = self.get_argument("username", "")
#         password = self.get_argument("password", "")
#         auth = self.authenticate(username, password)
#         if auth:
#             self.set_current_user(username)
#             self.set_admin(username)
#             self.write('Login successful.')
#         else:
#             raise tornado.web.HTTPError(401, 'Login Failed, username and/or password incorrect.')
# 
#     def authenticate(self, username, password):
#         '''Compares a username/password pair against that in the database.
#         If they match, return True.
#         Else, return False.'''
#         # Do some database stuff here to verify the user.
#         user = User.get(username=username)
#         if not user:
#             return False
#         return UserController.check_password(plaintext=password, hashed=user.password)
# 
#     def set_admin(self, user):
#         # Look up username in admins list in database
#         # if present, set secure cookie for admin
#         if user in settings.ADMINISTRATORS:
#             self.set_secure_cookie("admin", 'true')
#         else:
#             self.clear_cookie("admin")
# 
#     def set_current_user(self, user):
#         if user:
#             self.set_secure_cookie("user", user, domain=None)
#         else:
#             self.clear_cookie("user")
# 
# class RegistrationHandler(BaseHandler):
#     '''RegistrationHandler creates Users.
# 
#     .. http:post:: /register
# 
#         Creates a User in the AuthenticationServer's database.
# 
#         **Example request**:
# 
#         .. sourcecode:: http
# 
#             POST /register HTTP/1.1
# 
#             username=asdf&password=asdf
# 
#         **Example response**:
# 
#         .. sourcecode:: http
# 
#             HTTP/1.1 200 OK
# 
#             Registration succeeded.
# 
# 
#         :param username: The name of the user to create.
#         :param password: The password to use for authenticating the user.
#         :param email: Optional. An email to associate with the user.
# 
#         :status 200: Registration succeeded.
#         :status 400: A required parameter was missing.
#         :status 401: The User already exists.
#     '''
#     def post(self):
#         username = self.get_argument("username", "")
#         password = self.get_argument("password", "")
#         email = self.get_argument("email", "")
# 
#         if not username:
#             return self.HTTPError(400, "A user name is required.")
# 
#         if not password:
#             return self.HTTPError(400, "A password is required.")
# 
#         user = self.register_user(username, password, email=email)
#         logging.info("User was %s" % user)
#         if user:
#             return self.write('Registration successful.')
#         else:
#             return self.HTTPError(401, "User already exists.")
# 
#     def register_user(self, username, password, email=None):
#         if User.select().where(User.username==username).exists():
#             return False
# 
#         user = User(username=username,
#                     password=UserController.hash_password(password),
#                     email=email)
#         user.save()
#         return user


import unittest
import sys
import authserver
import settings
from tornado.web import Application
from mock import Mock, patch
from authserver import AuthHandler, RegistrationHandler
        from sqlalchemy.exc import IntegrityError
        MockAdmin.__iter__ = Mock(return_value=iter([]))
        mock_clear_cookie = Mock()

        with patch.object(settings, 'ADMINISTRATORS', MockAdmin):
            with patch.object(self.auth_handler, 'clear_cookie', mock_clear_cookie):
                self.auth_handler.set_admin(user)

        mock_clear_cookie.assert_called_once_with('admin')

    def test_set_current_user(self):
        user = "username"
        mock_set_secure_cookie = Mock()

        with patch.object(self.auth_handler, 'set_secure_cookie', mock_set_secure_cookie):
            self.auth_handler.set_current_user(user)

        mock_set_secure_cookie.assert_called_once_with("user", user, domain=None)

    def test_set_current_user_with_none(self):
        user = None
        mock_clear_cookie = Mock()

        with patch.object(self.auth_handler, 'clear_cookie', mock_clear_cookie):
            self.auth_handler.set_current_user(user)

        mock_clear_cookie.assert_called_once_with("user")

class TestRegistrationHandler(unittest.TestCase):

    def setUp(self):

# Path: authserver.py
# class AuthHandler(BaseHandler):
#     '''AuthHandler authenticates a user and sets a session in the database.
# 
#     .. http:post:: /login
# 
#         Creates a User in the AuthenticationServer's database.
# 
#         **Example request**:
# 
#         .. sourcecode:: http
# 
#             POST /login HTTP/1.1
# 
#             username=asdf&password=asdf
# 
#         **Example response**:
# 
#         .. sourcecode:: http
# 
#             HTTP/1.1 200 OK
#             Set-Cookie: user="VXNlcm5hbWU=|1341639882|ec1af42349272b09f4f7ebb1be4da826500d1f6c"; expires=Mon, 06 Aug 2012 05:44:42 GMT; Path=/
# 
#             Login successful.
# 
# 
#         :param username: The name of the user to log in as.
#         :param password: The password to use for authenticating the user.
# 
#         :status 200: Login successful.
#         :status 401: Login failed due to bad username and/or password
#         '''
#     def post(self):
#         username = self.get_argument("username", "")
#         password = self.get_argument("password", "")
#         auth = self.authenticate(username, password)
#         if auth:
#             self.set_current_user(username)
#             self.set_admin(username)
#             self.write('Login successful.')
#         else:
#             raise tornado.web.HTTPError(401, 'Login Failed, username and/or password incorrect.')
# 
#     def authenticate(self, username, password):
#         '''Compares a username/password pair against that in the database.
#         If they match, return True.
#         Else, return False.'''
#         # Do some database stuff here to verify the user.
#         user = User.get(username=username)
#         if not user:
#             return False
#         return UserController.check_password(plaintext=password, hashed=user.password)
# 
#     def set_admin(self, user):
#         # Look up username in admins list in database
#         # if present, set secure cookie for admin
#         if user in settings.ADMINISTRATORS:
#             self.set_secure_cookie("admin", 'true')
#         else:
#             self.clear_cookie("admin")
# 
#     def set_current_user(self, user):
#         if user:
#             self.set_secure_cookie("user", user, domain=None)
#         else:
#             self.clear_cookie("user")
# 
# class RegistrationHandler(BaseHandler):
#     '''RegistrationHandler creates Users.
# 
#     .. http:post:: /register
# 
#         Creates a User in the AuthenticationServer's database.
# 
#         **Example request**:
# 
#         .. sourcecode:: http
# 
#             POST /register HTTP/1.1
# 
#             username=asdf&password=asdf
# 
#         **Example response**:
# 
#         .. sourcecode:: http
# 
#             HTTP/1.1 200 OK
# 
#             Registration succeeded.
# 
# 
#         :param username: The name of the user to create.
#         :param password: The password to use for authenticating the user.
#         :param email: Optional. An email to associate with the user.
# 
#         :status 200: Registration succeeded.
#         :status 400: A required parameter was missing.
#         :status 401: The User already exists.
#     '''
#     def post(self):
#         username = self.get_argument("username", "")
#         password = self.get_argument("password", "")
#         email = self.get_argument("email", "")
# 
#         if not username:
#             return self.HTTPError(400, "A user name is required.")
# 
#         if not password:
#             return self.HTTPError(400, "A password is required.")
# 
#         user = self.register_user(username, password, email=email)
#         logging.info("User was %s" % user)
#         if user:
#             return self.write('Registration successful.')
#         else:
#             return self.HTTPError(401, "User already exists.")
# 
#     def register_user(self, username, password, email=None):
#         if User.select().where(User.username==username).exists():
#             return False
# 
#         user = User(username=username,
#                     password=UserController.hash_password(password),
#                     email=email)
#         user.save()
#         return user


# Path: tests/test_authserver.py
import unittest
import sys
import authserver
import settings
from tornado.web import Application
from mock import Mock, patch
from authserver import AuthHandler, RegistrationHandler
        from sqlalchemy.exc import IntegrityError

        MockAdmin.__iter__ = Mock(return_value=iter([]))
        mock_clear_cookie = Mock()

        with patch.object(settings, 'ADMINISTRATORS', MockAdmin):
            with patch.object(self.auth_handler, 'clear_cookie', mock_clear_cookie):
                self.auth_handler.set_admin(user)

        mock_clear_cookie.assert_called_once_with('admin')

    def test_set_current_user(self):
        user = "username"
        mock_set_secure_cookie = Mock()

        with patch.object(self.auth_handler, 'set_secure_cookie', mock_set_secure_cookie):
            self.auth_handler.set_current_user(user)

        mock_set_secure_cookie.assert_called_once_with("user", user, domain=None)

    def test_set_current_user_with_none(self):
        user = None
        mock_clear_cookie = Mock()

        with patch.object(self.auth_handler, 'clear_cookie', mock_clear_cookie):
            self.auth_handler.set_current_user(user)

        mock_clear_cookie.assert_called_once_with("user")

class TestRegistrationHandler(unittest.TestCase):

    def setUp(self):

        app = Application([('/', RegistrationHandler)])