# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2016-2020 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# 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/>.

from django.contrib import admin
from django.shortcuts import redirect
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
from django.views.decorators.cache import never_cache

from .models import AccessRight, ApiUser


@never_cache
def login(request, *args, **kwargs):
    try:
        auth_login_url = reverse('auth_login')
    except NoReverseMatch:
        return admin.site.orig_login(request, *args, **kwargs)
    auth_login_url += '?%s' % request.GET.urlencode()
    return redirect(auth_login_url)


@never_cache
def logout(request, *args, **kwargs):
    try:
        return redirect(reverse('auth_logout'))
    except NoReverseMatch:
        return admin.site.orig_logout(request, *args, **kwargs)


if admin.site.login != login:
    admin.site.orig_login = admin.site.login
    admin.site.login = login

if admin.site.logout != logout:
    admin.site.orig_logout = admin.site.logout
    admin.site.logout = logout

admin.site.register(ApiUser)
admin.site.register(AccessRight)
