예제 #1
0
파일: Consumer.php 프로젝트: himmelex/NTW
 static function generateNew()
 {
     $cons = new Consumer();
     $rand = common_good_rand(16);
     $cons->seed = $rand;
     $cons->consumer_key = md5(time() + $rand);
     $cons->consumer_secret = md5(md5(time() + time() + $rand));
     $cons->created = common_sql_now();
     return $cons;
 }
예제 #2
0
 function handle($args)
 {
     parent::handle($args);
     if (common_is_real_login()) {
         // TRANS: Client error displayed when trying to log in while already logged on.
         $this->clientError(_m('Already logged in.'));
     } else {
         global $casSettings;
         phpCAS::client(CAS_VERSION_2_0, $casSettings['server'], $casSettings['port'], $casSettings['path'], false);
         phpCAS::setNoCasServerValidation();
         phpCAS::handleLogoutRequests();
         phpCAS::forceAuthentication();
         global $casTempPassword;
         $casTempPassword = common_good_rand(16);
         $user = common_check_user(phpCAS::getUser(), $casTempPassword);
         if (!$user) {
             // TRANS: Server error displayed when trying to log in with incorrect username or password.
             $this->serverError(_m('Incorrect username or password.'));
             return;
         }
         // success!
         if (!common_set_user($user)) {
             // TRANS: Server error displayed when login fails in CAS authentication plugin.
             $this->serverError(_m('Error setting user. You are probably not authorized.'));
             return;
         }
         common_real_login(true);
         $url = common_get_returnto();
         if ($url) {
             // We don't have to return to it again
             common_set_returnto(null);
         } else {
             if (common_config('site', 'private') && $casSettings['takeOverLogin']) {
                 //SSO users expect to just go to the URL they entered
                 //if we don't have a returnto set, the user entered the
                 //main StatusNet url, so send them there.
                 $url = common_local_url('public');
             } else {
                 //With normal logins (regular form-based username/password),
                 //the user would expect to go to their home after logging in.
                 $url = common_local_url('public', array('nickname' => $user->nickname));
             }
         }
         common_redirect($url, 303);
     }
 }
 function makeNew($user)
 {
     $login_token = Login_token::staticGet('user_id', $user->id);
     if (!empty($login_token)) {
         $login_token->delete();
     }
     $login_token = new Login_token();
     $login_token->user_id = $user->id;
     $login_token->token = common_good_rand(16);
     $login_token->created = common_sql_now();
     $result = $login_token->insert();
     if (!$result) {
         common_log_db_error($login_token, 'INSERT', __FILE__);
         throw new Exception(sprintf(_('Could not create login token for %s'), $user->nickname));
     }
     return $login_token;
 }
예제 #4
0
 function new_access_token($token, $consumer)
 {
     common_debug('new_access_token("' . $token->key . '","' . $consumer->key . '")', __FILE__);
     $rt = new Token();
     $rt->consumer_key = $consumer->key;
     $rt->tok = $token->key;
     $rt->type = 0;
     // request
     if ($rt->find(true) && $rt->state == 1) {
         // authorized
         common_debug('request token found.', __FILE__);
         $at = new Token();
         $at->consumer_key = $consumer->key;
         $at->tok = common_good_rand(16);
         $at->secret = common_good_rand(16);
         $at->type = 1;
         // access
         $at->created = DB_DataObject_Cast::dateTime();
         if (!$at->insert()) {
             $e = $at->_lastError;
             common_debug('access token "' . $at->tok . '" not inserted: "' . $e->message . '"', __FILE__);
             return null;
         } else {
             common_debug('access token "' . $at->tok . '" inserted', __FILE__);
             // burn the old one
             $orig_rt = clone $rt;
             $rt->state = 2;
             // used
             if (!$rt->update($orig_rt)) {
                 return null;
             }
             common_debug('request token "' . $rt->tok . '" updated', __FILE__);
             // Update subscription
             // XXX: mixing levels here
             $sub = Subscription::staticGet('token', $rt->tok);
             if (!$sub) {
                 return null;
             }
             common_debug('subscription for request token found', __FILE__);
             $orig_sub = clone $sub;
             $sub->token = $at->tok;
             $sub->secret = $at->secret;
             if (!$sub->update($orig_sub)) {
                 return null;
             } else {
                 common_debug('subscription updated to use access token', __FILE__);
                 return new OAuthToken($at->tok, $at->secret);
             }
         }
     } else {
         return null;
     }
 }
