CASLogin.php 10.2 KB
Newer Older
1 2 3 4 5 6 7
<?php
namespace Drupal\casost\Controller;

use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;
8
use phpCAS;
9 10 11 12 13 14 15
use Drupal\user\Entity\User;
use Drupal\Core\Database\Connection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
16
use Symfony\Component\HttpFoundation\Cookie;
17
require ('RedirectResponseWithCookieExt.php');
18 19 20 21 22 23 24 25

class CASLogin extends ControllerBase
{

    protected $serverVersion;
    protected $serverHostname;
    protected $serverPort;
    protected $serverUri;
26
    protected $redirectUrl;
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    protected $changeSessionId;
    protected $CASServerCACert;
    protected $CASServerCNValidate;
    protected $noCASServerValidation;
    protected $proxy;
    protected $handleLogoutRequests;
    protected $CASLang;
    protected $allowed1;
    protected $allowed1Value;
    protected $allowed2;
    protected $allowed2Value;

    protected $entity_query;
    protected $entityTypeManager;
    protected $logger;
    protected $connection;

    public function __construct(
    EntityTypeManagerInterface $entityTypeManager,
    QueryFactory $entity_query,
    Connection $connection,
    LoggerChannelFactoryInterface $loggerChannel)
    {
        $this->entityTypeManager = $entityTypeManager;
        $this->entity_query = $entity_query;
        $this->connection = $connection;
        $this->logger = $loggerChannel->get('casost');

    }

57 58


59 60 61 62 63 64 65 66 67 68 69 70 71
    public static function create(ContainerInterface $container)
    {
        return new static(
          $container->get('entity.manager'),
          $container->get('entity.query'),
          $container->get('database'),
          $container->get('logger.factory')
      );
    }

    public function loginGo(Request $request)
    {

72
        $configRowName = 'casost_sch_sso_config';
73
        try {
74

75 76 77 78
            $configRowId = $request->query->get('config');
            if ($configRowId)
                $configRowName = $configRowName . '_' . $configRowId;
            $CASOSTConfigs = $this->entityTypeManager->getStorage('casost_config')->loadByProperties(array('name' => $configRowName));
79 80 81 82 83 84
            $CASOSTConfig = reset($CASOSTConfigs);
            if ($CASOSTConfig) {
                $this->serverVersion = $CASOSTConfig->serverversion->value;
                $this->serverHostname = $CASOSTConfig->serverhostname->value;
                $this->serverPort = $CASOSTConfig->serverport->value;
                $this->serverUri = $CASOSTConfig->serveruri->value === null ? '' : $CASOSTConfig->serveruri->value;
85
                $this->redirectUrl = $CASOSTConfig->redirecturl->value;
86 87 88 89 90 91 92 93 94 95 96 97
                $this->changeSessionId = $CASOSTConfig->changesessionid->value;
                $this->CASServerCACert = $CASOSTConfig->casservercacert->value;
                $this->CASServerCNValidate = $CASOSTConfig->casservercnvalidate->value;
                $this->noCASServerValidation = $CASOSTConfig->nocasservervalidation->value;
                $this->proxy = $CASOSTConfig->proxy->value;
                $this->handleLogoutRequests = $CASOSTConfig->handlelogoutrequests->value;
                $this->CASLang = $CASOSTConfig->caslang->value;
                $this->allowed1 = $CASOSTConfig->allowed1->value;
                $this->allowed1Value = $CASOSTConfig->allowed1value->value;
                $this->allowed2 = $CASOSTConfig->allowed2->value;
                $this->allowed2Value = $CASOSTConfig->allowed2value->value;
            }
98
            phpCAS::setDebug("phpcas.log");
99
            // Enable verbose error messages. Disable in production!
Open Source Developer's avatar
trans  
Open Source Developer committed
100
            //phpCAS::setVerbose(true);
101

102 103
            phpCAS::client(
                $this->serverVersion,
104 105 106
                $this->serverHostname,
                intval($this->serverPort),
                $this->serverUri,
107 108
                boolval($this->changeSessionId)
            );
109 110 111

            if ($this->CASServerCACert) {
                if ($this->CASServerCNValidate) {
112
                    phpCAS::setCasServerCACert($this->CASServerCACert, true);
113
                } else {
114
                    phpCAS::setCasServerCACert($this->CASServerCACert, false);
115 116 117
                }
            }
            if ($this->noCASServerValidation) {
118
                phpCAS::setNoCasServerValidation();
119
            }
120 121
            phpCAS::handleLogoutRequests();
            if (!phpCAS::forceAuthentication()) {
122
                return $this->redirectForbidden($configRowName, '5001');
123
            }
124
            $attributes = phpCAS::getAttributes();
125

126
            $CASUser = phpCAS::getUser();
127 128 129 130 131

            $this->logger->warning($CASUser);

            $filterAttribute = function ($attribute) use ($attributes) {
                if (!isset($attributes[$attribute])) {
132
                    return false;
133 134 135 136
                }
                return $attributes[$attribute];
            };

137
            $umdobject = $filterAttribute("umdobject");
138

139
            phpCAS::trace($umdobject);
140 141
//            phpCAS::trace($physicaldeliveryofficename);
    //        $gsnunitcodedn = $filterAttribute('edupersonorgunitdn:gsnunitcode:extended');
142
    //        $gsnunitcode = substr($gsnunitcodedn, strpos($gsnunitcodedn, ";") + 1);
143
            $gsnunitcode = $filterAttribute('edupersonorgunitdn:gsnunitcode');
144 145 146 147 148 149 150 151 152
/* check if myschool account */
            if (!$umdobject || $umdobject !== "ISaccount") {
                return $this->redirectForbidden($configRowName, '5002');
            }
            if (!$gsnunitcode || $gsnunitcode !== $CASUser) {
                return $this->redirectForbidden($configRowName, '5003');
            }
/* end of checking myschool account */

153
            $userAssigned = $this->assignRoleToUser($gsnunitcode);
154

155 156
            if (sizeof($userAssigned) === 0) {
                return $this->redirectForbidden($configRowName, '5004');
157 158
            }

159
            $epalToken = $this->authenticatePhase2($request, $CASUser, $userAssigned, $filterAttribute('cn'));
160
            if ($epalToken) {
161
                if ('casost_sch_sso_config' === $configRowName) {
162
                    return new RedirectResponse($this->redirectUrl . $epalToken.'&auth_role=' . $userAssigned["exposedRole"], 302, []);
163
                } else {
164
                    \Drupal::service('page_cache_kill_switch')->trigger();
165
                    return new RedirectResponseWithCookieExt($this->redirectUrl . $epalToken.'&auth_role=' . $userAssigned["exposedRole"], 302, []);
166
                }
167
            } else {
168
                return $this->redirectForbidden($configRowName, '5005');
169 170 171 172
            }

        } catch (\Exception $e) {
            $this->logger->warning($e->getMessage());
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
            return $this->redirectForbidden($configRowName, '6000');
        }
    }

