Server static images files on Lumen - lumen

Lumen handles requests by routing them.
How can I serve static image file instead of creating an API to access the images?
Not something like this:
public function viewFile($name){
return response()->make(Storage::disk('public')->get($name), 200, [
'Content-Type' => Storage::mimeType($name),
'Content-Disposition' => 'inline; '.$name,
]);
}

Couldn't you just put them all in a directory called static/ and then tweak your .htaccess file to not rewrite those URLs to lumen?

Related

RequestMiddlewares.php: new handling? (TYPO3 Extbase)

This used to work in TYPO3 9 and TYPO3 10 but is not working from me in TYPO3 11:
EXTDIR/Configuration/RequestMiddlewares.php
<?php
return [
'frontend' => [
'varioous/rest/mail-chimp-middleware' => [
'target' => Varioous\Rest\MailChimpMiddleware::class,
'before' => [
'typo3/cms-frontend/eid',
'typo3/cms-frontend/tsfe',
],
],
],
];
I've looked at this description here https://docs.typo3.org/m/typo3/reference-coreapi/11.5/en-us/ApiOverview/RequestHandling/Index.html but I can't find the problem. The code is from this example: https://various.at/news/typo3-tipps-und-tricks-psr-15-mideelware-am-beispiel-mailchimp-webhook and has been adjusted to a custom made extension that has been working fine with TYPO3 9 and TYPO3 10. The particular extension belongs to the customer and I am not permitted to post it here. It is configured exactly as the mailchimp extension is in the how-to and I am sure the author used that how-to as a reference. As it seems, the mailchimp extension from the TER stopped using middleware - so I can't use the current version as a reference to fix my problem.
With this temporary workaround it's working fine:
<?php
return [
'frontend' => [
'varioous/rest/mail-chimp-middleware' => [
'target' => Varioous\Rest\MailChimpMiddleware::class,
'before' => [
# 'typo3/cms-frontend/eid',
# 'typo3/cms-frontend/tsfe',
],
],
],
];
How do I have to adjust the references to 'typo3/cms-frontend/eid' and 'typo3/cms-frontend/tsfe' for TYPO3 11? When I look up HTTP Middlewares (PSR-15) in the Configuration BackEnd module I can find them in the frontend category:
typo3/cms-frontend/eid = TYPO3\CMS\Frontend\Middleware\EidHandler
typo3/cms-frontend/tsfe = TYPO3\CMS\Frontend\Middleware\TypoScriptFrontendInitialization
FYI Further description of the Problem:
Once the extension is activated, ALL local extbase extensions stop working. For Example:
#1316104317 TYPO3\CMS\Extbase\Mvc\Exception
The default controller for extension "News" and plugin "Pi1" can not be determined. Please check for TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin() in your ext_localconf.php.
Of course there is nothing wrong with the news extension. I temporarily added a debug output in the file typo3/sysext/extbase/Classes/Mvc/Web/RequestBuilder.php
protected function loadDefaultValues()
{
$configuration = $this->configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK);
print_r($configuration);
When the extension with the middleware is activated, the value "controllerConfiguration" in the array returned from the ConfigurationManager is empty (for all local extensions).

how to access header in lumen routing file(web.php)

how to access header in routing file lumen ?
i want to use header parameters values as namespace in route group in web.php.
example :
$router->group(['namespace' => 'Request::header('version')'], function() use ($router)
{
$router->post('login', 'UserController#loginUser');
$router->post('test', 'UserController#testApi');
});
if request header version param v1 then it use v1 namespace,if v2 then use v2 namespace.something like versioning.
If you just want a way to grab the version from header, you can try putting Request as callback parameter as seen:
$router->get('/head', function(\Illuminate\Http\Request $request) {
return $request->header('version');
});
above should return whatever value you put as header with version key.
But I personally suggest you to try separating the route group for this. Say you'll have
$app->router->group([
'namespace' => 'App\Http\Controllers\Api',
'prefix'=> 'api/v1/',
'middleware' => ['jwt.auth', 'student_access_token']
], function ($router) {
require __DIR__.'/../routes/api.php';
});
and then for other version you just define the same on bootstrap/app.php directing to other route files. Hope it helps.

signup to Laravel from a different server

I want to show a signup form on a website but then when user hits submit, the form data will be posted to a Laravel app (on a different server) for registration.
So far, laravel stops it throwing the CSRF not found exception. Any idea how to work around it ?
If both applications are yours?
You can create a new middleware group:
protected $middlewareGroups = [
'web' => [
...
],
'remote-login' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
// \App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
Commenting/removing/disabling the VerifyCsrfToken middleware. Then map it to a new file:
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
Route::middleware('remote-login')
->namespace($this->namespace)
->group(base_path('routes/remote-login.php'));
}
Then in your routes/remote-login.php, you better create a non-trivial login route:
Route::group(['prefix' => 'remote-login'], function () {
Route::get('/auth/8g7h6jk5l4oA/', function () {
dd('do you authentication');
});
});
Antonio's approach will work, but it's easier to just add the routes you don't want protected by the CSRF middleware to the $except array in app/Http/Middleware/VerifyCsrfToken.php.

How to Upload Image to AWS server from rails Controller

