Beispiel #1
0
 public function onGet()
 {
     try {
         $token = $this->get->token('string', array(new Filter\Length(40, 40), new Filter\Xdigit()));
         if ($token !== false) {
             $handler = $this->getHandler('AmunService\\User\\Account');
             $account = $handler->getRecoverByToken($token);
             if ($account instanceof Account\Record) {
                 if (!empty($account->email)) {
                     if ($_SERVER['REMOTE_ADDR'] == $account->ip) {
                         $security = new Security($this->registry);
                         $pw = $security->generatePw();
                         $date = new DateTime('NOW', $this->registry['core.default_timezone']);
                         $account->setStatus(Account\Record::NORMAL);
                         $account->setPw($pw);
                         $handler->update($account);
                         // send mail
                         $values = array('account.name' => $account->name, 'account.pw' => $pw, 'host.name' => $this->base->getHost(), 'recover.link' => $this->page->getUrl(), 'recover.date' => $date->format($this->registry['core.format_date']));
                         $mail = new Mail($this->registry);
                         $mail->send('LOGIN_RECOVER_SUCCESS', $account->email, $values);
                         $this->template->assign('success', true);
                     } else {
                         throw new Exception('Recover process was requested from another IP');
                     }
                 } else {
                     throw new Exception('No public email address is set for this account');
                 }
             } else {
                 throw new Exception('Invalid token');
             }
         } else {
             throw new Exception('Token not set');
         }
     } catch (\Exception $e) {
         $this->template->assign('error', $e->getMessage());
     }
 }
Beispiel #2
0
 public function create(RecordInterface $record)
 {
     if ($record->hasFields('status', 'name', 'email', 'url', 'title', 'description')) {
         $record->consumerKey = Security::generateToken();
         $record->consumerSecret = Security::generateToken();
         $date = new DateTime('NOW', $this->registry['core.default_timezone']);
         $record->date = $date->format(DateTime::SQL);
         $this->table->insert($record->getData());
         $record->id = $this->sql->getLastInsertId();
         $this->notify(RecordAbstract::INSERT, $record);
         return $record;
     } else {
         throw new Exception('Missing field in record');
     }
 }
Beispiel #3
0
 public function onPost()
 {
     try {
         $email = $this->post->email('string', array(new Filter\Length(3, 64), new Filter\Email()));
         $captcha = $this->post->captcha('string');
         // check captcha if anonymous
         $captchaProvider = Captcha::factory($this->config['amun_captcha']);
         if (!$captchaProvider->verify($captcha)) {
             throw new Exception('Invalid captcha');
         }
         if (!$this->validate->hasError()) {
             $handler = $this->getHandler('AmunService\\User\\Account');
             $account = $handler->getOneByIdentity(sha1($this->config['amun_salt'] . $email), array('id', 'name', 'status', 'email'), Sql::FETCH_OBJECT);
             if ($account instanceof Account\Record) {
                 if (!in_array($account->status, array(Account\Record::NORMAL, Account\Record::ADMINISTRATOR))) {
                     throw new Exception('Account has an invalid status');
                 }
                 if (!empty($account->email)) {
                     $token = Security::generateToken();
                     $link = $this->page->getUrl() . '/login/resetPw?token=' . $token;
                     $date = new DateTime('NOW', $this->registry['core.default_timezone']);
                     // update status
                     $account->setStatus(Account\Record::RECOVER);
                     $account->setToken($token);
                     $handler->update($account);
                     // send mail
                     $values = array('account.name' => $account->name, 'host.name' => $this->base->getHost(), 'recover.ip' => $_SERVER['REMOTE_ADDR'], 'recover.link' => $this->page->getUrl() . '/resetPw?token=' . $token, 'recover.date' => $date->format($this->registry['core.format_date']));
                     $mail = new Mail($this->registry);
                     $mail->send('LOGIN_RECOVER', $account->email, $values);
                     $this->template->assign('success', true);
                 } else {
                     throw new Exception('No public email address is set for this account');
                 }
             } else {
                 throw new Exception('Account does not exist');
             }
         } else {
             throw new Exception($this->validate->getLastError());
         }
     } catch (\Exception $e) {
         $this->template->assign('error', $e->getMessage());
     }
 }
