'''
@Author: hua
@Date: 2019-04-17 17:18:04
@LastEditors: hua
@LastEditTime: 2020-05-23 10:46:06
'''
from aiohttp.web import middleware
from aiohttp_session import get_session
from app.Model.Menu import Menu
from app.Model.Access import Access
from app.Vendor.tempDef import backStatus
from app.Vendor.ExceptionApi import ExceptionApi
from app.Vendor.Code import Code
from app import dBSession

""" 检查后端权限 """
@middleware
async def AdminCheck(request, handler):
    try:
        uncheckList = ['loginout']
        uncheckModule = ['Login', 'getCode', 'status']
        url = request.url.path.strip('/').split('/')
        isAdmin = url[0] if len(url)> 0 else ''
        controller = url[1] if len(url)> 1 else ''
        actionName = url[2] if len(url)> 2 else ''
        if isAdmin != 'fladmin':
            return await handler(request)
        if controller  in uncheckModule:
            return await handler(request)
        else:
            if actionName not in uncheckList:
                if controller != 'index' and actionName != 'index':
                    filters = {
                        Menu.controller ==  controller,
                        Menu.action == actionName
                    }
                    menu = Menu().getOne(filters, Menu.id.desc())
                    if menu != None:
                        menu_id = menu['id']
                    else:
                        return backStatus(request, '您暂时无权限浏览，请联系管理员', 0)
                    session = await get_session(request)
                    filters = {
                        Access.role_id == session['admin_info']['role_id'],
                        Access.menu_id == menu_id
                    }
                    check = Access().getOne(filters, Access.id.desc())
                        
                    if check == None:
                        return backStatus(request, '您暂时无权限浏览，请联系管理员', 0)
            return await handler(request)
    except Exception as e:
        dBSession.close()
        if hasattr(e, 'status'):
            if e.status == 404:
                return
        ExceptionApi(Code.ERROR, e)
