3 namespace BookStack\Auth\Access;
5 use BookStack\Auth\User;
6 use BookStack\Exceptions\UserTokenExpiredException;
7 use BookStack\Exceptions\UserTokenNotFoundException;
9 use Illuminate\Support\Facades\DB;
10 use Illuminate\Support\Str;
13 class UserTokenService
16 * Name of table where user tokens are stored.
20 protected $tokenTable = 'user_tokens';
23 * Token expiry time in hours.
27 protected $expiryTime = 24;
30 * Delete all email confirmations that belong to a user.
36 public function deleteByUser(User $user)
38 return DB::table($this->tokenTable)
39 ->where('user_id', '=', $user->id)
44 * Get the user id from a token, while check the token exists and has not expired.
46 * @param string $token
48 * @throws UserTokenNotFoundException
49 * @throws UserTokenExpiredException
53 public function checkTokenAndGetUserId(string $token): int
55 $entry = $this->getEntryByToken($token);
57 if (is_null($entry)) {
58 throw new UserTokenNotFoundException('Token "' . $token . '" not found');
61 if ($this->entryExpired($entry)) {
62 throw new UserTokenExpiredException("Token of id {$entry->id} has expired.", $entry->user_id);
65 return $entry->user_id;
69 * Creates a unique token within the email confirmation database.
73 protected function generateToken(): string
75 $token = Str::random(24);
76 while ($this->tokenExists($token)) {
77 $token = Str::random(25);
84 * Generate and store a token for the given user.
90 protected function createTokenForUser(User $user): string
92 $token = $this->generateToken();
93 DB::table($this->tokenTable)->insert([
94 'user_id' => $user->id,
96 'created_at' => Carbon::now(),
97 'updated_at' => Carbon::now(),
104 * Check if the given token exists.
106 * @param string $token
110 protected function tokenExists(string $token): bool
112 return DB::table($this->tokenTable)
113 ->where('token', '=', $token)->exists();
117 * Get a token entry for the given token.
119 * @param string $token
121 * @return object|null
123 protected function getEntryByToken(string $token)
125 return DB::table($this->tokenTable)
126 ->where('token', '=', $token)
131 * Check if the given token entry has expired.
133 * @param stdClass $tokenEntry
137 protected function entryExpired(stdClass $tokenEntry): bool
139 return Carbon::now()->subHours($this->expiryTime)
140 ->gt(new Carbon($tokenEntry->created_at));