]> git.mxchange.org Git - friendica.git/blob - include/auth.php
318b3d25800bd32b8404bf5b655e5f899a7db2d7
[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         if (get_config('system', 'disable_database_session')) {
9                 session_unset();
10                 return;
11         }
12
13         new_cookie(0); // make sure cookie is deleted on browser close, as a security measure
14
15         unset($_SESSION['authenticated']);
16         unset($_SESSION['uid']);
17         unset($_SESSION['visitor_id']);
18         unset($_SESSION['administrator']);
19         unset($_SESSION['cid']);
20         unset($_SESSION['theme']);
21         unset($_SESSION['mobile-theme']);
22         unset($_SESSION['page_flags']);
23         unset($_SESSION['submanage']);
24         unset($_SESSION['my_url']);
25         unset($_SESSION['my_address']);
26         unset($_SESSION['addr']);
27         unset($_SESSION['return_url']);
28
29 }
30
31
32 // login/logout
33
34
35
36
37 if((isset($_SESSION)) && (x($_SESSION,'authenticated')) && ((! (x($_POST,'auth-params'))) || ($_POST['auth-params'] !== 'login'))) {
38
39         if(((x($_POST,'auth-params')) && ($_POST['auth-params'] === 'logout')) || ($a->module === 'logout')) {
40
41                 // process logout request
42                 call_hooks("logging_out");
43                 nuke_session();
44                 info( t('Logged out.') . EOL);
45                 goaway(z_root());
46         }
47
48         if(x($_SESSION,'visitor_id') && (! x($_SESSION,'uid'))) {
49                 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
50                         intval($_SESSION['visitor_id'])
51                 );
52                 if(count($r)) {
53                         $a->contact = $r[0];
54                 }
55         }
56
57         if(x($_SESSION,'uid')) {
58
59                 // already logged in user returning
60
61                 $check = get_config('system','paranoia');
62                 // extra paranoia - if the IP changed, log them out
63                 if($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
64                         logger('Session address changed. Paranoid setting in effect, blocking session. '
65                                 . $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
66                         nuke_session();
67                         goaway(z_root());
68                 }
69
70                 $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
71                 FROM `user` WHERE `uid` = %d AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
72                         intval($_SESSION['uid'])
73                 );
74
75                 if(! count($r)) {
76                         nuke_session();
77                         goaway(z_root());
78                 }
79
80                 // Make sure to refresh the last login time for the user if the user
81                 // stays logged in for a long time, e.g. with "Remember Me"
82                 $login_refresh = false;
83                 if(! x($_SESSION['last_login_date'])) {
84                         $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
85                 }
86                 if( strcmp(datetime_convert('UTC','UTC','now - 12 hours'), $_SESSION['last_login_date']) > 0 ) {
87
88                         $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
89                         $login_refresh = true;
90                 }
91                 authenticate_success($r[0], false, false, $login_refresh);
92         }
93 }
94 else {
95
96         if(isset($_SESSION)) {
97                 nuke_session();
98         }
99
100         if((x($_POST,'password')) && strlen($_POST['password']))
101                 $encrypted = hash('whirlpool',trim($_POST['password']));
102         else {
103                 if((x($_POST,'openid_url')) && strlen($_POST['openid_url']) ||
104                    (x($_POST,'username')) && strlen($_POST['username'])) {
105
106                         $noid = get_config('system','no_openid');
107
108                         $openid_url = trim((strlen($_POST['openid_url'])?$_POST['openid_url']:$_POST['username']) );
109
110                         // validate_url alters the calling parameter
111
112                         $temp_string = $openid_url;
113
114                         // if it's an email address or doesn't resolve to a URL, fail.
115
116                         if(($noid) || (strpos($temp_string,'@')) || (! validate_url($temp_string))) {
117                                 $a = get_app();
118                                 notice( t('Login failed.') . EOL);
119                                 goaway(z_root());
120                                 // NOTREACHED
121                         }
122
123                         // Otherwise it's probably an openid.
124
125                         try {
126                         require_once('library/openid.php');
127                         $openid = new LightOpenID;
128                         $openid->identity = $openid_url;
129                         $_SESSION['openid'] = $openid_url;
130                         $a = get_app();
131                         $openid->returnUrl = $a->get_baseurl(true) . '/openid';
132                         goaway($openid->authUrl());
133                         } catch (Exception $e) {
134                             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());
135                         }
136                         // NOTREACHED
137                 }
138         }
139
140         if((x($_POST,'auth-params')) && $_POST['auth-params'] === 'login') {
141
142                 $record = null;
143
144                 $addon_auth = array(
145                         'username' => trim($_POST['username']), 
146                         'password' => trim($_POST['password']),
147                         'authenticated' => 0,
148                         'user_record' => null
149                 );
150
151                 /**
152                  *
153                  * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
154                  * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
155                  * and later plugins should not interfere with an earlier one that succeeded.
156                  *
157                  */
158
159                 call_hooks('authenticate', $addon_auth);
160
161                 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
162                         $record = $addon_auth['user_record'];
163                 }
164                 else {
165
166                         // process normal login request
167
168                         $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
169                                 FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
170                                 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
171                                 dbesc(trim($_POST['username'])),
172                                 dbesc(trim($_POST['username'])),
173                                 dbesc($encrypted)
174                         );
175                         if(count($r))
176                                 $record = $r[0];
177                 }
178
179                 if((! $record) || (! count($record))) {
180                         logger('authenticate: failed login attempt: ' . notags(trim($_POST['username'])) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
181                         notice( t('Login failed.') . EOL );
182                         goaway(z_root());
183                 }
184
185                 // If the user specified to remember the authentication, then change the cookie
186                 // to expire after one year (the default is when the browser is closed).
187                 // If the user did not specify to remember, change the cookie to expire when the
188                 // browser is closed. The reason this is necessary is because if the user
189                 // specifies to remember, then logs out and logs back in without specifying to
190                 // remember, the old "remember" cookie may remain and prevent the session from
191                 // expiring when the browser is closed.
192                 //
193                 // It seems like I should be able to test for the old cookie, but for some reason when
194                 // I read the lifetime value from session_get_cookie_params(), I always get '0'
195                 // (i.e. expire when the browser is closed), even when there's a time expiration
196                 // on the cookie
197                 if($_POST['remember']) {
198                         new_cookie(31449600); // one year
199                 }
200                 else {
201                         new_cookie(0); // 0 means delete on browser exit
202                 }
203
204                 // if we haven't failed up this point, log them in.
205
206                 $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
207                 authenticate_success($record, true, true);
208         }
209 }
210
211 function new_cookie($time) {
212         if (get_config('system', 'disable_database_session'))
213                 $old_sid = session_id();
214
215         session_set_cookie_params($time);
216
217         if (get_config('system', 'disable_database_session')) {
218                 session_regenerate_id(false);
219                 q("UPDATE session SET sid = '%s' WHERE sid = '%s'", dbesc(session_id()), dbesc($old_sid));
220         }
221 }