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