]> BookStack Code Mirror - bookstack/blob - app/Api/UserApiTokenController.php
Merge branch 'v25-07' into development
[bookstack] / app / Api / UserApiTokenController.php
1 <?php
2
3 namespace BookStack\Api;
4
5 use BookStack\Activity\ActivityType;
6 use BookStack\Http\Controller;
7 use BookStack\Permissions\Permission;
8 use BookStack\Users\Models\User;
9 use Illuminate\Http\Request;
10 use Illuminate\Support\Facades\Hash;
11 use Illuminate\Support\Str;
12
13 class UserApiTokenController extends Controller
14 {
15     /**
16      * Show the form to create a new API token.
17      */
18     public function create(Request $request, int $userId)
19     {
20         $this->checkPermission(Permission::AccessApi);
21         $this->checkPermissionOrCurrentUser(Permission::UsersManage, $userId);
22         $this->updateContext($request);
23
24         $user = User::query()->findOrFail($userId);
25
26         $this->setPageTitle(trans('settings.user_api_token_create'));
27
28         return view('users.api-tokens.create', [
29             'user' => $user,
30             'back' => $this->getRedirectPath($user),
31         ]);
32     }
33
34     /**
35      * Store a new API token in the system.
36      */
37     public function store(Request $request, int $userId)
38     {
39         $this->checkPermission(Permission::AccessApi);
40         $this->checkPermissionOrCurrentUser(Permission::UsersManage, $userId);
41
42         $this->validate($request, [
43             'name'       => ['required', 'max:250'],
44             'expires_at' => ['date_format:Y-m-d'],
45         ]);
46
47         $user = User::query()->findOrFail($userId);
48         $secret = Str::random(32);
49
50         $token = (new ApiToken())->forceFill([
51             'name'       => $request->get('name'),
52             'token_id'   => Str::random(32),
53             'secret'     => Hash::make($secret),
54             'user_id'    => $user->id,
55             'expires_at' => $request->get('expires_at') ?: ApiToken::defaultExpiry(),
56         ]);
57
58         while (ApiToken::query()->where('token_id', '=', $token->token_id)->exists()) {
59             $token->token_id = Str::random(32);
60         }
61
62         $token->save();
63
64         session()->flash('api-token-secret:' . $token->id, $secret);
65         $this->logActivity(ActivityType::API_TOKEN_CREATE, $token);
66
67         return redirect($token->getUrl());
68     }
69
70     /**
71      * Show the details for a user API token, with access to edit.
72      */
73     public function edit(Request $request, int $userId, int $tokenId)
74     {
75         $this->updateContext($request);
76
77         [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
78         $secret = session()->pull('api-token-secret:' . $token->id, null);
79
80         $this->setPageTitle(trans('settings.user_api_token'));
81
82         return view('users.api-tokens.edit', [
83             'user'   => $user,
84             'token'  => $token,
85             'model'  => $token,
86             'secret' => $secret,
87             'back' => $this->getRedirectPath($user),
88         ]);
89     }
90
91     /**
92      * Update the API token.
93      */
94     public function update(Request $request, int $userId, int $tokenId)
95     {
96         $this->validate($request, [
97             'name'       => ['required', 'max:250'],
98             'expires_at' => ['date_format:Y-m-d'],
99         ]);
100
101         [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
102         $token->fill([
103             'name'       => $request->get('name'),
104             'expires_at' => $request->get('expires_at') ?: ApiToken::defaultExpiry(),
105         ])->save();
106
107         $this->logActivity(ActivityType::API_TOKEN_UPDATE, $token);
108
109         return redirect($token->getUrl());
110     }
111
112     /**
113      * Show the delete view for this token.
114      */
115     public function delete(int $userId, int $tokenId)
116     {
117         [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
118
119         $this->setPageTitle(trans('settings.user_api_token_delete'));
120
121         return view('users.api-tokens.delete', [
122             'user'  => $user,
123             'token' => $token,
124         ]);
125     }
126
127     /**
128      * Destroy a token from the system.
129      */
130     public function destroy(int $userId, int $tokenId)
131     {
132         [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
133         $token->delete();
134
135         $this->logActivity(ActivityType::API_TOKEN_DELETE, $token);
136
137         return redirect($this->getRedirectPath($user));
138     }
139
140     /**
141      * Check the permission for the current user and return an array
142      * where the first item is the user in context and the second item is their
143      * API token in context.
144      */
145     protected function checkPermissionAndFetchUserToken(int $userId, int $tokenId): array
146     {
147         $this->checkPermissionOr(Permission::UsersManage, function () use ($userId) {
148             return $userId === user()->id && userCan(Permission::AccessApi);
149         });
150
151         $user = User::query()->findOrFail($userId);
152         $token = ApiToken::query()->where('user_id', '=', $user->id)->where('id', '=', $tokenId)->firstOrFail();
153
154         return [$user, $token];
155     }
156
157     /**
158      * Update the context for where the user is coming from to manage API tokens.
159      * (Track of location for correct return redirects)
160      */
161     protected function updateContext(Request $request): void
162     {
163         $context = $request->query('context');
164         if ($context) {
165             session()->put('api-token-context', $context);
166         }
167     }
168
169     /**
170      * Get the redirect path for the current api token editing session.
171      * Attempts to recall the context of where the user is editing from.
172      */
173     protected function getRedirectPath(User $relatedUser): string
174     {
175         $context = session()->get('api-token-context');
176         if ($context === 'settings' || user()->id !== $relatedUser->id) {
177             return $relatedUser->getEditUrl('#api_tokens');
178         }
179
180         return url('/my-account/auth#api_tokens');
181     }
182 }