    private function assignRoleToUser($registry_no) {
        $schools = $this->entityTypeManager->getStorage('eepal_school')->loadByProperties(array('registry_no' => $registry_no));
        $school = reset($schools);
        if ($school) {
            return array("id" => $school->id(), "exposedRole" => "director", "internalRole" => "epal");
        }
        $eduAdmins = $this->entityTypeManager->getStorage('eepal_admin_area')->loadByProperties(array('registry_no' => $registry_no));
        $eduAdmin = reset($eduAdmins);
        if ($eduAdmin) {
            return array("id" => $eduAdmin->id(), "exposedRole" => "dide", "internalRole" => "eduadmin");
        }
        $regionAdmins = $this->entityTypeManager->getStorage('eepal_region')->loadByProperties(array('registry_no' => $registry_no));
        $regionAdmin = reset($regionAdmins);
        if ($regionAdmin) {
            return array("id" => $regionAdmin->id(), "exposedRole" => "pde", "internalRole" => "regioneduadmin");
        }
        return array();

    }

    private function redirectForbidden($configRowName, $errorCode) {
        session_unset();
        session_destroy();
        \Drupal::service('page_cache_kill_switch')->trigger();
        if ('casost_sch_sso_config' === $configRowName) {
            return new RedirectResponse($this->redirectUrl.'&error_code=' . $errorCode, 302, []);
        } else {
            return new RedirectResponseWithCookieExt($this->redirectUrl .'&error_code=' . $errorCode, 302, []);
205 206 207
        }
    }

208
    private function authenticatePhase2($request, $CASUser, $userAssigned, $cn)
209 210 211 212 213 214 215 216 217 218 219 220 221
    {
    $trx = $this->connection->startTransaction();
    try {

        $currentTime = time();

        $epalToken = md5(uniqid(mt_rand(), true));

            $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('mail' => $CASUser));
            $user = reset($users);
            if ($user) {
                $user->setPassword($epalToken);
                $user->setUsername($epalToken);
222
                $user->set('init', $userAssigned["id"]);
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
                $user->save();
            }


        if ($user === null || !$user) {

            //Create a User
            $user = User::create();
            //Mandatory settings
            $unique_id = uniqid('####');
            $user->setPassword($epalToken);
            $user->enforceIsNew();
            $user->setEmail($CASUser);
            $user->setUsername($epalToken); //This username must be unique and accept only a-Z,0-9, - _ @ .
            $user->activate();
238 239
//            $user->set('init', $cn);
            $user->set('init', $userAssigned["id"]);
240 241 242 243 244 245 246 247

            //Set Language
            $language_interface = \Drupal::languageManager()->getCurrentLanguage();
            $user->set('langcode', $language_interface->getId());
            $user->set('preferred_langcode', $language_interface->getId());
            $user->set('preferred_admin_langcode', $language_interface->getId());

            //Adding default user role
248
            $user->addRole($userAssigned["internalRole"]);
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
            $user->save();
        }

        return $epalToken;
    } catch (OAuthException $e) {
        $this->logger->warning($e->getMessage());
        $trx->rollback();
        return false;
    } catch (\Exception $ee) {
        $this->logger->warning($ee->getMessage());
        $trx->rollback();
        return false;
    }

        return false;
    }

266
}