]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/UserApiTokenController.php
Apply fixes from StyleCI
[bookstack] / app / Http / Controllers / UserApiTokenController.php
1 <?php
2
3 namespace BookStack\Http\Controllers;
4
5 use BookStack\Actions\ActivityType;
6 use BookStack\Api\ApiToken;
7 use BookStack\Auth\User;
8 use Illuminate\Http\Request;
9 use Illuminate\Support\Facades\Hash;
10 use Illuminate\Support\Str;
11
12 class UserApiTokenController extends Controller
13 {
14     /**
15      * Show the form to create a new API token.
16      */
17     public function create(int $userId)
18     {
19         // Ensure user is has access-api permission and is the current user or has permission to manage the current user.
20         $this->checkPermission('access-api');
21         $this->checkPermissionOrCurrentUser('users-manage', $userId);
22
23         $user = User::query()->findOrFail($userId);
24
25         return view('users.api-tokens.create', [
26             'user' => $user,
27         ]);
28     }
29
30     /**
31      * Store a new API token in the system.
32      */
33     public function store(Request $request, int $userId)
34     {
35         $this->checkPermission('access-api');
36         $this->checkPermissionOrCurrentUser('users-manage', $userId);
37
38         $this->validate($request, [
39             'name'       => 'required|max:250',
40             'expires_at' => 'date_format:Y-m-d',
41         ]);
42
43         $user = User::query()->findOrFail($userId);
44         $secret = Str::random(32);
45
46         $token = (new ApiToken())->forceFill([
47             'name'       => $request->get('name'),
48             'token_id'   => Str::random(32),
49             'secret'     => Hash::make($secret),
50             'user_id'    => $user->id,
51             'expires_at' => $request->get('expires_at') ?: ApiToken::defaultExpiry(),
52         ]);
53
54         while (ApiToken::query()->where('token_id', '=', $token->token_id)->exists()) {
55             $token->token_id = Str::random(32);
56         }
57
58         $token->save();
59
60         session()->flash('api-token-secret:' . $token->id, $secret);
61         $this->showSuccessNotification(trans('settings.user_api_token_create_success'));
62         $this->logActivity(ActivityType::API_TOKEN_CREATE, $token);
63
64         return redirect($user->getEditUrl('/api-tokens/' . $token->id));
65     }
66
67     /**
68      * Show the details for a user API token, with access to edit.
69      */
70     public function edit(int $userId, int $tokenId)
71     {
72         [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
73         $secret = session()->pull('api-token-secret:' . $token->id, null);
74
75         return view('users.api-tokens.edit', [
76             'user'   => $user,
77             'token'  => $token,
78             'model'  => $token,
79             'secret' => $secret,
80         ]);
81     }
82
83     /**
84      * Update the API token.
85      */
86     public function update(Request $request, int $userId, int $tokenId)
87     {
88         $this->validate($request, [
89             'name'       => 'required|max:250',
90             'expires_at' => 'date_format:Y-m-d',
91         ]);
92
93         [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
94         $token->fill([
95             'name'       => $request->get('name'),
96             'expires_at' => $request->get('expires_at') ?: ApiToken::defaultExpiry(),
97         ])->save();
98
99         $this->showSuccessNotification(trans('settings.user_api_token_update_success'));
100         $this->logActivity(ActivityType::API_TOKEN_UPDATE, $token);
101
102         return redirect($user->getEditUrl('/api-tokens/' . $token->id));
103     }
104
105     /**
106      * Show the delete view for this token.
107      */
108     public function delete(int $userId, int $tokenId)
109     {
110         [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
111
112         return view('users.api-tokens.delete', [
113             'user'  => $user,
114             'token' => $token,
115         ]);
116     }
117
118     /**
119      * Destroy a token from the system.
120      */
121     public function destroy(int $userId, int $tokenId)
122     {
123         [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
124         $token->delete();
125
126         $this->showSuccessNotification(trans('settings.user_api_token_delete_success'));
127         $this->logActivity(ActivityType::API_TOKEN_DELETE, $token);
128
129         return redirect($user->getEditUrl('#api_tokens'));
130     }
131
132     /**
133      * Check the permission for the current user and return an array
134      * where the first item is the user in context and the second item is their
135      * API token in context.
136      */
137     protected function checkPermissionAndFetchUserToken(int $userId, int $tokenId): array
138     {
139         $this->checkPermissionOr('users-manage', function () use ($userId) {
140             return $userId === user()->id && userCan('access-api');
141         });
142
143         $user = User::query()->findOrFail($userId);
144         $token = ApiToken::query()->where('user_id', '=', $user->id)->where('id', '=', $tokenId)->firstOrFail();
145
146         return [$user, $token];
147     }
148 }