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