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