public static function generateForUser($user_id) { Token::where('user_id', '=', $user_id)->delete(); $token = new Token(); $token->{'user_id'} = $user_id; $token->token = $user_id . '-' . Token::v4UUID(); $token->expires = Token::expirationTime(); $token->save(); return $token; }
private function makePush(Token $token, $data) { $response = CloudMessaging::send($token->token, $data); $code = ResponseCode::fromResponse($response); if (ResponseCode::NOT_REGISTERED === $code || ResponseCode::UNKNOWN_ERROR === $code) { $token->delete(); } \Log::debug('PushHandler:Response', [ResponseCode::getMessageFromCode($code)]); return ResponseCode::getMessageFromCode($code); }
public function __construct(Request $request) { $headers = $request->header(); if (!empty($headers['x-api-token']) && !is_null($headers['x-api-token'])) { $this->token = Token::where('api_token', $headers['x-api-token'])->first(); } }
public function register() { if ($this->getIsNewRecord() == false) { throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user'); } if ($this->module->enableConfirmation == false) { $this->confirmed_at = time(); } if ($this->module->enableGeneratingPassword) { $this->password = Password::generate(8); } $this->trigger(self::USER_REGISTER_INIT); if ($this->save()) { $this->trigger(self::USER_REGISTER_DONE); if ($this->module->enableConfirmation) { $token = \Yii::createObject(['class' => Token::className(), 'type' => Token::TYPE_CONFIRMATION]); $token->link('user', $this); $this->mailer->sendConfirmationMessage($this, $token); } else { \Yii::$app->user->login($this); } if ($this->module->enableGeneratingPassword) { $this->mailer->sendWelcomeMessage($this); } \Yii::$app->session->setFlash('info', $this->getFlashMessage()); \Yii::getLogger()->log('User has been registered', Logger::LEVEL_INFO); return true; } \Yii::getLogger()->log('An error occurred while registering user account', Logger::LEVEL_ERROR); return false; }
/** * Generate a token to authenticate a user * * @return mixed */ public function login($device_id = null, $device_type = null, $device_token = null) { // clear old sessions for any user with: same(device_id, os) $to_remove = Token::where('device_id', '=', $device_id)->where('device_os', '=', $device_type)->delete(); $token = Token::getInstance(); $token->user_id = $this->_id; $token->device_id = $device_id; $token->device_os = $device_type; $token->device_token = $device_token; $token->save(); return $token; }
/** * @param \App\Restful\RestfulRequest $request * * @return bool */ public function isAuthorized(RestfulRequest $request) { if (!$request->token) { throw new RestfulException(Response::HTTP_UNAUTHORIZED, "missing token"); } /** @var \App\Models\Token $tokenModel */ $tokenModel = Token::ofToken($request->token)->first(); if ($tokenModel == null || $tokenModel->isExpired()) { throw new RestfulException(Response::HTTP_UNAUTHORIZED, "token is invalid or expired"); } return true; }
function get($token) { try { $tokenModel = TokenModel::where('token', $token)->firstOrFail(); } catch (ModelNotFoundException $e) { return null; } $token = new Token(); $token->token = $tokenModel->token; $token->userId = $tokenModel->user_id; $token->createTime = $tokenModel->create_time; $token->expireTime = $tokenModel->expire_time; return $token; }
public function login(Request $request) { $email = $request->input('email'); $password = $request->input('password'); if (!$email || !$password) { return response()->json(array('error' => 'You must provide an email address and password.'), 400); } $hashedPassword = User::hashedPassword($password); $user = User::where(['password' => $hashedPassword, 'email' => $email])->first(); if (!$user) { return response()->json(array('error' => 'Unable to find a user matching that email address and password.'), 401); } $token = Token::generateForUser($user->id); return response()->json(['user' => $user, 'token' => $token->token], 200, []); }
public function sendChangeEmail($user_id) { $token = Token::findByType(Token::TYPE_EMAIL, $user_id, $this->email); $rtnCd = false; if ($token) { $settings = Yii::$app->params['settings']; try { $rtnCd = Yii::$app->getMailer()->compose(['html' => 'emailChangeToken-text'], ['token' => $token])->setFrom([$settings['mailer_username'] => $settings['site_name']])->setTo($this->email)->setSubject($settings['site_name'] . '修改邮箱确认')->send(); } catch (\Exception $e) { return false; } (new History(['user_id' => $user_id, 'action' => History::ACTION_CHANGE_EMAIL, 'ext' => $this->email]))->save(false); } return $rtnCd; }
/** * Sends an email with a link, for resetting the password. * * @return boolean whether the email was send */ public function sendEmail() { $user = $this->_user; $settings = Yii::$app->params['settings']; $token = Token::findByType(Token::TYPE_PWD, $user->id); $rtnCd = false; if ($token) { try { $rtnCd = Yii::$app->getMailer()->compose('passwordResetToken-text', ['token' => $token])->setFrom([$settings['mailer_username'] => $settings['site_name']])->setTo($this->email)->setSubject($settings['site_name'] . '密码重置')->send(); } catch (\Exception $e) { return false; } (new History(['user_id' => $user->id, 'action' => History::ACTION_RESET_PWD]))->save(false); } return $rtnCd; }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $authenticated = false; if (!isset($_SERVER['HTTP_X_SITE_AUTH_TOKEN'])) { return response()->json(array('error' => 'This resource requires an authentication token.'), 403); } $token = $_SERVER['HTTP_X_SITE_AUTH_TOKEN']; if ($token) { $token = Token::where('token', '=', $token)->where('expires', '>', time())->first(); if ($token) { if ($token->{'user_id'} != 0) { session(['user_id' => $token->{'user_id'}]); } $authenticated = true; $token->updateExpiration(); } } if (!$authenticated) { return response()->json(array('error' => 'Invalid token'), 403); } return $next($request); }
/** * @api {post} /token Сохранить токен устройства * @apiName postToken * @apiGroup Tokens * * @apiParam {String} token Уникальный token устройства из GCM или APNS * @apiParam {Int} device_type_id Тип устройства(ANDROID = 1, IOS = 2) * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * * @param Request $request * @param TokenRepository $tokenRepository * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response|static */ public function store(Request $request, TokenRepository $tokenRepository) { /** * @var $user User */ $user = auth()->user(); if (!$user) { return response('User doesn\'t exist', 401); } $attributes = $request->all(); $attributes['user_id'] = $user->id; $token = $tokenRepository->getByToken($attributes['token']); /** * если токен существует, только обновляем время */ if ($token) { $token->touch(); return $token; } $token = Token::create($attributes); return $token; }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $headers = $request->header(); // header checked if (empty($headers['x-api-token']) || is_null($headers['x-api-token'])) { return response()->json(['error' => 'Not Authorization'], 401); } //token valid $token = Token::where('api_token', $headers['x-api-token'])->first(); if (empty($token)) { return response()->json(['error' => 'token_invalid'], 403); } //token expired //$token->expires_on //return response()->json(['error' => 'token_expired'], $e->getStatusCode()); // if (!$request->isMethod('get')) { if (empty($token->user->email) || !$token->user->role_id == 3) { return response()->json(['error' => 'Permission denied'], 403); } } return $next($request); }
/** * Creates a form model given a token. * * @param string $token * @param array $config name-value pairs that will be used to initialize the object properties * @throws \yii\base\InvalidParamException if token is empty or not valid */ public function __construct($token, $config = []) { $this->_token = Token::findByToken($token); parent::__construct($config); }
public function actionSendActivateMail() { if (Token::sendActivateMail(Yii::$app->getUser()->getIdentity())) { Yii::$app->getSession()->setFlash('activateMailOK', '邮件发送成功,请进邮箱点击激活链接'); } else { Yii::$app->getSession()->setFlash('activateMailNG', '邮件发送失败'); } // return $this->goBack(); return $this->redirect(['user/setting']); }
/** * @return \yii\db\ActiveQuery */ public function getTokens() { return $this->hasMany(Token::className(), ['user_id' => 'id']); }
public function actionActivate($token) { try { $token = Token::findByToken($token, Token::TYPE_REG); } catch (InvalidParamException $e) { return $this->render('opResult', ['title' => '帐号激活失败', 'status' => 'warning', 'msg' => $e->getMessage()]); } $user = $token->user; $token->status = Token::STATUS_USED; $token->save(false); if (!empty($token->ext) && $user->email !== $token->ext && User::findOne(['email' => $token->ext])) { return $this->render('opResult', ['title' => '帐号激活失败', 'status' => 'warning', 'msg' => '申请绑定邮箱[' . $token->ext . ']已被注册使用']); } if (intval($this->settings['admin_verify']) === 1) { $user->status = User::STATUS_ADMIN_VERIFY; $result = ['title' => '注册邮箱确认成功', 'status' => 'success', 'msg' => '注册邮箱确认成功,请等待管理员验证。']; } else { $user->status = User::STATUS_ACTIVE; $result = ['title' => '帐号激活成功', 'status' => 'success', 'msg' => '帐号激活成功,现在可以 ' . \yii\helpers\Html::a('登录', ['site/login']) . ' 发贴和回帖了。']; } $user->email = $token->ext; $user->save(false); return $this->render('opResult', $result); }
public function deleteToken($id, $token_id) { $server = Server::findOrFail($id); $token = Token::findOrFail($token_id); (new TeamspeakHelper())->deleteToken($server, $token); $token->delete(); return redirect()->back()->with('success', 'Token has been deleted'); }
public function getNotification() { $tokens = Token::where("os", "=", "ios")->get(); foreach ($tokens as $token) { $this->_ios_notification($token->token, "HOLA MUNDO", 1); } return $this->getIndex(); }
/** * @param $token * @return Token */ public function getByToken($token) { return Token::where('token', $token)->first(); }
public function actionConf($id = null, $code = NULL) { $tok = Token::find()->where(['id' => $id])->one(); if ($tok->code == $code) { if ($tok->delete()) { } else { echo 'delete token error'; } $sig = Sign::find()->where(['id' => $id])->one(); $sig->activate = 1; if ($sig->save()) { return $this->redirect(['sign/login']); } //return $this->render('activate',['tok' => $sig]); } }
/** * Signs user up. * * @return User|null the saved model or null if saving fails */ public function signup() { if ($this->validate()) { $user = new User(); $user->username = $this->username; $user->email = $this->email; $user->setPassword($this->password); $user->generateAuthKey(); $user->avatar = 'avatar/0_{size}.png'; if ($this->action != self::ACTION_AUTH_SIGNUP) { if (intval(Yii::$app->params['settings']['email_verify']) === 1) { $user->status = User::STATUS_INACTIVE; } else { if (intval(Yii::$app->params['settings']['admin_verify']) === 1) { $user->status = User::STATUS_ADMIN_VERIFY; } else { $user->status = User::STATUS_ACTIVE; } } } else { $user->status = User::STATUS_ACTIVE; } if ($user->save()) { if ($this->action != self::ACTION_AUTH_SIGNUP && intval(Yii::$app->params['settings']['email_verify']) === 1) { Token::sendActivateMail($user); } return $user; } } return null; }
public function user(Request $request) { $rules = ['email' => 'required', 'password' => 'required', 'name' => 'required']; $validator = Validator::make($request->all(), $rules); if ($validator->fails()) { return response()->json(['error' => 'Unprocessable Entity'], 422); } // user 검색 및 생 $user = User::where('email', $request->input('email'))->first(); if (empty($user)) { $user = new User(); $user->username = $request->input('name'); $user->email = $request->input('email'); $user->password = bcrypt($request->input('password')); $user->role_id = 2; $user->save(); } // api token 검색 및 생성 $token = Token::where('user_id', $user->id)->first(); if (empty($token)) { $token = new Token(); $token->user_id = $user->id; } $token->api_token = hash('sha256', str_random(10), false); $token->save(); // api token 리턴 return response()->json(['token' => $token->api_token], 200); }
/** * notifications function. * * @access public * @return void */ public function postNotification() { $device_token = Input::get('token', ''); $device_os = Input::get('os', ''); $token = Token::where('token', "=", $device_token)->where('os', "=", $device_os)->first(); if (!$token) { $token = new Token(); $token->token = $device_token; $token->os = $device_os; $token->save(); } $user = Auth::user()->id; $token->user_id = $user; $token->save(); return Response::json(array("service" => __FUNCTION__, "status" => true)); }