server.psgi 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. use strict;
  2. use warnings;
  3. no warnings 'experimental';
  4. use feature qw{signatures};
  5. use Date::Format qw{strftime};
  6. use URL::Encode ();
  7. use Text::Xslate ();
  8. use Plack::MIME ();
  9. use Mojo::File ();
  10. use DateTime::Format::HTTP();
  11. use Encode qw{encode_utf8};
  12. use CGI::Cookie ();
  13. #Grab our custom routes
  14. use lib 'lib';
  15. use Trog::Routes::HTML;
  16. use Trog::Routes::JSON;
  17. use Trog::Auth;
  18. # Troglodyne philosophy - simple as possible
  19. # Import the routes
  20. my %routes = %Trog::Routes::HTML::routes;
  21. @routes{keys(%Trog::Routes::JSON::routes)} = values(%Trog::Routes::JSON::routes);
  22. # Things we will actually produce from routes rather than just serving up files
  23. my $ct = 'Content-type';
  24. my %content_types = (
  25. plain => "$ct:text/plain;",
  26. html => "$ct:text/html; charset=UTF-8",
  27. json => "$ct:application/json;",
  28. blob => "$ct:application/octet-stream;",
  29. );
  30. my $cd = 'Content-disposition';
  31. my %content_dispositions = (
  32. attachment => 'attachment; filename=',
  33. inline => 'inline; filename=',
  34. );
  35. my $cc = 'Cache-control';
  36. my %cache_control = (
  37. revalidate => "$cc: no-cache, max-age=0;",
  38. nocache => "$cc: no-store;",
  39. static => "$cc: public, max-age=604800, immutable",
  40. );
  41. my $app = sub {
  42. my $env = shift;
  43. my $last_fetch = 0;
  44. if ($env->{HTTP_IF_MODIFIED_SINCE}) {
  45. $last_fetch = DateTime::Format::HTTP->parse_datetime($env->{HTTP_IF_MODIFIED_SINCE})->epoch();
  46. }
  47. my $query = {};
  48. $query = URL::Encode::url_params_mixed($env->{QUERY_STRING}) if $env->{QUERY_STRING};
  49. my $path = $env->{PATH_INFO};
  50. # Let's open up our default route before we bother to see if users even exist
  51. return $routes{default}{callback}->($query,$env->{'psgi.input'}, \&_render) unless -f "$ENV{HOME}/.tcms/setup";
  52. my $cookies = {};
  53. if ($env->{HTTP_COOKIE}) {
  54. $cookies = CGI::Cookie->parse($env->{HTTP_COOKIE});
  55. }
  56. my $active_user = '';
  57. if (exists $cookies->{tcmslogin}) {
  58. $active_user = Trog::Auth::session2user($cookies->{tcmslogin}->value);
  59. }
  60. $query->{user} = $active_user;
  61. $query->{domain} = $env->{HTTP_HOST};
  62. $query->{route} = $path;
  63. #Disallow any paths that are naughty ( starman auto-removes .. up-traversal)
  64. if (index($path,'/templates') == 0 || $path =~ m/.*\.psgi$/i ) {
  65. return [ 403, [$content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  66. }
  67. # If it's just a file, serve it up
  68. return _serve("www/$path", $last_fetch) if -f "www/$path";
  69. #TODO reject inappropriate content-lengths
  70. return [ 404, [$content_types{plain}], ["RETURN TO SENDER"]] unless exists $routes{$path};
  71. return [ 400, [$content_types{plain}], ["BAD REQUEST"]] unless $routes{$path}{method} eq $env->{REQUEST_METHOD};
  72. @{$query}{keys(%{$routes{$path}{'data'}})} = values(%{$routes{$path}{'data'}}) if ref $routes{$path}{'data'} eq 'HASH' && %{$routes{$path}{'data'}};
  73. my $output = $routes{$path}{callback}->($query,$env->{'psgi.input'}, \&_render);
  74. return $output;
  75. };
  76. sub _serve ($path, $last_fetch=0) {
  77. my $mf = Mojo::File->new($path);
  78. my $ext = '.'.$mf->extname();
  79. my $ft;
  80. $ft = Plack::MIME->mime_type($ext) if $ext;
  81. $ft = "$ct:$ft;" if $ft;
  82. $ft ||= $content_types{plain};
  83. my @headers = ($ft);
  84. #TODO figure out content-disposition
  85. #TODO use static Cache-Control for everything but JS/CSS?
  86. push(@headers,$cache_control{revalidate});
  87. #TODO Return 304 unchanged for files that haven't changed since the requestor reports they last fetched
  88. my $mt = (stat($path))[9];
  89. my @gm = gmtime($mt);
  90. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  91. my $code = $mt > $last_fetch ? 200 : 304;
  92. push(@headers, "Last-Modified: $now_string\n");
  93. my $h = join("\n",@headers);
  94. if (open(my $fh, '<', $path)) {
  95. return [ $code, [$h], $fh];
  96. }
  97. return [ 403, [$content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  98. }
  99. sub _render ($template, $vars, @headers) {
  100. my $processor = Text::Xslate->new(
  101. path => 'www/templates',
  102. header => ['header.tx'],
  103. footer => ['footer.tx'],
  104. );
  105. #XXX default vars that need to be pulled from config
  106. $vars->{dir} //= 'ltr';
  107. $vars->{lang} //= 'en-US';
  108. $vars->{title} //= 'tCMS';
  109. #XXX Need to have minification detection and so forth, use LESS
  110. $vars->{stylesheets} //= [];
  111. #XXX Need to have minification detection, use Typescript
  112. $vars->{scripts} //= [];
  113. # Absolute-ize the paths for scripts & stylesheets
  114. @{$vars->{stylesheets}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{stylesheets}};
  115. @{$vars->{scripts}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{scripts}};
  116. $vars->{contenttype} //= $content_types{html};
  117. $vars->{cachecontrol} //= $cache_control{revalidate};
  118. push(@headers, $vars->{contenttype});
  119. push(@headers,$vars->{contentdisposition}) if $vars->{contentdisposition};
  120. push(@headers, $vars->{cachecontrol}) if $vars->{cachecontrol};
  121. my $h = join("\n",@headers);
  122. my $body = $processor->render($template,$vars);
  123. return [200, [$h], [encode_utf8($body)]];
  124. }