diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..d159169d1050894d3ea3b98e1c965c4058208fe1 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/README.txt b/README.txt deleted file mode 100644 index 657bc75ddbf9c6d5c69b75f931ed9d03c6372b5f..0000000000000000000000000000000000000000 --- a/README.txt +++ /dev/null @@ -1 +0,0 @@ -"Drupal REST & JSON API Authentication for Drupal 10" diff --git a/config/install/rest_api_authentication.settings.yml b/config/install/rest_api_authentication.settings.yml new file mode 100644 index 0000000000000000000000000000000000000000..bbacbe78c19d4aa03507f9426dd08b830d66fcdf --- /dev/null +++ b/config/install/rest_api_authentication.settings.yml @@ -0,0 +1,6 @@ +rest_api_authentication_customer_admin_email: null +rest_api_authentication_license_key: null +rest_api_authentication_customer_id: '' +rest_api_authentication_customer_admin_token: '' +rest_api_authentication_customer_api_key: '' +rest_api_authentication_status: '' \ No newline at end of file diff --git a/config/schema/rest_api_authentication.schema.yml b/config/schema/rest_api_authentication.schema.yml new file mode 100644 index 0000000000000000000000000000000000000000..6047b1afb4d05530bd9eee99d9659199406aa4f2 --- /dev/null +++ b/config/schema/rest_api_authentication.schema.yml @@ -0,0 +1,16 @@ +rest_api_authentication.settings: + type: mapping + label: Settings + mapping: + rest_api_authentication_customer_admin_email: + type: string + rest_api_authentication_license_key: + type: string + rest_api_authentication_customer_id: + type: string + rest_api_authentication_customer_admin_token: + type: string + rest_api_authentication_customer_api_key: + type: string + rest_api_authentication_status: + type: string \ No newline at end of file diff --git a/css/rest_api_authentication.basic_style_settings.css b/css/rest_api_authentication.basic_style_settings.css new file mode 100644 index 0000000000000000000000000000000000000000..54eee55416eadf655fb7461ed66df25b04370eaa --- /dev/null +++ b/css/rest_api_authentication.basic_style_settings.css @@ -0,0 +1,17 @@ +.shift-right{ + float: right; +} +.mo_rest_api_highlight_background_note_1{ + background-color: #e0e0e0; + border-radius: 4px; + padding: 0.55em; + width: 97%; +} +.mo_rest_api_authn_background{ + background-color: #f3f4f9 !important; + padding: 0.5%; +} + +#module_background{ + background-color: black; +} diff --git a/css/rest_api_authentication.style_settings.css b/css/rest_api_authentication.style_settings.css new file mode 100644 index 0000000000000000000000000000000000000000..fdb4bb7d2725f975e37aeaa26e348d3373d8287c --- /dev/null +++ b/css/rest_api_authentication.style_settings.css @@ -0,0 +1,107 @@ + +#pricing-table { + padding-top: 30px; +} +#pricing-table li{ + height: 40px; + color: black; + text-align: center; + overflow: hidden; +} + +.class_inline_1{ + width: 49%; + display: inline-block; + padding-top: 1%; +} + +#pricing-table .pricing { + margin: 0; + padding: 0; + font-family: 'Robot', sans-serif; +} +#pricing-table .pricing .pricing-table { + padding-bottom: 15px; +} +#pricing-table .pricing .pricing-table .pricing-header { + position: relative; + background: #34495e; + padding: 6px 18px; + text-align: center; + border-top-right-radius: 4px; + border-top-left-radius: 4px; +} +#pricing-table .pricing .pricing-table .pricing-header .pricing-title { + color: #ffffff; + text-transform: uppercase; + letter-spacing: 2px; + font-size: 18px; + text-align: center; + font-weight: 500; +} +#pricing-table .pricing .pricing-table .pricing-header .pricing-rate { + font-size: 60px; + font-weight: 600; + color: #ffffff; + position: relative; + text-align: center; +} +#pricing-table .pricing .pricing-table .pricing-header .pricing-rate sup { + font-size: 24px; + position: relative; + top: -30px; + color: #bdc3c7; +} +#pricing-table .pricing .pricing-table .pricing-header .pricing-rate span { + font-size: 13px; + color: #bdc3c7; + text-transform: uppercase; +} +#pricing-table .pricing .pricing-list { + padding: 20px 0 40px 0; + background: #c4baba1c; + border: 1px solid #e3e3e3; +} +#pricing-table .pricing .pricing-list ul { + padding: 0px; + display: table; + margin: 0px auto; + width: 100%; + text-align: center; +} +#pricing-table .pricing .pricing-list ul li { + list-style: none; + border-bottom: 1px solid #EAECEB; + color: black; + font-size: 15px; + line-height: 42px; +} +#pricing-table .pricing .pricing-list ul li:last-child { + border: none; +} +#pricing-table .pricing .pricing-list ul li i { + margin-right: 12px; + color: #bdc3c7; +} +#pricing-table .pricing .pricing-list ul li span { + color: #34495e; +} +.pricing-title>span{ + font-size: 12px; + letter-spacing: 1px; +} +p.pricing-title{ + height: 70px; +} +p.pricing-rate{ + margin-bottom: 50px; +} + +.pricing-list li:nth-of-type(2n+1) { + background-color: rgba(23, 61, 80, 0.06); +} +.btn-disabled, .btn-disabled[disabled] { + opacity: .4; + cursor: default !important; + pointer-events: none; +} diff --git a/rest_api_authentication.info.yml b/rest_api_authentication.info.yml new file mode 100644 index 0000000000000000000000000000000000000000..12b3bf866a5fd00439e0661dcb852ff39b5e8a63 --- /dev/null +++ b/rest_api_authentication.info.yml @@ -0,0 +1,5 @@ +name: 'REST & JSON API Authentication' +type: module +core_version_requirement: ^9.3 || ^10 +description: 'Drupal API Authentication module secures unauthorized access to your Drupal site APIs using different API authentication methods.' +configure: rest_api_authentication.auth_settings \ No newline at end of file diff --git a/rest_api_authentication.info.yml.bak b/rest_api_authentication.info.yml.bak new file mode 100644 index 0000000000000000000000000000000000000000..212679b4d36d801fd7e7488b865d26ea5cd8ef4c --- /dev/null +++ b/rest_api_authentication.info.yml.bak @@ -0,0 +1,6 @@ +name: 'REST & JSON API Authentication' +type: module +core: 8.x +core_version_requirement: ^9.3 || ^10 +description: 'Drupal API Authentication module secures unauthorized access to your Drupal site APIs using different API authentication methods.' +configure: rest_api_authentication.auth_settings \ No newline at end of file diff --git a/rest_api_authentication.install b/rest_api_authentication.install new file mode 100644 index 0000000000000000000000000000000000000000..e7f78605dc91c9c3c596bff349b38c254a9a1ca4 --- /dev/null +++ b/rest_api_authentication.install @@ -0,0 +1,85 @@ + +<?php +/** + * @file + * Installation file for miniOrange REST API Module. + */ +use Drupal\rest_api_authentication\MiniorangeAPIAuthfeedback; +use Drupal\rest_api_authentication\Utilities; + +function rest_api_authentication_uninstall(){ + + $config = \Drupal::config('rest_api_authentication.settings'); + if(!( $config->get('miniorange_rest_api_authentication_uninstall_status') == 0)){ + $config->set('miniorange_rest_api_authentication_uninstall_status',0)->save(); + } + if ($config->get('miniorange_rest_api_authentication_uninstall_status') === 0) + { + $drupal_is_cli = Utilities::drupal_is_cli(); + if( !$drupal_is_cli ) + { + MiniorangeAPIAuthfeedback::rest_api_authentication_feedback_form(); + } + } +} + + +function rest_api_authentication_install(){ + + $config = \Drupal::configFactory()->getEditable('rest_api_authentication.settings'); + + $config->set('miniorange_rest_api_license_page_visited', "False"); + $config->set('miniorange_basic_authentication_tried', "Did not Try"); + $config->set('miniorange_api_key_authentication_tried', "Did not Try"); + $config->set('miniorange_rest_api_authentication_uninstall_status',0); + $config->set('miniorange_rest_api_installation_time_ref', time()); + $config->save(); +} + + + /** + * Implementing hook_schema + **/ + +function rest_api_authentication_schema() { + $schema['rest_api_authentication_token'] = array( + 'description' => t('User Tokens'), + 'fields' => array( + 'id' => array( + 'type' => 'serial', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'description' => t('S.No.: '), + ), + 'user_id_val' => array( + 'type' => 'int', + 'unsigned' => TRUE, + 'description' => t('The UserIn of the user.'), + ), + 'access_token' => array( + 'description' => 'The access token.', + 'type' => 'varchar', + 'length' => 256, + ), + 'access_token_request_time' => array( + 'description' => 'The access token expiry time.', + 'type' => 'varchar', + 'length' => 256, + 'not null' => FALSE, + ), + 'id_token' => array( + 'description' => 'The id token.', + 'type' => 'varchar', + 'length' => 2048, + ), + 'id_token_request_time' => array( + 'description' => 'The id token expiry time.', + 'type' => 'varchar', + 'length' => 256, + 'not null' => FALSE, + ), + ), + 'primary key' => array('id'), + ); + return $schema; +} diff --git a/rest_api_authentication.libraries.yml b/rest_api_authentication.libraries.yml new file mode 100644 index 0000000000000000000000000000000000000000..a37d1fc8076fc91e7bd6d72547824a34c5e771f1 --- /dev/null +++ b/rest_api_authentication.libraries.yml @@ -0,0 +1,11 @@ +rest_api_authentication.style_settings: + version: VERSION + css: + layout: + css/rest_api_authentication.style_settings.css: {} + +rest_api_authentication.basic_style_settings: + version: VERSION + css: + layout: + css/rest_api_authentication.basic_style_settings.css: {} diff --git a/rest_api_authentication.links.menu.yml b/rest_api_authentication.links.menu.yml new file mode 100644 index 0000000000000000000000000000000000000000..26711923249abc223d88991610ea84865aab48e8 --- /dev/null +++ b/rest_api_authentication.links.menu.yml @@ -0,0 +1,6 @@ + +rest_api_authentication.auth_settings: + route_name: rest_api_authentication.auth_settings + title: 'miniOrange API Authentication Configuration' + description: 'Setup configurations for the miniOrange API Authentication module' + parent: user.admin_index diff --git a/rest_api_authentication.links.task.yml b/rest_api_authentication.links.task.yml new file mode 100644 index 0000000000000000000000000000000000000000..b46f78edd7f5e0f4c729067c913a896b2d7a9260 --- /dev/null +++ b/rest_api_authentication.links.task.yml @@ -0,0 +1,5 @@ +rest_api_authentication.auth_settings: + route_name: rest_api_authentication.auth_settings + title: 'Setup API Authentication' + weight: 10 + base_route: rest_api_authentication.auth_settings diff --git a/rest_api_authentication.module b/rest_api_authentication.module new file mode 100644 index 0000000000000000000000000000000000000000..682588c0502600d84895dcf4bd13afcae2933ca1 --- /dev/null +++ b/rest_api_authentication.module @@ -0,0 +1,54 @@ +<?php +use Drupal\Core\Form\FormStateInterface; +use Drupal\Core\Routing\RouteMatchInterface; +use Drupal\rest_api_authentication\MiniorangeApiAuthConstants; +use Drupal\Core\Url; +/** + * @file + * Module file for miniOrange REST API Module. + */ + + +/** + * Implements hook_help(). + */ +function rest_api_authentication_help($route_name, RouteMatchInterface $route_match) +{ + switch ($route_name) { + case 'help.page.rest_api_authentication': + $url = Url::fromRoute('user.admin_index')->toString(); + $moduleLink = $url . '/rest_api_authentication/auth_settings'; + + $moduleLandingPage = MiniorangeApiAuthConstants::SITE_URL.'/drupal-rest-api-authentication'; + $setup_guides = MiniorangeApiAuthConstants::SITE_URL.'/drupal-api-authentication'; + + $output = ''; + $output .= '<b>' . t('ABOUT <a target="_blank" href="' . $moduleLandingPage . '">[Know more]</a>') . '</b>'; + $output .= '<br>' . t('Drupal API Authentication module allows you to authenticate any Drupal site API calls. The module is compatible with both RESTful Web Services and JSON API module. If you have any other custom APIs as well, this module can authenticate them as well.') . '<br>'; + $output .= '<br><b>' . t('AUTHENTICATION METHODS SUPPORTED:') . '</b>'; + $output .= '<br>' . t('<ol> + <li>Basic Authentication</li> + <li>Key Based Authentication</li> + <li>OAuth/Access Token Based Authentication</li> + <li>JWT Token Based Authentication</li> + <li>3rd Party/External IDP Token Authentication</li> + </ol>') . '</br>'; + $output .= '<p> + + </p>'; + $output .= '<b>' . t('SETUP GUIDE') . '</b><br>'; + $output .= '' . t('Please click on this <a target="_blank" href="'.$setup_guides.'"><strong>link here</strong></a> to setup the module according to your requirements.') . ''; + + $output .= '<br><br><b>' . t('24 / 7 ACTIVE SUPPORT') . '</b><br>'; + $output .= '' . t('If you have any questions or in case you need any sort of assistance in configuring our module according toy our requirements, please feel free to drop us an email at <a href="mailto:drupalsupport@xecurify.com">drupalsupport@xecurify.com</a>. We will be more than happy to help') . ''; + + return $output; + } +} + +function rest_api_authentication_form_alter(&$form, FormStateInterface $form_state, $form_id){ + if($form_id === 'rest_api_authentication_config_client'){ + $form['api_auth']['rest_api_authentication_authentication_method_submit'] = [ '#disabled' => TRUE ]; + } + return $form; +} diff --git a/rest_api_authentication.routing.yml b/rest_api_authentication.routing.yml new file mode 100644 index 0000000000000000000000000000000000000000..0ec0b866c095a72e01f0db82e313e9a6f126fb59 --- /dev/null +++ b/rest_api_authentication.routing.yml @@ -0,0 +1,37 @@ +rest_api_authentication.auth_settings: + path: /admin/config/people/rest_api_authentication/auth_settings + defaults: + _title: 'miniOrange API Authentication <a class="button button--primary js-form-submit form-submit use-ajax mo_top_bar_button" href="auth_settings/requestSupport">Contact Us</a><a class="button button--primary js-form-submit form-submit use-ajax mo_top_bar_button" href="auth_settings/requestFreeTrial">Request 7-days trial</a><a class="button js-form-submit form-submit mo_top_bar_button" href="?tab=edit-upgrade-plans">Upgrade Plans</a>' + _form: \Drupal\rest_api_authentication\Form\miniorangeAPIAuth + requirements: + _permission: 'administer site configuration' + +#Route for Support Request/Contact Us +rest_api_authentication.request_api_support: + path: /admin/config/people/rest_api_authentication/auth_settings/requestSupport + defaults: + _title: 'miniOrange API Authentication Request Support' + _controller: '\Drupal\rest_api_authentication\Controller\rest_api_authenticationController::openSupportRequestForm' + requirements: + _permission: 'administer site configuration' + +#Route for Trial Request +rest_api_authentication.request_trial: + path: /admin/config/people/rest_api_authentication/auth_settings/requestFreeTrial + defaults: + _title: 'miniOrange API Authentication Trial Request' + _controller: '\Drupal\rest_api_authentication\Controller\rest_api_authenticationController::openTrialRequestForm' + requirements: + _permission: 'administer site configuration' + + +#Route for feedback +rest_api_authentication.feedback: + path: /feedback + defaults: + _controller: '\Drupal\rest_api_authentication\Controller\rest_api_authenticationController::miniorange_API_Auth_feedback' + requirements: + _permission: 'administer site configuration' + + + diff --git a/rest_api_authentication.services.yml b/rest_api_authentication.services.yml new file mode 100644 index 0000000000000000000000000000000000000000..062866a3e93dafac5e39a44c54a46b7c432a7247 --- /dev/null +++ b/rest_api_authentication.services.yml @@ -0,0 +1,15 @@ +services: + rest_api_authentication.authentication.rest_api_authentication: + class: Drupal\rest_api_authentication\Authentication\Provider\restAPI + arguments: ['@config.factory', '@entity_type.manager'] + tags: + - { name: authentication_provider, provider_id: rest_api_authentication, priority: 150 } + rest_api_authentication.page_cache_request_policy.disallow_rest_api_authentication_requests: + class: Drupal\rest_api_authentication\PageCache\DisallowAPIRequests + public: false + tags: + - { name: page_cache_request_policy } + rest_api_authentication.route_subscriber: + class: Drupal\rest_api_authentication\Routing\RouteSubscriber + tags: + - { name: event_subscriber } diff --git a/src/API_Authentication_API_Token.php b/src/API_Authentication_API_Token.php new file mode 100644 index 0000000000000000000000000000000000000000..f7bcd33795fae031e42323545aa8d1d8b17ea93f --- /dev/null +++ b/src/API_Authentication_API_Token.php @@ -0,0 +1,66 @@ +<?php +namespace Drupal\rest_api_authentication; +use Drupal\Component\Utility\Html; +use Drupal\user; +class API_Authentication_API_Token { + + static function validate_api_request($request) { + $api_error = array(); + $api_error['user'] = null; + $authorization_header = ""; + $api_error['status'] = 'error'; + + $config = \Drupal::configFactory()->getEditable('rest_api_authentication.settings'); + + if ( $request->headers->get('AUTHORIZATION') !=null || $request->headers->get('AUTHORISATION')!=null ) + $authorization_header = $request->headers->get('AUTHORIZATION') !=null ? $request->headers->get('AUTHORIZATION') : $request->headers->get('AUTHORISATION'); + + if(empty($authorization_header) || $authorization_header == ""){ + $api_error = array('status' => 'error', 'code' => '401', 'error_description' => 'MISSING AUTHORIZATION HEADER'); + return $api_error; + } + if (!preg_match('/\Basic\b/', $authorization_header)) { + $api_error = array('status' => 'error', 'code' => '400', 'error_description' => 'INVALID AUTHORIZATION HEADER TOKEN TYPE'); + return $api_error; + } + + $authorization_header = Html::escape($authorization_header); //html::escape() is used to filtering or escaping or XSS vulnerabilities + if($authorization_header != "" && strcasecmp($authorization_header, 'Basic' ) != 0 ){ + $authorization_header_array = explode( " ", $authorization_header ); + $authorization_header_value = $authorization_header_array[1]; + $decoded_authorization_header = base64_decode($authorization_header_value); + + $creds = explode(":", $decoded_authorization_header); + + if( isset($creds[0]) && isset($creds[1]) ) { + $name = $creds[0]; + if(!empty($name)) + $user = user_load_by_name($name); + $api_key = $creds[1]; + + if(\Drupal::config('rest_api_authentication.settings')->get('api_token') != $api_key ){ + $config->set('miniorange_api_key_authentication_tried', "Failed")->save(); + $api_error = array('status' => 'error', 'code' => '401', "error" => "INVALID_API_KEY", 'error_description' => 'Sorry, you are using invalid API Key'); + } + else if(empty($user)){ + $config->set('miniorange_api_key_authentication_tried', "Failed")->save(); + $api_error = array('status' => 'error', 'code' => '401', "error" => "USER_DOES_NOT_EXIST", 'error_description' => 'The user does not exists'); + } + else{ + $api_error['status'] = 'SUCCESS'; + $api_error['user'] = $user; + $config->set('miniorange_api_key_authentication_tried', "Successful")->save(); + } + } + else{ + $config->set('miniorange_api_key_authentication_tried', "Failed")->save(); + $api_error = array('status' => 'error', 'code' => '401', "error" => "INVALID_AUTHORIZATION_HEADER", 'error_description' => 'The authorization header seems to be invalid'); + } + } + else{ + $config->set('miniorange_api_key_authentication_tried', "Failed")->save(); + $api_error = array('status' => 'error', 'code' => '401', "error" => "MISSING_AUTHORIZATION_HEADER", 'error_description' => 'The Authorization header is missing from the request.'); + } + return $api_error; + } +} diff --git a/src/API_Authentication_Basic_Auth.php b/src/API_Authentication_Basic_Auth.php new file mode 100644 index 0000000000000000000000000000000000000000..03eeef905d237ca229459e90d3b13095f1e23dd8 --- /dev/null +++ b/src/API_Authentication_Basic_Auth.php @@ -0,0 +1,61 @@ +<?php +namespace Drupal\rest_api_authentication; +use Drupal\Component\Utility\Html; +use Drupal\user; +class API_Authentication_Basic_Auth { + + static function validate_api_request($request) { + $api_error = array(); + $api_error['user'] = null; + $authorization_header = ""; + $config = \Drupal::configFactory()->getEditable('rest_api_authentication.settings'); + + if ( !empty(\Drupal::config('rest_api_authentication.settings')->get('custom_header')) || \Drupal::config('rest_api_authentication.settings')->get('custom_header') !=null ) + $authorization_header = $request->headers->get(\Drupal::config('rest_api_authentication.settings')->get('custom_header')); + + if ( $request->headers->get('AUTHORIZATION') !=null || $request->headers->get('AUTHORISATION')!=null ) + $authorization_header = $request->headers->get('AUTHORIZATION') !=null ? $request->headers->get('AUTHORIZATION') : $request->headers->get('AUTHORISATION'); + + $authorization_header = Html::escape($authorization_header); //html::escape() is used to filtering or escaping or XSS vulnerabilities + + if(empty($authorization_header) || $authorization_header == ""){ + $api_error = array('status' => 'error', 'code' => '401', 'error_description' => 'MISSING AUTHORIZATION HEADER'); + return $api_error; + } + if (!preg_match('/\Basic\b/', $authorization_header)) { + $api_error = array('status' => 'error', 'code' => '400', 'error_description' => 'INVALID AUTHORIZATION HEADER TOKEN TYPE'); + return $api_error; + } + $authorization_header_array = explode( " ", $authorization_header ); + $authorization_header_value = $authorization_header_array[1]; + $decoded_authorization_header = base64_decode($authorization_header_value); + + $creds = explode(":", $decoded_authorization_header); + + if( isset($creds[0]) && isset($creds[1]) ) { + $name = $creds[0]; + if(empty($name)){ + $api_error = array('status' => 'error', 'code' => '400', "error" => "MISSING_USERNAME", 'error_description' => 'Username Not Found'); + return $api_error; + } + $pwd = $creds[1]; + + if(! ( \Drupal::service('user.auth')->authenticate( $name, $pwd ) ) ){ + $config->set('miniorange_basic_authentication_tried', "Failed")->save(); + $api_error = array('status' => 'error', 'code' => '400', "error" => "INVALID_CREDENTIALS", 'error_description' => 'Invalid username or password'); + return $api_error; + } + $user = user_load_by_name($name); + $api_error['status'] = 'SUCCESS'; + $api_error['user'] = $user; + + $config->set('miniorange_basic_authentication_tried', "Successful")->save(); + } + else{ + + $config->set('miniorange_basic_authentication_tried', "Failed")->save(); + $api_error = array('status' => 'error', 'code' => '401', "error" => "INCOMPLETE_REQUEST", 'error_description' => 'Incomplete request'); + } + return $api_error; + } +} diff --git a/src/Authentication/Provider/restAPI.php b/src/Authentication/Provider/restAPI.php new file mode 100644 index 0000000000000000000000000000000000000000..0e2a55b4dff6cbd38351c82131b06276b35b335d --- /dev/null +++ b/src/Authentication/Provider/restAPI.php @@ -0,0 +1,118 @@ +<?php + +namespace Drupal\rest_api_authentication\Authentication\Provider; + +use Drupal\rest_api_authentication\API_Authentication_Basic_Auth; +use Drupal\rest_api_authentication\API_Authentication_API_Token; +use Drupal\Core\Authentication\AuthenticationProviderInterface; +use Drupal\Core\Config\ConfigFactoryInterface; +use Drupal\Core\Entity\EntityTypeManagerInterface; +use Drupal\user\Entity\User; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpKernel\Event\ExceptionEvent; +use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; +use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; + + +/** + * miniorange authentication provider. + */ +class restAPI implements AuthenticationProviderInterface { + +/** + * The module configuration. + * + * @var \Drupal\Core\Config\ImmutableConfig + */ + protected $config; + + /** + * The entity manager service. + * + * @var \Drupal\Core\Entity\EntityTypeManager + */ + protected $entityTypeManager; + + /** + * Constructs a new restAPI object. + * + * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory + * The config factory service. + * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager + * The entity type manager service. + */ + public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager) { + $this->config = $config_factory->get('rest_api_authentication.settings'); + $this->entityTypeManager = $entity_type_manager; + } + + /** + * {@inheritdoc} + */ + public function applies(Request $request) { + $enable_authentication=\Drupal::config('rest_api_authentication.settings')->get('enable_authentication'); + if($enable_authentication == 1) { + if (strpos($request->getRequestUri(), '/admin/config/services/jsonapi/') !== false) + return false; + if (strpos($request->getRequestUri(), '/jsonapi/') !== false) + return true; + if (strpos($request->getRequestUri(), '?_format=') !== false) + return true; + return false; + } + } + + /** + * {@inheritdoc} + */ + public function authenticate(Request $request) { + + $api_error = array(); + + if ($request->getPathInfo() == "/user/login") { + return null; + } + $authentication_method = \Drupal::config('rest_api_authentication.settings')->get('authentication_method'); + switch ($authentication_method) { + case 0: + $api_error = API_Authentication_Basic_Auth::validate_api_request($request); + break; + case 1: + $api_error = API_Authentication_API_Token::validate_api_request($request); + break; + default: + return null; + } + + if(isset($api_error['status']) && $api_error['status'] == 'error'){ + + if((isset($api_error['message']) && trim($api_error['message'])!='') || (isset($api_error['error_description']) && trim($api_error['error_description'])!='')){ + echo json_encode($api_error, JSON_PRETTY_PRINT);exit; + } + else{ + throw new AccessDeniedHttpException(); + return null; + } + } + $account = $api_error['user']; + $uid = $account->id(); + // Load user storage. + $storage = $this->entityTypeManager->getStorage('user'); + return $this->entityTypeManager + ->getStorage('user') + ->load($uid); + } + + + /** + * {@inheritdoc} + */ + public function handleException(ExceptionEvent $event) { + $exception = $event->getThrowable(); + if ($exception instanceof AccessDeniedHttpException) { + $event->setThrowable(new UnauthorizedHttpException('Invalid consumer origin.', $exception)); + return TRUE; + } + return FALSE; + } +} diff --git a/src/Controller/rest_api_authenticationController.php b/src/Controller/rest_api_authenticationController.php new file mode 100644 index 0000000000000000000000000000000000000000..73106b8c043817b468eb47e27a3838c8c11734c0 --- /dev/null +++ b/src/Controller/rest_api_authenticationController.php @@ -0,0 +1,137 @@ +<?php +/** + * @file + * Contains \Drupal\rest_api_authentication\Controller\DefaultController. + */ + +namespace Drupal\rest_api_authentication\Controller; +use Drupal\Core\Ajax\AjaxResponse; +use Drupal\Core\Ajax\OpenModalDialogCommand; +use Drupal\Core\Controller\ControllerBase; +use Drupal\rest_api_authentication\Utilities; +use Exception; +use Symfony\Component\HttpFoundation\RedirectResponse; +use Drupal\rest_api_authentication\MiniorangeApiAuthConstants; +use function Symfony\Component\VarDumper\Dumper\esc; +use GuzzleHttp\Client; + +class rest_api_authenticationController extends ControllerBase { + /** + * @return \Drupal\Core\Ajax\AjaxResponse + */ + public function openSupportRequestForm() { + $response = new AjaxResponse(); + $modal_form = \Drupal::formBuilder()->getForm('\Drupal\rest_api_authentication\Form\MiniornageAPIAuthnRequestSupport'); + $response->addCommand(new OpenModalDialogCommand('Support Request/Contact Us', $modal_form, ['width' => '40%'])); + return $response; + } + + /** + * @return \Drupal\Core\Ajax\AjaxResponse + */ + public function openTrialRequestForm() { + $response = new AjaxResponse(); + $modal_form = \Drupal::formBuilder()->getForm('\Drupal\rest_api_authentication\Form\MiniornageAPIAuthnRequestTrial'); + $response->addCommand(new OpenModalDialogCommand('Request 7-Days Full Feature Trial License', $modal_form, ['width' => '40%'])); + return $response; + } + + /** + * sends feedback mail to drupalsupport + */ + public function miniorange_API_Auth_feedback(){ + + global $base_url; + $reason=""; + if(isset($_GET['query']) && trim($_GET['query']!="")){ + $reason=$_GET['query']; + } + else{ + $reason = "Not Specified"; + } + + $query_feedback = $_GET['query_feedback']; + + $message = 'Reason: ' . $reason . '<br>' . 'Feedback: ' . $query_feedback; + + $config = \Drupal::config('rest_api_authentication.settings'); + if (isset($_GET['rest_feedback_submit']) || isset($_GET['rest_feedback_skip'])){ + $module_info = \Drupal::service('extension.list.module')->getExtensionInfo('rest_api_authentication'); + $module_version = $module_info['version']; + $_SESSION['mo_other']="False"; + + $config=\Drupal::config('rest_api_authentication.settings'); + $email =$config->get('rest_api_authentication_customer_admin_email'); + + if(empty($email)) + $email = $_GET['rest_feedback_email']; + + $customerKey= $config->get('rest_api_authentication_customer_id'); + $apikey = $config->get('rest_api_authentication_customer_api_key'); + if($customerKey==''){ + $customerKey="16555"; + $apikey="fFd2XcvTGDemZvbw1bcUesNJWEqKbbUq"; + } + + $basicAuthTried=$config->get('miniorange_basic_authentication_tried'); + $apikeyAuthTried=$config->get('miniorange_api_key_authentication_tried'); + $licensePageVisited=$config->get('miniorange_rest_api_license_page_visited'); + $triedAuthMethods = ($basicAuthTried == 'Did not Try')?'None':'<br>Basic Auth: '.$basicAuthTried.'</br>'; + + if(!str_contains($triedAuthMethods, 'None')){ + $triedAuthMethods .= $apikeyAuthTried !== 'Did not Try'?'<br>Api Key Auth: '.$apikeyAuthTried.'</br>':''; + }else{ + $triedAuthMethods = $apikeyAuthTried !== 'Did not Try'?'<br>Api Key Auth: '.$apikeyAuthTried.'<br>':'None'; + } + + $skipped = isset($_GET['rest_feedback_skip']) ? TRUE : FALSE; + $add_skip = $skipped ? "<b>Skipped: True</b><br><br>" : ""; + + $users_OS=Utilities::getUsersOS(); + + $installed_on = $config->get('miniorange_rest_api_installation_time_ref'); + $installed_date = date('d/m/Y H:i:s', $installed_on); + $current_time_in_ms = Utilities::get_timestamp(); + $stringToHash = $customerKey . $current_time_in_ms . $apikey; + $hashValue = hash("sha512", $stringToHash); + + $fromEmail = $email; + $subject = 'Drupal ' . \DRUPAL::VERSION . ' REST API Authentication Module Feedback | '.$module_version.' | PHP Version '.phpversion(); + $query = '[Drupal ' . \DRUPAL::VERSION . ' REST API Authentication | '.$module_version.' | PHP Version '.phpversion().' ]: ' . $message; + $content = '<div >Hello, <br><br>Company :<a href="' . $_SERVER['SERVER_NAME'] . '" target="_blank" >' . $_SERVER['SERVER_NAME'] .'</a><br><br>Email :<a href="mailto:' . $fromEmail . '" target="_blank">' . $fromEmail . '</a><br><br>Installed on: ' . $installed_date .'<br><br>Operating System:'.$users_OS. '<br><br>Payment Page Visited: ' . $licensePageVisited . '<br><br>Tried Authentication Methods: ' . $triedAuthMethods . '<br><br>' . $add_skip . 'Query: ' . $query . '</div>'; + $fields = array( + 'customerKey' => $customerKey, + 'sendEmail' => true, + 'email' => array( + 'customerKey' => $customerKey, + 'fromEmail' => $fromEmail, + 'fromName' => 'miniOrange', + 'toEmail' =>'drupalsupport@xecurify.com', + 'toName' =>'drupalsupport@xecurify.com', + 'subject' => $subject, + 'content' => $content + ), + ); + + $field_string = json_encode($fields); + $url = MiniorangeApiAuthConstants::BASE_URL . '/moas/api/notify/send'; + + $header = ['Content-Type'=> 'application/json', 'Customer-Key'=>$customerKey, 'Timestamp'=>$current_time_in_ms,'Authorization'=>$hashValue ]; + + try{ + $response = \Drupal::httpClient()->post($url, ['headers'=>$header,'body'=>$field_string,'verify'=>FALSE]); + + + }catch (Exception $exception){ + + } + + } + + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->clear('miniorange_rest_api_authentication_uninstall_status')->save(); + \Drupal::service('module_installer')->uninstall(['rest_api_authentication']); + $uninstall_redirect = $base_url.'/admin/modules'; + \Drupal::messenger()->addMessage('The module has been successfully uninstalled.'); + return new RedirectResponse($uninstall_redirect); + } +} diff --git a/src/Form/MiniornageAPIAuthnRequestSupport.php b/src/Form/MiniornageAPIAuthnRequestSupport.php new file mode 100644 index 0000000000000000000000000000000000000000..5a42d666c5c51a5aff61595451c3d5915197815d --- /dev/null +++ b/src/Form/MiniornageAPIAuthnRequestSupport.php @@ -0,0 +1,143 @@ +<?php + +namespace Drupal\rest_api_authentication\Form; + +use Drupal\Core\Ajax\AjaxResponse; +use Drupal\Core\Ajax\OpenModalDialogCommand; +use Drupal\Core\Ajax\ReplaceCommand; +use Drupal\Core\Ajax\RedirectCommand; +use Drupal\Core\Form\FormStateInterface; +use Drupal\Core\Url; +use Drupal\rest_api_authentication\MiniorangeApiAuthSupport; +use Drupal\Core\Form\FormBase; +/** + * + */ +class MiniornageAPIAuthnRequestSupport extends FormBase { + + /** + * + */ + public function getFormId() { + return 'mo_rest_api_authentication_request_support'; + } + + /** + * + */ + public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) { + + $form['#prefix'] = '<div id="modal_support_form">'; + $form['#suffix'] = '</div>'; + $form['status_messages'] = [ + '#type' => 'status_messages', + '#weight' => -10, + ]; + + $form['markup_library'] = [ + '#attached' => [ + 'library' => [ + "rest_api_authentication/rest_api_authentication.admin", + ], + ], + ]; + + $form['markup_1'] = [ + '#markup' => $this->t('<p>Need any help? We can help you with configuring <strong>Drupal API Authentication module</strong> on your site. Just send us a query and we will get back to you right away.</p>'), + ]; + $form['rest_api_authentication_support_email_address'] = [ + '#type' => 'email', + '#title' => t('Email'), + '#required' => TRUE, + '#attributes' => [ + 'placeholder' => $this->t('Enter your email'), + 'style' => 'width:99%;margin-bottom:1%;', + ], + ]; + $form['rest_api_authentication_support_phone_number'] = [ + '#type' => 'textfield', + '#title' => t('Phone'), + '#attributes' => [ + 'placeholder' => $this->t('Enter number with country code Eg. +00xxxxxxxxxx'), + 'style' => 'width:99%;margin-bottom:1%;', + ], + ]; + $form['rest_api_authentication_support_query'] = [ + '#type' => 'textarea', + '#required' => TRUE, + '#title' => t('Query'), + '#attributes' => [ + 'placeholder' => $this->t('Describe your query here!'), + 'style' => 'width:99%', + ], + ]; + + $form['actions'] = ['#type' => 'actions']; + $form['actions']['send'] = [ + '#type' => 'submit', + '#value' => $this->t('Submit'), + '#attributes' => [ + 'class' => [ + 'use-ajax', + 'button--primary', + ], + ], + '#ajax' => [ + 'callback' => [$this, 'submitModalFormAjax'], + 'event' => 'click', + ], + ]; + + $form['#attached']['library'][] = 'core/drupal.dialog.ajax'; + return $form; + } + + /** + * + */ + public function submitModalFormAjax(array $form, FormStateInterface $form_state) { + $form_values = $form_state->getValues(); + $response = new AjaxResponse(); + // If there are any form errors, AJAX replace the form. + if ($form_state->hasAnyErrors()) { + $response->addCommand(new ReplaceCommand('#modal_support_form', $form)); + } + else { + $email = $form_values['rest_api_authentication_support_email_address']; + $phone = $form_values['rest_api_authentication_support_phone_number']; + $query = $form_values['rest_api_authentication_support_query']; + $query_type = 'Support'; + + $support = new MiniorangeApiAuthSupport($email, $phone, $query, $query_type); + $support_response = $support->sendSupportQuery(); + if ($support_response) { + $message = array( + '#type' => 'item', + '#markup' => $this->t('Support query successfully sent. We will get back to you shortly.'), + ); + $ajax_form = new OpenModalDialogCommand('Thank you!', $message, ['width' => '50%']); + } else { + $error = array( + '#type' => 'item', + '#markup' => $this->t('Error submitting the support query. Please send us your query at + <a href="mailto:drupalsupport@xecurify.com"> + drupalsupport@xecurify.com</a>.'), + ); + $ajax_form = new OpenModalDialogCommand('Error!', $error, ['width' => '50%']); + } + $response->addCommand($ajax_form); + } + return $response; + } + + /** + * + */ + public function validateForm(array &$form, FormStateInterface $form_state) {} + + /** + * + */ + public function submitForm(array &$form, FormStateInterface $form_state) {} + +} diff --git a/src/Form/MiniornageAPIAuthnRequestTrial.php b/src/Form/MiniornageAPIAuthnRequestTrial.php new file mode 100644 index 0000000000000000000000000000000000000000..f0bce9a99ae3f2406a3ed25310f8e2e6e3600bb6 --- /dev/null +++ b/src/Form/MiniornageAPIAuthnRequestTrial.php @@ -0,0 +1,131 @@ +<?php + +namespace Drupal\rest_api_authentication\Form; + +use Drupal\Core\Ajax\AjaxResponse; +use Drupal\Core\Ajax\ReplaceCommand; +use Drupal\Core\Ajax\RedirectCommand; +use Drupal\Core\Ajax\OpenModalDialogCommand; +use Drupal\Core\Form\FormStateInterface; +use Drupal\Core\Url; +use Drupal\rest_api_authentication\MiniorangeApiAuthSupport; +use Drupal\Core\Form\FormBase; + +/** + * + */ +class MiniornageAPIAuthnRequestTrial extends FormBase { + + /** + * + */ + public function getFormId() { + return 'rest_api_authentication_request_support'; + } + + /** + * + */ + public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) { + + $form['#prefix'] = '<div id="modal_example_form">'; + $form['#suffix'] = '</div>'; + $form['status_messages'] = [ + '#type' => 'status_messages', + '#weight' => -10, + ]; + + $form['rest_api_authentication_trial_email_address'] = [ + '#type' => 'email', + '#title' => t('Email'), + '#required' => TRUE, + '#attributes' => [ + 'placeholder' => $this->t('Enter your email'), + 'style' => 'width:99%;margin-bottom:1%;', + ], + ]; + + $form['rest_api_authentication_trial_description'] = [ + '#type' => 'textarea', + '#rows' => 4, + '#required' => TRUE, + '#title' => t('Description'), + '#attributes' => [ + 'placeholder' => $this->t('Describe your use case here!'), + 'style' => 'width:99%;', + ], + ]; + + $form['rest_api_authentication_trial_note'] = [ + '#markup' => $this->t('<div>If you have any questions or in case you need any sort of assistance in configuring our module according to your requirements, you can get in touch with us on <a href="mailto:drupalsupport@xecurify.com">drupalsupport@xecurify.com</a> and we will assist you further.</div>'), + ]; + + $form['actions'] = ['#type' => 'actions']; + $form['actions']['send'] = [ + '#type' => 'submit', + '#value' => $this->t('Submit'), + '#attributes' => [ + 'class' => [ + 'use-ajax', + 'button--primary', + ], + ], + '#ajax' => [ + 'callback' => [$this, 'submitModalFormAjax'], + 'event' => 'click', + ], + ]; + + $form['#attached']['library'][] = 'core/drupal.dialog.ajax'; + return $form; + } + + /** + * + */ + public function submitModalFormAjax(array $form, FormStateInterface $form_state) { + $form_values = $form_state->getValues(); + $response = new AjaxResponse(); + // If there are any form errors, AJAX replace the form. + if ($form_state->hasAnyErrors()) { + $response->addCommand(new ReplaceCommand('#modal_example_form', $form)); + } + else { + $email = $form_values['rest_api_authentication_trial_email_address']; + $query = $form_values['rest_api_authentication_trial_description']; + $query_type = 'trial'; + + $support = new MiniorangeApiAuthSupport($email, '', $query, $query_type); + $support_response =$support->sendSupportQuery(); + if ($support_response) { + $message = array( + '#type' => 'item', + '#markup' => $this->t('Your request for a trial module was successfully sent. Please allow us some time and we will be sending you the trial module very shortly.'), + ); + $ajax_form = new OpenModalDialogCommand('Thank you!', $message, ['width' => '50%']); + } else { + $error = array( + '#type' => 'item', + '#markup' => $this->t('Error submitting the support query. Please send us your query at + <a href="mailto:drupalsupport@xecurify.com"> + drupalsupport@xecurify.com</a>.'), + ); + $ajax_form = new OpenModalDialogCommand('Error!', $error, ['width' => '50%']); + } + + $response->addCommand($ajax_form); + } + return $response; + } + + /** + * + */ + public function validateForm(array &$form, FormStateInterface $form_state) {} + + /** + * + */ + public function submitForm(array &$form, FormStateInterface $form_state) {} + +} diff --git a/src/Form/miniorangeAPIAuth.php b/src/Form/miniorangeAPIAuth.php new file mode 100644 index 0000000000000000000000000000000000000000..b83e415042a823713877c135d0ed86b4f3eecce4 --- /dev/null +++ b/src/Form/miniorangeAPIAuth.php @@ -0,0 +1,349 @@ +<?php + +/** + * @file + * Contains \Drupal\rest_api_authentication\Form\miniorangeAPIAuth. + */ + +namespace Drupal\rest_api_authentication\Form; +use Drupal\rest_api_authentication\AdvancedSettingsForm; +use Drupal\rest_api_authentication\CustomerSetupForm; +use Drupal\rest_api_authentication\RequestForDemoForm; +use Drupal\rest_api_authentication\SetupAuthenticationForm; +use Drupal\rest_api_authentication\Utilities; +use Drupal\rest_api_authentication\UpgradePlansForm; +use Drupal\Core\Form\FormStateInterface; +use Drupal\Core\Form\FormBase; +use Drupal\rest_api_authentication\MiniorangeRestAPICustomer; +use Symfony\Component\HttpFoundation\RedirectResponse; + +class miniorangeAPIAuth extends FormBase { + + public function getFormId() { + return 'rest_api_authentication_config_client'; + } + + public function buildForm(array $form, FormStateInterface $form_state){ + global $base_url; + $auth_method = \Drupal::config('rest_api_authentication.settings')->get('authentication_method'); + if(empty($auth_method) || $auth_method=null){ + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('authentication_method',0)->save(); + } + $form['markup_library_1'] = array( + '#attached' => array( + 'library' => array( + "rest_api_authentication/rest_api_authentication.basic_style_settings", + ) + ), + ); + $tab = (isset($_GET['tab'])) ? ($_GET['tab']) : ('edit-api-auth'); + $form['rest_api_authentication_background'] = array( + '#markup' => '<div class="mo_rest_api_authn_background">', + ); + $form['verticaltabs'] = [ + '#type' => 'vertical_tabs', + '#default_tab' => $tab, + ]; + + /** + * builds and inserts the Setup Authentication Method form + */ + SetupAuthenticationForm::insertForm($form, $form_state); + + /** + * builds and inserts the Advanced Settings form + */ + AdvancedSettingsForm::insertForm($form, $form_state); + + /** + * builds and inserts the Request For Demo form + */ + RequestForDemoForm::insertForm($form, $form_state); + + /** + * builds and inserts the Upgrade Plans form + */ + UpgradePlansForm::insertForm($form, $form_state); + + /** + * builds and inserts the Register/Login form + */ + CustomerSetupForm::insertForm($form, $form_state); + $form['rest_api_authentication_background_end'] = array( + '#markup' => '</div>', + ); + return $form; + } + + function rest_api_authentication_save_basic_config(array &$form, FormStateInterface $form_state){ + global $base_url; + $form_input = $form_state->getValues(); + $enable_authentication = $form_input['enable_authentication']; + + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('enable_authentication',$enable_authentication)->save(); + \Drupal::messenger()->addMessage(t('Settings Saved Successfully.')); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings/?tab=edit-api-auth"); + $response->send(); + return; + } + + function rest_api_authentication_generate_api_token(array &$form, FormStateInterface $form_state){ + global $base_url; + $api_key = Utilities::generateRandom(64); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('api_token', $api_key)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('authentication_method',1)->save(); + \Drupal::messenger()->addMessage(t('New API Key generated successfully.')); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-api-auth"); + $response->send(); + return; + } + function rest_api_authentication_save_ext_oauth(array &$form, FormStateInterface $form_state){ + global $base_url; + $user_info = $form['api_auth']['mo_rest_api_authentication_authenticator']['rest_api_authentication_ext_oauth']['#value']; + $username_attribute = $form['api_auth']['mo_rest_api_authentication_authenticator']['rest_api_authentication_ext_oauth_username']['#value']; + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('user_info_endpoint',$user_info)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('username_attribute',$username_attribute)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('authentication_method',4)->save(); + \Drupal::messenger()->addMessage(t('Configurations for 3rd party provider saved successfully.')); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-api-auth"); + $response->send(); + return; + } + function rest_api_authentication_generate_oauth_keys(array &$form, FormStateInterface $form_state){ + $client_id = Utilities::generateRandom(30); + $client_secret = Utilities::generateRandom(30); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('oauth_client_id',$client_id)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('oauth_client_secret',$client_secret)->save(); + self::rest_api_authentication_save_oauth_token($form, $form_state); + } + function rest_api_authentication_save_oauth_token(array &$form, FormStateInterface $form_state){ + global $base_url; + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('authentication_method',2)->save(); + \Drupal::messenger()->addMessage(t('OAuth method configurations Saved successfully.')); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-api-auth"); + $response->send(); + return; + } + function rest_api_authentication_save_id_token(array &$form, FormStateInterface $form_state){ + global $base_url; + if(isset($form['api_auth']['mo_rest_api_authentication_authenticator']['settings']['active'])) + $authentication_method = $form['api_auth']['mo_rest_api_authentication_authenticator']['settings']['active']['#value']; + if($authentication_method == 0){ + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('authentication_method',0)->save(); + \Drupal::messenger()->addMessage(t('Basic Authentication Configurations Saved successfully.')); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-api-auth"); + $response->send(); + return; + } + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('authentication_method',3)->save(); + \Drupal::messenger()->addMessage(t('Selected method saved Successfully.')); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-api-auth"); + $response->send(); + return; + } + + function submitForm(array &$form, FormStateInterface $form_state){ + global $base_url; + $list_of_apis = $form['advancedsettings']['support_container_outline']['list_apis']['api_textarea']['#value']; + $api_access = $form['advancedsettings']['support_container_outline']['list_apis']['settings']['#value']; + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('api_access_type',$api_access)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('list_of_apis',$list_of_apis)->save(); + \Drupal::messenger()->addMessage(t('Configurations for API Based Restriction saved successfully.')); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-advanced-settings"); + $response->send(); + return; + } + + function rest_api_authentication_save_basic_auth_conf(array &$form, FormStateInterface $form_state){ + global $base_url; + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('authentication_method',0)->save(); + \Drupal::messenger()->addMessage(t('Configurations saved successfully.')); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-api-auth"); + $response->send(); + return; + } + + /** + * Send support query. + */ + public function saved_support(array &$form, FormStateInterface $form_state) { + $email = trim($form['rest_api_authentication_support_email_address']['#value']); + $phone = $form['rest_api_authentication_support_phone_number']['#value']; + $query = trim($form['rest_api_authentication_support_query']['#value']); + Utilities::send_support_query($email, $phone, $query, null); + } + + /** + * Custom Header Save Button + */ + public function custom_header_submit(array &$form, FormStateInterface $form_state) { + global $base_url; + $custom_header = trim($form['advancedsettings']['support_container_outline']['custom_headers']['div_key']['#value']); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('custom_header',$custom_header)->save(); + \Drupal::messenger()->addMessage(t('Custom Header Configurations saved successfully.')); + + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-advanced-settings"); + $response->send(); + return; + } + + /** + * Save token Expiry + */ + public function token_expiry_submit(array &$form, FormStateInterface $form_state) { + global $base_url; + $custom_header = trim($form['advancedsettings']['support_container_outline']['custom_headers']['div_key']['#value']); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('custom_header',$custom_header)->save(); + $token_expiry = trim($form['advancedsettings']['support_container_outline']['token_expiry']['access_token_expiry_time']['#value']); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('token_expiry',$token_expiry)->save(); + \Drupal::messenger()->addMessage(t('Configurations saved successfully.')); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-advanced-settings"); + $response->send(); + return; + } + + /** + * Send a request for Demo. + */ + public function saved_demo_request(array &$form, FormStateInterface $form_state) { + global $base_url; + $email = trim($form['demo']['container_outline']['rest_api_authentication_email_address']['#value']); + $phone = $form['demo']['container_outline']['rest_api_authentication_phone_number']['#value']; + $query = trim($form['demo']['container_outline']['rest_api_authentication_demo_query']['#value']); + Utilities::send_support_query($email, $phone, $query, 'demo'); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-demo"); + $response->send(); + } +/** + * Remove account + */ + function rest_api_authentication_remove_account(&$form, $form_state){ + global $base_url; + if (isset($_POST['value_check']) && $_POST['value_check'] == 'True'){ + if(\Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_license_key') != NULL) { + $current_status = 'CUSTOMER_SETUP'; + $username = \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_admin_email'); + $customer = new MiniorangeRestAPICustomer($username, NULL); + $response = json_decode($customer->updateStatus()); + + if ($response->status == 'SUCCESS'){ + $clear_value = ''; + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_customer_admin_email', $clear_value)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_customer_id', $clear_value)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_customer_api_key', $clear_value)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_license_key', $clear_value)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_customer_password', $clear_value)->save(); + + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_status', $current_status)->save(); + + \Drupal::messenger()->addMessage(t('Your account has been removed successfully!'), 'status'); + $_POST['value_check'] = 'False'; + } + } + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-customer-setup"); + $response->send(); + return; + } + else{ + $myArray = array(); + $myArray = $_POST; + $form_id = $_POST['form_id']; + $form_token = $_POST['form_token']; + $op = $_POST['op']; + $build_id = $_POST['form_build_id']; + global $base_url; + ?> + + <html> + <head> + <title>Confirmation</title> + <link href="https://fonts.googleapis.com/css?family=PT+Serif" rel="stylesheet"> + </head> + + <body style="font-family: 'PT Serif', serif;"> + <div style="margin: 15% auto; height:35%; width: 40%; background-color: #eaebed; text-align: center; box-shadow: 10px 5px 5px darkgray; border-radius: 2%;"> + <div style="color: #a94442; background-color:#f2dede; padding: 15px; margin-bottom: 20px; text-align:center; border:1px solid #E6B3B2; font-size:16pt; border-radius: 2%;"> + <strong>Are you sure you want to remove account..!!</strong> + </div> + <p style="font-size:14px; margin-left: 8%; margin-right: 8%"><strong>Warning </strong>: If you remove your account, you will have to enter licence key again after login/sign in with the new account.</p> + <br/> + <form name="f" method="post" action="" id="mo_remove_account"> + <div> + <input type="hidden" name="op" value=<?php echo $op;?>> + <input type="hidden" name="form_build_id" value= <?php echo $build_id;?>> + <input type="hidden" name="form_token" value=<?php echo $form_token;?>> + <input type="hidden" name="form_id" value= <?php echo $form_id;?>> + <input type="hidden" name="value_check" value= 'True'> + </div> + <div style="margin: auto; text-align: center;" class="mo2f_modal-footer"> + <input type="submit" style=" padding:1%; width:100px; background: #0091CD none repeat scroll 0% 0%; cursor: pointer; font-size:15px; border-width: 1px; border-style: solid; border-radius: 3px; white-space: nowrap; box-sizing: border-box;border-color: #0073AA; box-shadow: 0px 1px 0px rgba(120, 200, 230, 0.6) inset; color: #FFF;" name="miniorange_confirm_submit" class="button button-danger button-large" value="Confirm"/> + + <a type="submit" style=" padding:1%; width:100px; background: #0091CD none repeat scroll 0% 0%; cursor: pointer; font-size:15px; border-width: 1px; border-style: solid; border-radius: 3px; white-space: nowrap; box-sizing: border-box;border-color: #0073AA; box-shadow: 0px 1px 0px rgba(120, 200, 230, 0.6) inset; color: #FFF; text-decoration: none;" class="button button-danger button-large" href=<?php echo $base_url.'/admin/config/people/rest_api_authentication/customer_setup'; ?> >Cancel</a> + + </div> + </form> + </div> + </body> + </html> + <?php + exit; + } + } + + /** + * Activating the module + */ + public function activate_module_request(array &$form, FormStateInterface $form_state) { + global $base_url; + $username = $form['customersetup']['customer_setup_container_outline']['rest_api_authentication_user_email']['#value']; + $password = $form['customersetup']['customer_setup_container_outline']['rest_api_authentication_user_password']['#value']; + if(empty($username)||empty($password)){ + \Drupal::messenger()->addMessage(t('The <b><u>Email Address</u></b> and the <b><u>Password</u></b> fields are mandatory.'), 'error'); + return; + } + if (!\Drupal::service('email.validator')->isValid( $username )) { + \Drupal::messenger()->addMessage(t('The email address <i>' . $username . '</i> does not seems to be valid.'), 'error'); + return; + } + $customer_config = new MiniorangeRestAPICustomer($username,$password); + $check_customer_response = json_decode($customer_config->checkCustomer()); + + if (isset( $check_customer_response->status ) && $check_customer_response->status == 'CUSTOMER_NOT_FOUND') { + \Drupal::messenger()->addMessage(t('Invalid credentials'), 'error'); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-customersetup"); + $response->send(); + return; + } + elseif (isset( $check_customer_response->status ) && $check_customer_response->status == 'CURL_ERROR') { + \Drupal::messenger()->addMessage(t('cURL is not enabled. Please enable cURL'), 'error'); + } + else { + + $customer_keys_response = json_decode($customer_config->getCustomerKeys()); +// $customer_keys_response = json_decode($customer_config->getCustomerKeys()->getBody()->getContents()); + + if (json_last_error() == JSON_ERROR_NONE) { + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_customer_id', $customer_keys_response->id)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_customer_admin_token', $customer_keys_response->token)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_customer_admin_email', $username)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_customer_api_key', $customer_keys_response->apiKey)->save(); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_customer_password', $password)->save(); + $current_status = 'PLUGIN_CONFIGURATION'; + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_status', $current_status)->save(); + \Drupal::messenger()->addMessage(t('Successfully retrieved your account.')); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-customersetup"); + $response->send(); + return; + } + else { + \Drupal::messenger()->addMessage(t('Invalid credentials'), 'error'); + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-customersetup"); + $response->send(); + return; + } + } + $response = new RedirectResponse($base_url."/admin/config/people/rest_api_authentication/auth_settings?tab=edit-customersetup"); + $response->send(); + return; + } +} diff --git a/src/MiniorangeAPIAuthfeedback.php b/src/MiniorangeAPIAuthfeedback.php new file mode 100644 index 0000000000000000000000000000000000000000..5e8f1a5240be1736fabaf3a88e51807f2f094878 --- /dev/null +++ b/src/MiniorangeAPIAuthfeedback.php @@ -0,0 +1,173 @@ +<?php +namespace Drupal\rest_api_authentication; +use Drupal\rest_api_authentication\utilities; + +class MiniorangeAPIAuthfeedback{ + +public static function rest_api_authentication_feedback_form(){ + + + global $base_url; + $feedback_url = $base_url.'/feedback'; + $_SESSION['mo_other'] = 'True'; + $form_id = $_POST['form_id']; + $form_token = $_POST['form_token']; + $admin_email=Utilities::getCustomerEmail(); +?> +<html> +<head> +<link href="https://fonts.googleapis.com/css?family=PT+Serif" rel="stylesheet"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> + <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> + <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> +<style> + + .container{ + font-family: sans-serif; + } +/* h4.modal-title { + font-size: 18px; +} + p { + padding-top: 20px; + text-align: left; + margin-left: 10px; +}*/ +input#rest_feedback_email { + margin-left: 7px; + width: 125%; +} +/* .modal-header { + margin-bottom: -11px; +} */ + .rest_loader { + margin: auto; + display: block; + border: 5px solid #f3f3f3; /* Light grey */ + border-top: 5px solid #3498db; /* Blue */ + border-radius: 50%; + width: 50px; + height: 50px; + animation: spin 2s linear infinite; + } + + @keyframes spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } + } + </style> + <script> + $(document).ready(function () { + $("#myModal").modal({ + backdrop: 'dynamic', + keyboard: TRUE + }); + }); + + $(function () { + $(".button").click(function () { + document.getElementById('rest_loader').style.display = 'block'; + var reason = $("input[name='performance']:checked").val(); + var q_feedback = document.getElementById("sso_feedback").value; + return false; + }); + }) + + </script> +</head> +<body> + <div class="container" style="background: rgba(0, 0, 0, 0.1);width:100%;" > + <div class="modal_fade" id="myModal" role="dialog" > + <div class="modal-dialog" style="width: 500px;" role="dialog" > + <div class="modal-content" style="border-radius: 20px;" > + <div class="modal-header" style="padding: 25px; border-top-left-radius: 20px; border-top-right-radius: 20px; background-color: #8fc1e3;"> + <h4 class="modal-title" style="color: white; text-align: center;">Hey, it seems like you want to deactivate Rest API Authentication Module</h4> + <hr> + <h4 style="text-align: center; color: white;" class="modal-title">What happened?</h4> + </div> + <div class="modal-body" style="font-size: 11px; padding-right: 25px; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; background-color: #ececec;"> + <form action="<?php echo $feedback_url; ?>" id="restapi_feedback"> + <div> + <p> + <?php + if(empty(\Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_admin_email'))) { ?> + <br><label style="font-size: 12.5px">Email ID:<label> <input onblur="validateEmail(this)" class="form-control" + type="email" id="rest_feedback_email" required value= <?php echo $admin_email; ?> + name="rest_feedback_email"/> + <p style="display: none;color:red" id="email_error">Invalid Email</p> + <?php + } ?> + <br> + <?php + $deactivate_reasons = array( + t("Not Working"), + t("Basic Authentication Not Working"), + t("API key Authentication Not Working"), + t("Does not have the features I'm looking for"), + t("Confusing interface"), + t("Bugs in the module"), + t("Other reasons: "), + ); + foreach ($deactivate_reasons as $deactivate_reasons) { + ?> + <div class="radio" style="padding:2px;font-size: 8px;text-align:left"> + <label style="font-weight:normal;font-size:14.6px;color:maroon;" for="<?php echo $deactivate_reasons; ?>"> + <input type="radio" name="query" value="<?php echo $deactivate_reasons;?>" required> + <?php echo $deactivate_reasons; ?> + </label> + </div> + <?php } ?> + <input type="hidden" name="form_token" value=<?php echo $form_token ?> > + <input type="hidden" name="form_id" value= <?php echo $form_id ?>> + <br> + <textarea class="form-control" id="query_feedback" name="query_feedback" rows="4" cols="50" style="margin-left:2%;text-align:left" placeholder="Write your query here"></textarea> + <br><br> + <div class="mo2f_modal-footer" style="margin-bottom: 5% !important;"> + <input type="submit" id="submit_button" name="rest_feedback_submit" class="button btn btn-primary" value="Submit and Continue" style=" display: block; font-size: 11px;float: left; margin-left: 21px;margin-bottom: 15%;" /> + <input type="submit" formnovalidate="formnovalidate" style="margin: auto; display: block; font-size: 11px; float: right;" name="rest_feedback_skip" class="btn btn-link" value="Skip" /> + </div> + <div class="rest_loader" id="rest_api_feedback" style="display: none;"></div> + <?php + echo "<br><br>"; + foreach($_POST as $key => $value) { + self::hiddenRestapifields($key,$value); + } + ?> + </div> + </form> + </div> + + </div> + </div> + </div> + </div> + </div> +</body> +</html> +<?php +exit; + + } + + public static function hiddenRestapiFields($key,$value) + { + $hiddenRestapiField = ""; + $value2 = array(); + if(is_array($value)) { + foreach($value as $key2 => $value2) + { + if(is_array($value2)){ + self::hiddenRestapiFields($key."[".$key2."]",$value2); + } else { + $hiddenRestapiField = "<input type='hidden' name='".$key."[".$key2."]"."' value='".$value2."'>"; + } + } + }else{ + $hiddenRestapiField = "<input type='hidden' name='".$key."' value='".$value."'>"; + } + + echo $hiddenRestapiField; + } +} + diff --git a/src/MiniorangeApiAuthConstants.php b/src/MiniorangeApiAuthConstants.php new file mode 100644 index 0000000000000000000000000000000000000000..3f0d44c412525aec8107a9f056d4842d2a5c00c9 --- /dev/null +++ b/src/MiniorangeApiAuthConstants.php @@ -0,0 +1,21 @@ +<?php +/** + * @file + * Contains constants class. + */ + +/** + * @file + * This class represents constants used throughout project. + */ +namespace Drupal\rest_api_authentication; + +class MiniorangeApiAuthConstants { + + const BASE_URL = 'https://login.xecurify.com'; + const SITE_URL = 'https://plugins.miniorange.com'; + const PHP_CURL = 'http://php.net/manual/en/curl.installation.php'; + const DRUPAL_SITE = 'https://www.drupal.org'; + const CREATE_ACCOUNT = 'https://www.miniorange.com/businessfreetrial'; +} + diff --git a/src/MiniorangeApiAuthSupport.php b/src/MiniorangeApiAuthSupport.php new file mode 100644 index 0000000000000000000000000000000000000000..96a8322f0319d7ece044070bfb7743d7898d3496 --- /dev/null +++ b/src/MiniorangeApiAuthSupport.php @@ -0,0 +1,139 @@ +<?php + +namespace Drupal\rest_api_authentication; +use Drupal\rest_api_authentication\Utilities; +use Drupal\rest_api_authentication\MiniorangeApiAuthConstants; +use Exception; + +/** + * @file + * This class represents support information for customer. + */ +/** + * @file + * Contains miniOrange Support class. + */ +class MiniorangeApiAuthSupport { + public $email; + public $phone; + public $query; + public $plan; + + public function __construct($email, $phone, $query, $plan = '') { + $this->email = $email; + $this->phone = $phone; + $this->query = $query; + $this->plan = $plan; + + } + + /** + * Send support query. + */ + public function sendSupportQuery() + { + $modules_info = \Drupal::service('extension.list.module')->getExtensionInfo('rest_api_authentication'); + $modules_version = $modules_info['version']; + if ($this->plan == 'demo') { + $url = MiniorangeApiAuthConstants::BASE_URL . '/moas/api/notify/send'; + + $subject = "Demo request for Drupal - ".\Drupal::VERSION." REST API Authentication Free Module "; + $this->query = 'Demo required for - ' . $this->query; + + $customerKey = \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_id'); + $apikey = \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_api_key'); + if ($customerKey == '') { + $customerKey = "16555"; + $apikey = "fFd2XcvTGDemZvbw1bcUesNJWEqKbbUq"; + } + + $currentTimeInMillis = Utilities::get_timestamp(); + $stringToHash = $customerKey . $currentTimeInMillis . $apikey; + $hashValue = hash("sha512", $stringToHash); + + $content = '<div >Hello, <br><br>Company :<a href="' . $_SERVER['SERVER_NAME'] . '" target="_blank" >' . $_SERVER['SERVER_NAME'] . '</a><br><br>Phone Number:' . $this->phone . '<br><br>Email:<a href="mailto:' . $this->email . '" target="_blank">' . $this->email . '</a><br><br>Query:[Drupal- '.\Drupal::VERSION.' API Authentication Free | '.$modules_version.' ] ' . $this->query . '</div>'; + + $fields = array( + 'customerKey' => $customerKey, + 'sendEmail' => true, + 'email' => array( + 'customerKey' => $customerKey, + 'fromEmail' => $this->email, + 'fromName' => 'miniOrange', + 'toEmail' => 'drupalsupport@xecurify.com', + 'toName' => 'drupalsupport@xecurify.com', + 'subject' => $subject, + 'content' => $content + ), + ); + + $header = ['Content-Type' => 'application/json','Customer-Key' =>$customerKey, 'Timestamp'=> $currentTimeInMillis,'Authorization' =>$hashValue]; + } elseif($this->plan == 'trial'){ + $url = MiniorangeApiAuthConstants::BASE_URL . '/moas/api/notify/send'; + + $subject = "Trial request for Drupal - ".\Drupal::VERSION." REST API Authentication Module "; + $this->query = 'Demo required for: ' . $this->query; + + $customerKey = \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_id'); + $apikey = \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_api_key'); + if ($customerKey == '') { + $customerKey = "16555"; + $apikey = "fFd2XcvTGDemZvbw1bcUesNJWEqKbbUq"; + } + + $currentTimeInMillis = Utilities::get_timestamp(); + $stringToHash = $customerKey . $currentTimeInMillis . $apikey; + $hashValue = hash("sha512", $stringToHash); + + $content = '<div >Hello, <br><br>Company :<a href="' . $_SERVER['SERVER_NAME'] . '" target="_blank" >' . $_SERVER['SERVER_NAME'] . '</a><br><br>Phone Number:' . $this->phone . '<br><br>Email:<a href="mailto:' . $this->email . '" target="_blank">' . $this->email . '</a><br><br>Query:[Drupal- '.\Drupal::VERSION.' API Authentication Free | '.$modules_version.' ] ' . $this->query . '</div>'; + + $fields = array( + 'customerKey' => $customerKey, + 'sendEmail' => true, + 'email' => array( + 'customerKey' => $customerKey, + 'fromEmail' => $this->email, + 'fromName' => 'miniOrange', + 'toEmail' => 'drupalsupport@xecurify.com', + 'toName' => 'drupalsupport@xecurify.com', + 'subject' => $subject, + 'content' => $content + ), + ); + + $header = ['Content-Type' => 'application/json','Customer-Key' =>$customerKey, 'Timestamp'=> $currentTimeInMillis,'Authorization' =>$hashValue]; + + } else { + + $this->query = '[Drupal - '.\Drupal::VERSION.' REST API Authentication Free Module] <br>' . $this->query; + $fields = array( + 'company' => $_SERVER['SERVER_NAME'], + 'email' => $this->email, + 'phone' => $this->phone, + 'ccEmail' => 'drupalsupport@xecurify.com', + 'query' => $this->query, + ); + + $url = MiniorangeApiAuthConstants::BASE_URL . '/moas/rest/customer/contact-us'; + + $header = ['Content-Type'=>'application/json','charset'=> 'UTF-8','Authorization'=> 'Basic']; + + } + + $field_string = json_encode($fields); + + try{ + $response = \Drupal::httpClient()->post($url,['headers'=>$header,'body'=>$field_string,'verify'=>FALSE]); + return TRUE; + + }catch (Exception $exception){ + $error = array( + '%method' => 'sendSupportQuery', + '%file' => 'miniorange_oauth_client_support.php', + '%error' => $exception->getMessage(), + ); + \Drupal::logger('rest_api_authentication')->notice($error); + return FALSE; + } + } +} diff --git a/src/MiniorangeRestAPICustomer.php b/src/MiniorangeRestAPICustomer.php new file mode 100644 index 0000000000000000000000000000000000000000..74a0b1b10e278cca275b7412f2af03549d06a372 --- /dev/null +++ b/src/MiniorangeRestAPICustomer.php @@ -0,0 +1,185 @@ +<?php +/** + * @file + * Contains miniOrange Customer class. + */ + +/** + * @file + * This class represents configuration for customer. + */ +namespace Drupal\rest_api_authentication; +use Drupal\Core\Url; +use Drupal\rest_api_authentication\Utilities; +use Drupal\rest_api_authentication\MiniorangeApiAuthConstants; +use Exception; +use Symfony\Component\HttpFoundation\RedirectResponse; + + + +class MiniorangeRestAPICustomer { + + public $email; + + public $phone; + + public $customerKey; + + public $transactionId; + + public $password; + + public $otpToken; + + private $defaultCustomerId; + + private $defaultCustomerApiKey; + + /** + * Constructor. + */ + public function __construct($email, $password) { + $this->email = $email; + $this->password = $password; + $this->defaultCustomerId = "16555"; + $this->defaultCustomerApiKey = "fFd2XcvTGDemZvbw1bcUesNJWEqKbbUq"; + } + function verifyLicense($code) + { + $url = MiniorangeApiAuthConstants::BASE_URL . '/moas/api/backupcode/verify'; + + $customerKey = \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_id'); + $apiKey = \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_api_key'); + global $base_url; + + /* Current time in milliseconds since midnight, January 1, 1970 UTC. */ + $currentTimeInMillis = round(microtime(true) * 1000); + + /* Creating the Hash using SHA-512 algorithm */ + $stringToHash = $customerKey . number_format($currentTimeInMillis, 0, '', '') . $apiKey; + $hashValue = hash("sha512", $stringToHash); + + $fields = ''; + + $fields = array( + 'code' => $code, + 'customerKey' => $customerKey, + 'additionalFields' => array( + 'field1' => $base_url + ) + ); + + $header = ['Content-Type'=> 'application/json','Customer-Key'=>$customerKey,'Timestamp'=>number_format($currentTimeInMillis, 0, '', ''),'Authorization'=>$hashValue]; + + $field_string = json_encode($fields); + + try{ + $response = \Drupal::httpClient()->post($url,['header'=>$header,'body'=>$field_string,'verify'=>FALSE]); + }catch(Exception $exception){ + $error_msg = $exception->getMessage(); + echo 'Request Error:' . $error_msg; + exit(); + } + + return $response; + } + + /** + * Check if customer exists. + */ + public function checkCustomer() { + if (!Utilities::isCurlInstalled()) { + return json_encode(array( + "status" => 'CURL_ERROR', + "statusMessage" => '<a href="'.MiniorangeApiAuthConstants::PHP_CURL .'">PHP cURL extension</a> is not installed or disabled.', + )); + } + + $url = MiniorangeApiAuthConstants::BASE_URL . '/moas/rest/customer/check-if-exists'; + + $email = $this->email; + + $fields = array( + 'email' => $email, + ); + $field_string = json_encode($fields); + + $header = ['Content-Type'=>'application/json','charset'=>'UTF - 8','Authorization'=>'Basic']; + + try{ + $content = \Drupal::httpClient()->post($url,['headers'=>$header,'body'=>$field_string,'verify'=>FALSE]); + return $content->getBody(); + }catch (Exception $exception){ + $error = array( + '%method' => 'checkCustomer', + '%file' => 'customer_setup.php', + '%error' => $exception->getMessage(), + ); + \Drupal::logger('rest_api_authentication')->notice('Error at %method of %file: %error', $error); + return $exception->getMessage(); + } + } + + function updateStatus() + { + + $url = MiniorangeApiAuthConstants::BASE_URL . '/moas/api/backupcode/updatestatus'; + + $customerKey = \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_id'); + $apiKey = \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_api_key'); + $currentTimeInMillis = round(microtime(true) * 1000); + $stringToHash = $customerKey . number_format($currentTimeInMillis, 0, '', '') . $apiKey; + $hashValue = hash("sha512", $stringToHash); + $code = \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_license_key'); + $fields = array('code' => $code, 'customerKey' => $customerKey); + $field_string = json_encode($fields); + + $herder=['Content-Type'=>'application/json','Customer-Key'=>$customerKey,'Timestamp'=>number_format($currentTimeInMillis, 0, '', ''),'Authorization'=>$hashValue]; + + try{ + $response = \Drupal::httpClient()->post($url,['headers'=>$herder,'body'=>$field_string,'verify'=>FALSE]); + }catch (Exception $exception){ + $error_msg = $exception->getMessage(); + echo 'Request Error:' . $error_msg; + exit(); + } + return $response; + } + + /** + * Get Customer Keys. + */ + public function getCustomerKeys() { + if (!Utilities::isCurlInstalled()) { + return json_encode(array( + "apiKey" => 'CURL_ERROR', + "token" => '<a href="'.MiniorangeApiAuthConstants::PHP_CURL.'">PHP cURL extension</a> is not installed or disabled.', + )); + } + + $url = MiniorangeApiAuthConstants::BASE_URL . '/moas/rest/customer/key'; + + $email = $this->email; + $password = $this->password; + + $fields = array( + 'email' => $email, + 'password' => $password, + ); + $field_string = json_encode($fields); + + $header = ['Content-Type'=> 'application/json','charset'=>'UTF - 8','Authorization'=>'Basic']; + try{ + $content = \Drupal::httpClient()->post($url,['headers'=>$header,'body'=>$field_string,'verify'=>FALSE]); + return $content->getBody(); + }catch (Exception $exception){ + $error = array( + '%method' => 'getCustomerKeys', + '%file' => 'customer_setup.php', + '%error' => $exception->getMessage(), + ); + \Drupal::logger('rest_api_authentication')->notice('Error at %method of %file: %error', $error); + return $exception->getMessage(); + } + } +} diff --git a/src/PageCache/DisallowAPIRequests.php b/src/PageCache/DisallowAPIRequests.php new file mode 100644 index 0000000000000000000000000000000000000000..92ebdc084e9a1289115cfe61cfb03d8cc457e29e --- /dev/null +++ b/src/PageCache/DisallowAPIRequests.php @@ -0,0 +1,24 @@ +<?php + +namespace Drupal\rest_api_authentication\PageCache; + +use Drupal\Core\PageCache\RequestPolicyInterface; +use Symfony\Component\HttpFoundation\Request; + +/** + * Cache policy for pages served from basic auth. + * + * This policy disallows caching of requests that use basic_auth for security + * reasons. Otherwise responses for authenticated requests can get into the + * page cache and could be delivered to unprivileged users. + */ +class DisallowAPIRequests implements RequestPolicyInterface { + + /** + * {@inheritdoc} + */ + public function check(Request $request) { + return self::DENY; + } + +} diff --git a/src/Routing/RouteSubscriber.php b/src/Routing/RouteSubscriber.php new file mode 100644 index 0000000000000000000000000000000000000000..1a79fbb825bb001cc6f5776edca242187eacab03 --- /dev/null +++ b/src/Routing/RouteSubscriber.php @@ -0,0 +1,34 @@ +<?php + +namespace Drupal\rest_api_authentication\Routing; + +use Drupal\Core\Routing\RouteSubscriberBase; +use Symfony\Component\Routing\Route; +use Symfony\Component\Routing\RouteCollection; + +/** + * Listens to the dynamic route events. + */ +class RouteSubscriber extends RouteSubscriberBase { + /** + * {@inheritdoc} + */ + protected function alterRoutes(RouteCollection $collection) { + $route_login = $collection->get('user.login.http'); + $route_login->addOptions([ + '_auth' => [ + 'rest_api_authentication' + ], + ]); + } + + /** + * @param Route $route + * + * @return false|true + */ + private function restLoginRount(Route $route) { + $path = $route->getPath(); + return strpos($path,'/user/login?_format='); + } +} diff --git a/src/Utilities.php b/src/Utilities.php new file mode 100644 index 0000000000000000000000000000000000000000..0dc1028fca669c182eb80c576b93c19ad9303eae --- /dev/null +++ b/src/Utilities.php @@ -0,0 +1,163 @@ +<?php +/** + * @package miniOrange + * @subpackage Plugins + * @license GNU/GPLv3 + * @copyright Copyright 2015 miniOrange. All Rights Reserved. + * + * + * This file is part of miniOrange Drupal REST API module. + * + * miniOrange Drupal REST API modules is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * miniOrange Drupal REST API module is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with miniOrange REST API Authentication plugin. If not, see <http://www.gnu.org/licenses/>. + */ + +namespace Drupal\rest_api_authentication; +use Drupal\Core\Form\FormStateInterface; +use Drupal\rest_api_authentication\MiniorangeApiAuthConstants; +use Drupal\Core\Ajax\AjaxResponse; +use Drupal\Core\Ajax\OpenModalDialogCommand; +use GuzzleHttp\Exception\GuzzleException; +use Exception; + +class Utilities { + public static function generateRandom($length=30) { + $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + $charactersLength = strlen($characters); + $randomString = ''; + + for ($i = 0; $i < $length; $i++) { + $randomString .= $characters[rand(0, $charactersLength - 1)]; + } + return $randomString; + } + + public static function isCurlInstalled() { + return in_array('curl', get_loaded_extensions()); + } + + public static function openSupportRequestForm() { + $response = new AjaxResponse(); + $modal_form = \Drupal::formBuilder()->getForm('\Drupal\rest_api_authentication\Form\MiniornageAPIAuthnRequestSupport'); + $response->addCommand(new OpenModalDialogCommand('Support Request/Contact Us', $modal_form, ['width' => '40%'])); + return $response; + } + /** + * Sends support query + */ + public static function send_support_query($email, $phone, $query, $type){ + if(empty($email)||empty($query)){ + \Drupal::messenger()->addMessage(t('The <b><u>Email</u></b> and <b><u>Query</u></b> fields are mandatory.'), 'error'); + return; + } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) { + \Drupal::messenger()->addMessage(t('The email address <b><i>' . $email . '</i></b> is not valid.'), 'error'); + return; + } + $support = new MiniorangeApiAuthSupport($email, $phone, $query, $type); + $support_response =$support->sendSupportQuery(); + if ($support_response) { + $message = array( + '#type' => 'item', + '#markup' => t('Support query successfully sent. We will get back to you shortly.'), + ); + $ajax_form = new OpenModalDialogCommand('Thank you!', $message, ['width' => '50%']); + } else { + $error = array( + '#type' => 'item', + '#markup' => t('Error submitting the support query. Please send us your query at + <a href="mailto:drupalsupport@xecurify.com"> + drupalsupport@xecurify.com</a>.'), + ); + $ajax_form = new OpenModalDialogCommand('Error!', $error, ['width' => '50%']); + } + } + + /** + * This function is used to get the timestamp value + */ + public static function get_timestamp() { + $url = MiniorangeApiAuthConstants::BASE_URL . '/moas/rest/mobile/get-timestamp'; + $fields = []; + + $fieldString = is_string($fields) ? $fields : json_encode($fields); + + try{ + $response = \Drupal::httpClient()->post($url,['headers'=>[],'body'=>$fieldString,'verify'=>FALSE]); + $content = $response->getBody()->getContents(); + + }catch (Exception $exception){ + \Drupal::logger('rest_api_authentication')->notice('Error in sending curl Request'.$exception->getMessage()); + exit(); + } + if(empty( $content )){ + $currentTimeInMillis = round( microtime( true ) * 1000 ); + $currentTimeInMillis = number_format( $currentTimeInMillis, 0, '', '' ); + } + return empty( $content ) ? $currentTimeInMillis : $content; + } + + public static function getCustomerEmail(){ + $user = \Drupal::currentUser(); + $adminEmail = is_null(\Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_admin_email')) ? $user->getEmail() : \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_admin_email'); + return $adminEmail; + } + + public static function getUsersOS() { + + global $user_agent; + $user_agent = $_SERVER['HTTP_USER_AGENT']; + $operating_sysytem = "Unknown OS Platform"; + + $os_array = array( + '/windows nt 10/i' => 'Windows 10', + '/windows nt 6.3/i' => 'Windows 8.1', + '/windows nt 6.2/i' => 'Windows 8', + '/windows nt 6.1/i' => 'Windows 7', + '/windows nt 6.0/i' => 'Windows Vista', + '/windows nt 5.2/i' => 'Windows Server 2003/XP x64', + '/windows nt 5.1/i' => 'Windows XP', + '/windows xp/i' => 'Windows XP', + '/windows nt 5.0/i' => 'Windows 2000', + '/windows me/i' => 'Windows ME', + '/win98/i' => 'Windows 98', + '/win95/i' => 'Windows 95', + '/win16/i' => 'Windows 3.11', + '/macintosh|mac os x/i' => 'Mac OS X', + '/mac_powerpc/i' => 'Mac OS 9', + '/linux/i' => 'Linux', + '/ubuntu/i' => 'Ubuntu', + '/iphone/i' => 'iPhone', + '/ipod/i' => 'iPod', + '/ipad/i' => 'iPad', + '/android/i' => 'Android', + '/blackberry/i' => 'BlackBerry', + '/webos/i' => 'Mobile' + ); + + foreach ($os_array as $regex => $value) + if (preg_match($regex, $user_agent)) + $operating_sysytem = $value; + + return $operating_sysytem; + } + + public static function drupal_is_cli() + { + $server = \Drupal::request()->server; + $server_software = $server->get('SERVER_SOFTWARE'); + $server_argc = $server->get('argc'); + + return !isset($server_software) && (php_sapi_name() == 'cli' || (is_numeric($server_argc) && $server_argc > 0)) ? true : false; + } + +} diff --git a/src/advancedSettingsForm.php b/src/advancedSettingsForm.php new file mode 100644 index 0000000000000000000000000000000000000000..d4632156df2aa7c423aca296b55f95673dcf433f --- /dev/null +++ b/src/advancedSettingsForm.php @@ -0,0 +1,135 @@ +<?php + +namespace Drupal\rest_api_authentication; +use Drupal\Core\Form\FormStateInterface; +class AdvancedSettingsForm{ + public static function insertForm(array &$form, FormStateInterface $form_state){ + global $base_url; + $disabled = TRUE; + $form['advancedsettings'] = [ + '#type' => 'details', + '#title' => t('Advanced Settings'), + '#open' => TRUE, + '#group' => 'verticaltabs', + ]; + + $form['advancedsettings']['support_container_outline']['publisher'] = array( + '#markup' => '<b>ADVANCED SETTINGS:</b> These features are present in the <a href = "'.$base_url.'/admin/config/people/rest_api_authentication/auth_settings?tab=edit-upgrade-plans"><b>PREMIUM</b></a> version of the module<hr><br><div class="mo_rest_api_highlight_background_note_1">Need any help? Just send us a query and we will get back to you soon.<br /></div><br>', + ); + $form['advancedsettings']['support_container_outline']['custom_headers'] = array( + '#type' => 'details', + '#title' => t(' Custom Header '), + '#description' => 'This feature allows you to set custom headers for authentication. If you want to authenticate the Drupal REST APIs in a more secure way, you can set a custom Header.', + ); + $form['advancedsettings']['support_container_outline']['custom_headers']['div_key'] = array( + '#type' => 'textfield', + '#disabled' => $disabled, + '#id' => 'rest_api_authentication_token_key', + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('custom_header'), + '#title' => t('Custom header for authentication: '), + '#attributes' => array('style' => 'width:50%'), + ); + $form['advancedsettings']['support_container_outline']['custom_headers']['div_key3'] = array( + '#type' => 'submit', + '#button_type' => 'primary', + '#disabled' => $disabled, + '#value' => t('Save Configuration'), + '#submit' => array('::custom_header_submit'), + ); + + $form['advancedsettings']['support_container_outline']['token_expiry'] = array( + '#type' => 'details', + '#title' => t(' Token Expiry Configurations'), + '#description' => 'Eligible for OAuth 2.0 and JWT Authentication. JWT Token and the OAuth Access Token will be expired on the given time.', + ); + + $form['advancedsettings']['support_container_outline']['token_expiry']['access_token_expiry_time'] = array( + '#type' => 'textfield', + '#disabled' => $disabled, + '#title' => t('Access Token Expiry Time (In minutes): '), + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('token_expiry'), + '#attributes' => array('style' => 'width:50%'), + ); + $form['advancedsettings']['support_container_outline']['token_expiry']['support_container_outline'] = array( + '#type' => 'submit', + '#button_type' => 'primary', + '#disabled' => $disabled, + '#value' => t('Save Token Configuration'), + '#submit' => array('::token_expiry_submit'), + ); + + $form['advancedsettings']['support_container_outline']['list_ip'] = array( + '#type' => 'details', + '#title' => t(' White list & Blacklist Ip Addresses'), + '#description' => 'Given APIs will be publicly accessible from the all users.', + ); + $form['advancedsettings']['support_container_outline']['list_ip']['settings'] = array( + '#type' => 'radios', + '#disabled' => $disabled, + '#prefix' => '<hr>', + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('ip_access_type'), + '#title' => '', + '#options' => array( + 0 => t('Allowed IP Addresses'), + 1 => t('Blocked IP Addresses'), + ), + '#attributes' => array('class' => array('container-inline')), + ); + $form['advancedsettings']['support_container_outline']['list_ip']['ip_textarea'] = array( + '#type' => 'textarea', + '#disabled' => $disabled, + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('list_of_ips'), + '#title' => t('You can add the IP Addresses here: '), + '#attributes' => array('style' => 'width:100%','placeholder' => 'You can also add multiple APIs using a ; as a seperator'), + ); + $form['advancedsettings']['support_container_outline']['list_ip']['token_submit_key3'] = array( + '#type' => 'submit', + '#disabled' => $disabled, + '#button_type' => 'primary', + '#name'=>'submit', + '#value' => t('Save IP Configuration'), + '#submit' => array('::ip_restriction_submit'), + ); + + $form['advancedsettings']['support_container_outline']['list_apis'] = array( + '#type' => 'details', + '#title' => t(' Restrict custom APIs'), + '#description' => 'Given APIs will be restricted. You can and multipel APIs using ";" as a separator', + ); + $form['advancedsettings']['support_container_outline']['list_apis']['custom_api_textarea'] = array( + '#type' => 'textarea', + '#disabled' => $disabled, + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('list_of_apis'), + '#title' => t('You can add the APIs here: '), + '#attributes' => array('style' => 'width:100%','placeholder' => 'You can also add multiple APIs using a ; as a seperator'), + ); + $form['advancedsettings']['support_container_outline']['list_apis']['token_submit_key3'] = array( + '#type' => 'submit', + '#button_type' => 'primary', + '#disabled' => $disabled, + '#name'=>'submit', + '#value' => t('Save Configuration'), + ); + + $form['advancedsettings']['support_container_outline']['restrict_roles'] = array( + '#type' => 'details', + '#title' => t(' Role Based Restriction'), + '#description' => 'Restriction based on User Roles.', + ); + $form['advancedsettings']['support_container_outline']['restrict_roles']['api_textarea'] = array( + '#type' => 'textarea', + '#disabled' => $disabled, + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('list_of_role_restrictions'), + '#title' => t('You can add the APIs and roles here: '), + '#attributes' => array('style' => 'width:100%','placeholder' => 'You can also add multiple APIs->roles using a ; as a seperator'), + ); + $form['advancedsettings']['support_container_outline']['restrict_roles']['token_submit_key3'] = array( + '#type' => 'submit', + '#button_type' => 'primary', + '#disabled' => $disabled, + '#value' => t('Save Role Based Restrictions'), + '#submit' => array('::role_restriction_submit'), + ); + return $form; + } +} diff --git a/src/customerSetupForm.php b/src/customerSetupForm.php new file mode 100644 index 0000000000000000000000000000000000000000..d724e09727903a8599607b00f03b11c1c1c4d8db --- /dev/null +++ b/src/customerSetupForm.php @@ -0,0 +1,85 @@ +<?php + +namespace Drupal\rest_api_authentication; +use Drupal\Core\Form\FormStateInterface; +use Drupal\rest_api_authentication\MiniorangeApiAuthConstants; + +class CustomerSetupForm{ + public static function insertForm(array &$form, FormStateInterface $form_state){ + $current_status = \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_status'); + $form['customersetup'] = [ + '#type' => 'details', + '#title' => t('Register/Login'), + '#open' => TRUE, + '#group' => 'verticaltabs', + ]; + if ($current_status == 'PLUGIN_CONFIGURATION') { + $form['customersetup']['customer_setup_container_outline']['markup_support_1'] = array( + '#markup' => '<div class="mo_rest_welcome_message">Thank you for registering with miniOrange</div><br><br><h4>Your Profile: </h4>' + ); + $header = array( + 'email' => array( + 'data' => t('Customer Email') + ), + 'customerid' => array( + 'data' => t('Customer ID') + ), + 'token' => array( + 'data' => t('Token Key') + ), + 'apikey' => array( + 'data' => t('API Key') + ), + ); + + $options = []; + $options[0] = array( + 'email' => \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_admin_email'), + 'customerid' => \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_id'), + 'token' => \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_admin_token'), + 'apikey' => \Drupal::config('rest_api_authentication.settings')->get('rest_api_authentication_customer_api_key'), + ); + $form['customersetup']['customer_setup_container_outline']['customerinfo'] = array( + '#theme' => 'table', + '#header' => $header, + '#rows' => $options, + '#suffix' => '<br>' + ); + \Drupal::configFactory()->getEditable('rest_api_authentication.settings')->set('rest_api_authentication_status', $current_status)->save(); + } + else{ + $form['customersetup']['customer_setup_container_outline']['markup_support_1'] = array( + '#markup' => '<b>LOGIN TO YOUR ACCOUNT USING THE MINIORANGE CREDENTIALS</b><hr><br><div class="mo_rest_api_highlight_background_note_1">If you do not have an account with us yet, please click on the link <a href="'. MiniorangeApiAuthConstants::CREATE_ACCOUNT .'" target="_blank">here</a><br>In case you are facing any issues while trying to configure or use our module, just send us a request and we will get back to you right away.<br /></div><br>', + ); + + $form['customersetup']['customer_setup_container_outline']['rest_api_authentication_user_email'] = array( + '#type' => 'textfield', + '#id' => 'general_text_field', + '#title' => t('Email: '), + '#prefix' => '<br>', + '#attributes' => array('placeholder' => 'Enter your Email here','style' => 'width: 70%'), + ); + $form['customersetup']['customer_setup_container_outline']['rest_api_authentication_user_password'] = array( + '#type' => 'password', + '#id' => 'general_text_field', + '#title' => t('Password: '), + '#attributes' => array('placeholder' => 'Enter your Password here','style' => 'width: 70%'), + ); + + $form['customersetup']['customer_setup_container_outline']['rest_api_authentication_activate_module_submit'] = array( + '#type' => 'submit', + '#prefix' => '<table><tr><td>', + '#button_type' => 'primary', + '#suffix' => '</td><td>', + '#value' => t('Login'), + '#submit' => array('::activate_module_request'), + ); + $form['customersetup']['header_bottom_create_account'] = array( + '#markup' => '<a href="'.MiniorangeApiAuthConstants::CREATE_ACCOUNT.'" target="_blank"> Create a new account</a>', + '#suffix' => '</td></tr></table>', + ); + return $form; + } + return $form; + } +} diff --git a/src/requestForDemoForm.php b/src/requestForDemoForm.php new file mode 100644 index 0000000000000000000000000000000000000000..6117fde4b3082ba1c4414c2f08447f96e95ed1b2 --- /dev/null +++ b/src/requestForDemoForm.php @@ -0,0 +1,42 @@ +<?php + +namespace Drupal\rest_api_authentication; +use Drupal\Core\Form\FormStateInterface; +class RequestForDemoForm{ + public static function insertForm(array &$form, FormStateInterface $form_state){ + $form['demo'] = [ + '#type' => 'details', + '#title' => t('Support/Request For Demo'), + '#open' => TRUE, + '#group' => 'verticaltabs', + ]; + + $form['demo']['container_outline']['markup_support_1'] = array( + '#markup' => '<b>SUPPORT/REQUEST FOR DEMO:</b><hr><div class="mo_rest_api_highlight_background_note_1">Want to test our premium module before purchasing? Just send us a request from here and we will send you a 7 day free trial.</div><br>', + ); + $form['demo']['container_outline']['rest_api_authentication_email_address'] = array( + '#type' => 'textfield', + '#id' => 'general_text_field', + '#attributes' => array('placeholder' => 'Enter your Email','style' => 'width: 70%'), + ); + + $form['demo']['container_outline']['rest_api_authentication_phone_number'] = array( + '#type' => 'textfield', + '#id' => 'general_text_field', + '#attributes' => array('placeholder' => 'Enter your Phone Number','style' => 'width: 70%'), + ); + + $form['demo']['container_outline']['rest_api_authentication_demo_query'] = array( + '#type' => 'textarea', + '#id' => 'general_text_field', + '#attributes' => array('placeholder' => 'Please write your use case requirements here','style' => 'width: 70%'), + ); + $form['demo']['container_outline']['rest_api_authentication_demo_query_submit'] = array( + '#type' => 'submit', + '#button_type' => 'primary', + '#value' => t('Submit'), + '#submit' => array('::saved_demo_request'), + ); + return $form; + } +} diff --git a/src/setupAuthenticationForm.php b/src/setupAuthenticationForm.php new file mode 100644 index 0000000000000000000000000000000000000000..7105cb3356d760255e7d307d58f177d4e73d6b18 --- /dev/null +++ b/src/setupAuthenticationForm.php @@ -0,0 +1,200 @@ +<?php + +namespace Drupal\rest_api_authentication; +use Drupal\Core\Form\FormStateInterface; +use Drupal\rest_api_authentication\MiniorangeApiAuthConstants; + +class SetupAuthenticationForm{ + public static function insertForm(array &$form, FormStateInterface $form_state){ + global $base_url; + $form['markup_library_3'] = array( + '#attached' => array( + 'library' => array( + "rest_api_authentication/rest_api_authentication.basic_style_settings", + ) + ), + ); + $form['api_auth'] = [ + '#type' => 'details', + '#title' => t('Setup Authentication Method'), + '#open' => TRUE, + '#group' => 'verticaltabs', + ]; + + $form['api_auth']['mo_rest_api_authentication_authenticator']['head_text'] = array( + '#markup' => '<div><b>SELECT AUTHENTICATION METHOD OF YOUR CHOICE: </b><a class=" shift-right" target="_blank" href="'.MiniorangeApiAuthConstants::SITE_URL .'/drupal-api-authentication"><b>How To Setup?</b></a></div><hr><br><div class="mo_rest_api_highlight_background_note_1">Need any help? We can help you with configuring your API authentication method. Just send us a query and we will get back to you soon.</div>', + ); + $form['api_auth']['mo_rest_api_authentication_authenticator']['enable_authentication'] = array( + '#type' => 'checkbox', + '#title' => t('Enable Authentication'), + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('enable_authentication'), + '#description' => 'Select this checkbox to enable API Authentication ', + ); + + $form['api_auth']['mo_rest_api_authentication_authenticator']['whitelist_get_apis'] = array( + '#type' => 'checkbox', + '#disabled' => TRUE, + '#title' => t('Whitelist all GET APIs <a href = "'.$base_url.'/admin/config/people/rest_api_authentication/auth_settings?tab=edit-upgrade-plans"><b>[Premium]</b></a>'), + '#default_value' => FALSE, + '#description' => 'Select this checkbox to disable authentication for all GET calls ', + ); + + $form['api_auth']['mo_rest_api_authentication_authenticator']['save_basic_settings'] = array( + '#type' => 'submit', + '#button_type' => 'primary', + '#value' => t('Save Above Settings'), + '#submit' => array('::rest_api_authentication_save_basic_config'), + ); + + $form['api_auth']['mo_rest_api_authentication_authenticator']['settings']['active'] = array( + '#type' => 'radios', + '#prefix' => '<br>', + '#title' => '', + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('authentication_method'), + '#options' => array( + 0 => ('Basic Authentication'), + 1 => t('API Key Authentication'), + 2 => t('OAuth/Access Token <b><a href = "'.$base_url.'/admin/config/people/rest_api_authentication/auth_settings?tab=edit-upgrade-plans">[Premium]</b></a>'), + 3 => t('JWT Token <b><a href = "'.$base_url.'/admin/config/people/rest_api_authentication/auth_settings?tab=edit-upgrade-plans">[Premium]</b></a>'), + 4 => t('External IDP Token <b><a href = "'.$base_url.'/admin/config/people/rest_api_authentication/auth_settings?tab=edit-upgrade-plans">[Premium]</b></a>'), + ), + '#attributes' => array('class' => array('container-inline')), + ); + + $form['api_auth']['rest_api_authentication_method_submit'] = array( + '#type' => 'submit', + '#button_type' => 'primary', + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 0 ), ),), + '#value' => t('Select Method'), + '#submit' => array('::rest_api_authentication_save_basic_auth_conf'), + ); + + + $form['api_auth']['mo_rest_api_authentication_authenticator']['rest_api_authentication_ext_oauth'] = array( + '#type' => 'textfield', + '#id' => 'rest_api_authentication_token_key', + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 4 ), ),), + '#title' => t('User Info Endpoint: '), + '#disabled' => TRUE, + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('user_info_endpoint'), + '#attributes' => array('style' => 'width:100%'), + ); + $form['api_auth']['mo_rest_api_authentication_authenticator']['rest_api_authentication_ext_oauth_username'] = array( + '#type' => 'textfield', + '#disabled' => TRUE, + '#id' => 'rest_api_authentication_token_key', + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 4 ), ),), + '#title' => t('Username Attribute: '), + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('username_attribute'), + '#attributes' => array('style' => 'width:100%'), + ); + $form['api_auth']['rest_api_authentication_save_ext_oauth'] = array( + '#type' => 'submit', + '#disabled' => TRUE, + '#button_type' => 'primary', + '#value' => t('Save Configurations'), + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 4 ), ),), + '#submit' => array('::rest_api_authentication_save_ext_oauth'), + ); + + $form['api_auth']['mo_rest_api_authentication_authenticator']['rest_api_authentication_key'] = array( + '#type' => 'textfield', + '#id' => 'rest_api_authentication_token_key', + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 1 ), ),), + '#disabled' => TRUE, + '#title' => t('API Key required for Authentication: '), + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('api_token'), + '#attributes' => array('style' => 'width:100%'), + ); + $form['api_auth']['rest_api_authentication_generate_key'] = array( + '#type' => 'submit', + '#button_type' => 'primary', + '#value' => t('Generate API Key'), + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 1 ), ),), + '#submit' => array('::rest_api_authentication_generate_api_token'), + ); + + $form['api_auth']['rest_api_authentication_key_generate_all_keys'] = array( + '#type' => 'checkbox', + '#disabled' => TRUE, + '#title' => t('Generate separate API Keys for all Drupal users <a href = "'.$base_url.'/admin/config/people/rest_api_authentication/auth_settings?tab=edit-upgrade-plans"><b>[Premium]</b></a>'), + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 1 ), ),), + ); + $form['api_auth']['rest_api_authentication_key_generate_akey'] = array( + '#type' => 'checkbox', + '#disabled' => TRUE, + '#title' => t('Reset API Key for a specific Drupal user <a href = "'.$base_url.'/admin/config/people/rest_api_authentication/auth_settings?tab=edit-upgrade-plans"><b>[Premium]</b></a>'), + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 1 ), ),), + ); + + $form['api_auth']['mo_rest_api_authentication_authenticator']['rest_api_authentication_oauth_client_id'] = array( + '#type' => 'textfield', + '#id' => 'rest_api_authentication_token_key', + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 2 ), ),), + '#title' => t('Client ID: '), + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('oauth_client_id'), + '#attributes' => array('style' => 'width:100%'), + '#disabled' => 'true', + ); + $form['api_auth']['mo_rest_api_authentication_authenticator']['rest_api_authentication_oauth_client_secret'] = array( + '#type' => 'textfield', + '#id' => 'rest_api_authentication_token_key', + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 2 ), ),), + '#title' => t('Client Secret: '), + '#default_value' => \Drupal::config('rest_api_authentication.settings')->get('oauth_client_secret'), + '#attributes' => array('style' => 'width:100%'), + '#disabled' => 'true', + ); + $form['api_auth']['rest_api_authentication_generate_and_secret'] = array( + '#type' => 'submit', + '#disabled' => TRUE, + '#value' => t('Generate a new Client ID and Secret'), + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 2 ), ),), + '#submit' => array('::rest_api_authentication_generate_oauth_keys'), + ); + $form['api_auth']['rest_api_authentication_save_oauth_config'] = array( + '#type' => 'submit', + '#disabled' => TRUE, + '#button_type' => 'primary', + '#value' => t('Save Settings'), + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 2 ), ),), + '#submit' => array('::rest_api_authentication_save_oauth_token'), + ); + $form['api_auth']['rest_api_authentication_generate_id_token'] = array( + '#type' => 'submit', + '#button_type' => 'primary', + '#disabled' => TRUE, + '#value' => t('Save JWT Configuration'), + '#states' => array('visible' => array(':input[name = "active"]' => array('value' => 3 ), ),), + '#submit' => array('::rest_api_authentication_save_id_token'), + ); + $form['api_auth']['select_api_head_text'] = array( + '#markup' => '<br><br><b>APIs TO BE RESTRICTED: </b><a href = "'.$base_url.'/admin/config/people/rest_api_authentication/auth_settings?tab=edit-upgrade-plans"><b>[PREMIUM]</b></a><hr>', + ); + $form['api_auth']['head_api_options'] = array( + '#type' => 'checkbox', + '#title' => '<b><a target="_blank" href="'.MiniorangeApiAuthConstants::DRUPAL_SITE.'/docs/8/core/modules/rest">RESTful Web Services APIs</a></b> (Always specify the <b>?_format=</b> query argument, e.g. http://example.com/node/1?_format=json)', + '#default_value' => "1", + '#disabled' => true, + '#attributes' => array('class' => array('container-inline')), + ); + + $form['api_auth']['head_jsonapi_options'] = array( + '#type' => 'checkbox', + '#title' => '<b><a href="'.MiniorangeApiAuthConstants::DRUPAL_SITE.'/docs/core-modules-and-themes/core-modules/jsonapi-module" target="_blank">JSON:API module APIs</a></b> (Always specify the <b><u>/jsonapi/</u></b> in the API, e.g. http://example.com/jsonapi/node/article/{{article_uuid}})', + '#default_value' => "1", + '#disabled' => true, + '#attributes' => array('class' => array('container-inline')), + ); + + $form['api_auth']['head_customapi_options'] = array( + '#type' => 'checkbox', + '#title' => 'Any Other/Custom APIs', + '#default_value' => "0", + '#disabled' => true, + '#attributes' => array('class' => array('container-inline')), + ); + + return $form; + } +} diff --git a/src/upgradePlansForm.php b/src/upgradePlansForm.php new file mode 100644 index 0000000000000000000000000000000000000000..8c0a969853a7b0eb6fc8e9a391639da5dd941232 --- /dev/null +++ b/src/upgradePlansForm.php @@ -0,0 +1,119 @@ +<?php + +namespace Drupal\rest_api_authentication; +use Drupal\Core\Form\FormStateInterface; +use Drupal\rest_api_authentication\MiniorangeApiAuthConstants; + +class UpgradePlansForm{ + public static function insertForm(array &$form, FormStateInterface $form_state){ + global $base_url; + $form['markup_library_4'] = array( + '#attached' => array( + 'library' => array( + "rest_api_authentication/rest_api_authentication.style_settings", + ) + ), + ); + + $form['upgrade-plans'] = [ + '#type' => 'details', + '#title' => t('Upgrade Plans'), + '#open' => TRUE, + '#group' => 'verticaltabs', + ]; + + $form['upgrade-plans']['upgrade_container_outline']['licensing'] = array( + '#markup' =>'<html lang="en"> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <!-- Main Style --> + </head> + <body> + <!-- Pricing Table Section --> + <section id="pricing-table"> + <div> + <div> + <div class="pricing"> + <div> + <div class="pricing-table class_inline_1"> + <div class="pricing-header"> + <p class="pricing-title">Free</p> + <p class="pricing-rate"><sup>$</sup> 0</p> + <a href="#" disabled="disabled" class="btn-disabled button">Current Plan</a><br><br> + </div> + + <div class="pricing-list"> + <ul> + <li>Supports JSON API module</li> + <li>Supports default REST APIs</li> + <li>-</li> + <li>API Key Authentication</li> + <li>Basic Authentication</li> + <li>-</li> + <li>-</li> + <li>-</li> + <li>-</li> + <li>-</li> + <li>-</li> + <li>-</li> + <li>-</li> + <li>-</li> + <li>Basic Email Support</li> + </ul> + </div> + </div> + + <div class="pricing-table class_inline_1"> + <div class="pricing-header"> + <p class="pricing-title">Premium</p> + <p class="pricing-rate"><sup>$</sup> 399<sup>*</sup></p> + <a href="'.MiniorangeApiAuthConstants::BASE_URL.'/moas/login?redirectUrl='.MiniorangeApiAuthConstants::BASE_URL.'/moas/initializepayment&requestOrigin=drupal_rest_api_authentication_premium_plan" target="_blank" class="button">Upgrade Now</a><br><br> + </div> + <div class="pricing-list"> + <ul> + <li>Supports JSON API module</li> + <li>Supports default REST APIs</li> + <li>Supports restriction of custom APIs</li> + <li>API Key Authentication</li> + <li>Basic Authentication</li> + <li>Access Token Based Authentication</li> + <li>JWT Based Authentication</li> + <li>3rd Party/External IDP Token Based Authentication</li> + <li>Generate separate API Keys for every user</li> + <li>Custom Authentication Header</li> + <li>Configurable Token Expiry Time</li> + <li>Whitelist or Blacklist APIs</li> + <li>IP Address Based Restriction</li> + <li>Role Based Restriction</li> + <li>Premium GoTo Meeting Support</li> + </ul> + </div> + </div> + + </div> + </div> + </div> + </div> + </section> + <!-- Pricing Table Section End --> + </body> + </html>', + ); + $form['upgrade-plans']['upgrade_container_outline']['instr'] = array( + '#markup' => ' + <br> + The above mentioned cost is applicable for one instance only. Licenses are perpetual and include free version updates for the first 12 months. You can renew maintenance(version updates) after the first 12 months at 50% of the current license cost. We also provide various Support Plans which includes 12 months of support. + <br><br><br><b>10 Days Return Policy -</b><br><br> + At miniOrange, we want to ensure that you are 100% happy with your purchase. If the premium module you purchased is not working as advertised and you have attempted to resolve any issues with our support team, which could not get resolved, we will refund the whole amount given that you have a raised a refund request within the first 10 days of the purchase.<br><br>Please email us at <a href="mailto:drupalsupport@xecurify.com">drupalsupport@xecurify.com</a> for any queries.' + ); + + $config = \Drupal::configFactory()->getEditable('rest_api_authentication.settings'); + if(isset($_GET['tab'])){ + if($_GET['tab'] == 'edit-upgrade-plans'){ + $config->set('miniorange_rest_api_license_page_visited', "TRUE")->save(); + } + } + return $form; + } +}