]> BookStack Code Mirror - bookstack/blob - app/Api/UserApiTokenController.php
Comments: Added text for new activity types
[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\Users\Models\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->logActivity(ActivityType::API_TOKEN_CREATE, $token);
62
63         return redirect($user->getEditUrl('/api-tokens/' . $token->id));
64     }
65
66     /**
67      * Show the details for a user API token, with access to edit.
68      */
69     public function edit(int $userId, int $tokenId)
70     {
71         [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
72         $secret = session()->pull('api-token-secret:' . $token->id, null);
73
74         return view('users.api-tokens.edit', [
75             'user'   => $user,
76             'token'  => $token,
77             'model'  => $token,
78             'secret' => $secret,
79         ]);
80     }
81
82     /**
83      * Update the API token.
84      */
85     public function update(Request $request, int $userId, int $tokenId)
86     {
87         $this->validate($request, [
88             'name'       => ['required', 'max:250'],
89             'expires_at' => ['date_format:Y-m-d'],
90         ]);
91
92         [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
93         $token->fill([
94             'name'       => $request->get('name'),
95             'expires_at' => $request->get('expires_at') ?: ApiToken::defaultExpiry(),
96         ])->save();
97
98         $this->logActivity(ActivityType::API_TOKEN_UPDATE, $token);
99
100         return redirect($user->getEditUrl('/api-tokens/' . $token->id));
101     }
102
103     /**
104      * Show the delete view for this token.
105      */
106     public function delete(int $userId, int $tokenId)
107     {
108         [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
109
110         return view('users.api-tokens.delete', [
111             'user'  => $user,
112             'token' => $token,
113         ]);
114     }
115
116     /**
117      * Destroy a token from the system.
118      */
119     public function destroy(int $userId, int $tokenId)
120     {
121         [$user, $token] = $this->checkPermissionAndFetchUserToken($userId, $tokenId);
122         $token->delete();
123
124         $this->logActivity(ActivityType::API_TOKEN_DELETE, $token);
125
126         return redirect($user->getEditUrl('#api_tokens'));
127     }
128
129     /**
130      * Check the permission for the current user and return an array
131      * where the first item is the user in context and the second item is their
132      * API token in context.
133      */
134     protected function checkPermissionAndFetchUserToken(int $userId, int $tokenId): array
135     {
136         $this->checkPermissionOr('users-manage', function () use ($userId) {
137             return $userId === user()->id && userCan('access-api');
138         });
139
140         $user = User::query()->findOrFail($userId);
141         $token = ApiToken::query()->where('user_id', '=', $user->id)->where('id', '=', $tokenId)->firstOrFail();
142
143         return [$user, $token];
144     }
145 }