# authentic2-auth-fc - authentic2 authentication for FranceConnect
# Copyright (C) 2019 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/>.

import base64
import hashlib
import hmac
import json
import urllib.parse

from django.conf import settings
from django.db import models
from django.utils.encoding import force_bytes, force_text
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _

from authentic2_auth_oidc.utils import parse_timestamp

from . import app_settings


def base64url_decode(encoded):
    rem = len(encoded) % 4
    if rem > 0:
        encoded += '=' * (4 - rem)
    return base64.urlsafe_b64decode(encoded)


def parse_id_token(id_token, client_id=None, client_secret=None):
    try:
        splitted = str(id_token).split('.')
    except Exception:
        return None, 'invalid id_token'
    if len(splitted) != 3:
        return None, 'invalid id_token'
    header, payload, signature = splitted
    try:
        signature = base64url_decode(signature)
    except (ValueError, TypeError):
        return None, 'invalid signature'
    signed = '%s.%s' % (header, payload)
    if client_secret is not None:
        h = hmac.HMAC(key=client_secret, msg=force_bytes(signed), digestmod=hashlib.sha256)
        if h.digest() != signature:
            return None, 'hmac signature does not match'
    payload = base64url_decode(str(payload))
    try:
        payload = json.loads(force_text(payload))
    except ValueError:
        return None, 'invalid payload'
    if client_id and ('aud' not in payload or payload['aud'] != client_id):
        return None, 'invalid audience'
    if 'exp' not in payload or parse_timestamp(payload['exp']) < now():
        return None, 'id_token is expired'

    def check_issuer():
        parsed = urllib.parse.urlparse(app_settings.authorize_url)
        if 'iss' not in payload:
            return False
        try:
            parsed_issuer = urllib.parse.urlparse(payload['iss'])
        except Exception:
            return False
        return parsed_issuer.scheme == parsed.scheme and parsed_issuer.netloc == parsed.netloc

    if not check_issuer():
        return None, 'wrong issuer received, %r' % payload['iss']
    return payload, None


class FcAccount(models.Model):
    created = models.DateTimeField(verbose_name=_('created'), auto_now_add=True)
    modified = models.DateTimeField(verbose_name=_('modified'), auto_now=True)
    user = models.ForeignKey(
        to=settings.AUTH_USER_MODEL,
        verbose_name=_('user'),
        related_name='fc_accounts',
        on_delete=models.CASCADE,
    )
    sub = models.TextField(verbose_name=_('sub'), db_index=True)
    order = models.PositiveIntegerField(verbose_name=_('order'), default=0)
    token = models.TextField(verbose_name=_('access token'), default='{}')
    user_info = models.TextField(verbose_name=_('access token'), null=True, default='{}')

    @property
    def id_token(self):
        return parse_id_token(self.get_token()['id_token'])

    def get_token(self):
        if self.token:
            return json.loads(self.token)
        else:
            return {}

    def get_user_info(self):
        if self.user_info:
            return json.loads(self.user_info)
        else:
            return {}

    def __str__(self):
        user_info = self.get_user_info()
        display_name = []
        if 'given_name' in user_info:
            display_name.append(user_info['given_name'])
        if 'family_name' in user_info:
            display_name.append(user_info['family_name'])
        return ' '.join(display_name)

    class Meta:
        unique_together = [
            ('sub', 'order'),
            ('user', 'order'),
        ]
