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

authenticate token #1066

Open
wants to merge 3 commits into
base: master
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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "unisharp/laravel-filemanager",
"name": "uasoft-indonesia/laravel-filemanager",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This pull request contains namespace change so we cannot merge this. Please undo the namespace change.

"description": "A file upload/editor intended for use with Laravel 5 to 6 and CKEditor / TinyMCE",
"license": "MIT",
"keywords": [
Expand Down
84 changes: 70 additions & 14 deletions public/js/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ var sort_type = 'alphabetic';
var multi_selection_enabled = false;
var selected = [];
var items = [];
var key_auth_token = 'key_auth_token';
var route_check_authenticate = 'route_check_authenticate';
var no_authenticate_redirect_to = 'no_authenticate_redirect_to'

$.fn.fab = function (options) {
var menu = this;
Expand Down Expand Up @@ -258,28 +261,72 @@ function setOpenFolders() {
// ====================

function performLfmRequest(url, parameter, type) {
var data = defaultParameters();

var data = defaultParameters();

if (parameter != null) {
$.each(parameter, function (key, value) {
data[key] = value;
});
}

return $.ajax({
type: 'GET',
beforeSend: function(request) {
var token = getUrlParam('token');
if (token !== null) {
request.setRequestHeader("Authorization", 'Bearer ' + token);
const request = (token) => {
return $.ajax({
type: "GET",
beforeSend: async function(request) {
if (token !== null) {
request.setRequestHeader("Authorization", "Bearer " + token);
}
},
dataType: type || "text",
url: lfm_route + "/" + url,
data: data,
cache: false
});
}

// If authenticate with token, this step check authenticate
var keyAuthToken = localStorage.getItem(key_auth_token);
if (keyAuthToken != null && keyAuthToken != "") {
var token = localStorage.getItem(keyAuthToken);
var urlApiAuthenticate = localStorage.getItem(route_check_authenticate);
return $.ajax({
method: "GET",
url: urlApiAuthenticate,
headers: {
Authorization: "Bearer " + token
},
cache: false
}).then(response => {
return request(token).catch(({statusText}) => {
let redirect_to = localStorage.getItem(no_authenticate_redirect_to);
return displayErrorResponseFromApi(statusText, redirect_to);
});
}).catch(({responseJSON: { data, message}, status}) => {
if(status == 401){
let { authorization, redirect_to } = data;
return displayErrorResponseFromApi(message, redirect_to)
} else {
let redirect_to = localStorage.getItem(no_authenticate_redirect_to);
displayErrorResponseFromApi(message, redirect_to);
}
},
dataType: type || 'text',
url: lfm_route + '/' + url,
data: data,
cache: false
}).fail(function (jqXHR, textStatus, errorThrown) {
displayErrorResponse(jqXHR);
return Promise.resolve()
});
} else {
var token = getUrlParam("token");
return request(token).fail(function(jqXHR, textStatus, errorThrown) {
displayErrorResponse(jqXHR);
});
}
}

function displayErrorResponseFromApi(message, urlRedirectBack){
notifyAuthenticate(`
<div style="max-height:50vh;">
<p>${message}</p>
</div>
`, () => {
window.location.replace(urlRedirectBack)
});
}

Expand Down Expand Up @@ -794,6 +841,15 @@ function notImp() {
notify('Not yet implemented!');
}

function notifyAuthenticate(body, callback = null){
$("#notify")
.find(".btn-secondary")
.unbind()
.click(callback);
$('#notify').modal('show').find('.modal-body').html(body)
$('#notify').find('.btn-primary').hide();
}

function notify(body, callback) {
$('#notify').find('.btn-primary').toggle(callback !== undefined);
$('#notify').find('.btn-primary').unbind().click(callback);
Expand Down
60 changes: 55 additions & 5 deletions src/Controllers/LfmController.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ public function __get($var_name)
*/
public function show()
{
return view('laravel-filemanager::index')
$key_auth_token = \config('lfm')['key_auth_token'];
$no_authenticate_redirect_to = \config('lfm')['no_authenticate_token_redirect_to'];

return view('laravel-filemanager::index', compact('key_auth_token', 'no_authenticate_redirect_to'))
->withHelper($this->helper);
}

Expand All @@ -48,23 +51,23 @@ public function getErrors()
{
$arr_errors = [];

if (! extension_loaded('gd') && ! extension_loaded('imagick')) {
if (!extension_loaded('gd') && !extension_loaded('imagick')) {
array_push($arr_errors, trans('laravel-filemanager::lfm.message-extension_not_found'));
}

if (! extension_loaded('exif')) {
if (!extension_loaded('exif')) {
array_push($arr_errors, 'EXIF extension not found.');
}

if (! extension_loaded('fileinfo')) {
if (!extension_loaded('fileinfo')) {
array_push($arr_errors, 'Fileinfo extension not found.');
}

$mine_config_key = 'lfm.folder_categories.'
. $this->helper->currentLfmType()
. '.valid_mime';

if (! is_array(config($mine_config_key))) {
if (!is_array(config($mine_config_key))) {
array_push($arr_errors, 'Config : ' . $mine_config_key . ' is not a valid array.');
}

Expand Down Expand Up @@ -95,4 +98,51 @@ public function applyIniOverrides()
}
}
}


/**
* If your use token authenticate, before show media manager call this api for checking authenticate
*
* @return object|null
*
*/
public function checkAuthenticate()
{
try {
$guard_name = \config('lfm.guard_name');

$auth = \Auth::guard($guard_name);
if ($auth->check()) {
$response = [
'message' => 'Authorization',
'errors' => [],
'data' => [
'authorization' => true,
'redirect_to' => null,
]
];
$status_code = 200;
} else {
$response = [
'message' => 'No authorization',
'errors' => [],
'data' => [
'authorization' => false,
'redirect_to' => \config('lfm.no_authenticate_token_redirect_to'),
]
];
$status_code = 401;
}

return response($response, $status_code);
} catch (\Exception $e) {
return \response([
'message' => 'Error machine',
'errors' => [
'machine' => [$e->getMessage()],
],
'data' => [],
], 500);
}
}
}
21 changes: 18 additions & 3 deletions src/Lfm.php
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ public function allowMultiUser()
*/
public function allowShareFolder()
{
if (! $this->allowMultiUser()) {
if (!$this->allowMultiUser()) {
return true;
}

Expand All @@ -206,8 +206,11 @@ public function allowShareFolder()
*/
public function translateFromUtf8($input)
{

if ($this->isRunningOnWindows()) {
$input = iconv('UTF-8', mb_detect_encoding($input), $input);
if (gettype($input) == 'string') {
$input = iconv('UTF-8', mb_detect_encoding($input), $input);
}
}

return $input;
Expand Down Expand Up @@ -257,7 +260,7 @@ public function error($error_type, $variables = [])
*/
public static function routes()
{
$middleware = [ CreateDefaultFolder::class, MultiUser::class ];
$middleware = [CreateDefaultFolder::class, MultiUser::class];
$as = 'unisharp.lfm.';
$namespace = '\\UniSharp\\LaravelFilemanager\\Controllers\\';

Expand All @@ -269,6 +272,18 @@ public static function routes()
'as' => 'show',
]);

// if use auth via token, check authenticate
Route::get('/checkauhenticate', [
'uses' => 'LfmController@checkAuthenticate',
'as' => 'checkAuthenticate',
]);
});


$config_middleware = \config('lfm.middleware') ?? [];
$middleware = array_merge($middleware, $config_middleware);
Route::group(compact('middleware', 'as', 'namespace'), function () {

// display integration error messages
Route::get('/errors', [
'uses' => 'LfmController@getErrors',
Expand Down
36 changes: 36 additions & 0 deletions src/config/lfm.php
Original file line number Diff line number Diff line change
Expand Up @@ -169,4 +169,40 @@
'php_ini_overrides' => [
'memory_limit' => '256M',
],

/*
|--------------------------------------------------------------------------
| default prefix route
|--------------------------------------------------------------------------
|
*/

'route_prefix' => env('MIX_FILE_MANAGER_PREFIX_ROUTE', 'laravel-filemanager'),

/*
|--------------------------------------------------------------------------
| authenticate
|--------------------------------------------------------------------------
|
*/

// Example default auth middleware => ['web', 'auth']
'middleware' => [
'web',
],

// Guard default value => web
'guard_name' => 'web',

// Key name token auth in local storage
// If you do not use authenticate with a token default value is null
// Location : browser => inspect element => application => Local Storage
// 'key_auth_token' => 'token',
'key_auth_token' => null,

// If not authenticate redirect to
// Default value => /login
'no_authenticate_redirect_to' => '/login',
// 'no_authenticate_redirect_to' => '/dashboard/login',

];
10 changes: 10 additions & 0 deletions src/views/index.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,16 @@
<script>{!! \File::get(base_path('vendor/unisharp/laravel-filemanager/public/js/script.js')) !!}</script>
{{-- Use the line below instead of the above if you need to cache the script. --}}
{{-- <script src="{{ asset('vendor/laravel-filemanager/js/script.js') }}"></script> --}}
<script>
let keyAuthToken = "{{$key_auth_token}}" ;
let routeCheckAuthenticate = "{{route('unisharp.lfm.checkAuthenticate')}}" ;
let noAuthenticateRedirectTo = "{{$no_authenticate_redirect_to}}" ;

localStorage.setItem(key_auth_token, keyAuthToken);
localStorage.setItem(route_check_authenticate, routeCheckAuthenticate);
localStorage.setItem(no_authenticate_redirect_to, noAuthenticateRedirectTo);
</script>
{{-- use authenticate with token, check --}}
<script>
Dropzone.options.uploadForm = {
paramName: "upload[]", // The name that will be used to transfer the file
Expand Down