Beispiel #4
0
 public function create(RecordInterface $record)
 {
     if ($record->hasFields('url', 'type')) {
         $record->globalId = $this->base->getUUID('vcshook:' . uniqid());
         $record->userId = $this->user->getId();
         $record->secret = Security::generateToken(40);
         // check whether project exists
         $type = TypeAbstract::factory($record->type);
         if (!$type->hasProject($record->url)) {
             throw new Exception('Project doesnt exist');
         }
         $date = new DateTime('NOW', $this->registry['core.default_timezone']);
         $record->date = $date->format(DateTime::SQL);
         $this->table->insert($record->getData());
         $record->id = $this->sql->getLastInsertId();
         $this->notify(RecordAbstract::INSERT, $record);
         return $record;
     } else {
         throw new Exception('Missing field in record');
     }
 }
Beispiel #5
0
 public function testRequest()
 {
     // discover endpoints
     $yadis = new Yadis($this->http);
     $xrds = $yadis->discover(new Url($this->config['psx_url']));
     // get oauth request uri
     $requestUri = null;
     foreach ($xrds->getService() as $service) {
         if (in_array('http://oauth.net/core/1.0/endpoint/request', $service->getType())) {
             $requestUri = $service->getUri();
             break;
         }
     }
     $this->assertEquals(true, !empty($requestUri), 'Could not find http://oauth.net/core/1.0/endpoint/request in xrds');
     // get request token
     $response = $this->oauth->requestToken(new Url($requestUri), $this->consumerKey, $this->consumerSecret);
     $this->assertEquals(true, strlen($response->getToken()) > 4, $this->http->getResponse());
     $this->assertEquals(true, strlen($response->getTokenSecret()) > 4, $this->http->getResponse());
     $token = $response->getToken();
     $tokenSecret = $response->getTokenSecret();
     // since we can not login and approve the request we do this manually in
     // the table
     $verifier = Security::generateToken(32);
     $con = new Condition(array('token', '=', $token));
     $this->sql->update($this->registry['table.oauth_request'], array('userId' => 1, 'status' => Oauth\Record::APPROVED, 'verifier' => $verifier), $con);
     // get oauth access uri
     $accessUri = null;
     foreach ($xrds->getService() as $service) {
         if (in_array('http://oauth.net/core/1.0/endpoint/access', $service->getType())) {
             $accessUri = $service->getUri();
             break;
         }
     }
     $this->assertEquals(true, !empty($accessUri), 'Could not find http://oauth.net/core/1.0/endpoint/access in xrds');
     // get access token
     $response = $this->oauth->accessToken(new Url($accessUri), $this->consumerKey, $this->consumerSecret, $token, $tokenSecret, $verifier);
     $this->assertEquals(true, strlen($response->getToken()) > 4, $this->http->getResponse());
     $this->assertEquals(true, strlen($response->getTokenSecret()) > 4, $this->http->getResponse());
 }
Beispiel #6
0
 private function handleOauthExt()
 {
     $consumerKey = isset($this->oauth['consumer']) ? $this->oauth['consumer'] : null;
     $row = $this->getHandler('AmunService\\Openid')->getOneByConsumerKey($consumerKey);
     if (!empty($row)) {
         $token = Security::generateToken(40);
         $verifier = Security::generateToken(32);
         $date = new DateTime('NOW', $this->registry['core.default_timezone']);
         $this->getSql()->insert($this->registry['table.oauth_request'], array('apiId' => $row['id'], 'userId' => $this->user->getId(), 'status' => Oauth\Record::APPROVED, 'ip' => $_SERVER['REMOTE_ADDR'], 'nonce' => Security::generateToken(16), 'callback' => 'oob', 'token' => $token, 'tokenSecret' => '', 'verifier' => $verifier, 'timestamp' => time(), 'expire' => 'PT30M', 'date' => $date->format(DateTime::SQL)));
         // insert access
         $this->getSql()->replace($this->registry['table.oauth_access'], array('apiId' => $row['id'], 'userId' => $this->user->getId(), 'allowed' => 1, 'date' => $date->format(DateTime::SQL)));
         // return params
         $params = array();
         $params['openid.ns.oauth'] = Extension\Oauth::NS;
         $params['openid.oauth.request_token'] = $token;
         $params['openid.oauth.verifier'] = $verifier;
         return $params;
     } else {
         throw new Exception('Invalid consumer');
     }
 }
