Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding flat encryption support to flat_deposit #35

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -418,5 +418,49 @@ function customRollback($message){

}

function generateFlatEncryptionMetadata()
{
$this->logging('Starting generateFlatEncryptionMetadata');

// normalizing currently saved metadata, null, empty str will be marked as empty array
$marked = $this->wrapper->flat_encrypted_resources->value();
$marked = empty($marked) ? [] : explode(',', $marked);

$flat_auth_endpoint = $this->wrapper->flat_encrypted_auth_endpoint->value();
$this->logging('FLAT ENCRYPTED AUTH URL: ' . $flat_auth_endpoint);

$user = $this->getUserResourceForUserName($this->owner);

$app_token = base64_encode($flat_auth_endpoint . '|apptoken|' . flat_auth_get_token_for_user($user));

$cmdi_dir = dirname($this->cmdiTarget);
$write = file_put_contents($cmdi_dir . '/flat_encryption.json', json_encode([

'marked' => $marked,
'token' => $app_token,
]));

$this->logging('Files marked for encryption: ' . var_export($marked, true));
$this->logging('FLAT ENCRYPTED AUTH URL: ' . $flat_auth_endpoint);

if (!$write) {
throw new IngestServiceException('Unable to write flat encryption metadata to target location (' . $cmdi_dir . ')');
}

$this->logging('Finishing generateFlatEncryptionMetadata');
return TRUE;
}

/**
* This method will fetch the user object, based on his username credential.
* If it doesn't find a user, it will default to null
*
* @param string $username
*
* @return stdClass|null
*/
private function getUserResourceForUserName($username)
{
return user_load_by_name($username);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -189,4 +189,5 @@ function finish()


function customRollback($message){}
function generateFlatEncryptionMetadata() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ protected function DoSipIngest($SIP, $info)
$this->processLog['addResourcesToCmdi'] = $this->factorySIP->addResourcesToCmdi();
//throw new IngestServiceException('Debug');
$this->processLog['generatePolicy'] = $this->factorySIP->generatePolicy();
$this->processLog['generateFlatEncryptionMetadata'] = $this->factorySIP->generateFlatEncryptionMetadata();
$this->processLog['createBag'] = $this->factorySIP->createBag();
$this->processLog['doSword'] = $this->factorySIP->doSword();
$this->processLog['doDoorkeeper'] = $this->factorySIP->doDoorkeeper();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
name = FLAT Auth
package = FLAT
description = FLAT Auth
core = 7.x
version = 7.x-0.1-dev
dependencies[] = flat_deposit
dependencies[] = authtoken
249 changes: 249 additions & 0 deletions docker/add-deposit-ui-to-flat/flat_deposit/flat_auth/flat_auth.module
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
<?php

define('FLAT_AUTH_THRESHOLD_EXPIRE', 60 * 5);
define('FLAT_AUTH_THRESHOLD_DELETE', 60 * 10);
define('FLAT_AUTH_MAX_ERROR_COUNT', 10);
define('FLAT_AUTH_MAX_USAGE_COUNT', 10);

function flat_auth_menu() {

$items = [];
$items['flat_auth'] = [

'type' => MENU_LOCAL_TASK,
'title' => 'Flat Auth - Check Token',
'description' => 'Flat Auth - Check Token',
'page callback' => 'flat_auth_check_token',
'access callback' => true,
];

$items['flat_auth/create'] = [

'type' => MENU_LOCAL_TASK,
'title' => 'Flat Auth - Create Token',
'description' => 'Flat Auth - Create Token',
'page callback' => 'flat_auth_create_token',
'access callback' => true,
];

$items['flat_auth/renew'] = [

'type' => MENU_LOCAL_TASK,
'title' => 'Flat Auth - Renew Token',
'description' => 'Flat Auth - Renew Token',
'page callback' => 'flat_auth_renew_token',
'access callback' => true,
];

$items['flat_auth/download'] = [

'type' => MENU_LOCAL_TASK,
'title' => 'Flat Auth - Download file',
'description' => 'Flat Auth - Downloading file test function',
'page callback' => 'flat_auth_download_file',
'access callback' => true,
];

$items['flat_auth/stream'] = [

'type' => MENU_LOCAL_TASK,
'title' => 'Flat Auth - Stream file',
'description' => 'Flat Auth - Streaming file test function',
'page callback' => 'flat_auth_stream_file',
'access callback' => true,
];

$items['admin/config/flat_deposit/flat_auth'] = [

'title' => 'FLAT Auth Configuration',
'description' => 'FLAT Auth Configuration',
'access arguments' => array('admin deposit module'),
'page callback' => 'drupal_get_form',
'page arguments' => array('flat_auth_admin_form'),
'file' => 'includes/admin.inc',
'weight' => 999,
];

return $items;
}

function flat_auth_authtoken_type_info() {

return [

'flat_auth' => [

'entity type' => 'user',
'label' => 'FLAT Auth',
'settings' => [

'threshold expire' => variable_get('flat_auth_expiration_time', FLAT_AUTH_THRESHOLD_EXPIRE),
'threshold delete' => variable_get('flat_auth_deletion_time', FLAT_AUTH_THRESHOLD_DELETE),
'max error count' => variable_get('flat_auth_max_error_count', FLAT_AUTH_MAX_ERROR_COUNT),
'max usage count' => variable_get('flat_auth_max_usage_count', FLAT_AUTH_MAX_USAGE_COUNT),
],
'generate token callback' => 'flat_auth_generate_token',
],
];
}

/**
* Generate an unique token
*
* @return string
*/
function flat_auth_generate_token() {
return drupal_strtoupper(bin2hex(drupal_random_bytes(16)));
}

/**
* Get the bearer token
*/
function flat_auth_get_bearer_token() {

$bearer_token = NULL;

if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
$bearer_token = str_replace('Bearer ', '', $_SERVER['HTTP_AUTHORIZATION']);
} elseif (isset($_SERVER['HTTP_X_AUTHORIZATION'])) {
$bearer_token = str_replace('Bearer ', '', $_SERVER['HTTP_X_AUTHORIZATION']);
} elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
$bearer_token = str_replace('Bearer ', '', $_SERVER['REDIRECT_HTTP_AUTHORIZATION']);
}

