4 * Based on oauth2-php <http://code.google.com/p/oauth2-php/>
9 use Friendica\Core\Config;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
12 use Friendica\Database\DBM;
14 define('REQUEST_TOKEN_DURATION', 300);
15 define('ACCESS_TOKEN_DURATION', 31536000);
17 require_once("library/OAuth1.php");
18 require_once("library/oauth2-php/lib/OAuth2.inc");
20 class FKOAuthDataStore extends OAuthDataStore {
22 return md5(base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), uniqid())));
25 function lookup_consumer($consumer_key) {
26 logger(__function__.":".$consumer_key);
27 //echo "<pre>"; var_dump($consumer_key); killme();
29 $r = q("SELECT client_id, pw, redirect_uri FROM clients WHERE client_id='%s'",
32 if (DBM::is_result($r))
33 return new OAuthConsumer($r[0]['client_id'],$r[0]['pw'],$r[0]['redirect_uri']);
37 function lookup_token($consumer, $token_type, $token) {
38 logger(__function__.":".$consumer.", ". $token_type.", ".$token);
39 $r = q("SELECT id, secret,scope, expires, uid FROM tokens WHERE client_id='%s' AND scope='%s' AND id='%s'",
40 dbesc($consumer->key),
44 if (DBM::is_result($r)){
45 $ot=new OAuthToken($r[0]['id'],$r[0]['secret']);
46 $ot->scope=$r[0]['scope'];
47 $ot->expires = $r[0]['expires'];
48 $ot->uid = $r[0]['uid'];
54 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
55 //echo __file__.":".__line__."<pre>"; var_dump($consumer,$key); killme();
56 $r = q("SELECT id, secret FROM tokens WHERE client_id='%s' AND id='%s' AND expires=%d",
57 dbesc($consumer->key),
61 if (DBM::is_result($r))
62 return new OAuthToken($r[0]['id'],$r[0]['secret']);
66 function new_request_token($consumer, $callback = null) {
67 logger(__function__.":".$consumer.", ". $callback);
68 $key = $this->gen_token();
69 $sec = $this->gen_token();
77 $r = q("INSERT INTO tokens (id, secret, client_id, scope, expires) VALUES ('%s','%s','%s','%s', UNIX_TIMESTAMP()+%d)",
82 intval(REQUEST_TOKEN_DURATION));
84 return new OAuthToken($key,$sec);
87 function new_access_token($token, $consumer, $verifier = null) {
88 logger(__function__.":".$token.", ". $consumer.", ". $verifier);
90 // return a new access token attached to this consumer
91 // for the user associated with this token if the request token
93 // should also invalidate the request token
97 // get user for this verifier
98 $uverifier = Config::get("oauth", $verifier);
99 logger(__function__.":".$verifier.",".$uverifier);
100 if (is_null($verifier) || ($uverifier!==false)){
102 $key = $this->gen_token();
103 $sec = $this->gen_token();
104 $r = q("INSERT INTO tokens (id, secret, client_id, scope, expires, uid) VALUES ('%s','%s','%s','%s', UNIX_TIMESTAMP()+%d, %d)",
107 dbesc($consumer->key),
109 intval(ACCESS_TOKEN_DURATION),
112 $ret = new OAuthToken($key,$sec);
116 dba::delete('tokens', array('id' => $token->key));
119 if (!is_null($ret) && $uverifier!==false){
120 Config::delete("oauth", $verifier);
121 /* $apps = PConfig::get($uverifier, "oauth", "apps");
122 if ($apps===false) $apps=array();
123 $apps[] = $consumer->key;
124 PConfig::set($uverifier, "oauth", "apps", $apps);*/
132 class FKOAuth1 extends OAuthServer {
133 function __construct() {
134 parent::__construct(new FKOAuthDataStore());
135 $this->add_signature_method(new OAuthSignatureMethod_PLAINTEXT());
136 $this->add_signature_method(new OAuthSignatureMethod_HMAC_SHA1());
139 function loginUser($uid){
140 logger("FKOAuth1::loginUser $uid");
142 $r = q("SELECT * FROM `user` WHERE uid=%d AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
145 if (DBM::is_result($r)){
148 logger('FKOAuth1::loginUser failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
149 header('HTTP/1.0 401 Unauthorized');
150 die('This api requires login');
152 $_SESSION['uid'] = $record['uid'];
153 $_SESSION['theme'] = $record['theme'];
154 $_SESSION['mobile-theme'] = PConfig::get($record['uid'], 'system', 'mobile_theme');
155 $_SESSION['authenticated'] = 1;
156 $_SESSION['page_flags'] = $record['page-flags'];
157 $_SESSION['my_url'] = System::baseUrl() . '/profile/' . $record['nickname'];
158 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
159 $_SESSION["allow_api"] = true;
161 //notice( t("Welcome back ") . $record['username'] . EOL);
164 if (strlen($a->user['timezone'])) {
165 date_default_timezone_set($a->user['timezone']);
166 $a->timezone = $a->user['timezone'];
169 $r = q("SELECT * FROM `contact` WHERE `uid` = %s AND `self` = 1 LIMIT 1",
170 intval($_SESSION['uid']));
171 if (DBM::is_result($r)) {
173 $a->cid = $r[0]['id'];
174 $_SESSION['cid'] = $a->cid;
176 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d",
177 dbesc(datetime_convert()),
178 intval($_SESSION['uid'])
181 call_hooks('logged_in', $a->user);
186 class FKOAuth2 extends OAuth2 {
188 private function db_secret($client_secret){
189 return hash('whirlpool',$client_secret);
192 public function addClient($client_id, $client_secret, $redirect_uri) {
193 $client_secret = $this->db_secret($client_secret);
194 $r = q("INSERT INTO clients (client_id, pw, redirect_uri) VALUES ('%s', '%s', '%s')",
196 dbesc($client_secret),
203 protected function checkClientCredentials($client_id, $client_secret = NULL) {
204 $client_secret = $this->db_secret($client_secret);
206 $r = q("SELECT pw FROM clients WHERE client_id = '%s'",
209 if ($client_secret === NULL)
210 return $result !== FALSE;
212 return $result["client_secret"] == $client_secret;
215 protected function getRedirectUri($client_id) {
216 $r = q("SELECT redirect_uri FROM clients WHERE client_id = '%s'",
221 return isset($r[0]["redirect_uri"]) && $r[0]["redirect_uri"] ? $r[0]["redirect_uri"] : NULL;
224 protected function getAccessToken($oauth_token) {
225 $r = q("SELECT client_id, expires, scope FROM tokens WHERE id = '%s'",
226 dbesc($oauth_token));
228 if (DBM::is_result($r))
235 protected function setAccessToken($oauth_token, $client_id, $expires, $scope = NULL) {
236 $r = q("INSERT INTO tokens (id, client_id, expires, scope) VALUES ('%s', '%s', %d, '%s')",
245 protected function getSupportedGrantTypes() {
247 OAUTH2_GRANT_TYPE_AUTH_CODE,
252 protected function getAuthCode($code) {
253 $r = q("SELECT id, client_id, redirect_uri, expires, scope FROM auth_codes WHERE id = '%s'",
256 if (DBM::is_result($r))
261 protected function setAuthCode($code, $client_id, $redirect_uri, $expires, $scope = NULL) {
262 $r = q("INSERT INTO auth_codes
263 (id, client_id, redirect_uri, expires, scope) VALUES
264 ('%s', '%s', '%s', %d, '%s')",
267 dbesc($redirect_uri),