]> git.mxchange.org Git - friendica.git/blob - src/Module/Security/Login.php
make errormessages modular and better
[friendica.git] / src / Module / Security / Login.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Module\Security;
23
24 use Friendica\App;
25 use Friendica\BaseModule;
26 use Friendica\Core\Config\Capability\IManageConfigValues;
27 use Friendica\Core\Hook;
28 use Friendica\Core\L10n;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Session\Capability\IHandleUserSessions;
31 use Friendica\DI;
32 use Friendica\Module\Register;
33 use Friendica\Module\Response;
34 use Friendica\Security\Authentication;
35 use Friendica\Util\Profiler;
36 use Psr\Log\LoggerInterface;
37
38 /**
39  * Login module
40  */
41 class Login extends BaseModule
42 {
43         /** @var Authentication */
44         private $auth;
45
46         /** @var IManageConfigValues */
47         private $config;
48
49         /** @var IHandleUserSessions */
50         private $session;
51
52         public function __construct(Authentication $auth, IManageConfigValues $config, IHandleUserSessions $session, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
53         {
54                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
55
56                 $this->auth    = $auth;
57                 $this->config  = $config;
58                 $this->session = $session;
59         }
60
61         protected function content(array $request = []): string
62         {
63                 $return_path = $request['return_path'] ?? $this->session->pop('return_path', '') ;
64
65                 if ($this->session->getLocalUserId()) {
66                         $this->baseUrl->redirect($return_path);
67                 }
68
69                 return self::form($return_path, intval($this->config->get('config', 'register_policy')) !== \Friendica\Module\Register::CLOSED);
70         }
71
72         protected function post(array $request = [])
73         {
74                 $this->session->clear();
75
76                 // OpenId Login
77                 if (
78                         empty($request['password'])
79                         && (!empty($request['openid_url'])
80                                 || !empty($request['username']))
81                 ) {
82                         $openid_url = trim(($request['openid_url'] ?? '') ?: $request['username']);
83
84                         $this->auth->withOpenId($openid_url, !empty($request['remember']));
85                 }
86
87                 if (!empty($request['auth-params']) && $request['auth-params'] === 'login') {
88                         $this->auth->withPassword(
89                                 DI::app(),
90                                 trim($request['username']),
91                                 trim($request['password']),
92                                 !empty($request['remember']),
93                                 $request['return_path'] ?? ''
94                         );
95                 }
96         }
97
98         /**
99          * Wrapper for adding a login box.
100          *
101          * @param string|null $return_path The path relative to the base the user should be sent back to after login completes.
102          * @param bool        $register    If $register == true provide a registration link.
103          *                                 This will almost always depend on the value of config.register_policy.
104          *
105          * @return string Returns the complete html for inserting into the page
106          *
107          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
108          * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
109          * @hooks 'login_hook' string $o
110          */
111         public static function form(string $return_path = null, bool $register = false): string
112         {
113                 $noid = DI::config()->get('system', 'no_openid');
114
115                 if ($noid) {
116                         DI::session()->remove('openid_identity');
117                         DI::session()->remove('openid_attributes');
118                 }
119
120                 $reg = false;
121                 if ($register && intval(DI::config()->get('config', 'register_policy')) !== Register::CLOSED) {
122                         $reg = [
123                                 'title' => DI::l10n()->t('Create a New Account'),
124                                 'desc' => DI::l10n()->t('Register'),
125                                 'url' => self::getRegisterURL()
126                         ];
127                 }
128
129                 if (DI::userSession()->getLocalUserId()) {
130                         $tpl = Renderer::getMarkupTemplate('logout.tpl');
131                 } else {
132                         DI::page()['htmlhead'] .= Renderer::replaceMacros(
133                                 Renderer::getMarkupTemplate('login_head.tpl'),
134                                 [
135                                 ]
136                         );
137
138                         $tpl = Renderer::getMarkupTemplate('login.tpl');
139                 }
140
141                 if (!empty(DI::session()->get('openid_identity'))) {
142                         $openid_title = DI::l10n()->t('Your OpenID: ');
143                         $openid_readonly = true;
144                         $identity = DI::session()->get('openid_identity');
145                         $username_desc = DI::l10n()->t('Please enter your username and password to add the OpenID to your existing account.');
146                 } else {
147                         $openid_title = DI::l10n()->t('Or login using OpenID: ');
148                         $openid_readonly = false;
149                         $identity = '';
150                         $username_desc = '';
151                 }
152
153                 $o = Renderer::replaceMacros(
154                         $tpl,
155                         [
156                                 '$dest_url'     => DI::baseUrl() . '/login',
157                                 '$logout'       => DI::l10n()->t('Logout'),
158                                 '$login'        => DI::l10n()->t('Login'),
159
160                                 '$lname'        => ['username', DI::l10n()->t('Nickname or Email: '), '', $username_desc],
161                                 '$lpassword'    => ['password', DI::l10n()->t('Password: '), '', ''],
162                                 '$lremember'    => ['remember', DI::l10n()->t('Remember me'), 0,  ''],
163
164                                 '$openid'       => !$noid,
165                                 '$lopenid'      => ['openid_url', $openid_title, $identity, '', $openid_readonly],
166
167                                 '$hiddens'      => ['return_path' => $return_path ?? DI::args()->getQueryString()],
168
169                                 '$register'     => $reg,
170
171                                 '$lostpass'     => DI::l10n()->t('Forgot your password?'),
172                                 '$lostlink'     => DI::l10n()->t('Password Reset'),
173
174                                 '$tostitle'     => DI::l10n()->t('Website Terms of Service'),
175                                 '$toslink'      => DI::l10n()->t('terms of service'),
176
177                                 '$privacytitle' => DI::l10n()->t('Website Privacy Policy'),
178                                 '$privacylink'  => DI::l10n()->t('privacy policy'),
179                         ]
180                 );
181
182                 Hook::callAll('login_hook', $o);
183
184                 return $o;
185         }
186
187         /**
188          * Get the URL to the register page and add OpenID parameters to it
189          */
190         private static function getRegisterURL(): string
191         {
192                 if (empty(DI::session()->get('openid_identity'))) {
193                         return 'register';
194                 }
195
196                 $args = [];
197                 $attr = DI::session()->get('openid_attributes', []);
198
199                 if (is_array($attr) && count($attr)) {
200                         foreach ($attr as $k => $v) {
201                                 if ($k === 'namePerson/friendly') {
202                                         $nick = trim($v);
203                                 }
204                                 if ($k === 'namePerson/first') {
205                                         $first = trim($v);
206                                 }
207                                 if ($k === 'namePerson') {
208                                         $args['username'] = trim($v);
209                                 }
210                                 if ($k === 'contact/email') {
211                                         $args['email'] = trim($v);
212                                 }
213                                 if ($k === 'media/image/aspect11') {
214                                         $photosq = bin2hex(trim($v));
215                                 }
216                                 if ($k === 'media/image/default') {
217                                         $photo = bin2hex(trim($v));
218                                 }
219                         }
220                 }
221
222                 if (!empty($nick)) {
223                         $args['nickname'] = $nick;
224                 } elseif (!empty($first)) {
225                         $args['nickname'] = $first;
226                 }
227
228                 if (!empty($photosq)) {
229                         $args['photo'] = $photosq;
230                 } elseif (!empty($photo)) {
231                         $args['photo'] = $photo;
232                 }
233
234                 $args['openid_url'] = trim(DI::session()->get('openid_identity'));
235
236                 return 'register?' . http_build_query($args);
237         }
238 }