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;
13 define('REQUEST_TOKEN_DURATION', 300);
14 define('ACCESS_TOKEN_DURATION', 31536000);
16 require_once("library/OAuth1.php");
17 require_once("library/oauth2-php/lib/OAuth2.inc");
19 class FKOAuthDataStore extends OAuthDataStore {
21 return md5(base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), uniqid())));
24 function lookup_consumer($consumer_key) {
25 logger(__function__.":".$consumer_key);
26 //echo "<pre>"; var_dump($consumer_key); killme();
28 $r = q("SELECT client_id, pw, redirect_uri FROM clients WHERE client_id='%s'",
31 if (dbm::is_result($r))
32 return new OAuthConsumer($r[0]['client_id'],$r[0]['pw'],$r[0]['redirect_uri']);
36 function lookup_token($consumer, $token_type, $token) {
37 logger(__function__.":".$consumer.", ". $token_type.", ".$token);
38 $r = q("SELECT id, secret,scope, expires, uid FROM tokens WHERE client_id='%s' AND scope='%s' AND id='%s'",
39 dbesc($consumer->key),
43 if (dbm::is_result($r)){
44 $ot=new OAuthToken($r[0]['id'],$r[0]['secret']);
45 $ot->scope=$r[0]['scope'];
46 $ot->expires = $r[0]['expires'];
47 $ot->uid = $r[0]['uid'];
53 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
54 //echo __file__.":".__line__."<pre>"; var_dump($consumer,$key); killme();
55 $r = q("SELECT id, secret FROM tokens WHERE client_id='%s' AND id='%s' AND expires=%d",
56 dbesc($consumer->key),
60 if (dbm::is_result($r))
61 return new OAuthToken($r[0]['id'],$r[0]['secret']);
65 function new_request_token($consumer, $callback = null) {
66 logger(__function__.":".$consumer.", ". $callback);
67 $key = $this->gen_token();
68 $sec = $this->gen_token();
76 $r = q("INSERT INTO tokens (id, secret, client_id, scope, expires) VALUES ('%s','%s','%s','%s', UNIX_TIMESTAMP()+%d)",
81 intval(REQUEST_TOKEN_DURATION));
83 return new OAuthToken($key,$sec);
86 function new_access_token($token, $consumer, $verifier = null) {
87 logger(__function__.":".$token.", ". $consumer.", ". $verifier);
89 // return a new access token attached to this consumer
90 // for the user associated with this token if the request token
92 // should also invalidate the request token
96 // get user for this verifier
97 $uverifier = Config::get("oauth", $verifier);
98 logger(__function__.":".$verifier.",".$uverifier);
99 if (is_null($verifier) || ($uverifier!==false)){
101 $key = $this->gen_token();
102 $sec = $this->gen_token();
103 $r = q("INSERT INTO tokens (id, secret, client_id, scope, expires, uid) VALUES ('%s','%s','%s','%s', UNIX_TIMESTAMP()+%d, %d)",
106 dbesc($consumer->key),
108 intval(ACCESS_TOKEN_DURATION),
111 $ret = new OAuthToken($key,$sec);
115 q("DELETE FROM tokens WHERE id='%s'", $token->key);
118 if (!is_null($ret) && $uverifier!==false){
119 del_config("oauth", $verifier);
120 /* $apps = PConfig::get($uverifier, "oauth", "apps");
121 if ($apps===false) $apps=array();
122 $apps[] = $consumer->key;
123 PConfig::set($uverifier, "oauth", "apps", $apps);*/
131 class FKOAuth1 extends OAuthServer {
132 function __construct() {
133 parent::__construct(new FKOAuthDataStore());
134 $this->add_signature_method(new OAuthSignatureMethod_PLAINTEXT());
135 $this->add_signature_method(new OAuthSignatureMethod_HMAC_SHA1());
138 function loginUser($uid){
139 logger("FKOAuth1::loginUser $uid");
141 $r = q("SELECT * FROM `user` WHERE uid=%d AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
144 if (dbm::is_result($r)){
147 logger('FKOAuth1::loginUser failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
148 header('HTTP/1.0 401 Unauthorized');
149 die('This api requires login');
151 $_SESSION['uid'] = $record['uid'];
152 $_SESSION['theme'] = $record['theme'];
153 $_SESSION['mobile-theme'] = PConfig::get($record['uid'], 'system', 'mobile_theme');
154 $_SESSION['authenticated'] = 1;
155 $_SESSION['page_flags'] = $record['page-flags'];
156 $_SESSION['my_url'] = System::baseUrl() . '/profile/' . $record['nickname'];
157 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
158 $_SESSION["allow_api"] = true;
160 //notice( t("Welcome back ") . $record['username'] . EOL);
163 if (strlen($a->user['timezone'])) {
164 date_default_timezone_set($a->user['timezone']);
165 $a->timezone = $a->user['timezone'];
168 $r = q("SELECT * FROM `contact` WHERE `uid` = %s AND `self` = 1 LIMIT 1",
169 intval($_SESSION['uid']));
170 if (dbm::is_result($r)) {
172 $a->cid = $r[0]['id'];
173 $_SESSION['cid'] = $a->cid;
175 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d",
176 dbesc(datetime_convert()),
177 intval($_SESSION['uid'])
180 call_hooks('logged_in', $a->user);
185 class FKOAuth2 extends OAuth2 {
187 private function db_secret($client_secret){
188 return hash('whirlpool',$client_secret);
191 public function addClient($client_id, $client_secret, $redirect_uri) {
192 $client_secret = $this->db_secret($client_secret);
193 $r = q("INSERT INTO clients (client_id, pw, redirect_uri) VALUES ('%s', '%s', '%s')",
195 dbesc($client_secret),
202 protected function checkClientCredentials($client_id, $client_secret = NULL) {
203 $client_secret = $this->db_secret($client_secret);
205 $r = q("SELECT pw FROM clients WHERE client_id = '%s'",
208 if ($client_secret === NULL)
209 return $result !== FALSE;
211 return $result["client_secret"] == $client_secret;
214 protected function getRedirectUri($client_id) {
215 $r = q("SELECT redirect_uri FROM clients WHERE client_id = '%s'",
220 return isset($r[0]["redirect_uri"]) && $r[0]["redirect_uri"] ? $r[0]["redirect_uri"] : NULL;
223 protected function getAccessToken($oauth_token) {
224 $r = q("SELECT client_id, expires, scope FROM tokens WHERE id = '%s'",
225 dbesc($oauth_token));
227 if (dbm::is_result($r))
234 protected function setAccessToken($oauth_token, $client_id, $expires, $scope = NULL) {
235 $r = q("INSERT INTO tokens (id, client_id, expires, scope) VALUES ('%s', '%s', %d, '%s')",
244 protected function getSupportedGrantTypes() {
246 OAUTH2_GRANT_TYPE_AUTH_CODE,
251 protected function getAuthCode($code) {
252 $r = q("SELECT id, client_id, redirect_uri, expires, scope FROM auth_codes WHERE id = '%s'",
255 if (dbm::is_result($r))
260 protected function setAuthCode($code, $client_id, $redirect_uri, $expires, $scope = NULL) {
261 $r = q("INSERT INTO auth_codes
262 (id, client_id, redirect_uri, expires, scope) VALUES
263 ('%s', '%s', '%s', %d, '%s')",
266 dbesc($redirect_uri),