예제 #5
0
파일: util.php 프로젝트: himmelex/NTW
function common_session_token()
{
    common_ensure_session();
    if (!array_key_exists('token', $_SESSION)) {
        $_SESSION['token'] = common_good_rand(64);
    }
    return $_SESSION['token'];
}
예제 #6
0
 function setAvatar($user)
 {
     try {
         $picUrl = sprintf('http://graph.facebook.com/%d/picture?type=large', $this->fbuser->id);
         // fetch the picture from Facebook
         $client = new HTTPClient();
         // fetch the actual picture
         $response = $client->get($picUrl);
         if ($response->isOk()) {
             // seems to always be jpeg, but not sure
             $tmpname = "facebook-avatar-tmp-" . common_good_rand(4);
             $ok = file_put_contents(Avatar::path($tmpname), $response->getBody());
             if (!$ok) {
                 common_log(LOG_WARNING, 'Couldn\'t save tmp Facebook avatar: ' . $tmpname, __FILE__);
             } else {
                 // save it as an avatar
                 $file = new ImageFile($user->id, Avatar::path($tmpname));
                 $filename = $file->resize(180);
                 // size of the biggest img we get from Facebook
                 $profile = $user->getProfile();
                 if ($profile->setOriginal($filename)) {
                     common_log(LOG_INFO, sprintf('Saved avatar for %s (%d) from Facebook picture for ' . '%s (fbuid %d), filename = %s', $user->nickname, $user->id, $this->fbuser->name, $this->fbuid, $filename), __FILE__);
                     // clean up tmp file
                     @unlink(Avatar::path($tmpname));
                 }
             }
         }
     } catch (Exception $e) {
         common_log(LOG_WARNING, 'Couldn\'t save Facebook avatar: ' . $e->getMessage(), __FILE__);
         // error isn't fatal, continue
     }
 }
예제 #7
0
파일: HubSub.php 프로젝트: Br3nda/StatusNet
 /**
  * Send a verification ping to subscriber, and if confirmed apply the changes.
  * This may create, update, or delete the database record.
  *
  * @param string $mode 'subscribe' or 'unsubscribe'
  * @param string $token hub.verify_token value, if provided by client
  * @throws ClientException on failure
  */
 function verify($mode, $token = null)
 {
     assert($mode == 'subscribe' || $mode == 'unsubscribe');
     $challenge = common_good_rand(32);
     $params = array('hub.mode' => $mode, 'hub.topic' => $this->topic, 'hub.challenge' => $challenge);
     if ($mode == 'subscribe') {
         $params['hub.lease_seconds'] = $this->lease;
     }
     if ($token !== null) {
         $params['hub.verify_token'] = $token;
     }
     // Any existing query string parameters must be preserved
     $url = $this->callback;
     if (strpos($url, '?') !== false) {
         $url .= '&';
     } else {
         $url .= '?';
     }
     $url .= http_build_query($params, '', '&');
     $request = new HTTPClient();
     $response = $request->get($url);
     $status = $response->getStatus();
     if ($status >= 200 && $status < 300) {
         common_log(LOG_INFO, "Verified {$mode} of {$this->callback}:{$this->topic}");
     } else {
         throw new ClientException("Hub subscriber verification returned HTTP {$status}");
     }
     $old = HubSub::staticGet($this->topic, $this->callback);
     if ($mode == 'subscribe') {
         if ($old) {
             $this->update($old);
         } else {
             $ok = $this->insert();
         }
     } else {
         if ($mode == 'unsubscribe') {
             if ($old) {
                 $old->delete();
             } else {
                 // That's ok, we're already unsubscribed.
             }
         }
     }
 }
예제 #8
0
파일: uuid.php 프로젝트: Grasia/bolotweet
 /**
  * Generate a new UUID
  *
  * @return 36-char v4 (random-ish) UUID
  */
 static function gen()
 {
     return sprintf('%s-%s-%04x-%04x-%s', common_good_rand(4), common_good_rand(2), hexdec(common_good_rand(2)) & 0xfff | 0x4000, hexdec(common_good_rand(2)) & 0x3fff | 0x8000, common_good_rand(6));
 }
