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