3 namespace BookStack\Http\Controllers;
6 use HttpRequestException;
7 use Illuminate\Foundation\Bus\DispatchesJobs;
8 use Illuminate\Http\Exception\HttpResponseException;
9 use Illuminate\Routing\Controller as BaseController;
10 use Illuminate\Foundation\Validation\ValidatesRequests;
11 use Illuminate\Support\Facades\Auth;
12 use Illuminate\Support\Facades\Session;
15 abstract class Controller extends BaseController
17 use DispatchesJobs, ValidatesRequests;
22 protected $currentUser;
29 * Controller constructor.
31 public function __construct()
33 $this->middleware(function ($request, $next) {
35 // Get a user instance for the current user
38 // Share variables with controllers
39 $this->currentUser = $user;
40 $this->signedIn = auth()->check();
42 // Share variables with views
43 view()->share('signedIn', $this->signedIn);
44 view()->share('currentUser', $user);
46 return $next($request);
51 * Stops the application and shows a permission error if
52 * the application is in demo mode.
54 protected function preventAccessForDemoUsers()
56 if (config('app.env') === 'demo') $this->showPermissionError();
60 * Adds the page title into the view.
63 public function setPageTitle($title)
65 view()->share('pageTitle', $title);
69 * On a permission error redirect to home and display.
70 * the error as a notification.
72 protected function showPermissionError()
74 if (request()->wantsJson()) {
75 $response = response()->json(['error' => trans('errors.permissionJson')], 403);
77 $response = redirect('/');
78 session()->flash('error', trans('errors.permission'));
81 throw new HttpResponseException($response);
85 * Checks for a permission.
86 * @param string $permissionName
87 * @return bool|\Illuminate\Http\RedirectResponse
89 protected function checkPermission($permissionName)
91 if (!user() || !user()->can($permissionName)) {
92 $this->showPermissionError();
98 * Check the current user's permissions against an ownable item.
100 * @param Ownable $ownable
103 protected function checkOwnablePermission($permission, Ownable $ownable)
105 if (userCan($permission, $ownable)) return true;
106 return $this->showPermissionError();
110 * Check if a user has a permission or bypass if the callback is true.
111 * @param $permissionName
115 protected function checkPermissionOr($permissionName, $callback)
117 $callbackResult = $callback();
118 if ($callbackResult === false) $this->checkPermission($permissionName);
123 * Send back a json error message.
124 * @param string $messageText
125 * @param int $statusCode
128 protected function jsonError($messageText = "", $statusCode = 500)
130 return response()->json(['message' => $messageText], $statusCode);