Skip to content
This repository has been archived by the owner on Jan 25, 2021. It is now read-only.

Commit

Permalink
Merge branch 'feature/NLimprovedBackChannel' into development
Browse files Browse the repository at this point in the history
  • Loading branch information
Lionel Walter committed Apr 3, 2017
2 parents 0bc5023 + dc9e194 commit 46c0d13
Show file tree
Hide file tree
Showing 8 changed files with 157 additions and 111 deletions.
Empty file modified cli/send-national-licence-user-export.sh
100644 → 100755
Empty file.
20 changes: 1 addition & 19 deletions cli/update-national-licence-user-info.sh
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,8 @@ VUFIND_LOCAL_DIR="$BASEDIR/../local"

export VUFIND_LOCAL_MODULES=Swissbib
export VUFIND_LOCAL_DIR
export APPLICATION_ENV=development
#Check the environmnet
if [ "$APPLICATION_ENV" == "development" ]
then
SWITCH_API_USER="${SWITCH_API_USER:=natlic}"
SWITCH_API_PASSW="${SWITCH_API_PASSW:=Amg6vZXo}"
else
#Set these environment variable for production to connect to the SWITCH API
SWITCH_API_USER="${SWITCH_API_USER:=}"
SWITCH_API_PASSW="${SWITCH_API_PASSW:=}"
fi
export SWITCH_API_USER;
export SWITCH_API_PASSW;

#Check that the SWITCH API has been correctly configured.
: "${SWITCH_API_USER:? The environment variable SWITCH_API_USER have to be set}"
: "${SWITCH_API_USER:? The environment variable SWITCH_API_PASSW have to be set}"

php $INDEX update-national-licence-user-info $@

