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