# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
#     class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
#     def default(self, obj):
#     def exists(cls, *args, **kwargs):
#     def json_dumps(self):
#     def __repr__(self):
#     def __repr__(self):
#     def loc(self):
#     def loc(self, val):
#     def set_modified(self, date_time=None):
#     def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
# 
# Path: zoneserver.py
# class ObjectsHandler(DateLimitedObjectHandler):
#     '''ObjectsHandler returns a list of objects and their data.'''
#     target_object = Object
# 
# class CharStatusHandler(BaseHandler):
#     '''Manages if a character is active in the zone or not.'''
# 
#     @tornado.web.authenticated
#     def post(self):
#         user = self.get_secure_cookie('user')
#         character = self.get_argument('character', '')
#         status = self.get_argument('status', '')
#         self.char_controller = CharacterController()
# 
#         # If the character is not owned by this user, disallow it.
# #         if not self.char_controller.is_owner(user, character):
# #             retval = False
# 
#         retval = False
#         # Only allow setting the status to online or offline.
#         if status in ("online", "offline"):
#             if self.char_controller.set_char_status(character, status, user=user):
#                 retval = True
# 
#         self.write(json.dumps(retval))
# 
# 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")


import unittest
import json
import sys
import settings
        import mongoengine as me
        import mongoengine as me
        import zoneserver
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from elixir_models import metadata, setup_all, create_all
from zoneserver import ObjectsHandler, CharStatusHandler
from authserver import AuthHandler
    from tornado.web import RequestHandler
        from importlib import import_module
        from test_authserver import add_user
        from importlib import import_module
        from test_authserver import add_user
        from mock import patch
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####



sys.path.append(".")



def set_up_db():
    '''Connects to an in-memory SQLite database,
    with the purpose of emptying it and recreating it.'''
    metadata.bind = "sqlite:///:memory:"
    setup_all()
    create_all()

def set_user_cookie(app, request, username):
    r = RequestHandler(app, request)
    r.set_secure_cookie('user', username)
    authcookie = r._new_cookies[0]
    cookiestring = authcookie.items()[0][1]
    request.cookies.update({'user': cookiestring})
    return request


class TestObjectsHandler(AsyncHTTPTestCase):
    def get_app(self):

# Path: elixir_models.py
# class RetryDB(RetryOperationalError, SqliteExtDatabase):
# class ComplexEncoder(json.JSONEncoder):
# class BaseModel(Model):
#     class Meta:
# class User(BaseModel):
# class Character(BaseModel):
# class Zone(BaseModel):
# class Message(BaseModel):
# class Object(BaseModel):
# class Message(BaseModel):
# class ScriptedObject(Object):
#     def default(self, obj):
#     def exists(cls, *args, **kwargs):
#     def json_dumps(self):
#     def __repr__(self):
#     def __repr__(self):
#     def loc(self):
#     def loc(self, val):
#     def set_modified(self, date_time=None):
#     def get_objects(since=None, physical=None, limit=None, player=None, scripted=None, name=None):
# def setup(db_uri='simplemmo.sqlite', echo=False):
# 
# Path: zoneserver.py
# class ObjectsHandler(DateLimitedObjectHandler):
#     '''ObjectsHandler returns a list of objects and their data.'''
#     target_object = Object
# 
# class CharStatusHandler(BaseHandler):
#     '''Manages if a character is active in the zone or not.'''
# 
#     @tornado.web.authenticated
#     def post(self):
#         user = self.get_secure_cookie('user')
#         character = self.get_argument('character', '')
#         status = self.get_argument('status', '')
#         self.char_controller = CharacterController()
# 
#         # If the character is not owned by this user, disallow it.
# #         if not self.char_controller.is_owner(user, character):
# #             retval = False
# 
#         retval = False
#         # Only allow setting the status to online or offline.
#         if status in ("online", "offline"):
#             if self.char_controller.set_char_status(character, status, user=user):
#                 retval = True
# 
#         self.write(json.dumps(retval))
# 
# 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")


# Path: tests/integration/test_zoneserver.py
import unittest
import json
import sys
import settings
        import mongoengine as me
        import mongoengine as me
        import zoneserver
from tornado.web import Application
from tornado.testing import AsyncHTTPTestCase
from mock import Mock
from elixir_models import metadata, setup_all, create_all
from zoneserver import ObjectsHandler, CharStatusHandler
from authserver import AuthHandler
    from tornado.web import RequestHandler
        from importlib import import_module
        from test_authserver import add_user
        from importlib import import_module
        from test_authserver import add_user
        from mock import patch

#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ##### END AGPL LICENSE BLOCK #####



sys.path.append(".")



def set_up_db():
    '''Connects to an in-memory SQLite database,
    with the purpose of emptying it and recreating it.'''
    metadata.bind = "sqlite:///:memory:"
    setup_all()
    create_all()

def set_user_cookie(app, request, username):
    r = RequestHandler(app, request)
    r.set_secure_cookie('user', username)
    authcookie = r._new_cookies[0]
    cookiestring = authcookie.items()[0][1]
    request.cookies.update({'user': cookiestring})
    return request


class TestObjectsHandler(AsyncHTTPTestCase):
    def get_app(self):

        return Application([('/login', AuthHandler), ('/objects', ObjectsHandler),], cookie_secret=settings.COOKIE_SECRET)