public static function make(User $user) { $access_token = new AccessToken(); $access_token->token = str_random(255); $access_token->user_id = $user->id; $access_token->expires_at = new \DateTime('now + 30 days'); $successful = false; while (!$successful) { try { $successful = $access_token->save(); } catch (QueryException $e) { $successful = false; } } return $access_token; }
public function getAccessToken() { $sessionId = \Yii::$app->session->getId(); $user = \Yii::$app->getUser(); $accessToken = AccessToken::find()->where(['user_id' => $user->id])->andWhere(['session_id' => $sessionId])->one(); if ($accessToken != null) { if (!$accessToken->validate(['token'])) { $accessToken->token = TokenService::generateAccessToken(); } } else { $accessToken = new AccessToken(); $accessToken->user_id = $user->id; $accessToken->session_id = $sessionId; $accessToken->token = TokenService::generateAccessToken(); } $date = date('Y-m-d H:i:s'); $accessToken->created = $date; if ($accessToken->save()) { $this->accessToken = $accessToken; return $accessToken->token; } else { return null; } }