# Path: core/config.py

# 
# Path: core/validation/permissions.py
# def get_user_restrictions():
#     """Format restriction schemas. Saved on auth login to speedup following accesses"""
#     
#     
#     # Recursively replace needs a condition_function and replace_function
#     replacements = { 
#                     '%%username%%' : '^%s$' % (cherrypy.session['_ts_user']['username']), 
#                     '%%_id%%' : '^%s$' % (str(cherrypy.session['_ts_user']['_id'])),
#                     '%%managed_projects%%' : (cherrypy.session['_ts_user']['managed_projects']),
#                     '%%employed_projects%%' : (cherrypy.session['_ts_user']['employed_projects']),
#                     '%%projects%%' : (cherrypy.session['_ts_user']['projects']),
#                     '%%approval_flow%%' : get_role_approval_step(cherrypy.session['_ts_user']['group']),
#                     '%%draft_flow%%' : get_role_approval_step('draft'),
#                     }
# 
#     def _replace_function_permissions_schema(container):
#         if isinstance(container,basestring):
#             replacement = replacements.get(container)
#             if replacement != None:
#                 # Replace strings and objectid with string
#                 if isinstance(replacement,(basestring, ObjectId)):
#                     return str(replacement)
#                 # Replace managed_projects with project list
#                 elif isinstance(replacement, types.ListType):
#                     return replacement
#                 else:
#                     return replacement
#         
#     formatted_schemas = {}
#     
#     for collection_name, collection_schema in restrictions_schema.items():
#         try:
#             group_schema = collection_schema[cherrypy.session['_ts_user']['group']]
#         except (KeyError, TypeError):
#             pass
#         else:
#             formatted_schemas[collection_name] = recursive_replace(group_schema, _replace_function_permissions_schema)
#     return formatted_schemas
# 
# Path: core/api/crud.py
# def get(collection, criteria_projection_order):
# def remove(collection, criterias = []):
# def add(collection, documents_list):
# def update(collection, document):


import cherrypy, logging, pprint
from core.config import conf_auth, conf_auth_db, conf_auth_ldap, templates
from core.validation.permissions import get_user_restrictions
from core.api.crud import db
from core import auth
# needed if you want to use it inside of an any_of(...) condition
def all_of(*conditions):
    """Returns True if all of the conditions match"""
    def check():
        for c in conditions:
            if not c():
                return False
        return True
    return check



def _unique_keeping_order(seq):
    seen = set()
    seen_add = seen.add
    return [ x for x in seq if x not in seen and not seen_add(x)]

# Controller to provide login and logout actions
class AuthController(object):
    
    def reload_users_projects(self):

        # Save ids of managed_projects
        cherrypy.session['_ts_user']['managed_projects'] = []
        cursor = db.project.find({ 'responsibles._id' : cherrypy.session['_ts_user']['_id'] }, { '_id' : 1 })
        for document in cursor:
            cherrypy.session['_ts_user']['managed_projects'].append(str(document['_id']))

        # Save ids of taken projects
        cherrypy.session['_ts_user']['employed_projects'] = []

# Path: core/config.py

# 
# Path: core/validation/permissions.py
# def get_user_restrictions():
#     """Format restriction schemas. Saved on auth login to speedup following accesses"""
#     
#     
#     # Recursively replace needs a condition_function and replace_function
#     replacements = { 
#                     '%%username%%' : '^%s$' % (cherrypy.session['_ts_user']['username']), 
#                     '%%_id%%' : '^%s$' % (str(cherrypy.session['_ts_user']['_id'])),
#                     '%%managed_projects%%' : (cherrypy.session['_ts_user']['managed_projects']),
#                     '%%employed_projects%%' : (cherrypy.session['_ts_user']['employed_projects']),
#                     '%%projects%%' : (cherrypy.session['_ts_user']['projects']),
#                     '%%approval_flow%%' : get_role_approval_step(cherrypy.session['_ts_user']['group']),
#                     '%%draft_flow%%' : get_role_approval_step('draft'),
#                     }
# 
#     def _replace_function_permissions_schema(container):
#         if isinstance(container,basestring):
#             replacement = replacements.get(container)
#             if replacement != None:
#                 # Replace strings and objectid with string
#                 if isinstance(replacement,(basestring, ObjectId)):
#                     return str(replacement)
#                 # Replace managed_projects with project list
#                 elif isinstance(replacement, types.ListType):
#                     return replacement
#                 else:
#                     return replacement
#         
#     formatted_schemas = {}
#     
#     for collection_name, collection_schema in restrictions_schema.items():
#         try:
#             group_schema = collection_schema[cherrypy.session['_ts_user']['group']]
#         except (KeyError, TypeError):
#             pass
#         else:
#             formatted_schemas[collection_name] = recursive_replace(group_schema, _replace_function_permissions_schema)
#     return formatted_schemas
# 
# Path: core/api/crud.py
# def get(collection, criteria_projection_order):
# def remove(collection, criterias = []):
# def add(collection, documents_list):
# def update(collection, document):


# Path: core/auth/auth.py
import cherrypy, logging, pprint
from core.config import conf_auth, conf_auth_db, conf_auth_ldap, templates
from core.validation.permissions import get_user_restrictions
from core.api.crud import db
from core import auth

# needed if you want to use it inside of an any_of(...) condition
def all_of(*conditions):
    """Returns True if all of the conditions match"""
    def check():
        for c in conditions:
            if not c():
                return False
        return True
    return check



def _unique_keeping_order(seq):
    seen = set()
    seen_add = seen.add
    return [ x for x in seq if x not in seen and not seen_add(x)]

# Controller to provide login and logout actions
class AuthController(object):
    
    def reload_users_projects(self):

        # Save ids of managed_projects
        cherrypy.session['_ts_user']['managed_projects'] = []
        cursor = db.project.find({ 'responsibles._id' : cherrypy.session['_ts_user']['_id'] }, { '_id' : 1 })
        for document in cursor:
            cherrypy.session['_ts_user']['managed_projects'].append(str(document['_id']))

        # Save ids of taken projects
        cherrypy.session['_ts_user']['employed_projects'] = []

        cursor = db.project.find({ 'employees._id' : cherrypy.session['_ts_user']['_id'] }, { '_id' : 1 })