rm -rf $VUFIND_CACHE/searchspecs/*
rm -rf $VUFIND_CACHE/objects/*
rm -rf $VUFIND_CACHE/languages/*

16 changes: 5 additions & 11 deletions local/config/vufind/NationalLicences.ini
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ national_licence_programme_group_id = 1d3baa7b-da70-440d-b777-5bb2d11f8718
base_endpoint_url = https://eduid.ch/sg/index.php
back_channel_param_entityID = https://eduid.ch/idp/shibboleth
back_channel_endpoint_path = /Shibboleth.sso/AttributeResolver
back_channel_endpoint_host = https://localhost
schema_patch = urn:ietf:params:scim:api:messages:2.0:PatchOp
operation_add = add
operation_remove = remove
Expand All @@ -13,7 +14,8 @@ allowed_mobile_prefixes[] = +41 79
allowed_mobile_prefixes[] = +41 78
allowed_mobile_prefixes[] = +41 77
allowed_mobile_prefixes[] = +41 76
user_export_path = /local/export/nationalLicence
allowed_mobile_prefixes[] = +41 75
user_export_path = /local/export/nationalLicencesUsers
user_export_filename = user_export.csv
user_export_default_email_address_to = [email protected]
national_licence_user_fields_to_export[] = home_postal_address
Expand All @@ -25,22 +27,14 @@ national_licence_user_fields_to_export[] = date_expiration
national_licence_user_fields_to_export[] = blocked
national_licence_user_fields_to_export[] = active_last_12_month
national_licence_user_fields_to_export[] = persistent_id
national_licence_user_fields_to_export[] = mobile
national_licence_user_fields_to_export[] = assurance_level
vufind_user_fields_to_export[] = firstname
vufind_user_fields_to_export[] = lastname
vufind_user_fields_to_export[] = email
request_account_extension_expiration_days = 30
temporary_access_expiration_days = 14

[EmailService]
#Change with the production address
default_email_address_from = [email protected]
SmtpOptions.name = host
#Change with production SMTP server host
SmtpOptions.host = smtp.gmail.com
SmtpOptions.port= 587
SmtpOptions.connection_class = login
SmtpOptions.connection_config[ssl] = tls

#Unit test configuration
[Test]
switchApi.external_id_test = [email protected]
Expand Down
12 changes: 1 addition & 11 deletions module/Swissbib/src/Swissbib/Services/Email.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,8 @@
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Mime;
use Zend\ServiceManager\ServiceManager;
//use Zend\Mail\Transport\Sendmail as SendmailTransport;
use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
use Zend\Mail\Transport\Sendmail as SendmailTransport;

/**
Expand Down Expand Up @@ -158,8 +155,7 @@ public function sendMailWithAttachment(
);
}
// and finally we create the actual email
$emailAddressFrom = $this->config
->get('NationalLicences')['EmailService']['default_email_address_from'];
$emailAddressFrom = $this->config->get('config')['Site']['email'];
$message = new Message();
$message->setBody($mimeMessage);
$message->addTo($to)
Expand All @@ -168,12 +164,6 @@ public function sendMailWithAttachment(
$transport = null;
if ($tlsActive) {
$transport = new SmtpTransport();
$options
= new SmtpOptions(
$this->config
->get('NationalLicences')['EmailService']['SmtpOptions']
);
$transport->setOptions($options);
} else {
$transport = new SendmailTransport();
}
Expand Down
103 changes: 60 additions & 43 deletions module/Swissbib/src/Swissbib/Services/NationalLicence.php
Original file line number Diff line number Diff line change
Expand Up @@ -625,15 +625,19 @@ protected function createCsvFileFromListUsers($path, $users)
= $this->config['national_licence_user_fields_to_export'];
$fieldVuFindUser = $this->config['vufind_user_fields_to_export'];

if (!file_exists(dirname($path))) {
mkdir(dirname($path), 0777, true);
}

$file = fopen($path, 'w+') or die('Unable to open file!');

//Header
$str = '';
foreach ($fieldVuFindUser as $field) {
$str = $str . $field . ',';
$str = $str . $field . "\t";
}
foreach ($fieldsNationalLicenceUser as $field) {
$str = $str . $field . ',';
$str = $str . $field . "\t";
}
$str = $str . "\r\n";
fwrite($file, $str);
Expand All @@ -647,10 +651,10 @@ protected function createCsvFileFromListUsers($path, $users)
foreach ($users as $user) {
$str = '';
foreach ($fieldVuFindUser as $field) {
$str = $str . $user->getRelUser()->$field . ',';
$str = $str . $user->getRelUser()->$field . "\t";
}
foreach ($fieldsNationalLicenceUser as $field) {
$str = $str . $user->$field . ',';
$str = $str . $user->$field . "\t";
}
$str = $str . "\r\n";
fwrite($file, $str);
Expand Down Expand Up @@ -792,54 +796,67 @@ public function checkAndUpdateNationalLicenceUserInfo()
* @var NationalLicenceUser $user
*/
foreach ($users as $user) {
echo 'Processing user ' . $user->getEduId() . ".\r\n";
echo "\r\n" . 'Processing user ' . $user->getEduId() . ".\r\n";
//Update attributes from the edu-Id account
try{
$user = $this->switchApiService->getUserUpdatedInformation(
$user->getNameId(), $user->getPersistentId()
);
} catch (\Exception $e){
echo $e->getMessage();
}

//If last activity date < last 12 month
if (!$user->hasBeenActiveInLast12Month()) {
echo "User was not active in last 12 month.\r\n";
//If last_account_extension_request == null
if ($this->isAccountExtensionEmailHasAlreadyBeenSent($user)) {
if ($this->isAccountExtensionRequestStillValid($user)) {
echo "Account extension request is still valid.\r\n";
} else {
//Else if last_account_extension_request < XX days ago
//Unset the national licence compliant flag
echo "Unset national compliant flag...\r\n";
$this->switchApiService
->unsetNationalCompliantFlag($user->id);
//for registered users who haven't used their Switch edu-ID
// in the last 12 months
//they need to renew by email
if ($this->hasAccessToNationalLicenceContent($user)) {
//If last activity date < last 12 month
if (!$user->hasBeenActiveInLast12Month()) {
echo "User was not active in last 12 month.\r\n";
//If last_account_extension_request == null
if ($this->isAccountExtensionEmailHasAlreadyBeenSent($user)
) {
if ($this->isAccountExtensionRequestStillValid($user)) {
echo "Account extension request is still valid.\r\n";
} else {
//Else if last_account_extension_request< XX days ago
//Unset the national licence compliant flag
echo "Unset national compliant flag...\r\n";
$this->switchApiService
->unsetNationalCompliantFlag($user->id);
}
} else {
//Send and email to the user for extending their account
$this->emailService->sendAccountExtensionEmail(
$user->getRelUser()
);
echo 'Email sent to ' . $user->getRelUser()->email .
"\r\n";
//Set the last_account_extension_request to now
$user->setLastAccountExtensionRequest(new \DateTime());
$user->save();
}
}
} else {
//Send and email to the user for extending their account
$this->emailService->sendAccountExtensionEmail(
$user->getRelUser()
}
//if user is not anymore compliant with their homePostalAddress
//No address -->remove flag
//Postal address not verified anymore --> remove user to national
// compliant group
//Postal address not in CH -->remove user to national compliant group
// This also takes care of expired temporary accesses

$e = $user->getEduId();

if ($this->switchApiService->userIsOnNationalCompliantSwitchGroup($e)
&& !$this->isNationalLicenceCompliant($user)
) {
echo "Unset national compliant flag.....\r\n";
//Unset the national licence compliant flag
$this->switchApiService->unsetNationalCompliantFlag(
$user->getEduId()
);
echo 'Email sent to ' . $user->getRelUser()->email . "\r\n";
//Set the last_account_extension_request to now
$user->setLastAccountExtensionRequest(new \DateTime());
$user->setRequestPermanentAccess(false);
$user->save();
}
}
//if user is not anymore compliant with their homePostalAddress
//No address -->remove flag
//Postal address not verified anymore --> remove user to national
// compliant group
//Postal address not in CH -->remove user to national compliant group
if (!$this->isNationalLicenceCompliant($user)) {
echo "Unset national compliant flag...\r\n";
//Unset the national licence compliant flag
$this->switchApiService->unsetNationalCompliantFlag(
$user->getEduId()
);
$user->setRequestPermanentAccess(false);
$user->save();

} catch (\Exception $e){
echo $e->getMessage();
}
}
}
Expand Down
83 changes: 70 additions & 13 deletions module/Swissbib/src/Swissbib/Services/SwitchApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,8 @@ protected function getBaseClient(
throw new \Exception(
'Was not possible to find the SWITCH API ' .
'credentials. Make sure you have correctly configured the ' .
'"SWITCH_API_USER" and "SWITCH_API_PASSW" either in the ' .
'apache setup or before launching the script.'
'"SWITCH_API_USER" and "SWITCH_API_PASSW" in ' .
'config.ini.'
);

}
Expand All @@ -174,6 +174,38 @@ protected function getBaseClient(
return $client;
}

/**
* Get an instance of the HTTP Client with some basic configuration
* for shibboleth back-channel queries.
*
* @return Client
* @throws \Exception
*/
protected function getBaseClientBackChannel()
{
$client = new Client(
$this->configNL['back_channel_endpoint_host'] .
$this->configNL['back_channel_endpoint_path'], [
'maxredirects' => 0,
'timeout' => 30,
'adapter' => 'Zend\Http\Client\Adapter\Curl',
'curloptions' => [
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false
]
]
);
$client->setHeaders(
[
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
);
$client->setMethod(Request::METHOD_GET);

return $client;
}

/**
* Add user to the National Licenses Programme group on the National Licenses
* registration platform.
Expand Down Expand Up @@ -208,7 +240,7 @@ protected function addUserToNationalCompliantGroup($userInternalId)
],
],
];
$str = json_encode($params, JSON_PRETTY_PRINT);
//$str = json_encode($params, JSON_PRETTY_PRINT);
//echo "<pre> $str < /pre>";
$rawData = json_encode($params, JSON_UNESCAPED_SLASHES);
$client->setRawBody($rawData);
Expand All @@ -232,7 +264,6 @@ public function userIsOnNationalCompliantSwitchGroup($userExternalId)
{
$internalId = $this->createSwitchUser($userExternalId);
$switchUser = $this->getSwitchUserInfo($internalId);
$id = 'national_licence_programme_group_id';
foreach ($switchUser->groups as $group) {
$v = $this->configNL['national_licence_programme_group_id'];
if ($group->value === $v) {
Expand Down Expand Up @@ -346,7 +377,8 @@ public function getUserUpdatedInformation($nameId, $persistentId)
'edu_id' => 'uniqueID',
'home_postal_address' => 'homePostalAddress',
'affiliation' => 'affiliation',
'active_last_12_month' => 'swissEduIDUsage1y'
'active_last_12_month' => 'swissEduIDUsage1y',
'assurance_level' => 'swissEduIdAssuranceLevel'
];
$userFieldsRelation = [
'username' => 'persistent-id',
Expand Down Expand Up @@ -397,28 +429,53 @@ public function getUserUpdatedInformation($nameId, $persistentId)
*/
protected function getNationalLicenceUserCurrentInformation($nameId)
{
//Make http request fro retrieve new edu-ID information usign the back-
//channel api
// @codingStandardsIgnoreStart
/*
* Make http request to retrieve new edu-ID information usign the back-
* channel api
* example :
*
* (very long line)
* curl -k 'https://test.swissbib.ch/Shibboleth.sso/AttributeResolver?entityID=https%3A%2F%2Feduid.ch%2Fidp%2Fshibboleth&nameId=AaduBHpQXrRs9BJqQcB7aLXgWTI%3D&format=urn%3Aoasis%3Anames%3Atc%3ASAML%3A2.0%3Anameid-format%3Apersistent&encoding=JSON%2FCGI'
*
* answer :
* {
* "mobile" : "+41 79 200 00 00",
* "swissLibraryPersonResidence" : "CH",
* "homeOrganizationType" : "others",
* "uniqueID" : "[email protected]",
* "homeOrganization" : "eduid.ch",
* "mail" : "[email protected]",
* "persistent-id" : "https://eduid.ch/idp/shibboleth!https://test.swissbib.ch/shibboleth!AaduBHpQXrRs9BJqQcB7aLXgWTI=",
* "swissEduIdAssuranceLevel" : "mobile:https://eduid.ch/def/loa2;mail:https://eduid.ch/def/loa2;homePostalAddress:https://eduid.ch/def/loa2",
* "givenName" : "Hans",
* "surname" : "Mustermann",
* "homePostalAddress" : "Rue Neuve 5$1222 Geneve$Switzerland",
* "swissEduIDUsage1y" : "TRUE",
* "affiliation" : "affiliate",
* "persistent-id" : "https://eduid.ch/idp/shibboleth!https://test.swissbib.ch/shibboleth!AaduBHpQXrRs9BJqQcB7aLXgWTI="
* }
*/
// @codingStandardsIgnoreEnd

/**
* Client.
*
* @var Client $client
*/
$client = $this->getBaseClient(
Request::METHOD_GET,
$this->configNL['back_channel_endpoint_path'],
$this->config['Site']['url']
);
$client = $this->getBaseClientBackChannel();
$client->setParameterGet(
[
'entityID' => $this->configNL['back_channel_param_entityID'],
'nameId' => $nameId,
'format' => "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent",
'encoding' => "JSON/CGI"
]
);
$response = $client->send();
$statusCode = $response->getStatusCode();
$body = $response->getBody();
if ($statusCode !== 200) {
if ($statusCode !== 200 or $body == "{}") {
throw new \Exception(
"There was a problem retrieving data for user " .
"with name id: $nameId. Status code: $statusCode result: $body"
Expand Down
Loading

0 comments on commit 46c0d13

Please sign in to comment.