Beispiel #7
0
 protected function getResponse(Provider\Consumer $consumer, Provider\Request $request)
 {
     if ($this->nonce == $request->getNonce()) {
         throw new Exception('Nonce hasnt changed');
     }
     if ($this->verifier != $request->getVerifier()) {
         throw new Exception('Invalid verifier');
     }
     // the access token can be used six month
     $expire = 'P6M';
     // generate a new access token
     $token = Security::generateToken();
     $tokenSecret = Security::generateToken();
     $date = new DateTime('NOW', $this->registry['core.default_timezone']);
     $con = new Condition(array('id', '=', $this->requestId));
     $this->sql->update($this->registry['table.oauth_request'], array('status' => Oauth\Record::ACCESS, 'token' => $token, 'tokenSecret' => $tokenSecret, 'expire' => $expire, 'date' => $date->format(DateTime::SQL)), $con);
     $response = new Provider\Response();
     $response->setToken($token);
     $response->setTokenSecret($tokenSecret);
     return $response;
 }
Beispiel #8
0
 public function handle($identity, $password)
 {
     $result = ldap_search($this->res, '', 'uid=' . $identity);
     $entries = ldap_get_entries($this->res, $result);
     $count = isset($entries['count']) ? $entries['count'] : 0;
     if ($count == 1) {
         $acc = $entries[0];
         $mail = isset($acc['mail'][0]) ? $acc['mail'][0] : null;
         $name = isset($acc['givenname'][0]) ? $acc['givenname'][0] : null;
         $pw = isset($acc['userpassword'][0]) ? $acc['userpassword'][0] : null;
         if (empty($mail)) {
             throw new Exception('Mail not set');
         }
         if (empty($name)) {
             throw new Exception('Given name not set');
         }
         if (empty($pw)) {
             throw new Exception('User password not set');
         }
         if ($this->comparePassword($pw, $password) === true) {
             $identity = $mail;
             $con = new Condition(array('identity', '=', sha1($this->config['amun_salt'] . $identity)));
             $userId = $this->hm->getTable('AmunService\\User\\Account')->getField('id', $con);
             if (empty($userId)) {
                 // user doesnt exist so register a new user check whether
                 // registration is enabled
                 if (!$this->registry['login.registration_enabled']) {
                     throw new Exception('Registration is disabled');
                 }
                 // normalize name
                 $name = $this->normalizeName($name);
                 // create user account
                 $security = new Security($this->registry);
                 $handler = $this->hm->getHandler('AmunService\\User\\Account', $this->user);
                 $account = $handler->getRecord();
                 $account->setGroupId($this->registry['core.default_user_group']);
                 $account->setStatus(Account\Record::NORMAL);
                 $account->setIdentity($identity);
                 $account->setName($name);
                 $account->setPw($security->generatePw());
                 $account = $handler->create($account);
                 $userId = $account->id;
                 // if the id is not set the account was probably added to
                 // the approval table
                 if (!empty($userId)) {
                     $this->setUserId($userId);
                 } else {
                     throw new Exception('Could not create account');
                 }
             } else {
                 $this->setUserId($userId);
             }
             return true;
         } else {
             throw new InvalidPasswordException('Invalid password');
         }
     }
 }
Beispiel #9
0
 private function allowAccess($token, $callback, $insertAccess = true)
 {
     // insert or update access
     if ($insertAccess) {
         $now = new DateTime('NOW', $this->registry['core.default_timezone']);
         $this->getSql()->replace($this->registry['table.oauth_access'], array('apiId' => $this->apiId, 'userId' => $this->user->getId(), 'allowed' => 1, 'date' => $now->format(DateTime::SQL)));
         $accessId = $this->getSql()->getLastInsertId();
         // insert rights
         $this->insertAppRights($accessId);
     }
     // approve token
     $verifier = Security::generateToken(32);
     $con = new Condition(array('token', '=', $token));
     $this->getSql()->update($this->registry['table.oauth_request'], array('userId' => $this->user->getId(), 'status' => Oauth\Record::APPROVED, 'verifier' => $verifier), $con);
     // redirect if callback available
     if ($callback != 'oob') {
         $url = new Url($callback);
         $url->addParam('oauth_token', $token);
         $url->addParam('oauth_verifier', $verifier);
         header('Location: ' . strval($url));
         exit;
     } else {
         $this->template->assign('verifier', $verifier);
     }
 }
