<?php

class SsoauthController extends Controller {

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('issuetoken', 'sslogin'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('index'),
                'expression' => '$user->isMember()',
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIssuetoken() {
        $username = Yii::app()->request->getParam('username');
        $condition = "t.sso_username='" . $username . "'";
        $model = User::model()->find(["condition" => $condition]);
        $token = CPasswordHelper::hashPassword($username . time());
        User::model()->updateByPk($model->id, ["sso_token" => $token, "token_time" => date("Y-m-d H:i:s")]);
        echo json_encode(["status" => "success", "token" => $token]);
    }

    public function actionSslogin() {
        $token = Yii::app()->request->getParam('token');
        $sso_username = Yii::app()->request->getParam('u');
        $condition = "t.sso_username='" . $sso_username . "'";
        $usermodel = User::model()->find(["condition" => $condition]);
        if ($usermodel->sso_token == $token) {
            $model = new LoginForm();
            $model->isSSO = true;
            $model->username = $usermodel->username;
            $model->password = $usermodel->password;
            if ($model->validate() && $model->login()) {
//                User::model()->updateByPk($usermodel->id, ["sso_token" => ""]);
                $this->redirect(["/site/index"]);
            } else {
                echo "Error in login";
            }
        } else {
            echo "Error in sign in $token";
        }
    }

}
