# -*- encoding: utf-8 -*-
# 项目：JDG-
# 模块名称：
# 描述：
# Copyright 2018 JDG <www.yunside.com>
# Created by wxh (xianhuo.weng@yunside.com) at  2020/7/1 - 17:22

from odoo.http import request
from odoo import http
from odoo.addons.web.controllers import main
from odoo.addons.web.controllers.main import ensure_db
from odoo.addons.web.controllers.main import login_and_redirect, set_cookie_and_redirect
from odoo.exceptions import AccessDenied, ValidationError
from core.middleware.template import TemplateTools

import werkzeug
import urllib2
import base64
import random
import math
import logging
from .pycas import login

_logger = logging.getLogger(__name__)


class CasController(http.Controller):
    
    @http.route('/cas/login/fail', auth='none')
    def user_not_found(self, **kwargs):
        info = kwargs.get('info', '')
        tmpl = TemplateTools()
        html = tmpl.render("/jd_base/template/cas/user_login_fail.html", data={'info': info})
        return html
    
    @http.route('/cas/login', auth='none')
    def index(self, ticket=None, hash=None):
        # print ticket
        # if request.session.uid:
        #     return set_cookie_and_redirect('/web')

        # 获取ticket
        open_login_auth_cas = request.env['ir.config_parameter'].sudo().get_param('open_login_auth_cas')
        is_open_cas = open_login_auth_cas == 'on'
        # 若未登陆
        if is_open_cas:
            service = request.httprequest.url_root + 'cas/login'
            if hash:
                service += '?hash=' + urllib2.quote(urllib2.quote(hash))

            if not ticket:
                # ticket不存在 跳转到认证平台
                cas_url = request.env['ir.config_parameter'].sudo().get_param('cas_url')
                redirect_url = cas_url + '/cas/login?service=' + service
                return werkzeug.utils.redirect(redirect_url, 301)

            cas_url = request.env['ir.config_parameter'].sudo().get_param('cas_url')

            result = login(cas_url, service, ticket)
            if result:
                status, username, cookie = result
                if username and status == 0:
                    # 获取eval拼接方法
                    cas_eval = request.env['ir.config_parameter'].sudo().get_param('cas_eval')
                    if cas_eval not in ['False', '0']:
                        try:
                            username = eval(cas_eval, {'login': username})
                        except Exception:
                            pass
                    user_rec = request.env['res.users'].sudo().search([('login', '=', username)], limit=1)
                    if user_rec:
                        user_rec.write({'cas_ticket': ticket})
                        request.env.cr.commit()
                        try:
                            path = '/web'
                            if hash:
                                path += '#' + hash
                            return login_and_redirect(request.db, username, ticket, path)
                        except AccessDenied:
                            values = {}
                            values['databases'] = http.db_list()
                            values['error'] = "用户名或密码错误"
                            return request.render('web.login', values)
                    else:
                        info = u'系统中用户[%s]不存在，请联系系统管理员开通' % username
                        return werkzeug.utils.redirect('/cas/login/fail?info=' + info, 303)
                else:
                    info = u'登录状态已失效，请关闭当前页面'
                    return werkzeug.utils.redirect('/cas/login/fail?info=' + info, 303)
        elif ticket and not is_open_cas:
            _logger.error(u'当前登录传入了ticket【%s】，但是未启用cas认证登录，请检查参数【open_login_auth_cas】是否打开' % ticket)


class Session(main.Session):
    @http.route('/web/session/logout', type='http', auth="none")
    def logout(self, redirect='/web'):
        open_login_auth_cas = request.env['ir.config_parameter'].sudo().get_param('open_login_auth_cas')
        is_open_cas = open_login_auth_cas == 'on'
        if is_open_cas:
            # 删除此次验证通过的ticket
            cr = request.env.cr
            sql = 'update res_users set cas_ticket = %s where id = %s'
            cr.execute(sql, ('', request.session.uid))
            cas_url = request.env['ir.config_parameter'].sudo().get_param('cas_url')
            service = request.httprequest.url_root + 'cas/login'
            redirect = cas_url + '/cas/logout?service=' + service
        request.session.logout(keep_db=True)
        return werkzeug.utils.redirect(redirect, 303)