Please Help for Upload image on AWS server in Controller.
I want following things to do.
1. Submit form data with image.
2. Get the image in controller and upload to AWS server.
3. No model coding for upload image to AWS.
Instead of write code in model as below
has_mongoid_attached_file :avatar, {
path: ':class/:id/:style/:basename.:extension',
storage: :s3,
bucket: bucket_name,
s3_credentials: {
access_key_id: 'access_key_id',
secret_access_key: 'secret_access_key'
},
styles: {
thumb: ['90x90^', :jpg],
feature: ['220x142^', :jpg],
show_page: ['720x420^', :jpg],
preview: ['145x90^', :jpg]
}
}
I want to upload image directly from controller.
and only save the URL of uploaded image in database instead of below.
"attachment_file_name": "imagename.png",
"attachment_content_type": "image/png",
"attachment_file_size": 1235,
"attachment_updated_at": TimeStamp,
i want to store only URL like this
avatar = https://s3.amazonaws.com/bucket_name/imagename.png
NOTE: My project in Rails 3.1.12 , Ruby 1.9.3p484 using mongoid
You need to pass url option in model , like this
has_mongoid_attached_file :avatar, {
:url => ':s3_alias_url',
}
Hi friend your store S3 credential model this is wrong thing, you need to store s3 credential in separate yml file.
In Your config/production.rb
# config/environments/production.rb
config.paperclip_defaults = {
:storage => :s3,
:s3_credentials => {
:bucket => ENV['S3_BUCKET_NAME'],
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
}
Writer your paperclip.rb
config/initializers/paperclip.rb
Paperclip::Attachment.default_options[:url] = ':s3_domain_url'
Paperclip::Attachment.default_options[:path]= '/:class/:attachment/:id_partition/:style/:filename'
In your model need to validate image type
has_attached_file :avatar, styles: {
thumb: '100x100>',
square: '200x200#',
medium: '300x300>'
}
# Validate the attached image is image/jpg, image/png, etc
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/

How to serve a static folder in sails.js?

I want to serve a folder app, which is at the same level with assets folder, under the url /app.
It's possible with AppController to serve file according the url, but I want to know whether it is possible to do this like the following with express?
app.use(express.static(__dirname + '/public'));
You can use custom middleware for express in sails by adding it to your config/http.js:
var express = require('express');
module.exports.express = {
customMiddleware: function (app) {
app.use(express.logger());
app.use(express.compress());
app.use('/app', express.static(process.cwd() + '/../client/www/'));
}
};
Off the top of my head, there's two choices:
Create a symlink assets/app pointing to your destination. The resources should be accessible via http://your.host.com/app/* since that's the way Sails serves assets.
There's still Express underneath Sails, you should be able to access it with sails.express.app and do your thing, let's say, from config/bootstrap.js:
var express = require('express');
…
sails.express.app.use(express.static(process.cwd() + '/app'));
I'm using Sails.js v0.12.4. The http.js uses module.exports.http and not module.exports.express I did the following to serve up another folder like the existing /assets folder. In my example to serve up the app folder, replace the 'node_modules/bootstrap/dist' path with /app
In the config/http.js file I added
var express = require('express');
Then in the middleware object I added the express static module. I'm wanting to serve up the bootstrap assets contained in my node_modules folder.
bootstrapAssets: express.static('node_modules/bootstrap/dist'),
Then in the order array, I added the 'bootstrapAssets' in the order I wanted this middleware to run. Here is the full code:
var express = require('express');
module.exports.http = {
middleware: {
passportInit : require('passport').initialize(),
passportSession : require('passport').session(),
bootstrapAssets : express.static('node_modules/bootstrap/dist'),
order: [
'startRequestTimer',
'cookieParser',
'session',
'bootstrapAssets',
'passportInit',
'passportSession',
'myRequestLogger',
'bodyParser',
'handleBodyParserError',
'compress',
'methodOverride',
'poweredBy',
'$custom',
'router',
'www',
'favicon',
'404',
'500'
],
Now in my HTML I can access the the bootstrap css using the following:
<link rel="stylesheet" href="/css/bootstrap.min.css">
In Sails 1.0 you can modify the file config/routes.js and add this:
var express = require('express')
var serveStatic = require('serve-static')
var os = require('os')
const dir = `${os.homedir()}/foo` // dir = /home/dimas/foo
module.exports.routes = {
'/public/*': serveStatic(dir, {skipAssets: true}), // <-- ADD THIS
'/': {
controller: 'FooController',
action: 'checkLogin'
},
};
Then you have to create the directory structure:
/home/dimas/foo/public
NOTE that the public entry (the route) is INCLUDED in the filesystem path, the files to be served must be placed there!
After that you can access any content by hitting the following URL:
http://localhost:1337/public/foratemer.txt
You can serve your files simple like this:
var express = require('../node_modules/sails/node_modules/express');
module.exports.express = {
middleware: {
custom: true
},
customMiddleware: function (app) {
app.use(express.logger());
app.use(express.compress());
app.use('/api/docs',express.static('assets/swagger-ui/dist/'));
}
};
This is my config/express.js file
You can use this for sails 0.12.3:
Install express to your sail: npm install express --save
After that, modify config/route.js
module.exports.routes = {
...
'/public/*': require('express').static('the-directory-that-contains-public-director')
...
}
This will works. However, it is a bit ugly that you have to create a directory as a parent for your public directory. It is because the static middleware create by express will count the '/public/' prefix in calculating to path to the target files.
Sails v1.0: Serve a file with a . dot folder in sails. Example: https://myWebSite.com/.well-known/test.txt
in the config/http.js file add express.static to serve and then add publicFolder in the order array.
module.exports.http = {
middleware: {
publicFolder: express.static('public/public'),
order: [
'cookieParser',
'session',
'publicFolder'
// 'favicon',
],
}}
Create a public folder and .well-known folder so public/.well-known/test.txt