public function executeRegister($request) { $userParams = $request->getParameter('api_user'); $this->user_form = new ApiUserForm(); $this->created = false; if ($request->isMethod('post')) { //bind request params to form $captcha = array('recaptcha_challenge_field' => $request->getParameter('recaptcha_challenge_field'), 'recaptcha_response_field' => $request->getParameter('recaptcha_response_field')); $userParams = array_merge($userParams, array('captcha' => $captcha)); $this->user_form->bind($userParams); //look for user with duplicate email $q = LsDoctrineQuery::create()->from('ApiUser u')->where('u.email = ?', $userParams['email']); if ($q->count()) { $validator = new sfValidatorString(array(), array('invalid' => 'There is already an API user with that email address.')); $this->user_form->getErrorSchema()->addError(new sfValidatorError($validator, 'invalid'), 'email'); $request->setError('email', 'There is already a user with that email'); } if ($this->user_form->isValid() && !$request->hasErrors()) { //create inactive api user $user = new ApiUser(); $user->name_first = $userParams['name_first']; $user->name_last = $userParams['name_last']; $user->email = $userParams['email']; $user->reason = $userParams['reason']; $user->api_key = $user->generateKey(); $user->is_active = 1; $user->save(); //add admin notification email to queue $email = new ScheduledEmail(); $email->from_name = sfConfig::get('app_mail_sender_name'); $email->from_email = sfConfig::get('app_mail_sender_address'); $email->to_name = sfConfig::get('app_mail_sender_name'); $email->to_email = sfConfig::get('app_mail_sender_address'); $email->subject = sprintf("%s (%s) has requested an API key", $user->getFullName(), $user->email); $email->body_text = $this->getPartial('keyrequestnotify', array('user' => $user)); $email->save(); $this->created = true; //send approval email $mailBody = $this->getPartial('keycreatenotify', array('user' => $user)); $mailer = new Swift(new Swift_Connection_NativeMail()); $message = new Swift_Message('Your LittleSis API key', $mailBody, 'text/plain'); $from = new Swift_Address(sfConfig::get('app_mail_sender_address'), sfConfig::get('app_mail_sender_name')); $recipients = new Swift_RecipientList(); $recipients->addTo($user->email, $user->name_first . ' ' . $user->name_last); $recipients->addBcc(sfConfig::get('app_mail_sender_address')); $mailer->send($message, $recipients, $from); $mailer->disconnect(); } } }
public static function fromPupilsMentorsArrays(array $pupils, array $mentors) { $userCol = new ApiUserCollection(); $userCol->pupils = array_map(function ($u) { return ApiUser::fromUser($u); }, $pupils); $userCol->mentors = array_map(function ($u) { return ApiUser::fromUser($u); }, $mentors); return $userCol; }
/** * Create User object representing * not-logged-in ApiUser * Later when OAuth based login is added the User object * will be created based on OAuth token * * @return object $this */ protected function initClientUser() { /** * @todo when OAuth2 is supported then route to * initOAuth2User if OAuth2 token is present in request * * @todo check if Basic Auth is enabled in Settings API section * admin may disable basic auth in case OAuth2 is available * If Basic auth is disabled then throw appropriate exception * */ if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) { $this->initBasicAuthUser($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); } else { d('No user credentials in request. Using basic quest user'); $this->Registry->Viewer = ApiUser::factory($this->Registry); } d('Viewer id: ' . $this->Registry->Viewer->getUid()); return $this; }
<?php } ?> <div class="page-header" style="margin: 0 0 20px;"> <h2> <a href="<?php echo URL::route('home'); ?> " class="pull-right btn btn-default">Back to List</a> Timer Details </h2> </div> <?php $name = MapItem::find($timer->itemID); $user = ApiUser::find($timer->user_id); $sys_tmp = preg_split("/\\ [IVX]+/", $name->itemName); $system = $sys_tmp[0]; ?> <h3><a href="http://evemaps.dotlan.net/system/<?php echo $system; ?> "><?php echo $name->itemName; ?> </a></h3> <h4><?php echo date('Y-m-d H:i:s e', strtotime($timer->timeExiting)); ?> - <?php echo Carbon::createFromTimeStamp(strtotime($timer->timeExiting))->diffForHumans();
/* * API Filter: checks every API request for authentication */ Route::filter('private_api', function () { if (isset($_SERVER['PHP_AUTH_USER'])) { $key = Apikey::where('user_id', '=', $_SERVER['PHP_AUTH_USER'])->where('api_key', '=', $_SERVER['PHP_AUTH_PW'])->first(); if ($key) { $user = ApiUser::getInstance(); $user->user_id = $key->user_id; $user->user_fp = $key->user_fp; $user->readonly = $key->readonly; } else { return Response::authHeader(); } } else { return Response::authHeader(); } }); /* * API Filter: checks if API key is readonly */ Route::filter('check_readonly', function () { if (ApiUser::getInstance()->readonly == 1) { App::abort(405, "Your key is readonly"); } }); Route::filter('csrf', function () { if (BaseController::userId() != 1 && Input::get('token') != BaseController::sessionGet('token')) { App::abort(403, "Invalid csrf token"); } });
/** * Authenticates this user and signs them in, if the API key or session is valid. * * @param sfActions $action * @throws Exception if validation fails. */ public function authenticate() { //require SSL, if applicable $this->assertSslApiRequest(); //authenticate via the API key, if provided $api_key = $this->getHttpRequestHeader('Authorization', null); if (!is_null($api_key)) { if (preg_match('/\\s*Basic\\s+(.*?)\\s*$/im', $api_key, $regs)) { $api_key = $regs[1]; $api_user = \ApiUserQuery::create()->filterByApiKey($api_key)->filterByActive(true)->findOne(); if (!$api_user) { throw new \Exception('Unknown or inactive API user.'); } if (0) { $api_user = new \ApiUser(); } $sf_guard_user = $api_user->getUser()->getsfGuardUser(); if ($sf_guard_user->getIsActive()) { \sfContext::getInstance()->getUser()->signIn($sf_guard_user, false); } else { throw new \Exception('Unknown or inactive API user.'); } } else { throw new \Exception('API key format not recognized'); } } //try to authenticate via the session, if the api key was not provided if (is_null($api_key)) { $session_id = $this->getCookie(\sfConfig::get('altumo_api_session_cookie_name', 'my_session_name'), null); if (!is_null($session_id)) { $session = \SessionPeer::retrieveBySessionKey($session_id); if (!$session) { throw new \Exception('Invalid session.'); } $user = $session->getUser(); if (!$user) { throw new \Exception('Invalid session.'); } if (!$user->hasApiUser()) { throw new \Exception('Invalid session.'); } $api_user = $user->getApiUser(); if (!$api_user->isActive()) { throw new \Exception('Inactive API user.'); } else { \sfContext::getInstance()->getUser()->signIn($user->getsfGuardUser(), false); } } else { throw new \Exception('Please provide either a valid session or valid API key.'); } } //successful authentication }
public function userFp() { return ApiUser::getInstance()->user_fp; }
/** * 检查 token 对应的用户是否有权限访问接口 * * @param string $token 用于API权限验证的 token * @param string $action 控制器类名及方法(不包含命名空间) * @param \App\Http\Request $req HTTP 请求对象 * @return array */ public function valid_token($token, $action, &$req = null) : array { if (!$token || strlen($token) !== 32) { return [-101, '请提供有效的 token']; } $dateline = time(); $uid = mem_get('api_' . $token); if ($uid === false) { $m_al = new ApiLogin(); $api_login = $m_al->find(['token' => $token, 'dateline >=' => $dateline - self::CACHE_TIME], 'uid, token, dateline'); if ($api_login) { $uid = $api_login['uid']; mem_set('api_' . $token, $uid, self::CACHE_TIME); } else { return [-102, 'token不匹配']; } } // 检查权限 $key_rights = 'api_rights_' . $uid; $key_allowed_ip = 'api_allowed_ip_' . $uid; $uid_rights = mem_get($key_rights); $allowed_ip = mem_get($key_allowed_ip); if ($uid_rights === false) { $m_au = new ApiUser(); $api_user = $m_au->find(['uid' => $uid], 'rights, allowed_ip'); if (!$api_user) { return [-103, 'token 对应的用户不存在']; } $uid_rights = $api_user['rights']; $allowed_ip = $api_user['allowed_ip']; mem_set($key_rights, $uid_rights, self::CACHE_TIME); mem_set($key_allowed_ip, $allowed_ip, self::CACHE_TIME); } list($controller, $method) = explode(':', $action, 2); if (!$this->check_rights($uid_rights, $controller, $method)) { return [-104, '您没有权限访问该接口']; } // 检查IP是否允许 $ip = $_SERVER['REMOTE_ADDR']; if ($allowed_ip && strpos($allowed_ip, $ip) === false) { return [-105, '您的IP无权限访问接口']; } $req = $this->set_extra_args($req, $uid_rights, $action); return [0, $uid]; }
private function updateUser($token, $result) { // validate permissions $permission = 0; foreach (Config::get('braveapi.auth-edit-tags') as $tag) { if (in_array($tag, $result->tags)) { $permission = 1; break; } } // per user overrides foreach (Config::get('braveapi.auth-edit-users') as $id) { if ($id == $result->character->id) { $permission = 1; break; } } // Get alliance info $api = new Brave\API(Config::get('braveapi.application-endpoint'), Config::get('braveapi.application-identifier'), Config::get('braveapi.local-private-key'), Config::get('braveapi.remote-public-key')); $alliance_result = $api->lookup->alliance(array('search' => $result->alliance->id, 'only' => 'short')); /* if($result->character->id == 93647416) { dd($result); } */ // check for existing user $userfound = ApiUser::find($result->character->id); if ($userfound == false) { // no user found, create it $userfound = ApiUser::create(array('id' => $result->character->id, 'token' => $token, 'remember_token' => '', 'character_name' => $result->character->name, 'alliance_id' => $result->alliance->id, 'alliance_name' => $result->alliance->name, 'alliance_ticker' => $alliance_result->short, 'tags' => json_encode($result->tags), 'status' => 1, 'permission' => $permission)); } else { // update the existing user $userfound->token = $token; $userfound->status = 1; $userfound->permission = $permission; $userfound->token = $token; $userfound->character_name = $result->character->name; $userfound->alliance_id = $result->alliance->id; $userfound->alliance_name = $result->alliance->name; $userfound->alliance_ticker = $alliance_result->short; $userfound->permission = $permission; $userfound->tags = json_encode($result->tags); $userfound->save(); } return $userfound; }
/** * Returns the * @return mixed * @throws EApiError */ protected function getUser() { if (null === $this->_user) { $apiKeyName = 'HTTP_' . Yii::app()->params['api.key.name']; if (!isset($_SERVER[$apiKeyName]) || !($apiKey = trim($_SERVER[$apiKeyName])) || !($this->_user = ApiUser::model()->findByAttributes(array('api_key' => $apiKey)))) { throw new EApiError(HHttp::ERROR_UNAUTHORIZED, HHttp::getErrorMessage(HHttp::ERROR_UNAUTHORIZED)); } } Yii::app()->user->setId($this->_user->id); Yii::app()->user->setName($this->_user->{$this->attributeName}); return $this->_user; }