return $bearer_token;
}

function flat_auth_check_token() {

$token = flat_auth_get_bearer_token();
$authtoken = authtoken_load($token);

if ($authtoken) {

if (authtoken_authenticate($authtoken->token(), [$authtoken->type()])) {

echo drupal_json_output([

'type' => 'success',
'expiration_time' => (int)variable_get('flat_auth_expiration_time', FLAT_AUTH_THRESHOLD_EXPIRE),
'deletion_time' => (int)variable_get('flat_auth_deletion_time', FLAT_AUTH_THRESHOLD_DELETE),
]);

exit;
}
}

echo drupal_json_output([

'type' => 'error',
'message' => 'Invalid token2',
]);

exit;
}

function flat_auth_get_token() {

global $user;
return flat_auth_get_token_for_user($user);
}

function flat_auth_get_token_for_user($user) {

$entity = $user;

$authtoken = authtoken_assign('flat_auth', $user, $entity);
return $authtoken->token();
}

function flat_auth_renew_token() {

$token = flat_auth_get_bearer_token();
$authtoken = authtoken_load($token);

if ($authtoken) {

if (authtoken_authenticate($authtoken->token(), [$authtoken->type()])) {

if ($user = user_load($authtoken->uid())) {

// renew in db
flat_auth_renew_token_db($authtoken);

$token = flat_auth_get_token_for_user($user);
drupal_add_http_header('Authorization', 'Bearer ' . $token);

echo drupal_json_output([

'type' => 'success',
'expiration_time' => (int)variable_get('flat_auth_expiration_time', FLAT_AUTH_THRESHOLD_EXPIRE),
'deletion_time' => (int)variable_get('flat_auth_deletion_time', FLAT_AUTH_THRESHOLD_DELETE),
]);

exit;
}
}
}

echo drupal_json_output([

'type' => 'error',
'message' => 'Invalid token',
]);

exit;
}

function flat_auth_create_token() {

echo drupal_json_output([
'token' => flat_auth_get_token(),
]);

exit;
}

function flat_auth_download_file($pid, $dsid) {

flat_auth_serve($pid, $dsid, true);
exit;
}

function flat_auth_stream_file($pid, $dsid) {

flat_auth_serve($pid, $dsid, false);
exit;
}

function flat_auth_serve($pid, $dsid, $download = false) {

global $base_url;
$appToken = base64_encode($base_url . '/flat_auth|apptoken|' . flat_auth_get_token());

$url = $base_url . '/tla-decryption/render/' . $pid . '/' . $dsid . '/' . $appToken . '?download=' . ($download ? '1' : '0');
header('Location: ' . $url);
exit;
}

/**
* renew auth token
*
* @param Authtoken $authtoken
* The authentication token.
* @return bool
* Whether the operation was successful.
*/
function flat_auth_renew_token_db(Authtoken $authtoken) {

$query = db_update('authtoken')
->fields(array(
'updated' => REQUEST_TIME,
))
->expression('created', 'NOW()')
->expression('updated', 'NOW()');

$query->condition('token', $authtoken->token());

return ($query->execute() > 0);
}
Loading