Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Basic Authentication Example

Marlon Monzon edited this page Jan 16, 2018 · 4 revisions

Basic Authentication Example

Connector PHP - php/connector.minimal.php

<?php

error_reporting(0); // Set E_ALL for debuging

/***** basic auth section *****/
session_start();
$admins = array('admin' => true); // Rewite your setting
if (isset($_GET['login']) || isset($_GET['logout']) || isset($_GET['status'])) {
	$auths = array( // Rewrite your setting
		'admin' => 'admin_pass',
		'user1' => 'user1_pass'
	);
	if (!isset($_SERVER['PHP_AUTH_USER']) && !isset($_GET['status'])) {
		header("WWW-Authenticate: Basic realm=\"elFinder-demo\"");
		header("HTTP/1.0 401 Unauthorized");
		echo '{"error": "Login failed."}';
		exit;
	} else {
		//	|| !isset($_SESSION['ELFINDER_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] !== $_SESSION['ELFINDER_AUTH_USER']
		if (isset($_GET['logout'])) {
			unset($_SESSION['ELFINDER_AUTH_USER']);
			echo '{"uname": ""}';
		} else {
			if (isset($_SERVER['PHP_AUTH_USER']) && isset($auths[$_SERVER['PHP_AUTH_USER']]) && $auths[$_SERVER['PHP_AUTH_USER']] === $_SERVER['PHP_AUTH_PW']) {
				if (isset($_GET['status'])) {
					echo '{"uname": "'.(isset($_SESSION['ELFINDER_AUTH_USER'])? $_SESSION['ELFINDER_AUTH_USER'] : '').'"}';
				} else {
					$_SESSION['ELFINDER_AUTH_USER'] = $_SERVER['PHP_AUTH_USER'];
					echo '{"uname": "'.$_SERVER['PHP_AUTH_USER'].'"}';
				}
			} else {
				if (isset($_GET['status'])) {
					echo '{"uname": ""}';
				} else {
					header("WWW-Authenticate: Basic realm=\"elFinder-demo\"");
					header("HTTP/1.0 401 Unauthorized");
					echo '{"error": "Login failed."}';
					exit;
				}
			}
		}
	}
	exit();
}
$uname = '';
if (!empty($_SESSION['ELFINDER_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_USER'])) {
	$uname = ($_SESSION['ELFINDER_AUTH_USER'] === $_SERVER['PHP_AUTH_USER'])? $_SERVER['PHP_AUTH_USER'] : '';
}
$isAdmin = isset($admins[$uname]);
$isUser = $uname? true : false;
/******************************/


include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderConnector.class.php';
include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinder.class.php';
include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderVolumeDriver.class.php';
include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderVolumeLocalFileSystem.class.php';
// Required for MySQL storage connector
// include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderVolumeMySQL.class.php';
// Required for FTP connector support
// include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderVolumeFTP.class.php';

/**
 * # Dropbox volume driver need "dropbox-php's Dropbox" and "PHP OAuth extension" or "PEAR's HTTP_OAUTH package"
 * * dropbox-php: http://www.dropbox-php.com/
 * * PHP OAuth extension: http://pecl.php.net/package/oauth
 * * PEAR's HTTP_OAUTH package: http://pear.php.net/package/http_oauth
 *  * HTTP_OAUTH package require HTTP_Request2 and Net_URL2
 */
// Required for Dropbox.com connector support
// include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderVolumeDropbox.class.php';

// Dropbox driver need next two settings. You can get at https://www.dropbox.com/developers
// define('ELFINDER_DROPBOX_CONSUMERKEY',    '');
// define('ELFINDER_DROPBOX_CONSUMERSECRET', '');
// define('ELFINDER_DROPBOX_META_CACHE_PATH',''); // optional for `options['metaCachePath']`

/**
 * Simple function to demonstrate how to control file access using "accessControl" callback.
 * This method will disable accessing files/folders starting from '.' (dot)
 *
 * @param  string  $attr  attribute name (read|write|locked|hidden)
 * @param  string  $path  file path relative to volume root directory started with directory separator
 * @return bool|null
 **/
