diff --git a/.gitignore b/.gitignore index 2a359b1810781708bd2f3ecc4008be77b945aa64..f01cd9e7ed0e0b700cce470b8b69593cc9359d57 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ drupal/modules/* !drupal/modules/epal/ !drupal/modules/epalreadydata/ !drupal/modules/oauthost/ +!drupal/modules/casost/ !drupal/modules/epaldeploysystem/ # Logs diff --git a/drupal/modules/casost/casost.info.yml b/drupal/modules/casost/casost.info.yml new file mode 100644 index 0000000000000000000000000000000000000000..b77024e5fb2780c1272031ad94512b4b350a54bd --- /dev/null +++ b/drupal/modules/casost/casost.info.yml @@ -0,0 +1,5 @@ +name: casost +type: module +description: Authentication Provider OST +core: 8.x +package: casost diff --git a/drupal/modules/casost/casost.links.action.yml b/drupal/modules/casost/casost.links.action.yml new file mode 100644 index 0000000000000000000000000000000000000000..901e5012b5f784074639309e199f5d22853bea67 --- /dev/null +++ b/drupal/modules/casost/casost.links.action.yml @@ -0,0 +1,10 @@ +entity.casost_config.add_form: + route_name: entity.casost_config.add_form + title: 'Add CASOST Config' + appears_on: + - entity.casost_config.collection +entity.casost_session.add_form: + route_name: entity.casost_session.add_form + title: 'Add CASOST Session' + appears_on: + - entity.casost_session.collection diff --git a/drupal/modules/casost/casost.links.menu.yml b/drupal/modules/casost/casost.links.menu.yml new file mode 100644 index 0000000000000000000000000000000000000000..58d508fe9793e195048b4e5ec8206a525c6c6866 --- /dev/null +++ b/drupal/modules/casost/casost.links.menu.yml @@ -0,0 +1,28 @@ + +# CASOST Config menu items definition +entity.casost_config.collection: + title: 'CASOST Config list' + route_name: entity.casost_config.collection + description: 'List CASOST Config entities' + parent: system.admin_structure + weight: 100 + +casost_config.admin.structure.settings: + title: CASOST Config settings + description: 'Configure CASOST Config entities' + route_name: casost_config.settings + parent: system.admin_structure + +# CASOST Session menu items definition +entity.casost_session.collection: + title: 'CASOST Session list' + route_name: entity.casost_session.collection + description: 'List CASOST Session entities' + parent: system.admin_structure + weight: 100 + +casost_session.admin.structure.settings: + title: CASOST Session settings + description: 'Configure CASOST Session entities' + route_name: casost_session.settings + parent: system.admin_structure diff --git a/drupal/modules/casost/casost.links.task.yml b/drupal/modules/casost/casost.links.task.yml new file mode 100644 index 0000000000000000000000000000000000000000..ba40346a5a18a1e5d2a3d71217da90fdc64ad2b7 --- /dev/null +++ b/drupal/modules/casost/casost.links.task.yml @@ -0,0 +1,43 @@ +# CASOST Config routing definition +casost_config.settings_tab: + route_name: casost_config.settings + title: 'Settings' + base_route: casost_config.settings + +entity.casost_config.canonical: + route_name: entity.casost_config.canonical + base_route: entity.casost_config.canonical + title: 'View' + +entity.casost_config.edit_form: + route_name: entity.casost_config.edit_form + base_route: entity.casost_config.canonical + title: 'Edit' + +entity.casost_config.delete_form: + route_name: entity.casost_config.delete_form + base_route: entity.casost_config.canonical + title: Delete + weight: 10 + +# CASOST Session routing definition +casost_session.settings_tab: + route_name: casost_session.settings + title: 'Settings' + base_route: casost_session.settings + +entity.casost_session.canonical: + route_name: entity.casost_session.canonical + base_route: entity.casost_session.canonical + title: 'View' + +entity.casost_session.edit_form: + route_name: entity.casost_session.edit_form + base_route: entity.casost_session.canonical + title: 'Edit' + +entity.casost_session.delete_form: + route_name: entity.casost_session.delete_form + base_route: entity.casost_session.canonical + title: Delete + weight: 10 diff --git a/drupal/modules/casost/casost.module b/drupal/modules/casost/casost.module new file mode 100644 index 0000000000000000000000000000000000000000..94ab174c050b32cc75a8348e095b5fa3f8112d45 --- /dev/null +++ b/drupal/modules/casost/casost.module @@ -0,0 +1,36 @@ +' . t('About') . ''; + $output .= '

' . t('Authentication Provider OST') . '

'; + return $output; + + default: + } +} + +/** + * Implements hook_theme(). + */ +function casost_theme() { + return [ + 'casost' => [ + 'template' => 'casost', + 'render element' => 'children', + ], + ]; +} diff --git a/drupal/modules/casost/casost.permissions.yml b/drupal/modules/casost/casost.permissions.yml new file mode 100644 index 0000000000000000000000000000000000000000..50bf5ff48bb19675102b453d856d7d89b3c68650 --- /dev/null +++ b/drupal/modules/casost/casost.permissions.yml @@ -0,0 +1,44 @@ +add casost config entities: + title: 'Create new CASOST Config entities' + +administer casost config entities: + title: 'Administer CASOST Config entities' + description: 'Allow to access the administration form to configure CASOST Config entities.' + restrict access: true + +delete casost config entities: + title: 'Delete CASOST Config entities' + +edit casost config entities: + title: 'Edit CASOST Config entities' + +access casost config overview: + title: 'Access the CASOST Config overview page' + +view published casost config entities: + title: 'View published CASOST Config entities' + +view unpublished casost config entities: + title: 'View unpublished CASOST Config entities' +add casost session entities: + title: 'Create new CASOST Session entities' + +administer casost session entities: + title: 'Administer CASOST Session entities' + description: 'Allow to access the administration form to configure CASOST Session entities.' + restrict access: true + +delete casost session entities: + title: 'Delete CASOST Session entities' + +edit casost session entities: + title: 'Edit CASOST Session entities' + +access casost session overview: + title: 'Access the CASOST Session overview page' + +view published casost session entities: + title: 'View published CASOST Session entities' + +view unpublished casost session entities: + title: 'View unpublished CASOST Session entities' diff --git a/drupal/modules/casost/casost.routing.yml b/drupal/modules/casost/casost.routing.yml new file mode 100644 index 0000000000000000000000000000000000000000..7f0f3e40b8ebcd6825e40bf7b3424d6d04a5402d --- /dev/null +++ b/drupal/modules/casost/casost.routing.yml @@ -0,0 +1,14 @@ +casost.log_in_go: + path: /cas/login + defaults: + _controller: '\Drupal\casost\Controller\CASLogin::loginGo' + requirements: + _access: 'TRUE' +casost.log_out_go: + path: /cas/logout + options: + _auth: [ 'basic_auth' ] + defaults: + _controller: '\Drupal\casost\Controller\CASLogout::logoutGo' + requirements: + _user_is_logged_in: 'TRUE' diff --git a/drupal/modules/casost/casost.services.yml b/drupal/modules/casost/casost.services.yml new file mode 100644 index 0000000000000000000000000000000000000000..57cdb9ab18092fcf15c1f03febe9c93c04bef341 --- /dev/null +++ b/drupal/modules/casost/casost.services.yml @@ -0,0 +1,4 @@ +services: + logger.channel.cas: + parent: 'logger.channel_base' + arguments: ['epal'] diff --git a/drupal/modules/casost/casost_config.page.inc b/drupal/modules/casost/casost_config.page.inc new file mode 100644 index 0000000000000000000000000000000000000000..a2e96c1415e087d47c227e29b4bf27eba195142c --- /dev/null +++ b/drupal/modules/casost/casost_config.page.inc @@ -0,0 +1,30 @@ +isPublished()) { + return AccessResult::allowedIfHasPermission($account, 'view unpublished casost config entities'); + } + return AccessResult::allowedIfHasPermission($account, 'view published casost config entities'); + + case 'update': + return AccessResult::allowedIfHasPermission($account, 'edit casost config entities'); + + case 'delete': + return AccessResult::allowedIfHasPermission($account, 'delete casost config entities'); + } + + // Unknown operation, no opinion. + return AccessResult::neutral(); + } + + /** + * {@inheritdoc} + */ + protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) { + return AccessResult::allowedIfHasPermission($account, 'add casost config entities'); + } + +} diff --git a/drupal/modules/casost/src/CASOSTConfigHtmlRouteProvider.php b/drupal/modules/casost/src/CASOSTConfigHtmlRouteProvider.php new file mode 100644 index 0000000000000000000000000000000000000000..7597fbdd9fdbbcc33a348d1cc9e0ec44f45de2e8 --- /dev/null +++ b/drupal/modules/casost/src/CASOSTConfigHtmlRouteProvider.php @@ -0,0 +1,85 @@ +id(); + + if ($collection_route = $this->getCollectionRoute($entity_type)) { + $collection->add("entity.{$entity_type_id}.collection", $collection_route); + } + + if ($settings_form_route = $this->getSettingsFormRoute($entity_type)) { + $collection->add("$entity_type_id.settings", $settings_form_route); + } + + return $collection; + } + + /** + * Gets the collection route. + * + * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type + * The entity type. + * + * @return \Symfony\Component\Routing\Route|null + * The generated route, if available. + */ + protected function getCollectionRoute(EntityTypeInterface $entity_type) { + if ($entity_type->hasLinkTemplate('collection') && $entity_type->hasListBuilderClass()) { + $entity_type_id = $entity_type->id(); + $route = new Route($entity_type->getLinkTemplate('collection')); + $route + ->setDefaults([ + '_entity_list' => $entity_type_id, + '_title' => "{$entity_type->getLabel()} list", + ]) + ->setRequirement('_permission', 'access casost config overview') + ->setOption('_admin_route', TRUE); + + return $route; + } + } + + /** + * Gets the settings form route. + * + * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type + * The entity type. + * + * @return \Symfony\Component\Routing\Route|null + * The generated route, if available. + */ + protected function getSettingsFormRoute(EntityTypeInterface $entity_type) { + if (!$entity_type->getBundleEntityType()) { + $route = new Route("/admin/structure/{$entity_type->id()}/settings"); + $route + ->setDefaults([ + '_form' => 'Drupal\casost\Form\CASOSTConfigSettingsForm', + '_title' => "{$entity_type->getLabel()} settings", + ]) + ->setRequirement('_permission', $entity_type->getAdminPermission()) + ->setOption('_admin_route', TRUE); + + return $route; + } + } + +} diff --git a/drupal/modules/casost/src/CASOSTConfigListBuilder.php b/drupal/modules/casost/src/CASOSTConfigListBuilder.php new file mode 100644 index 0000000000000000000000000000000000000000..28c23d9abff11305b10c696421e5e694b83f6835 --- /dev/null +++ b/drupal/modules/casost/src/CASOSTConfigListBuilder.php @@ -0,0 +1,45 @@ +t('CASOST Config ID'); + $header['name'] = $this->t('Name'); + return $header + parent::buildHeader(); + } + + /** + * {@inheritdoc} + */ + public function buildRow(EntityInterface $entity) { + /* @var $entity \Drupal\casost\Entity\CASOSTConfig */ + $row['id'] = $entity->id(); + $row['name'] = $this->l( + $entity->label(), + new Url( + 'entity.casost_config.edit_form', array( + 'casost_config' => $entity->id(), + ) + ) + ); + return $row + parent::buildRow($entity); + } + +} diff --git a/drupal/modules/casost/src/CASOSTSessionAccessControlHandler.php b/drupal/modules/casost/src/CASOSTSessionAccessControlHandler.php new file mode 100644 index 0000000000000000000000000000000000000000..0ef78656945783b27f35fcf3e75d8fcd0b741072 --- /dev/null +++ b/drupal/modules/casost/src/CASOSTSessionAccessControlHandler.php @@ -0,0 +1,47 @@ +isPublished()) { + return AccessResult::allowedIfHasPermission($account, 'view unpublished casost session entities'); + } + return AccessResult::allowedIfHasPermission($account, 'view published casost session entities'); + + case 'update': + return AccessResult::allowedIfHasPermission($account, 'edit casost session entities'); + + case 'delete': + return AccessResult::allowedIfHasPermission($account, 'delete casost session entities'); + } + + // Unknown operation, no opinion. + return AccessResult::neutral(); + } + + /** + * {@inheritdoc} + */ + protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) { + return AccessResult::allowedIfHasPermission($account, 'add casost session entities'); + } + +} diff --git a/drupal/modules/casost/src/CASOSTSessionHtmlRouteProvider.php b/drupal/modules/casost/src/CASOSTSessionHtmlRouteProvider.php new file mode 100644 index 0000000000000000000000000000000000000000..3acd122a968d89b79f210b90332868c69d59e482 --- /dev/null +++ b/drupal/modules/casost/src/CASOSTSessionHtmlRouteProvider.php @@ -0,0 +1,85 @@ +id(); + + if ($collection_route = $this->getCollectionRoute($entity_type)) { + $collection->add("entity.{$entity_type_id}.collection", $collection_route); + } + + if ($settings_form_route = $this->getSettingsFormRoute($entity_type)) { + $collection->add("$entity_type_id.settings", $settings_form_route); + } + + return $collection; + } + + /** + * Gets the collection route. + * + * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type + * The entity type. + * + * @return \Symfony\Component\Routing\Route|null + * The generated route, if available. + */ + protected function getCollectionRoute(EntityTypeInterface $entity_type) { + if ($entity_type->hasLinkTemplate('collection') && $entity_type->hasListBuilderClass()) { + $entity_type_id = $entity_type->id(); + $route = new Route($entity_type->getLinkTemplate('collection')); + $route + ->setDefaults([ + '_entity_list' => $entity_type_id, + '_title' => "{$entity_type->getLabel()} list", + ]) + ->setRequirement('_permission', 'access casost session overview') + ->setOption('_admin_route', TRUE); + + return $route; + } + } + + /** + * Gets the settings form route. + * + * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type + * The entity type. + * + * @return \Symfony\Component\Routing\Route|null + * The generated route, if available. + */ + protected function getSettingsFormRoute(EntityTypeInterface $entity_type) { + if (!$entity_type->getBundleEntityType()) { + $route = new Route("/admin/structure/{$entity_type->id()}/settings"); + $route + ->setDefaults([ + '_form' => 'Drupal\casost\Form\CASOSTSessionSettingsForm', + '_title' => "{$entity_type->getLabel()} settings", + ]) + ->setRequirement('_permission', $entity_type->getAdminPermission()) + ->setOption('_admin_route', TRUE); + + return $route; + } + } + +} diff --git a/drupal/modules/casost/src/CASOSTSessionListBuilder.php b/drupal/modules/casost/src/CASOSTSessionListBuilder.php new file mode 100644 index 0000000000000000000000000000000000000000..c9e2c974bec2da3c25bca81ef45281920fd6fc48 --- /dev/null +++ b/drupal/modules/casost/src/CASOSTSessionListBuilder.php @@ -0,0 +1,45 @@ +t('CASOST Session ID'); + $header['name'] = $this->t('Name'); + return $header + parent::buildHeader(); + } + + /** + * {@inheritdoc} + */ + public function buildRow(EntityInterface $entity) { + /* @var $entity \Drupal\casost\Entity\CASOSTSession */ + $row['id'] = $entity->id(); + $row['name'] = $this->l( + $entity->label(), + new Url( + 'entity.casost_session.edit_form', array( + 'casost_session' => $entity->id(), + ) + ) + ); + return $row + parent::buildRow($entity); + } + +} diff --git a/drupal/modules/casost/src/Controller/CASLogin.php b/drupal/modules/casost/src/Controller/CASLogin.php new file mode 100644 index 0000000000000000000000000000000000000000..ff6fd7c16f26227e689e690aa0977bf2978a747f --- /dev/null +++ b/drupal/modules/casost/src/Controller/CASLogin.php @@ -0,0 +1,256 @@ +entityTypeManager = $entityTypeManager; + $this->entity_query = $entity_query; + $this->connection = $connection; + $this->logger = $loggerChannel->get('casost'); + + } + + + + 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) + { + + try { + + $CASOSTConfigs = $this->entityTypeManager->getStorage('casost_config')->loadByProperties(array('name' => 'casost_sch_sso_config')); + $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; + $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; + } +// phpCAS::setDebug("/home/haris/devel/eepal/drupal/modules/casost/phpcas.log"); + // Enable verbose error messages. Disable in production! + phpCAS::setVerbose(true); + + phpCAS::client($this->serverVersion, + $this->serverHostname, + intval($this->serverPort), + $this->serverUri, + boolval($this->changeSessionId)); + + +// \phpCAS::setServerLoginURL('http://sso-test.sch.gr/login'); +// \phpCAS::setServerServiceValidateURL('http://sso-test.sch.gr/cas/samlValidate'); + + if ($this->CASServerCACert) { + if ($this->CASServerCNValidate) { + phpCAS::setCasServerCACert($this->CASServerCACert, true); + } else { + phpCAS::setCasServerCACert($this->CASServerCACert, false); + } + } + if ($this->noCASServerValidation) { + phpCAS::setNoCasServerValidation(); + } + phpCAS::handleLogoutRequests(); + if (!phpCAS::forceAuthentication()) { + $response = new Response(); + $response->setContent('forbidden. cannot force authentication'); + $response->setStatusCode(Response::HTTP_FORBIDDEN); + $response->headers->set('Content-Type', 'application/json'); + return $response; + } + $attributes = phpCAS::getAttributes(); + +/* $isAllowed = true; + $att1 = $attributes[$this->allowed1]; + $att2 = $attributes[$this->allowed2]; + if (!isset($att1) || !isset($att2)) { + $isAllowed = false; + } + if (!is_array($attributes[$this->allowed1])) { + $attributes[$this->allowed1] = [$attributes[$this->allowed1]]; + } + if (!is_array($attributes[$this->allowed2])) { + $attributes[$this->allowed2] = [$attributes[$this->allowed2]]; + } + $found1 = false; + foreach ($attributes[$this->allowed1] as $value) { + if (1 === preg_match($this->allowed1Value, $value)) { + $found1 = true; + } + } + $found2 = false; + foreach ($attributes[$this->allowed2] as $value) { + if (1 === preg_match($this->allowed2Value, $value)) { + $found2 = true; + } + } + if (!$found1 || !$found2) { + $isAllowed = false; + } */ + + /* if (!$isAllowed) { + $response = new Response(); + $response->setContent(t('Access is allowed only to official school accounts')); + $response->setStatusCode(Response::HTTP_FORBIDDEN); + $response->headers->set('Content-Type', 'application/json;charset=UTF-8'); + return $response; + } */ + $CASUser = phpCAS::getUser(); + + $this->logger->warning($CASUser); + + $filterAttribute = function ($attribute) use ($attributes) { + if (!isset($attributes[$attribute])) { + return; + } + + if (is_array($attributes[$attribute])) { + return $attributes[$attribute]; + } + + return $attributes[$attribute]; + }; + +// $this->logger->warning('cn=' . $filterAttribute('cn')); + $epalToken = $this->authenticatePhase2($request, $CASUser, $filterAttribute('cn')); + if ($epalToken) { + + return new RedirectResponse('/dist/#/school?auth_token=' . $epalToken.'&auth_role=director', 302, []); + } else { + $response = new Response(); + $response->setContent('forbidden'); + $response->setStatusCode(Response::HTTP_FORBIDDEN); + $response->headers->set('Content-Type', 'application/json'); + return $response; + } + + } catch (\Exception $e) { + $this->logger->warning($e->getMessage()); + $response = new Response(); + $response->setContent('forbidden'); + $response->setStatusCode(Response::HTTP_FORBIDDEN); + $response->headers->set('Content-Type', 'application/json'); + return $response; + } + } + + public function authenticatePhase2($request, $CASUser, $cn) + { + $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); + $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(); + $user->set('init', $cn); + + //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 + $user->addRole('epal'); + $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; + } + +} diff --git a/drupal/modules/casost/src/Controller/CASLogout.php b/drupal/modules/casost/src/Controller/CASLogout.php new file mode 100644 index 0000000000000000000000000000000000000000..639f327adcd8da6877aca917ca3f64876dd95adc --- /dev/null +++ b/drupal/modules/casost/src/Controller/CASLogout.php @@ -0,0 +1,139 @@ +entityTypeManager = $entityTypeManager; + $this->entity_query = $entity_query; + $this->connection = $connection; + $this->logger = $loggerChannel->get('casost'); + } + + 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 logoutGo(Request $request) + { + try { + $CASOSTConfigs = $this->entityTypeManager->getStorage('casost_config')->loadByProperties(array('name' => 'casost_sch_sso_config')); + $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; + $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; + } else { + $response = new Response(); + $response->setContent('forbidden. No config'); + $response->setStatusCode(Response::HTTP_FORBIDDEN); + $response->headers->set('Content-Type', 'application/json'); + return $response; + } + + + + // Enable debugging +// phpCAS::setDebug("/home/haris/devel/eepal/drupal/modules/casost/phpcas.log"); + // Enable verbose error messages. Disable in production! + phpCAS::setVerbose(true); + + // Initialize phpCAS + phpCAS::client($this->serverVersion, + $this->serverHostname, + intval($this->serverPort), + $this->serverUri, + boolval($this->changeSessionId)); + + $authToken = $request->headers->get('PHP_AUTH_USER'); + $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken)); + $user = reset($users); + + if (!$user) { + $this->logger->warning("user not found"); + $response = new Response(); + $response->setContent('forbidden'); + $response->setStatusCode(Response::HTTP_FORBIDDEN); + $response->headers->set('Content-Type', 'application/json'); + return $response; + } +// phpCAS::handleLogoutRequests(); +// phpCAS::logout(); + $user->setPassword(uniqid('pw')); + $user->save(); + $response = new Response(); + $response->setContent('logout successful'); + $response->setStatusCode(Response::HTTP_OK); + $response->headers->set('Content-Type', 'application/json'); + $this->logger->warning("/dist/#/school?auth_token=&auth_role="); +// return new RedirectResponse('/dist/#/school?auth_token=&auth_role=', 302, []); + return $response; + } catch (\Exception $e) { + $this->logger->warning($e->getMessage()); + $response = new Response(); + $response->setContent('forbidden'); + $response->setStatusCode(Response::HTTP_FORBIDDEN); + $response->headers->set('Content-Type', 'application/json'); + return $response; + } + } + +} diff --git a/drupal/modules/casost/src/Entity/CASOSTConfig.php b/drupal/modules/casost/src/Entity/CASOSTConfig.php new file mode 100644 index 0000000000000000000000000000000000000000..93c5311765506c781f7b23495ad5a64ae4951de3 --- /dev/null +++ b/drupal/modules/casost/src/Entity/CASOSTConfig.php @@ -0,0 +1,469 @@ + \Drupal::currentUser()->id(), + ); + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return $this->get('name')->value; + } + + /** + * {@inheritdoc} + */ + public function setName($name) + { + $this->set('name', $name); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function getCreatedTime() + { + return $this->get('created')->value; + } + + /** + * {@inheritdoc} + */ + public function setCreatedTime($timestamp) + { + $this->set('created', $timestamp); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function getOwner() + { + return $this->get('user_id')->entity; + } + + /** + * {@inheritdoc} + */ + public function getOwnerId() + { + return $this->get('user_id')->target_id; + } + + /** + * {@inheritdoc} + */ + public function setOwnerId($uid) + { + $this->set('user_id', $uid); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function setOwner(UserInterface $account) + { + $this->set('user_id', $account->id()); + + return $this; + } + + /** + * {@inheritdoc} + */ + public function isPublished() + { + return (bool) $this->getEntityKey('status'); + } + + /** + * {@inheritdoc} + */ + public function setPublished($published) + { + $this->set('status', $published ? true : false); + + return $this; + } + + /** + * {@inheritdoc} + */ + public static function baseFieldDefinitions(EntityTypeInterface $entity_type) + { + $fields = parent::baseFieldDefinitions($entity_type); + + $fields['user_id'] = BaseFieldDefinition::create('entity_reference') + ->setLabel(t('Authored by')) + ->setDescription(t('The user ID of author of the CASOST Config entity.')) + ->setRevisionable(true) + ->setSetting('target_type', 'user') + ->setSetting('handler', 'default') + ->setTranslatable(true) + ->setDisplayOptions('view', array( + 'label' => 'hidden', + 'type' => 'author', + 'weight' => 0, + )) + ->setDisplayOptions('form', array( + 'type' => 'entity_reference_autocomplete', + 'weight' => 5, + 'settings' => array( + 'match_operator' => 'CONTAINS', + 'size' => '60', + 'autocomplete_type' => 'tags', + 'placeholder' => '', + ), + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + $fields['name'] = BaseFieldDefinition::create('string') + ->setLabel(t('Name')) + ->setDescription(t('The name of the CASOST Config entity.')) + ->setSettings(array( + 'max_length' => 50, + 'text_processing' => 0, + )) + ->setDefaultValue('casost_sch_sso_config') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + $fields['serverversion'] = BaseFieldDefinition::create('string') + ->setLabel(t('Server Version')) + ->setDescription(t('The Server Version')) + ->setSettings(array( + 'max_length' => 200, + 'text_processing' => 0, + )) + ->setDefaultValue('S1') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + $fields['serverhostname'] = BaseFieldDefinition::create('string') + ->setLabel(t('Server Hostname')) + ->setDescription(t('The Server Hostname')) + ->setSettings(array( + 'max_length' => 200, + 'text_processing' => 0, + )) + ->setDefaultValue('sso-test.sch.gr') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + $fields['serverport'] = BaseFieldDefinition::create('integer') + ->setLabel(t('User Authorization Url')) + ->setDescription(t('The User Authorization Url')) + ->setSettings(array( + 'max_length' => 10, + 'text_processing' => 0, + )) + ->setDefaultValue('443') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + $fields['serveruri'] = BaseFieldDefinition::create('string') + ->setLabel(t('Server Uri')) + ->setDescription(t('The Server Uri')) + ->setSettings(array( + 'max_length' => 200, + 'text_processing' => 0, + )) + ->setDefaultValue('') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + $fields['changesessionid'] = BaseFieldDefinition::create('boolean') + ->setLabel(t('Change Session Id')) + ->setDescription(t('A boolean indicating whether we change session id.')) + ->setDefaultValue(false); + + $fields['casservercacert'] = BaseFieldDefinition::create('string') + ->setLabel(t('CAS Server CaCert')) + ->setDescription(t('The Cas Server CaCert')) + ->setSettings(array( + 'max_length' => 1000, + 'text_processing' => 0, + )) + ->setDefaultValue('') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + $fields['casservercnvalidate'] = BaseFieldDefinition::create('string') + ->setLabel(t('CAS Server Cn Validate')) + ->setDescription(t('The CAS Server Cn Validate')) + ->setSettings(array( + 'max_length' => 1000, + 'text_processing' => 0, + )) + ->setDefaultValue('') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + $fields['nocasservervalidation'] = BaseFieldDefinition::create('boolean') + ->setLabel(t('no CAS Server Validation')) + ->setDescription(t('A boolean indicating whether we do CAS server validation.')) + ->setDefaultValue(true); + + $fields['proxy'] = BaseFieldDefinition::create('boolean') + ->setLabel(t('proxy')) + ->setDescription(t('A boolean indicating whether we proxy.')) + ->setDefaultValue(false); + + $fields['handlelogoutrequests'] = BaseFieldDefinition::create('boolean') + ->setLabel(t('Handle Logout Requests')) + ->setDescription(t('A boolean indicating whether logout requests are handled.')) + ->setDefaultValue(true); + + $fields['caslang'] = BaseFieldDefinition::create('string') + ->setLabel(t('Language')) + ->setDescription(t('Language')) + ->setSettings(array( + 'max_length' => 100, + 'text_processing' => 0, + )) + ->setDefaultValue('CAS_Languages_Greek') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + $fields['allowed1'] = BaseFieldDefinition::create('string') + ->setLabel(t('Allowed attribute 1')) + ->setDescription(t('Allowed Attribute 1')) + ->setSettings(array( + 'max_length' => 200, + 'text_processing' => 0, + )) + ->setDefaultValue('physicaldeliveryofficename') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + $fields['allowed1value'] = BaseFieldDefinition::create('string') + ->setLabel(t('Allowed attribute 1 Value')) + ->setDescription(t('Allowed Attribute 1 Value')) + ->setSettings(array( + 'max_length' => 200, + 'text_processing' => 0, + )) + ->setDefaultValue('/^ΕΠΙΣΗΜΟΣ ΛΟΓΑΡΙΑΣΜΟΣ$/i') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + $fields['allowed2'] = BaseFieldDefinition::create('string') + ->setLabel(t('Allowed attribute 2')) + ->setDescription(t('Allowed Attribute 2')) + ->setSettings(array( + 'max_length' => 200, + 'text_processing' => 0, + )) + ->setDefaultValue('umdobject') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + $fields['allowed2value'] = BaseFieldDefinition::create('string') + ->setLabel(t('Allowed attribute 2 Value')) + ->setDescription(t('Allowed Attribute 2 Value')) + ->setSettings(array( + 'max_length' => 200, + 'text_processing' => 0, + )) + ->setDefaultValue('/^account$/i') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', true) + ->setDisplayConfigurable('view', true); + + + $fields['status'] = BaseFieldDefinition::create('boolean') + ->setLabel(t('Publishing status')) + ->setDescription(t('A boolean indicating whether the OAuthOST Config is published.')) + ->setDefaultValue(true); + + $fields['created'] = BaseFieldDefinition::create('created') + ->setLabel(t('Created')) + ->setDescription(t('The time that the entity was created.')); + + $fields['changed'] = BaseFieldDefinition::create('changed') + ->setLabel(t('Changed')) + ->setDescription(t('The time that the entity was last edited.')); + + return $fields; + } +} diff --git a/drupal/modules/casost/src/Entity/CASOSTConfigInterface.php b/drupal/modules/casost/src/Entity/CASOSTConfigInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..ea18165a120d580658d777cd76bd3f7c0c1fd395 --- /dev/null +++ b/drupal/modules/casost/src/Entity/CASOSTConfigInterface.php @@ -0,0 +1,77 @@ + \Drupal::currentUser()->id(), + ); + } + + /** + * {@inheritdoc} + */ + public function getName() { + return $this->get('name')->value; + } + + /** + * {@inheritdoc} + */ + public function setName($name) { + $this->set('name', $name); + return $this; + } + + /** + * {@inheritdoc} + */ + public function getCreatedTime() { + return $this->get('created')->value; + } + + /** + * {@inheritdoc} + */ + public function setCreatedTime($timestamp) { + $this->set('created', $timestamp); + return $this; + } + + /** + * {@inheritdoc} + */ + public function getOwner() { + return $this->get('user_id')->entity; + } + + /** + * {@inheritdoc} + */ + public function getOwnerId() { + return $this->get('user_id')->target_id; + } + + /** + * {@inheritdoc} + */ + public function setOwnerId($uid) { + $this->set('user_id', $uid); + return $this; + } + + /** + * {@inheritdoc} + */ + public function setOwner(UserInterface $account) { + $this->set('user_id', $account->id()); + return $this; + } + + /** + * {@inheritdoc} + */ + public function isPublished() { + return (bool) $this->getEntityKey('status'); + } + + /** + * {@inheritdoc} + */ + public function setPublished($published) { + $this->set('status', $published ? TRUE : FALSE); + return $this; + } + + /** + * {@inheritdoc} + */ + public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { + $fields = parent::baseFieldDefinitions($entity_type); + + $fields['user_id'] = BaseFieldDefinition::create('entity_reference') + ->setLabel(t('Authored by')) + ->setDescription(t('The user ID of author of the CASOST Session entity.')) + ->setRevisionable(TRUE) + ->setSetting('target_type', 'user') + ->setSetting('handler', 'default') + ->setTranslatable(TRUE) + ->setDisplayOptions('view', array( + 'label' => 'hidden', + 'type' => 'author', + 'weight' => 0, + )) + ->setDisplayOptions('form', array( + 'type' => 'entity_reference_autocomplete', + 'weight' => 5, + 'settings' => array( + 'match_operator' => 'CONTAINS', + 'size' => '60', + 'autocomplete_type' => 'tags', + 'placeholder' => '', + ), + )) + ->setDisplayConfigurable('form', TRUE) + ->setDisplayConfigurable('view', TRUE); + + $fields['name'] = BaseFieldDefinition::create('string') + ->setLabel(t('CASOST session id')) + ->setDescription(t('The name of the CASOST Session entity.')) + ->setSettings(array( + 'max_length' => 200, + 'text_processing' => 0, + )) + ->setDefaultValue('') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', TRUE) + ->setDisplayConfigurable('view', TRUE); + + $fields['request_token'] = BaseFieldDefinition::create('string') + ->setLabel(t('Request Token')) + ->setDescription(t('The Request Token.')) + ->setSettings(array( + 'max_length' => 500, + 'text_processing' => 0, + )) + ->setDefaultValue('') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', TRUE) + ->setDisplayConfigurable('view', TRUE); + + $fields['request_token_secret'] = BaseFieldDefinition::create('string') + ->setLabel(t('Request Token Secret')) + ->setDescription(t('The Request Token Secret.')) + ->setSettings(array( + 'max_length' => 500, + 'text_processing' => 0, + )) + ->setDefaultValue('') + ->setDisplayOptions('view', array( + 'label' => 'above', + 'type' => 'string', + 'weight' => -4, + )) + ->setDisplayOptions('form', array( + 'type' => 'string_textfield', + 'weight' => -4, + )) + ->setDisplayConfigurable('form', TRUE) + ->setDisplayConfigurable('view', TRUE); + + $fields['status'] = BaseFieldDefinition::create('boolean') + ->setLabel(t('Publishing status')) + ->setDescription(t('A boolean indicating whether the CASOST Session is published.')) + ->setDefaultValue(TRUE); + + $fields['created'] = BaseFieldDefinition::create('created') + ->setLabel(t('Created')) + ->setDescription(t('The time that the entity was created.')); + + $fields['changed'] = BaseFieldDefinition::create('changed') + ->setLabel(t('Changed')) + ->setDescription(t('The time that the entity was last edited.')); + + return $fields; + } + +} diff --git a/drupal/modules/casost/src/Entity/CASOSTSessionInterface.php b/drupal/modules/casost/src/Entity/CASOSTSessionInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..fdfa549b95315e602eef4c2e750bf205be3f16bc --- /dev/null +++ b/drupal/modules/casost/src/Entity/CASOSTSessionInterface.php @@ -0,0 +1,77 @@ +entity; + + return $form; + } + + /** + * {@inheritdoc} + */ + public function save(array $form, FormStateInterface $form_state) { + $entity = &$this->entity; + + $status = parent::save($form, $form_state); + + switch ($status) { + case SAVED_NEW: + drupal_set_message($this->t('Created the %label CASOST Config.', [ + '%label' => $entity->label(), + ])); + break; + + default: + drupal_set_message($this->t('Saved the %label CASOST Config.', [ + '%label' => $entity->label(), + ])); + } + $form_state->setRedirect('entity.casost_config.canonical', ['casost_config' => $entity->id()]); + } + +} diff --git a/drupal/modules/casost/src/Form/CASOSTConfigSettingsForm.php b/drupal/modules/casost/src/Form/CASOSTConfigSettingsForm.php new file mode 100644 index 0000000000000000000000000000000000000000..46de6194d83a93c8f6efee96cf0e6e19dcb7c7c7 --- /dev/null +++ b/drupal/modules/casost/src/Form/CASOSTConfigSettingsForm.php @@ -0,0 +1,55 @@ +entity; + + return $form; + } + + /** + * {@inheritdoc} + */ + public function save(array $form, FormStateInterface $form_state) { + $entity = &$this->entity; + + $status = parent::save($form, $form_state); + + switch ($status) { + case SAVED_NEW: + drupal_set_message($this->t('Created the %label CASOST Session.', [ + '%label' => $entity->label(), + ])); + break; + + default: + drupal_set_message($this->t('Saved the %label CASOST Session.', [ + '%label' => $entity->label(), + ])); + } + $form_state->setRedirect('entity.casost_session.canonical', ['casost_session' => $entity->id()]); + } + +} diff --git a/drupal/modules/casost/src/Form/CASOSTSessionSettingsForm.php b/drupal/modules/casost/src/Form/CASOSTSessionSettingsForm.php new file mode 100644 index 0000000000000000000000000000000000000000..7b66ffe07fd8720e23a20f021d7091b5c8e63d3c --- /dev/null +++ b/drupal/modules/casost/src/Form/CASOSTSessionSettingsForm.php @@ -0,0 +1,55 @@ +user = $this->drupalCreateUser(['administer site configuration']); + $this->drupalLogin($this->user); + } + + /** + * Tests that the home page loads with a 200 response. + */ + public function testLoad() { + $this->drupalGet(Url::fromRoute('')); + $this->assertResponse(200); + } + +} diff --git a/drupal/modules/casost/templates/oauthost.html.twig b/drupal/modules/casost/templates/oauthost.html.twig new file mode 100644 index 0000000000000000000000000000000000000000..91e43c8f8098915c42ca8660b3de3088d4475a61 --- /dev/null +++ b/drupal/modules/casost/templates/oauthost.html.twig @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/drupal/modules/casost/templates/oauthost_config.html.twig b/drupal/modules/casost/templates/oauthost_config.html.twig new file mode 100644 index 0000000000000000000000000000000000000000..99b9d34027590ed8dac28d7fd55f82b83fe69855 --- /dev/null +++ b/drupal/modules/casost/templates/oauthost_config.html.twig @@ -0,0 +1,22 @@ +{# +/** + * @file oauthost_config.html.twig + * Default theme implementation to present OAuthOST Config data. + * + * This template is used when viewing OAuthOST Config pages. + * + * + * Available variables: + * - content: A list of content items. Use 'content' to print all content, or + * - attributes: HTML attributes for the container element. + * + * @see template_preprocess_oauthost_config() + * + * @ingroup themeable + */ +#} + + {% if content %} + {{- content -}} + {% endif %} + diff --git a/drupal/modules/casost/templates/oauthost_session.html.twig b/drupal/modules/casost/templates/oauthost_session.html.twig new file mode 100644 index 0000000000000000000000000000000000000000..f36010dba38bfe3830a29a1063be79b446fc6378 --- /dev/null +++ b/drupal/modules/casost/templates/oauthost_session.html.twig @@ -0,0 +1,22 @@ +{# +/** + * @file oauthost_session.html.twig + * Default theme implementation to present OAuthOST Session data. + * + * This template is used when viewing OAuthOST Session pages. + * + * + * Available variables: + * - content: A list of content items. Use 'content' to print all content, or + * - attributes: HTML attributes for the container element. + * + * @see template_preprocess_oauthost_session() + * + * @ingroup themeable + */ +#} + + {% if content %} + {{- content -}} + {% endif %} + diff --git a/drupal/modules/epal/src/Controller/CurrentUser.php b/drupal/modules/epal/src/Controller/CurrentUser.php index 6c83916d7e608a4a340055c99e99f634540407e0..1289ca109f1ce6c60fbba9c3c2113f2d47091c15 100644 --- a/drupal/modules/epal/src/Controller/CurrentUser.php +++ b/drupal/modules/epal/src/Controller/CurrentUser.php @@ -39,7 +39,28 @@ class CurrentUser extends ControllerBase public function getLoginInfo(Request $request) { + $authToken = $request->headers->get('PHP_AUTH_USER'); + $users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken)); + $user = reset($users); + if (!$user) { + return $this->respondWithStatus([ + 'message' => t("User not found"), + ], Response::HTTP_FORBIDDEN); + } + + $userRoles = $user->getRoles(); + foreach ($userRoles as $userRole) { + if ($userRole === 'epal') { + return $this->respondWithStatus([ + 'name' => $user->mail->value, + 'title' => $user->init->value, + ], Response::HTTP_OK); + } else if ($userRole === 'applicant') { + break; + } + + } $epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('authtoken' => $authToken)); $epalUser = reset($epalUsers); diff --git a/drupal/modules/oauthost/src/Controller/OAuthLogin.php b/drupal/modules/oauthost/src/Controller/OAuthLogin.php index bb22d4c46936397792b97b5a85e43da8ebedaa83..53e1e316505582c18db9d38a59d57add1a491cd0 100644 --- a/drupal/modules/oauthost/src/Controller/OAuthLogin.php +++ b/drupal/modules/oauthost/src/Controller/OAuthLogin.php @@ -30,6 +30,7 @@ class OAuthLogin extends ControllerBase protected $api_url; protected $callback_url; protected $logout_url; + protected $redirect_url; public function __construct( EntityTypeManagerInterface $entityTypeManager, @@ -67,6 +68,7 @@ class OAuthLogin extends ControllerBase $this->api_url = $ostauthConfig->api_url->value; $this->callback_url = $ostauthConfig->callback_url->value; $this->logout_url = $ostauthConfig->logout_url->value; + $this->redirect_url = $ostauthConfig->redirect_url->value; } else { $response = new Response(); $response->setContent('forbidden'); diff --git a/drupal/modules/oauthost/src/Controller/OAuthLogout.php b/drupal/modules/oauthost/src/Controller/OAuthLogout.php index 82f5f9ee484def87a3bcb6f29d4f3adfb460e512..6180c9ccf900fab022def2936431f1ac0a65cb90 100644 --- a/drupal/modules/oauthost/src/Controller/OAuthLogout.php +++ b/drupal/modules/oauthost/src/Controller/OAuthLogout.php @@ -11,6 +11,8 @@ 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; class OAuthLogout extends ControllerBase { @@ -28,6 +30,7 @@ class OAuthLogout extends ControllerBase protected $api_url; protected $callback_url; protected $logout_url; + protected $redirect_url; public function __construct( EntityTypeManagerInterface $entityTypeManager, @@ -67,6 +70,7 @@ class OAuthLogout extends ControllerBase $this->api_url = $ostauthConfig->api_url->value; $this->callback_url = $ostauthConfig->callback_url->value; $this->logout_url = $ostauthConfig->logout_url->value; + $this->redirect_url = $ostauthConfig->redirect_url->value; } else { $response = new Response(); $response->setContent('forbidden'); @@ -121,7 +125,7 @@ class OAuthLogout extends ControllerBase $response->setStatusCode(Response::HTTP_OK); $response->headers->set('Content-Type', 'application/json'); return $response; - +// return new RedirectResponse($this->redirect_url . '&auth_role=', 302, []); } catch (Exception $e) { diff --git a/source/app.settings.ts b/source/app.settings.ts index b970dfb88893f634f3656e7f8f42f3f7bd0d31a6..91d0eac52125ed1a214b1ae8e571b12c7a8fea11 100644 --- a/source/app.settings.ts +++ b/source/app.settings.ts @@ -1,8 +1,8 @@ // export const API_ENDPOINT = 'http://eduslim2.minedu.gov.gr/drupal'; -export const API_ENDPOINT = 'http://localhost/drupal-8.2.6'; +export const API_ENDPOINT = 'http://eduslim2.minedu.gov.gr/drupal'; export class AppSettings { public static get API_ENDPOINT(): string { // return 'http://eduslim2.minedu.gov.gr/drupal'; - return 'http://localhost/drupal-8.2.6'; + return 'http://eduslim2.minedu.gov.gr/drupal'; } } diff --git a/source/app.ts b/source/app.ts index 27e8e8e958bcdbe8275dde4d629758534c738e3e..691d4bb02e6e048167b0aec1e8e396759d6210b0 100644 --- a/source/app.ts +++ b/source/app.ts @@ -80,5 +80,5 @@ class MyLocalization extends NgLocalization { }) class AppModule {} -// enableProdMode(); + enableProdMode(); platformBrowserDynamic().bootstrapModule(AppModule); diff --git a/source/components/home.ts b/source/components/home.ts index 034c1fc75cca8e38ec8f57e6e0c5212f94bde785..e7a6d6086164efc65e6662a7f9ec558f1f44a8e9 100644 --- a/source/components/home.ts +++ b/source/components/home.ts @@ -64,7 +64,7 @@ export default class Home implements OnInit { state.loginInfo.reduce(({}, loginInfoToken) => { this.authToken = loginInfoToken.auth_token; this.authRole = loginInfoToken.auth_role; - if (this.authToken && this.authToken.length > 0) + if (this.authToken && this.authToken.length > 0 && this.authRole && this.authRole === 'student') this.router.navigate(['/parent-form']); return loginInfoToken; }, {}); diff --git a/source/components/navbar/navbar.component.html b/source/components/navbar/navbar.component.html index 7caea8ae7abaf78a9c974f2e2a4fc423a62aa554..524eb2865e41fe0aa7a47bc68ad4cef95a756114 100644 --- a/source/components/navbar/navbar.component.html +++ b/source/components/navbar/navbar.component.html @@ -8,36 +8,27 @@ Αρχική diff --git a/source/components/navbar/navbar.component.ts b/source/components/navbar/navbar.component.ts index ef34c131885607002ca1af57bf865f01223c1904..8d2ddf32a4b6c1808a871c8892199e7aafdf9734 100644 --- a/source/components/navbar/navbar.component.ts +++ b/source/components/navbar/navbar.component.ts @@ -1,13 +1,14 @@ -import {Component, OnInit} from '@angular/core'; +import {Component, OnInit, OnDestroy} from '@angular/core'; import {Router} from '@angular/router'; import { Injectable } from "@angular/core"; -import { Observable } from 'rxjs/Rx'; +import { BehaviorSubject } from 'rxjs/Rx'; import { NgRedux, select } from 'ng2-redux'; import { IAppState } from '../../store/store'; import { ILoginInfo, ILoginInfoToken } from '../../store/logininfo/logininfo.types'; import { HelperDataService } from '../../services/helper-data-service'; import { LoginInfoActions } from '../../actions/logininfo.actions'; +import { LOGININFO_INITIAL_STATE } from '../../store/logininfo/logininfo.initial-state'; @@ -16,10 +17,11 @@ import { LoginInfoActions } from '../../actions/logininfo.actions'; templateUrl: 'navbar.component.html', }) -@Injectable() export default class NavbarComponent implements OnInit{ +@Injectable() export default class NavbarComponent implements OnInit, OnDestroy{ private authToken: string; private authRole: string; - private loginInfo$: Observable; + private cuName: string; + private loginInfo$: BehaviorSubject; public cuser :any; constructor( private _ata: LoginInfoActions, @@ -30,31 +32,47 @@ import { LoginInfoActions } from '../../actions/logininfo.actions'; this.authToken = ''; this.authRole = ''; + this.cuName = ''; + this.loginInfo$ = new BehaviorSubject(LOGININFO_INITIAL_STATE); }; ngOnInit() { - this.loginInfo$ = this._ngRedux.select(state => { + this._ngRedux.select(state => { if (state.loginInfo.size > 0) { state.loginInfo.reduce(({}, loginInfoToken) => { this.authToken = loginInfoToken.auth_token; this.authRole = loginInfoToken.auth_role; + this.cuName = loginInfoToken.cu_name; + console.log(loginInfoToken.cu_name); return loginInfoToken; - }, {}); + }, {}) } return state.loginInfo; - }); + }).subscribe(this.loginInfo$); + + } + ngOnDestroy() { + this.loginInfo$.unsubscribe(); } oauthSignOut() { this._hds.signOut().then(data => { this._ata.initLoginInfo(); + console.log(this.authRole); + if (this.authRole === 'director') { + console.log("director"); + this.router.navigate(['/school']); + } + else if (this.authRole === 'student') { + console.log("applicant"); + this.router.navigate(['']); + } this.authToken = ''; this.authRole = ''; - this.router.navigate(['/']); }); } diff --git a/source/components/school.home.ts b/source/components/school.home.ts new file mode 100644 index 0000000000000000000000000000000000000000..033344a7383661124b7c3914b8d0d85841aa4a69 --- /dev/null +++ b/source/components/school.home.ts @@ -0,0 +1,91 @@ +import {Router, ActivatedRoute, Params} from '@angular/router'; +import {OnInit, Component} from '@angular/core'; +import { LoginInfoActions } from '../actions/logininfo.actions'; +import { ILoginInfo } from '../store/logininfo/logininfo.types'; +import { NgRedux, select } from 'ng2-redux'; +import { Observable } from 'rxjs/Rx'; +import { IAppState } from '../store/store'; +import { HelperDataService } from '../services/helper-data-service'; +import { + FormBuilder, + FormGroup, + FormControl, + FormArray +} from '@angular/forms'; + +import { API_ENDPOINT } from '../app.settings'; +@Component({ + selector: 'school-home', + template: ` +
+
+ + +
+
+ +
+ +
+
+
+
+ ` +}) + +export default class SchoolHome implements OnInit { + public formGroup: FormGroup; + private authToken: string; + private authRole: string; + private name: any; + private xcsrftoken: any; + private loginInfo$: Observable; + private apiEndPoint = API_ENDPOINT; + + constructor(private fb: FormBuilder, + private _ata: LoginInfoActions, + private _ngRedux: NgRedux, + private activatedRoute: ActivatedRoute, + private _hds: HelperDataService, + private router: Router + ) { + this.authToken = ''; + this.authRole = ''; + this.name = ''; + this.formGroup = this.fb.group({ + }); + }; + + ngOnInit() { + this.loginInfo$ = this._ngRedux.select(state => { + if (state.loginInfo.size > 0) { + state.loginInfo.reduce(({}, loginInfoToken) => { + this.authToken = loginInfoToken.auth_token; + this.authRole = loginInfoToken.auth_role; + if (this.authToken && this.authToken.length > 0) + this.router.navigate(['/submited-preview']); + return loginInfoToken; + }, {}); + } + + return state.loginInfo; + }); + + // subscribe to router event + this.activatedRoute.queryParams.subscribe((params: Params) => { + if (params) { + this.authToken = params['auth_token']; + this.authRole = params['auth_role']; + } + + if (this.authToken && this.authRole) + this._ata.getloginInfo({ auth_token: this.authToken, auth_role: this.authRole }); + + }); + } + checkvalidation() { + + } +} diff --git a/source/containers/main.routes.ts b/source/containers/main.routes.ts index 90cb09e58754a8a0a2863d9f4d644ab96fa23091..bce23509b8994206aa35a6ad0ee17bc3d4f5dba7 100644 --- a/source/containers/main.routes.ts +++ b/source/containers/main.routes.ts @@ -9,6 +9,7 @@ import ParentForm from '../components/student-application-form/parent.form'; import StudentApplicationMain from '../components/student-application-form/application.form.main'; import StudentsList from '../components/students/students-list'; import Home from '../components/home'; +import SchoolHome from '../components/school.home'; import CourseFieldsSelect from '../components/student-application-form/course.fields.select'; import EpalClassesSelect from '../components/student-application-form/epal.class.select'; import SectorFieldsSelect from '../components/student-application-form/sector.fields.select'; @@ -24,6 +25,7 @@ import DirectorClassCapacity from '../components/director/director-classcapacity export const MainRoutes: Routes = [ { path: '', component: Home }, + { path: 'school', component: SchoolHome }, { path: 'parent-form', component: ParentForm }, { path: 'student-application-form-main', component: StudentApplicationMain }, { path: 'students-list', component: StudentsList }, @@ -46,6 +48,7 @@ export const MainDeclarations = [ RemoveSpaces, StudentsList, Home, + SchoolHome, CourseFieldsSelect, EpalClassesSelect, SectorFieldsSelect, diff --git a/source/containers/main.ts b/source/containers/main.ts index 45fd69df9b3f6dc610c381c315cfcb15f930f606..a2fe8086af9a322f56716c5e5eda9c040606a747 100644 --- a/source/containers/main.ts +++ b/source/containers/main.ts @@ -61,6 +61,7 @@ import { }) export default class Main { public path: string = ''; + public pathSchool: string = 'school'; constructor( private router: Router, @@ -70,6 +71,7 @@ export default class Main { ) { router.events.subscribe((data) => { this.path = data.url.substr(1); + this.pathSchool = data.url.substr(1); }); @@ -81,7 +83,7 @@ export default class Main { {}, middleware, // tools ? [ ...enhancers, tools ] : enhancers); - tools); -// ); +// tools); + ); } } diff --git a/source/services/helper-data-service.ts b/source/services/helper-data-service.ts index 2699cd3ea6599e7542096992238e2c4bb9ae075b..46ad183df124cee8de690621a592631692b27b91 100644 --- a/source/services/helper-data-service.ts +++ b/source/services/helper-data-service.ts @@ -1,6 +1,6 @@ import {Http, Headers, RequestOptions} from '@angular/http'; -import {Injectable} from '@angular/core'; -import {Observable} from "rxjs/Observable"; +import {Injectable, OnInit, OnDestroy} from '@angular/core'; +import {BehaviorSubject} from "rxjs/Rx"; import 'rxjs/add/operator/map'; import { ICourseField } from '../store/coursefields/coursefields.types'; import { ISectorField } from '../store/sectorfields/sectorfields.types'; @@ -11,31 +11,41 @@ import { AppSettings } from '../app.settings'; import { NgRedux, select } from 'ng2-redux'; import { IAppState } from '../store/store'; import { ILoginInfo, ILoginInfoToken } from '../store/logininfo/logininfo.types'; +import { LOGININFO_INITIAL_STATE } from '../store/logininfo/logininfo.initial-state'; const HEADER = { headers: new Headers({ 'Content-Type': 'application/json' }) }; @Injectable() -export class HelperDataService { +export class HelperDataService implements OnInit, OnDestroy{ private authToken: string; - private loginInfo$: Observable; + private authRole: string; + private loginInfo$: BehaviorSubject; constructor( private http: Http, private _ngRedux: NgRedux) { - this.loginInfo$ = this._ngRedux.select(state => { - if (state.loginInfo.size > 0) { - state.loginInfo.reduce(({}, loginInfoToken) => { - this.authToken = loginInfoToken.auth_token; - return loginInfoToken; - }, {}); - } - return state.loginInfo; - }); + this.loginInfo$ = new BehaviorSubject(LOGININFO_INITIAL_STATE); }; + ngOnInit() { + this._ngRedux.select(state => { + if (state.loginInfo.size > 0) { + state.loginInfo.reduce(({}, loginInfoToken) => { + this.authToken = loginInfoToken.auth_token; + this.authRole = loginInfoToken.auth_role; + return loginInfoToken; + }, {}); + } + return state.loginInfo; + }).subscribe(this.loginInfo$); + } + + ngOnDestroy() { + this.loginInfo$.unsubscribe(); + } createAuthorizationHeader(headers: Headers) { headers.append('Authorization', 'Basic ' + btoa(this.authToken + ':' + this.authToken)); } @@ -43,6 +53,7 @@ export class HelperDataService { getEpalUserData() { this.loginInfo$.forEach(loginInfoToken => { this.authToken = loginInfoToken.get(0).auth_token; + this.authRole = loginInfoToken.get(0).auth_role; }); let headers = new Headers({ "Content-Type": "application/json", @@ -56,6 +67,7 @@ export class HelperDataService { sendVerificationCode(email) { this.loginInfo$.forEach(loginInfoToken => { this.authToken = loginInfoToken.get(0).auth_token; + this.authRole = loginInfoToken.get(0).auth_role; }); let headers = new Headers({ "Content-Type": "application/json", @@ -82,6 +94,7 @@ export class HelperDataService { verifyVerificationCode(verificationCode) { this.loginInfo$.forEach(loginInfoToken => { this.authToken = loginInfoToken.get(0).auth_token; + this.authRole = loginInfoToken.get(0).auth_role; }); let headers = new Headers({ "Content-Type": "application/json", @@ -109,6 +122,7 @@ export class HelperDataService { saveProfile(userProfile) { this.loginInfo$.forEach(loginInfoToken => { this.authToken = loginInfoToken.get(0).auth_token; + this.authRole = loginInfoToken.get(0).auth_role; }); let headers = new Headers({ "Content-Type": "application/json", @@ -133,6 +147,7 @@ export class HelperDataService { this.loginInfo$.forEach(loginInfoToken => { this.authToken = loginInfoToken.get(0).auth_token; + this.authRole = loginInfoToken.get(0).auth_role; }); let headers = new Headers({ //"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass @@ -165,6 +180,7 @@ export class HelperDataService { getSectorFields() { this.loginInfo$.forEach(loginInfoToken => { this.authToken = loginInfoToken.get(0).auth_token; + this.authRole = loginInfoToken.get(0).auth_role; }); let headers = new Headers({ //"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass @@ -196,6 +212,7 @@ export class HelperDataService { getRegionsWithSchools(classActive,courseActive) { this.loginInfo$.forEach(loginInfoToken => { this.authToken = loginInfoToken.get(0).auth_token; + this.authRole = loginInfoToken.get(0).auth_role; }); let headers = new Headers({ //"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass @@ -237,6 +254,7 @@ export class HelperDataService { getSectorsWithCourses() { this.loginInfo$.forEach(loginInfoToken => { this.authToken = loginInfoToken.get(0).auth_token; + this.authRole = loginInfoToken.get(0).auth_role; }); let headers = new Headers({ //"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass @@ -311,6 +329,7 @@ export class HelperDataService { this.loginInfo$.forEach(loginInfoToken => { console.log(loginInfoToken.get(0)); this.authToken = loginInfoToken.get(0).auth_token; + this.authRole = loginInfoToken.get(0).auth_role; }); let headers = new Headers({ "Content-Type": "application/json", @@ -335,6 +354,7 @@ export class HelperDataService { getCurrentUser(oauthtoken, oauthrole) { this.authToken = oauthtoken; + this.authRole = oauthrole; let headers = new Headers({ //"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass // "Authorization": "Basic bmthdHNhb3Vub3M6emVtcmFpbWU=", @@ -374,6 +394,7 @@ export class HelperDataService { signOut() { this.loginInfo$.forEach(loginInfoToken => { this.authToken = loginInfoToken.get(0).auth_token; + this.authRole = loginInfoToken.get(0).auth_role; }); let headers = new Headers({ //"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass @@ -392,8 +413,13 @@ export class HelperDataService { }); this.createAuthorizationHeader(headers); let options = new RequestOptions({ headers: headers, withCredentials: true }); + let logoutRoute = '/oauth/logout'; + console.log(this.authRole); + if (this.authRole === 'director') + logoutRoute = '/cas/logout'; + return new Promise((resolve, reject) => { - this.http.post(`${AppSettings.API_ENDPOINT}/oauth/logout`, {}, options) + this.http.post(`${AppSettings.API_ENDPOINT}${logoutRoute}`, {}, options) .map(response => response) .subscribe(data => { resolve(data);