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