# coding:utf-8

from rest_framework.permissions import BasePermission
from django.contrib.sessions.models import Session
from django.utils import timezone
from smartfarming.models.user import DeviceUser
from kedong.utils import PrAes


class LoginPermission(BasePermission):

    def has_permission(self, request, view):
        token = request.data.get("token", "")
        if not token:
            return False
        try:
            ip = request.META['HTTP_X_FORWARDED_FOR']
        except Exception as e:
            ip = request.META['REMOTE_ADDR']
        if '%2B' in token or " " in token:
            token = str(token).replace("%2B", "+").replace(" ", "+")
        try:
            session_key = PrAes.aesdecrypt(token)
            sessions_obj = Session.objects.get(session_key=session_key)
            expired_time = sessions_obj.expire_date
            if timezone.now() >= expired_time:
                raise Exception()
            sessions = sessions_obj.get_decoded()
            try:
                value = sessions.get('user_id')
                uid = int(value)
                state = 1
                try:
                    auto_login_uid = int(sessions.get('auto_login_uid'))
                    temp_state = auto_login_uid - uid
                    if temp_state in [1, 4]:
                        state = temp_state
                except Exception as e:
                    pass
                device_user = DeviceUser.objects.get(uid=uid, state=state)
                request.myuser = device_user
                request.ip = ip
                try:
                    perm = device_user.perm(uid)
                    request.user_perm = perm
                    request.role_id = device_user.role_id
                    request.user_type = device_user.user_type
                except Exception:
                    request.user_perm = None
                    request.role_id = None
                    pass
            except Exception:
                request.myuser = None
                request.user_perm = None
                request.role_id = None
                return False
        except Exception as e:
            return False
        return True