]> git.mxchange.org Git - friendica.git/blob - include/auth.php
Improved "remember me" functionality
[friendica.git] / include / auth.php
1 <?php
2
3
4 require_once('include/security.php');
5 require_once('include/datetime.php');
6
7 function nuke_session() {
8
9         new_cookie(0); // make sure cookie is deleted on browser close, as a security measure
10         session_unset();
11 }
12
13 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
14 if(isset($_COOKIE["Friendica"])) {
15         $data = json_decode($_COOKIE["Friendica"]);
16
17         if (isset($data->uid)) {
18                 $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
19                 FROM `user` WHERE `uid` = %d AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
20                         intval($data->uid)
21                 );
22
23                 if ($r) {
24                         // Renew the cookie
25                         new_cookie(604800, json_encode(array("uid" => $r[0]["uid"], "ip" => $_SERVER['REMOTE_ADDR'])));
26
27                         // Do the authentification if not done by now
28                         if(!isset($_SESSION) OR !isset($_SESSION['authenticated'])) {
29                                 authenticate_success($r[0], false, false, false);
30
31                         if (get_config('system','paranoia'))
32                                 $_SESSION['addr'] = $data->ip;
33                         }
34                 }
35         }
36 }
37
38 // login/logout
39
40 if((isset($_SESSION)) && (x($_SESSION,'authenticated')) && ((! (x($_POST,'auth-params'))) || ($_POST['auth-params'] !== 'login'))) {
41
42         if(((x($_POST,'auth-params')) && ($_POST['auth-params'] === 'logout')) || ($a->module === 'logout')) {
43
44                 // process logout request
45                 call_hooks("logging_out");
46                 nuke_session();
47                 new_cookie(-1);
48                 info( t('Logged out.') . EOL);
49                 goaway(z_root());
50         }
51
52         if(x($_SESSION,'visitor_id') && (! x($_SESSION,'uid'))) {
53                 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
54                         intval($_SESSION['visitor_id'])
55                 );
56                 if(count($r)) {
57                         $a->contact = $r[0];
58                 }
59         }
60
61         if(x($_SESSION,'uid')) {
62
63                 // already logged in user returning
64
65                 $check = get_config('system','paranoia');
66                 // extra paranoia - if the IP changed, log them out
67                 if($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
68                         logger('Session address changed. Paranoid setting in effect, blocking session. '
69                                 . $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
70                         nuke_session();
71                         goaway(z_root());
72                 }
73
74                 $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
75                 FROM `user` WHERE `uid` = %d AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
76                         intval($_SESSION['uid'])
77                 );
78
79                 if(! count($r)) {
80                         nuke_session();
81                         goaway(z_root());
82                 }
83
84                 // Make sure to refresh the last login time for the user if the user
85                 // stays logged in for a long time, e.g. with "Remember Me"
86                 $login_refresh = false;
87                 if(! x($_SESSION['last_login_date'])) {
88                         $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
89                 }
90                 if( strcmp(datetime_convert('UTC','UTC','now - 12 hours'), $_SESSION['last_login_date']) > 0 ) {
91
92                         $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
93                         $login_refresh = true;
94                 }
95                 authenticate_success($r[0], false, false, $login_refresh);
96         }
97 } else {
98
99         if(isset($_SESSION)) {
100                 nuke_session();
101         }
102
103         if((x($_POST,'password')) && strlen($_POST['password']))
104                 $encrypted = hash('whirlpool',trim($_POST['password']));
105         else {
106                 if((x($_POST,'openid_url')) && strlen($_POST['openid_url']) ||
107                    (x($_POST,'username')) && strlen($_POST['username'])) {
108
109                         $noid = get_config('system','no_openid');
110
111                         $openid_url = trim((strlen($_POST['openid_url'])?$_POST['openid_url']:$_POST['username']) );
112
113                         // validate_url alters the calling parameter
114
115                         $temp_string = $openid_url;
116
117                         // if it's an email address or doesn't resolve to a URL, fail.
118
119                         if(($noid) || (strpos($temp_string,'@')) || (! validate_url($temp_string))) {
120                                 $a = get_app();
121                                 notice( t('Login failed.') . EOL);
122                                 goaway(z_root());
123                                 // NOTREACHED
124                         }
125
126                         // Otherwise it's probably an openid.
127
128                         try {
129                         require_once('library/openid.php');
130                         $openid = new LightOpenID;
131                         $openid->identity = $openid_url;
132                         $_SESSION['openid'] = $openid_url;
133                         $a = get_app();
134                         $openid->returnUrl = $a->get_baseurl(true) . '/openid';
135                         goaway($openid->authUrl());
136                         } catch (Exception $e) {
137                             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());
138                         }
139                         // NOTREACHED
140                 }
141         }
142
143         if((x($_POST,'auth-params')) && $_POST['auth-params'] === 'login') {
144
145                 $record = null;
146
147                 $addon_auth = array(
148                         'username' => trim($_POST['username']),
149                         'password' => trim($_POST['password']),
150                         'authenticated' => 0,
151                         'user_record' => null
152                 );
153
154                 /**
155                  *
156                  * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
157                  * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
158                  * and later plugins should not interfere with an earlier one that succeeded.
159                  *
160                  */
161
162                 call_hooks('authenticate', $addon_auth);
163
164                 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
165                         $record = $addon_auth['user_record'];
166                 }
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, json_encode(array("uid" => $r[0]["uid"], "ip" => $_SERVER['REMOTE_ADDR'])));
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 new_cookie($time, $value = "") {
205
206         if ($time != 0)
207                 $time = $time + time();
208
209         setcookie("Friendica", $value, $time);
210
211         return;
212 }