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