function rwaccess($attr, $path, $data, $volume) {
	return strpos(basename($path), '.') === 0       // if file/folder begins with '.' (dot)
		? !($attr == 'read' || $attr == 'write')    // set read+write to false, other (locked+hidden) set to true
		:  null;                                    // else elFinder decide it itself
}

function roaccess($attr, $path, $data, $volume) {
	return strpos(basename($path), '.') === 0       // if file/folder begins with '.' (dot)
		? !($attr == 'read' || $attr == 'write')    // set read+write to false, other (locked+hidden) set to true
		: ($attr == 'read' || $attr == 'locked');   // else read only
}


// Documentation for connector options:
// https://github.com/Studio-42/elFinder/wiki/Connector-configuration-options
$opts = array(
	// 'debug' => true,
	'roots' => array(
		array(
			'driver'        => 'LocalFileSystem',           // driver for accessing file system (REQUIRED)
			'path'          => '../files/',                 // path to files (REQUIRED)
			'URL'           => dirname($_SERVER['PHP_SELF']) . '/../files/', // URL to files (REQUIRED)
			'uploadDeny'    => array('all'),                // All Mimetypes not allowed to upload
			'uploadAllow'   => array('image', 'text/plain'),// Mimetype `image` and `text/plain` allowed to upload
			'uploadOrder'   => array('deny', 'allow'),      // allowed Mimetype `image` and `text/plain` only
			'accessControl' => $isAdmin? 'rwaccess' : 'roaccess'  // Admin: R+W, Other: R
		)
	)
);

// run elFinder
$connector = new elFinderConnector(new elFinder($opts));
$connector->run();

JavaScript - js/elfinderBasicAuth.js

