TCMS.pm 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package TCMS;
  2. use strict;
  3. use warnings;
  4. no warnings 'experimental';
  5. use feature qw{signatures state};
  6. use Carp qw{confess};
  7. use Clone qw{clone};
  8. use Date::Format qw{strftime};
  9. use Sys::Hostname();
  10. use HTTP::Body ();
  11. use URL::Encode ();
  12. use Text::Xslate ();
  13. use DateTime::Format::HTTP();
  14. use CGI::Cookie ();
  15. use File::Basename();
  16. use Time::HiRes qw{gettimeofday tv_interval};
  17. use List::Util;
  18. use URI();
  19. use Ref::Util qw{is_coderef is_hashref is_arrayref};
  20. #Grab our custom routes
  21. use FindBin;
  22. use lib "$FindBin::Bin/../lib";
  23. use FindBin::libs;
  24. use Trog::Routes::HTML;
  25. use Trog::Routes::JSON;
  26. use Trog::Log qw{:all};
  27. use Trog::Log::DBI;
  28. use Trog::Auth;
  29. use Trog::Config;
  30. use Trog::Data;
  31. use Trog::Themes;
  32. # Troglodyne philosophy - simple as possible
  33. my $cur_query = {};
  34. # Build routes
  35. sub build_routes {
  36. my $conf = Trog::Config::get();
  37. my $data = Trog::Data->new($conf);
  38. my %routes = %{ _routes($data) };
  39. my $default_route = $routes{default}{callback};
  40. # Transform 'method' / 'callback' to new scheme
  41. my %routes_adj;
  42. foreach my $k (keys(%routes)) {
  43. my $v = $routes{$k};
  44. # Some routes are just pointers to other routes.
  45. # In this case they might have already been transformed and need to be skipped.
  46. if (exists $v->{callbacks}) {
  47. $routes_adj{$k} = $v;
  48. next;
  49. }
  50. my %cb;
  51. my $method = $v->{method};
  52. my $callback = delete $v->{callback};
  53. #XXX For now we will discard the tPSGI object. We might want it later.
  54. my $cb_wrap = sub {
  55. my ( $tpsgi, $query ) = @_;
  56. confess "Cannot determine directory for logs!" unless $tpsgi->{log_dir};
  57. # Make sure the tCMS logs live in the same dir as the tpsgi logs.
  58. log_init("$tpsgi->{log_dir}/tpsgi.log", $tpsgi->{verbose} ? 'debug' : 'info');
  59. # Let's open up our default route if needed before we bother thinking any harder
  60. return $default_route->($query) unless -f "config/setup";
  61. # Set the urchin parameters if necessary.
  62. %$Trog::Log::DBI::urchin = map { $_ => delete $query->{$_} } qw{utm_source utm_medium utm_campaign utm_term utm_content};
  63. # Set the IP of the request so we can fail2ban
  64. $Trog::Log::ip = $query->{ip};
  65. # Set the referer & ua to go into DB logs, but not logs in general.
  66. # The referer/ua largely has no importance beyond being a proto bug report for log messages.
  67. $Trog::Log::DBI::referer = $query->{referer};
  68. $Trog::Log::DBI::ua = $query->{ua};
  69. # Figure out if we have a logged in user, so we can serve them user-specific files
  70. my $cookies = {};
  71. $cookies = CGI::Cookie->parse( $query->{cookies} ) if $query->{cookies};
  72. my $active_user = '';
  73. $Trog::Log::user = 'nobody';
  74. if ( exists $cookies->{tcmslogin} ) {
  75. $active_user = Trog::Auth::session2user( $cookies->{tcmslogin}->value );
  76. $Trog::Log::user = $active_user if $active_user;
  77. }
  78. # Make sure TPSGI can log the user
  79. $tpsgi->{user} = $active_user;
  80. # Enrich the query with tcms specific foo
  81. $query->{user_acls} = [];
  82. $query->{user_acls} = Trog::Auth::acls4user($active_user) // [] if $active_user;
  83. # Grab the list of ACLs we want to add to a post, if any.
  84. $query->{acls} = [ $query->{acls} ] if ( $query->{acls} && ref $query->{acls} ne 'ARRAY' );
  85. # Filter out passed ACLs which are naughty
  86. my $is_admin = grep { $_ eq 'admin' } @{ $query->{user_acls} };
  87. @{ $query->{acls} } = grep { $_ ne 'admin' } @{ $query->{acls} } unless $is_admin;
  88. $query->{user} = $active_user;
  89. $query->{body} = '';
  90. $query->{social_meta} = 1;
  91. $query->{primary_post} = {};
  92. $query->{nocache} = $v->{nocache};
  93. # Some routes may just need to do serve()
  94. $query->{tpsgi} = $tpsgi;
  95. # Redirecting somewhere naughty not allow
  96. $query->{to} = URI->new( $query->{to} // '' )->path() || $query->{to} if $query->{to};
  97. # Now that we have firmed up the actual routing, let's validate.
  98. return $tpsgi->forbidden($query) if exists $query->{dispatcher}{auth} && !$active_user;
  99. no strict 'refs';
  100. $callback->($query);
  101. use strict;
  102. };
  103. #XXX todo support different callbacks per requested content-type
  104. $cb{'*'} = $cb_wrap if $callback;
  105. $v->{callbacks} = \%cb;
  106. $routes_adj{$k} = $v;
  107. }
  108. return [%routes_adj];
  109. }
  110. # Override the generic error handler to look spiffy
  111. sub generic_route ( $rname, $code, $title, $query ) {
  112. $query->{code} = $code;
  113. $query->{route} //= $rname;
  114. $query->{title} = $title;
  115. $query->{template} = "$rname.tx";
  116. return Trog::Routes::HTML::index($query);
  117. }
  118. our @routes = @{ build_routes() };
  119. our %aliases = aliases();
  120. #XXX Return a clone of the routing table ref, because code modifies it later
  121. sub _routes ( $data = {} ) {
  122. state %routes;
  123. return clone( \%routes ) if %routes;
  124. my $conf = Trog::Config::get();
  125. $data = Trog::Data->new($conf) unless $data;
  126. # Routes in general are going to override earlier, more default ones.
  127. # XXX this is probably bad in the case of the specific content-typed routes, they should be mutex
  128. my %roots = $data->routes();
  129. # Setup the /secure/... versions for logged in users, except for already secured routes.
  130. foreach my $route (keys(%roots)) {
  131. next if index($route, '/secure/') == 0;
  132. $roots{"/secure$route"} = $roots{$route};
  133. }
  134. # It is the responsibility of theme authors to setup /secure routes (other than index)
  135. my %themed = Trog::Themes::routes();
  136. %routes = %Trog::Routes::HTML::routes;
  137. @routes{ keys(%Trog::Routes::JSON::routes) } = values(%Trog::Routes::JSON::routes);
  138. @routes{ keys(%roots) } = values(%roots);
  139. @routes{ keys(%themed) } = values(%themed) if %themed;
  140. # Add in global routes, here because they *must* know about all other routes
  141. # Also, nobody should ever override these.
  142. $routes{'/robots.txt'} = {
  143. method => 'GET',
  144. callback => \&robots,
  145. };
  146. # Special 'am I authenticated' route for nginx
  147. $routes{'/authenticated'} = {
  148. method => 'GET',
  149. nocache => 1,
  150. noindex => 1,
  151. callback => sub {
  152. my ($query) = @_;
  153. return $query->{tpsgi}->ok($query) if $query->{user};
  154. return $query->{tpsgi}->forbidden($query);
  155. },
  156. };
  157. # Heartbeat route
  158. $routes{'/status'} = {
  159. method => 'GET',
  160. nocache => 1,
  161. noindex => 1,
  162. callback => sub {
  163. my ($query) = @_;
  164. return $query->{tpsgi}->ok($query);
  165. },
  166. };
  167. # The Various aliases for directory indices
  168. foreach my $index (qw{ / /index.html /index.htm}) {
  169. $routes{$index} = $routes{'/index'} unless exists $routes{$index};
  170. $routes{"/secure$index"} = $routes{'/index'} unless exists $routes{"/secure$index"};
  171. }
  172. return clone( \%routes );
  173. }
  174. sub aliases {
  175. my $conf = Trog::Config::get();
  176. my $data = Trog::Data->new($conf);
  177. return $data->aliases();
  178. }
  179. =head2 robots
  180. Return an appropriate robots.txt
  181. This is a "special" route as it needs to know about all the routes in order to disallow noindex=1 routes.
  182. =cut
  183. # TODO anytime that the routing table changes, we need to invalidate the cache.
  184. sub robots ($query) {
  185. state $etag = "robots-" . time();
  186. my $routes = _routes();
  187. # If there's a 'capture' route, we need to format it correctly.
  188. state @banned = map { exists $routes->{$_}{robot_name} ? $routes->{$_}{robot_name} : $_ } grep { $routes->{$_}{noindex} } sort keys(%$routes);
  189. return Trog::Renderer->render(
  190. contenttype => 'text/plain',
  191. template => 'robots.tx',
  192. data => {
  193. etag => $etag,
  194. banned => \@banned,
  195. %$query,
  196. },
  197. code => 200,
  198. );
  199. }
  200. 1;