]> git.mxchange.org Git - friendica.git/blob - include/auth.php
be4d6d8a035805b7c96b05eace1ec70f50e32c49
[friendica.git] / include / auth.php
1 <?php
2 require_once('include/security.php');
3 require_once('include/datetime.php');
4
5 function nuke_session() {
6
7         new_cookie(0); // make sure cookie is deleted on browser close, as a security measure
8         session_unset();
9 }
10
11 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
12 if(isset($_COOKIE["Friendica"])) {
13         $data = json_decode($_COOKIE["Friendica"]);
14         if (isset($data->uid)) {
15                 $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
16                 FROM `user` WHERE `uid` = %d AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
17                         intval($data->uid)
18                 );
19
20                 if ($r) {
21                         if ($data->hash != cookie_hash($r[0])) {
22                                 logger("Hash for user ".$data->uid." doesn't fit.");
23                                 nuke_session();
24                                 goaway(z_root());
25                         }
26
27                         // Renew the cookie
28                         new_cookie(604800, $r[0]);
29
30                         // Do the authentification if not done by now
31                         if(!isset($_SESSION) OR !isset($_SESSION['authenticated'])) {
32                                 authenticate_success($r[0]);
33
34                                 if (get_config('system','paranoia'))
35                                         $_SESSION['addr'] = $data->ip;
36                         }
37                 }
38         }
39 }
40
41
42 // login/logout
43
44 if((isset($_SESSION)) && (x($_SESSION,'authenticated')) && ((! (x($_POST,'auth-params'))) || ($_POST['auth-params'] !== 'login'))) {
45
46         if(((x($_POST,'auth-params')) && ($_POST['auth-params'] === 'logout')) || ($a->module === 'logout')) {
47
48                 // process logout request
49                 call_hooks("logging_out");
50                 nuke_session();
51                 info(t('Logged out.').EOL);
52                 goaway(z_root());
53         }
54
55         if(x($_SESSION,'visitor_id') && (! x($_SESSION,'uid'))) {
56                 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
57                         intval($_SESSION['visitor_id'])
58                 );
59                 if(count($r)) {
60                         $a->contact = $r[0];
61                 }
62         }
63
64         if(x($_SESSION,'uid')) {
65
66                 // already logged in user returning
67
68                 $check = get_config('system','paranoia');
69                 // extra paranoia - if the IP changed, log them out
70                 if($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
71                         logger('Session address changed. Paranoid setting in effect, blocking session. '
72                                 . $_SESSION['addr'].' != '.$_SERVER['REMOTE_ADDR']);
73                         nuke_session();
74                         goaway(z_root());
75                 }
76
77                 $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
78                 FROM `user` WHERE `uid` = %d AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
79                         intval($_SESSION['uid'])
80                 );
81
82                 if(! count($r)) {
83                         nuke_session();
84                         goaway(z_root());
85                 }
86
87                 // Make sure to refresh the last login time for the user if the user
88                 // stays logged in for a long time, e.g. with "Remember Me"
89                 $login_refresh = false;
90                 if(! x($_SESSION['last_login_date'])) {
91                         $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
92                 }
93                 if(strcmp(datetime_convert('UTC','UTC','now - 12 hours'), $_SESSION['last_login_date']) > 0) {
94
95                         $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
96                         $login_refresh = true;
97                 }
98                 authenticate_success($r[0], false, false, $login_refresh);
99         }
100 } else {
101
102         session_unset();
103
104         if((x($_POST,'password')) && strlen($_POST['password']))
105                 $encrypted = hash('whirlpool',trim($_POST['password']));
106         else {
107                 if((x($_POST,'openid_url')) && strlen($_POST['openid_url']) ||
108                    (x($_POST,'username')) && strlen($_POST['username'])) {
109
110                         $noid = get_config('system','no_openid');
111
112                         $openid_url = trim((strlen($_POST['openid_url'])?$_POST['openid_url']:$_POST['username']));
113
114                         // validate_url alters the calling parameter
115
116                         $temp_string = $openid_url;
117
118                         // if it's an email address or doesn't resolve to a URL, fail.
119
120                         if(($noid) || (strpos($temp_string,'@')) || (! validate_url($temp_string))) {
121                                 $a = get_app();
122                                 notice(t('Login failed.').EOL);
123                                 goaway(z_root());
124                                 // NOTREACHED
125                         }
126
127                         // Otherwise it's probably an openid.
128
129                         try {
130                                 require_once('library/openid.php');
131                                 $openid = new LightOpenID;
132                                 $openid->identity = $openid_url;
133                                 $_SESSION['openid'] = $openid_url;
134                                 $a = get_app();
135                                 $openid->returnUrl = $a->get_baseurl(true).'/openid';
136                                 goaway($openid->authUrl());
137                         } catch (Exception $e) {
138                                 notice(t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.').'<br /><br >'. t('The error message was:').' '.$e->getMessage());
139                         }
140                         // NOTREACHED
141                 }
142         }
143
144         if((x($_POST,'auth-params')) && $_POST['auth-params'] === 'login') {
145
146                 $record = null;
147
148                 $addon_auth = array(
149                         'username' => trim($_POST['username']),
150                         'password' => trim($_POST['password']),
151                         'authenticated' => 0,
152                         'user_record' => null
153                 );
154
155                 /**
156                  *
157                  * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
158                  * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
159                  * and later plugins should not interfere with an earlier one that succeeded.
160                  *
161                  */
162
163                 call_hooks('authenticate', $addon_auth);
164
165                 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
166                         $record = $addon_auth['user_record'];
167                 } else {
168
169                         // process normal login request
170
171                         $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
172                                 FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
173                                 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
174                                 dbesc(trim($_POST['username'])),
175                                 dbesc(trim($_POST['username'])),
176                                 dbesc($encrypted)
177                         );
178                         if(count($r))
179                                 $record = $r[0];
180                 }
181
182                 if (!$record || !count($record)) {
183                         logger('authenticate: failed login attempt: '.notags(trim($_POST['username'])).' from IP '.$_SERVER['REMOTE_ADDR']);
184                         notice(t('Login failed.').EOL);
185                         goaway(z_root());
186                 }
187
188                 // If the user specified to remember the authentication, then set a cookie
189                 // that expires after one week (the default is when the browser is closed).
190                 // The cookie will be renewed automatically.
191                 // The week ensures that sessions will expire after some inactivity.
192                 if($_POST['remember'])
193                         new_cookie(604800, $r[0]);
194                 else
195                         new_cookie(0); // 0 means delete on browser exit
196
197                 // if we haven't failed up this point, log them in.
198
199                 $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
200                 authenticate_success($record, true, true);
201         }
202 }
203
204 function cookie_hash($user) {
205         return(hash("sha256", get_config("system", "site_prvkey").
206                                 $user["uprvkey"].
207                                 $user["password"]));
208 }
209
210 function new_cookie($time, $user = array()) {
211
212         if ($time != 0)
213                 $time = $time + time();
214
215         if ($user)
216                 $value = json_encode(array("uid" => $user["uid"],
217                                         "hash" => cookie_hash($user),
218                                         "ip" => $_SERVER['REMOTE_ADDR']));
219         else
220                 $value = "";
221
222         setcookie("Friendica", $value, $time, "/", "",
223                 (get_config('system', 'ssl_policy') == SSL_POLICY_FULL), true);
224
225         return;
226 }