apache-openid-2.0.1/COPYING0000644000000000000000000010451311344732416015211 0ustar rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. 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 them 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 prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. 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. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey 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; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. 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. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 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. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 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 state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 3 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, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program 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, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU 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. But first, please read . apache-openid-2.0.1/README0000644000000000000000000000745411344732416015044 0ustar rootroot00000000000000 = Apache OpenID module = This is a library that you can use with Apache web server [1] and mod_python [2] to enable OpenID [3] access control to web resources. [1] http://httpd.apache.org/ [2] http://www.modpython.org/ [3] http://openid.net/ == Configuration == To configure OpenID access control, you will only need to decide which users should be authorized for this content. You'll need to get a list of those URLs, separated by white space. You can either put them in the Apache configuration as the value for the PythonOption authorized-users directive or in a file that is pointed to by the PythonOption authorized-users-list-url directive. Other handlers can be written to use other OpenID extensions to manage access. An example which grants access based on Launchpad (http://launchpad.net/) team membership in included and can be used by setting the 'handler' option to 'openidteams'. The default setup for this module works best for protecting an entire directory on a Web server. When using this configuration, you should be able to just modify the example configuration below. When you're using this default configuration, the location of the login screen will default to '+login' within the root of the directory that you put the PythonAccessHandler directive. === General options === * debug Enable debug messages. Values: '0', '1' Default: '0' (off) * external-cookie-names Cookie names from your protected app to be deleted on logout. Values: Space-separated list of cookie names * handler The authentication handler to use. Values: 'openid', 'openidteams', others as implemented. Default: 'openid' * store-type The OpenID store type to use. Values: 'memory', 'file', others as implemented. Default: 'memory' * store-directory The location of the store directory if store-type is 'file'. Values: directory location on filesystem * template-path The location of the template directory for alternative templates. Values: directory location on filesystem === OpenID options === * allowed-op-list-url A file containing a list of OPs which support directed identity. Values: one per line, either 'http://hostname/' or 'http://hostname/=Label' * authorized-users A list of OpenIDs which can access the resources. Values: Space-separated list of OpenIDs * authorized-users-list-url A file containing a list of OpenIDs which can access the resources. Values: one per line === OpenID teams options === * authorized-teams A list of teams whose members can access the resources. Values: Space-separated list of OpenID teams * authorized-teams-list-url A file containing a list of teams whose members can access the resources. Values: one team name per line * team-cache-lifetime The time before a user's team membership should be re-checked. Values: time in seconds == Example .htaccess file == Most of this example .htaccess file can be used directly in a or block in any part of Apache configuration. Example config:: # This directive tells Apache to check for OpenID authentication before # continuing to serve the request. PythonAccessHandler apache_openid::protect # This directive tells the protection code which identifiers should be allowed # to access these resources. The format of the data is a text file containing # the identifiers. It can be any URL that is accessible to this server, # including a file:// URL. PythonOption authorized-users-list-url file:///my/directory/allowed-users.txt # You can also add authorized users inline in the apache config PythonOption authorized-users "http://me.example.com/ http://you.example.com/" # If you use both kinds of authorized user directive, both lists of users are # combined into a single list. == Providing custom templates == apache-openid-2.0.1/apache_openid/0000755000000000000000000000000011344732416016731 5ustar rootroot00000000000000apache-openid-2.0.1/apache_openid/__init__.py0000644000000000000000000000321411344732416021042 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . __all__ = ['action', 'handlers', 'logging', 'request', 'response', 'template'] from apache_openid import handlers from apache_openid.utils import Session from request import Request from response import Response def protect(apache_request): options = apache_request.get_options() if options.get('debug', '0') == '1': logging.debug_mode = True session = Session(apache_request, timeout=3600, lock=False) action_path = get_action_path(options, apache_request) request = Request(apache_request, action_path, session) response = Response(request, action_path, session) handler = handlers.Factory( request, response, options, session, action_path).get_handler(options.get('handler', 'openid')) try: return handler.protect() finally: session.save() def get_action_path(options, apache_request): return options.get('action-path', apache_request.hlist.location) apache-openid-2.0.1/apache_openid/action.py0000644000000000000000000000241511344732416020562 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from apache_openid.template import Template class Action(object): @property def template(self): try: return self._template except AttributeError: self._template = Template(self.request, self.response, self.session, self.options.get('template-path')) return self._template def __init__(self, request, response, session, consumer, options): self.request = request self.response = response self.session = session self.consumer = consumer self.options = options apache-openid-2.0.1/apache_openid/handlers/0000755000000000000000000000000011344732416020531 5ustar rootroot00000000000000apache-openid-2.0.1/apache_openid/handlers/__init__.py0000644000000000000000000000221111344732416022636 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . __all__ = ['factory', 'openid', 'openidteams'] from apache_openid import logging from apache_openid.handlers.factory import Factory, known_handlers def register_handler(name, handlerclass): logging.error("Registering handler: %s", name) if name in known_handlers.keys(): logging.error("Handler name exists: %s (%s)", name, handlerclass) else: known_handlers[name] = handlerclass from apache_openid.handlers import * apache-openid-2.0.1/apache_openid/handlers/factory.py0000644000000000000000000000276111344732416022560 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from apache_openid import logging known_handlers = {} class UnknownHandlerException(Exception): pass class Factory(object): def __init__(self, request, response, options, session, action_path): self.request = request self.response = response self.options = options self.session = session self.action_path = action_path def get_handler(self, requested_handler): logging.debug("Looking for handler: %s", requested_handler) for handler in known_handlers: logging.debug("Found handler: %s", handler) if handler == requested_handler: return known_handlers[handler](self.request, self.response, self.options, self.session, self.action_path) raise UnknownHandlerException() apache-openid-2.0.1/apache_openid/handlers/openid/0000755000000000000000000000000011344732416022007 5ustar rootroot00000000000000apache-openid-2.0.1/apache_openid/handlers/openid/__init__.py0000644000000000000000000000165611344732416024130 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . __all__ = ['actions', 'authenticator', 'handler', 'mixins'] from apache_openid.handlers import register_handler from apache_openid.handlers.openid.handler import OpenIDLoginHandler register_handler('openid', OpenIDLoginHandler) apache-openid-2.0.1/apache_openid/handlers/openid/actions.py0000644000000000000000000000147411344732416024027 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from login_action import LoginAction from logout_action import LogoutAction from return_action import ReturnAction apache-openid-2.0.1/apache_openid/handlers/openid/authenticator.py0000644000000000000000000000563011344732416025237 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import urllib import urlparse try: from openid.urinorm import urinorm except ImportError: # An OpenID library that does not yet have urinorm. Anything # before 2.0 should be in this state. Not normalizing URLs just # means that you have to be more careful about what you type when # you're listing the authorized URLs. from openid.oidutil import normalizeUrl as urinorm from apache_openid import logging class Authenticator(object): def __init__(self, request, options): self.request = request self.options = options def authenticate(self, openid): logging.debug("Checking auth for: %s" % openid) return (openid is not None and openid in self.authorized_urls) @property def authorized_urls(self): authorized_urls = [] if 'authorized-users' in self.options: authorized_urls.extend(self.get_authorized_urls_from_options()) if 'authorized-users-list-url' in self.options: url = self.options.get('authorized-users-list-url') authorized_urls.extend(self.get_authorized_urls_from_url(url)) return authorized_urls def get_authorized_urls_from_options(self): authorized_urls_raw = self.options.get('authorized-users') return self.parse_authorized_urls(authorized_urls_raw) def get_authorized_urls_from_url(self, url): try: url_handle = urllib.urlopen(url) data = url_handle.read() url_handle.close() return self.parse_authorized_urls(data) except IOError: logging.error('Failed to fetch authorized list URL %r', url) return [] def parse_authorized_urls(self, data, force_http=True): """Parse and normalize a string containing a whitespace-separated list of URLs""" urls = [] for s in data.split(): url = s.strip() if not url or url[0] == '#': continue if not force_http: urls.append(url) continue parsed = urlparse.urlparse(url) if not (parsed[0] and parsed[1]): url = 'http://' + url urls.append(urinorm(url)) return urls apache-openid-2.0.1/apache_openid/handlers/openid/handler.py0000644000000000000000000001335311344732416024003 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import os from apache_openid import logging from apache_openid.handlers.openid.authenticator import Authenticator from apache_openid.handlers.openid.actions import (LoginAction, LogoutAction, ReturnAction) from apache_openid.utils import OK, HTTP_FORBIDDEN, SERVER_RETURN from openid.consumer import consumer from openid.store import filestore, memstore class OpenIDLoginHandler(object): session_timeout = 60 * 60 * 24 * 7 # Time out sessions after a week actions = { '+login': LoginAction, '+logout': LogoutAction, '+return': ReturnAction, } @property def authenticator(self): try: return self._auth except AttributeError: self._auth = self._get_authenticator() return self._auth @property def consumer(self): try: return self._consumer except AttributeError: store_type = self.options.get('store-type', 'memory') store = StoreFactory(self.options).get_store(store_type) self._consumer = consumer.Consumer(self.session, store) return self._consumer @property def known_actions(self): return self.actions.keys() # Cache for authorized identities _authorized_cache = {} _max_authorized_cache_size = 100 def __init__(self, request, response, options, session, action_path): self.request = request self.response = response self.options = options self.session = session self.action_path = action_path def protect(self): """Decide how to handle the current request for a protected resource.""" if self.request.uri.endswith('favicon.ico'): # Ignore special case of "favicon.ico" which browsers request # automatically and will incorrectly set the session target. logging.debug("Allowed request for favicon.ico") return OK elif self.request.action is not None: # To enable us to overlay the handler on top of a normal directory, # we only set the python handler if it handles the requested action. logging.debug("Creating handler for %s", self.request.action) self.request.add_handler('PythonHandler', self.handle_request) return OK elif self.is_authenticated(): # If the user is authenticated, we make sure the protected content # isn't cached and set apache's REMOTE_USER value. logging.debug("Allowing user %s", self.request.cookied_user) self.request.user = self.request.cookied_user self.request.headers_out['Cache-Control'] = 'no-cache' return OK elif self.request.cookied_user is not None: # If the user is logged in and we get here then the user is not # entitled to access the protected resource. We log them out and # present a "Permission denied" message. logging.debug("Access denied for user %s" % self.request.cookied_user) self.response.login_redirect('denied', self.request.uri) elif self.request.method == 'GET': # If a protected resource is requested using GET then we redirect # the user to login, storing the requested URL. logging.debug("Access denied: %s. Forcing login", self.request.uri) self.response.login_redirect(None, self.request.uri) else: # It's not always safe to redirect non-GET requests so we just # present a "Permission denied" error. logging.debug("Access denied for non-GET request.") raise SERVER_RETURN, HTTP_FORBIDDEN def handle_request(self, request): """Dispatch to the appropriate access control action.""" for action in self.known_actions: if self.request.action == action: action = self.actions[action](self.request, self.response, self.session, self.consumer, self.options) return action.do() logging.error("Unknown OpenID access control action: %r " "(action_path=%r)", self.request.action, self.action_path) self.response.login_redirect() def is_authenticated(self): return self.authenticator.authenticate(self.request.cookied_user) def _get_authenticator(self): return Authenticator(self.request, self.options) class UnknownStoreException(Exception): pass class StoreFactory(object): def __init__(self, options): self.options = options def get_store(self, store_type): """Get the store for this request. If you want to use a different kind of store, change this function to support creating it. """ if store_type == 'file': store_dir = os.path.normpath(self.options['store-directory']) return filestore.FileOpenIDStore(store_dir) elif store_type == 'memory': return memstore.MemoryStore() else: # XXX: implement other store types (SQL...) raise UnknownStoreException() apache-openid-2.0.1/apache_openid/handlers/openid/login_action.py0000644000000000000000000000777011344732416025041 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from apache_openid import logging from apache_openid.action import Action from apache_openid.handlers.openid.mixins import ProvidersMixin from apache_openid.utils import FieldStorage from openid.association import Association from openid.fetchers import HTTPFetchingError from openid.yadis.discover import DiscoveryFailure class LoginAction(Action, ProvidersMixin): def do(self): """Show a login page for setting the OpenID cookie.""" openid = self.get_openid_identifier_from_request(self.request) messages = self.get_messages_from_session(self.session) if self.request.method == 'POST': try: return self.process_login_request(openid) except AssertionError: messages.append('empty') except (DiscoveryFailure, HTTPFetchingError): logging.debug("Discovery failed for %s", openid) messages.append('discovery') return self.template.render('login_page.html', {'messages': messages, 'openid_identifier': openid, 'allowed_ops': self.allowed_ops, 'target': self.session.get('target')}) def get_openid_identifier_from_request(self, request): form = FieldStorage(request) openid = form.getfirst('openid_identifier', self.request.cookied_user) if not openid and self.request.last_user: openid = self.request.last_user # Check that the requested identity is allowed if self.allowed_ops and not openid in self.allowed_ops.values(): openid = '' return openid def get_messages_from_session(self, session): message = session.get('message', None) if message is None: return [] else: return [message] def process_login_request(self, openid): assert openid auth_request = self.consumer.begin(openid) auth_request = self.add_openid_extensions(auth_request) self.store_op_for_endpoint(openid, auth_request.endpoint.server_url) if auth_request.shouldSendRedirect(): # Do the redirect to the OpenID server logging.debug("Redirecting to OP with GET") redirect_url = auth_request.redirectURL( self.request.server_url, self.request.action_url('return')) self.response.redirect(redirect_url) else: # use a form-based redirect logging.debug("Redirecting to OP with POST") form_html = auth_request.formMarkup( self.request.server_url, self.request.action_url('return'), form_tag_attrs={'id': 'openid_message'}) title = 'OpenID Authentication Required' return self.template.render('post_redirect.html', { 'title': title, 'id': 'openid_message', 'form': form_html}) def add_openid_extensions(self, auth_request): """This is a hook for other classes to use.""" return auth_request def store_op_for_endpoint(self, op, endpoint): """ Store a discovered op=>endpoint mapping for an allowed op """ store = self.consumer.consumer.store assoc = Association.fromExpiresIn(600, op, endpoint, 'HMAC-SHA1') if not '://' in op: op = 'http://' + op store.storeAssociation(op, assoc) apache-openid-2.0.1/apache_openid/handlers/openid/logout_action.py0000644000000000000000000000524011344732416025230 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from apache_openid.action import Action from apache_openid.utils import add_cookie, get_cookies class LogoutAction(Action): @property def external_cookie_names(self): try: return self.split_values(self.options.get('external-cookie-names')) except AssertionError: return [] def do(self): self.clear_user_session() self.clear_external_cookies() redirect_url = self.options.get('external-logout-url') if redirect_url is None: return self.template.render('logout_page.html') else: self.response.redirect(redirect_url) def clear_user_session(self): try: del self.request.cookied_user del self.request.last_user except KeyError: pass def clear_external_cookies(self): """Clear any cookies from external apps which are defined in the config This is useful when the application protected by Apache OpenID doesn't provide a mechanism to log out of OpenID as well as itself. Redirect requests for the application's logout URL should be handled by the OpenID logout handler. The configuration should define the names of the application's cookies. These will be deleted at the same time as the OpenID session. """ cookies = get_cookies(self.request) for name in self.external_cookie_names: if ':' in name: path, name = name.split(':', 1) else: path = '/' if name in cookies: add_cookie(self.request, name, '', expires=0, path=path) def split_values(self, data): """Parse a string containing whitespace-separated team names.""" assert data is not None values = [] for s in data.split(): val = s.strip() if not val or val[0] == '#': continue values.append(val) return values apache-openid-2.0.1/apache_openid/handlers/openid/mixins.py0000644000000000000000000000371111344732416023672 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import urllib from apache_openid import logging class ProvidersMixin(object): @property def allowed_ops(self): """Get OPs that can be selected for login using directed identity.""" try: return self._allowed_ops except AttributeError: return self.get_allowed_ops_from_url( self.options.get('allowed-op-list-url')) def get_allowed_ops_from_url(self, url): try: url_handle = urllib.urlopen(url) data = url_handle.read() url_handle.close() op_list = self.parse_allowed_ops(data) self._allowed_ops = op_list return self._allowed_ops except (AttributeError, IOError): logging.error('Failed to fetch allowed OP URL %r', url) return {} def parse_allowed_ops(self, data): """Parse a key=value string of OP URI's, separated by newlines.""" ops = {} for s in data.split('\n'): op = s.strip() if not op or op[0] == '#': continue if op.find('=') < 0: ops[op] = op else: op_parts = op.split('=') ops[op_parts[0].strip()] = op_parts[1].strip() return ops apache-openid-2.0.1/apache_openid/handlers/openid/return_action.py0000644000000000000000000000671511344732416025246 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from apache_openid import logging from apache_openid.action import Action from apache_openid.handlers.openid.mixins import ProvidersMixin from apache_openid.utils import FieldStorage from openid.consumer import consumer class ReturnAction(Action, ProvidersMixin): def do(self): """Handle a response from the OpenID server. Always redirects.""" auth_response = self.get_response(FieldStorage(self.request)) if auth_response is None: self.response.login_redirect(message='failure') elif auth_response.status == consumer.SUCCESS: self.on_success(auth_response) elif auth_response.status == consumer.CANCEL: self.response.login_redirect(message='cancel') elif auth_response.status == consumer.FAILURE: self.response.login_redirect(message='failure') elif auth_response.status == consumer.SETUP_NEEDED: self.response.login_redirect() else: assert False, auth_response.status def get_response(self, form): query = {} for k in form.keys(): query[k] = form.getfirst(k).decode('utf-8') return self.consumer.complete(query, self.request.action_url('return')) def on_success(self, auth_response): """Set the cookie and then redirect back to the target.""" op = self.fetch_op_for_endpoint(auth_response.endpoint.server_url) if op is None: # Not a trusted endpoint self.response.login_redirect('failure') else: logging.debug("OpenID success!") self.complete_login(auth_response) def fetch_op_for_endpoint(self, endpoint): """Retrieve the (trusted) op that led to a given endpoint, if any.""" store = self.consumer.consumer.store # If there are no allowed OPs specified, we should be OK with any if not self.allowed_ops: return True for op in self.allowed_ops.values(): assoc_handle = op if not '://' in op: assoc_handle = 'http://' + op fake_assoc = store.getAssociation(assoc_handle) if fake_assoc is None: continue if fake_assoc.handle == op and fake_assoc.secret == endpoint: return op def complete_login(self, auth_response): self.request.cookied_user = auth_response.identity_url self.request.last_user = auth_response.identity_url target = self.session.get('target') if target is None: logging.debug('session target not set. redirecting to default') self.response.redirect() else: logging.debug('redirecting to session target %r', target) self.session['target'] = None self.response.redirect(target) apache-openid-2.0.1/apache_openid/handlers/openidteams/0000755000000000000000000000000011344732416023041 5ustar rootroot00000000000000apache-openid-2.0.1/apache_openid/handlers/openidteams/__init__.py0000644000000000000000000000170211344732416025152 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . __all__ = ['actions', 'authenticator', 'handler', 'mixins'] from apache_openid.handlers import register_handler from apache_openid.handlers.openidteams.handler import OpenIDTeamsLoginHandler register_handler('openidteams', OpenIDTeamsLoginHandler) apache-openid-2.0.1/apache_openid/handlers/openidteams/actions.py0000644000000000000000000000404511344732416025056 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from apache_openid import logging from apache_openid.handlers.openid.actions import * from apache_openid.handlers.openidteams.mixins import CookiedTeamsMixin #from openid.extensions import teams from apache_openid.handlers.openidteams import teams class TeamsLoginAction(LoginAction, CookiedTeamsMixin): def add_openid_extensions(self, auth_request): # Request Launchpad teams information, if configured if len(self.authorized_teams) > 0: teams_request = teams.TeamsRequest(self.authorized_teams) auth_request.addExtension(teams_request) return auth_request class TeamsReturnAction(ReturnAction, CookiedTeamsMixin): def complete_login(self, response): if len(self.authorized_teams) > 0: teams_response = teams.TeamsResponse.fromSuccessResponse(response) logging.debug('Teams response: %r',teams_response.is_member) self.cookied_teams = teams_response.is_member logging.debug('do_return: cookied_teams: %r', self.cookied_teams) super(TeamsReturnAction, self).complete_login(response) class TeamsLogoutAction(LogoutAction, CookiedTeamsMixin): def do(self): try: del self.cookied_teams logging.debug("Deleted cookied teams") except KeyError: pass return super(TeamsLogoutAction, self).do() apache-openid-2.0.1/apache_openid/handlers/openidteams/authenticator.py0000644000000000000000000000417211344732416026271 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from apache_openid import logging from apache_openid.handlers.openid.authenticator import Authenticator from apache_openid.handlers.openidteams.mixins import CookiedTeamsMixin class TeamsAuthenticator(Authenticator, CookiedTeamsMixin): def __init__(self, request, options, session): super(TeamsAuthenticator, self).__init__(request, options) self.session = session def authenticate(self, openid): """Check to see if any of the cookied teams are authorized.""" if openid is None: return False elif len(self.authorized_teams) > 0: return self.check_team_entitlement(self.authorized_teams, self.cookied_teams) else: logging.debug('Team support disabled, or no authorized teams ' 'configured.') return super(TeamsAuthenticator, self).authenticate(openid) def check_team_entitlement(self, allowed_teams, user_teams): logging.debug("Authorized Teams: %r", ', '.join(allowed_teams)) logging.debug("Cookied Teams: %r", ', '.join(user_teams)) for team in user_teams: if team in allowed_teams: logging.debug('Allowed user %r - team %r', self.request.cookied_user, team) return True logging.error('Access denied to %r for %r (teams: %r)', self.request.uri, self.request.cookied_user, user_teams) return False apache-openid-2.0.1/apache_openid/handlers/openidteams/handler.py0000644000000000000000000000230511344732416025030 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from apache_openid.handlers.openid.handler import OpenIDLoginHandler from apache_openid.handlers.openidteams.actions import * from apache_openid.handlers.openidteams.authenticator import TeamsAuthenticator class OpenIDTeamsLoginHandler(OpenIDLoginHandler): actions = { '+login': TeamsLoginAction, '+logout': TeamsLogoutAction, '+return': TeamsReturnAction, } def _get_authenticator(self): return TeamsAuthenticator(self.request, self.options, self.session) apache-openid-2.0.1/apache_openid/handlers/openidteams/mixins.py0000644000000000000000000001417611344732416024733 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import datetime import urllib import urlparse from apache_openid import logging class SubstitutionMixin(object): def _substitutions(self): """A dictionary of substitutions. $-substitutions are allowed, using the CGI environment, plus the public attributes of the request object, plus session data, in that order of preference. """ substitutions = self.request.subprocess_env.copy() for attribute in dir(self.request): if attribute.startswith('_'): continue value = getattr(self.request, attribute) if isinstance(value, basestring): substitutions[attribute] = value substitutions.update(self.session) self.debug('substitutions: %r', substitutions) return substitutions class CookiedTeamsMixin(SubstitutionMixin): @property def cache_lifetime(self): """The team cache lifetime from the config options.""" cache_lifetime = self.options.get('team-cache-lifetime') if cache_lifetime is None: logging.error('team-cache-lifetime should be set explicitly. Using default for now.') cache_lifetime = 43200 try: cache_lifetime = int(cache_lifetime) except ValueError: logging.error('Bad team-cache-lifetime: %s', cache_lifetime) cache_lifetime = 43200 logging.debug('team-cache-lifetime: %s', cache_lifetime) return datetime.timedelta(seconds=cache_lifetime) def _get_cookied_teams(self): """Get the list of Launchpad teams for the current user. The cookied teams list is cached for a period of time, specified by the team-cache-lifetime option. """ # BarryWarsaw 18-Dec-2008 At one point I tried to use a separate class # to represent the cookied team cache, but that had several problems. # Because the session data is actually pickled into the dbm file, the # instance stored here must be picklable. However, in order to do # logging in the cache instance, you'd have to pass a hook into that # instance which would not be picklable (e.g. an instancemethod or the # Apache request object). So then you'd have to deal with the pickle # protocol and figure out a way to initialize that log hook when the # session is unpickled. Or forgo logging. Neither option is really # acceptable, so the choice was made to use a simpler inline cache. # However this means that we need to hijack assignment to # .cookied_teams in order to keep the cache consistent. team_cache = self.session.setdefault('cookied_teams', {}) # Evict expired cache items. Use .keys() to avoid # mutation-while-iterating exceptions. now = datetime.datetime.now() for team in team_cache.keys(): if team_cache[team] < now: logging.debug('Evicting cookied team: %s', team) del team_cache[team] return team_cache.keys() def _set_cookied_teams(self, teams): """Set the list of Launchpad teams for the current user. We pervert the meaning of assignment here to be extension. Use this instead of .extend() on self.cookied_teams because the latter will not be persistent. Practicality beats purity. """ expiration_date = datetime.datetime.now() + self.cache_lifetime team_cache = self.session.setdefault('cookied_teams', {}) team_cache.update(dict((team, expiration_date) for team in teams)) def _del_cookied_teams(self): """Delete the list of Launchpad teams for the current user.""" self.session.setdefault('cookied_teams', {}).clear() cookied_teams = property(_get_cookied_teams, _set_cookied_teams, _del_cookied_teams, _get_cookied_teams.__doc__) @property def authorized_teams(self): """Get all authorized teams for this request.""" authorized_teams = [] if 'authorized-teams' in self.options: authorized_teams.extend(self.get_authorized_teams_from_options()) if 'authorized-teams-list-url' in self.options: url = self.options.get('authorized-teams-list-url') parts = urlparse.urlparse(url) # Use the url scheme to determine how to get the team list. We # have a few custom ones (e.g. regexp: and xmlrpc:) and Python # itself provides most defaults through urllib. teams = self.get_authorized_teams_from_url(url) authorized_teams.extend(teams) return authorized_teams def get_authorized_teams_from_options(self): authorized_teams_raw = self.options.get('authorized-teams') return self.parse_authorized_teams(authorized_teams_raw) def get_authorized_teams_from_url(self, url): try: url_handle = urllib.urlopen(url) data = url_handle.read() url_handle.close() return self.parse_authorized_teams(data) except IOError: logging.error('Failed to fetch authorized list URL %r', url) return [] def parse_authorized_teams(self, data): """Parse a string containing whitespace-separated team names.""" teams = [] for s in data.split(): team = s.strip() if not team or team[0] == '#': continue teams.append(team) return teams apache-openid-2.0.1/apache_openid/handlers/openidteams/teams.py0000644000000000000000000003235211344732416024531 0ustar rootroot00000000000000# Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . """Team membership support for Launchpad. The primary form of communication between the RP and Launchpad is an OpenID authentication request. Our solution is to piggyback a team membership test onto this interaction. As part of an OpenID authentication request, the RP includes the following fields: openid.ns.lp: An OpenID 2.0 namespace URI for the extension. It is not strictly required for 1.1 requests, but including it is good for forward compatibility. It must be set to: http://ns.launchpad.net/2007/openid-teams openid.lp.query_membership: A comma separated list of Launchpad team names that the RP is interested in. As part of the positive assertion OpenID response, the following field will be provided: openid.ns.lp: (as above) openid.lp.is_member: A comma separated list of teams that the user is actually a member of. The list may be limited to those teams mentioned in the request. This field must be included in the response signature in order to be considered valid (as the response is bounced through the user's web browser, an unsigned value could be modified). @since: 2.1.1 """ from openid.message import registerNamespaceAlias, \ NamespaceAliasRegistrationError from openid.extension import Extension from openid import oidutil try: basestring #pylint:disable-msg=W0104 except NameError: # For Python 2.2 basestring = (str, unicode) #pylint:disable-msg=W0622 __all__ = [ 'TeamsRequest', 'TeamsResponse', 'ns_uri', 'supportsTeams', ] ns_uri = 'http://ns.launchpad.net/2007/openid-teams' try: registerNamespaceAlias(ns_uri, 'lp') except NamespaceAliasRegistrationError, e: oidutil.log('registerNamespaceAlias(%r, %r) failed: %s' % (ns_uri, 'lp', str(e),)) def supportsTeams(endpoint): """Does the given endpoint advertise support for Launchpad Teams? @param endpoint: The endpoint object as returned by OpenID discovery @type endpoint: openid.consumer.discover.OpenIDEndpoint @returns: Whether an lp type was advertised by the endpoint @rtype: bool """ return endpoint.usesExtension(ns_uri) class TeamsNamespaceError(ValueError): """The Launchpad teams namespace was not found and could not be created using the expected name (there's another extension using the name 'lp') This is not I{illegal}, for OpenID 2, although it probably indicates a problem, since it's not expected that other extensions will re-use the alias that is in use for OpenID 1. If this is an OpenID 1 request, then there is no recourse. This should not happen unless some code has modified the namespaces for the message that is being processed. """ def getTeamsNS(message): """Extract the Launchpad teams namespace URI from the given OpenID message. @param message: The OpenID message from which to parse Launchpad teams. This may be a request or response message. @type message: C{L{openid.message.Message}} @returns: the lp namespace URI for the supplied message. The message may be modified to define a Launchpad teams namespace. @rtype: C{str} @raise ValueError: when using OpenID 1 if the message defines the 'lp' alias to be something other than a Launchpad teams type. """ # See if there exists an alias for the Launchpad teams type. alias = message.namespaces.getAlias(ns_uri) if alias is None: # There is no alias, so try to add one. (OpenID version 1) try: message.namespaces.addAlias(ns_uri, 'lp') except KeyError, why: # An alias for the string 'lp' already exists, but it's # defined for something other than Launchpad teams raise TeamsNamespaceError(why[0]) # we know that ns_uri defined, because it's defined in the # else clause of the loop as well, so disable the warning return ns_uri #pylint:disable-msg=W0631 class TeamsRequest(Extension): """An object to hold the state of a Launchpad teams request. @ivar query_membership: A comma separated list of Launchpad team names that the RP is interested in. @type required: [str] @group Consumer: requestField, requestTeams, getExtensionArgs, addToOpenIDRequest @group Server: fromOpenIDRequest, parseExtensionArgs """ ns_alias = 'lp' def __init__(self, query_membership=None, lp_ns_uri=ns_uri): """Initialize an empty Launchpad teams request""" Extension.__init__(self) self.query_membership = [] self.ns_uri = lp_ns_uri if query_membership: self.requestTeams(query_membership) # Assign getTeamsNS to a static method so that it can be # overridden for testing. _getTeamsNS = staticmethod(getTeamsNS) def fromOpenIDRequest(cls, request): """Create a Launchpad teams request that contains the fields that were requested in the OpenID request with the given arguments @param request: The OpenID request @type request: openid.server.CheckIDRequest @returns: The newly created Launchpad teams request @rtype: C{L{TeamsRequest}} """ self = cls() # Since we're going to mess with namespace URI mapping, don't # mutate the object that was passed in. message = request.message.copy() self.ns_uri = self._getTeamsNS(message) args = message.getArgs(self.ns_uri) self.parseExtensionArgs(args) return self fromOpenIDRequest = classmethod(fromOpenIDRequest) def parseExtensionArgs(self, args, strict=False): """Parse the unqualified Launchpad teams request parameters and add them to this object. This method is essentially the inverse of C{L{getExtensionArgs}}. This method restores the serialized Launchpad teams request fields. If you are extracting arguments from a standard OpenID checkid_* request, you probably want to use C{L{fromOpenIDRequest}}, which will extract the lp namespace and arguments from the OpenID request. This method is intended for cases where the OpenID server needs more control over how the arguments are parsed than that method provides. >>> args = message.getArgs(ns_uri) >>> request.parseExtensionArgs(args) @param args: The unqualified Launchpad teams arguments @type args: {str:str} @param strict: Whether requests with fields that are not defined in the Launchpad teams specification should be tolerated (and ignored) @type strict: bool @returns: None; updates this object """ items = args.get('query_membership') if items: for team_name in items.split(','): try: self.requestTeam(team_name, strict) except ValueError: if strict: raise def allRequestedTeams(self): """A list of all of the Launchpad teams that were requested. @rtype: [str] """ return self.query_membership def wereTeamsRequested(self): """Have any Launchpad teams been requested? @rtype: bool """ return bool(self.allRequestedTeams()) def __contains__(self, team_name): """Was this team in the request?""" return team_name in self.query_membership def requestTeam(self, team_name, strict=False): """Request the specified team from the OpenID user @param team_name: the unqualified Launchpad team name @type team_name: str @param strict: whether to raise an exception when a team is added to a request more than once @raise ValueError: when strict is set and the team was requested more than once """ if strict: if team_name in self.query_membership: raise ValueError('That team has already been requested') else: if team_name in self.query_membership: return self.query_membership.append(team_name) def requestTeams(self, query_membership, strict=False): """Add the given list of teams to the request @param query_membership: The Launchpad teams request @type query_membership: [str] @raise ValueError: when a team requested is not a string or strict is set and a team was requested more than once """ if isinstance(query_membership, basestring): raise TypeError('Teams should be passed as a list of ' 'strings (not %r)' % (type(query_membership),)) for team_name in query_membership: self.requestTeam(team_name, strict=strict) def getExtensionArgs(self): """Get a dictionary of unqualified Launchpad teams arguments representing this request. This method is essentially the inverse of C{L{parseExtensionArgs}}. This method serializes the Launchpad teams request fields. @rtype: {str:str} """ args = {} if self.query_membership: args['query_membership'] = ','.join(self.query_membership) return args class TeamsResponse(Extension): """Represents the data returned in a Launchpad teams response inside of an OpenID C{id_res} response. This object will be created by the OpenID server, added to the C{id_res} response object, and then extracted from the C{id_res} message by the Consumer. @ivar data: The Launchpad teams data, an array. @ivar ns_uri: The URI under which the Launchpad teams data was stored in the response message. @group Server: extractResponse @group Consumer: fromSuccessResponse @group Read-only dictionary interface: keys, iterkeys, items, iteritems, __iter__, get, __getitem__, keys, has_key """ ns_alias = 'lp' def __init__(self, is_member=None, lp_ns_uri=ns_uri): Extension.__init__(self) if is_member is None: self.is_member = [] else: self.is_member = is_member self.ns_uri = lp_ns_uri def addTeam(self, team_name): if team_name not in self.is_member: self.is_member.append(team_name) def extractResponse(cls, request, is_member_str): """Take a C{L{TeamsRequest}} and a list of Launchpad team values and create a C{L{TeamsResponse}} object containing that data. @param request: The Launchpad teams request object @type request: TeamsRequest @param is_member: The Launchpad teams data for this response, as a list of strings. @type is_member: {str:str} @returns: a Launchpad teams response object @rtype: TeamsResponse """ self = cls() self.ns_uri = request.ns_uri self.is_member = is_member_str.split(',') return self extractResponse = classmethod(extractResponse) # Assign getTeamsNS to a static method so that it can be # overridden for testing _getTeamsNS = staticmethod(getTeamsNS) def fromSuccessResponse(cls, success_response, signed_only=True): """Create a C{L{TeamsResponse}} object from a successful OpenID library response (C{L{openid.consumer.consumer.SuccessResponse}}) response message @param success_response: A SuccessResponse from consumer.complete() @type success_response: C{L{openid.consumer.consumer.SuccessResponse}} @param signed_only: Whether to process only data that was signed in the id_res message from the server. @type signed_only: bool @rtype: TeamsResponse @returns: A Launchpad teams response containing the data that was supplied with the C{id_res} response. """ self = cls() self.ns_uri = self._getTeamsNS(success_response.message) if signed_only: args = success_response.getSignedNS(self.ns_uri) else: args = success_response.message.getArgs(self.ns_uri) if "is_member" in args: is_member_str = args["is_member"] self.is_member = is_member_str.split(',') #self.is_member = args["is_member"] return self fromSuccessResponse = classmethod(fromSuccessResponse) def getExtensionArgs(self): """Get the fields to put in the Launchpad teams namespace when adding them to an id_res message. @see: openid.extension """ ns_args = {'is_member': ','.join(self.is_member),} return ns_args apache-openid-2.0.1/apache_openid/logging.py0000644000000000000000000000254211344732416020734 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from apache_openid.utils import log_error debug_mode = False def debug(message, *args): """Write debugging output to the Apache error log. Output only occurs if this line appears in the configuration file: PythonOption debug 1 See OpenIDAccessRequest.error() for args """ if debug_mode: error(message, *args) def error(message, *args): """Write output to the Apache error log. :param message: The %-style string template. :type message: string :param args: An optional sequence of values to interpolate into the `message` template. :type args: A *-args tuple """ log_error(message % args) apache-openid-2.0.1/apache_openid/request.py0000644000000000000000000001244011344732416020774 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import time import urlparse from apache_openid import logging from apache_openid.utils import add_cookie, get_cookies class Request(object): auto_login_lifetime = 24 * 60 * 60 * 365 def __init__(self, request, action_path, session): self.request = request self.action_path = action_path self.session = session def action_url(self, action): """Generate a URL that performs the given action. This depends on knowing where the actions live. """ action_path = self.action_path if action_path.endswith('/'): action_path = action_path[:-1] return urlparse.urljoin(self.server_url, action_path) + "/+" + action def _get_cookied_user(self): user = self.session.get('cookied_user') logging.debug("Getting cookied user: %s", user) return user def _set_cookied_user(self, openid_identifier): logging.debug("Setting cookied user to %s", openid_identifier) self.session['cookied_user'] = openid_identifier def _del_cookied_user(self): del self.session['cookied_user'] def _get_last_user(self): cookies = get_cookies(self.request) cookie = cookies.get('mpopenid.last_user') if cookie is None: logging.debug('No last user') return None logging.debug('Got last user: %r', cookie.value) return cookie.value def _set_last_user(self, username): assert isinstance(username, basestring) expires = time.time() + self.auto_login_lifetime add_cookie(self.request, 'mpopenid.last_user', username, expires=expires) logging.debug('Set last user: %r', username) def _del_last_user(self): add_cookie(self.request, 'mpopenid.last_user', '', expires=0) logging.debug('Deleted last user') @property def uri(self): # request.request_uri and unparsed_uri # this may not always be giving the correct value! # Seems to miss the "/openid/" prefix when called # inside a directive. # The value in subprocess_env seems correct. #return urlparse.urljoin(self.server_url, self.request.unparsed_uri) request_url = self.request.subprocess_env['REQUEST_URI'] request_url = request_url.split('?') return urlparse.urljoin(self.server_url, request_url[0]) @property def action(self): action = self.uri.split('/').pop() logging.debug("Looking for %s", action) if action in ['+login', '+logout', '+return']:#self.handler.known_actions: logging.debug("Action %s found in URL %s", action, self.uri) return action else: return None @property def server_url(self): """Return the root URL of the server that is serving this request.""" host = self.request.hostname port = self.request.connection.local_addr[1] # Don't include the default port number in the URL if self.request.is_https(): default_port = 443 proto = 'https' else: default_port = 80 proto = 'http' if port == default_port: return '%s://%s/' % (proto, host) else: return '%s://%s:%s/' % (proto, host, port) def __getattribute__(self, name): if name in ['cookied_user', 'last_user']: return object.__getattribute__(self, '_get_%s' % name)() else: try: request = object.__getattribute__(self, 'request') if name.startswith('__') or name in dir(self): raise AttributeError else: return request.__getattribute__(name) except AttributeError: return object.__getattribute__(self, name) def __setattr__(self, name, value): if name in ['request', 'action_path', 'session']: object.__getattribute__(self, '__dict__')[name] = value elif name in ['cookied_user', 'last_user']: object.__getattribute__(self, '_set_%s' % name)(value) else: try: request = object.__getattribute__(self, 'request') if name.startswith('__') or name in dir(self): raise AttributeError else: request.__setattr__(name, value) except AttributeError: object.__getattribute__(self, '__dict__')[name] = value def __delattr__(self, name): if name in ['cookied_user', 'last_user']: object.__getattribute__(self, '_del_%s' % name)() apache-openid-2.0.1/apache_openid/response.py0000644000000000000000000000461711344732416021151 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from apache_openid import logging from apache_openid.request import Request from apache_openid.utils import DONE, HTTP_MOVED_TEMPORARILY, SERVER_RETURN class Response(Request): def __init__(self, request, action_path, session): self.apache_request = request.request super(Response, self).__init__(request, action_path, session) def login_redirect(self, message=None, target=None, logout=False): """Issue a 302 redirect to the OpenID login page.""" if target: logging.debug('Setting target: %r', target) self.session['target'] = target self.session['message'] = message self.session['logout'] = logout #self.handler.clear_user() self.redirect(self.request.action_url('login')) def redirect(self, url=None): # This function raises an exception, so it will halt anything # that calls it. This is probably what you want, but beware! #try: # util.redirect(self.request, url) #except IOError: # # Mask the symptom of body content being output # # too early. This is not a proper fix, but will # # at least avoid tracebacks. # raise apache.SERVER_RETURN, apache.DONE # The below will perform a request without printing # any default Apache method, but browser cookies # will also not be set on the first page load. #self.request.log_error("redirecting to: %r" % url) if url is None: url = self.request.action_path self.request.request.headers_out['location'] = url self.request.request.status = HTTP_MOVED_TEMPORARILY self.session.save() raise SERVER_RETURN, DONE apache-openid-2.0.1/apache_openid/run_tests.py0000755000000000000000000000170011344732416021332 0ustar rootroot00000000000000#!/usr/bin/env python # Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import os import sys import unittest module_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../')) sys.path.append(module_path) os.environ['APACHE_OPENID_MOCK'] = 'yes' unittest.main('apache_openid.tests') apache-openid-2.0.1/apache_openid/template.py0000644000000000000000000001243611344732416021124 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import os from apache_openid import logging from apache_openid.utils import OK from cgi import escape message_text = { 'empty': ('message', 'Enter an OpenID URL to continue'), 'cancel': ('message', 'Authorization cancelled'), 'bad_html': ('error', 'No OpenID information was found at that URL'), 'http_failed': ('error', 'There was an error communicating with the ' 'server'), 'failure': ('error', 'The server reported an error'), 'denied': ('error', 'Either you have not been granted access to this ' 'resource or your entitlement has timed out. Please try again.'), 'discovery': ('error', 'Failed to discover an OpenID server'), } class Template(object): def __init__(self, request, response, session, template_path): self.request = request self.response = response self.session = session self._template_path = template_path def render(self, template, values={}): if template == 'login_page.html': content = self.get_template(template) % self.fill_login_page(values) else: content = self.get_template(template) % values self.response.apache_request.content_type = 'text/html; charset=UTF-8' self.response.apache_request.set_content_length(len(content)) self.response.apache_request.write(content) self.session['message'] = None self.session.save() return OK def fill_login_page(self, values): """Generate the HTML for the login page.""" openid_identifier = values.get('openid_identifier') messages = values.get('messages') allowed_ops = values.get('allowed_ops') target = values.get('target') message_chunks = [] for name in messages: message_info = message_text.get(name) if message_info is None: message_info = ('error', 'An error occurred') chunk = "
%s
" % message_info message_chunks.append(chunk) if self.request.cookied_user: chunk = ("
You are currently logged " "in as %s. (logout)
" % (escape(self.request.cookied_user), escape(self.request.action_url('logout'), True))) message_chunks.append(chunk) message_html = '\n'.join(message_chunks) if target: resource = ( '
Authorization is required to access ' '%s
') % (target, escape(target)) else: resource = '' if not openid_identifier: openid_identifier = '' if len(allowed_ops) == 0: # use a text input box form_input = '