예제 #9
0
 static function saveNew($user_id, $action, $arg1, $arg2)
 {
     $channel = new Realtime_channel();
     $channel->user_id = $user_id;
     $channel->action = $action;
     $channel->arg1 = $arg1;
     $channel->arg2 = $arg2;
     $channel->audience = 1;
     $channel->channel_key = common_good_rand(16);
     // 128-bit key, 32 hex chars
     $channel->created = common_sql_now();
     $channel->modified = $channel->created;
     $channel->insert();
     return $channel;
 }
 function setAvatar($user)
 {
     $picUrl = sprintf('http://graph.facebook.com/%s/picture?type=large', $this->fbuid);
     // fetch the picture from Facebook
     $client = new HTTPClient();
     // fetch the actual picture
     $response = $client->get($picUrl);
     if ($response->isOk()) {
         $finalUrl = $client->getUrl();
         // Make sure the filename is unique becuase it's possible for a user
         // to deauthorize our app, and then come back in as a new user but
         // have the same Facebook picture (avatar URLs have a unique index
         // and their URLs are based on the filenames).
         $filename = 'facebook-' . common_good_rand(4) . '-' . substr(strrchr($finalUrl, '/'), 1);
         $ok = file_put_contents(Avatar::path($filename), $response->getBody());
         if (!$ok) {
             common_log(LOG_WARNING, sprintf('Couldn\'t save Facebook avatar %s', $tmp), __FILE__);
         } else {
             // save it as an avatar
             $profile = $user->getProfile();
             if ($profile->setOriginal($filename)) {
                 common_log(LOG_INFO, sprintf('Saved avatar for %s (%d) from Facebook picture for ' . '%s (fbuid %d), filename = %s', $user->nickname, $user->id, $this->fbuser['name'], $this->fbuid, $filename), __FILE__);
             }
         }
     }
 }
예제 #11
0
 static function createAnonProfile()
 {
     // Get the anon user's IP, and turn it into a nickname
     list($proxy, $ip) = common_client_ip();
     // IP + time + random number should help to avoid collisions
     $baseNickname = $ip . '-' . time() . '-' . common_good_rand(5);
     $profile = new Profile();
     $profile->nickname = $baseNickname;
     $id = $profile->insert();
     if (!$id) {
         // TRANS: Server exception.
         throw new ServerException(_m("Could not create anonymous user session."));
     }
     // Stick the Profile ID into the nickname
     $orig = clone $profile;
     $profile->nickname = 'anon-' . $id . '-' . $baseNickname;
     $result = $profile->update($orig);
     if (!$result) {
         // TRANS: Server exception.
         throw new ServerException(_m("Could not create anonymous user session."));
     }
     common_log(LOG_INFO, "AnonymousFavePlugin - created profile for anonymous user from IP: " . $ip . ', nickname = ' . $profile->nickname);
     return $profile;
 }
예제 #12
0
 function new_access_token($token, $consumer)
 {
     common_debug('new_access_token("' . $token->key . '","' . $consumer->key . '")', __FILE__);
     $rt = new Token();
     $rt->consumer_key = $consumer->key;
     $rt->tok = $token->key;
     $rt->type = 0;
     // request
     $app = Oauth_application::getByConsumerKey($consumer->key);
     if (empty($app)) {
         common_debug("empty app!");
     }
     if ($rt->find(true) && $rt->state == 1) {
         // authorized
         common_debug('request token found.', __FILE__);
         // find the associated user of the app
         $appUser = new Oauth_application_user();
         $appUser->application_id = $app->id;
         $appUser->token = $rt->tok;
         $result = $appUser->find(true);
         if (!empty($result)) {
             common_debug("Oath app user found.");
         } else {
             common_debug("Oauth app user not found. app id {$app->id} token {$rt->tok}");
             return null;
         }
         // go ahead and make the access token
         $at = new Token();
         $at->consumer_key = $consumer->key;
         $at->tok = common_good_rand(16);
         $at->secret = common_good_rand(16);
         $at->type = 1;
         // access
         $at->created = DB_DataObject_Cast::dateTime();
         if (!$at->insert()) {
             $e = $at->_lastError;
             common_debug('access token "' . $at->tok . '" not inserted: "' . $e->message . '"', __FILE__);
             return null;
         } else {
             common_debug('access token "' . $at->tok . '" inserted', __FILE__);
             // burn the old one
             $orig_rt = clone $rt;
             $rt->state = 2;
             // used
             if (!$rt->update($orig_rt)) {
                 return null;
             }
             common_debug('request token "' . $rt->tok . '" updated', __FILE__);
             // update the token from req to access for the user
             $orig = clone $appUser;
             $appUser->token = $at->tok;
             // It's at this point that we change the access type
             // to whatever the application's access is.  Request
             // tokens should always have an access type of 0, and
             // therefore be unuseable for making requests for
             // protected resources.
             $appUser->access_type = $app->access_type;
             $result = $appUser->update($orig);
             if (empty($result)) {
                 common_debug('couldn\'t update OAuth app user.');
                 return null;
             }
             // Okay, good
             return new OAuthToken($at->tok, $at->secret);
         }
     } else {
         return null;
     }
 }
