]> git.mxchange.org Git - friendica.git/blob - include/oauth.php
Merge remote-tracking branch 'upstream/develop' into 1706-ostatus-attach
[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
10 define('REQUEST_TOKEN_DURATION', 300);
11 define('ACCESS_TOKEN_DURATION', 31536000);
12
13 require_once("library/OAuth1.php");
14 require_once("library/oauth2-php/lib/OAuth2.inc");
15
16 class FKOAuthDataStore extends OAuthDataStore {
17   function gen_token(){
18                 return md5(base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), uniqid())));
19   }
20
21   function lookup_consumer($consumer_key) {
22                 logger(__function__.":".$consumer_key);
23       //echo "<pre>"; var_dump($consumer_key); killme();
24
25                 $r = q("SELECT client_id, pw, redirect_uri FROM clients WHERE client_id='%s'",
26                         dbesc($consumer_key)
27                 );
28                 if (dbm::is_result($r))
29                         return new OAuthConsumer($r[0]['client_id'],$r[0]['pw'],$r[0]['redirect_uri']);
30                 return null;
31   }
32
33   function lookup_token($consumer, $token_type, $token) {
34                 logger(__function__.":".$consumer.", ". $token_type.", ".$token);
35                 $r = q("SELECT id, secret,scope, expires, uid  FROM tokens WHERE client_id='%s' AND scope='%s' AND id='%s'",
36                         dbesc($consumer->key),
37                         dbesc($token_type),
38                         dbesc($token)
39                 );
40                 if (dbm::is_result($r)){
41                         $ot=new OAuthToken($r[0]['id'],$r[0]['secret']);
42                         $ot->scope=$r[0]['scope'];
43                         $ot->expires = $r[0]['expires'];
44                         $ot->uid = $r[0]['uid'];
45                         return $ot;
46                 }
47                 return null;
48   }
49
50   function lookup_nonce($consumer, $token, $nonce, $timestamp) {
51                 //echo __file__.":".__line__."<pre>"; var_dump($consumer,$key); killme();
52                 $r = q("SELECT id, secret  FROM tokens WHERE client_id='%s' AND id='%s' AND expires=%d",
53                         dbesc($consumer->key),
54                         dbesc($nonce),
55                         intval($timestamp)
56                 );
57                 if (dbm::is_result($r))
58                         return new OAuthToken($r[0]['id'],$r[0]['secret']);
59                 return null;
60   }
61
62   function new_request_token($consumer, $callback = null) {
63                 logger(__function__.":".$consumer.", ". $callback);
64                 $key = $this->gen_token();
65                 $sec = $this->gen_token();
66
67                 if ($consumer->key){
68                         $k = $consumer->key;
69                 } else {
70                         $k = $consumer;
71                 }
72
73                 $r = q("INSERT INTO tokens (id, secret, client_id, scope, expires) VALUES ('%s','%s','%s','%s', UNIX_TIMESTAMP()+%d)",
74                                 dbesc($key),
75                                 dbesc($sec),
76                                 dbesc($k),
77                                 'request',
78                                 intval(REQUEST_TOKEN_DURATION));
79                 if (!$r) return null;
80                 return new OAuthToken($key,$sec);
81   }
82
83   function new_access_token($token, $consumer, $verifier = null) {
84     logger(__function__.":".$token.", ". $consumer.", ". $verifier);
85
86     // return a new access token attached to this consumer
87     // for the user associated with this token if the request token
88     // is authorized
89     // should also invalidate the request token
90
91     $ret=Null;
92
93     // get user for this verifier
94     $uverifier = get_config("oauth", $verifier);
95     logger(__function__.":".$verifier.",".$uverifier);
96     if (is_null($verifier) || ($uverifier!==false)){
97
98                 $key = $this->gen_token();
99                 $sec = $this->gen_token();
100                 $r = q("INSERT INTO tokens (id, secret, client_id, scope, expires, uid) VALUES ('%s','%s','%s','%s', UNIX_TIMESTAMP()+%d, %d)",
101                                 dbesc($key),
102                                 dbesc($sec),
103                                 dbesc($consumer->key),
104                                 'access',
105                                 intval(ACCESS_TOKEN_DURATION),
106                                 intval($uverifier));
107                 if ($r)
108                         $ret = new OAuthToken($key,$sec);
109         }
110
111
112         q("DELETE FROM tokens WHERE id='%s'", $token->key);
113
114
115         if (!is_null($ret) && $uverifier!==false){
116                 del_config("oauth", $verifier);
117         /*      $apps = get_pconfig($uverifier, "oauth", "apps");
118                 if ($apps===false) $apps=array();
119                 $apps[] = $consumer->key;
120                 set_pconfig($uverifier, "oauth", "apps", $apps);*/
121         }
122
123     return $ret;
124
125   }
126 }
127
128 class FKOAuth1 extends OAuthServer {
129         function __construct() {
130                 parent::__construct(new FKOAuthDataStore());
131                 $this->add_signature_method(new OAuthSignatureMethod_PLAINTEXT());
132                 $this->add_signature_method(new OAuthSignatureMethod_HMAC_SHA1());
133         }
134
135         function loginUser($uid){
136                 logger("FKOAuth1::loginUser $uid");
137                 $a = get_app();
138                 $r = q("SELECT * FROM `user` WHERE uid=%d AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
139                         intval($uid)
140                 );
141                 if (dbm::is_result($r)){
142                         $record = $r[0];
143                 } else {
144                    logger('FKOAuth1::loginUser failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
145                     header('HTTP/1.0 401 Unauthorized');
146                     die('This api requires login');
147                 }
148                 $_SESSION['uid'] = $record['uid'];
149                 $_SESSION['theme'] = $record['theme'];
150                 $_SESSION['mobile-theme'] = get_pconfig($record['uid'], 'system', 'mobile_theme');
151                 $_SESSION['authenticated'] = 1;
152                 $_SESSION['page_flags'] = $record['page-flags'];
153                 $_SESSION['my_url'] = App::get_baseurl() . '/profile/' . $record['nickname'];
154                 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
155                 $_SESSION["allow_api"] = true;
156
157                 //notice( t("Welcome back ") . $record['username'] . EOL);
158                 $a->user = $record;
159
160                 if (strlen($a->user['timezone'])) {
161                         date_default_timezone_set($a->user['timezone']);
162                         $a->timezone = $a->user['timezone'];
163                 }
164
165                 $r = q("SELECT * FROM `contact` WHERE `uid` = %s AND `self` = 1 LIMIT 1",
166                         intval($_SESSION['uid']));
167                 if (dbm::is_result($r)) {
168                         $a->contact = $r[0];
169                         $a->cid = $r[0]['id'];
170                         $_SESSION['cid'] = $a->cid;
171                 }
172                 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d",
173                         dbesc(datetime_convert()),
174                         intval($_SESSION['uid'])
175                 );
176
177                 call_hooks('logged_in', $a->user);
178         }
179
180 }
181 /*
182 class FKOAuth2 extends OAuth2 {
183
184         private function db_secret($client_secret){
185                 return hash('whirlpool',$client_secret);
186         }
187
188         public function addClient($client_id, $client_secret, $redirect_uri) {
189                 $client_secret = $this->db_secret($client_secret);
190                 $r = q("INSERT INTO clients (client_id, pw, redirect_uri) VALUES ('%s', '%s', '%s')",
191                         dbesc($client_id),
192                         dbesc($client_secret),
193                         dbesc($redirect_uri)
194                 );
195
196                 return $r;
197         }
198
199         protected function checkClientCredentials($client_id, $client_secret = NULL) {
200                 $client_secret = $this->db_secret($client_secret);
201
202                 $r = q("SELECT pw FROM clients WHERE client_id = '%s'",
203                         dbesc($client_id));
204
205                 if ($client_secret === NULL)
206                         return $result !== FALSE;
207
208                 return $result["client_secret"] == $client_secret;
209         }
210
211         protected function getRedirectUri($client_id) {
212                 $r = q("SELECT redirect_uri FROM clients WHERE client_id = '%s'",
213                                 dbesc($client_id));
214                 if ($r === FALSE)
215                         return FALSE;
216
217                 return isset($r[0]["redirect_uri"]) && $r[0]["redirect_uri"] ? $r[0]["redirect_uri"] : NULL;
218         }
219
220         protected function getAccessToken($oauth_token) {
221                 $r = q("SELECT client_id, expires, scope FROM tokens WHERE id = '%s'",
222                                 dbesc($oauth_token));
223
224                 if (dbm::is_result($r))
225                         return $r[0];
226                 return null;
227         }
228
229
230
231         protected function setAccessToken($oauth_token, $client_id, $expires, $scope = NULL) {
232                 $r = q("INSERT INTO tokens (id, client_id, expires, scope) VALUES ('%s', '%s', %d, '%s')",
233                                 dbesc($oauth_token),
234                                 dbesc($client_id),
235                                 intval($expires),
236                                 dbesc($scope));
237
238                 return $r;
239         }
240
241         protected function getSupportedGrantTypes() {
242                 return array(
243                   OAUTH2_GRANT_TYPE_AUTH_CODE,
244                 );
245         }
246
247
248         protected function getAuthCode($code) {
249                 $r = q("SELECT id, client_id, redirect_uri, expires, scope FROM auth_codes WHERE id = '%s'",
250                                 dbesc($code));
251
252                 if (dbm::is_result($r))
253                         return $r[0];
254                 return null;
255         }
256
257         protected function setAuthCode($code, $client_id, $redirect_uri, $expires, $scope = NULL) {
258                 $r = q("INSERT INTO auth_codes
259                                         (id, client_id, redirect_uri, expires, scope) VALUES
260                                         ('%s', '%s', '%s', %d, '%s')",
261                                 dbesc($code),
262                                 dbesc($client_id),
263                                 dbesc($redirect_uri),
264                                 intval($expires),
265                                 dbesc($scope));
266                 return $r;
267         }
268
269 }
270 */