Subversion Repositories oidplus

Rev

Rev 702 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
635 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
5
 * Copyright 2019 - 2021 Daniel Marschall, ViaThinkSoft
6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
 
20
if (!defined('INSIDE_OIDPLUS')) die();
21
 
22
class OIDplusPageRaInvite extends OIDplusPagePluginRa {
23
 
24
        public function action($actionID, $params) {
25
                if ($actionID == 'invite_ra') {
26
                        $email = $params['email'];
27
 
28
                        if (!OIDplus::mailUtils()->validMailAddress($email)) {
29
                                throw new OIDplusException(_L('Invalid email address'));
30
                        }
31
 
32
                        if (OIDplus::baseConfig()->getValue('RECAPTCHA_ENABLED', false)) {
33
                                $secret=OIDplus::baseConfig()->getValue('RECAPTCHA_PRIVATE', '');
34
                                $response=$params["captcha"];
35
                                $verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
36
                                $captcha_success=json_decode($verify);
37
                                if ($captcha_success->success==false) {
38
                                        throw new OIDplusException(_L('CAPTCHA not successfully verified'));
39
                                }
40
                        }
41
 
42
                        $this->inviteSecurityCheck($email);
43
                        // TODO: should we also log who has invited?
44
                        OIDplus::logger()->log("[INFO]RA($email)!", "RA '$email' has been invited");
45
 
46
                        $timestamp = time();
47
                        $activate_url = OIDplus::webpath() . '?goto='.urlencode('oidplus:activate_ra$'.$email.'$'.$timestamp.'$'.OIDplus::authUtils()->makeAuthKey('activate_ra;'.$email.';'.$timestamp));
48
 
49
                        $message = $this->getInvitationText($email);
50
                        $message = str_replace('{{ACTIVATE_URL}}', $activate_url, $message);
51
 
52
                        OIDplus::mailUtils()->sendMail($email, OIDplus::config()->getValue('system_title').' - Invitation', $message, OIDplus::config()->getValue('global_cc'));
53
 
54
                        return array("status" => 0);
55
 
56
                } else if ($actionID == 'activate_ra') {
57
 
58
                        _CheckParamExists($params, 'password1');
59
                        _CheckParamExists($params, 'password2');
60
                        _CheckParamExists($params, 'email');
61
                        _CheckParamExists($params, 'auth');
62
                        _CheckParamExists($params, 'timestamp');
63
 
64
                        $password1 = $params['password1'];
65
                        $password2 = $params['password2'];
66
                        $email = $params['email'];
67
                        $auth = $params['auth'];
68
                        $timestamp = $params['timestamp'];
69
 
70
                        if (!OIDplus::authUtils()->validateAuthKey('activate_ra;'.$email.';'.$timestamp, $auth)) {
71
                                throw new OIDplusException(_L('Invalid auth key'));
72
                        }
73
 
74
                        if ((OIDplus::config()->getValue('max_ra_invite_time') > 0) && (time()-$timestamp > OIDplus::config()->getValue('max_ra_invite_time'))) {
75
                                throw new OIDplusException(_L('Invitation expired!'));
76
                        }
77
 
78
                        if ($password1 !== $password2) {
79
                                throw new OIDplusException(_L('Passwords do not match'));
80
                        }
81
 
82
                        if (strlen($password1) < OIDplus::config()->getValue('ra_min_password_length')) {
83
                                $minlen = OIDplus::config()->getValue('ra_min_password_length');
84
                                throw new OIDplusException(_L('Password is too short. Need at least %1 characters',$minlen));
85
                        }
86
 
87
                        OIDplus::logger()->log("[OK]RA($email)!", "RA '$email' has been registered due to invitation");
88
 
89
                        $ra = new OIDplusRA($email);
90
                        $ra->register_ra($password1);
91
 
92
                        return array("status" => 0);
93
                } else {
94
                        throw new OIDplusException(_L('Unknown action ID'));
95
                }
96
        }
97
 
98
        public function init($html=true) {
99
                OIDplus::config()->prepareConfigKey('max_ra_invite_time', 'Max RA invite time in seconds (0 = infinite)', '0', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
100
                        if (!is_numeric($value) || ($value < 0)) {
101
                                throw new OIDplusException(_L('Please enter a valid value.'));
102
                        }
103
                });
104
                OIDplus::config()->prepareConfigKey('ra_invitation_enabled', 'May RAs be invited? (0=no, 1=yes)', '1', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
105
                        if (($value != 0) && ($value != 1)) {
106
                                throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
107
                        }
108
                });
