from server

This commit is contained in:
Shohrat 2023-09-04 17:34:14 +05:00
parent 90da3c14a7
commit cff2ae027f
23 changed files with 588 additions and 17 deletions

View File

@ -30,7 +30,9 @@
"october/system": "1.1.*", "october/system": "1.1.*",
"october/backend": "1.1.*", "october/backend": "1.1.*",
"october/cms": "1.1.*", "october/cms": "1.1.*",
"laravel/framework": "~6.0" "laravel/framework": "~6.0",
"rluders/cors": "^1.0",
"fruitcake/laravel-cors": "^3.0"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^8.4|^9.3.3", "phpunit/phpunit": "^8.4|^9.3.3",

View File

@ -92,7 +92,7 @@ return [
| |
*/ */
'timezone' => 'UTC', 'timezone' => 'Asia/Ashgabat',
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------

View File

@ -80,7 +80,7 @@ return [
| |
*/ */
'backendTimezone' => 'UTC', 'backendTimezone' => 'Asia/Ashgabat',
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------

View File

@ -22,7 +22,7 @@ App::before(function ($request) {
* Other pages * Other pages
*/ */
Route::group([ Route::group([
'middleware' => ['web'], 'middleware' => ['web','\Barryvdh\Cors\HandleCors'],
'prefix' => Config::get('cms.backendUri', 'backend') 'prefix' => Config::get('cms.backendUri', 'backend')
], function () { ], function () {
Route::any('{slug?}', 'Backend\Classes\BackendController@run')->where('slug', '(.*)?'); Route::any('{slug?}', 'Backend\Classes\BackendController@run')->where('slug', '(.*)?');

View File

@ -7,7 +7,7 @@ App::before(function ($request) {
/* /*
* Combine JavaScript and StyleSheet assets * Combine JavaScript and StyleSheet assets
*/ */
Route::any('combine/{file}', 'System\Classes\SystemController@combine'); Route::any('combine/{file}', 'System\Classes\SystemController@combine')->middleware('\Barryvdh\Cors\HandleCors');
/* /*
* Resize image assets * Resize image assets

View File

@ -38,7 +38,7 @@ class CategoriesController extends Controller
return response()->json( return response()->json(
CategoryResource::collection($this->Category::orderBy('nest_left', $data['sort_order'] ?? 'asc') CategoryResource::collection($this->Category::orderBy('nest_left', $data['sort_order'] ?? 'asc')
->paginate($data['count'] ?? 7))->response()->getData(), 200); ->paginate($data['count'] ?? 7))->response()->getData(), 200)->header('Access-Control-Allow-Origin', '*');
} }

View File

@ -54,7 +54,7 @@ class PostsController extends Controller
//$data = $this->Post::select('id','title','slug', 'excerpt', 'published_at')->with(['categories:id,name'])->listFrontEnd($filter); //$data = $this->Post::select('id','title','slug', 'excerpt', 'published_at')->with(['categories:id,name'])->listFrontEnd($filter);
$data = response()->json( $data = response()->json(
PostResource::collection($this->Post::with(['categories:id,name'])->listFrontEnd($filter))); PostResource::collection($this->Post::with(['categories:id,name'])->listFrontEnd($filter)))->header('Access-Control-Allow-Origin', '*');
return $data; return $data;
//return $this->helpers->apiArrayResponseBuilder(200, 'success', $data); //return $this->helpers->apiArrayResponseBuilder(200, 'success', $data);
@ -143,7 +143,7 @@ class PostsController extends Controller
$data = response()->json(PostResource::collection( $data = response()->json(PostResource::collection(
$this->Post::with(['categories']) $this->Post::with(['categories'])
->listFrontEnd($filter) ->listFrontEnd($filter)
)->response()->getData(), 200); )->response()->getData(), 200)->header('Access-Control-Allow-Origin', '*');
return $data; return $data;
@ -216,11 +216,19 @@ class PostsController extends Controller
// PostResource::collection($this->Post::isPublished()->select("id", "excerpt") // PostResource::collection($this->Post::isPublished()->select("id", "excerpt")
// ->leftJoin('vdomah_blogviews_views as pv', 'pv.post_id', '=', 'rainlab_blog_posts.id')->paginate(8))); // ->leftJoin('vdomah_blogviews_views as pv', 'pv.post_id', '=', 'rainlab_blog_posts.id')->paginate(8)));
$posts = response()->json( // $posts = response()->json(
Post::isPublished()->select("id", "title", "slug", "excerpt", "published_at", "type", "views", "video", "powerseo_title", "powerseo_description", "powerseo_keywords") // Post::isPublished()->select("id", "title", "slug", "excerpt", "published_at", "type", "views", "video", "powerseo_title", "powerseo_description", "powerseo_keywords")
->with("featured_images") // ->with("featured_images")
->with("categories") // ->with("categories")
->leftJoin('vdomah_blogviews_views as pv', 'pv.post_id', '=', 'rainlab_blog_posts.id')->listFrontEnd($filter)); // ->leftJoin('vdomah_blogviews_views as pv', 'pv.post_id', '=', 'rainlab_blog_posts.id')->listFrontEnd($filter));
$posts = response()->json(PostResource::collection(
$this->Post::with(['categories'])
->leftJoin('vdomah_blogviews_views as pv', 'pv.post_id', '=', 'rainlab_blog_posts.id')
->orderByRaw('pv.views DESC')
->listFrontEnd($filter)
)->response()->getData(), 200)->header('Access-Control-Allow-Origin', '*');
return $posts; return $posts;
} }

View File

@ -36,7 +36,9 @@ class Post extends Model
'powerseo_title' => 'required', 'powerseo_title' => 'required',
'powerseo_description' => 'required', 'powerseo_description' => 'required',
'powerseo_keywords' => 'required', 'powerseo_keywords' => 'required',
'excerpt' => 'required' 'excerpt' => 'required',
'categories' => 'required',
'awtor' => 'required',
]; ];
/** /**
@ -270,14 +272,14 @@ class Post extends Model
extract(array_merge([ extract(array_merge([
'page' => 1, 'page' => 1,
'perPage' => 30, 'perPage' => 30,
'sort' => 'created_at', 'sort' => 'published_at',
'categories' => null, 'categories' => null,
'exceptCategories' => null, 'exceptCategories' => null,
'category' => null, 'category' => null,
'search' => '', 'search' => '',
'published' => true, 'published' => true,
'featured' => false, 'featured' => null,
'type' => 'photo', 'type' => '',
'date' => '', 'date' => '',
'exceptPost' => null 'exceptPost' => null
], $options)); ], $options));

View File

@ -47,6 +47,7 @@ secondaryTabs:
label: 'rainlab.blog::lang.post.published_by' label: 'rainlab.blog::lang.post.published_by'
span: right span: right
type: dropdown type: dropdown
hidden: true
emptyOption: 'rainlab.blog::lang.post.current_user' emptyOption: 'rainlab.blog::lang.post.current_user'
published_at: published_at:
tab: 'rainlab.blog::lang.post.tab_manage' tab: 'rainlab.blog::lang.post.tab_manage'

View File

@ -0,0 +1,12 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: rluders # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']

76
plugins/rluders/cors/.gitignore vendored Normal file
View File

@ -0,0 +1,76 @@
# Created by https://www.gitignore.io/api/osx,linux,windows,composer
### Composer ###
composer.phar
/vendor/
# Commit your application's lock file http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file
# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file
# composer.lock
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### OSX ###
*.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Windows ###
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# End of https://www.gitignore.io/api/osx,linux,windows,composer

View File

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Ricardo Lüders
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,81 @@
<?php
namespace RLuders\Cors;
use Config;
use System\Classes\PluginBase;
use System\Classes\SettingsManager;
use RLuders\Cors\Models\Settings as PluginSettings;
/**
* CORS Plugin Information File.
*/
class Plugin extends PluginBase
{
/**
* @var boolean Determine if this plugin should have elevated privileges.
*/
public $elevated = true;
/**
* Returns information about this plugin.
*
* @return array
*/
public function pluginDetails()
{
return [
'name' => 'rluders.cors::lang.plugin.name',
'description' => 'rluders.cors::lang.plugin.description',
'author' => 'Ricardo Lüders',
'icon' => 'icon-exchange',
];
}
/**
* Register the plugin settings
*
* @return array
*/
public function registerSettings()
{
return [
'settings' => [
'label' => 'rluders.cors::lang.settings.menu_label',
'description' => 'rluders.cors::lang.settings.menu_description',
'category' => SettingsManager::CATEGORY_MISC,
'icon' => 'icon-exchange',
'class' => 'RLuders\Cors\Models\Settings',
'order' => 600,
'permissions' => ['rluders.cors.access_settings'],
]
];
}
/**
* Register the plugin permissions
*
* @return array
*/
public function registerPermissions()
{
return [
'rluders.cors.access_settings' => [
'tab' => 'rluders.cors::lang.plugin.name',
'label' => 'rluders.cors::lang.permissions.settings'
]
];
}
/**
* Register method, called when the plugin is first registered.
*
* @return void
*/
public function register()
{
$this->app->register(\RLuders\Cors\Providers\CorsServiceProvider::class);
$this->app['router']->middleware('cors', \Barryvdh\Cors\HandleCors::class);
$this->app['router']->prependMiddlewareToGroup('api', \Barryvdh\Cors\HandleCors::class);
}
}

View File

@ -0,0 +1,51 @@
# CORS Plugin
<p align="left">
<a href="https://octobercms.com/plugin/rluders-cors">
<img src="https://img.shields.io/badge/OctoberCMS-Plugin-%23EE7203.svg">
</a>
<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2FHDXT4QTD7RA&source=url">
<img src="https://img.shields.io/badge/Donate-PayPal-green.svg">
</a>
<a href="https://opensource.org/licenses/MIT">
<img src="https://img.shields.io/github/license/rluders/oc-cors-plugin.svg">
</a>
<a href="https://snyk.io//test/github/rluders/oc-cors-plugin?targetFile=composer.lock"><img src="https://snyk.io//test/github/rluders/oc-cors-plugin/badge.svg?targetFile=composer.lock" alt="Known Vulnerabilities" data-canonical-src="https://snyk.io//test/github/rluders/oc-cors-plugin?targetFile=composer.lock" style="max-width:100%;"></a>
</p>
This plugin provides a simple CORS support your for [OctoberCMS](http://www.octobercms.com) implementing the [barryvdh/laravel-cors](https://github.com/barryvdh/laravel-cors).
## Installation
### From OctoberCMS
To install from OctoberCMS you can [access the plugin page](https://octobercms.com/plugin/rluders-cors) or search for `CORS` in your OctoberCMS Dashboard and install the `RLuders.CORS` Plugin.
### From repository
1. Clone this repository:
`$ git clone https://github.com/rluders/oc-cors-plugin.git plugins/rluders/cors`
2. Install the composer dependencies:
`$ cd plugins/rluders/cors`
`$ composer install`
3. Configure it on your OctoberCMS Backend.
4. Use it on your `route.php`
```php
<?php
Route::group(['prefix' => 'api/e1', 'middleware' => ['\Barryvdh\Cors\HandleCors']], function(){
// routes here
});
```
## LICENSE
MIT

View File

@ -0,0 +1,27 @@
{
"name": "rluders/cors",
"type": "october-plugin",
"description": "CORS plugin for OctoberCMS",
"keywords": ["october", "cms", "octobercms", "api", "authentication", "cors"],
"homepage": "http://www.luders.com.br",
"license": "MIT",
"authors": [
{
"name": "Ricardo Lüders",
"email": "ricardo@luders.com.br",
"homepage": "http://www.luders.com.br",
"role": "Developer"
}
],
"autoload": {
"psr-4": {
"RLuders\\Cors\\": ""
}
},
"require": {
"php": ">=7.0",
"composer/installers": "~1.0",
"barryvdh/laravel-cors": "^0.11.0@dev"
},
"minimum-stability": "dev"
}

View File

@ -0,0 +1,41 @@
<?php
return [
'plugin' => [
'name' => 'CORS',
'description' => 'Cross-Origin Resource Sharing.',
],
'permissions' => [
'settings' => 'Manage CORS',
],
'settings' => [
'menu_label' => 'CORS',
'menu_description' => 'Configure the CORS',
'fields' => [
'supportsCredentials' => [
'label' => 'Support credentials',
'comment' => "Enable it to support credentials between domains."
],
'allowedOrigins' => [
'label' => 'Allowed Origins',
'comment' => 'The domains that do requests to your site (use * for all domains).'
],
'allowedHeaders' => [
'label' => 'Allowed Headers',
'comment' => 'The headers that are supported.'
],
'allowedMethods' => [
'label' => 'Allowed Methods',
'comment' => 'The HTTP methods that can be requested (use * for all methods).'
],
'exposedHeaders' => [
'label' => 'Exposed Headers',
'comment' => 'The headers that can be exposed.'
],
'maxAge' => [
'label' => 'Max Age',
'comment' => 'Set Access-Control-Max-Age to this value.'
]
]
]
];

View File

@ -0,0 +1,41 @@
<?php
return [
'plugin' => [
'name' => 'CORS',
'description' => 'Cross-Origin Resource Sharing.',
],
'permissions' => [
'settings' => 'Gerenciar CORS',
],
'settings' => [
'menu_label' => 'CORS',
'menu_description' => 'Configurar o CORS',
'fields' => [
'supportsCredentials' => [
'label' => 'Suportar credenciais',
'comment' => "Habilite para suportar credenciais entre domínios."
],
'allowedOrigins' => [
'label' => 'Origens permitidas',
'comment' => 'Os domínios que podem realizar requisições para o seu site (use * para permitir todos).'
],
'allowedHeaders' => [
'label' => 'Headers permitidos',
'comment' => 'Os headers que são suportados.'
],
'allowedMethods' => [
'label' => 'Métodos permitidos',
'comment' => 'Os médotos HTTP que podem ser requisitados (use * para permitir todos).'
],
'exposedHeaders' => [
'label' => 'Headers expostos',
'comment' => 'Os headers que podem ser expostos.'
],
'maxAge' => [
'label' => 'Idade máxima',
'comment' => 'Define o valor para o header Access-Control-Max-Age.'
]
]
]
];

View File

@ -0,0 +1,44 @@
<?php
namespace RLuders\Cors\Models;
use Model;
class Settings extends Model
{
/**
* Model extensions
*
* @var array
*/
public $implement = ['System.Behaviors.SettingsModel'];
/**
* Settings code
*
* @var string
*/
public $settingsCode = 'rluders_cors_settings';
/**
* Settings form
*
* @var string
*/
public $settingsFields = 'fields.yaml';
/**
* Initial plugin settings
*
* @return void
*/
public function initSettingsData()
{
$this->supportsCredentials = false;
$this->allowedOrigins = '*';
$this->allowedHeaders = 'Content-Type X-Requested-With';
$this->allowedMethods = '*';
$this->exposedHeaders = '';
$this->maxAge = 0;
}
}

View File

@ -0,0 +1 @@
<p><?= e(trans('rluders.cors::lang.settings.hint_templates')) ?></p>

View File

@ -0,0 +1,47 @@
# ===================================
# Field Definitions
# ===================================
fields:
# CORS Settings
supportsCredentials:
span: left
label: rluders.cors::lang.settings.fields.supportsCredentials.label
comment: rluders.cors::lang.settings.fields.supportsCredentials.comment
type: switch
allowedOrigins:
span: left
label: rluders.cors::lang.settings.fields.allowedOrigins.label
comment: rluders.cors::lang.settings.fields.allowedOrigins.comment
type: taglist
separator: space
allowedHeaders:
span: left
label: rluders.cors::lang.settings.fields.allowedHeaders.label
comment: rluders.cors::lang.settings.fields.allowedHeaders.comment
type: taglist
separator: space
allowedMethods:
span: left
label: rluders.cors::lang.settings.fields.allowedMethods.label
comment: rluders.cors::lang.settings.fields.allowedMethods.comment
type: taglist
separator: space
exposedHeaders:
span: left
label: rluders.cors::lang.settings.fields.exposedHeaders.label
comment: rluders.cors::lang.settings.fields.exposedHeaders.comment
type: taglist
separator: space
maxAge:
span: left
label: rluders.cors::lang.settings.fields.maxAge.label
comment: rluders.cors::lang.settings.fields.maxAge.comment
type: number

View File

@ -0,0 +1,103 @@
<?php
namespace RLuders\Cors\Providers;
use Config;
use Asm89\Stack\CorsService;
use Barryvdh\Cors\HandleCors;
use Barryvdh\Cors\HandlePreflight;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use RLuders\Cors\Models\Settings;
class CorsServiceProvider extends BaseServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton(
CorsService::class,
function ($app) {
$options = $app['config']->get('cors');
if (isset($options['allowedOrigins'])) {
foreach ($options['allowedOrigins'] as $origin) {
if (strpos($origin, '*') !== false) {
$options['allowedOriginsPatterns'][] = $this->convertWildcardToPattern($origin);
}
}
}
return new CorsService($options);
}
);
}
/**
* Add the Cors middleware to the router.
*
*/
public function boot()
{
$this->loadConfiguration();
$kernel = $this->app->make(Kernel::class);
// When the HandleCors middleware is not attached globally, add the PreflightCheck
if (!$kernel->hasMiddleware(HandleCors::class)) {
$kernel->prependMiddleware(HandlePreflight::class);
}
$this->app['router']->middleware('cors', \Barryvdh\Cors\HandleCors::class);
}
/**
* Create a pattern for a wildcard, based on Str::is() from Laravel
*
* @see https://github.com/laravel/framework/blob/5.5/src/Illuminate/Support/Str.php
* @param $pattern
* @return string
*/
protected function convertWildcardToPattern($pattern)
{
$pattern = preg_quote($pattern, '#');
// Asterisks are translated into zero-or-more regular expression wildcards
// to make it convenient to check if the strings starts with the given
// pattern such as "library/*", making any string check convenient.
$pattern = str_replace('\*', '.*', $pattern);
return '#^'.$pattern.'\z#u';
}
/**
* Load plugin configuration
*
* @return void
*/
protected function loadConfiguration()
{
Config::set(
'cors',
[
'supportsCredentials' => (bool)Settings::get('supportsCredentials'),
'allowedOrigins' => explode(' ', Settings::get('allowedOrigins')),
'allowedHeaders' => explode(' ', Settings::get('allowedHeaders')),
'allowedMethods' => explode(' ', Settings::get('allowedMethods')),
'exposedHeaders' => explode(' ', Settings::get('exposedHeaders')),
'maxAge' => (int)Settings::get('maxAge')
]
);
}
}

View File

@ -0,0 +1,13 @@
1.0.0:
- First version of RLuders.Cors
1.0.1:
- Fix the icon
1.0.2:
- Fix plugin dependencies
- Fix English language
- Adds Brazilian Portuguese language
- Replace the namespace RLuders\CORS to RLuders\Cors
1.0.3:
- Adds the middleware to the api Middleware Group
1.0.4:
- Update dependencies