]> git.mxchange.org Git - friendica.git/blob - include/oauth.php
Issue-#3873
[friendica.git] / include / oauth.php
1 <?php
2 /**
3  * OAuth server
4  * Based on oauth2-php <http://code.google.com/p/oauth2-php/>
5  *
6  */
7
8 use Friendica\App;
9 use Friendica\Core\Config;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
12
13 define('REQUEST_TOKEN_DURATION', 300);
14 define('ACCESS_TOKEN_DURATION', 31536000);
15
16 require_once("library/OAuth1.php");
17 require_once("library/oauth2-php/lib/OAuth2.inc");
18
19 class FKOAuthDataStore extends OAuthDataStore {
20   function gen_token(){
21                 return md5(base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), uniqid())));
22   }
23
24   function lookup_consumer($consumer_key) {
25                 logger(__function__.":".$consumer_key);
26       //echo "<pre>"; var_dump($consumer_key); killme();
27
28                 $r = q("SELECT client_id, pw, redirect_uri FROM clients WHERE client_id='%s'",
29                         dbesc($consumer_key)
30                 );
31                 if (dbm::is_result($r))
32                         return new OAuthConsumer($r[0]['client_id'],$r[0]['pw'],$r[0]['redirect_uri']);
33                 return null;
34   }
35
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),
40                         dbesc($token_type),
41                         dbesc($token)
42                 );
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'];
48                         return $ot;
49                 }
50                 return null;
51   }
52
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),
57                         dbesc($nonce),
58                         intval($timestamp)
59                 );
60                 if (dbm::is_result($r))
61                         return new OAuthToken($r[0]['id'],$r[0]['secret']);
62                 return null;
63   }
64
65   function new_request_token($consumer, $callback = null) {
66                 logger(__function__.":".$consumer.", ". $callback);
67                 $key = $this->gen_token();
68                 $sec = $this->gen_token();
69
70                 if ($consumer->key){
71                         $k = $consumer->key;
72                 } else {
73                         $k = $consumer;
74                 }
75
76                 $r = q("INSERT INTO tokens (id, secret, client_id, scope, expires) VALUES ('%s','%s','%s','%s', UNIX_TIMESTAMP()+%d)",
77                                 dbesc($key),
78                                 dbesc($sec),
79                                 dbesc($k),
80                                 'request',
81                                 intval(REQUEST_TOKEN_DURATION));
82                 if (!$r) return null;
83                 return new OAuthToken($key,$sec);
84   }
85
86   function new_access_token($token, $consumer, $verifier = null) {
87     logger(__function__.":".$token.", ". $consumer.", ". $verifier);
88
89     // return a new access token attached to this consumer
90     // for the user associated with this token if the request token
91     // is authorized
92     // should also invalidate the request token
93
94     $ret=Null;
95
96     // get user for this verifier
97     $uverifier = Config::get("oauth", $verifier);
98     logger(__function__.":".$verifier.",".$uverifier);
99     if (is_null($verifier) || ($uverifier!==false)){
100
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)",
104                                 dbesc($key),
105                                 dbesc($sec),
106                                 dbesc($consumer->key),
107                                 'access',
108                                 intval(ACCESS_TOKEN_DURATION),
109                                 intval($uverifier));
110                 if ($r)
111                         $ret = new OAuthToken($key,$sec);
112         }
113
114
115         q("DELETE FROM tokens WHERE id='%s'", $token->key);
116
117
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);*/
124         }
125
126     return $ret;
127
128   }
129 }
130
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());
136         }
137
138         function loginUser($uid){
139                 logger("FKOAuth1::loginUser $uid");
140                 $a = get_app();
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",
142                         intval($uid)
143                 );
144                 if (dbm::is_result($r)){
145                         $record = $r[0];
146                 } else {
147                    logger('FKOAuth1::loginUser failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
148                     header('HTTP/1.0 401 Unauthorized');
149                     die('This api requires login');
150                 }
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;
159
160                 //notice( t("Welcome back ") . $record['username'] . EOL);
161                 $a->user = $record;
162
163                 if (strlen($a->user['timezone'])) {
164                         date_default_timezone_set($a->user['timezone']);
165                         $a->timezone = $a->user['timezone'];
166                 }
167
168                 $r = q("SELECT * FROM `contact` WHERE `uid` = %s AND `self` = 1 LIMIT 1",
169                         intval($_SESSION['uid']));
170                 if (dbm::is_result($r)) {
171                         $a->contact = $r[0];
172                         $a->cid = $r[0]['id'];
173                         $_SESSION['cid'] = $a->cid;
174                 }
175                 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d",
176                         dbesc(datetime_convert()),
177                         intval($_SESSION['uid'])
178                 );
179
180                 call_hooks('logged_in', $a->user);
181         }
182
183 }
184 /*
185 class FKOAuth2 extends OAuth2 {
186
187         private function db_secret($client_secret){
188                 return hash('whirlpool',$client_secret);
189         }
190
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')",
194                         dbesc($client_id),
195                         dbesc($client_secret),
196                         dbesc($redirect_uri)
197                 );
198
199                 return $r;
200         }
201
202         protected function checkClientCredentials($client_id, $client_secret = NULL) {
203                 $client_secret = $this->db_secret($client_secret);
204
205                 $r = q("SELECT pw FROM clients WHERE client_id = '%s'",
206                         dbesc($client_id));
207
208                 if ($client_secret === NULL)
209                         return $result !== FALSE;
210
211                 return $result["client_secret"] == $client_secret;
212         }
213
214         protected function getRedirectUri($client_id) {
215                 $r = q("SELECT redirect_uri FROM clients WHERE client_id = '%s'",
216                                 dbesc($client_id));
217                 if ($r === FALSE)
218                         return FALSE;
219
220                 return isset($r[0]["redirect_uri"]) && $r[0]["redirect_uri"] ? $r[0]["redirect_uri"] : NULL;
221         }
222
223         protected function getAccessToken($oauth_token) {
224                 $r = q("SELECT client_id, expires, scope FROM tokens WHERE id = '%s'",
225                                 dbesc($oauth_token));
226
227                 if (dbm::is_result($r))
228                         return $r[0];
229                 return null;
230         }
231
232
233
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')",
236                                 dbesc($oauth_token),
237                                 dbesc($client_id),
238                                 intval($expires),
239                                 dbesc($scope));
240
241                 return $r;
242         }
243
244         protected function getSupportedGrantTypes() {
245                 return array(
246                   OAUTH2_GRANT_TYPE_AUTH_CODE,
247                 );
248         }
249
250
251         protected function getAuthCode($code) {
252                 $r = q("SELECT id, client_id, redirect_uri, expires, scope FROM auth_codes WHERE id = '%s'",
253                                 dbesc($code));
254
255                 if (dbm::is_result($r))
256                         return $r[0];
257                 return null;
258         }
259
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')",
264                                 dbesc($code),
265                                 dbesc($client_id),
266                                 dbesc($redirect_uri),
267                                 intval($expires),
268                                 dbesc($scope));
269                 return $r;
270         }
271
272 }
273 */