Beispiel #10
0
 public function callback()
 {
     // initialize openid
     $openid = new \PSX\OpenId($this->http, $this->config['psx_url'], $this->store);
     if ($openid->verify() === true) {
         $identity = $openid->getIdentifier();
         if (!empty($identity)) {
             // check whether user is already registered
             $data = $openid->getData();
             $con = new Condition(array('identity', '=', sha1($this->config['amun_salt'] . $openid->getIdentifier())));
             $userId = $this->hm->getTable('AmunService\\User\\Account')->getField('id', $con);
             if (empty($userId)) {
                 // user doesnt exist so register a new user check whether
                 // registration is enabled
                 if (!$this->registry['login.registration_enabled']) {
                     throw new Exception('Registration is disabled');
                 }
                 // get data for account
                 $acc = $this->getAccountData($data);
                 if (empty($acc)) {
                     throw new Exception('No user informations provided');
                 }
                 if (empty($acc['name'])) {
                     throw new Exception('No username provided');
                 }
                 $name = $this->normalizeName($acc['name']);
                 // create user account
                 $security = new Security($this->registry);
                 $handler = $this->hm->getHandler('AmunService\\User\\Account', $this->user);
                 $account = $handler->getRecord();
                 $account->setGroupId($this->registry['core.default_user_group']);
                 $account->setStatus(Account\Record::NORMAL);
                 $account->setIdentity($identity);
                 $account->setName($name);
                 $account->setPw($security->generatePw());
                 $account->setGender($acc['gender']);
                 $account->setTimezone($acc['timezone']);
                 $account = $handler->create($account);
                 $userId = $account->id;
                 // if the id is not set the account was probably added to
                 // the approval table
                 if (!empty($userId)) {
                     $this->setUserId($userId);
                 } else {
                     throw new Exception('Could not create account');
                 }
             } else {
                 $this->setUserId($userId);
             }
             // redirect
             header('Location: ' . $this->config['psx_url']);
             exit;
         } else {
             throw new Exception('Invalid identity');
         }
     } else {
         throw new Exception('Authentication failed');
     }
 }
Beispiel #11
0
    /**
     * Is called if an user has made a friendship request on an remote website.
     * The website makes a call to the api/user/friend/relation inorder to
     * inform us that the friendship request was made. We make an webfinger
     * request to the host and check whether the user actually exists. If the
     * user exists on the remote website we create the friend as remote user
     * in our user account table and create a relation to this user.
     *
     * @param RecordInterface $record
     * @return boolean
     */
    protected function handleRequest(RecordInterface $record)
    {
        $sql = <<<SQL
SELECT
\t`host`.`id`       AS `hostId`,
\t`host`.`name`     AS `hostName`,
\t`host`.`template` AS `hostTemplate`
FROM 
\t{$this->registry['table.core_host']} `host`
WHERE 
\t`host`.`name` = ?
SQL;
        $row = $this->sql->getRow($sql, array($record->host));
        if (!empty($row)) {
            // request profile url
            $email = $record->name . '@' . $row['hostName'];
            $profile = $this->getAcctProfile($email, $row['hostTemplate']);
            $identity = OpenId::normalizeIdentifier($profile['url']);
            // create remote user if not exists
            $con = new Condition(array('identity', '=', sha1($this->config['amun_salt'] . $identity)));
            $friendId = $this->sql->select($this->registry['table.user_account'], array('id'), $con, Sql::SELECT_FIELD);
            if (empty($friendId)) {
                $security = new Security($this->registry);
                $handler = $this->hm->getHandler('AmunService\\User\\Account', $this->user);
                $account = $handler->getRecord();
                $account->globalId = $profile['id'];
                $account->setGroupId($this->registry['core.default_user_group']);
                $account->setHostId($row['hostId']);
                $account->setStatus(Account\Record::REMOTE);
                $account->setIdentity($identity);
                $account->setName($profile['name']);
                $account->setPw($security->generatePw());
                $account = $handler->create($account);
                $friendId = $account->id;
            }
            // create relation
            $friend = $this->hm->getTable('AmunService\\User\\Friend')->getRecord();
            $friend->friendId = $friendId;
            return $this->create($friend);
        } else {
            throw new Exception('Invalid host');
        }
    }
