]> git.mxchange.org Git - friendica.git/blob - include/oauth.php
make 'PHP "register_argc_argv"' easier to translate, may require fix for po2php
[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['authenticated'] = 1;
149                 $_SESSION['page_flags'] = $record['page-flags'];
150                 $_SESSION['my_url'] = $a->get_baseurl() . '/profile/' . $record['nickname'];
151                 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
152
153                 //notice( t("Welcome back ") . $record['username'] . EOL);
154                 $a->user = $record;
155
156                 if(strlen($a->user['timezone'])) {
157                         date_default_timezone_set($a->user['timezone']);
158                         $a->timezone = $a->user['timezone'];
159                 }
160
161                 $r = q("SELECT * FROM `contact` WHERE `uid` = %s AND `self` = 1 LIMIT 1",
162                         intval($_SESSION['uid']));
163                 if(count($r)) {
164                         $a->contact = $r[0];
165                         $a->cid = $r[0]['id'];
166                         $_SESSION['cid'] = $a->cid;
167                 }
168                 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d LIMIT 1",
169                         dbesc(datetime_convert()),
170                         intval($_SESSION['uid'])
171                 );
172
173                 call_hooks('logged_in', $a->user);              
174         }
175         
176 }
177 /*
178 class FKOAuth2 extends OAuth2 {
179
180         private function db_secret($client_secret){
181                 return hash('whirlpool',$client_secret);
182         }
183
184         public function addClient($client_id, $client_secret, $redirect_uri) {
185                 $client_secret = $this->db_secret($client_secret);
186                 $r = q("INSERT INTO clients (client_id, pw, redirect_uri) VALUES ('%s', '%s', '%s')",
187                         dbesc($client_id),
188                         dbesc($client_secret),
189                         dbesc($redirect_uri)
190                 );
191                   
192                 return $r;
193         }
194
195         protected function checkClientCredentials($client_id, $client_secret = NULL) {
196                 $client_secret = $this->db_secret($client_secret);
197                 
198                 $r = q("SELECT pw FROM clients WHERE client_id = '%s'",
199                         dbesc($client_id));
200
201                 if ($client_secret === NULL)
202                         return $result !== FALSE;
203
204                 return $result["client_secret"] == $client_secret;
205         }
206
207         protected function getRedirectUri($client_id) {
208                 $r = q("SELECT redirect_uri FROM clients WHERE client_id = '%s'",
209                                 dbesc($client_id));
210                 if ($r === FALSE)
211                         return FALSE;
212
213                 return isset($r[0]["redirect_uri"]) && $r[0]["redirect_uri"] ? $r[0]["redirect_uri"] : NULL;
214         }
215
216         protected function getAccessToken($oauth_token) {
217                 $r = q("SELECT client_id, expires, scope FROM tokens WHERE id = '%s'",
218                                 dbesc($oauth_token));
219         
220                 if (count($r))
221                         return $r[0];
222                 return null;
223         }
224
225
226         
227         protected function setAccessToken($oauth_token, $client_id, $expires, $scope = NULL) {
228                 $r = q("INSERT INTO tokens (id, client_id, expires, scope) VALUES ('%s', '%s', %d, '%s')",
229                                 dbesc($oauth_token),
230                                 dbesc($client_id),
231                                 intval($expires),
232                                 dbesc($scope));
233                                 
234                 return $r;
235         }
236
237         protected function getSupportedGrantTypes() {
238                 return array(
239                   OAUTH2_GRANT_TYPE_AUTH_CODE,
240                 );
241         }
242
243
244         protected function getAuthCode($code) {
245                 $r = q("SELECT id, client_id, redirect_uri, expires, scope FROM auth_codes WHERE id = '%s'",
246                                 dbesc($code));
247                 
248                 if (count($r))
249                         return $r[0];
250                 return null;
251         }
252
253         protected function setAuthCode($code, $client_id, $redirect_uri, $expires, $scope = NULL) {
254                 $r = q("INSERT INTO auth_codes 
255                                         (id, client_id, redirect_uri, expires, scope) VALUES 
256                                         ('%s', '%s', '%s', %d, '%s')",
257                                 dbesc($code),
258                                 dbesc($client_id),
259                                 dbesc($redirect_uri),
260                                 intval($expires),
261                                 dbesc($scope));
262                 return $r;        
263         }       
264         
265 }
266 */