add status code to System::externalRedirect
[friendica.git/.git] / src / Core / Authentication.php
1 <?php
2 /**
3  * @file /src/Core/Authentication.php
4  */
5
6 namespace Friendica\Core;
7
8 use Friendica\BaseObject;
9 use Friendica\Database\DBA;
10 use Friendica\Model\User;
11 use Friendica\Util\BaseURL;
12 use Friendica\Util\DateTimeFormat;
13
14 /**
15 * Handle Authentification, Session and Cookies
16 */
17 class Authentication extends BaseObject
18 {
19         /**
20          * @brief Calculate the hash that is needed for the "Friendica" cookie
21          *
22          * @param array $user Record from "user" table
23          *
24          * @return string Hashed data
25          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
26          */
27         public static function getCookieHashForUser($user)
28         {
29                 return(hash("sha256", Config::get("system", "site_prvkey") .
30                                 $user["prvkey"] .
31                                 $user["password"]));
32         }
33
34         /**
35          * @brief Set the "Friendica" cookie
36          *
37          * @param int   $time
38          * @param array $user Record from "user" table
39          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
40          */
41         public static  function setCookie($time, $user = [])
42         {
43                 if ($time != 0) {
44                         $time = $time + time();
45                 }
46
47                 if ($user) {
48                         $value = json_encode(["uid" => $user["uid"],
49                                 "hash" => self::getCookieHashForUser($user),
50                                 "ip" => defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0')]);
51                 } else {
52                         $value = "";
53                 }
54
55                 setcookie("Friendica", $value, $time, "/", "", (Config::get('system', 'ssl_policy') == BaseUrl::SSL_POLICY_FULL), true);
56         }
57
58         /**
59          * @brief Sets the provided user's authenticated session
60          *
61          * @todo  Should be moved to Friendica\Core\Session once it's created
62          *
63          * @param array $user_record
64          * @param bool  $login_initial
65          * @param bool  $interactive
66          * @param bool  $login_refresh
67          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
68          */
69         public static function setAuthenticatedSessionForUser($user_record, $login_initial = false, $interactive = false, $login_refresh = false)
70         {
71                 $a = self::getApp();
72
73                 $_SESSION['uid'] = $user_record['uid'];
74                 $_SESSION['theme'] = $user_record['theme'];
75                 $_SESSION['mobile-theme'] = PConfig::get($user_record['uid'], 'system', 'mobile_theme');
76                 $_SESSION['authenticated'] = 1;
77                 $_SESSION['page_flags'] = $user_record['page-flags'];
78                 $_SESSION['my_url'] = $a->getbaseUrl() . '/profile/' . $user_record['nickname'];
79                 $_SESSION['my_address'] = $user_record['nickname'] . '@' . substr($a->getbaseUrl(), strpos($a->getbaseUrl(), '://') + 3);
80                 $_SESSION['addr'] = defaults($_SERVER, 'REMOTE_ADDR', '0.0.0.0');
81
82                 $a->user = $user_record;
83
84                 if ($interactive) {
85                         if ($a->user['login_date'] <= DBA::NULL_DATETIME) {
86                                 $_SESSION['return_path'] = 'profile_photo/new';
87                                 $a->module = 'profile_photo';
88                                 info(L10n::t("Welcome ") . $a->user['username'] . EOL);
89                                 info(L10n::t('Please upload a profile photo.') . EOL);
90                         } else {
91                                 info(L10n::t("Welcome back ") . $a->user['username'] . EOL);
92                         }
93                 }
94
95                 $member_since = strtotime($a->user['register_date']);
96                 if (time() < ($member_since + ( 60 * 60 * 24 * 14))) {
97                         $_SESSION['new_member'] = true;
98                 } else {
99                         $_SESSION['new_member'] = false;
100                 }
101                 if (strlen($a->user['timezone'])) {
102                         date_default_timezone_set($a->user['timezone']);
103                         $a->timezone = $a->user['timezone'];
104                 }
105
106                 $masterUid = $user_record['uid'];
107
108                 if (!empty($_SESSION['submanage'])) {
109                         $user = DBA::selectFirst('user', ['uid'], ['uid' => $_SESSION['submanage']]);
110                         if (DBA::isResult($user)) {
111                                 $masterUid = $user['uid'];
112                         }
113                 }
114
115                 $a->identities = User::identities($masterUid);
116
117                 if ($login_initial) {
118                         Logger::log('auth_identities: ' . print_r($a->identities, true), Logger::DEBUG);
119                 }
120                 if ($login_refresh) {
121                         Logger::log('auth_identities refresh: ' . print_r($a->identities, true), Logger::DEBUG);
122                 }
123
124                 $contact = DBA::selectFirst('contact', [], ['uid' => $_SESSION['uid'], 'self' => true]);
125                 if (DBA::isResult($contact)) {
126                         $a->contact = $contact;
127                         $a->cid = $contact['id'];
128                         $_SESSION['cid'] = $a->cid;
129                 }
130
131                 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] . '"');
132
133                 if ($login_initial || $login_refresh) {
134                         DBA::update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $_SESSION['uid']]);
135
136                         // Set the login date for all identities of the user
137                         DBA::update('user', ['login_date' => DateTimeFormat::utcNow()],
138                                 ['parent-uid' => $masterUid, 'account_removed' => false]);
139                 }
140
141                 if ($login_initial) {
142                         /*
143                          * If the user specified to remember the authentication, then set a cookie
144                          * that expires after one week (the default is when the browser is closed).
145                          * The cookie will be renewed automatically.
146                          * The week ensures that sessions will expire after some inactivity.
147                          */
148                         if (!empty($_SESSION['remember'])) {
149                                 Logger::log('Injecting cookie for remembered user ' . $a->user['nickname']);
150                                 self::setCookie(604800, $user_record);
151                                 unset($_SESSION['remember']);
152                         }
153                 }
154
155                 if ($login_initial) {
156                         Hook::callAll('logged_in', $a->user);
157
158                         if (($a->module !== 'home') && isset($_SESSION['return_path'])) {
159                                 $a->internalRedirect($_SESSION['return_path']);
160                         }
161                 }
162         }
163
164         /**
165          * @brief Kills the "Friendica" cookie and all session data
166          */
167         public static function deleteSession()
168         {
169                 self::setCookie(-3600); // make sure cookie is deleted on browser close, as a security measure
170                 session_unset();
171                 session_destroy();
172         }
173 }
174