109
        }
110
 
111
        public function gui($id, &$out, &$handled) {
112
                if (explode('$',$id)[0] == 'oidplus:invite_ra') {
113
                        $handled = true;
114
 
115
                        $email = explode('$',$id)[1];
116
                        $origin = explode('$',$id)[2];
117
 
118
                        $out['title'] = _L('Invite a Registration Authority');
119
 
120
                        if (!OIDplus::config()->getValue('ra_invitation_enabled')) {
121
                                $out['icon'] = 'img/error_big.png';
122
                                $out['text'] = '<p>'._L('Invitations are disabled by the administrator.').'</p>';
123
                                return;
124
                        }
125
 
126
                        $out['icon'] = OIDplus::webpath(__DIR__).'invite_ra_big.png';
127
 
128
                        try {
129
                                $this->inviteSecurityCheck($email);
130
                                $cont = $this->getInvitationText($email);
131
 
132
                                $out['text'] .= '<p>'._L('You have chosen to invite %1 as a Registration Authority. If you click "Send", the following email will be sent to %2:','<b>'.$email.'</b>',$email).'</p><p><i>'.nl2br(htmlentities($cont)).'</i></p>
133
                                  <form id="inviteForm" action="javascript:void(0);" onsubmit="return OIDplusPageRaInvite.inviteFormOnSubmit();">
134
                                    <input type="hidden" id="email" value="'.htmlentities($email).'"/>
135
                                    <input type="hidden" id="origin" value="'.htmlentities($origin).'"/>'.
136
                                 (OIDplus::baseConfig()->getValue('RECAPTCHA_ENABLED', false) ?
137
                                 '<div id="g-recaptcha" class="g-recaptcha" data-sitekey="'.OIDplus::baseConfig()->getValue('RECAPTCHA_PUBLIC', '').'"></div>'.
138
                                 '<script> grecaptcha.render($("#g-recaptcha")[0], { "sitekey" : "'.OIDplus::baseConfig()->getValue('RECAPTCHA_PUBLIC', '').'" }); </script>' : '').
139
                                ' <br>
140
                                    <input type="submit" value="'._L('Send invitation').'">
141
                                  </form>';
142
 
143
                        } catch (Exception $e) {
144
 
145
                                $out['icon'] = 'img/error_big.png';
146
                                $out['text'] = _L('Error: %1',$e->getMessage());
147
 
148
                        }
149
                } else if (explode('$',$id)[0] == 'oidplus:activate_ra') {
150
                        $handled = true;
151
 
152
                        $email = explode('$',$id)[1];
153
                        $timestamp = explode('$',$id)[2];
154
                        $auth = explode('$',$id)[3];
155
 
156
                        $out['title'] = _L('Register as Registration Authority');
157
 
158
                        if (!OIDplus::config()->getValue('ra_invitation_enabled')) {
159
                                $out['icon'] = 'img/error_big.png';
160
                                $out['text'] = '<p>'._L('Invitations are disabled by the administrator.').'</p>';
161
                                return;
162
                        }
163
 
164
                        $out['icon'] = OIDplus::webpath(__DIR__).'activate_ra_big.png';
165
 
166
                        $res = OIDplus::db()->query("select * from ###ra where email = ?", array($email));
167
                        if ($res->num_rows() > 0) {
168
                                $out['text'] = _L('This RA is already registered and does not need to be invited.');
169
                        } else {
170
                                if (!OIDplus::authUtils()->validateAuthKey('activate_ra;'.$email.';'.$timestamp, $auth)) {
171
                                        $out['icon'] = 'img/error_big.png';
172
                                        $out['text'] = _L('Invalid authorization. Is the URL OK?');
173
                                } else {
174
                                        // TODO: like in the FreeOID plugin, we could ask here at least for a name for the RA
175
                                        $out['text'] = '<p>'._L('E-Mail-Address').': <b>'.$email.'</b></p>
176
 
177
                                          <form id="activateRaForm" action="javascript:void(0);" onsubmit="return OIDplusPageRaInvite.activateRaFormOnSubmit();">
178
                                            <input type="hidden" id="email" value="'.htmlentities($email).'"/>
179
                                            <input type="hidden" id="timestamp" value="'.htmlentities($timestamp).'"/>
180
                                            <input type="hidden" id="auth" value="'.htmlentities($auth).'"/>
181
                                            <div><label class="padding_label">'._L('New password').':</label><input type="password" id="password1" value=""/></div>
182
                                            <div><label class="padding_label">'._L('Repeat').':</label><input type="password" id="password2" value=""/></div>
183
                                            <br><input type="submit" value="'._L('Register').'">
184
                                          </form>';
185
                                }
186
                        }
187
                }
188
        }
