# 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
    redirect_uri = _append_url_params(redirect_uri,
                                      access_token=token,
                                      token_type='bearer',
                                      scope='amiv',
                                      state=state)

    # If the user wants to be remembered, save the token as cookie
    # so the next time only 'confirm' needs to be pressed
    response = current_app.make_response(redirect(redirect_uri))
    if request.form.get('remember'):
        response.set_cookie('token', token)
    return response


@oauth_blueprint.route('/oauth', methods=['GET', 'POST'])
def oauth():
    """Endpoint for OAuth login. OAuth clients redirect users here."""
    response_type = request.args.get('response_type')
    client_id = request.args.get('client_id')
    redirect_uri = request.args.get('redirect_uri')
    scope = request.args.get('scope')
    state = request.args.get('state')
    token = request.cookies.get('token', '')
    error_msg = ''

    # Check this is a request by a proper client
    redirect_uri = validate_oauth_authorization_request(
        response_type, client_id, redirect_uri, scope, state)

    # Check if the user already has a token

# 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

    redirect_uri = _append_url_params(redirect_uri,
                                      access_token=token,
                                      token_type='bearer',
                                      scope='amiv',
                                      state=state)

    # If the user wants to be remembered, save the token as cookie
    # so the next time only 'confirm' needs to be pressed
    response = current_app.make_response(redirect(redirect_uri))
    if request.form.get('remember'):
        response.set_cookie('token', token)
    return response


@oauth_blueprint.route('/oauth', methods=['GET', 'POST'])
def oauth():
    """Endpoint for OAuth login. OAuth clients redirect users here."""
    response_type = request.args.get('response_type')
    client_id = request.args.get('client_id')
    redirect_uri = request.args.get('redirect_uri')
    scope = request.args.get('scope')
    state = request.args.get('state')
    token = request.cookies.get('token', '')
    error_msg = ''

    # Check this is a request by a proper client
    redirect_uri = validate_oauth_authorization_request(
        response_type, client_id, redirect_uri, scope, state)

    # Check if the user already has a token

    authenticate_token(token)