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