server.psgi 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. =head2 $app
  42. Dispatches requests based on %routes built above.
  43. The dispatcher here does *not* do anything with the authn/authz data. It sets those in the 'user' and 'acls' parameters of the query object passed to routes.
  44. If a path passed is not a defined route (or regex route), but exists as a file under www/, it will be served up immediately.
  45. =cut
  46. my $app = sub {
  47. my $env = shift;
  48. my $last_fetch = 0;
  49. if ($env->{HTTP_IF_MODIFIED_SINCE}) {
  50. $last_fetch = DateTime::Format::HTTP->parse_datetime($env->{HTTP_IF_MODIFIED_SINCE})->epoch();
  51. }
  52. my $query = {};
  53. $query = URL::Encode::url_params_mixed($env->{QUERY_STRING}) if $env->{QUERY_STRING};
  54. my $path = $env->{PATH_INFO};
  55. # Let's open up our default route before we bother to see if users even exist
  56. return $routes{default}{callback}->($query,$env->{'psgi.input'}, \&_render) unless -f "$ENV{HOME}/.tcms/setup";
  57. my $cookies = {};
  58. if ($env->{HTTP_COOKIE}) {
  59. $cookies = CGI::Cookie->parse($env->{HTTP_COOKIE});
  60. }
  61. my ($active_user,$user_id) = ('','');
  62. if (exists $cookies->{tcmslogin}) {
  63. ($active_user,$user_id) = Trog::Auth::session2user($cookies->{tcmslogin}->value);
  64. }
  65. $query->{acls} = Trog::Auth::acls4user($user_id) // [] if $user_id;
  66. $query->{user} = $active_user;
  67. $query->{domain} = $env->{HTTP_HOST};
  68. $query->{route} = $path;
  69. #Disallow any paths that are naughty ( starman auto-removes .. up-traversal)
  70. if (index($path,'/templates') == 0 || $path =~ m/.*\.psgi$/i ) {
  71. return Trog::Routes::HTML::forbidden($query,$env->{'psgi.input'}, \&_render);
  72. }
  73. # If it's just a file, serve it up
  74. return _serve("www/$path", $last_fetch) if -f "www/$path";
  75. #Handle regex/capture routes
  76. if (!exists $routes{$path}) {
  77. my @captures;
  78. foreach my $pattern (keys(%routes)) {
  79. @captures = $path =~ m/^$pattern$/;
  80. if (@captures) {
  81. $path = $pattern;
  82. foreach my $field (@{$routes{$path}{captures}}) {
  83. $routes{$path}{data} //= {};
  84. $routes{$path}{data}{$field} = shift @captures;
  85. }
  86. last;
  87. }
  88. }
  89. }
  90. #TODO reject inappropriate content-lengths
  91. return Trog::Routes::HTML::notfound($query,$env->{'psgi.input'}, \&_render) unless exists $routes{$path};
  92. return Trog::Routes::HTML::badrequest($query,$env->{'psgi.input'}, \&_render) unless $routes{$path}{method} eq $env->{REQUEST_METHOD};
  93. @{$query}{keys(%{$routes{$path}{'data'}})} = values(%{$routes{$path}{'data'}}) if ref $routes{$path}{'data'} eq 'HASH' && %{$routes{$path}{'data'}};
  94. my $output = $routes{$path}{callback}->($query,$env->{'psgi.input'}, \&_render);
  95. return $output;
  96. };
  97. sub _serve ($path, $last_fetch=0) {
  98. my $mf = Mojo::File->new($path);
  99. my $ext = '.'.$mf->extname();
  100. my $ft;
  101. $ft = Plack::MIME->mime_type($ext) if $ext;
  102. $ft = "$ct:$ft;" if $ft;
  103. $ft ||= $content_types{plain};
  104. my @headers = ($ft);
  105. #TODO figure out content-disposition
  106. #TODO use static Cache-Control for everything but JS/CSS?
  107. push(@headers,$cache_control{revalidate});
  108. #TODO Return 304 unchanged for files that haven't changed since the requestor reports they last fetched
  109. my $mt = (stat($path))[9];
  110. my @gm = gmtime($mt);
  111. my $now_string = strftime( "%a, %d %b %Y %H:%M:%S GMT", @gm );
  112. my $code = $mt > $last_fetch ? 200 : 304;
  113. push(@headers, "Last-Modified: $now_string\n");
  114. my $h = join("\n",@headers);
  115. if (open(my $fh, '<', $path)) {
  116. return [ $code, [$h], $fh];
  117. }
  118. return [ 403, [$content_types{plain}], ["STAY OUT YOU RED MENACE"]];
  119. }
  120. sub _render ($template, $vars, @headers) {
  121. my $processor = Text::Xslate->new(
  122. path => 'www/templates',
  123. header => ['header.tx'],
  124. footer => ['footer.tx'],
  125. );
  126. #XXX default vars that need to be pulled from config
  127. $vars->{dir} //= 'ltr';
  128. $vars->{lang} //= 'en-US';
  129. $vars->{title} //= 'tCMS';
  130. #XXX Need to have minification detection and so forth, use LESS
  131. $vars->{stylesheets} //= [];
  132. #XXX Need to have minification detection, use Typescript
  133. $vars->{scripts} //= [];
  134. # Absolute-ize the paths for scripts & stylesheets
  135. @{$vars->{stylesheets}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{stylesheets}};
  136. @{$vars->{scripts}} = map { index($_, '/') == 0 ? $_ : "/$_" } @{$vars->{scripts}};
  137. $vars->{contenttype} //= $content_types{html};
  138. $vars->{cachecontrol} //= $cache_control{revalidate};
  139. $vars->{code} ||= 200;
  140. push(@headers, $vars->{contenttype});
  141. push(@headers,$vars->{contentdisposition}) if $vars->{contentdisposition};
  142. push(@headers, $vars->{cachecontrol}) if $vars->{cachecontrol};
  143. my $h = join("\n",@headers);
  144. my $body = $processor->render($template,$vars);
  145. return [$vars->{code}, [$h], [encode_utf8($body)]];
  146. }