I want to protect all forms from CSRF with Dancer.
I tried using Plack::Middleware::CSRFBlock, but the error said "CSRFBlock needs Session.". Even if I use Plack::Session, forms didn't have a hidden input field that contains one time token.
Are there any good practice to do this? Any advice much appreciated.
my environment/development.yml is:
# configuration file for development environment
# the logger engine to use
# console: log messages to STDOUT (your console where you started the
# application server)
# file: log message to a file in log/
logger: "console"
# the log level for this environment
# core is the lowest, it shows Dancer's core log messages as well as yours
# (debug, info, warning and error)
log: "core"
# should Dancer consider warnings as critical errors?
warnings: 1
# should Dancer show a stacktrace when an error is caught?
show_errors: 1
# auto_reload is a development and experimental feature
# you should enable it by yourself if you want it
# Module::Refresh is needed
#
# Be aware it's unstable and may cause a memory leak.
# DO NOT EVER USE THIS FEATURE IN PRODUCTION
# OR TINY KITTENS SHALL DIE WITH LOTS OF SUFFERING
auto_reload: 0
session: Simple
#session: YAML
plack_middlewares:
-
#- Session
- CSRFBlock
- Debug
- panels
-
- Parameters
- Dancer::Version
- Dancer::Settings
- Memory
and the route is:
get '/test' => sub {
return <<EOM
<!DOCTYPE html>
<html>
<head><title>test route</title></head>
<body>
<form action="./foobar" method="post">
<input type="text"/>
<input type="submit"/>
</form>
</body>
</html>
EOM
};
Well, I noticed the Debug panel isn't shown, meaning Plack::Middlewares::Debug isn't loaded.
With help from How to use Dancer with Plack middlewares | PerlDancer Advent Calendar and Plack::Middleware::Debug::Dancer::Version I managed to turn it on
session: PSGI
## Dancer::Session::PSGI
plack_middlewares:
-
- Session
-
- CSRFBlock
-
- Debug
## panels is an argument for Debug, as in
## enable 'Debug', panels => [ qw( Parameters Response Environment Session Timer Dancer::Logger Dancer::Settings Dancer::Version ) ];
- panels
-
- Parameters
- Response
- Environment
- Session
- Timer
- Dancer::Logger
- Dancer::Settings
- Dancer::Version
#Plack::Middleware::Debug::Dancer::Version
Related
When I run tests which fail I get a huge output with a lot of markup hiding the error.
Example:
$ perl script/my_prove.pl t/2410-topinfo.t
t/2410-topinfo.t .. 1/?
# Failed test '200 OK'
# at t/2410-topinfo.t line 12.
# got: '500'
# expected: '200'
# Failed test 'similar match for selector "h1"'
# at t/2410-topinfo.t line 12.
# ''
# doesn't match '(?^:Flatinfo\ Business\-Apartment\ Hietzing)'
# Failed test 'content is similar'
# at t/2410-topinfo.t line 12.
# '<!DOCTYPE html>
# <html>
# <head>
# <title>Server error (development mode)</title>
# <meta http-equiv="Pragma" content="no-cache">
# <meta http-equiv="Expires" content="-1">
# <script src="/mojo/jquery/jquery.js"></script>
# <script src="/mojo/prettify/run_prettify.js"></script>
# <link href="/mojo/prettify/prettify-mojo-dark.css" rel="stylesheet">
# <style>
# a img { border: 0 }
# body {
#
# ........... lots of lines removed here ...........
#
# <div id="wrapperlicious">
# <div id="nothing" class="box spaced"></div>
# <div id="showcase" class="box code spaced">
# <pre id="error">Can't call method "name" on an undefined value at template extern/topinfo/show.html.ep line 2.
# </pre>
#
# .... lots of lines follow here ............
The error seems to be a single line:
Can't call method "name" on an undefined value at template extern/topinfo/show.html.ep line 2
The test-script producing this output is:
use Mojo::Base -strict;
use Test::More;
use Test::Mojo;
use FindBin;
require "$FindBin::Bin/../script/ba_db";
my $t = Test::Mojo->new( 'BaDb' );
$t->ua->max_redirects(1);
$t->get_ok('/info/penx2')
->status_is(200)
->text_like('h1' => qr/\QFlatinfo Business-Apartment Hietzing\E/)
->content_like( qr/\QSelected language: German\E/ )
# ...
;
done_testing();
Is there a way to tell Mojolicious to respond without all this HTML-Markup so that I can see the error-mesage immediately?
There are two things at play here.
The large debug output with the full page source is because the content_like method from Test::Mojo didn't find a match, and it's telling you in which string it was looking. That's a convenience method, but if the page is large, it's a lot of text. This might tell you that the test failed because the content was wrong. But in this specific case it didn't.
The real problem is that the test failed because you had a syntax error. You can already see that from the very first test.
$t->get_ok('/info/penx2')
->status_is(200)
This test also failed. (It's a bit confusing for people who are used to Test::WWW::Mechanize because there get_ok will also check if the response was 200 OK).
# Failed test '200 OK'
# at t/2410-topinfo.t line 12.
# got: '500'
# expected: '200'
The actual error message should be there without all that HTML markup somewhere else, because while it was doing the get_ok it would have encountered the error, which should have gone to the application log. In a unit-test, that probably is STDERR.
I don't know if you've not included it, or if it's omitted. The log should be there too I believe.
Getting back to the HTML and the actual question, the reason it's output is because Test::Mojo's content_like (and most other of its methods) uses Test::More under hood. It just dispatches to like from Test::More and passes along the page content. This in turn will always display the full string it was matching against.
In recent Test::More versions, it already uses Test2 under the hood. The relevant part that outputs the full string is here.
Unfortunately there is not much you can do about it. I'd focus on finding out why it doesn't show a proper log during the unit tests (possibly because you didn't run prove with -v), and maybe find a way to make errors come out in color, which would make it easier to read. There is a color logger for the Dancer2 framework (which I maintain), but I can't find one for Mojo there wasn't one for Mojo.
Now there is Mojo::Log::Colored, which can color individual log lines based on their log level.
use Mojo::Log::Colored;
# Log to STDERR
$app->log(
Mojo::Log::Colored->new(
# optionally set the colors
colors => {
debug => "bold bright_white",
info => "bold bright_blue",
warn => "bold green",
error => "bold yellow",
fatal => "bold yellow on_red",
}
)
);
This will give you nice colorful output to the console. Here's an example script.
$ MOJO_LOG_LEVEL=debug perl -Mojo -MMojo::Log::Colored \
-e 'a(
"/" => sub {
app->log->$_("hello world") for qw/debug info warn error fatal/;
shift->render(text=>"ok");
})->log( Mojo::Log::Colored->new )->start' \
daemon
And the output if called with $ curl localhost:3000.
I am trying to fetch unread emails from server and mark them as seen (read) after fetching. I'm using perl script and the package Net::IMAP::Simple. I'm writing this script for the office work.
Below is some code :
use strict;
use warnings;
use Net::IMAP::Simple;
use Email::Simple;
use HTTP::Date;
#some code....
# Create the object
my $server = Net::IMAP::Simple->new($imap_server) or die "Can't connect to server: $imap_server ";
# Log on
my $login = $server->login($imap_user,$imap_passwd) or die "Login failed (bad username or password)";
#some code.....
# set the message as seen
$server->see($i);
# i also used $server->add_flags($i,'\Seen'); but it throws same error.
The Irony is, this code works fine on my Gmail account , which i use for testing. but when i test it in office it throws error ;
can't locate object method "see" via package "Net::IMAP::Simple"
I don't know what's the issue here.
The methods see and unsee were added in Net::IMAP::Simple version 1.1899_05.
> 1.1899_05: Tue Jun 16 06:42:16 EDT 2009
> - I started working on ticket 45953,
> - created sub_flags() and add_flags()
> - taught delete() to use add_flags() -- adds \Deleted
> - providing see() and unsee() for ticket 45953
> - I started building tests for the flag manipulation stuff and
> put reselect stuff ... noticed a possible bug in
> Net::IMAP::Server
You likely have an older version on your production system. Update it, and include a minimum version in your Makefile.PL or cpanfile or whatever you use to track dependencies.
I am using basic features with MinkZombieDriver. my
node -v 5.2.0, npm -v 3.10.5, mink-zombie-driver v1.4.0 ..
behat.yml
default:
extensions:
Behat\MinkExtension:
base_url: 'https://example.com'
javascript_session: zombie
zombie:
node_modules_path: '/home/ubuntu/node_modules'
goutte: ~
paths:
features: features
bootstrap: %behat.paths.features%/bootstrap
I wrote simple feature and it is giving Behat\Mink\Exception\DriverException
#javascript
Scenario: View Products to assign store
Given I am on "/index.php" # FeatureContext::visit()
When I fill in "Username" with "hello" # FeatureContext::fillField()
When I fill in "Password" with "123" # FeatureContext::fillField()
And I should see "Manage Your Accounts" # FeatureContext::assertPageContainsText()
When I press "login_button" # FeatureContext::pressButton()
Error while processing event 'click': "SyntaxError: Unexpected token u\n at Object.parse (native)\n
I searched in the web but not sure how to solve. I am still using the basic default features. I know the problem is with JSON parsing .. I am not sure what I am doing wrong? I am looking forward for any suggestions.. Thanks ..
As is seems from my comment link you need to update zombie version to at least version 2.
Please note that you might have some compatibility issues that you will need to solve.
Check this answer also nodejs cannot find module 'zombie' with PHP mink
I'm working with PigLatin, using grunt, and every time I 'dump' stuffs, my console gets clobbered with blah blah, blah non-info, is there a way to surpress all that?
grunt> A = LOAD 'testingData' USING PigStorage(':'); dump A;
2013-05-06 19:42:04,146 [main] INFO org.apache.pig.tools.pigstats.ScriptState - Pig features used in the script: UNKNOWN
2013-05-06 19:42:04,147 [main] INFO org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRCompiler - File concatenation threshold: 100 optimistic? false
...
...
--- another like 50 lines of useless context clobbering junk here... till ---
...
...
org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - Success!
now my like 4 lines of info looking for:
(daemon,*,1,1,System Services,/var/root,/usr/bin/false)
(uucp,*,,,/var/spool/uucp,/usr/sbin/uucico)
(taskgated,*,13,13,Task Gate Daemon,/var/empty,/usr/bin/false)
(networkd,*,24,24,Network Services,/var/empty,/usr/bin/false)
(installassistant,*,25,25,/usr/bin/false)
grunt>
---> obviously if it errors, fine lotsa info helpful, but not when it basically works great.
You need to set the log4j properties.
For example:
$PIG_HOME/conf/pig.properties :
enable:
# log4jconf=./conf/log4j.properties
rename: log4j.properties.template -> log4j.properties
log4j.properties :
set info to error:
log4j.logger.org.apache.pig=info, A
You may also set the Hadoop related logging level as well:
log4j.logger.org.apache.hadoop = error, A
An easy way to do this seems to be to redirect standard error as below.
But it will suppress all errors.
pig -x local 2> /dev/null
Also found that if you remove or rename your hadoop install directory to basically make it inaccessible to pig then all those INFO messages go away. Changing logging levels in hadoop didn't help, just so that you know.
When you start pig, pass it a log4j.properties file with pig -4 <filename>.
In my case there was a log4j.properties in the conf directory and setting the level of the logger named org.apache.pig to ERROR is sufficient to make the logger less verbose.
log4j.logger.org.apache.pig=ERROR, A
pig has debug log level one need to set that in pig.properties file,
# Logging level. debug=OFF|ERROR|WARN|INFO|DEBUG (default: INFO)
#
# debug=INFO
The reason one get large logs on console, e.g. change it to ERROR
I have a HTTP Request Handler for mod_perl which needs to read an environment variable, from %ENV, at module load time. The environment variable is passed from the Apache config into mod_perl using the PerlSetEnv directive.
This worked fine, until we changed the Apache configuration to AutoLoad the handler at startup time, for performance reasons. When the module is AutoLoaded like this, thePerlSetEnv does not take effect at module load time, and the variable we need is only available from %ENV at request time inside the handler method.
Is there a way to continue using AutoLoad, but still set an environment variable in the Apache config which is available in Perl's %ENV at module load time?
Minimal example:
Here's a stripped down test-case to illustrate the problem.
The Apache config without autoload enabled:
PerlSwitches -I/home/day/modperl
<Location /perl>
SetHandler modperl
PerlSetEnv TEST_PERLSETENV 'Does it work?'
PerlResponseHandler ModPerl::Test
Allow from all
</Location>
Contents of /home/day/modperl/ModPerl/Test.pm:
package ModPerl::Test;
use strict;
use warnings;
use Apache2::RequestRec ();
use Apache2::RequestIO ();
use Apache2::Const qw(OK);
my %ENV_AT_MODULE_LOAD = %ENV; # Take a copy
sub handler {
my $r = shift;
$r->content_type('text/plain');
$r->print("ENV:\n");
foreach my $key (sort keys %ENV) {
$r->print(" $key: $ENV{$key}\n");
}
$r->print("ENV_AT_MODULE_LOAD:\n");
foreach my $key (sort keys %ENV_AT_MODULE_LOAD) {
$r->print(" $key: $ENV_AT_MODULE_LOAD{$key}\n");
}
return OK;
}
1;
When localhost/perl is viewed in the browser, I see this:
ENV:
MOD_PERL: mod_perl/2.0.5
MOD_PERL_API_VERSION: 2
PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
TEST_PERLSETENV: Does it work?
ENV_AT_MODULE_LOAD:
MOD_PERL: mod_perl/2.0.5
MOD_PERL_API_VERSION: 2
PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
TEST_PERLSETENV: Does it work?
Hooray! TEST_PERLSETENV is available at module load time, as we want.
But when we change the Apache config to enable Autoload (by using + in the PerlResponseHandler like so):
PerlResponseHandler +ModPerl::Test
I get the following output instead:
ENV:
MOD_PERL: mod_perl/2.0.5
MOD_PERL_API_VERSION: 2
PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
TEST_PERLSETENV: Does it work?
ENV_AT_MODULE_LOAD:
MOD_PERL: mod_perl/2.0.5
MOD_PERL_API_VERSION: 2
PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Boo! TEST_PERLSETENV is no longer available at module load time :( How can I get it back while keeping the AutoLoad behaviour?
Argh, 30 seconds after posting this question, I found the answer. Thank you rubber duck.
Move the PerlSetEnv to before the <Location> block which contains the PerlResponseHandler directive, and it works again!
i.e. like this:
PerlSwitches -I/home/dbarr/modperl
PerlSetEnv TEST_PERLSETENV 'Does it work?'
<Location /perl>
SetHandler modperl
PerlResponseHandler +ModPerl::Test
Allow from all
</Location>