예제 #13
0
 function new_request_token($consumer, $callback)
 {
     $t = new Token();
     $t->consumer_key = $consumer->key;
     $t->tok = common_good_rand(16);
     $t->secret = common_good_rand(16);
     $t->type = 0;
     // request
     $t->state = 0;
     // unauthorized
     $t->verified_callback = $callback;
     if ($callback === 'oob') {
         // six digit pin
         $t->verifier = mt_rand(0, 9999999);
     } else {
         $t->verifier = common_good_rand(8);
     }
     $t->created = DB_DataObject_Cast::dateTime();
     if (!$t->insert()) {
         return null;
     } else {
         return new OAuthToken($t->tok, $t->secret);
     }
 }
예제 #14
0
 protected function doSubscribe($mode)
 {
     $orig = clone $this;
     $this->verify_token = common_good_rand(16);
     if ($mode == 'subscribe') {
         $this->secret = common_good_rand(32);
     }
     $this->sub_state = $mode;
     $this->update($orig);
     unset($orig);
     try {
         $callback = common_local_url('pushcallback', array('feed' => $this->id));
         $headers = array('Content-Type: application/x-www-form-urlencoded');
         $post = array('hub.mode' => $mode, 'hub.callback' => $callback, 'hub.verify' => 'sync', 'hub.verify_token' => $this->verify_token, 'hub.secret' => $this->secret, 'hub.topic' => $this->uri);
         $client = new HTTPClient();
         if ($this->huburi) {
             $hub = $this->huburi;
         } else {
             if (common_config('feedsub', 'fallback_hub')) {
                 $hub = common_config('feedsub', 'fallback_hub');
                 if (common_config('feedsub', 'hub_user')) {
                     $u = common_config('feedsub', 'hub_user');
                     $p = common_config('feedsub', 'hub_pass');
                     $client->setAuth($u, $p);
                 }
             } else {
                 throw new FeedSubException('WTF?');
             }
         }
         $response = $client->post($hub, $headers, $post);
         $status = $response->getStatus();
         if ($status == 202) {
             common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
             return true;
         } else {
             if ($status == 204) {
                 common_log(LOG_INFO, __METHOD__ . ': sub req ok and verified');
                 return true;
             } else {
                 if ($status >= 200 && $status < 300) {
                     common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP {$status}: " . $response->getBody());
                     return false;
                 } else {
                     common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP {$status}: " . $response->getBody());
                     return false;
                 }
             }
         }
     } catch (Exception $e) {
         // wtf!
         common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub {$this->huburi} subscribing to {$this->uri}");
         $orig = clone $this;
         $this->verify_token = '';
         $this->sub_state = 'inactive';
         $this->update($orig);
         unset($orig);
         return false;
     }
 }
예제 #15
0
 function autoRegister($username, $nickname)
 {
     if (is_null($nickname)) {
         $nickname = $username;
     }
     $entry = $this->ldapCommon->get_user($username, $this->attributes);
     if ($entry) {
         $registration_data = array();
         foreach ($this->attributes as $sn_attribute => $ldap_attribute) {
             //ldap won't let us read a user's password,
             //and we're going to set the password to a random string later anyways,
             //so don't bother trying to read it.
             if ($sn_attribute != 'password') {
                 $registration_data[$sn_attribute] = $entry->getValue($ldap_attribute, 'single');
             }
         }
         if (isset($registration_data['email']) && !empty($registration_data['email'])) {
             $registration_data['email_confirmed'] = true;
         }
         $registration_data['nickname'] = $nickname;
         //set the database saved password to a random string.
         $registration_data['password'] = common_good_rand(16);
         return User::register($registration_data);
     } else {
         //user isn't in ldap, so we cannot register him
         return false;
     }
 }
 private function _fakeNotice($user = null, $text = null)
 {
     if (empty($user)) {
         $user = $this->author1;
     }
     if (empty($text)) {
         $text = "fake-o text-o " . common_good_rand(32);
     }
     return Notice::saveNew($user->id, $text, 'test', array('uri' => null));
 }