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 // Get a user instance for the current user
34 $user = auth()->user();
35 if (!$user) $user = User::getDefault();
37 // Share variables with views
38 view()->share('signedIn', auth()->check());
39 view()->share('currentUser', $user);
41 // Share variables with controllers
42 $this->currentUser = $user;
43 $this->signedIn = auth()->check();
47 * Stops the application and shows a permission error if
48 * the application is in demo mode.
50 protected function preventAccessForDemoUsers()
52 if (config('app.env') === 'demo') $this->showPermissionError();
56 * Adds the page title into the view.
59 public function setPageTitle($title)
61 view()->share('pageTitle', $title);
65 * On a permission error redirect to home and display.
66 * the error as a notification.
68 protected function showPermissionError()
70 Session::flash('error', trans('errors.permission'));
71 $response = request()->wantsJson() ? response()->json(['error' => trans('errors.permissionJson')], 403) : redirect('/');
72 throw new HttpResponseException($response);
76 * Checks for a permission.
77 * @param string $permissionName
78 * @return bool|\Illuminate\Http\RedirectResponse
80 protected function checkPermission($permissionName)
82 if (!$this->currentUser || !$this->currentUser->can($permissionName)) {
83 $this->showPermissionError();
89 * Check the current user's permissions against an ownable item.
91 * @param Ownable $ownable
94 protected function checkOwnablePermission($permission, Ownable $ownable)
96 if (userCan($permission, $ownable)) return true;
97 return $this->showPermissionError();
101 * Check if a user has a permission or bypass if the callback is true.
102 * @param $permissionName
106 protected function checkPermissionOr($permissionName, $callback)
108 $callbackResult = $callback();
109 if ($callbackResult === false) $this->checkPermission($permissionName);
114 * Send back a json error message.
115 * @param string $messageText
116 * @param int $statusCode
119 protected function jsonError($messageText = "", $statusCode = 500)
121 return response()->json(['message' => $messageText], $statusCode);