Beispiel #12
0
 public function callback()
 {
     // get access token
     $token = $this->session->get('oauth_login_token');
     $tokenSecret = $this->session->get('oauth_login_token_secret');
     $verifier = isset($_GET['oauth_verifier']) ? $_GET['oauth_verifier'] : null;
     if (empty($token) || empty($tokenSecret)) {
         throw new Exception('Token not set');
     }
     $response = $this->oauth->accessToken(new Url(self::ACCESS_TOKEN), self::CONSUMER_KEY, self::CONSUMER_SECRET, $token, $tokenSecret, $verifier, 'HMAC-SHA1');
     $token = $response->getToken();
     $tokenSecret = $response->getTokenSecret();
     // check access token
     if (empty($token) || empty($tokenSecret)) {
         throw new Exception('Could not request access token');
     }
     // request user informations
     $url = new Url(self::VERIFY_ACCOUNT);
     $header = array('Authorization' => $this->oauth->getAuthorizationHeader($url, self::CONSUMER_KEY, self::CONSUMER_SECRET, $token, $tokenSecret, $method = 'HMAC-SHA1'));
     $request = new GetRequest($url, $header);
     $response = $this->http->request($request);
     if ($response->getCode() == 200) {
         $acc = Json::decode($response->getBody());
         if (empty($acc)) {
             throw new Exception('No user informations provided');
         }
         if (empty($acc['screen_name'])) {
             throw new Exception('No username provided');
         }
         $identity = $acc['screen_name'] . '@twitter.com';
         $con = new Condition(array('identity', '=', sha1($this->config['amun_salt'] . $identity)));
         $userId = $this->hm->getTable('AmunService\\User\\Account')->getField('id', $con);
         if (empty($userId)) {
             // user doesnt exist so register a new user check whether
             // registration is enabled
             if (!$this->registry['login.registration_enabled']) {
                 throw new Exception('Registration is disabled');
             }
             // normalize name
             $name = $this->normalizeName($acc['screen_name']);
             // create user account
             $security = new Security($this->registry);
             $handler = $this->hm->getHandler('AmunService\\User\\Account', $this->user);
             $account = $handler->getRecord();
             $account->setGroupId($this->registry['core.default_user_group']);
             $account->setStatus(Account\Record::NORMAL);
             $account->setIdentity($identity);
             $account->setName($name);
             $account->setPw($security->generatePw());
             $account->profileUrl = 'https://twitter.com/' . $acc['screen_name'];
             $account->thumbnailUrl = isset($acc['profile_image_url']) ? $acc['profile_image_url'] : null;
             $account = $handler->create($account);
             $userId = $account->id;
             // if the id is not set the account was probably added to
             // the approval table
             if (!empty($userId)) {
                 $this->setUserId($userId);
             } else {
                 throw new Exception('Could not create account');
             }
         } else {
             $this->setUserId($userId);
         }
         // redirect
         header('Location: ' . $this->config['psx_url']);
         exit;
     } else {
         throw new Exception('Authentication failed');
     }
 }
