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
36 $user = auth()->user();
37 if (!$user) $user = User::getDefault();
39 // Share variables with views
40 view()->share('signedIn', auth()->check());
41 view()->share('currentUser', $user);
43 // Share variables with controllers
44 $this->currentUser = $user;
45 $this->signedIn = auth()->check();
47 return $next($request);
52 * Stops the application and shows a permission error if
53 * the application is in demo mode.
55 protected function preventAccessForDemoUsers()
57 if (config('app.env') === 'demo') $this->showPermissionError();
61 * Adds the page title into the view.
64 public function setPageTitle($title)
66 view()->share('pageTitle', $title);
70 * On a permission error redirect to home and display.
71 * the error as a notification.
73 protected function showPermissionError()
75 Session::flash('error', trans('errors.permission'));
76 $response = request()->wantsJson() ? response()->json(['error' => trans('errors.permissionJson')], 403) : redirect('/');
77 throw new HttpResponseException($response);
81 * Checks for a permission.
82 * @param string $permissionName
83 * @return bool|\Illuminate\Http\RedirectResponse
85 protected function checkPermission($permissionName)
87 if (!$this->currentUser || !$this->currentUser->can($permissionName)) {
88 $this->showPermissionError();
94 * Check the current user's permissions against an ownable item.
96 * @param Ownable $ownable
99 protected function checkOwnablePermission($permission, Ownable $ownable)
101 if (userCan($permission, $ownable)) return true;
102 return $this->showPermissionError();
106 * Check if a user has a permission or bypass if the callback is true.
107 * @param $permissionName
111 protected function checkPermissionOr($permissionName, $callback)
113 $callbackResult = $callback();
114 if ($callbackResult === false) $this->checkPermission($permissionName);
119 * Send back a json error message.
120 * @param string $messageText
121 * @param int $statusCode
124 protected function jsonError($messageText = "", $statusCode = 500)
126 return response()->json(['message' => $messageText], $statusCode);