(function(){
	var style = document.createElement('style'),
		sheet;
	document.head.appendChild(style);
	sheet = style.sheet;
	sheet.insertRule('.elfinder-button-icon-login { background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAgCAYAAAAbifjMAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3wwODgkfXMcF3gAAA0ZJREFUSMftlVFo1VUYwH/nf+/uvW4O3NA23R0uHdPV1qJ6CwwiCgKfJNCXIiuxKAipoIdi9Bb1WA8rCcKXJMQgjIweTCgUdWipTMttuEWhbd61sf3/5/u+c3rYdrcbblhvQQcO39P3+w7nfN/vOP7FunjwlXdDsANmOp3/J4mXP3n15xCss7ChlZHRSzQnBa0C+vv7YwiBxW1m1bi3J5IQKKxvYe3dnQQLxJGfEMmoAsyMcrkMgHOuJsZ4kaaHHgYc2cwEJhkxBkSUZDkA4ER6nEjEOVfdZkYwI62MI7NTBPHEYIhktQDnHH9kN/mq8kUNQNUTTDD1BPUEzYgh4H1KfucHj8VggQt6isFbP9DR1oGqcXTsMLva9szD1RNVCeIx9RAdMQRUUvKmxlOP7kKCoaZoUMSEM+k5Phs+xJ6tTyMLlU0yoqa0bLjBL1HxPiOvYngVJtNJvAliAji679nOYHqer0eP0VEPpor5jMaGWzSvm6AuN8e0pCSqRmaeQlKkmCtRzJXIuRxnzw1SGf+TJ7fsRCQlaIZJRmUyx+joejJfN/+MKsrhLz9HxTA1yuU2NBhT49M8f99+nHN4nxFUCJJhIkxkeQgBEU9y8u3T7vt3zrru3/p4+d4DTP06w8T1Ci/0vbj0CpLO34EKpguwEFD1S42kqjjniBbZf/9LNc3kJZtPlowgHucCMa4A2Nu3r1p5ESAyX7W+qZ2ggmazEH/HTHEDAwNxaGiIsbGxmv5fHndvGaWhsZFiqYFCqZ66QpHpmQrXrwzedHcyhR8/136XmW41k24z7QrBykm+sNskm3L/+6B2nCORE+nxavKd+KDmBN/OHWPKV3D1rqYX/u4DcEs+WAQMNZ9nU8tGmmwdh4YPYmrV+fiw/YGVfQDwxPuP/Ni6qZXerl40KNs7tyELXjhy5OjqPnj8vR2fbt64ube3q4dKWmFWZhETfBAa8mtRNUT8yj745vWTz1wZvnrp9IUzJC5HMVeilF9DKbeGzDwqtroPAL5761TPjjdcnEvnUFWuXRvBNGBqBAur+qB6iVtubGPEXSWJOV578M2aXtDLH9X4wLl81QfJ8nF+tnsf0Wr/hNv5IIi/vQ+SJPkP+uAvyoJNfRlNM5QAAAAASUVORK5CYII="); background-position: 0 0; }', 0);
	sheet.insertRule('.elfinder-button-icon-logout { background-position: 0 -16px; }', 1);
})();
$.fn.elfinderloginbutton = function(cmd) {
	return this.each(function() {
		var button = $(this).elfinderbutton(cmd),
			icon   = button.children('.elfinder-button-icon');
		cmd.change(function() {
			var logined = cmd.value? true : false;
			icon.toggleClass('elfinder-button-icon-logout', logined);
			button.attr('title', logined? cmd.fm.i18n('logout', cmd.value) : cmd.fm.i18n('login'));
		});
	});
}
elFinder.prototype.commands.login = function() {
	var self = this,
		fm   = this.fm,
		url  = fm.options.url,
		aopt = {
			dataType: 'json',
			headers: fm.options.customHeaders,
			xhrFields: fm.options.xhrFields
		};
	this.alwaysEnabled  = true;
	this.updateOnSelect = false;
	this.options = {
		ui       : 'loginbutton',
		loginUrl : url+'?login',
		logoutUrl: url+'?logout',
		statusUrl: url+'?status'
	};
	this.value = null;
	this.handlers = {
		'open': function(){
			if (self.value === null) {
				self.value = '';
				$.ajax(self.options.statusUrl, aopt).done(function(res){
					self.value = res.uname? res.uname : '';
					self.update(void(0), self.value);
				});
			}
		} 
	};
	
	this.getstate = function() {
		return this.value? 1 : 0;
	};
	
	this.exec = function() {
		$.ajax(self.options[self.value? 'logoutUrl' : 'loginUrl'], aopt).done(function(res){
			if (res.error) {
				fm.error(res.error);
			} else {
				self.update(void(0), res.uname? res.uname : '');
				fm.sync();
			}
		});
	};
}

elFinder.prototype._options.commands.push('login');
elFinder.prototype._options.uiOptions.toolbar.push(['login']);
elFinder.prototype.i18.en.messages.logout = '$1: logout';

Front end HTML - elfinder.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>elFinder 2.1</title>

		<!-- jQuery and jQuery UI (REQUIRED) -->
		<link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
		<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

		<!-- elFinder CSS (REQUIRED) -->
		<link rel="stylesheet" type="text/css" href="css/elfinder.min.css">
		<link rel="stylesheet" type="text/css" href="css/theme.css">

		<!-- elFinder JS (REQUIRED) -->
		<script src="js/elfinder.min.js"></script>

		<!-- elFinder Basic Auth JS -->
		<script src="js/elfinderBasicAuth.js"></script>

		<!-- elFinder initialization (REQUIRED) -->
		<script type="text/javascript" charset="utf-8">
			// Documentation for client options:
			// https://github.com/Studio-42/elFinder/wiki/Client-configuration-options
			$(document).ready(function() {
				$('#elfinder').elfinder({
					url : 'php/connector.minimal.php'  // connector URL (REQUIRED)
				});
			});
		</script>
	</head>
	<body>

		<!-- Element where elFinder will be created (REQUIRED) -->
		<div id="elfinder"></div>

	</body>
</html>

Clone this wiki locally

Morty Proxy This is a proxified and sanitized view of the page, visit original site.