]> git.mxchange.org Git - friendica.git/blob - include/auth.php
diaspora - add braces
[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                                 $openid->returnUrl = App::get_baseurl(true).'/openid';
129                                 goaway($openid->authUrl());
130                         } catch (Exception $e) {
131                                 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());
132                         }
133                         // NOTREACHED
134                 }
135         }
136
137         if (x($_POST,'auth-params') && $_POST['auth-params'] === 'login') {
138
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
156                 call_hooks('authenticate', $addon_auth);
157
158                 if ($addon_auth['authenticated'] && count($addon_auth['user_record']))
159                         $record = $addon_auth['user_record'];
160                 else {
161
162                         // process normal login request
163
164                         $r = q("SELECT `user`.*, `user`.`pubkey` as `upubkey`, `user`.`prvkey` as `uprvkey`
165                                 FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
166                                 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
167                                 dbesc(trim($_POST['username'])),
168                                 dbesc(trim($_POST['username'])),
169                                 dbesc($encrypted)
170                         );
171                         if (dbm::is_result($r))
172                                 $record = $r[0];
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(z_root());
179                 }
180
181                 // If the user specified to remember the authentication, then set a cookie
182                 // that expires after one week (the default is when the browser is closed).
183                 // The cookie will be renewed automatically.
184                 // The week ensures that sessions will expire after some inactivity.
185                 if ($_POST['remember'])
186                         new_cookie(604800, $r[0]);
187                 else
188                         new_cookie(0); // 0 means delete on browser exit
189
190                 // if we haven't failed up this point, log them in.
191
192                 $_SESSION['last_login_date'] = datetime_convert('UTC','UTC');
193                 authenticate_success($record, true, true);
194         }
195 }
196
197 /**
198  * @brief Kills the "Friendica" cookie and all session data
199  */
200 function nuke_session() {
201
202         new_cookie(-3600); // make sure cookie is deleted on browser close, as a security measure
203         session_unset();
204         session_destroy();
205 }
206
207 /**
208  * @brief Calculate the hash that is needed for the "Friendica" cookie
209  *
210  * @param array $user Record from "user" table
211  *
212  * @return string Hashed data
213  */
214 function cookie_hash($user) {
215         return(hash("sha256", get_config("system", "site_prvkey").
216                                 $user["uprvkey"].
217                                 $user["password"]));
218 }
219
220 /**
221  * @brief Set the "Friendica" cookie
222  *
223  * @param int $time
224  * @param array $user Record from "user" table
225  */
226 function new_cookie($time, $user = array()) {
227
228         if ($time != 0)
229                 $time = $time + time();
230
231         if ($user)
232                 $value = json_encode(array("uid" => $user["uid"],
233                                         "hash" => cookie_hash($user),
234                                         "ip" => $_SERVER['REMOTE_ADDR']));
235         else
236                 $value = "";
237
238         setcookie("Friendica", $value, $time, "/", "",
239                 (get_config('system', 'ssl_policy') == SSL_POLICY_FULL), true);
240
241 }