# Path: amivapi/auth/auth.py
# class AdminOnlyAuth(AmivTokenAuth):
#     """Auth class to use if no access at all is given for non admins of a
#     resource."""
#     def create_user_lookup_filter(self, user):
#         """If this hook gets called, the user is not an admin for this resource.
#         Therefore no results should be given. To give a more precise error
#         message, we abort. Otherwise normal users would just see an empty list.
#         """
#         return None
# 
# def authenticate_token(token):
#     """Authenticate user and set g.current_token, g.current_session and
#     g.current_user.
# 
#     See also the authenticate function.
#     """
#     # Set defaults
#     g.current_token = g.current_session = g.current_user = None
# 
#     if token:
#         g.current_token = token
# 
#         # Get session
#         sessions = current_app.data.driver.db['sessions']
#         session = sessions.find_one({'token': token})
# 
#         if session:
#             # Update timestamp (remove microseconds to match mongo precision)
#             new_time = dt.utcnow().replace(microsecond=0)
#             sessions.update_one({'_id': session['_id']},
#                                 {'$set': {
#                                     '_updated': new_time
#                                 }})
#             session['_updated'] = new_time
# 
#             # Save user_id and session with updated timestamp in g
#             g.current_session = session
#             g.current_user = str(session['user'])  # ObjectId to str
# 
# Path: amivapi/settings.py
# REDIRECT_URI_REGEX = '^((http://)?localhost[^#]*|https://[^#]+)$'
# 
# Path: amivapi/utils.py
# def register_domain(app, domain):
#     """Add all resources in a domain to the app.
# 
#     The domain has to be deep-copied first because eve will modify it
#     (since it heavily relies on setdefault()), which can cause problems
#     especially in test environments, since the defaults don't get properly
#     erase sometimes.
# 
#     TODO: Make tests better maybe so this is no problem anymore?
# 
#     Args:
#         app (Eve object): The app to extend
#         domain (dict): The domain to be added to the app, will not be changed
#     """
#     domain_copy = deepcopy(domain)
# 
#     for resource, settings in domain_copy.items():
#         # Add default for the resource title:
#         # Capitalize like Eve does with item titles
#         settings.setdefault('resource_title', resource.capitalize())
# 
#         app.register_resource(resource, settings)
#         _better_schema_defaults(app, resource, settings)


from urllib.parse import urlencode
from bson import ObjectId
from cerberus import Validator
from eve.methods.post import post_internal
from flask import (
    make_response,
    abort,
    Blueprint,
    current_app,
    g,
    redirect,
    render_template,
    request,
)
from werkzeug.exceptions import Unauthorized
from amivapi.auth.auth import AdminOnlyAuth, authenticate_token
from amivapi.settings import REDIRECT_URI_REGEX
from amivapi.utils import register_domain
        # Check if the user wants to log out
        logout = request.form.get('submit') == 'logout'
        if logout:
            # Reset token and user
            token = user = ''
        else:
            try:
                return oauth_redirect(redirect_uri, state)
            except Unauthorized as error:
                # Login failed. Set error message and reset token
                token = ''
                error_msg = ("Login failed! If you think there is an error, "
                             "please contact AMIV with the exact time of your "
                             "login.")
                current_app.logger.info("Login failed with error: %s" % error)

    # Serve the login page (reset cookie if needed)
    response = make_response(render_template("loginpage.html",
                                             client_id=client_id,
                                             user=user,
                                             error_msg=error_msg))
    response.set_cookie('token', token)
    return response


description = ("""
Only registered OAuth clients are allowed to use the central login.
This whitelisting is necessary to prevent phishing attacks.
[More on OAuth with the API][1].


# Path: amivapi/auth/auth.py
# class AdminOnlyAuth(AmivTokenAuth):
#     """Auth class to use if no access at all is given for non admins of a
#     resource."""
#     def create_user_lookup_filter(self, user):
#         """If this hook gets called, the user is not an admin for this resource.
#         Therefore no results should be given. To give a more precise error
#         message, we abort. Otherwise normal users would just see an empty list.
#         """
#         return None
# 
# def authenticate_token(token):
#     """Authenticate user and set g.current_token, g.current_session and
#     g.current_user.
# 
#     See also the authenticate function.
#     """
#     # Set defaults
#     g.current_token = g.current_session = g.current_user = None
# 
#     if token:
#         g.current_token = token
# 
#         # Get session
#         sessions = current_app.data.driver.db['sessions']
#         session = sessions.find_one({'token': token})
# 
#         if session:
#             # Update timestamp (remove microseconds to match mongo precision)
#             new_time = dt.utcnow().replace(microsecond=0)
#             sessions.update_one({'_id': session['_id']},
#                                 {'$set': {
#                                     '_updated': new_time
#                                 }})
#             session['_updated'] = new_time
# 
#             # Save user_id and session with updated timestamp in g
#             g.current_session = session
#             g.current_user = str(session['user'])  # ObjectId to str
# 
# Path: amivapi/settings.py
# REDIRECT_URI_REGEX = '^((http://)?localhost[^#]*|https://[^#]+)$'
# 
# Path: amivapi/utils.py
# def register_domain(app, domain):
#     """Add all resources in a domain to the app.
# 
#     The domain has to be deep-copied first because eve will modify it
#     (since it heavily relies on setdefault()), which can cause problems
#     especially in test environments, since the defaults don't get properly
#     erase sometimes.
# 
#     TODO: Make tests better maybe so this is no problem anymore?
# 
#     Args:
#         app (Eve object): The app to extend
#         domain (dict): The domain to be added to the app, will not be changed
#     """
#     domain_copy = deepcopy(domain)
# 
#     for resource, settings in domain_copy.items():
#         # Add default for the resource title:
#         # Capitalize like Eve does with item titles
#         settings.setdefault('resource_title', resource.capitalize())
# 
#         app.register_resource(resource, settings)
#         _better_schema_defaults(app, resource, settings)


# Path: amivapi/auth/oauth.py
from urllib.parse import urlencode
from bson import ObjectId
from cerberus import Validator
from eve.methods.post import post_internal
from flask import (
    make_response,
    abort,
    Blueprint,
    current_app,
    g,
    redirect,
    render_template,
    request,
)
from werkzeug.exceptions import Unauthorized
from amivapi.auth.auth import AdminOnlyAuth, authenticate_token
from amivapi.settings import REDIRECT_URI_REGEX
from amivapi.utils import register_domain

        # Check if the user wants to log out
        logout = request.form.get('submit') == 'logout'
        if logout:
            # Reset token and user
            token = user = ''
        else:
            try:
                return oauth_redirect(redirect_uri, state)
            except Unauthorized as error:
                # Login failed. Set error message and reset token
                token = ''
                error_msg = ("Login failed! If you think there is an error, "
                             "please contact AMIV with the exact time of your "
                             "login.")
                current_app.logger.info("Login failed with error: %s" % error)

    # Serve the login page (reset cookie if needed)
    response = make_response(render_template("loginpage.html",
                                             client_id=client_id,
                                             user=user,
                                             error_msg=error_msg))
    response.set_cookie('token', token)
    return response


description = ("""
Only registered OAuth clients are allowed to use the central login.
This whitelisting is necessary to prevent phishing attacks.
[More on OAuth with the API][1].


Only **admins** are allowed to access this resource.