Subversion Repositories oidplus

Rev

Rev 224 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
117 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
5
 * Copyright 2019 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('IN_OIDPLUS')) die();
21
 
22
class OIDplusPageRaInvite extends OIDplusPagePlugin {
23
        public function type() {
24
                return 'ra';
25
        }
26
 
222 daniel-mar 27
        public static function getPluginInformation() {
28
                $out = array();
29
                $out['name'] = 'Invite RA';
30
                $out['author'] = 'ViaThinkSoft';
31
                $out['version'] = null;
32
                $out['descriptionHTML'] = null;
33
                return $out;
34
        }
35
 
117 daniel-mar 36
        public function priority() {
37
                return 92;
38
        }
39
 
40
        public function action(&$handled) {
41
                if (isset($_POST["action"]) && ($_POST["action"] == "invite_ra")) {
42
                        $handled = true;
43
                        $email = $_POST['email'];
44
 
45
                        if (!oidplus_valid_email($email)) {
46
                                die(json_encode(array("error" => 'Invalid email address')));
47
                        }
48
 
49
                        if (RECAPTCHA_ENABLED) {
50
                                $secret=RECAPTCHA_PRIVATE;
51
                                $response=$_POST["captcha"];
52
                                $verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
53
                                $captcha_success=json_decode($verify);
54
                                if ($captcha_success->success==false) {
55
                                        die(json_encode(array("error" => 'Captcha wrong')));
56
                                }
57
                        }
58
 
59
                        $this->inviteSecurityCheck($email);
119 daniel-mar 60
                        // TODO: should we also log who has invited?
117 daniel-mar 61
                        OIDplus::logger()->log("RA($email)!", "RA '$email' has been invited");
62
 
63
                        $timestamp = time();
227 daniel-mar 64
                        $activate_url = OIDplus::getSystemUrl() . '?goto='.urlencode('oidplus:activate_ra$'.$email.'$'.$timestamp.'$'.OIDplus::authUtils()::makeAuthKey('activate_ra;'.$email.';'.$timestamp));
117 daniel-mar 65
 
66
                        $message = $this->getInvitationText($email);
67
                        $message = str_replace('{{ACTIVATE_URL}}', $activate_url, $message);
68
 
69
                        my_mail($email, OIDplus::config()->systemTitle().' - Invitation', $message, OIDplus::config()->globalCC());
70
 
71
                        echo json_encode(array("status" => 0));
72
                }
73
 
74
                if (isset($_POST["action"]) && ($_POST["action"] == "activate_ra")) {
75
                        $handled = true;
76
 
77
                        $password1 = $_POST['password1'];
78
                        $password2 = $_POST['password2'];
79
                        $email = $_POST['email'];
80
                        $auth = $_POST['auth'];
81
                        $timestamp = $_POST['timestamp'];
82
 
83
                        if (!OIDplus::authUtils()::validateAuthKey('activate_ra;'.$email.';'.$timestamp, $auth)) {
84
                                die(json_encode(array("error" => 'Invalid auth key')));
85
                        }
86
 
87
                        if ((OIDplus::config()->getValue('max_ra_invite_time') > 0) && (time()-$timestamp > OIDplus::config()->getValue('max_ra_invite_time'))) {
88
                                die(json_encode(array("error" => 'Invitation expired!')));
89
                        }
90
 
91
                        if ($password1 !== $password2) {
92
                                die(json_encode(array("error" => 'Passwords are not equal')));
93
                        }
94
 
95
                        if (strlen($password1) < OIDplus::config()->minRaPasswordLength()) {
96
                                die(json_encode(array("error" => 'Password is too short. Minimum password length: '.OIDplus::config()->minRaPasswordLength())));
97
                        }
98
 
99
                        OIDplus::logger()->log("RA($email)!", "RA '$email' has been registered due to invitation");
100
 
101
                        $ra = new OIDplusRA($email);
102
                        $ra->register_ra($password1);
103
 
104
                        echo json_encode(array("status" => 0));
105
                }
106
        }
107
 
108
        public function init($html=true) {
109
                OIDplus::config()->prepareConfigKey('max_ra_invite_time', 'Max RA invite time in seconds (0 = infinite)', '0', 0, 1);
155 daniel-mar 110
                OIDplus::config()->prepareConfigKey('ra_invitation_enabled', 'May RAs be invited?', '1', 0, 1);
117 daniel-mar 111
        }
112
 
113
        public function cfgSetValue($name, $value) {
114
                if ($name == 'max_ra_invite_time') {
115
                        if (!is_numeric($value) || ($value < 0)) {
116
                                throw new Exception("Please enter a valid value.");
117
                        }
118
                }
155 daniel-mar 119
                else if ($name == 'ra_invitation_enabled') {
120
                        if (($value != 0) && ($value != 1)) {
121
                                throw new Exception("Please enter a valid value: 0 or 1.");
122
                        }
123
                }
117 daniel-mar 124
        }
125
 
126
        public function gui($id, &$out, &$handled) {
127
                if (explode('$',$id)[0] == 'oidplus:invite_ra') {
128
                        $handled = true;
129
 
130
                        $email = explode('$',$id)[1];
131
                        $origin = explode('$',$id)[2];
213 daniel-mar 132
 
155 daniel-mar 133
                        $out['title'] = 'Invite a Registration Authority';
117 daniel-mar 134
 
155 daniel-mar 135
                        if (!OIDplus::config()->getValue('ra_invitation_enabled')) {
136
                                $out['icon'] = 'img/error_big.png';
137
                                $out['text'] = '<p>Invitations are disabled by the administrator.</p>';
138
                                return $out;
139
                        }
140
 
148 daniel-mar 141
                        $out['icon'] = 'plugins/'.basename(dirname(__DIR__)).'/'.basename(__DIR__).'/invite_ra_big.png';
117 daniel-mar 142
 
143
                        try {
144
                                $this->inviteSecurityCheck($email);
145
                                $cont = $this->getInvitationText($email);
146
 
147
                                $out['text'] .= '<p>You have chosen to invite <b>'.$email.'</b> as an Registration Authority. If you click "Send", the following email will be sent to '.$email.':</p><p><i>'.nl2br(htmlentities($cont)).'</i></p>
148
                                  <form id="inviteForm" onsubmit="return inviteFormOnSubmit();">
149
                                    <input type="hidden" id="email" value="'.htmlentities($email).'"/>
150
                                    <input type="hidden" id="origin" value="'.htmlentities($origin).'"/>'.
151
                                 (RECAPTCHA_ENABLED ? '<script> grecaptcha.render(document.getElementById("g-recaptcha"), { "sitekey" : "'.RECAPTCHA_PUBLIC.'" }); </script>'.
152
                                                   '<div id="g-recaptcha" class="g-recaptcha" data-sitekey="'.RECAPTCHA_PUBLIC.'"></div>' : '').
153
                                ' <br>
154
                                    <input type="submit" value="Send invitation">
155
                                  </form>';
156
 
157
                        } catch (Exception $e) {
158
 
159
                                $out['icon'] = 'img/error_big.png';
160
                                $out['text'] = "Error: ".$e->getMessage();
161
 
162
                        }
163
                } else if (explode('$',$id)[0] == 'oidplus:activate_ra') {
164
                        $handled = true;
165
 
155 daniel-mar 166
                        $out['title'] = 'Register as Registration Authority';
167
 
168
                        if (!OIDplus::config()->getValue('ra_invitation_enabled')) {
169
                                $out['icon'] = 'img/error_big.png';
170
                                $out['text'] = '<p>Invitations are disabled by the administrator.</p>';
171
                                return $out;
172
                        }
173
 
117 daniel-mar 174
                        $email = explode('$',$id)[1];
175
                        $timestamp = explode('$',$id)[2];
176
                        $auth = explode('$',$id)[3];
177
 
148 daniel-mar 178
                        $out['icon'] = 'plugins/'.basename(dirname(__DIR__)).'/'.basename(__DIR__).'/activate_ra_big.png';
117 daniel-mar 179
 
150 daniel-mar 180
                        $res = OIDplus::db()->query("select * from ".OIDPLUS_TABLENAME_PREFIX."ra where email = ?", array($email));
117 daniel-mar 181
                        if (OIDplus::db()->num_rows($res) > 0) {
182
                                $out['text'] = 'This RA is already registered and does not need to be invited.';
183
                        } else {
184
                                if (!OIDplus::authUtils()::validateAuthKey('activate_ra;'.$email.';'.$timestamp, $auth)) {
185
                                        $out['icon'] = 'img/error_big.png';
186
                                        $out['text'] = 'Invalid authorization. Is the URL OK?';
187
                                } else {
188
                                        // TODO: like in the FreeOID plugin, we could ask here at least for a name for the RA
189
                                        $out['text'] = '<p>E-Mail-Adress: <b>'.$email.'</b></p>
190
 
191
                                          <form id="activateRaForm" onsubmit="return activateRaFormOnSubmit();">
192
                                            <input type="hidden" id="email" value="'.htmlentities($email).'"/>
193
                                            <input type="hidden" id="timestamp" value="'.htmlentities($timestamp).'"/>
194
                                            <input type="hidden" id="auth" value="'.htmlentities($auth).'"/>
152 daniel-mar 195
                                            <div><label class="padding_label">New password:</label><input type="password" id="password1" value=""/></div>
153 daniel-mar 196
                                            <div><label class="padding_label">Repeat:</label><input type="password" id="password2" value=""/></div>
152 daniel-mar 197
                                            <br><input type="submit" value="Register">
117 daniel-mar 198
                                          </form>';
199
                                }
200
                        }
201
                }
202
        }
203
 
204
        public function tree(&$json, $ra_email=null, $nonjs=false, $req_goto='') {
205
                return false;
206
        }
207
 
208
        private function inviteSecurityCheck($email) {
150 daniel-mar 209
                $res = OIDplus::db()->query("select * from ".OIDPLUS_TABLENAME_PREFIX."ra where email = ?", array($email));
117 daniel-mar 210
                if (OIDplus::db()->num_rows($res) > 0) {
211
                        throw new Exception("This RA is already registered and does not need to be invited.");
212
                }
213
 
214
                if (!OIDplus::authUtils()::isAdminLoggedIn()) {
215
                        // Check if the RA may invite the user (i.e. the they are the parent of an OID of that person)
216
                        $ok = false;
150 daniel-mar 217
                        $res = OIDplus::db()->query("select parent from ".OIDPLUS_TABLENAME_PREFIX."objects where ra_email = ?", array($email));
117 daniel-mar 218
                        while ($row = OIDplus::db()->fetch_array($res)) {
219
                                $objParent = OIDplusObject::parse($row['parent']);
220
                                if (is_null($objParent)) throw new Exception("Type of ".$row['parent']." unknown");
221
                                if ($objParent->userHasWriteRights()) {
222
                                        $ok = true;
223
                                }
224
                        }
225
                        if (!$ok) {
226
                                throw new Exception('You may not invite this RA. Maybe you need to log in again.');
227
                        }
228
                }
229
        }
230
 
231
        private function getInvitationText($email) {
232
                $list_of_oids = array();
150 daniel-mar 233
                $res = OIDplus::db()->query("select id from ".OIDPLUS_TABLENAME_PREFIX."objects where ra_email = ?", array($email));
117 daniel-mar 234
                while ($row = OIDplus::db()->fetch_array($res)) {
235
                        $list_of_oids[] = $row['id'];
236
                }
237
 
238
                $message = file_get_contents(__DIR__ . '/invite_msg.tpl');
239
 
240
                // Resolve stuff
227 daniel-mar 241
                $message = str_replace('{{SYSTEM_URL}}', OIDplus::getSystemUrl(), $message);
117 daniel-mar 242
                $message = str_replace('{{OID_LIST}}', implode("\n", $list_of_oids), $message);
243
                $message = str_replace('{{ADMIN_EMAIL}}', OIDplus::config()->getValue('admin_email'), $message);
244
                $message = str_replace('{{PARTY}}', OIDplus::authUtils()::isAdminLoggedIn() ? 'the system administrator' : 'a superior Registration Authority', $message);
245
 
246
                // {{ACTIVATE_URL}} will be resolved in ajax.php
247
 
248
                return $message;
249
        }
250
 
251
        public function tree_search($request) {
252
                return false;
253
        }
254
}