189
 
190
        public function tree(&$json, $ra_email=null, $nonjs=false, $req_goto='') {
191
                //if (!$ra_email) return false;
192
                //if (!OIDplus::authUtils()->isRaLoggedIn($ra_email) && !OIDplus::authUtils()->isAdminLoggedIn()) return false;
193
 
194
                return false;
195
        }
196
 
197
        private function inviteSecurityCheck($email) {
198
                $res = OIDplus::db()->query("select * from ###ra where email = ?", array($email));
199
                if ($res->num_rows() > 0) {
200
                        throw new OIDplusException(_L('This RA is already registered and does not need to be invited.'));
201
                }
202
 
203
                if (!OIDplus::authUtils()->isAdminLoggedIn()) {
204
                        // Check if the RA may invite the user (i.e. the they are the parent of an OID of that person)
205
                        $ok = false;
206
                        $res = OIDplus::db()->query("select parent from ###objects where ra_email = ?", array($email));
207
                        while ($row = $res->fetch_array()) {
208
                                $objParent = OIDplusObject::parse($row['parent']);
209
                                if (is_null($objParent)) throw new OIDplusException(_L('Type of %1 unknown',$row['parent']));
210
                                if ($objParent->userHasWriteRights()) {
211
                                        $ok = true;
212
                                }
213
                        }
214
                        if (!$ok) {
215
                                throw new OIDplusException(_L('You may not invite this RA. Maybe you need to <a %1>log in</a> again.',OIDplus::gui()->link('oidplus:login')));
216
                        }
217
                }
218
        }
219
 
220
        private function getInvitationText($email) {
221
                $list_of_oids = array();
222
                $res = OIDplus::db()->query("select id from ###objects where ra_email = ?", array($email));
223
                while ($row = $res->fetch_array()) {
224
                        $list_of_oids[] = $row['id'];
225
                }
226
 
227
                $message = file_get_contents(__DIR__ . '/invite_msg.tpl');
228
 
229
                // Resolve stuff
230
                $message = str_replace('{{SYSTEM_URL}}', OIDplus::webpath(null,false), $message);
231
                $message = str_replace('{{OID_LIST}}', implode("\n", $list_of_oids), $message);
232
                $message = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $message);
233
                $message = str_replace('{{PARTY}}', OIDplus::authUtils()->isAdminLoggedIn() ? 'the system administrator' : 'a superior Registration Authority', $message);
234
 
235
                // {{ACTIVATE_URL}} will be resolved in ajax.php
236
 
237
                return $message;
238
        }
239
 
240
        public function tree_search($request) {
241
                return false;
242
        }
243
}