From 88c834f4a50eefedcf572f21888b52575bdf1fe9 Mon Sep 17 00:00:00 2001
From: Olav Morken <olav.morken@uninett.no>
Date: Tue, 21 Apr 2009 07:41:42 +0000
Subject: [PATCH] Create helper function for admin authentication.

git-svn-id: https://simplesamlphp.googlecode.com/svn/trunk@1466 44740490-163a-0410-bde0-09ae8108e29a
---
 lib/SimpleSAML/Utilities.php     | 50 ++++++++++++++++++++++++++++++++
 modules/core/www/login-admin.php | 14 +++++++++
 2 files changed, 64 insertions(+)
 create mode 100644 modules/core/www/login-admin.php

diff --git a/lib/SimpleSAML/Utilities.php b/lib/SimpleSAML/Utilities.php
index e4b40bbae..19a66e9ab 100644
--- a/lib/SimpleSAML/Utilities.php
+++ b/lib/SimpleSAML/Utilities.php
@@ -1678,6 +1678,56 @@ class SimpleSAML_Utilities {
 		}
 	}
 
+
+	/**
+	 * Check whether the current user is a admin user.
+	 *
+	 * @return bool  TRUE if the current user is a admin user, FALSE if not.
+	 */
+	public static function isAdmin() {
+
+		$session = SimpleSAML_Session::getInstance();
+
+		return $session->isValid('login-admin');
+	}
+
+
+	/**
+	 * Retrieve a admin login URL.
+	 *
+	 * @param string|NULL $returnTo  The URL the user should arrive on after admin authentication.
+	 * @return string  An URL which can be used for admin authentication.
+	 */
+	public static function getAdminLoginURL($returnTo = NULL) {
+		assert('is_string($returnTo) || is_null($returnTo)');
+
+		if ($returnTo === NULL) {
+			$returnTo = SimpleSAML_Utilities::selfURL();
+		}
+
+		return SimpleSAML_Module::getModuleURL('core/login-admin.php?ReturnTo=' . urlencode($returnTo));
+	}
+
+
+	/**
+	 * Require admin access for current page.
+	 *
+	 * This is a helper-function for limiting a page to admin access. It will redirect
+	 * the user to a login page if the current user doesn't have admin access.
+	 */
+	public static function requireAdmin() {
+
+		if (self::isAdmin()) {
+			return;
+		}
+
+		/* Not authenticated as admin user. Start authentication. */
+		$config = SimpleSAML_Configuration::getInstance();
+		SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'auth/login-admin.php',
+			array('RelayState' => SimpleSAML_Utilities::selfURL())
+		);
+	}
+
 }
 
 ?>
\ No newline at end of file
diff --git a/modules/core/www/login-admin.php b/modules/core/www/login-admin.php
new file mode 100644
index 000000000..16acc1e0f
--- /dev/null
+++ b/modules/core/www/login-admin.php
@@ -0,0 +1,14 @@
+<?php
+/*
+ * Helper page for starting a admin login. Can be used as a target for links.
+ */
+
+if (!array_key_exists('ReturnTo', $_REQUEST)) {
+	throw new SimpleSAML_Error_BadRequest('Missing ReturnTo parameter.');
+}
+$returnTo = $_REQUEST['ReturnTo'];
+
+SimpleSAML_Utilities::requireAdmin();
+
+SimpleSAML_Utilities::redirect($returnTo);
+
-- 
GitLab