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