Enter your OpenID identity URL to continue.

' form_input += ('' % (openid_identifier,)) onload_js = 'document.oid_form.openid_identifier.focus();' elif len(allowed_ops) == 1: # use a hidden field for k in allowed_ops.keys(): form_input = ('' % (allowed_ops[k].decode('utf-8'),)) if target and not self.request.cookied_user and not messages: onload_js = ('document.getElementById(\'continue_btn\').style.visibility=\'hidden\'; ' + 'document.oid_form.submit();') else: onload_js = '' else: # use a dropdown list form_input = '

Enter your OpenID identity URL to continue.

' form_input += '' onload_js = '' return dict( action=escape(self.request.action_url('login'), True), resource=resource, title='OpenID Authentication Required', message=message_html, openid_identifier=escape(openid_identifier, True), form_input=form_input, onload=onload_js, ) def get_template(self, template): return file('%s/%s' % (self.template_path, template)).read() @property def template_path(self): if self._template_path is None: return os.path.join(os.path.dirname(__file__), 'templates') else: return self._template_path apache-openid-2.0.1/apache_openid/templates/0000755000000000000000000000000011344732416020727 5ustar rootroot00000000000000apache-openid-2.0.1/apache_openid/templates/login_page.html0000644000000000000000000000137611344732416023730 0ustar rootroot00000000000000 %(title)s

