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