Beispiel #13
0
 public function callback()
 {
     $code = new AuthorizationCode($this->http, new Url(self::ACCESS_TOKEN));
     $code->setClientPassword(self::CLIENT_ID, self::CLIENT_SECRET, AuthorizationCode::AUTH_POST);
     $accessToken = $code->getAccessToken($this->pageUrl . '/callback/facebook');
     // request user informations
     $url = new Url(self::VERIFY_ACCOUNT);
     $header = array('Authorization' => $this->oauth->getAuthorizationHeader($accessToken));
     $request = new GetRequest($url, $header);
     $response = $this->http->request($request);
     if ($response->getCode() == 200) {
         $acc = Json::decode($response->getBody());
         if (empty($acc)) {
             throw new Exception('No user informations provided');
         }
         if (empty($acc['id'])) {
             throw new Exception('No user id provided');
         }
         $identity = $acc['id'];
         $con = new Condition(array('identity', '=', sha1($this->config['amun_salt'] . $identity)));
         $userId = $this->hm->getTable('AmunService\\User\\Account')->getField('id', $con);
         if (empty($userId)) {
             // user doesnt exist so register a new user check whether
             // registration is enabled
             if (!$this->registry['login.registration_enabled']) {
                 throw new Exception('Registration is disabled');
             }
             if (empty($acc['username'])) {
                 throw new Exception('No username provided');
             }
             $name = $this->normalizeName($acc['username']);
             // create user account
             $security = new Security($this->registry);
             $handler = $this->hm->getHandler('AmunService\\User\\Account', $this->user);
             $account = $handler->getRecord();
             $account->setGroupId($this->registry['core.default_user_group']);
             $account->setStatus(Account\Record::NORMAL);
             $account->setIdentity($identity);
             $account->setName($name);
             $account->setPw($security->generatePw());
             $account->profileUrl = isset($acc['link']) ? $acc['link'] : null;
             $account->thumbnailUrl = 'http://graph.facebook.com/' . $identity . '/picture';
             $account = $handler->create($account);
             $userId = $account->id;
             // if the id is not set the account was probably added to
             // the approval table
             if (!empty($userId)) {
                 $this->setUserId($userId);
             } else {
                 throw new Exception('Could not create account');
             }
         } else {
             $this->setUserId($userId);
         }
         // redirect
         header('Location: ' . $this->config['psx_url']);
         exit;
     } else {
         throw new Exception('Authentication failed');
     }
 }
Beispiel #14
0
 protected function insertUser()
 {
     $count = $this->sql->count($this->registry['table.user_account']);
     if ($count == 0) {
         $this->logger->info('Create users');
         $security = new Security($this->registry);
         $handler = new UserAccount\Handler($this->container);
         $validate = $this->container->get('validate');
         // get name, pw and email
         $this->name = isset($_POST['name']) ? $_POST['name'] : null;
         $this->pw = isset($_POST['pw']) ? $_POST['pw'] : null;
         $this->email = isset($_POST['email']) ? $_POST['email'] : null;
         $io = $this->container->get('io');
         if ($io instanceof IOInterface) {
             if (empty($this->name)) {
                 $this->name = $this->untilValid(function () use($io, $handler, $validate) {
                     $name = $io->ask('Username: '******'Password: '******'Email: ');
                     $validate->clearError();
                     $handler->getRecord()->setEmail($email);
                     return $email;
                 });
             }
         }
         // admin user
         $record = $handler->getRecord();
         $record->setGroupId(1);
         $record->setStatus(UserAccount\Record::ADMINISTRATOR);
         $record->setIdentity($this->email);
         $record->setName($this->name);
         $record->setPw($this->pw);
         $record->setEmail($this->email);
         $record->setTimezone('UTC');
         $handler->create($record);
         $this->logger->info('> Created administrator user');
         // anonymous user
         $record = $handler->getRecord();
         $record->setGroupId(3);
         $record->setStatus(UserAccount\Record::ANONYMOUS);
         $record->setIdentity('*****@*****.**');
         $record->setName('Anonymous');
         $record->setPw($security->generatePw());
         $record->setTimezone('UTC');
         $record = $handler->create($record);
         // set anonymous_user
         $con = new Condition(array('name', '=', 'core.anonymous_user'));
         $this->sql->update($this->registry['table.core_registry'], array('value' => $record->id), $con);
         $this->logger->info('> Created anonymous user');
     }
 }
