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