%(title)s

%(resource)s%(message)s
%(form_input)s
apache-openid-2.0.1/apache_openid/templates/logout_page.html0000644000000000000000000000107311344732416024123 0ustar rootroot00000000000000 Logged out

Logged out

You have been logged out.

apache-openid-2.0.1/apache_openid/templates/post_redirect.html0000644000000000000000000000103511344732416024462 0ustar rootroot00000000000000 %(title)s %(form)s apache-openid-2.0.1/apache_openid/tests/0000755000000000000000000000000011344732416020073 5ustar rootroot00000000000000apache-openid-2.0.1/apache_openid/tests/__init__.py0000644000000000000000000000140511344732416022204 0ustar rootroot00000000000000# Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from actions import * from authenticators import * from handlers import * from mixins import * apache-openid-2.0.1/apache_openid/tests/actions.py0000644000000000000000000001706211344732416022113 0ustar rootroot00000000000000# Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import os from unittest import TestCase from openid.consumer import consumer from openid.message import Message from openid.store.memstore import MemoryStore from apache_openid import get_action_path from apache_openid.handlers.openid.actions import (LoginAction, LogoutAction, ReturnAction) from apache_openid.handlers.openidteams.actions import (TeamsLoginAction, TeamsLogoutAction, TeamsReturnAction) from apache_openid.request import Request from apache_openid.response import Response from apache_openid.utils import FieldStorage, SERVER_RETURN from apache_openid.utils.mock import ApacheMockRequest, Options, Session __all__ = [ 'LoginActionTest', 'LogoutActionTest', 'ReturnActionTest', 'TeamsLoginActionTest', 'TeamsLogoutActionTest', 'TeamsReturnActionTest'] def create_mock_consumer(session): store = MemoryStore() _consumer = consumer.Consumer(session, store) return _consumer class ActionTestCase(TestCase): def setUp(self): self.apache_request = ApacheMockRequest() overrides = { 'authorized-teams': "canonical-isd-hackers bzr-core", 'action-path': "/openid", 'allowed-op-list-url': "file://%s" % os.path.abspath(os.path.join(os.path.dirname(__file__), 'allowed-ops.txt')), } self.options = Options(overrides) self.action_path = get_action_path(self.options, self.apache_request) self.session = Session() self.request = Request( self.apache_request, self.action_path, self.session) self.response = Response(self.request, self.action_path, self.session) self.consumer = create_mock_consumer(self.session) class FakeOpenIDRequest(object): extension = None def endpoint(self): pass endpoint.server_url = 'login.launchpad.net' def addExtension(self, extension): self.extension = extension class FakeOpenIDResponse(FakeOpenIDRequest): message = Message.fromPostArgs({'namesapces': ''}) identity_url = 'http://launchpad.net/~test' def getSignedNS(self, uri): return uri class LoginActionTest(ActionTestCase): def setUp(self): super(LoginActionTest, self).setUp() self.action = LoginAction( self.request, self.response, self.session, self.consumer, self.options) def test_get_openid_identifier_from_request(self): # FIXME: test with actual request data self.assertEqual( self.action.get_openid_identifier_from_request(self.request), '') def test_get_messages_from_session(self): # FIXME: test with actual messages self.assertEqual( self.action.get_messages_from_session(self.session), []) def test_process_login_request(self): # FIXME: test with actual openid identifier self.assertRaises( AssertionError, self.action.process_login_request, '') def test_add_openid_extensions(self): openid_request = FakeOpenIDRequest() modified_request = self.action.add_openid_extensions(openid_request) self.assertEqual(openid_request, modified_request) def test_store_op_for_endpoint(self): # FIXME: test with actual openid identifier openid_request = FakeOpenIDRequest() self.action.store_op_for_endpoint('login.launchpad.net', None) def test_do(self): # FIXME: test with POST data self.request.method = 'GET' self.action.do() class LogoutActionTest(ActionTestCase): def setUp(self): super(LogoutActionTest, self).setUp() self.action = LogoutAction( self.request, self.response, self.session, self.consumer, self.options) def test_external_cookie_names(self): # FIXME: test with actual 'external-cookie-names' option set self.assertEqual( self.action.external_cookie_names, []) def test_do(self): self.action.do() def test_clear_user_session(self): # FIXME: find a way to test if they were really del'ed self.action.clear_user_session() def test_clear_external_cookies(self): # FIXME: test with actual cookies self.action.clear_external_cookies() def test_split_values(self): values = self.action.split_values('a-cookie b-cookie c-cookie') self.assertEqual( values, ['a-cookie', 'b-cookie', 'c-cookie']) class ReturnActionTest(ActionTestCase): def setUp(self): super(ReturnActionTest, self).setUp() self.action = ReturnAction( self.request, self.response, self.session, self.consumer, self.options) self.openid_response = FakeOpenIDResponse() def test_do(self): self.assertRaises( SERVER_RETURN, self.action.do) def test_get_response(self): form = FieldStorage(self.request) self.assertEqual( self.action.get_response(form), None) def test_on_success(self): # FIXME: test both branches self.assertRaises( SERVER_RETURN, self.action.on_success, self.openid_response) def test_fetch_op_for_endpoint(self): self.assertEqual( self.action.fetch_op_for_endpoint(None), None) def test_complete_login(self): self.assertRaises( SERVER_RETURN, self.action.complete_login, self.openid_response) class TeamsLoginActionTest(ActionTestCase): def setUp(self): super(TeamsLoginActionTest, self).setUp() self.action = TeamsLoginAction( self.request, self.response, self.session, None, self.options) self.openid_request = FakeOpenIDRequest() def test_add_openid_extensions(self): modified_request = self.action.add_openid_extensions( self.openid_request) memberships_requested = modified_request.extension.query_membership self.assertEqual( memberships_requested, ['canonical-isd-hackers', 'bzr-core']) class TeamsLogoutActionTest(ActionTestCase): def setUp(self): super(TeamsLogoutActionTest, self).setUp() self.action = TeamsLogoutAction( self.request, self.response, self.session, None, self.options) def test_do(self): self.action.do() class TeamsReturnActionTest(ActionTestCase): def setUp(self): super(TeamsReturnActionTest, self).setUp() self.action = TeamsReturnAction( self.request, self.response, self.session, None, self.options) self.openid_response = FakeOpenIDResponse() def test_complete_login(self): self.assertRaises( SERVER_RETURN, self.action.complete_login, self.openid_response) self.assertEqual(self.apache_request.status, 302) self.assertEqual( self.apache_request.headers_out['location'], '/openid') apache-openid-2.0.1/apache_openid/tests/allowed-ops.txt0000644000000000000000000000003611344732416023061 0ustar rootroot00000000000000Launchpad=login.launchpad.net apache-openid-2.0.1/apache_openid/tests/authenticators.py0000644000000000000000000001430111344732416023501 0ustar rootroot00000000000000# Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import os from unittest import TestCase from apache_openid import get_action_path from apache_openid.handlers.openid.authenticator import Authenticator from apache_openid.handlers.openidteams.authenticator import TeamsAuthenticator from apache_openid.utils.mock import ApacheMockRequest, Options, Session from apache_openid.request import Request __all__ = ['AuthenticatorTest', 'TeamsAuthenticatorTest'] class AuthenticatorTestCase(TestCase): def setUp(self): self.apache_request = ApacheMockRequest() self.overrides = { 'authorized-teams': "canonical-isd-hackers bzr-core", 'action-path': "/openid", } self.options = Options(self.overrides) self.action_path = get_action_path(self.options, self.apache_request) self.session = Session() self.request = Request( self.apache_request, self.action_path, self.session) class AuthenticatorTest(AuthenticatorTestCase): def setUp(self): super(AuthenticatorTest, self).setUp() self.authenticator = Authenticator(self.request, self.options) def test_authenticate(self): self.assertEqual(self.authenticator.authenticate(None), False) self.assertEqual( self.authenticator.authenticate('https://login.launchpad.net/+id/1234567'), False) self.overrides['authorized-users'] = "https://login.launchpad.net/+id/1234567\n" self.options = Options(self.overrides) self.authenticator = Authenticator(self.request, self.options) self.assertEqual( self.authenticator.authenticate('https://login.launchpad.net/+id/1234567'), True) def test_authorized_urls(self): self.overrides['authorized-users'] = "https://login.launchpad.net/+id/abcdefg "\ "https://login.launchpad.net/+id/gfedcba" self.overrides['authorized-users-list-url'] = "file://%s" % os.path.abspath(os.path.join(os.path.dirname(__file__), 'authorized-users.txt')) self.options = Options(self.overrides) self.authenticator = Authenticator(self.request, self.options) self.assertEqual( self.authenticator.authorized_urls, [ 'https://login.launchpad.net/+id/abcdefg', 'https://login.launchpad.net/+id/gfedcba', 'https://login.launchpad.net/+id/1234567', 'https://login.launchpad.net/+id/7654321', ]) def test_get_authorized_urls_from_options(self): self.overrides['authorized-users'] = "https://login.launchpad.net/+id/1234567 "\ "https://login.launchpad.net/+id/7654321" self.options = Options(self.overrides) self.authenticator = Authenticator(self.request, self.options) self.assertEqual( self.authenticator.get_authorized_urls_from_options(), [ 'https://login.launchpad.net/+id/1234567', 'https://login.launchpad.net/+id/7654321', ]) def test_get_authorized_urls_from_url(self): url = "file://%s" % os.path.abspath(os.path.join(os.path.dirname(__file__), 'authorized-users.txt')) self.assertEqual( self.authenticator.get_authorized_urls_from_url(url), [ 'https://login.launchpad.net/+id/1234567', 'https://login.launchpad.net/+id/7654321', ]) def test_get_authorized_urls_from_url_error(self): url = 'http://www.non-existing-host.com/this/page/doesnt/exist/' self.assertEqual( self.authenticator.get_authorized_urls_from_url(url), []) def test_parse_authorized_urls(self): data = """https://login.launchpad.net/+id/1234567 #https://login.launchpad.net/+id/7654321 https://login.launchpad.net/+id/abcdefg """ self.assertEqual( self.authenticator.parse_authorized_urls(data), [ 'https://login.launchpad.net/+id/1234567', 'https://login.launchpad.net/+id/abcdefg', ]) class TeamsAuthenticatorTest(AuthenticatorTestCase): def setUp(self): super(TeamsAuthenticatorTest, self).setUp() self.session = Session() self.authenticator = TeamsAuthenticator( self.request, self.options, self.session) def test_check_team_entitlement(self): self.assertEqual( self.authenticator.check_team_entitlement([], []), False) self.assertEqual( self.authenticator.check_team_entitlement( ['test-team'], ['another-team']), False) self.assertEqual( self.authenticator.check_team_entitlement( ['test-team', 'another-team'], ['another-team']), True) def test_authenticate(self): self.assertEqual(self.authenticator.authenticate(None), False) self.authenticator.cookied_teams = ['ubuntumembers'] self.assertEqual( self.authenticator.authenticate( 'https://login.launchpad.net/+id/1234567'), False) self.authenticator.cookied_teams = ['bzr-core', 'motu'] self.assertEqual( self.authenticator.authenticate( 'https://login.launchpad.net/+id/1234567'), True) self.options = Options({}) self.authenticator = TeamsAuthenticator( self.request, self.options, self.session) self.assertEqual( self.authenticator.authenticate( 'https://login.launchpad.net/+id/1234567'), False) apache-openid-2.0.1/apache_openid/tests/authorized-teams.txt0000644000000000000000000000004311344732416024116 0ustar rootroot00000000000000ubuntumembers ubuntu-core-dev motu apache-openid-2.0.1/apache_openid/tests/authorized-users.txt0000644000000000000000000000012011344732416024142 0ustar rootroot00000000000000https://login.launchpad.net/+id/1234567 https://login.launchpad.net/+id/7654321 apache-openid-2.0.1/apache_openid/tests/handlers.py0000644000000000000000000000633611344732416022255 0ustar rootroot00000000000000# Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from unittest import TestCase from apache_openid import get_action_path from apache_openid.handlers.openid.handler import OpenIDLoginHandler from apache_openid.request import Request from apache_openid.response import Response from apache_openid.utils import DONE, HTTP_FORBIDDEN, OK, SERVER_RETURN from apache_openid.utils.mock import ApacheMockRequest, Options, Session class HandlerTestCase(TestCase): def setUp(self): self.apache_request = ApacheMockRequest() self.overrides = { 'action-path': "/openid/", } self.options = Options(self.overrides) self.action_path = get_action_path(self.options, self.apache_request) self.session = Session() self.request = Request( self.apache_request, self.action_path, self.session) self.response = Response( self.request, self.action_path, self.session) self.handler = OpenIDLoginHandler( self.request, self.response, self.options, None, None) def assertRaisesMessage(self, exc, call, msg): try: result = call() except Exception, e: self.assertEqual(isinstance(e, exc), True) self.assertEqual(e.message, msg) else: self.fail("No exception raised. Got a result instead: %s" % result) class OpenIDLoginHandlerTest(HandlerTestCase): def test_authenticator(self): self.assertEqual(getattr(self.handler, '_auth', None), None) authenticator = self.handler.authenticator self.assertNotEqual(getattr(self.handler, '_auth', None), None) def test_consumer(self): self.assertEqual(getattr(self.handler, '_consumer', None), None) consumer = self.handler.consumer self.assertNotEqual(getattr(self.handler, '_consumer', None), None) def test_known_actions(self): self.assertEqual( self.handler.known_actions, ['+logout', '+login', '+return']) def test_protect(self): self.assertRaisesMessage(SERVER_RETURN, self.handler.protect, DONE) def test_protect_favicon(self): self.handler.request.request.subprocess_env['REQUEST_URI'] = '/favicon.ico' self.assertEquals(self.handler.protect(), OK) def test_protect_post(self): self.handler.request.request.method = 'POST' self.assertRaisesMessage( SERVER_RETURN, self.handler.protect, HTTP_FORBIDDEN) def test_protect_cookied_user(self): self.handler.request.cookied_user = [] self.assertRaisesMessage( SERVER_RETURN, self.handler.protect, DONE) apache-openid-2.0.1/apache_openid/tests/mixins.py0000644000000000000000000001003011344732416021746 0ustar rootroot00000000000000# Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import datetime import os import unittest from apache_openid.handlers.openid.mixins import ProvidersMixin from apache_openid.handlers.openidteams.authenticator import TeamsAuthenticator from apache_openid.handlers.openidteams.mixins import CookiedTeamsMixin from apache_openid.utils.mock import Options, Session __all__ = ['CookiedTeamsMixinTest', 'ProvidersMixinTest', 'TeamsAuthenticatorMixinTest'] class CookiedTeamsMixinTest(unittest.TestCase): def setUp(self): self.mixin = CookiedTeamsMixin() overrides = { 'authorized-teams': "canonical-isd-hackers bzr-core", } self.mixin.options = Options(overrides) def test_cache_lifetime(self): self.assertEqual( self.mixin.cache_lifetime, datetime.timedelta(seconds=43200)) self.mixin.options = Options({'team-cache-lifetime': 'foobar'}) self.assertEqual( self.mixin.cache_lifetime, datetime.timedelta(seconds=43200)) def test_authorized_teams_from_options(self): self.assertEqual( self.mixin.get_authorized_teams_from_options(), ['canonical-isd-hackers', 'bzr-core']) def test_expiring_team_cache(self): self.mixin.session = Session() self.mixin.cookied_teams = ['ubuntumembers', 'motu'] sorted_teams = ['ubuntumembers', 'motu'] sorted_teams.sort() self.assertEqual( self.mixin.cookied_teams, sorted_teams) # Set expiry times back to the past self.mixin.session['cookied_teams']['motu'] = datetime.datetime.now() - datetime.timedelta(minutes=1) self.mixin.session['cookied_teams']['ubuntumembers'] = datetime.datetime.now() - datetime.timedelta(minutes=1) self.assertEqual( self.mixin.cookied_teams, []) class ProvidersMixinTest(unittest.TestCase): def setUp(self): self.mixin = ProvidersMixin() overrides = { 'allowed-op-list-url': "file://%s" % os.path.abspath(os.path.join(os.path.dirname(__file__), 'allowed-ops.txt')), } self.mixin.options = Options(overrides) def test_allowed_ops(self): self.assertEqual( self.mixin.allowed_ops, {'Launchpad': 'login.launchpad.net'}) class TeamsAuthenticatorMixinTest(unittest.TestCase): def setUp(self): overrides = { 'authorized-teams': "canonical-isd-hackers bzr-core", 'authorized-teams-list-url': "file://%s" % os.path.abspath(os.path.join(os.path.dirname(__file__), 'authorized-teams.txt')), } options = Options(overrides) self.authenticator = TeamsAuthenticator(None, options, None) def test_authorized_teams_from_url(self): self.assertEqual( self.authenticator.get_authorized_teams_from_url( self.authenticator.options.get('authorized-teams-list-url')), ['ubuntumembers', 'ubuntu-core-dev', 'motu']) def test_authorized_teams_from_url_error(self): url = 'http://www.non-existing-host.com/this/page/doesnt/exist/' self.assertEqual( self.authenticator.get_authorized_teams_from_url(url), []) def test_authorized_teams(self): self.assertEqual( self.authenticator.authorized_teams, ['canonical-isd-hackers', 'bzr-core', 'ubuntumembers', 'ubuntu-core-dev', 'motu']) apache-openid-2.0.1/apache_openid/utils/0000755000000000000000000000000011344732416020071 5ustar rootroot00000000000000apache-openid-2.0.1/apache_openid/utils/__init__.py0000644000000000000000000000305711344732416022207 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import os from apache_openid.utils.mock import MockUtil from apache_openid.utils.modpython import ModPythonUtil __all__ = ['FieldStorage', 'Session', 'DONE', 'HTTP_FORBIDDEN', 'HTTP_MOVED_TEMPORARILY', 'OK', 'SERVER_RETURN', 'add_cookie', 'get_cookies', 'log_error'] if 'APACHE_OPENID_MOCK' in os.environ: utils_obj = MockUtil() else: utils_obj = ModPythonUtil() # Class definitions FieldStorage = utils_obj.cls_field_storage() Session = utils_obj.cls_session() # Const definitions DONE = utils_obj.const_done() HTTP_FORBIDDEN = utils_obj.const_http_forbidden() HTTP_MOVED_TEMPORARILY = utils_obj.const_http_moved_temporarily() OK = utils_obj.const_ok() SERVER_RETURN = utils_obj.const_server_return() # Function definitions add_cookie = utils_obj.func_add_cookie() get_cookies = utils_obj.func_get_cookies() log_error = utils_obj.func_log_error() apache-openid-2.0.1/apache_openid/utils/baseutil.py0000644000000000000000000000257511344732416022264 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . class BaseUtil(object): def cls_field_storage(self): raise NotImplementedError def cls_session(self): raise NotImplementedError def const_done(self): raise NotImplementedError def const_http_forbidden(self): raise NotImplementedError def const_http_moved_temporarily(self): raise NotImplementedError def const_ok(self): raise NotImplementedError def const_server_return(self): raise NotImplementedError def func_add_cookie(self): raise NotImplementedError def func_get_cookies(self): raise NotImplementedError def func_log_error(self): raise NotImplementedError apache-openid-2.0.1/apache_openid/utils/mock.py0000644000000000000000000000637411344732416021406 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . from apache_openid.utils.baseutil import BaseUtil DONE = -2 HTTP_FORBIDDEN = 403 HTTP_MOVED_TEMPORARILY = 302 OK = 0 class SERVER_RETURN(Exception): pass class FieldStorage(object): def __init__(self, req): self.request = req def getfirst(self, key, default=None): return default def keys(self): return [] class Options(object): defaults = {} def __init__(self, overrides=None): if overrides is None: overrides = {} self.overrides = overrides def __getitem__(self, index): value = self.overrides.get(index) if value is not None: return value else: return self.defaults[index] def __setitem__(self, index, value): self.overrides[index] = value def __delitem__(self, index): del self.overrides[index] def __len__(self): return len(self.overrides) def __contains__(self, item): return item in self.overrides def get(self, index, default=None): try: return self.__getitem__(index) except KeyError: return default class ApacheMockRequest(object): def __init__(self): self.buf = '' self.content_type = None self.headers_out = {} self.hostname = 'localhost' self.method = 'GET' self.subprocess_env = { 'REQUEST_URI': '', } def connection(self): pass connection.local_addr = ('localhost', '80') def hlist(self): pass hlist.location = None def is_https(self): return False def set_content_length(self, length): pass def write(self, string): self.buf = string class Session(dict): def save(self): pass def add_cookie(req, cookie, value='', **kw): pass def get_cookies(req): cookies = {} return cookies def log_error(error_string): print "log_error(): %s" % error_string class MockUtil(BaseUtil): def cls_field_storage(self): return FieldStorage def cls_session(self): return Session def const_done(self): return DONE def const_http_forbidden(self): return HTTP_FORBIDDEN def const_http_moved_temporarily(self): return HTTP_MOVED_TEMPORARILY def const_ok(self): return OK def const_server_return(self): return SERVER_RETURN def func_add_cookie(self): return add_cookie def func_get_cookies(self): return get_cookies def func_log_error(self): return log_error apache-openid-2.0.1/apache_openid/utils/modpython.py0000644000000000000000000000313711344732416022470 0ustar rootroot00000000000000# Copyright (C) 2005 JanRain, Inc. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import os try: from mod_python import apache, util, Cookie, Session except ImportError: if 'APACHE_OPENID_MOCK' in os.environ: pass else: raise from apache_openid.utils.baseutil import BaseUtil class ModPythonUtil(BaseUtil): def cls_field_storage(self): return util.FieldStorage def cls_session(self): return Session.Session def const_done(self): return apache.DONE def const_http_forbidden(self): return apache.HTTP_FORBIDDEN def const_http_moved_temporarily(self): return apache.HTTP_MOVED_TEMPORARILY def const_ok(self): return apache.OK def const_server_return(self): return apache.SERVER_RETURN def func_add_cookie(self): return Cookie.add_cookie def func_get_cookies(self): return Cookie.get_cookies def func_log_error(self): return apache.log_error apache-openid-2.0.1/examples/0000755000000000000000000000000011344732416015770 5ustar rootroot00000000000000apache-openid-2.0.1/examples/cookie/0000755000000000000000000000000011344732416017241 5ustar rootroot00000000000000apache-openid-2.0.1/examples/cookie/apache.conf0000644000000000000000000000062411344732416021333 0ustar rootroot00000000000000 SetHandler mod_python PythonAccessHandler apache_openid::protect PythonOption handler openid PythonOption store-type file PythonOption store-directory /tmp/apache_openid PythonOption authorized-users-list-url file:///var/www/apache_openid/openid/openids.txt PythonOption external-cookie-names /apache_openid/cookie/:openidcookie apache-openid-2.0.1/examples/cookie/success.html0000644000000000000000000000100111344732416021567 0ustar rootroot00000000000000 OpenID authentication successful You have been successfully authenticated. A cookie named openidcookie was stored. After clicking on the Logout link, that cookie will be deleted. Logout apache-openid-2.0.1/examples/index.html0000644000000000000000000000654111344732416017773 0ustar rootroot00000000000000 Apache-OpenID use-cases

