#!/usr/bin/env perl
use Mojolicious::Lite;

# conditions
my $conditions = {
    authenticated => sub {
        my $self = shift;
        unless ($self->session('authenticated')) {
            $self->flash(
                class   => 'alert alert-info',
                message => 'Please log in first!'
            );
            $self->redirect_to('/login');
            return;
        }
        return 1;
    },
};

plugin 'Blog' => {
    authCondition => $conditions,
    dsn           => "dbi:SQLite:dbname=db/myblog.db",
};

# Documentation browser under "/perldoc"
plugin 'PODRenderer';

get '/' => sub {
    my $self = shift;
    $self->render('index');
};

get '/login' => sub {
    my $self = shift;
    $self->render('login');
};

get '/logout' => sub {
  my $self = shift;
  $self->session->{authenticated} = undef;
  $self->redirect_to('/login');
};

post '/login' => sub {
  my $self= shift;
  $self->session->{authenticated} = 1;
  $self->redirect_to('/admin/blog/');
};

app->start;
__DATA__

@@ index.html.ep
% layout 'default';
% title 'Welcome';
neat0 blog.

@@ login.html.ep
% layout 'default';
% title 'Login';

<h2>Auth</h2>

%= form_for '/login' => ( method => 'POST' ) => begin
    <label>Login</label>
    %= text_field 'login', class => 'span3', type => 'text'
    <br />
    <label>Password</label>
    %= password_field 'password', class => 'span3'
    <br />
    %= submit_button 'Login'
% end

@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
  <head><title><%= title %></title></head>
  <body><%= content %></body>
</html>
