]> git.mxchange.org Git - friendica.git/blob - include/oauth.php
Merge pull request #3975 from tobiasd/20171127-tagcloud
[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\Config;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
12 use Friendica\Database\DBM;
13
14 define('REQUEST_TOKEN_DURATION', 300);
15 define('ACCESS_TOKEN_DURATION', 31536000);
16
17 require_once("library/OAuth1.php");
18 require_once("library/oauth2-php/lib/OAuth2.inc");
19
20 class FKOAuthDataStore extends OAuthDataStore {
21   function gen_token(){
22                 return md5(base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), uniqid())));
23   }
24
25   function lookup_consumer($consumer_key) {
26                 logger(__function__.":".$consumer_key);
27       //echo "<pre>"; var_dump($consumer_key); killme();
28
29                 $r = q("SELECT client_id, pw, redirect_uri FROM clients WHERE client_id='%s'",
30                         dbesc($consumer_key)
31                 );
32                 if (DBM::is_result($r))
33                         return new OAuthConsumer($r[0]['client_id'],$r[0]['pw'],$r[0]['redirect_uri']);
34                 return null;
35   }
36
37   function lookup_token($consumer, $token_type, $token) {
38                 logger(__function__.":".$consumer.", ". $token_type.", ".$token);
39                 $r = q("SELECT id, secret,scope, expires, uid  FROM tokens WHERE client_id='%s' AND scope='%s' AND id='%s'",
40                         dbesc($consumer->key),
41                         dbesc($token_type),
42                         dbesc($token)
43                 );
44                 if (DBM::is_result($r)){
45                         $ot=new OAuthToken($r[0]['id'],$r[0]['secret']);
46                         $ot->scope=$r[0]['scope'];
47                         $ot->expires = $r[0]['expires'];
48                         $ot->uid = $r[0]['uid'];
49                         return $ot;
50                 }
51                 return null;
52   }
53
54   function lookup_nonce($consumer, $token, $nonce, $timestamp) {
55                 //echo __file__.":".__line__."<pre>"; var_dump($consumer,$key); killme();
56                 $r = q("SELECT id, secret  FROM tokens WHERE client_id='%s' AND id='%s' AND expires=%d",
57                         dbesc($consumer->key),
58                         dbesc($nonce),
59                         intval($timestamp)
60                 );
61                 if (DBM::is_result($r))
62                         return new OAuthToken($r[0]['id'],$r[0]['secret']);
63                 return null;
64   }
65
66   function new_request_token($consumer, $callback = null) {
67                 logger(__function__.":".$consumer.", ". $callback);
68                 $key = $this->gen_token();
69                 $sec = $this->gen_token();
70
71                 if ($consumer->key){
72                         $k = $consumer->key;
73                 } else {
74                         $k = $consumer;
75                 }
76
77                 $r = q("INSERT INTO tokens (id, secret, client_id, scope, expires) VALUES ('%s','%s','%s','%s', UNIX_TIMESTAMP()+%d)",
78                                 dbesc($key),
79                                 dbesc($sec),
80                                 dbesc($k),
81                                 'request',
82                                 intval(REQUEST_TOKEN_DURATION));
83                 if (!$r) return null;
84                 return new OAuthToken($key,$sec);
85   }
86
87   function new_access_token($token, $consumer, $verifier = null) {
88     logger(__function__.":".$token.", ". $consumer.", ". $verifier);
89
90     // return a new access token attached to this consumer
91     // for the user associated with this token if the request token
92     // is authorized
93     // should also invalidate the request token
94
95     $ret=Null;
96
97     // get user for this verifier
98     $uverifier = Config::get("oauth", $verifier);
99     logger(__function__.":".$verifier.",".$uverifier);
100     if (is_null($verifier) || ($uverifier!==false)){
101
102                 $key = $this->gen_token();
103                 $sec = $this->gen_token();
104                 $r = q("INSERT INTO tokens (id, secret, client_id, scope, expires, uid) VALUES ('%s','%s','%s','%s', UNIX_TIMESTAMP()+%d, %d)",
105                                 dbesc($key),
106                                 dbesc($sec),
107                                 dbesc($consumer->key),
108                                 'access',
109                                 intval(ACCESS_TOKEN_DURATION),
110                                 intval($uverifier));
111                 if ($r)
112                         $ret = new OAuthToken($key,$sec);
113         }
114
115
116         dba::delete('tokens', array('id' => $token->key));
117
118
119         if (!is_null($ret) && $uverifier!==false){
120                 Config::delete("oauth", $verifier);
121         /*      $apps = PConfig::get($uverifier, "oauth", "apps");
122                 if ($apps===false) $apps=array();
123                 $apps[] = $consumer->key;
124                 PConfig::set($uverifier, "oauth", "apps", $apps);*/
125         }
126
127     return $ret;
128
129   }
130 }
131
132 class FKOAuth1 extends OAuthServer {
133         function __construct() {
134                 parent::__construct(new FKOAuthDataStore());
135                 $this->add_signature_method(new OAuthSignatureMethod_PLAINTEXT());
136                 $this->add_signature_method(new OAuthSignatureMethod_HMAC_SHA1());
137         }
138
139         function loginUser($uid){
140                 logger("FKOAuth1::loginUser $uid");
141                 $a = get_app();
142                 $r = q("SELECT * FROM `user` WHERE uid=%d AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
143                         intval($uid)
144                 );
145                 if (DBM::is_result($r)){
146                         $record = $r[0];
147                 } else {
148                    logger('FKOAuth1::loginUser failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
149                     header('HTTP/1.0 401 Unauthorized');
150                     die('This api requires login');
151                 }
152                 $_SESSION['uid'] = $record['uid'];
153                 $_SESSION['theme'] = $record['theme'];
154                 $_SESSION['mobile-theme'] = PConfig::get($record['uid'], 'system', 'mobile_theme');
155                 $_SESSION['authenticated'] = 1;
156                 $_SESSION['page_flags'] = $record['page-flags'];
157                 $_SESSION['my_url'] = System::baseUrl() . '/profile/' . $record['nickname'];
158                 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
159                 $_SESSION["allow_api"] = true;
160
161                 //notice( t("Welcome back ") . $record['username'] . EOL);
162                 $a->user = $record;
163
164                 if (strlen($a->user['timezone'])) {
165                         date_default_timezone_set($a->user['timezone']);
166                         $a->timezone = $a->user['timezone'];
167                 }
168
169                 $r = q("SELECT * FROM `contact` WHERE `uid` = %s AND `self` = 1 LIMIT 1",
170                         intval($_SESSION['uid']));
171                 if (DBM::is_result($r)) {
172                         $a->contact = $r[0];
173                         $a->cid = $r[0]['id'];
174                         $_SESSION['cid'] = $a->cid;
175                 }
176                 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d",
177                         dbesc(datetime_convert()),
178                         intval($_SESSION['uid'])
179                 );
180
181                 call_hooks('logged_in', $a->user);
182         }
183
184 }