Apache-OpenID use-cases

Remove cookies on logout

Because most web applications store authentication details in cookies, it is useful to have an option to remove them on logout.

PythonOption external-cookie-names /apache_openid/cookie/:openidcookie

Test here

Simple OpenID authentication

Authentication is allowed only for certain users.

Inline option

PythonOption authorized-users "%(authorized_users)s"

Test here

URL

PythonOption authorized-users-list-url file:///tmp/apache_openid/examples/openid/openids.txt

Contents of openids.txt:

%(authorized_users_lines)s

Test here

OpenID Provider (OP) options

No provider configured

The simple OpenID authentication use-cases have no OPs configured, so you can enter any OpenID URLs on authentication.

One provider configured

If only one OP is configured, the authentication mechanism automatically redirects the user to that OP, so the whole process will be faster.

PythonOption allowed-op-list-url file:///var/www/apache_openid/ops/op-launchpad.txt
Contents of op-launchpad.txt:
Launchpad=login.launchpad.net

Test here

Several providers configured

As the first step of the authentication process, a drop-down box is shown, where you can select through which provider you'd like to authenticate.

PythonOption allowed-op-list-url file:///var/www/apache_openid/ops/op-list.txt
Contents of op-list.txt:
Launchpad=login.launchpad.net
MyOpenID=myopenid.com