Beispiel #15
0
 public function create(RecordInterface $record)
 {
     if ($record->hasFields('groupId', 'status', 'identity', 'name', 'pw')) {
         // check whether identity exists
         $con = new Condition();
         $con->add('identity', '=', $record->identity);
         if ($this->table->count($con) > 0) {
             throw new Exception('Identity already exists');
         }
         // check whether name and hostid exists
         $con = new Condition();
         $con->add('hostId', '=', !empty($record->hostId) ? $record->hostId : 0);
         $con->add('name', '=', $record->name);
         if ($this->table->count($con) > 0) {
             throw new Exception('Identity already exists');
         }
         // default values
         if (!isset($record->countryId)) {
             $record->setCountryId(1);
         }
         if (!isset($record->timezone)) {
             $record->setTimezone('UTC');
         }
         $date = new DateTime('NOW', $this->registry['core.default_timezone']);
         $record->token = Security::generateToken();
         $record->ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
         $record->lastSeen = $date->format(DateTime::SQL);
         $record->updated = $date->format(DateTime::SQL);
         $record->date = $date->format(DateTime::SQL);
         // set host id if we have an remote host discover the profile url
         if (empty($record->hostId)) {
             $record->hostId = 0;
             $record->profileUrl = $this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . 'profile/' . $record->name;
         } else {
             $record->status = Record::REMOTE;
             $record->profileUrl = $this->discoverProfileUrl($record->hostId, $record->name);
         }
         // set global id
         if (!isset($record->globalId)) {
             $profileUrl = new Url($record->profileUrl);
             $record->globalId = $this->base->getUUID('user:account:' . $profileUrl->getHost() . ':' . $record->name . ':' . uniqid());
         }
         // set thumbnail if email available and thumbnail not set
         if (!isset($record->thumbnailUrl)) {
             $default = $this->config['psx_url'] . '/img/avatar/no_image.png';
             if (!empty($record->email)) {
                 $record->thumbnailUrl = 'http://www.gravatar.com/avatar/' . md5(strtolower(trim($record->email))) . '?d=' . urlencode($default) . '&s=48';
             } else {
                 $record->thumbnailUrl = $default;
             }
         }
         $this->table->insert($record->getData());
         $record->id = $this->sql->getLastInsertId();
         // insert relation to self
         $this->sql->insert($this->registry['table.user_friend'], array('status' => Friend\Record::NORMAL, 'userId' => $record->id, 'friendId' => $record->id, 'date' => $date->format(DateTime::SQL)));
         $this->notify(RecordAbstract::INSERT, $record);
         return $record;
     } else {
         throw new Exception('Missing field in record');
     }
 }
Beispiel #16
0
 protected function getResponse(Provider\Consumer $consumer, Provider\Request $request)
 {
     // we check how often this ip has requested an token ... because
     // of security reasons each consumer can have max 5 request tokens
     $maxCount = 5;
     $ip = $_SERVER['REMOTE_ADDR'];
     $con = new Condition(array('ip', '=', $ip), array('status', '=', Oauth\Record::TEMPORARY));
     $count = $this->sql->count($this->registry['table.oauth_request'], $con);
     if ($count >= $maxCount) {
         $conDelete = new Condition();
         $result = $this->sql->select($this->registry['table.oauth_request'], array('id', 'expire', 'date'), $con, Sql::SELECT_ALL);
         foreach ($result as $row) {
             $now = new DateTime('NOW', $this->registry['core.default_timezone']);
             $date = new DateTime($row['date'], $this->registry['core.default_timezone']);
             $date->add(new DateInterval($row['expire']));
             if ($now > $date) {
                 $conDelete->add('id', '=', $row['id'], 'OR');
             }
         }
         if ($conDelete->hasCondition()) {
             $this->sql->delete($this->registry['table.oauth_request'], $conDelete);
         }
         throw new Exception('You can only have max. ' . $maxCount . ' active request tokens');
     }
     // get nonce
     $nonce = $request->getNonce();
     // assign callback
     $callback = $request->getCallback();
     // generate tokens
     $token = Security::generateToken();
     $tokenSecret = Security::generateToken();
     // we save the timestamp in the request but because it comes from
     // the user we doesnt use them to check the expire date
     $timestamp = $request->getTimestamp();
     // you have 30 minutes to authorize the request token and to exchange
     // them for an access token
     $expire = 'PT30M';
     $date = new DateTime('NOW', $this->registry['core.default_timezone']);
     $this->sql->insert($this->registry['table.oauth_request'], array('apiId' => $this->apiId, 'status' => Oauth\Record::TEMPORARY, 'ip' => $ip, 'nonce' => $nonce, 'callback' => $callback, 'token' => $token, 'tokenSecret' => $tokenSecret, 'timestamp' => $timestamp, 'expire' => $expire, 'date' => $date->format(DateTime::SQL)));
     $response = new Provider\Response();
     $response->setToken($token);
     $response->setTokenSecret($tokenSecret);
     return $response;
 }