Test here

Redirect to external site after logout

By default a static page is displayed after logging out. However, it's possible to configure an URL where the user will be redirected after logging out.

PythonOption external-logout-url http://www.ubuntu.com/

Test here

Authentication based on Launchpad team membership

Inline option

PythonOption authorized-teams "%(authorized_teams)s"

Test here

URL

PythonOption authorized-teams-list-url file:///var/www/apache_openid/teams/teams.txt

Contents of teams.txt:

%(authorized_teams_lines)s

Test here

apache-openid-2.0.1/examples/openid/0000755000000000000000000000000011344732416017246 5ustar rootroot00000000000000apache-openid-2.0.1/examples/openid/inline/0000755000000000000000000000000011344732416020524 5ustar rootroot00000000000000apache-openid-2.0.1/examples/openid/inline/apache.conf0000644000000000000000000000045511344732416022620 0ustar rootroot00000000000000 SetHandler mod_python PythonAccessHandler apache_openid::protect PythonOption handler openid PythonOption store-type file PythonOption store-directory /tmp/apache_openid PythonOption authorized-users "%(authorized_users)s" apache-openid-2.0.1/examples/openid/inline/success.html0000644000000000000000000000031211344732416023056 0ustar rootroot00000000000000 OpenID authentication successful You have been successfully authenticated with pre-configured inline OpenID. Logout apache-openid-2.0.1/examples/openid/openids.txt0000644000000000000000000000000011344732416021436 0ustar rootroot00000000000000apache-openid-2.0.1/examples/openid/url/0000755000000000000000000000000011344732416020050 5ustar rootroot00000000000000apache-openid-2.0.1/examples/openid/url/apache.conf0000644000000000000000000000051511344732416022141 0ustar rootroot00000000000000 SetHandler mod_python PythonAccessHandler apache_openid::protect PythonOption handler openid PythonOption store-type file PythonOption store-directory /tmp/apache_openid PythonOption authorized-users-list-url file:///var/www/apache_openid/openid/openids.txt apache-openid-2.0.1/examples/openid/url/success.html0000644000000000000000000000031511344732416022405 0ustar rootroot00000000000000 OpenID authentication successful You have been successfully authenticated with pre-configured URL-based OpenID. Logout apache-openid-2.0.1/examples/ops/0000755000000000000000000000000011344732416016571 5ustar rootroot00000000000000apache-openid-2.0.1/examples/ops/one/0000755000000000000000000000000011344732416017352 5ustar rootroot00000000000000apache-openid-2.0.1/examples/ops/one/apache.conf0000644000000000000000000000064211344732416021444 0ustar rootroot00000000000000 SetHandler mod_python PythonAccessHandler apache_openid::protect PythonOption handler openid PythonOption store-type file PythonOption store-directory /tmp/apache_openid PythonOption allowed-op-list-url file:///var/www/apache_openid/ops/op-launchpad.txt PythonOption authorized-users-list-url file:///var/www/apache_openid/openid/openids.txt apache-openid-2.0.1/examples/ops/one/success.html0000644000000000000000000000030311344732416021704 0ustar rootroot00000000000000 OpenID authentication successful You have been successfully authenticated with one OP pre-configured. Logout apache-openid-2.0.1/examples/ops/op-launchpad.txt0000644000000000000000000000003611344732416021704 0ustar rootroot00000000000000Launchpad=login.launchpad.net apache-openid-2.0.1/examples/ops/op-list.txt0000644000000000000000000000006411344732416020721 0ustar rootroot00000000000000Launchpad=login.launchpad.net MyOpenID=myopenid.com apache-openid-2.0.1/examples/ops/several/0000755000000000000000000000000011344732416020232 5ustar rootroot00000000000000apache-openid-2.0.1/examples/ops/several/apache.conf0000644000000000000000000000064111344732416022323 0ustar rootroot00000000000000 SetHandler mod_python PythonAccessHandler apache_openid::protect PythonOption handler openid PythonOption store-type file PythonOption store-directory /tmp/apache_openid PythonOption allowed-op-list-url file:///var/www/apache_openid/ops/op-list.txt PythonOption authorized-users-list-url file:///var/www/apache_openid/openid/openids.txt apache-openid-2.0.1/examples/ops/several/success.html0000644000000000000000000000030611344732416022567 0ustar rootroot00000000000000 OpenID authentication successful You have been successfully authenticated with a few OPs pre-configured. Logout apache-openid-2.0.1/examples/redirect/0000755000000000000000000000000011344732416017571 5ustar rootroot00000000000000apache-openid-2.0.1/examples/redirect/apache.conf0000644000000000000000000000060711344732416021664 0ustar rootroot00000000000000 SetHandler mod_python PythonAccessHandler apache_openid::protect PythonOption handler openid PythonOption store-type file PythonOption store-directory /tmp/apache_openid PythonOption external-logout-url http://www.ubuntu.com/ PythonOption authorized-users-list-url file:///var/www/apache_openid/openid/openids.txt apache-openid-2.0.1/examples/redirect/success.html0000644000000000000000000000041311344732416022125 0ustar rootroot00000000000000 OpenID authentication successful You have been successfully authenticated. After clicking on the Logout link, you will be redirected to an external website. Logout apache-openid-2.0.1/examples/teams/0000755000000000000000000000000011344732416017101 5ustar rootroot00000000000000apache-openid-2.0.1/examples/teams/inline/0000755000000000000000000000000011344732416020357 5ustar rootroot00000000000000apache-openid-2.0.1/examples/teams/inline/apache.conf0000644000000000000000000000061111344732416022445 0ustar rootroot00000000000000 SetHandler mod_python PythonAccessHandler apache_openid::protect PythonOption handler openidteams PythonOption store-type file PythonOption store-directory /tmp/apache_openid PythonOption allowed-op-list-url file:///var/www/apache_openid/ops/op-launchpad.txt PythonOption authorized-teams "%(authorized_teams)s" apache-openid-2.0.1/examples/teams/inline/success.html0000644000000000000000000000030111344732416022707 0ustar rootroot00000000000000 OpenID authentication successful You have been successfully authenticated via inline teams support. Logout apache-openid-2.0.1/examples/teams/teams.txt0000644000000000000000000000004511344732416020752 0ustar rootroot00000000000000launchpad-beta canonical-isd-hackers apache-openid-2.0.1/examples/teams/url/0000755000000000000000000000000011344732416017703 5ustar rootroot00000000000000apache-openid-2.0.1/examples/teams/url/apache.conf0000644000000000000000000000064611344732416022001 0ustar rootroot00000000000000 SetHandler mod_python PythonAccessHandler apache_openid::protect PythonOption handler openidteams PythonOption store-type file PythonOption store-directory /tmp/apache_openid PythonOption allowed-op-list-url file:///var/www/apache_openid/ops/op-launchpad.txt PythonOption authorized-teams-list-url file:///var/www/apache_openid/teams/teams.txt apache-openid-2.0.1/examples/teams/url/success.html0000644000000000000000000000030411344732416022236 0ustar rootroot00000000000000 OpenID authentication successful You have been successfully authenticated via URL-based teams support. Logout apache-openid-2.0.1/setup.py0000755000000000000000000000500611344732416015670 0ustar rootroot00000000000000#!/usr/bin/env python # Copyright (c) Django Software Foundation and individual contributors. # Copyright (C) 2009, 2010 Canonical Ltd # # 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 3 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, see . import os from distutils.core import setup from distutils.command.install import INSTALL_SCHEMES """ The logic comes from Django's setup.py """ def fullsplit(path, result=None): """ Split a pathname into components (the opposite of os.path.join) in a platform-neutral way. """ if result is None: result = [] head, tail = os.path.split(path) if head == '': return [tail] + result if head == path: return result return fullsplit(head, [tail] + result) # Tell distutils to put the data_files in platform-specific installation # locations. See here for an explanation: # http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d9e8042cb for scheme in INSTALL_SCHEMES.values(): scheme['data'] = scheme['purelib'] data_files = [] packages = [] for dirpath, dirnames, filenames in os.walk('apache_openid'): # Ignore dirnames that start with '.' for i, dirname in enumerate(dirnames): if dirname.startswith('.'): del dirnames[i] if '__init__.py' in filenames: packages.append('.'.join(fullsplit(dirpath))) elif filenames: data_files.append([ dirpath, [os.path.join(dirpath, f) for f in filenames]]) setup( name="apache_openid", version="2.0.1", author="Canonical ISD hackers", author_email="canonical-isd@lists.launchpad.net", url="http://launchpad.net/apache-openid", description="OpenID consumer module for Apache", long_description="This is a library that you can use with Apache web server and mod_python to enable OpenID access control to web resources.", license="GPLv3", packages=packages, data_files=data_files, install_requires=[ "python-openid", ], )