diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..1528af29 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "node" + - "5.11" + - "4.4" + - "4.3" + - "0.12" + - "0.10" diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..d3d2a639 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at [email address goes here]. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..a5a8c64e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +## How to contribute to rollup-libre + +#### Did you find a bug? + +* **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/omouse/node-oauth-libre/issues). + +* If you're unable to find an open issue addressing the problem, [open a new one](https://github.com/omouse/node-oauth-libre/issues/new). +Be sure to include a **title and clear description**, as much relevant information as possible, and a **code sample** or +an **executable test case** demonstrating the expected behavior that is not occurring. + +#### Did you write a patch? + +* Open a new GitHub pull request with the patch. + +* Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable. + +#### Do you want to get started writing a patch or feature? + +* Read the [HACKING](./HACKING.md) guide to learn where to get started diff --git a/LICENSE b/LICENSE index f8049f8c..94a9ed02 100644 --- a/LICENSE +++ b/LICENSE @@ -1,8 +1,674 @@ -The MIT License (MIT) -Copyright (c) <2010-2012> + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + 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. -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + Preamble -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + 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 +. diff --git a/LICENSE.mit b/LICENSE.mit new file mode 100644 index 00000000..a6c62f16 --- /dev/null +++ b/LICENSE.mit @@ -0,0 +1,17 @@ +The MIT License (MIT) +Copyright (c) <2010-2012> + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Readme.md b/Readme.md index 89132102..d43462f3 100644 --- a/Readme.md +++ b/Readme.md @@ -1,32 +1,114 @@ -node-oauth -=========== +# node-oauth + +[![Build Status](https://travis-ci.org/rudolfolah/node-oauth-libre.svg)](https://travis-ci.org/rudolfolah/node-oauth-libre) +[![License](http://img.shields.io/:license-gpl3-blue.svg)](http://www.gnu.org/licenses/gpl-3.0.html) +[![Flattr This](http://button.flattr.com/flattr-badge-large.png)](https://flattr.com/submit/auto?fid=y0jx3j&url=https%3A%2F%2Fgithub.com%2Frudolfolah%2Fnode-oauth-libre) +[![npm package](https://img.shields.io/npm/v/oauth-libre/latest.svg)](https://www.npmjs.com/package/oauth-libre) +[![npm downloads](https://img.shields.io/npm/dm/oauth-libre.svg)](https://www.npmjs.com/package/oauth-libre) + A simple oauth API for node.js . This API allows users to authenticate against OAUTH providers, and thus act as OAuth consumers. It also has support for OAuth Echo, which is used for communicating with 3rd party media providers such as TwitPic and yFrog. Tested against Twitter (http://twitter.com), term.ie (http://term.ie/oauth/example/), TwitPic, and Yahoo! Also provides rudimentary OAuth2 support, tested against facebook, github, foursquare, google and Janrain. For more complete usage examples please take a look at connect-auth (http://github.com/ciaranj/connect-auth) -[![Clone in Koding](http://learn.koding.com/btn/clone_d.png)][koding] -[koding]: https://koding.com/Teamwork?import=https://github.com/ciaranj/node-oauth/archive/master.zip&c=git1 -[![Pair on Thinkful](https://tf-assets-staging.s3.amazonaws.com/badges/thinkful_repo_badge.svg)][Thinkful] -[Thinkful]: http://start.thinkful.com/node/?utm_source=github&utm_medium=badge&utm_campaign=node-oauth +## How can I help/contribute? + +* You can help by reporting any bugs that you find: + * [report new issue](https://github.com/omouse/node-oauth-libre/issues/new) +* You can write code to fix bugs (some of them are labeled as "help wanted"): + * [submit a patch to one of these issues](https://github.com/omouse/node-oauth-libre/issues) +* You can find a bug fix or new feature in the original project, node-oauth, and add it to node-oauth-libre: + * [find a bug in node-oauth and fix it for node-oauth-libre](https://github.com/ciaranj/node-oauth/issues) + * [find a feature/bug fix to add to node-oauth-libre](https://github.com/ciaranj/node-oauth/pulls?utf8=%E2%9C%93&q=is%3Apr) +* Write documentation in [JSDoc](http://usejsdoc.org/) for each function/method/class in the codebase: + * [write documentation](https://github.com/omouse/node-oauth-libre/tree/master/lib) +* Use the library in your own project and promote it. + +## Related Libraries + +- [passport-oauth2-libre](https://github.com/caco0516/passport-oauth2-libre) Passport OAuth2 Strategy using node-oauth-libre. + +## License and Copyright + +**This code is covered under the GNU GPL version 3 or later with parts of the code also covered by the MIT license.** + +If you modify the code in this project, your changes will be under the GNU GPL version 3 or later. + +If you go to the original project and modify the code there, your changes will be under the MIT license. + +*Note: if you submit patches to the original project and they are applied here, I will assume that they +are under the MIT license.* But someone else will have to go through the work to extract them away from +the GPLv3 bits if they want to use them in a proprietary project + +# Installation + + npm install oauth-libre + +# Build the Docs + +Requires JSDoc to be installed: -Installation -============== + npm run build-docs - $ npm install oauth +# Examples +## Using Promises -Examples -========== +Using promises is *optional*. + +Install the bluebird promises library: + + npm install bluebird + +An example of using oauth-libre with OAuth2 and Promises to access the Github API: + +``` +var OAuth2 = require('oauth-libre').PromiseOAuth2; + +var clientId = ''; +var clientSecret = ''; + +// Fill these in: +var user = 'USER'; +var personalAccessToken = 'PERSONAL_ACCESS_TOKEN'; + +var baseSiteUrl = 'https://' + user + ':' + personalAccessToken + '@api.github.com/'; +var authorizePath = 'oauth2/authorize'; +var accessTokenPath = 'oauth2/access_token'; +var customHeaders = null; + +var oauth2 = new OAuth2( + clientId, clientSecret, baseSiteUrl, authorizePath, accessTokenPath, customHeaders +); + +var url = 'https://api.github.com/users/' + user + '/received_events'; +oauth2 + .get(url, personalAccessToken) + .then(jsonParse) + .then(function(json) { + for (var i = 0; i < json.length; i += 1) { + console.log(json[i]['id'] + ': ' + json[i].type); + } + }) + .catch(function(err) { + console.log('Error: ' + err); + }); + +function jsonParse(data) { + return JSON.parse(data); +} +``` -To run examples/tests install Mocha `$ npm install -g mocha` and run `$ mocha you-file-name.js`: +Note that in the first line you must explicitly import OAuth2 with promises. ## OAuth1.0 +Example of using OAuth 1.0 with the Twitter API. + ```javascript describe('OAuth1.0',function(){ - var OAuth = require('oauth'); + var OAuth = require('oauth-libre'); it('tests trends Twitter API v1.1',function(done){ var oauth = new OAuth.OAuth( @@ -38,33 +120,101 @@ describe('OAuth1.0',function(){ null, 'HMAC-SHA1' ); + oauth.setDefaultContentType('application/json'); oauth.get( 'https://api.twitter.com/1.1/trends/place.json?id=23424977', 'your user token for this app', //test user token - 'your user secret for this app', //test user secret + 'your user secret for this app', //test user secret function (e, data, res){ - if (e) console.error(e); + if (e) console.error(e); console.log(require('util').inspect(data)); - done(); - }); + done(); + }); }); }); ``` -## OAuth2.0 +## OAuth2.0 + +### Usage + +```javascript +var OAuth2 = require('oauth-libre').OAuth2; + +console.log("Login here to get an authorization code: " + oauth2.getAuthorizeUrl()); + +var oauth2 = new OAuth2( + "client_id", // client id + "client_secret", // client secret + "http://localhost:3000/", // base site url + null, // authorize path + "/oauth/token", // access token path + null // custom headers object +); + +oauth2.getOAuthAccessToken( + "auth_code", + { + "grant_type": "authorization_code", + "redirect_uri": "http://example.com/redirect_uri" + }, + function(error, accessToken, refreshToken, results) { + if (error) { + console.log("Error: " + error); + } else { + console.log("Results: " + results); + } + } +); +``` + +### Hooks +OAuth 2.0 implements hooks for every request before and after it is executed. We're using the [EventEmitter](https://nodejs.org/api/events.html) Node.js class to implement this. + +#### request:before +This event is emitted before the HTTP (or HTTPS) request is executed. At this point we can modify the information in the request, such as the headers and POST data. Also we are given a `done` function because this event blocks request execution and we need to specify when to resume the current process. + +Let's see an example: + +```javascript + oa2.on('request:before', (options, postBody, done) => { + // here you can add anything you want to the request before execution + // can add new headers or add new data to body. + // + // NOTE: you must call done and send 3 parameters without exception. + // The 3rd parameter must to be true if you want to execute request + // immediately. + done(options, postBody, true); + }); +``` + +You must call `done(modifiedOptions, modifiedPostBody, shouldExecute)` always. The `shouldExecute` parameter exists because if we have more listeners for the `request:before` event we want to make sure all of the listeners are able to receive the event. The request should execute only once, that's why we have this parameter to tell event that we want to execute the request immediately. + +### request:after +This event is emitted after the request has been executed, we receive information about status and body of the response. + ```javascript -describe('OAuth2',function(){ - var OAuth = require('oauth'); + oa2.on('request:after', (status, response) => { + console.log('Status :' + JSON.stringify(status)); + console.log('Response : ' + JSON.stringify(response)); + }); +``` + +### Test + +```javascript +describe('OAuth2',function() { + var OAuth = require('oauth-libre'); it('gets bearer token', function(done){ - var OAuth2 = OAuth.OAuth2; + var OAuth2 = OAuth.OAuth2; var twitterConsumerKey = 'your key'; var twitterConsumerSecret = 'your secret'; var oauth2 = new OAuth2(server.config.keys.twitter.consumerKey, - twitterConsumerSecret, - 'https://api.twitter.com/', + twitterConsumerSecret, + 'https://api.twitter.com/', null, - 'oauth2/token', + 'oauth2/token', null); oauth2.getOAuthAccessToken( '', @@ -76,8 +226,80 @@ describe('OAuth2',function(){ }); ``` -Change History -============== +## Examples Using Web-Based Interface + +Included with the source code are examples of using a web-based interface to login with: + +* Github: `examples/github-example.js` +* Github OAuth 2.0 and Hooks: `examples/github-oauth2-authentication.js` +* Twitter: `examples/twitter-example.js` + +The Google example was removed due to the need for a custom Google-specific OAuth2 library for authentication. + +### Example: Authentication with Github + +1. Create a Github account +1. Create a new Developer Application (Settings > OAuth applications > Developer Applications) +1. Fill in the Authorization callback URL with `http://localhost:8080/code` +1. Copy the Client ID into `examples/github-example.js` where it says `clientID` +1. Copy the Client Secret into `examples/github-example.js` where it says `clientSecret` +1. Run the web server: `node examples/github-example.js` +1. Open the website: `http://localhost:8080/` +1. Click the link that says "Get Code" +1. Login to Github and authorize the application +1. You will be returned to `http://localhost:8080/code` and should see the access token, on the command-line you will see something like "Obtained access_token: ..." + + +### Example: Authentication with Github OAuth 2.0 and Hooks + +1. Create a Github account +1. Create a new Developer Application (Settings > OAuth applications > Developer Applications) +1. Fill in the Authorization callback URL with `http://localhost:3000/github/callback` +1. Complete this with your information: +```javascript + const clientId = 'YOURCLIENTID'; + const clientSecret = 'YOURCLIENTSECRET'; + const scope = 'user'; + const redirectUrl = 'http://localhost:' + port + '/github/callback'; + const baseUrl = 'https://github.com'; + const authorizeUrl = '/login/oauth/authorize'; + const tokenUrl = '/login/oauth/access_token'; +``` +1. Run the web server: `node examples/github-oauth2-authentication.js` +1. Open the website: `http://localhost:3000/` +1. Click the link that says "Sign In with Github" +1. Login to Github and authorize the application +1. You will be returned to `http://localhost:8080/github/callback` and that's it. + +### Example: Authentication with Google + +*Note: This example has been removed because Google needs a custom OAuth2 client library: https://github.com/google/google-auth-library-nodejs* + +### Example: Authentication with Twitter + +1. Create a Twitter account +1. Create a new Developer Application https://apps.twitter.com/ > Create New App +1. Fill in the Callback URL with `http://127.0.0.1:8080/callback` +1. Copy the Consumer Key (API Key) into `examples/twitter-example.js` where it says `clientID` +1. Copy the Consumer Secret (API Secret) into `examples/twitter-example.js` where it says `clientSecret` +1. Run the web server: `node examples/twitter-example.js` +1. Open the website: `http://localhost:8080/` +1. Login to Twitter and authorize the application +1. You will be returned to `http://localhost:8080/code` and should see some results from the response on the command-line + +# Change History +* 0.9.17 + - OAuth1: Allow setting of default Content-Type for requests, either through constructor's `customHeaders` parameter or through `setDefaultContentType` method +* 0.9.16 + - OAuth2 hooks for before and after a request is executed +* 0.9.15 + - Promises for OAuth1 and OAuth2 with multiArgs + - PATCH support for OAuth1 and OAuth2 + - GPLv3+ licensing + - Code examples updated, tested and working + - OAuth2: Authorization header added for POST token + - OAuth1: Able to set HTTPS/HTTP options + - OAuth1: getOAuthAccessToken now accepts an additional extraParams argument * 0.9.14 - OAuth2: Extend 'successful' token responses to include anything in the 2xx range. * 0.9.13 @@ -106,82 +328,88 @@ Change History - OAuth2: Don't force a https request if given a http url (Thanks to Damien Mathieu) - OAuth2: Supports specifying a grant-type of 'refresh-token' (Thanks to Luke Baker) * 0.9.6 - - OAuth2: Support for 302 redirects (Thanks Patrick Negri). - - OAuth1/2: Some code tidying. ( Thanks to Raoul Millais ) + - OAuth2: Support for 302 redirects (Thanks Patrick Negri). + - OAuth1/2: Some code tidying. ( Thanks to Raoul Millais ) * 0.9.5 - - OAuth1: Allow usage of HTTP verbs other than GET for retrieving the access and request tokens (Thanks to Raoul Millais) + - OAuth1: Allow usage of HTTP verbs other than GET for retrieving the access and request tokens (Thanks to Raoul Millais) * 0.9.4 - - OAuth1/2: Support for OAuth providers that drop connections (don't send response lengths? [Google]) - - OAuth2: Change getOAuthAccessToken to POST rather than GET ( Possible Breaking change!!! ... re-tested against Google, Github, Facebook, FourSquare and Janrain and seems ok .. is closer to the spec (v20) ) + - OAuth1/2: Support for OAuth providers that drop connections (don't send response lengths? [Google]) + - OAuth2: Change getOAuthAccessToken to POST rather than GET ( Possible Breaking change!!! ... re-tested against Google, Github, Facebook, FourSquare and Janrain and seems ok .. is closer to the spec (v20) ) * 0.9.3 - - OAuth1: Adds support for following 301 redirects (Thanks bdickason) -* 0.9.2 - - OAuth1: Correct content length calculated for non-ascii post bodies (Thanks selead) - - OAuth1: Allowed for configuration of the 'access token' name used when requesting protected resources (OAuth2) + - OAuth1: Adds support for following 301 redirects (Thanks bdickason) +* 0.9.2 + - OAuth1: Correct content length calculated for non-ascii post bodies (Thanks selead) + - OAuth1: Allowed for configuration of the 'access token' name used when requesting protected resources (OAuth2) * 0.9.1 - - OAuth1: Added support for automatically following 302 redirects (Thanks neyric) - - OAuth1: Added support for OAuth Echo (Thanks Ryan LeFevre). - - OAuth1: Improved handling of 2xx responses (Thanks Neil Mansilla). + - OAuth1: Added support for automatically following 302 redirects (Thanks neyric) + - OAuth1: Added support for OAuth Echo (Thanks Ryan LeFevre). + - OAuth1: Improved handling of 2xx responses (Thanks Neil Mansilla). * 0.9.0 - - OAuth1/2: Compatibility fixes to bring node-oauth up to speed with node.js 0.4x [thanks to Rasmus Andersson for starting the work ] + - OAuth1/2: Compatibility fixes to bring node-oauth up to speed with node.js 0.4x [thanks to Rasmus Andersson for starting the work ] * 0.8.4 - OAuth1: Fixed issue #14 (Parameter ordering ignored encodings). - OAuth1: Added support for repeated parameter names. - OAuth1/2: Implements issue #15 (Use native SHA1 if available, 10x speed improvement!). - OAuth2: Fixed issue #16 (Should use POST when requesting access tokens.). - - OAuth2: Fixed Issue #17 (OAuth2 spec compliance). - - OAuth1: Implemented enhancement #13 (Adds support for PUT & DELETE http verbs). - - OAuth1: Fixes issue #18 (Complex/Composite url arguments [thanks novemberborn]) + - OAuth2: Fixed Issue #17 (OAuth2 spec compliance). + - OAuth1: Implemented enhancement #13 (Adds support for PUT & DELETE http verbs). + - OAuth1: Fixes issue #18 (Complex/Composite url arguments [thanks novemberborn]) * 0.8.3 - - OAuth1: Fixed an issue where the auth header code depended on the Array's toString method (Yohei Sasaki) Updated the getOAuthRequestToken method so we can access google's OAuth secured methods. Also re-implemented and fleshed out the test suite. + - OAuth1: Fixed an issue where the auth header code depended on the Array's toString method (Yohei Sasaki) Updated the getOAuthRequestToken method so we can access google's OAuth secured methods. Also re-implemented and fleshed out the test suite. * 0.8.2 - OAuth1: The request returning methods will now write the POST body if provided (Chris Anderson), the code responsible for manipulating the headers is a bit safe now when working with other code (Paul McKellar) - - Package: Tweaked the package.json to use index.js instead of main.js + - Package: Tweaked the package.json to use index.js instead of main.js * 0.8.1 - - OAuth1: Added mechanism to get hold of a signed Node Request object, ready for attaching response listeners etc. (Perfect for streaming APIs) + - OAuth1: Added mechanism to get hold of a signed Node Request object, ready for attaching response listeners etc. (Perfect for streaming APIs) * 0.8.0 - - OAuth1: Standardised method capitalisation, the old getOauthAccessToken is now getOAuthAccessToken (Breaking change to existing code) + - OAuth1: Standardised method capitalisation, the old getOauthAccessToken is now getOAuthAccessToken (Breaking change to existing code) * 0.7.7 - - OAuth1: Looks like non oauth_ parameters where appearing within the Authorization headers, which I believe to be incorrect. + - OAuth1: Looks like non oauth_ parameters where appearing within the Authorization headers, which I believe to be incorrect. * 0.7.6 - - OAuth1: Added in oauth_verifier property to getAccessToken required for 1.0A + - OAuth1: Added in oauth_verifier property to getAccessToken required for 1.0A * 0.7.5 - - Package: Added in a main.js to simplify the require'ing of OAuth + - Package: Added in a main.js to simplify the require'ing of OAuth * 0.7.4 - - OAuth1: Minor change to add an error listener to the OAuth client (thanks troyk) + - OAuth1: Minor change to add an error listener to the OAuth client (thanks troyk) * 0.7.3 - - OAuth2: Now sends a Content-Length Http header to keep nginx happy :) + - OAuth2: Now sends a Content-Length Http header to keep nginx happy :) * 0.7.2 - - OAuth1: Fixes some broken unit tests! + - OAuth1: Fixes some broken unit tests! * 0.7.0 - - OAuth1/2: Introduces support for HTTPS end points and callback URLS for OAuth 1.0A and Oauth 2 (Please be aware that this was a breaking change to the constructor arguments order) + - OAuth1/2: Introduces support for HTTPS end points and callback URLS for OAuth 1.0A and Oauth 2 (Please be aware that this was a breaking change to the constructor arguments order) -Contributors (In no particular order) -===================================== +# Contributors (In first-name alphabetical order) +* AJ ONeal +* Alex Nuccio - https://github.com/anuccio1 +* Andreas Knecht +* Andrew Martins - http://www.andrewmartens.com +* Brian Park - http://github.com/yaru22 +* Carlos Castillo Oporta - https://github.com/caco0516 +* Christian Schwarz - http://github.com/chrischw/ +* Ciaran Jessup - ciaranj@gmail.com +* Damien Mathieu - http://42.dmathieu.com +* Daniel Mahlow - https://github.com/dmahlow +* Derek Brooks * Evan Prodromou +* Garrick Cheung - http://www.garrickcheung.com/ +* George Haddad - https://github.com/george-haddad +* Jeffrey D. Van Alstine +* Joe Rozer - http://www.deadbytes.net * Jose Ignacio Andres -* Ted Goddard -* Derek Brooks -* Ciaran Jessup - ciaranj@gmail.com +* José F. Romaniello - http://github.com/jfromaniello +* Luke Baker - http://github.com/lukebaker * Mark Wubben - http://equalmedia.com/ -* Ryan LeFevre - http://meltingice.net -* Raoul Millais +* Michael Garvin +* Oleg Zd - https://github.com/olegzd * Patrick Negri - http://github.com/pnegri +* Pieter Joost van de Sande - https://github.com/pjvds +* Raoul Millais +* Rudolf Olah - https://neverfriday.com +* Ryan Ausanka-Crues - http://quanticmind.com/ +* Ryan LeFevre - http://meltingice.net * Tang Bo Hao - http://github.com/btspoony -* Damien Mathieu - http://42.dmathieu.com -* Luke Baker - http://github.com/lukebaker -* Christian Schwarz - http://github.com/chrischw/ -* Joe Rozer - http://www.deadbytes.net -* Garrick Cheung - http://www.garrickcheung.com/ -* rolandboon - http://rolandboon.com -* Brian Park - http://github.com/yaru22 -* José F. Romaniello - http://github.com/jfromaniello +* Ted Goddard * bendiy - https://github.com/bendiy -* Andrew Martins - http://www.andrewmartens.com -* Daniel Mahlow - https://github.com/dmahlow -* Pieter Joost van de Sande - https://github.com/pjvds -* Jeffrey D. Van Alstine -* Michael Garvin -* Andreas Knecht -* AJ ONeal +* rolandboon - http://rolandboon.com +* cr24osome - https://github.com/cr24osome diff --git a/conf.json b/conf.json new file mode 100644 index 00000000..0a393faa --- /dev/null +++ b/conf.json @@ -0,0 +1,23 @@ +{ + "opts": { + "destination": "api-docs", + "readme": "Readme.md" + }, + "tags": { + "allowUnknownTags": true, + "dictionaries": ["jsdoc","closure"] + }, + "source": { + "includePattern": ".+\\.js(doc|x|on)?$", + "include": [ + "Readme.md", + "index.js", + "lib" + ] + }, + "plugins": [], + "templates": { + "cleverLinks": false, + "monospaceLinks": false + } +} diff --git a/examples/express-gdata/server.js b/examples/express-gdata/server.js deleted file mode 100644 index 3c7bf7fe..00000000 --- a/examples/express-gdata/server.js +++ /dev/null @@ -1,168 +0,0 @@ -var express = require('express'), - OAuth = require('oauth').OAuth, - querystring = require('querystring'); - -// Setup the Express.js server -var app = express.createServer(); -app.use(express.logger()); -app.use(express.bodyParser()); -app.use(express.cookieParser()); -app.use(express.session({ - secret: "skjghskdjfhbqigohqdiouk" -})); - -// Home Page -app.get('/', function(req, res){ - if(!req.session.oauth_access_token) { - res.redirect("/google_login"); - } - else { - res.redirect("/google_contacts"); - } -}); - -// Request an OAuth Request Token, and redirects the user to authorize it -app.get('/google_login', function(req, res) { - - var getRequestTokenUrl = "https://www.google.com/accounts/OAuthGetRequestToken"; - - // GData specifid: scopes that wa want access to - var gdataScopes = [ - querystring.escape("https://www.google.com/m8/feeds/"), - querystring.escape("https://www.google.com/calendar/feeds/") - ]; - - var oa = new OAuth(getRequestTokenUrl+"?scope="+gdataScopes.join('+'), - "https://www.google.com/accounts/OAuthGetAccessToken", - "anonymous", - "anonymous", - "1.0", - "http://localhost:3000/google_cb"+( req.param('action') && req.param('action') != "" ? "?action="+querystring.escape(req.param('action')) : "" ), - "HMAC-SHA1"); - - oa.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret, results){ - if(error) { - console.log('error'); - console.log(error); - } - else { - // store the tokens in the session - req.session.oa = oa; - req.session.oauth_token = oauth_token; - req.session.oauth_token_secret = oauth_token_secret; - - // redirect the user to authorize the token - res.redirect("https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token="+oauth_token); - } - }) - -}); - -// Callback for the authorization page -app.get('/google_cb', function(req, res) { - - // get the OAuth access token with the 'oauth_verifier' that we received - - var oa = new OAuth(req.session.oa._requestUrl, - req.session.oa._accessUrl, - req.session.oa._consumerKey, - req.session.oa._consumerSecret, - req.session.oa._version, - req.session.oa._authorize_callback, - req.session.oa._signatureMethod); - - console.log(oa); - - oa.getOAuthAccessToken( - req.session.oauth_token, - req.session.oauth_token_secret, - req.param('oauth_verifier'), - function(error, oauth_access_token, oauth_access_token_secret, results2) { - - if(error) { - console.log('error'); - console.log(error); - } - else { - - // store the access token in the session - req.session.oauth_access_token = oauth_access_token; - req.session.oauth_access_token_secret = oauth_access_token_secret; - - res.redirect((req.param('action') && req.param('action') != "") ? req.param('action') : "/google_contacts"); - } - - }); - -}); - - -function require_google_login(req, res, next) { - if(!req.session.oauth_access_token) { - res.redirect("/google_login?action="+querystring.escape(req.originalUrl)); - return; - } - next(); -}; - -app.get('/google_contacts', require_google_login, function(req, res) { - var oa = new OAuth(req.session.oa._requestUrl, - req.session.oa._accessUrl, - req.session.oa._consumerKey, - req.session.oa._consumerSecret, - req.session.oa._version, - req.session.oa._authorize_callback, - req.session.oa._signatureMethod); - - console.log(oa); - - // Example using GData API v3 - // GData Specific Header - oa._headers['GData-Version'] = '3.0'; - - oa.getProtectedResource( - "https://www.google.com/m8/feeds/contacts/default/full?alt=json", - "GET", - req.session.oauth_access_token, - req.session.oauth_access_token_secret, - function (error, data, response) { - - var feed = JSON.parse(data); - - res.render('google_contacts.ejs', { - locals: { feed: feed } - }); - }); - -}); - -app.get('/google_calendars', require_google_login, function(req, res) { - var oa = new OAuth(req.session.oa._requestUrl, - req.session.oa._accessUrl, - req.session.oa._consumerKey, - req.session.oa._consumerSecret, - req.session.oa._version, - req.session.oa._authorize_callback, - req.session.oa._signatureMethod); - // Example using GData API v2 - // GData Specific Header - oa._headers['GData-Version'] = '2'; - - oa.getProtectedResource( - "https://www.google.com/calendar/feeds/default/allcalendars/full?alt=jsonc", - "GET", - req.session.oauth_access_token, - req.session.oauth_access_token_secret, - function (error, data, response) { - - var feed = JSON.parse(data); - - res.render('google_calendars.ejs', { - locals: { feed: feed } - }); - }); - -}); - -app.listen(3000); -console.log("listening on http://localhost:3000"); diff --git a/examples/express-gdata/views/google_calendars.ejs b/examples/express-gdata/views/google_calendars.ejs deleted file mode 100644 index 15b826f8..00000000 --- a/examples/express-gdata/views/google_calendars.ejs +++ /dev/null @@ -1,21 +0,0 @@ - -

Check google_contacts

- -

Google Calendars

- -<% for(var i = 0 ; i < feed.data.items.length ; i++ ) { - - var calendar = feed.data.items[i]; %> -
- -

"><%= calendar["title"] %>

- -

canEdit: <%= calendar["canEdit"] %>

-

accessLevel: <%= calendar["accessLevel"] %>

-

timeZone: <%= calendar["timeZone"] %>

-

kind: <%= calendar["kind"] %>

-

updated: <%= calendar["updated"] %>

-

created: <%= calendar["created"] %>

- -
-<% } %> \ No newline at end of file diff --git a/examples/express-gdata/views/google_contacts.ejs b/examples/express-gdata/views/google_contacts.ejs deleted file mode 100644 index a2050b21..00000000 --- a/examples/express-gdata/views/google_contacts.ejs +++ /dev/null @@ -1,24 +0,0 @@ - -

Check google_calendars

- -

Google Contacts

- -<% for(var i = 0 ; i < feed.feed.entry.length ; i++ ) { - - var contact = feed.feed.entry[i]; %> - -
- - <%= contact["title"]["$t"] %> - <% emails = contact["gd$email"] %> - -
    - <% for(var j = 0 ; j < emails.length ; j++) { %> -
  • <%= emails[j]["address" ]%>
  • - <% } %> -
- -
- - -<% } %> diff --git a/examples/express-gdata/views/layout.ejs b/examples/express-gdata/views/layout.ejs deleted file mode 100644 index 8d1ac6d5..00000000 --- a/examples/express-gdata/views/layout.ejs +++ /dev/null @@ -1,9 +0,0 @@ - - - - - -<%- body %> - - - \ No newline at end of file diff --git a/examples/github-example.js b/examples/github-example.js index 1a388bdb..e5932e8b 100644 --- a/examples/github-example.js +++ b/examples/github-example.js @@ -1,73 +1,91 @@ -var http = require('http'); -var qs = require('querystring'); -// var OAuth = require('oauth'), OAuth2 = OAuth.OAuth2; -var OAuth2 = require('../lib/oauth2.js').OAuth2; +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * + * 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. -var clientID = ''; -var clientSecret = ''; -var oauth2 = new OAuth2(clientID, - clientSecret, - 'https://github.com/', - 'login/oauth/authorize', - 'login/oauth/access_token', - null); /** Custom headers */ + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ -http.createServer(function (req, res) { - var p = req.url.split('/'); - pLen = p.length; - - /** - * Authorised url as per github docs: - * https://developer.github.com/v3/oauth/#redirect-users-to-request-github-access - * - * getAuthorizedUrl: https://github.com/ciaranj/node-oauth/blob/master/lib/oauth2.js#L148 - * Adding params to authorize url with fields as mentioned in github docs - * - */ - var authURL = oauth2.getAuthorizeUrl({ - redirect_uri: 'http://localhost:8080/code', - scope: ['repo', 'user'], - state: 'some random string to protect against cross-site request forgery attacks' - }); +var http = require("http"); +var qs = require("querystring"); +// var OAuth = require("oauth"), OAuth2 = OAuth.OAuth2; +var OAuth2 = require("../lib/oauth2.js").OAuth2; +var clientID = ""; +var clientSecret = ""; +var oauth2 = new OAuth2( + clientID, + clientSecret, + "https://github.com/", + "login/oauth/authorize", + "login/oauth/access_token", + null /** Custom headers */ +); - /** - * Creating an anchor with authURL as href and sending as response - */ - var body = ' Get Code '; - if (pLen === 2 && p[1] === '') { - res.writeHead(200, { - 'Content-Length': body.length, - 'Content-Type': 'text/html' }); - res.end(body); - } else if (pLen === 2 && p[1].indexOf('code') === 0) { +http.createServer(function (req, res) { + var p = req.url.split("/"); + var pLen = p.length; + + /** + * Authorised url as per github docs: + * https://developer.github.com/v3/oauth/#redirect-users-to-request-github-access + * + * getAuthorizedUrl: https://github.com/ciaranj/node-oauth/blob/master/lib/oauth2.js#L148 + * Adding params to authorize url with fields as mentioned in github docs + * + */ + var authURL = oauth2.getAuthorizeUrl({ + redirect_uri: "http://localhost:8080/code", + scope: ["repo", "user"], + state: "some random string to protect against cross-site request forgery attacks" + }); - /** Github sends auth code so that access_token can be obtained */ - var qsObj = {}; - - /** To obtain and parse code='...' from code?code='...' */ - qsObj = qs.parse(p[1].split('?')[1]); + /** + * Creating an anchor with authURL as href and sending as response + */ + var body = " Get Code "; + if (pLen === 2 && p[1] === "") { + res.writeHead(200, { + "Content-Length": body.length, + "Content-Type": "text/html" }); + res.end(body); + } else if (pLen === 2 && p[1].indexOf("code") === 0) { + /** Github sends auth code so that access_token can be obtained */ + var qsObj = {}; + + /** To obtain and parse code="..." from code?code="..." */ + qsObj = qs.parse(p[1].split("?")[1]); - /** Obtaining access_token */ - oauth2.getOAuthAccessToken( - qsObj.code, - {'redirect_uri': 'http://localhost:8080/code/'}, - function (e, access_token, refresh_token, results){ - if (e) { - console.log(e); - res.end(e); - } else if (results.error) { - console.log(results); - res.end(JSON.stringify(results)); - } - else { - console.log('Obtained access_token: ', access_token); - res.end( access_token); - } - }); + /** Obtaining access_token */ + oauth2.getOAuthAccessToken( + qsObj.code, + {"redirect_uri": "http://localhost:8080/code/"}, + function (error, access_token, refresh_token, results) { + if (error) { + console.log(error); + res.end(error); + } else if (results.error) { + console.log(results); + res.end(JSON.stringify(results)); + } else { + console.log("Obtained access_token: ", access_token); + res.end( access_token); + } + }); - } else { - // Unhandled url - } + } else { + // Unhandled url + } }).listen(8080); diff --git a/examples/github-oauth2-authentication.js b/examples/github-oauth2-authentication.js new file mode 100644 index 00000000..c9b1ed18 --- /dev/null +++ b/examples/github-oauth2-authentication.js @@ -0,0 +1,83 @@ +/** + * Example of using Hooks (request:before and request:after) with + * OAuth2. + */ +const express = require("express"); +const session = require("express-session"); +const bodyParser = require("body-parser"); +const randomstring = require("randomstring"); + +const app = express(); +const port = process.env.PORT || 3000; + +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: false })); +app.use(session({ + secret: "keyboard cat", + resave: true, + saveUninitialized: true, + cookie: { secure: false } +})); + +const clientId = "YOURCLIENTID"; +const clientSecret = "YOURCLIENTSECRET"; +const scope = "user"; +const redirectUrl = "http://localhost:" + port + "/github/callback"; +const baseUrl = "https://github.com"; +const authorizeUrl = "/login/oauth/authorize"; +const tokenUrl = "/login/oauth/access_token"; + +const OAuth2 = require("../lib/oauth2").OAuth2; +const oa2 = new OAuth2(clientId, clientSecret, baseUrl, authorizeUrl, tokenUrl, {}); + +oa2.on("request:before", function (options, postBody, done) { + // here you can add anything you want to the request before + // execution can add new headers or add new data to body. + // + // NOTE: you must call done and send 3 parameters without exception + // 3rd parameter must to be true if you want to execute request in + // this moment. + done(options, postBody, true); +}); + +oa2.on("request:after", function (status, response) { + console.log("Status:" + JSON.stringify(status)); + console.log("Response: " + JSON.stringify(response)); +}); + +app.set("oa", oa2); + +app.get("/", function (req, res) { + res.send("Sign In with Github"); +}); + +app.get("/github/auth", function (req, res) { + const oa = req.app.get("oa"); + const state = randomstring.generate(7); + req.session.state = state; + const params = { + "client_id": oa._clientId, + "redirect_uri": redirectUrl, + "scope": scope, + "state": state, + "allow_signup": "false" + }; + const url = oa.getAuthorizeUrl(params); + res.redirect(url); +}); + +app.get("/github/callback", function (req, res) { + const oa = req.app.get("oa"); + const code = req.query.code; + const requestState = req.query.state; + if (requestState !== req.session.state) { + return res.send("Github error state mismatch"); + } + oa.getOAuthAccessToken(code, {}, function (accessToken, refreshToken, result) { + res.send("Github must authenticated this accessToken: " + accessToken + " - refreshToken: " + refreshToken); + }); +}); + +app.listen(port, function () { + console.log("github outh2 example running on " + port); +}); diff --git a/examples/github-oauth2.js b/examples/github-oauth2.js new file mode 100644 index 00000000..6bae8cf4 --- /dev/null +++ b/examples/github-oauth2.js @@ -0,0 +1,53 @@ +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2016 Rudolf Olah + * + * 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 . + */ + +var OAuth2 = require("../index").PromiseOAuth2; + +var clientId = ""; +var clientSecret = ""; + +// Fill these in: +var user = "USER"; +var personalAccessToken = "PERSONAL_ACCESS_TOKEN"; + +var baseSiteUrl = "https://" + user + ":" + personalAccessToken + "@api.github.com/"; +var authorizePath = "oauth2/authorize"; +var accessTokenPath = "oauth2/access_token"; +var customHeaders = null; + +function jsonParse(data) { + return JSON.parse(data); +} + +var oauth2 = new OAuth2( + clientId, clientSecret, baseSiteUrl, authorizePath, accessTokenPath, customHeaders +); + +var url = "https://api.github.com/users/" + user + "/received_events"; +oauth2 + .get(url, personalAccessToken) + .then(jsonParse) + .then(function(json) { + for (var i = 0; i < json.length; i += 1) { + console.log(json[i]["id"] + ": " + json[i].type); + } + }) + .catch(function(err) { + console.log("Error: " + err); + }); diff --git a/examples/promise-twitter-example.js b/examples/promise-twitter-example.js new file mode 100644 index 00000000..a7c60232 --- /dev/null +++ b/examples/promise-twitter-example.js @@ -0,0 +1,122 @@ +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2016 Oleg Zd + * + * 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 . + */ + +/* + * + * This is an example of the original Twitter OAuth 1 example, ported + * over to use the promise library. + * + * NOTE: Express should be installed (included here for ease of use, + * if you're not using Express, this can be easily done through + * Node's http.createSever() call. + * + */ + +var http = require("http"); +var OAuth = require("../lib/oauth-promise").OAuth; +var express = require("express"); + +const callbackURL = "http://localhost:5000/oauth_callback"; +const yourConsumerKey = "INSERT YOUR CONSUMER KEY HERE"; +const yourConsumerSecret = "INSERT YOUR CONSUMER SECRET KEY HERE"; + +// Hash that contains the req_token:req_token_secret key vals +var reqTokenSecrets = {}; + +/* + STEP 1 - init the OAuth Client! +*/ +var oa = new OAuth( + "https://api.twitter.com/oauth/request_token", + "https://api.twitter.com/oauth/access_token", + yourConsumerKey, // CONSUMER KEY + yourConsumerSecret, // CONSUMER SECRET + "1.0", + callbackURL, + "HMAC-SHA1" +); + +var app = express(); +app.get("/", function(req, res) { + // STEP 2: Ask twitter for a signed request token + + // oAuthToken/Secret used for this this handshake process + var requestTokenPromise = oa.getOAuthRequestToken(); + + /* + Promise returns data array in the format: + + data[0]: oauth_token + data[1]: oauth_token_secret + data[2]: results + + */ + requestTokenPromise.then(function(data){ + // Extract data + var oauthToken = data[0]; + var oauthTokenSecret = data[1]; + + // Get the secret oauth request token + reqTokenSecrets[oauthToken] = oauthTokenSecret; + + // Redirect user to Twitter Auth + var redirectURL = "https://api.twitter.com/oauth/authorize" + + "?oauth_token=" + oauthToken; + res.redirect(redirectURL); + + }); + +}); + + +app.get("/oauth_callback", function(req, res) { + + // This is where we get the oauth token, oauth verifier, and give the oauth token secret as well + + /** + * STEP 4: Get the access token and access token secret - finally what we need! :) + */ + var accessTokenPromise = oa.getOAuthAccessToken( + req.query.oauth_token, + reqTokenSecrets[req.query.oauth_token], + req.query.oauth_verifier + ); + + /* + Similar to access token: + data[0]: access token + data[1]: access token secret + data[2]: results + */ + accessTokenPromise.then(function(data) { + var accessToken = data[0]; + var accessTokenSecret = data[1]; + var results = data[2]; + // here we get access token, access token secret - this is what we use to access the + // user"s Twitter resources, you want to store this! + res.send("Acc token: " + accessToken + + " \nAcc token secret: " + accessTokenSecret); + }); + +}); + +app.listen(5000, function(){ + console.log("Listening on port 5000"); +}); + diff --git a/examples/term.ie.oauth-HMAC-SHA1.js b/examples/term.ie.oauth-HMAC-SHA1.js index 91af05db..d632daec 100644 --- a/examples/term.ie.oauth-HMAC-SHA1.js +++ b/examples/term.ie.oauth-HMAC-SHA1.js @@ -1,31 +1,59 @@ -var util= require('util') +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * + * 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. -var OAuth= require('../lib/oauth').OAuth; + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +var util = require("util"); +var OAuth = require("../lib/oauth").OAuth; -var oa= new OAuth("http://term.ie/oauth/example/request_token.php", - "http://term.ie/oauth/example/access_token.php", - "key", - "secret", - "1.0", - null, - "HMAC-SHA1") +var oa = new OAuth( + "http://term.ie/oauth/example/request_token.php", + "http://term.ie/oauth/example/access_token.php", + "key", + "secret", + "1.0", + null, + "HMAC-SHA1" +); -oa.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret, results){ - if(error) util.puts('error :' + error) - else { - util.puts('oauth_token :' + oauth_token) - util.puts('oauth_token_secret :' + oauth_token_secret) - util.puts('requestoken results :' + util.inspect(results)) - util.puts("Requesting access token") - oa.getOAuthAccessToken(oauth_token, oauth_token_secret, function(error, oauth_access_token, oauth_access_token_secret, results2) { - util.puts('oauth_access_token :' + oauth_access_token) - util.puts('oauth_token_secret :' + oauth_access_token_secret) - util.puts('accesstoken results :' + util.inspect(results2)) - util.puts("Requesting access token") - var data= ""; - oa.getProtectedResource("http://term.ie/oauth/example/echo_api.php?foo=bar&too=roo", "GET", oauth_access_token, oauth_access_token_secret, function (error, data, response) { +oa.getOAuthRequestToken(function(error, oauthToken, oauthTokenSecret, results) { + if (error) { + util.puts("error :" + error); + return; + } + util.puts("oauth_token :" + oauthToken); + util.puts("oauth_token_secret :" + oauthTokenSecret); + util.puts("requestoken results :" + util.inspect(results)); + util.puts("Requesting access token"); + oa.getOAuthAccessToken( + oauthToken, + oauthTokenSecret, + function(error, oauthAccessToken, oauthAccessTokenSecret, results2) { + util.puts("oauth_access_token :" + oauthAccessToken); + util.puts("oauth_token_secret :" + oauthAccessTokenSecret); + util.puts("accesstoken results :" + util.inspect(results2)); + util.puts("Requesting access token"); + var data = ""; + oa.getProtectedResource( + "http://term.ie/oauth/example/echo_api.php?foo=bar&too=roo", + "GET", + oauthAccessToken, + oauthAccessTokenSecret, + function (error, data, response) { util.puts(data); - }); + }); }); - } -}) +}); diff --git a/examples/twitter-example.js b/examples/twitter-example.js index 90b6adcb..088703e7 100644 --- a/examples/twitter-example.js +++ b/examples/twitter-example.js @@ -1,75 +1,106 @@ -var http = require('http'); -var OAuth = require('../lib/oauth.js').OAuth; -var nodeUrl = require('url'); -var clientID = ''; -var clientSecret = ''; -var callbackURL = ''; +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * + * 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. -oa = new OAuth( - 'https://api.twitter.com/oauth/request_token', - 'https://api.twitter.com/oauth/access_token', - clientID, - clientSecret, - '1.0', - callbackURL, - 'HMAC-SHA1' -); + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ -http.createServer(function (request, response) { - oa.getOAuthRequestToken(function (error, oAuthToken, oAuthTokenSecret, results) { - var urlObj = nodeUrl.parse(request.url, true); - var authURL = 'https://twitter.com/' + - 'oauth/authenticate?oauth_token=' + oAuthToken; - var handlers = { - '/': function (request, response) { - /** - * Creating an anchor with authURL as href and sending as response - */ - var body = ' Get Code '; - response.writeHead(200, { - 'Content-Length': body.length, - 'Content-Type': 'text/html' }); - response.end(body); - }, - '/callback': function (request, response) { - /** Obtaining access_token */ - var getOAuthRequestTokenCallback = function (error, oAuthAccessToken, - oAuthAccessTokenSecret, results) { - if (error) { - console.log(error); - response.end(JSON.stringify({ - message: 'Error occured while getting access token', - error: error - })); - return; - } +var http = require("http"); +var OAuth = require("../lib/oauth.js").OAuth; +var nodeUrl = require("url"); +var clientID = ""; +var clientSecret = ""; +var callbackURL = "http://localhost:8080/callback"; - oa.get('https://api.twitter.com/1.1/account/verify_credentials.json', - oAuthAccessToken, - oAuthAccessTokenSecret, - function (error, twitterResponseData, result) { - if (error) { - console.log(error) - res.end(JSON.stringify(error)); - return; - } - try { - console.log(JSON.parse(twitterResponseData)); - } catch (parseError) { - console.log(parseError); - } - console.log(twitterResponseData); - response.end(twitterResponseData); - }); - }; +var oa = new OAuth( + "https://api.twitter.com/oauth/request_token", + "https://api.twitter.com/oauth/access_token", + clientID, + clientSecret, + "1.0", + callbackURL, + "HMAC-SHA1" +); - oa.getOAuthAccessToken(urlObj.query.oauth_token, oAuthTokenSecret, - urlObj.query.oauth_verifier, - getOAuthRequestTokenCallback); +http.createServer(function (request, response) { + oa.getOAuthRequestToken(function (error, oAuthToken, oAuthTokenSecret, results) { + var urlObj = nodeUrl.parse(request.url, true); + var handlers = { + "/": function (request, response) { + /** + * Creating an anchor with authURL as href and sending as response + */ + oa.getOAuthRequestToken(function (error) { + var statusCode; + var body; + var authURL; + if (error) { + statusCode = 401; + body = "Error: " + error.data; + } else { + statusCode = 200; + authURL = "https://api.twitter.com/oauth/authorize?oauth_token=" + oAuthToken; + body = " Get Code "; + } + response.writeHead(statusCode, { + "Content-Length": body.length, + "Content-Type": "text/html" + }); + response.end(body); + }); + }, + "/callback": function (request, response) { + /** Obtaining access_token */ + var getOAuthRequestTokenCallback = function (error, oAuthAccessToken, oAuthAccessTokenSecret, results) { + if (error) { + console.log(error); + response.end(JSON.stringify({ + message: "Error occured while getting access token", + error: error + })); + return; + } - } + oa.get( + "https://api.twitter.com/1.1/account/verify_credentials.json", + oAuthAccessToken, + oAuthAccessTokenSecret, + function (error, twitterResponseData, result) { + if (error) { + console.log(error); + response.end(JSON.stringify(error)); + return; + } + try { + console.log(JSON.parse(twitterResponseData)); + } catch (parseError) { + console.log(parseError); + } + console.log(twitterResponseData); + response.end(twitterResponseData); + }); }; - handlers[urlObj.pathname](request, response); - }) -}).listen(3000); + oa.getOAuthAccessToken( + urlObj.query.oauth_token, + oAuthTokenSecret, + urlObj.query.oauth_verifier, + getOAuthRequestTokenCallback + ); + } + }; + handlers[urlObj.pathname](request, response); + }); +}).listen(8080); diff --git a/examples/twitter-oauth-promises.js b/examples/twitter-oauth-promises.js new file mode 100644 index 00000000..97039448 --- /dev/null +++ b/examples/twitter-oauth-promises.js @@ -0,0 +1,59 @@ +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2016 Rudolf Olah + * + * 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 . + */ + +var OAuth = require("../index").PromiseOAuth; + +// Setting up the OAuth client +var requestUrl = "https://api.twitter.com/oauth/request_token"; +var accessUrl = "https://api.twitter.com/oauth/access_token"; +var version = "1.0"; +var authorizeCallback = "oob"; +var signatureMethod = "HMAC-SHA1"; +var nonceSize = null; +var customHeaders = null; + +// Go to https://dev.twitter.com/oauth/overview/application-owner-access-tokens +// to fill these in: +var consumerKey = "your consumer key"; +var consumerSecret = "your consumer secret"; + +var client = new OAuth( + requestUrl, accessUrl, + consumerKey, consumerSecret, + version, + authorizeCallback, + signatureMethod, + nonceSize, + customHeaders +); + +// Making a request to the API +var url = "https://api.twitter.com/1.1/statuses/home_timeline.json"; + +// Go to https://dev.twitter.com/oauth/overview/application-owner-access-tokens +// to fill these in: +var accessToken = "your access token"; +var accessTokenSecret = "your access token secret"; + +client.get(url, accessToken, accessTokenSecret).then(function(data, response) { + console.log("Data: " + data); + console.log("Response: " + response); +}).catch(function(error) { + console.log("Error: " + error); +}); diff --git a/index.js b/index.js index e20716dd..36c0d05a 100644 --- a/index.js +++ b/index.js @@ -1,3 +1,54 @@ +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * Copyright (C) 2016 Rudolf Olah + * + * 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 . + */ + +/** + * Node OAuth Libre + * @module oauth-libre + */ + +/** + * OAuth 1.0 + * @see OAuth + */ exports.OAuth = require("./lib/oauth").OAuth; + +/** + * OAuth 1.0 Echo + * @see OAuthEcho + */ exports.OAuthEcho = require("./lib/oauth").OAuthEcho; -exports.OAuth2 = require("./lib/oauth2").OAuth2; \ No newline at end of file + +/** + * OAuth 2.0 + * @see OAuth2 + */ +exports.OAuth2 = require("./lib/oauth2").OAuth2; + +/** + * OAuth 1.0 with Promises interface instead of callbacks + * @see OAuthPromise + */ +exports.PromiseOAuth = require("./lib/oauth-promise").OAuth; + +/** + * OAuth 2.0 with Promises interface instead of callbacks + * @see OAuth2Promise + */ +exports.PromiseOAuth2 = require("./lib/oauth2-promise").OAuth2; diff --git a/lib/_utils.js b/lib/_utils.js index 69fc3009..c7b91651 100644 --- a/lib/_utils.js +++ b/lib/_utils.js @@ -1,4 +1,30 @@ -// Returns true if this is a host that closes *before* it ends?!?! -module.exports.isAnEarlyCloseHost= function( hostName ) { - return hostName && hostName.match(".*google(apis)?.com$") -} \ No newline at end of file +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * + * 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 . + */ + +/** @module OAuthUtils */ + +/** + * Returns true if this is a host that closes *before* it ends?!?! + * + * @param {string} hostName + * @return {boolean} True if the host name includes Google + */ +module.exports.isAnEarlyCloseHost = function(hostName) { + return hostName && hostName.match(".*google(apis)?.com$"); +}; diff --git a/lib/oauth-promise.js b/lib/oauth-promise.js new file mode 100644 index 00000000..8165cdfc --- /dev/null +++ b/lib/oauth-promise.js @@ -0,0 +1,178 @@ +/* + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2016 Rudolf Olah + * + * 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 . + */ + +var Promise = require("bluebird"); +var _OAuth = require("./oauth").OAuth; + +/** + * Constructor for Promisified OAuth1 object. Creates the original + * class and delegates most methods to it. + * + * @class OAuthPromise + */ +var OAuth = function(requestUrl, accessUrl, consumerKey, consumerSecret, version, authorize_callback, signatureMethod, nonceSize, customHeaders) { + this._oa = new _OAuth(requestUrl, accessUrl, consumerKey, consumerSecret, version, authorize_callback, signatureMethod, nonceSize, customHeaders); + this._oa.prototype = Promise.promisifyAll(_OAuth.prototype, { multiArgs: true }); +}; + +/** + * Delegates the method in the Promisified OAuth1 class to the + * original class. + * @private + */ +function delegate(methodName) { + OAuth.prototype[methodName] = function() { + return this._oa[methodName].apply(this._oa, arguments); + }; +} + +/** + * Delegates the asynchronous method in the Promisified OAuth1 class to + * the original class (these method names end with "Async"). + * @private + */ +function asyncDelegate(methodName) { + OAuth.prototype[methodName] = function() { + return this._oa[methodName + "Async"].apply(this._oa, arguments); + }; +} + +var delegatedPromiseMethods = [ + /** + * @method delete + * @memberof OAuthPromise + * @instance + * @see OAuth#delete + * @return {Promise} + */ + "delete", + + /** + * @method get + * @memberof OAuthPromise + * @instance + * @see OAuth#get + * @return {Promise} + */ + "get", + + /** + * @method getOAuthAccessToken + * @memberof OAuthPromise + * @instance + * @see OAuth#getOAuthAccessToken + * @return {Promise} + */ + "getOAuthAccessToken", + + /** + * @method getOAuthRequestToken + * @memberof OAuthPromise + * @instance + * @see OAuth#getOAuthRequestToken + * @return {Promise} + */ + "getOAuthRequestToken", + + /** + * @method post + * @memberof OAuthPromise + * @instance + * @see OAuth#post + * @return {Promise} + */ + "post", + + /** + * @method put + * @memberof OAuthPromise + * @instance + * @see OAuth#put + * @return {Promise} + */ + "put" +]; + +delegatedPromiseMethods.forEach(asyncDelegate); + +/** + * delegates PromiseOAuth.methodName to OAuth.methodName + * @private + */ +var delegatedMethods = [ + /** + * @instance + * @method authHeader + * @memberof OAuthPromise + * @see OAuth#authHeader + */ + "authHeader", + + /** + * @instance + * @method getProtectedResource + * @memberof OAuthPromise + * @see OAuth#getProtectedResource + */ + "getProtectedResource", + + /** + * @instance + * @method setClientOptions + * @memberof OAuthPromise + * @see OAuth#setClientOptions + */ + "setClientOptions", + + /** + * @instance + * @method setDefaultContentType + * @memberof OAuthPromise + * @see OAuth#setDefaultContentType + */ + "setDefaultContentType", + + /** + * @instance + * @method signUrl + * @memberof OAuthPromise + * @see OAuth#signUrl + */ + "signUrl", + + // Required for testing + "_buildAuthorizationHeaders", + "_createSignature", + "_createSignatureBase", + "_encodeData", + "_getNonce", + "_getSignature", + "_getTimestamp", + "_isParameterNameAnOAuthParameter", + "_makeArrayOfArgumentsHash", + "_normaliseRequestParams", + "_normalizeUrl", + "_performSecureRequest", + "_prepareParameters", + "_sortRequestParams" +]; + +delegatedMethods.forEach(delegate); + +exports.OAuth = OAuth; diff --git a/lib/oauth.js b/lib/oauth.js index 50dccf99..25fe5758 100644 --- a/lib/oauth.js +++ b/lib/oauth.js @@ -1,3 +1,22 @@ +/* + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * + * 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 . + */ + var crypto= require('crypto'), sha1= require('./sha1'), http= require('http'), @@ -6,6 +25,19 @@ var crypto= require('crypto'), querystring= require('querystring'), OAuthUtils= require('./_utils'); +/** + * OAuth 1.0 client + * @class + * @param {string} requestUrl + * @param {string} accessUrl + * @param {string} consumerKey + * @param {string} consumerSecret + * @param {string} version + * @param {string} authorize_callback default is "oob" + * @param {string} signatureMethod can be PLAINTEXT, HMAC-SHA1 or RSA-SHA1 + * @param {number} nonceSize default is 32 + * @param {Object} customHeaders Default headers are set for Accept, Connection, User-Agent + */ exports.OAuth= function(requestUrl, accessUrl, consumerKey, consumerSecret, version, authorize_callback, signatureMethod, nonceSize, customHeaders) { this._isEcho = false; @@ -28,6 +60,11 @@ exports.OAuth= function(requestUrl, accessUrl, consumerKey, consumerSecret, vers throw new Error("Un-supported signature method: " + signatureMethod ) this._signatureMethod= signatureMethod; this._nonceSize= nonceSize || 32; + this._defaultContentType = 'application/x-www-form-urlencoded'; + if (customHeaders && customHeaders['Content-Type']) { + this._defaultContentType = customHeaders['Content-Type']; + delete customHeaders['Content-Type']; + } this._headers= customHeaders || {"Accept" : "*/*", "Connection" : "close", "User-Agent" : "Node authentication"} @@ -37,6 +74,19 @@ exports.OAuth= function(requestUrl, accessUrl, consumerKey, consumerSecret, vers this._oauthParameterSeperator = ","; }; +/** + * OAuth 1.0 Echo client + * @class + * @augments OAuth + * @param realm + * @param verify_credentials + * @param {string} consumerKey + * @param {string} consumerSecret + * @param {string} version + * @param {string} signatureMethod can be PLAINTEXT, HMAC-SHA1 or RSA-SHA1 + * @param {number} nonceSize default is 32 + * @param {Object} customHeaders Default headers are set for Accept, Connection, User-Agent + */ exports.OAuthEcho= function(realm, verify_credentials, consumerKey, consumerSecret, version, signatureMethod, nonceSize, customHeaders) { this._isEcho = true; @@ -61,10 +111,23 @@ exports.OAuthEcho= function(realm, verify_credentials, consumerKey, consumerSecr exports.OAuthEcho.prototype = exports.OAuth.prototype; +/** + * Returns the current time as a UNIX timestamp + * + * @return {number} + */ exports.OAuth.prototype._getTimestamp= function() { return Math.floor( (new Date()).getTime() / 1000 ); } +/** + * Encodes the data given by replacing characters "!'()*" with their + * encoded equivalents and returning the result of encodeURIComponent. + * + * @param {string} toEncode + * @return {string} + * @see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent + */ exports.OAuth.prototype._encodeData= function(toEncode){ if( toEncode == null || toEncode == "" ) return "" else { @@ -78,6 +141,14 @@ exports.OAuth.prototype._encodeData= function(toEncode){ } } +/** + * Decodes the data provided by replacing "+" plus character with + * spaces and returning the result of decodeURIComponent. + * + * @param {string} toDecode + * @return {string} + * @see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent + */ exports.OAuth.prototype._decodeData= function(toDecode) { if( toDecode != null ) { toDecode = toDecode.replace(/\+/g, " "); @@ -85,11 +156,25 @@ exports.OAuth.prototype._decodeData= function(toDecode) { return decodeURIComponent( toDecode); } +/** + * Returns the signature + * + * @param {string} method HTTP method + * @param {string} url + * @param {Object} parameters Query string parameters + * @param {string} tokenSecret + */ exports.OAuth.prototype._getSignature= function(method, url, parameters, tokenSecret) { var signatureBase= this._createSignatureBase(method, url, parameters); return this._createSignature( signatureBase, tokenSecret ); } +/** + * Normalizes the URL by accounting for custom HTTP and HTTPS ports. + * + * @param {string} url + * @return {string} + */ exports.OAuth.prototype._normalizeUrl= function(url) { var parsedUrl= URL.parse(url, true) var port =""; @@ -105,7 +190,12 @@ exports.OAuth.prototype._normalizeUrl= function(url) { return parsedUrl.protocol + "//" + parsedUrl.hostname + port + parsedUrl.pathname; } -// Is the parameter considered an OAuth parameter +/** + * Is the parameter considered an OAuth parameter. + * + * @param {string} parameter + * @return {boolean} true if the parameter starts with "oauth_" + */ exports.OAuth.prototype._isParameterNameAnOAuthParameter= function(parameter) { var m = parameter.match('^oauth_'); if( m && ( m[0] === "oauth_" ) ) { @@ -116,7 +206,12 @@ exports.OAuth.prototype._isParameterNameAnOAuthParameter= function(parameter) { } }; -// build the OAuth request authorization header +/** + * Build the OAuth request authorization header + * + * @param {Object} orderedParameters + * @return {Object} the authorization header + */ exports.OAuth.prototype._buildAuthorizationHeaders= function(orderedParameters) { var authHeader="OAuth "; if( this._isEcho ) { @@ -135,8 +230,13 @@ exports.OAuth.prototype._buildAuthorizationHeaders= function(orderedParameters) return authHeader; } -// Takes an object literal that represents the arguments, and returns an array -// of argument/value pairs. +/** + * Takes an object literal that represents the arguments, and returns + * an array of argument/value pairs. + * + * @param {Object} argumentsHash + * @return {Array} + */ exports.OAuth.prototype._makeArrayOfArgumentsHash= function(argumentsHash) { var argument_pairs= []; for(var key in argumentsHash ) { @@ -155,7 +255,13 @@ exports.OAuth.prototype._makeArrayOfArgumentsHash= function(argumentsHash) { return argument_pairs; } -// Sorts the encoded key value pairs by encoded name, then encoded value +/** + * Sorts the encoded key value pairs by encoded name, then encoded + * value + * + * @param {Array} argument_pairs + * @param {Array} + */ exports.OAuth.prototype._sortRequestParams= function(argument_pairs) { // Sort by name, then value. argument_pairs.sort(function(a,b) { @@ -168,6 +274,12 @@ exports.OAuth.prototype._sortRequestParams= function(argument_pairs) { return argument_pairs; } +/** + * Normalizes the request parameters. + * + * @param {Object} args + * @return {Object} + */ exports.OAuth.prototype._normaliseRequestParams= function(args) { var argument_pairs= this._makeArrayOfArgumentsHash(args); // First encode them #3.4.1.3.2 .1 @@ -190,12 +302,28 @@ exports.OAuth.prototype._normaliseRequestParams= function(args) { return args; } +/** + * Creates the base signature + * + * @param {string} method HTTP Method + * @param {string} url + * @param {string} parameters Query string parameters + * @return {string} + */ exports.OAuth.prototype._createSignatureBase= function(method, url, parameters) { url= this._encodeData( this._normalizeUrl(url) ); parameters= this._encodeData( parameters ); return method.toUpperCase() + "&" + url + "&" + parameters; } +/** + * Creates the signature from the base signature and token secret + * + * @param {string} signatureBase + * @param {string} tokenSecret + * @return {string} The hashed version of the signature + * @see OAuth#_createSignatureBase + */ exports.OAuth.prototype._createSignature= function(signatureBase, tokenSecret) { if( tokenSecret === undefined ) var tokenSecret= ""; else tokenSecret= this._encodeData( tokenSecret ); @@ -215,17 +343,27 @@ exports.OAuth.prototype._createSignature= function(signatureBase, tokenSecret) { hash = crypto.createHmac("sha1", key).update(signatureBase).digest("base64"); } else { - hash= sha1.HMACSHA1(key, signatureBase); + hash= sha1.hmacsha1(key, signatureBase); } } return hash; } + +/** + * The characters that can be used in the nonce + */ exports.OAuth.prototype.NONCE_CHARS= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v','w','x','y','z','A','B', 'C','D','E','F','G','H','I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3', '4','5','6','7','8','9']; +/** + * Generates a new nonce with the size of nonceSize + * + * @param {number} nonceSize + * @return {string} + */ exports.OAuth.prototype._getNonce= function(nonceSize) { var result = []; var chars= this.NONCE_CHARS; @@ -239,6 +377,9 @@ exports.OAuth.prototype._getNonce= function(nonceSize) { return result.join(''); } +/** + * Creates the OAuth client + */ exports.OAuth.prototype._createClient= function( port, hostname, method, path, headers, sslEnabled ) { var options = { host: hostname, @@ -253,9 +394,24 @@ exports.OAuth.prototype._createClient= function( port, hostname, method, path, h } else { httpModel= http; } + + for (var k in this._httpOptions) { + options[k] = this._httpOptions[k]; + } + return httpModel.request(options); } +/** + * Sets the HTTP (or HTTPS) options for requests + * + * @see for HTTPS options: https://nodejs.org/api/https.html#https_https_request_options_callback + * @see for HTTP options: https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener + */ +exports.OAuth.prototype.setHttpOptions = function(options) { + this._httpOptions = options; +} + exports.OAuth.prototype._prepareParameters= function( oauth_token, oauth_token_secret, method, url, extra_params ) { var oauthParameters= { "oauth_timestamp": this._getTimestamp(), @@ -305,11 +461,31 @@ exports.OAuth.prototype._prepareParameters= function( oauth_token, oauth_token_s return orderedParameters; } +/** + * @callback requestCallback + * @memberof OAuth + * @param error + * @param data + * @param response + */ + +/** + * Peforms an HTTP or HTTPS request + * + * @param {string} oauth_token + * @param {string} oauth_token_string + * @param {string} method + * @param {string} url + * @param {Object} extra_params + * @param {Buffer} post_body + * @param {string} post_content_type + * @param {OAuth.requestCallback} callback + */ exports.OAuth.prototype._performSecureRequest= function( oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback ) { var orderedParameters= this._prepareParameters(oauth_token, oauth_token_secret, method, url, extra_params); if( !post_content_type ) { - post_content_type= "application/x-www-form-urlencoded"; + post_content_type= this._defaultContentType; } var parsedUrl= URL.parse( url, false ); if( parsedUrl.protocol == "http:" && !parsedUrl.port ) parsedUrl.port= 80; @@ -339,7 +515,7 @@ exports.OAuth.prototype._performSecureRequest= function( oauth_token, oauth_toke } } - if( (method == "POST" || method == "PUT") && ( post_body == null && extra_params != null) ) { + if( (method == "POST" || method == "PUT" || method == "PATCH") && ( post_body == null && extra_params != null) ) { // Fix the mismatch between the output of querystring.stringify() and this._encodeData() post_body= querystring.stringify(extra_params) .replace(/\!/g, "%21") @@ -422,13 +598,13 @@ exports.OAuth.prototype._performSecureRequest= function( oauth_token, oauth_toke } }); - if( (method == "POST" || method =="PUT") && post_body != null && post_body != "" ) { + if( (method == "POST" || method =="PUT" || method == "PATCH") && post_body != null && post_body != "" ) { request.write(post_body); } request.end(); } else { - if( (method == "POST" || method =="PUT") && post_body != null && post_body != "" ) { + if( (method == "POST" || method =="PUT" || method == "PATCH") && post_body != null && post_body != "" ) { request.write(post_body); } return request; @@ -437,6 +613,11 @@ exports.OAuth.prototype._performSecureRequest= function( oauth_token, oauth_toke return; } +/** + * Sets the HTTP client options + * + * @param {Object} options + */ exports.OAuth.prototype.setClientOptions= function(options) { var key, mergedOptions= {}, @@ -452,9 +633,21 @@ exports.OAuth.prototype.setClientOptions= function(options) { this._clientOptions= mergedOptions; }; +exports.OAuth.prototype.setDefaultContentType= function(contentType) { + this._defaultContentType = contentType; +}; -exports.OAuth.prototype.getOAuthAccessToken= function(oauth_token, oauth_token_secret, oauth_verifier, callback) { - var extraParams= {}; +/** + * Performs a request to retrieve the OAuth Access Token + * + * @param {string} oauth_token + * @param {string} oauth_token_secret + * @param {string} oauth_verifier + * @param {OAuth.requestCallback} callback + * @param {Object} [extraParams] Extra parameters to send with the request + */ +exports.OAuth.prototype.getOAuthAccessToken= function(oauth_token, oauth_token_secret, oauth_verifier, callback, extraParams) { + var extraParams = extraParams || {}; if( typeof oauth_verifier == "function" ) { callback= oauth_verifier; } else { @@ -474,19 +667,48 @@ exports.OAuth.prototype.getOAuthAccessToken= function(oauth_token, oauth_token_s }) } -// Deprecated +/** + * @deprecated + */ exports.OAuth.prototype.getProtectedResource= function(url, method, oauth_token, oauth_token_secret, callback) { this._performSecureRequest( oauth_token, oauth_token_secret, method, url, null, "", null, callback ); } +/** + * Executes an authenticated DELETE request + * + * @param {string} url + * @param {string} oauth_token + * @param {string} oauth_token_string + * @param {OAuth.requestCallback} callback + */ exports.OAuth.prototype.delete= function(url, oauth_token, oauth_token_secret, callback) { return this._performSecureRequest( oauth_token, oauth_token_secret, "DELETE", url, null, "", null, callback ); } +/** + * Executes an authenticated GET request + * + * @param {string} url + * @param {string} oauth_token + * @param {string} oauth_token_string + * @param {OAuth.requestCallback} callback + */ exports.OAuth.prototype.get= function(url, oauth_token, oauth_token_secret, callback) { return this._performSecureRequest( oauth_token, oauth_token_secret, "GET", url, null, "", null, callback ); } +/** + * Executes an authenticated PUT or POST request + * + * @param {string} methpd + * @param {string} url + * @param {string} oauth_token + * @param {string} oauth_token_string + * @param {Buffer} post_body + * @param {string} post_content_type + * @param {OAuth.requestCallback} callback + */ exports.OAuth.prototype._putOrPost= function(method, url, oauth_token, oauth_token_secret, post_body, post_content_type, callback) { var extra_params= null; if( typeof post_content_type == "function" ) { @@ -501,15 +723,43 @@ exports.OAuth.prototype._putOrPost= function(method, url, oauth_token, oauth_tok return this._performSecureRequest( oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback ); } - +/** + * Executes an authenticated PUT request + * + * @param {string} url + * @param {string} oauth_token + * @param {string} oauth_token_string + * @param {Buffer} post_body + * @param {string} post_content_type + * @param {OAuth.requestCallback} callback + */ exports.OAuth.prototype.put= function(url, oauth_token, oauth_token_secret, post_body, post_content_type, callback) { return this._putOrPost("PUT", url, oauth_token, oauth_token_secret, post_body, post_content_type, callback); } +/** + * Executes an authenticated POST request + * + * @param {string} url + * @param {string} oauth_token + * @param {string} oauth_token_string + * @param {Buffer} post_body + * @param {string} post_content_type + * @param {OAuth.requestCallback} callback + */ exports.OAuth.prototype.post= function(url, oauth_token, oauth_token_secret, post_body, post_content_type, callback) { return this._putOrPost("POST", url, oauth_token, oauth_token_secret, post_body, post_content_type, callback); } +/** + * @callback oauthRequestTokenCallback + * @memberof OAuth + * @param error + * @param token + * @param tokenSecret + * @param parsedQueryString + */ + /** * Gets a request token from the OAuth provider and passes that information back * to the calling code. @@ -529,7 +779,9 @@ exports.OAuth.prototype.post= function(url, oauth_token, oauth_token_secret, pos * N.B. This method will HTTP POST verbs by default, if you wish to override this behaviour you will * need to provide a requestTokenHttpMethod option when creating the client. * - **/ + * @param {Object} extraParams + * @param {OAuth.oauthRequestTokenCallback} + */ exports.OAuth.prototype.getOAuthRequestToken= function( extraParams, callback ) { if( typeof extraParams == "function" ){ callback = extraParams; @@ -553,29 +805,61 @@ exports.OAuth.prototype.getOAuthRequestToken= function( extraParams, callback ) }); } -exports.OAuth.prototype.signUrl= function(url, oauth_token, oauth_token_secret, method) { +/** + * Returns the prepared ordered parameters + * + * @param oauthToken + * @param oauthTokenSecret + * @param method If this is undefined or null, default is 'GET' + * @param url + * + * @return the result of calling _prepareParameters + */ +exports.OAuth.prototype._getOrderedParameters = function(oauthToken, oauthTokenSecret, method, url) { + return this._prepareParameters(oauthToken, oauthTokenSecret, method ? method : 'GET', url, {}); +}; - if( method === undefined ) { - var method= "GET"; - } +/** + * Signs the url + * + * @param url + * @param oauthToken + * @param oauthTokenSecret + * @param method + * + * @see OAuth._getOrderedParameters + * @see OAuth._encodeData + */ +exports.OAuth.prototype.signUrl = function(url, oauthToken, oauthTokenSecret, method) { - var orderedParameters= this._prepareParameters(oauth_token, oauth_token_secret, method, url, {}); - var parsedUrl= URL.parse( url, false ); + var orderedParameters = this._getOrderedParameters(oauthToken, oauthTokenSecret, method, url); - var query=""; - for( var i= 0 ; i < orderedParameters.length; i++) { - query+= orderedParameters[i][0]+"="+ this._encodeData(orderedParameters[i][1]) + "&"; + var parsedUrl = URL.parse( url, false ); + + var query = ""; + for (var i = 0; i < orderedParameters.length; i++) { + query += orderedParameters[i][0] + "=" + + this._encodeData(orderedParameters[i][1]) + "&"; } - query= query.substring(0, query.length-1); + query = query.substring(0, query.length - 1); - return parsedUrl.protocol + "//"+ parsedUrl.host + parsedUrl.pathname + "?" + query; + return parsedUrl.protocol + "//" + + parsedUrl.host + parsedUrl.pathname + "?" + + query; }; -exports.OAuth.prototype.authHeader= function(url, oauth_token, oauth_token_secret, method) { - if( method === undefined ) { - var method= "GET"; - } - - var orderedParameters= this._prepareParameters(oauth_token, oauth_token_secret, method, url, {}); +/** + * Returns the built authorization header + * + * @param url + * @param oauthToken + * @param oauthTokenSecret + * @param method + * + * @see OAuth._getOrderedParameters + * @see OAuth._buildAuthorizationHeaders + */ +exports.OAuth.prototype.authHeader = function(url, oauthToken, oauthTokenSecret, method) { + var orderedParameters = this._getOrderedParameters(oauthToken, oauthTokenSecret, method, url); return this._buildAuthorizationHeaders(orderedParameters); }; diff --git a/lib/oauth2-promise.js b/lib/oauth2-promise.js new file mode 100644 index 00000000..0cb798d2 --- /dev/null +++ b/lib/oauth2-promise.js @@ -0,0 +1,77 @@ +/* + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2016 Rudolf Olah + * + * 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 . + */ + +var Promise = require("bluebird"); +var _OAuth2 = require("./oauth2").OAuth2; + +/** + * Constructor for Promisified OAuth2 object. Creates the original + * class and delegates most methods to it. + * + * @class OAuth2Promise + */ +var OAuth2 = function(clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders) { + this._oa = new _OAuth2(clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders); + this._oa.prototype = Promise.promisifyAll(_OAuth2.prototype, { multiArgs: true }); +}; + +/** + * Promisified getOAuthAccessToken method + * @see OAuth2~getOAuthAccessToken + */ +OAuth2.prototype.getOAuthAccessToken = function() { + return this._oa.getOAuthAccessTokenAsync.apply(this._oa, arguments); +}; + +/** + * Promisified get method + * @see OAuth2~get + */ +OAuth2.prototype.get = function() { + return this._oa.getAsync.apply(this._oa, arguments).then(function(res) { + return res[0]; + }); +}; + +// delegates PromiseOAuth2.methodName to OAuth2.methodName +var delegatedMethods = [ + "buildAuthHeader", + "getAuthorizeUrl", + "setAuthMethod", + "useAuthorizationHeaderforGET", + + // Required for testing + "_executeRequest", + "_request" +]; + +/** + * Delegates the method in the Promisified OAuth2 class to the + * original class. + * @private + */ +function delegate(methodName) { + OAuth2.prototype[methodName] = function() { + return this._oa[methodName].apply(this._oa, arguments); + }; +} + +delegatedMethods.forEach(delegate); + +exports.OAuth2 = OAuth2; diff --git a/lib/oauth2.js b/lib/oauth2.js index 94ed662c..0e4791f7 100644 --- a/lib/oauth2.js +++ b/lib/oauth2.js @@ -1,125 +1,347 @@ -var querystring= require('querystring'), - crypto= require('crypto'), - https= require('https'), - http= require('http'), - URL= require('url'), - OAuthUtils= require('./_utils'); - -exports.OAuth2= function(clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders) { - this._clientId= clientId; - this._clientSecret= clientSecret; - this._baseSite= baseSite; - this._authorizeUrl= authorizePath || "/oauth/authorize"; - this._accessTokenUrl= accessTokenPath || "/oauth/access_token"; - this._accessTokenName= "access_token"; - this._authMethod= "Bearer"; +/* + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * + * 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 . + */ + +var querystring = require("querystring"); +var crypto = require("crypto"); +var https = require("https"); +var http = require("http"); +var URL = require("url"); +var OAuthUtils = require("./_utils"); +var Buffer = require("buffer").Buffer; +var util = require("util"); + +var EventEmitter = require("events").EventEmitter; + +/** + * OAuth 2.0 client + * @class + * @param {string} clientId The id of the client + * @param {string} clientSecret The secret key of the client + * @param {string} baseSite URL of the OAuth endpoint + * @param {string} authorizePath URL for token authorization endpoint + * @param {string} accessTokenPath URL for access token endpoint + * @param {Object} customHeaders HTTP headers for every request + */ +exports.OAuth2 = function (clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders) { + EventEmitter.call(this); + /** @protected */ + this._clientId = clientId; + /** @protected */ + this._clientSecret = clientSecret; + /** @protected */ + this._baseSite = baseSite; + + /** + * @protected + * @default "/oauth/authorize" + */ + this._authorizeUrl = authorizePath || "/oauth/authorize"; + + /** + * @protected + * @default "/oauth/access_token" + */ + this._accessTokenUrl = accessTokenPath || "/oauth/access_token"; + + /** + * The name of the access token in the query string + * @protected + * @default "access_token" + */ + this._accessTokenName = "access_token"; + + /** + * The authorization method to use + * @protected + * @default "Bearer" + */ + this._authMethod = "Bearer"; + + /** + * Custom headers for each request + * @protected + * @default {} + */ this._customHeaders = customHeaders || {}; - this._useAuthorizationHeaderForGET= false; -} - -// This 'hack' method is required for sites that don't use -// 'access_token' as the name of the access token (for requests). -// ( http://tools.ietf.org/html/draft-ietf-oauth-v2-16#section-7 ) -// it isn't clear what the correct value should be atm, so allowing -// for specific (temporary?) override for now. -exports.OAuth2.prototype.setAccessTokenName= function ( name ) { - this._accessTokenName= name; -} - -// Sets the authorization method for Authorization header. -// e.g. Authorization: Bearer # "Bearer" is the authorization method. -exports.OAuth2.prototype.setAuthMethod = function ( authMethod ) { - this._authMethod = authMethod; + + /** + * Whether or not to use the authorization header for a GET request + * @protected + * @default false + */ + this._useAuthorizationHeaderForGET = false; }; +/** + * inherits from EventEmitter should use extends for future versions + */ +util.inherits(exports.OAuth2, EventEmitter); -// If you use the OAuth2 exposed 'get' method (and don't construct your own _request call ) -// this will specify whether to use an 'Authorize' header instead of passing the access_token as a query parameter -exports.OAuth2.prototype.useAuthorizationHeaderforGET = function(useIt) { - this._useAuthorizationHeaderForGET= useIt; -} +/** + * This 'hack' method is required for sites that don't use + * 'access_token' as the name of the access token (for requests). It + * isn't clear what the correct value should be at the moment, so + * allowing for specific (temporary?) override for now. + * + * @param {string} name + * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-16#section-7 + */ +exports.OAuth2.prototype.setAccessTokenName = function (name) { + this._accessTokenName = name; +}; -exports.OAuth2.prototype._getAccessTokenUrl= function() { +/** + * Sets the authorization method for Authorization header. + * e.g. Authorization: Bearer # "Bearer" is the authorization method. + * + * @param {string} authMethod + */ +exports.OAuth2.prototype.setAuthMethod = function (authMethod) { + this._authMethod = authMethod; +}; + +/** + * If you use the OAuth2 exposed 'get' method (and don't construct + * your own _request call) this will specify whether to use an + * 'Authorize' header instead of passing the access_token as a query + * parameter + * + * @param {boolean} useIt + */ +exports.OAuth2.prototype.useAuthorizationHeaderforGET = function (useIt) { + this._useAuthorizationHeaderForGET = useIt; +}; + +/** + * Returns the access token url constructed from the baseSite and + * accessTokenUrl. + * + * @return {string} + */ +exports.OAuth2.prototype._getAccessTokenUrl = function () { return this._baseSite + this._accessTokenUrl; /* + "?" + querystring.stringify(params); */ -} +}; -// Build the authorization header. In particular, build the part after the colon. -// e.g. Authorization: Bearer # Build "Bearer " -exports.OAuth2.prototype.buildAuthHeader= function(token) { - return this._authMethod + ' ' + token; +/** + * Build the authorization header. In particular, build the part after the colon. + * e.g. Authorization: Bearer # Build "Bearer " + * + * @param {string} token + * @return {string} + */ +exports.OAuth2.prototype.buildAuthHeader = function (token) { + return this._authMethod + " " + token; }; -exports.OAuth2.prototype._chooseHttpLibrary= function( parsedUrl ) { - var http_library= https; +/** + * Chooses the HTTP or HTTPS library. Assumes HTTPS by default. + * + * @param {url} parsedUrl Protocol of this URL begins with "http:" or "https:", if it does not assumes HTTPS protocol. + * + * @return {Object} http or https library + */ +exports.OAuth2.prototype._chooseHttpLibrary = function (parsedUrl) { + var httpLibrary = https; // As this is OAUth2, we *assume* https unless told explicitly otherwise. - if( parsedUrl.protocol != "https:" ) { - http_library= http; + if (parsedUrl.protocol != "https:") { + httpLibrary = http; } - return http_library; + return httpLibrary; }; -exports.OAuth2.prototype._request= function(method, url, headers, post_body, access_token, callback) { +/** + * Callback when the request has completed + * + * @callback OAuth2~executeRequestCallback + * @param {object|null} data + * @param {number} data.statusCode The HTTP Status Code + * @param {any} data.data The data from the response + * @param {any} result The data from the response + * @param {Response} response The HTTP response object + */ - var parsedUrl= URL.parse( url, true ); - if( parsedUrl.protocol == "https:" && !parsedUrl.port ) { - parsedUrl.port= 443; +/** + * Executes an HTTP (or HTTPS) request. If the User-Agent HTTP header + * is not provided in _customHeaders or in the headers parameter, the + * default is "Node-oauth". + * + * @fires OAuth2#request:before + * @fires OAuth2#request:after + * + * @param {string} method The HTTP method to use (GET, POST, PUT, HEAD) + * @param {string} url The URL to execute the request against + * @param {Object} headers The headers to send as part of this request + * @param {Buffer|null} postBody The body to send if this is a POST request + * @param {string} accessToken The access token + * @param {OAuth2~executeRequestCallback} callback The callback function to call when the request has been completed + */ +exports.OAuth2.prototype._request = function oauth2Request(method, url, headers, postBody, accessToken, callback) { + var key; + var instance = this; + var parsedUrl = URL.parse(url, true); + if (parsedUrl.protocol === "https:" && !parsedUrl.port) { + parsedUrl.port = 443; } - var http_library= this._chooseHttpLibrary( parsedUrl ); - + var httpLibrary = this._chooseHttpLibrary(parsedUrl); - var realHeaders= {}; - for( var key in this._customHeaders ) { - realHeaders[key]= this._customHeaders[key]; + var realHeaders = {}; + for (key in this._customHeaders) { + if ({}.hasOwnProperty.call(this._customHeaders, key)) { + realHeaders[key] = this._customHeaders[key]; + } } - if( headers ) { - for(var key in headers) { - realHeaders[key] = headers[key]; + if (headers) { + for (key in headers) { + if ({}.hasOwnProperty.call(headers, key)) { + realHeaders[key] = headers[key]; + } } } - realHeaders['Host']= parsedUrl.host; + realHeaders["Host"] = parsedUrl.host; - if (!realHeaders['User-Agent']) { - realHeaders['User-Agent'] = 'Node-oauth'; + if (!realHeaders["User-Agent"]) { + realHeaders["User-Agent"] = "Node-oauth"; } - if( post_body ) { - if ( Buffer.isBuffer(post_body) ) { - realHeaders["Content-Length"]= post_body.length; - } else { - realHeaders["Content-Length"]= Buffer.byteLength(post_body); - } + if (postBody) { + if (Buffer.isBuffer(postBody)) { + realHeaders["Content-Length"] = postBody.length; + } else { + realHeaders["Content-Length"] = Buffer.byteLength(postBody); + } } else { - realHeaders["Content-length"]= 0; + realHeaders["Content-Length"] = 0; } - if( access_token && !('Authorization' in realHeaders)) { - if( ! parsedUrl.query ) parsedUrl.query= {}; - parsedUrl.query[this._accessTokenName]= access_token; + if (accessToken && !("Authorization" in realHeaders)) { + if (!parsedUrl.query) { + parsedUrl.query = {}; + } + parsedUrl.query[this._accessTokenName] = accessToken; } - var queryStr= querystring.stringify(parsedUrl.query); - if( queryStr ) queryStr= "?" + queryStr; + var queryStr = querystring.stringify(parsedUrl.query); + if (queryStr) { + queryStr = "?" + queryStr; + } var options = { - host:parsedUrl.hostname, + host: parsedUrl.hostname, port: parsedUrl.port, path: parsedUrl.pathname + queryStr, method: method, headers: realHeaders }; + + /** + * Prepare response callback for _executeRequest method and emit then OAuth2#request:after event. + * @method wrapRequestCallbackToEmit + * @param {object} oauth - This + * @param {OAuth2~executeRequestCallback} requestCallback - callback form original request method + * @return {OAuth2~executeRequestCallback} Function to be executed after request execution + */ + function wrapRequestCallbackToEmit(oauth, requestCallback) { + /** + * Event raised after a request is executed. + * + * @event OAuth2#request:after + * @type {function} + * @param {object} response - Contains information about response of the request + * @param {object} result - You can access to data returned from the request if there"s data. + */ + return function () { + var response, result; + if (arguments.length > 1) { + response = arguments[2]; // status code + result = arguments[1]; // result + oauth.emit("request:after", response, result); + requestCallback(arguments[0], arguments[1], arguments[2]); // null error , result data, status code + }else { + response = arguments[0].statusCode; + result = arguments[0].data; + oauth.emit("request:after", response, result); + requestCallback(arguments[0]); // error or response formated object + } + }; + } + + var executed = false; + var listenersCount = EventEmitter.listenerCount(this, "request:before"); + if (listenersCount > 0) { + /** + * This blocking callback allow to indicate when to continue when request execution, this is indicated + * by shouldExecute param. + * + * @callback requestBeforeCallback + * @param {object} optionsModified - Object contianing modified request optionsModified. + * @param {object} postBodyModified - Object contianing postBody request with new values. + * @param {boolean} shouldExecute - Indicates if request must be executes just before this event handling. + */ - this._executeRequest( http_library, options, post_body, callback ); -} + /** + * Event raised before a request is executed, pass a blocking flag to prevent + * many reques executions at same time. + * + * @event OAuth2#request:before + * @type {function} + * @param {object} options - Contains information of request like, host, post, path, method, and headers object + * @param {object} postBody - Contains information of request body parameters + * @param {requestBeforeCallback} done - Blocking function to pass modified request properties back + */ + instance.emit("request:before", options, postBody, function (optionsModified, postBodyModified, shouldExecute) { + shouldExecute = shouldExecute || false; + if (!executed && shouldExecute) { + executed = true; + instance._executeRequest(httpLibrary, optionsModified, postBodyModified, wrapRequestCallbackToEmit(instance, callback)); + } else if (shouldExecute) { + throw new Exception("request must be called just once"); + } + }); + } else { + instance._executeRequest(httpLibrary, options, postBody, wrapRequestCallbackToEmit(instance, callback)); + } +}; -exports.OAuth2.prototype._executeRequest= function( http_library, options, post_body, callback ) { +/** + * Executes an OAuth-authenticated HTTP or HTTPS request. Allows for + * some hosts that close connections early or that send no + * Content-Length header. + * + * Sends the postBody if the request method is a POST, PUT, or PATCH. + * + * @param {Object} httpLibrary The HTTP or HTTPS library to use to execute the request + * @param {Object} options The options for the request being made + * @param {string} options.method + * @param {Buffer|null} postBody + * @param {OAuth2~executeRequestCallback} callback + * + * @see OAuthUtils#isAnEarlyCloseHost + */ +exports.OAuth2.prototype._executeRequest = function (httpLibrary, options, postBody, callback) { // Some hosts *cough* google appear to close the connection early / send no content-length header // allow this behaviour. - var allowEarlyClose= OAuthUtils.isAnEarlyCloseHost(options.host); - var callbackCalled= false; - function passBackControl( response, result ) { - if(!callbackCalled) { - callbackCalled=true; - if( !(response.statusCode >= 200 && response.statusCode <= 299) && (response.statusCode != 301) && (response.statusCode != 302) ) { + var allowEarlyClose = OAuthUtils.isAnEarlyCloseHost(options.host); + var callbackCalled = false; + function passBackControl (response, result) { + if (!callbackCalled) { + callbackCalled = true; + if (!(response.statusCode >= 200 && response.statusCode <= 299) && (response.statusCode !== 301) && (response.statusCode !== 302)) { callback({ statusCode: response.statusCode, data: result }); } else { callback(null, result, response); @@ -127,88 +349,132 @@ exports.OAuth2.prototype._executeRequest= function( http_library, options, post_ } } - var result= ""; + var result = ""; - var request = http_library.request(options); - request.on('response', function (response) { + var request = httpLibrary.request(options); + request.on("response", function (response) { response.on("data", function (chunk) { - result+= chunk + result += chunk; }); response.on("close", function (err) { - if( allowEarlyClose ) { - passBackControl( response, result ); + if (allowEarlyClose) { + passBackControl(response, result); } }); response.addListener("end", function () { - passBackControl( response, result ); + passBackControl(response, result); }); }); - request.on('error', function(e) { - callbackCalled= true; + request.on("error", function (e) { + callbackCalled = true; callback(e); }); - if( (options.method == 'POST' || options.method == 'PUT') && post_body ) { - request.write(post_body); + if ((options.method === "POST" || options.method === "PUT" || options.method === "PATCH") && postBody) { + request.write(postBody); } request.end(); -} - -exports.OAuth2.prototype.getAuthorizeUrl= function( params ) { - var params= params || {}; - params['client_id'] = this._clientId; - return this._baseSite + this._authorizeUrl + "?" + querystring.stringify(params); -} - -exports.OAuth2.prototype.getOAuthAccessToken= function(code, params, callback) { - var params= params || {}; - params['client_id'] = this._clientId; - params['client_secret'] = this._clientSecret; - var codeParam = (params.grant_type === 'refresh_token') ? 'refresh_token' : 'code'; - params[codeParam]= code; - - var post_data= querystring.stringify( params ); - var post_headers= { - 'Content-Type': 'application/x-www-form-urlencoded' - }; - - - this._request("POST", this._getAccessTokenUrl(), post_headers, post_data, null, function(error, data, response) { - if( error ) callback(error); - else { +}; + +/** + * Returns the fully-qualified authorization url including query + * string parameters. + * + * @param params Query string parameters + */ +exports.OAuth2.prototype.getAuthorizeUrl = function (params) { + var mergedParams = params || {}; + mergedParams["client_id"] = this._clientId; + return this._baseSite + this._authorizeUrl + "?" + querystring.stringify(mergedParams); +}; + +/** + * Returns the authorization header + * + * @return {string} + */ +exports.OAuth2.prototype._getAuthorizationHeader = function () { + var clientIdAndSecret = this._clientId + ":" + this._clientSecret; + var clientInfoAsBase64 = new Buffer(clientIdAndSecret).toString("base64"); + return "Basic " + clientInfoAsBase64.toString(); +}; + +/** + * @callback OAuth2~accessTokenCallback + * @param {Error|null} error If there was an error in the request + * @param {string} accessToken The OAuth access token + * @param {string} refreshToken The OAuth refresh token + * @param {any} results The data from the HTTP response + */ + +/** + * Gets the OAuth access token from the OAuth2.0 endpoint. Sends a + * POST request to the access token url and on success or error, calls + * the provided callback. + * + * @param {string} code The code to send + * @param {Object} params The OAuth parameters to send + * @param {string} [params.grant_type] The grant type to use with OAuth, the two options are 'refresh_token' or 'code'. + * @param {OAuth2~accessTokenCallback} callback + */ +exports.OAuth2.prototype.getOAuthAccessToken = function (code, params, callback) { + var params = params || {}; + params["client_id"] = this._clientId; + params["client_secret"] = this._clientSecret; + var codeParam = (params.grant_type === "refresh_token") ? "refresh_token" : "code"; + params[codeParam] = code; + + var postData = querystring.stringify(params); + + var postHeaders = { + "Content-Type": "application/x-www-form-urlencoded", + "Authorization": this._getAuthorizationHeader() + }; + + this._request("POST", this._getAccessTokenUrl(), postHeaders, postData, null, function (error, data, response) { + if (error) { + callback(error); + } else { var results; try { // As of http://tools.ietf.org/html/draft-ietf-oauth-v2-07 // responses should be in JSON - results= JSON.parse( data ); - } - catch(e) { + results = JSON.parse(data); + } catch(e) { // .... However both Facebook + Github currently use rev05 of the spec // and neither seem to specify a content-type correctly in their response headers :( // clients of these services will suffer a *minor* performance cost of the exception // being thrown - results= querystring.parse( data ); + results = querystring.parse(data); } - var access_token= results["access_token"]; - var refresh_token= results["refresh_token"]; + var accessToken = results["access_token"]; + var refresh_token = results["refresh_token"]; delete results["refresh_token"]; - callback(null, access_token, refresh_token, results); // callback results =-= + callback(null, accessToken, refresh_token, results); // callback results =-= } }); -} +}; -// Deprecated -exports.OAuth2.prototype.getProtectedResource= function(url, access_token, callback) { - this._request("GET", url, {}, "", access_token, callback ); -} +/** + * @deprecated + */ +exports.OAuth2.prototype.getProtectedResource = function (url, accessToken, callback) { + this._request("GET", url, {}, "", accessToken, callback); +}; -exports.OAuth2.prototype.get= function(url, access_token, callback) { - if( this._useAuthorizationHeaderForGET ) { - var headers= {'Authorization': this.buildAuthHeader(access_token) } - access_token= null; - } - else { - headers= {}; +/** + * Executes an OAuth2-authenticated GET request to the url provided + * + * @param {string} url The URL to make a request to + * @param {string} accessToken OAuth 2.0 Access Token + * @param {OAuth2~executeRequestCallback} callback + */ +exports.OAuth2.prototype.get = function (url, accessToken, callback) { + if (this._useAuthorizationHeaderForGET) { + var headers = { "Authorization": this.buildAuthHeader(accessToken)}; + accessToken = null; + } else { + headers = {}; } - this._request("GET", url, headers, "", access_token, callback ); -} + this._request("GET", url, headers, "", accessToken, callback); +}; diff --git a/lib/sha1.js b/lib/sha1.js index d73277a6..a7f674b1 100644 --- a/lib/sha1.js +++ b/lib/sha1.js @@ -329,6 +329,6 @@ function bit_rol(num, cnt) return (num << cnt) | (num >>> (32 - cnt)); } -exports.HMACSHA1= function(key, data) { +exports.hmacsha1 = function(key, data) { return b64_hmac_sha1(key, data); -} \ No newline at end of file +} diff --git a/package.json b/package.json index 1a555333..0ea345b0 100644 --- a/package.json +++ b/package.json @@ -1,19 +1,46 @@ -{ "name" : "oauth" -, "description" : "Library for interacting with OAuth 1.0, 1.0A, 2 and Echo. Provides simplified client access and allows for construction of more complex apis and OAuth providers." -, "version" : "0.9.14" -, "directories" : { "lib" : "./lib" } -, "main" : "index.js" -, "author" : "Ciaran Jessup " -, "repository" : { "type":"git", "url":"http://github.com/ciaranj/node-oauth.git" } -, "devDependencies": { +{ + "name": "oauth-libre", + "description": "Library for interacting with OAuth 1.0, 1.0A, 2 and Echo. Provides simplified client access and allows for construction of more complex apis and OAuth providers. Licensed under the GNU GPL version 3 or later.", + "version": "0.9.17", + "directories": { + "lib": "./lib" + }, + "main": "index.js", + "author": "Ciaran Jessup ", + "contributors": [ + { + "name": "Rudolf Olah", + "email": "omouse@gmail.com" + } + ], + "repository": { + "type": "git", + "url": "http://github.com/omouse/node-oauth-libre.git" + }, + "devDependencies": { + "jsdoc": "^3.4.3", + "randomstring": "^1.1.5", "vows": "0.5.x" - } -, "scripts": { - "test": "make test" - } -, "licenses" : - [ { "type" : "MIT" - , "url" : "http://github.com/ciaranj/node-oauth/raw/master/LICENSE" + }, + "scripts": { + "test": "make test", + "build-docs": "jsdoc -c conf.json" + }, + "licenses": [ + { + "type": "GPL", + "url": "http://github.com/omouse/node-oauth-libre/raw/master/LICENSE" + }, + { + "type": "MIT", + "url": "https://github.com/omouse/node-oauth-libre/raw/master/LICENSE.mit" } - ] + ], + "optionalDependencies": { + "body-parser": "^1.15.0", + "bluebird": "^3.3.4", + "express": "^4.13.4", + "express-session": "^1.13.0", + "morgan": "^1.7.0" + } } diff --git a/tests/oauth2promise-tests.js b/tests/oauth2promise-tests.js new file mode 100644 index 00000000..5f86593d --- /dev/null +++ b/tests/oauth2promise-tests.js @@ -0,0 +1,310 @@ +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * Copyright (C) 2016 Rudolf Olah + * + * 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 . + */ + +var vows = require("vows"); +var assert = require("assert"); +var DummyResponse= require("./shared").DummyResponse; +var DummyRequest= require("./shared").DummyRequest; +var https = require("https"); +var OAuth2= require("../lib/oauth2-promise").OAuth2; +var url = require("url"); + +vows.describe("OAuth2-Promise").addBatch({ + "Given an OAuth2 instance with clientId and clientSecret, ": { + topic: new OAuth2("clientId", "clientSecret"), + "When dealing with the response from the OP": { + "we should treat a 201 response as a success": function (oa) { + var callbackCalled = false; + var httpLibrary = { + request: function () { + return new DummyRequest(new DummyResponse(201)); + } + }; + oa._executeRequest(httpLibrary, {}, null, function (err, result, response) { + callbackCalled = true; + assert.equal(err, null); + }); + assert.ok(callbackCalled); + }, + "we should treat a 200 response as a success": function (oa) { + var callbackCalled = false; + var httpLibrary = { + request: function () { + return new DummyRequest(new DummyResponse(200)); + } + }; + oa._executeRequest(httpLibrary, {}, null, function (err, result, response) { + callbackCalled = true; + assert.equal(err, null); + }); + assert.ok(callbackCalled); + } + }, + "When handling the access token response": { + "we should correctly extract the token if received as form-data": function (oa) { + oa._request = function (method, url, fo, bar, bleh, callback) { + callback(null, "access_token=access&refresh_token=refresh"); + }; + oa.getOAuthAccessToken("", {}, function (error, accessToken, refreshToken) { + assert.equal(accessToken, "access"); + assert.equal(refreshToken, "refresh"); + }); + }, + "we should not include access token in both querystring and headers (favours headers if specified)": function (oa) { + oa._request = new OAuth2("clientId", "clientSecret")._request.bind(oa); + oa._executeRequest = function (httpLibrary, options, post_body, callback) { + callback(null, url.parse(options.path, true).query, options.headers); + }; + + oa._request("GET", "http://foo/", { "Authorization": "Bearer BadNews" }, null, "accessx", function (error, query, headers) { + assert.ok(!("access_token" in query), "access_token also in query"); + assert.ok("Authorization" in headers, "Authorization not in headers"); + }); + }, + "we should include access token in the querystring if no Authorization header present to override it": function (oa) { + oa._request = new OAuth2("clientId", "clientSecret")._request.bind(oa); + oa._executeRequest = function (httpLibrary, options, post_body, callback) { + callback(null, url.parse(options.path, true).query, options.headers); + }; + oa._request("GET", "http://foo/", {}, null, "access", function (error, query, headers) { + assert.ok("access_token" in query, "access_token not present in query"); + assert.ok(!("Authorization" in headers), "Authorization in headers"); + }); + }, + "we should correctly extract the token if received as a JSON literal": function (oa) { + oa._request = function (method, url, headers, post_body, accessToken, callback) { + callback(null, '{ "access_token": "access","refresh_token": "refresh" }'); + }; + oa.getOAuthAccessToken("", {}, function (error, accessToken, refreshToken) { + assert.equal(accessToken, "access"); + assert.equal(refreshToken, "refresh"); + }); + }, + "we should return the received data to the calling method": function (oa) { + oa._request = function (method, url, headers, post_body, accessToken, callback) { + callback(null, '{ "access_token": "access","refresh_token": "refresh","extra_1":1, "extra_2": "foo" }'); + }; + oa.getOAuthAccessToken("", {}, function (error, accessToken, refreshToken, results) { + assert.equal(accessToken, "access"); + assert.equal(refreshToken, "refresh"); + assert.isNotNull(results); + assert.equal(results.extra_1, 1); + assert.equal(results.extra_2, "foo"); + }); + } + }, + "When no grant_type parameter is specified": { + "we should pass the value of the code argument as the code parameter": function (oa) { + oa._request = function (method, url, headers, post_body, accessToken, callback) { + assert.isTrue(post_body.indexOf("code=xsds23") != -1); + }; + oa.getOAuthAccessToken("xsds23", {}); + } + }, + "When an invalid grant_type parameter is specified": { + "we should pass the value of the code argument as the code parameter": function (oa) { + oa._request = function (method, url, headers, post_body, accessToken, callback) { + assert.isTrue(post_body.indexOf("code=xsds23") !== -1); + }; + oa.getOAuthAccessToken("xsds23", {grant_type: "refresh_toucan" }); + } + }, + "When a grant_type parameter of value 'refresh_token' is specified": { + "we should pass the value of the code argument as the refresh_token parameter, should pass a grant_type parameter, but shouldn\"t pass a code parameter": function (oa) { + oa._request = function (method, url, headers, post_body, accessToken, callback) { + assert.isTrue(post_body.indexOf("refresh_token=sdsds2") !== -1); + assert.isTrue(post_body.indexOf("grant_type=refresh_token") !== -1); + assert.isTrue(post_body.indexOf("code=") === -1); + }; + oa.getOAuthAccessToken("sdsds2", {grant_type: "refresh_token" }); + } + }, + "When we use the authorization header": { + "and call get with the default authorization method": { + "we should pass the authorization header with Bearer method and value of the access_token, _request should be passed a null access_token": function (oa) { + oa._request = function (method, url, headers, post_body, accessToken, callback) { + assert.equal(headers["Authorization"], "Bearer abcd5"); + assert.isNull(accessToken); + }; + oa.useAuthorizationHeaderforGET(true); + oa.get("", "abcd5"); + } + }, + "and call get with the authorization method set to Basic": { + "we should pass the authorization header with Basic method and value of the access_token, _request should be passed a null access_token": function (oa) { + oa._request = function (method, url, headers, post_body, accessToken, callback) { + assert.equal(headers["Authorization"], "Basic cdg2"); + assert.isNull(accessToken); + }; + oa.useAuthorizationHeaderforGET(true); + oa.setAuthMethod("Basic"); + oa.get("", "cdg2"); + } + } + }, + "When we do not use the authorization header": { + "and call get": { + "we should pass NOT provide an authorization header and the access_token should be being passed to _request": function (oa) { + oa._request = function (method, url, headers, post_body, accessToken, callback) { + assert.isUndefined(headers["Authorization"]); + assert.equal(accessToken, "abcd5"); + }; + oa.useAuthorizationHeaderforGET(false); + oa.get("", "abcd5"); + } + } + } + }, + "Given an OAuth2 instance with clientId, clientSecret and customHeaders": { + topic: new OAuth2("clientId", "clientSecret", null, null, null, + { "SomeHeader": "123" }), + "When GETing": { + "we should see the custom headers mixed into headers property in options passed to http-library": function (oa) { + oa._executeRequest = function (httpLibrary, options, callback) { + assert.equal(options.headers["SomeHeader"], "123"); + }; + oa.get("", {}); + }, + } + }, + "Given an OAuth2 instance with a clientId and clientSecret": { + topic: new OAuth2("clientId", "clientSecret"), + "When POSTing": { + "we should see a given string being sent to the request": function (oa) { + var bodyWritten = false; + oa._oa._chooseHttpLibrary = function () { + return { + request: function (options) { + assert.equal(options.headers["Content-Type"], "text/plain"); + assert.equal(options.headers["Content-Length"], 26); + assert.equal(options.method, "POST"); + return { + end: function () {}, + on: function () {}, + write: function (body) { + bodyWritten = true; + assert.isNotNull(body); + assert.equal(body, "THIS_IS_A_POST_BODY_STRING"); + } + }; + } + }; + } + oa._request("POST", "", { "Content-Type": "text/plain" }, "THIS_IS_A_POST_BODY_STRING"); + assert.ok(bodyWritten); + }, + "we should see a given buffer being sent to the request": function (oa) { + var bodyWritten = false; + oa._oa._chooseHttpLibrary = function () { + return { + request: function (options) { + assert.equal(options.headers["Content-Type"], "application/octet-stream"); + assert.equal(options.headers["Content-Length"], 4); + assert.equal(options.method, "POST"); + return { + end: function () {}, + on: function () {}, + write: function (body) { + bodyWritten = true; + assert.isNotNull(body); + assert.equal(4, body.length); + } + }; + } + }; + } + oa._request("POST", "", { "Content-Type": "application/octet-stream" }, new Buffer([1,2,3,4])); + assert.ok(bodyWritten); + } + }, + "When PUTing": { + "we should see a given string being sent to the request": function (oa) { + var bodyWritten = false; + oa._oa._chooseHttpLibrary = function () { + return { + request: function (options) { + assert.equal(options.headers["Content-Type"], "text/plain"); + assert.equal(options.headers["Content-Length"], 25); + assert.equal(options.method, "PUT"); + return { + end: function () {}, + on: function () {}, + write: function (body) { + bodyWritten = true; + assert.isNotNull(body); + assert.equal(body, "THIS_IS_A_PUT_BODY_STRING"); + } + }; + } + }; + } + oa._request("PUT", "", { "Content-Type": "text/plain" }, "THIS_IS_A_PUT_BODY_STRING"); + assert.ok(bodyWritten); + }, + "we should see a given buffer being sent to the request": function (oa) { + var bodyWritten = false; + oa._oa._chooseHttpLibrary = function () { + return { + request: function (options) { + assert.equal(options.headers["Content-Type"], "application/octet-stream"); + assert.equal(options.headers["Content-Length"], 4); + assert.equal(options.method, "PUT"); + return { + end: function () {}, + on: function () {}, + write: function (body) { + bodyWritten = true; + assert.isNotNull(body); + assert.equal(4, body.length) + } + }; + } + }; + } + oa._request("PUT", "", { "Content-Type": "application/octet-stream" }, new Buffer([1,2,3,4])); + assert.ok(bodyWritten); + } + } + }, + "When the user passes in the User-Agent in customHeaders": { + topic: new OAuth2("clientId", "clientSecret", null, null, null, + { "User-Agent": "123Agent" }), + "When calling get": { + "we should see the User-Agent mixed into headers property in options passed to http-library": function (oa) { + oa._executeRequest = function (httpLibrary, options, callback) { + assert.equal(options.headers["User-Agent"], "123Agent"); + }; + oa.get("", {}); + } + } + }, + "When the user does not pass in a User-Agent in customHeaders": { + topic: new OAuth2("clientId", "clientSecret", null, null, null, + null), + "When calling get": { + "we should see the default User-Agent mixed into headers property in options passed to http-library": function (oa) { + oa._executeRequest = function (httpLibrary, options, callback) { + assert.equal(options.headers["User-Agent"], "Node-oauth"); + }; + oa.get("", {}); + } + } + } +}).export(module); diff --git a/tests/oauth2tests.js b/tests/oauth2tests.js index 134f85bc..a9a533ad 100644 --- a/tests/oauth2tests.js +++ b/tests/oauth2tests.js @@ -1,290 +1,385 @@ -var vows = require('vows'), - assert = require('assert'), - DummyResponse= require('./shared').DummyResponse, - DummyRequest= require('./shared').DummyRequest, - https = require('https'), - OAuth2= require('../lib/oauth2').OAuth2, - url = require('url'); +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * + * 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 . + */ + +var vows = require('vows'); +var assert = require('assert'); +var DummyResponse = require('./shared').DummyResponse; +var DummyRequest = require('./shared').DummyRequest; +var https = require('https'); +var OAuth2 = require('../lib/oauth2').OAuth2; +var url = require('url'); vows.describe('OAuth2').addBatch({ - 'Given an OAuth2 instance with clientId and clientSecret, ': { - topic: new OAuth2("clientId", "clientSecret"), - 'When dealing with the response from the OP': { - 'we should treat a 201 response as a success': function(oa) { - var callbackCalled= false; - var http_library= { - request: function() { + 'Given an OAuth2 instance with clientId and clientSecret, ': { + topic: new OAuth2('clientId', 'clientSecret'), + 'When adding event listener to request:before event': { + 'we should raise an event before a request is sent and wait for method callback': function (oa) { + oa._executeRequest = function (http_library, options, post_body, callback) { + oa._executeRequest = new OAuth2('clientId', 'clientSecret')._executeRequest.bind(oa); // reset to original state + assert.equal(options.headers['test-header'], 'test'); + assert.equal(options.headers['kidding-header'], ':p'); + }; + // oa._executeRequest(httpLibrary, {}, null, function (err, result, response) {}) + // we register a new event to handle informations from last time before execute request + oa.on('request:before', function (options, post_body, doneFunction) { + options.headers['test-header'] = 'test'; + doneFunction(options, post_body); + }); + + oa.on('request:before', function (options, post_body, doneFunction) { + options.headers['kidding-header'] = ':p'; + doneFunction(options, post_body, true); + }); + + oa._request('POST', 'https://www.someurl.com/auth', {}, null, '', function (error, data, response) { + assert.ok((error === null)); + oa.removeAllListeners('request:before'); + }); + } + }, + 'When adding event listener to request:after event': { + 'we should raise an event after a request is sent': function (oa) { + oa._chooseHttpLibrary = function (parseUrl) { + return { + request: function () { return new DummyRequest(new DummyResponse(201)); } }; - oa._executeRequest( http_library, {}, null, function(err, result, response) { - callbackCalled= true; - assert.equal(err, null); - }); - assert.ok(callbackCalled); - }, - 'we should treat a 200 response as a success': function(oa) { - var callbackCalled= false; - var http_library= { - request: function() { - return new DummyRequest(new DummyResponse(200)); - } - }; - oa._executeRequest( http_library, {}, null, function(err, result, response) { - callbackCalled= true; - assert.equal(err, null); - }); - assert.ok(callbackCalled); - } - }, - 'When handling the access token response': { - 'we should correctly extract the token if received as form-data': function (oa) { - oa._request= function( method, url, fo, bar, bleh, callback) { - callback(null, "access_token=access&refresh_token=refresh"); - }; - oa.getOAuthAccessToken("", {}, function(error, access_token, refresh_token) { - assert.equal( access_token, "access"); - assert.equal( refresh_token, "refresh"); - }); - }, - 'we should not include access token in both querystring and headers (favours headers if specified)': function (oa) { - oa._request = new OAuth2("clientId", "clientSecret")._request.bind(oa); - oa._executeRequest= function( http_library, options, post_body, callback) { - callback(null, url.parse(options.path, true).query, options.headers); - }; + }; - oa._request("GET", "http://foo/", {"Authorization":"Bearer BadNews"}, null, "accessx", function(error, query, headers) { - assert.ok( !('access_token' in query), "access_token also in query"); - assert.ok( 'Authorization' in headers, "Authorization not in headers"); - }); - }, - 'we should include access token in the querystring if no Authorization header present to override it': function (oa) { - oa._request = new OAuth2("clientId", "clientSecret")._request.bind(oa); - oa._executeRequest= function( http_library, options, post_body, callback) { - callback(null, url.parse(options.path, true).query, options.headers); - }; - oa._request("GET", "http://foo/", {}, null, "access", function(error, query, headers) { - assert.ok( 'access_token' in query, "access_token not present in query"); - assert.ok( !('Authorization' in headers), "Authorization in headers"); - }); - }, - 'we should correctly extract the token if received as a JSON literal': function (oa) { - oa._request= function(method, url, headers, post_body, access_token, callback) { - callback(null, '{"access_token":"access","refresh_token":"refresh"}'); - }; - oa.getOAuthAccessToken("", {}, function(error, access_token, refresh_token) { - assert.equal( access_token, "access"); - assert.equal( refresh_token, "refresh"); - }); - }, - 'we should return the received data to the calling method': function (oa) { - oa._request= function(method, url, headers, post_body, access_token, callback) { - callback(null, '{"access_token":"access","refresh_token":"refresh","extra_1":1, "extra_2":"foo"}'); - }; - oa.getOAuthAccessToken("", {}, function(error, access_token, refresh_token, results) { - assert.equal( access_token, "access"); - assert.equal( refresh_token, "refresh"); - assert.isNotNull( results ); - assert.equal( results.extra_1, 1); - assert.equal( results.extra_2, "foo"); - }); - } - }, - 'When no grant_type parameter is specified': { - 'we should pass the value of the code argument as the code parameter': function(oa) { - oa._request= function(method, url, headers, post_body, access_token, callback) { - assert.isTrue( post_body.indexOf("code=xsds23") != -1 ); - }; - oa.getOAuthAccessToken("xsds23", {} ); - } + oa.on('request:after', function (res, data) { + assert.equal(res.statusCode, 201); + }); + + oa.on('request:after', function (res, data) { + assert.equal(res.statusCode, 201); + }); + + oa._request('POST', 'https://www.someurl.com/auth', {}, null, '', function (error, data, response) { + oa._chooseHttpLibrary = new OAuth2('clientId', 'clientSecret')._chooseHttpLibrary.bind(oa); // reset to original state + }); + } + }, + 'When dealing with the response from the OP': { + 'we should treat a 201 response as a success': function (oa) { + oa.removeAllListeners('request:after'); + var callbackCalled = false; + var httpLibrary = { + request: function () { + return new DummyRequest(new DummyResponse(201)); + } + }; + oa._executeRequest(httpLibrary, {}, null, function (err, result, response) { + callbackCalled = true; + assert.equal(err, null); + }); + assert.ok(callbackCalled); }, - 'When an invalid grant_type parameter is specified': { - 'we should pass the value of the code argument as the code parameter': function(oa) { - oa._request= function(method, url, headers, post_body, access_token, callback) { - assert.isTrue( post_body.indexOf("code=xsds23") != -1 ); - }; - oa.getOAuthAccessToken("xsds23", {grant_type:"refresh_toucan"} ); - } + 'we should treat a 200 response as a success': function (oa) { + var callbackCalled = false; + var httpLibrary = { + request: function () { + return new DummyRequest(new DummyResponse(200)); + } + }; + oa._executeRequest(httpLibrary, {}, null, function (err, result, response) { + callbackCalled = true; + assert.equal(err, null); + }); + assert.ok(callbackCalled); + } + }, + 'When handling the access token response': { + 'we should correctly extract the token if received as form-data': function (oa) { + oa._request = function (method, url, fo, bar, bleh, callback) { + callback(null, 'access_token=access&refresh_token=refresh'); + }; + oa.getOAuthAccessToken('', {}, function (error, accessToken, refreshToken) { + assert.equal(accessToken, 'access'); + assert.equal(refreshToken, 'refresh'); + }); }, - 'When a grant_type parameter of value "refresh_token" is specified': { - 'we should pass the value of the code argument as the refresh_token parameter, should pass a grant_type parameter, but shouldn\'t pass a code parameter' : function(oa) { - oa._request= function(method, url, headers, post_body, access_token, callback) { - assert.isTrue( post_body.indexOf("refresh_token=sdsds2") != -1 ); - assert.isTrue( post_body.indexOf("grant_type=refresh_token") != -1 ); - assert.isTrue( post_body.indexOf("code=") == -1 ); - }; - oa.getOAuthAccessToken("sdsds2", {grant_type:"refresh_token"} ); + 'we should correctly create base64-encoded authorization header from client id and secret': function (oa) { + oa._clientId = 'hello'; + oa._clientSecret = 'world'; + var authHeaderContent = oa._getAuthorizationHeader(); + var headerSplit = authHeaderContent.split(' '); + assert.equal(headerSplit[0], 'Basic'); + var decodedAuthHeader = ''; + try { // newer node versions + decodedAuthHeader = Buffer.from(headerSplit[1], 'base64').toString('ascii'); + } catch (e) { // node version 5 and older + decodedAuthHeader = new Buffer(headerSplit[1], 'base64').toString('ascii'); } + assert.equal(decodedAuthHeader, oa._clientId + ':' + oa._clientSecret); }, - 'When we use the authorization header': { - 'and call get with the default authorization method': { - 'we should pass the authorization header with Bearer method and value of the access_token, _request should be passed a null access_token' : function(oa) { - oa._request= function(method, url, headers, post_body, access_token, callback) { - assert.equal(headers["Authorization"], "Bearer abcd5"); - assert.isNull( access_token ); - }; - oa.useAuthorizationHeaderforGET(true); - oa.get("", "abcd5"); - } - }, - 'and call get with the authorization method set to Basic': { - 'we should pass the authorization header with Basic method and value of the access_token, _request should be passed a null access_token' : function(oa) { - oa._request= function(method, url, headers, post_body, access_token, callback) { - assert.equal(headers["Authorization"], "Basic cdg2"); - assert.isNull( access_token ); - }; - oa.useAuthorizationHeaderforGET(true); - oa.setAuthMethod("Basic"); - oa.get("", "cdg2"); + 'we should correctly send Authorization header encoded Base64 for token request': function (oa) { + oa._request = function (method, url, postHeaders, bar, bleh, callback) { + var authHeaderContent = postHeaders.Authorization; + assert.isNotNull(authHeaderContent, 'Authorization header for token request must to be present.'); + var headerSplit = authHeaderContent.split(' '); + assert.equal('Basic', headerSplit[0]); + var decodedAuthHeader = ''; + try { // newer node versions + decodedAuthHeader = Buffer.from(headerSplit[1], 'base64').toString('ascii'); + } catch (e) { // node version 5 and older + decodedAuthHeader = new Buffer(headerSplit[1], 'base64').toString('ascii'); } + assert.equal(decodedAuthHeader, oa._clientId + ':' + oa._clientSecret); + callback(null, 'access_token=access&refresh_token=refresh'); + }; + oa.getOAuthAccessToken('', {}, function (error, accessToken, refreshToken) {}); + }, + 'we should not include access token in both querystring and headers (favours headers if specified)': function (oa) { + oa._request = new OAuth2('clientId', 'clientSecret')._request.bind(oa); + oa._executeRequest = function (httpLibrary, options, postBody, callback) { + callback(null, url.parse(options.path, true).query, options.headers); + }; + oa._request('GET', 'http://foo/', { 'Authorization': 'Bearer BadNews' }, null, 'accessx', function (error, query, headers) { + assert.ok(!('access_token' in query), 'access_token also in query'); + assert.ok('Authorization' in headers, 'Authorization not in headers'); + }); + }, + 'we should include access token in the querystring if no Authorization header present to override it': function (oa) { + oa._request = new OAuth2('clientId', 'clientSecret')._request.bind(oa); + oa._executeRequest = function (httpLibrary, options, postBody, callback) { + callback(null, url.parse(options.path, true).query, options.headers); + }; + oa._request('GET', 'http://foo/', {}, null, 'access', function (error, query, headers) { + assert.ok('access_token' in query, 'access_token not present in query'); + assert.ok(!('Authorization' in headers), 'Authorization in headers'); + }); + }, + 'we should correctly extract the token if received as a JSON literal': function (oa) { + oa._request = function (method, url, headers, postBody, accessToken, callback) { + callback(null, '{ "access_token": "access","refresh_token": "refresh" }'); + }; + oa.getOAuthAccessToken('', {}, function (error, accessToken, refreshToken) { + assert.equal(accessToken, 'access'); + assert.equal(refreshToken, 'refresh'); + }); + }, + 'we should return the received data to the calling method': function (oa) { + oa._request = function (method, url, headers, postBody, accessToken, callback) { + callback(null, '{ "access_token": "access","refresh_token": "refresh","extra_1":1, "extra_2": "foo" }'); + }; + oa.getOAuthAccessToken('', {}, function (error, accessToken, refreshToken, results) { + assert.equal(accessToken, 'access'); + assert.equal(refreshToken, 'refresh'); + assert.isNotNull(results); + assert.equal(results.extra_1, 1); + assert.equal(results.extra_2, 'foo'); + }); + } + }, + 'When no grant_type parameter is specified': { + 'we should pass the value of the code argument as the code parameter': function (oa) { + oa._request = function (method, url, headers, postBody, accessToken, callback) { + assert.isTrue(postBody.indexOf('code=xsds23') !== -1); + }; + oa.getOAuthAccessToken('xsds23', {}); + } + }, + 'When an invalid grant_type parameter is specified': { + 'we should pass the value of the code argument as the code parameter': function (oa) { + oa._request = function (method, url, headers, postBody, accessToken, callback) { + assert.isTrue(postBody.indexOf('code=xsds23') !== -1); + }; + oa.getOAuthAccessToken('xsds23', { 'grant_type': 'refresh_toucan' }); + } + }, + "When a grant_type parameter of value 'refresh_token' is specified": { + 'we should pass the value of the code argument as the refresh_token parameter, should pass a grant_type parameter, but shouldn"t pass a code parameter': function (oa) { + oa._request = function (method, url, headers, postBody, accessToken, callback) { + assert.isTrue(postBody.indexOf('refresh_token=sdsds2') !== -1); + assert.isTrue(postBody.indexOf('grant_type=refresh_token') !== -1); + assert.isTrue(postBody.indexOf('code=') === -1); + }; + oa.getOAuthAccessToken('sdsds2', { 'grant_type': 'refresh_token' }); + } + }, + 'When we use the authorization header': { + 'and call get with the default authorization method': { + 'we should pass the authorization header with Bearer method and value of the accessToken, _request should be passed a null accessToken': function (oa) { + oa._request = function (method, url, headers, postBody, accessToken, callback) { + assert.equal(headers['Authorization'], 'Bearer abcd5'); + assert.isNull(accessToken); + }; + oa.useAuthorizationHeaderforGET(true); + oa.get('', 'abcd5'); } }, - 'When we do not use the authorization header': { - 'and call get': { - 'we should pass NOT provide an authorization header and the access_token should be being passed to _request' : function(oa) { - oa._request= function(method, url, headers, post_body, access_token, callback) { - assert.isUndefined(headers["Authorization"]); - assert.equal( access_token, "abcd5" ); - }; - oa.useAuthorizationHeaderforGET(false); - oa.get("", "abcd5"); - } + 'and call get with the authorization method set to Basic': { + 'we should pass the authorization header with Basic method and value of the accessToken, _request should be passed a null accessToken': function (oa) { + oa._request = function (method, url, headers, postBody, accessToken, callback) { + assert.equal(headers['Authorization'], 'Basic cdg2'); + assert.isNull(accessToken); + }; + oa.useAuthorizationHeaderforGET(true); + oa.setAuthMethod('Basic'); + oa.get('', 'cdg2'); } } }, - 'Given an OAuth2 instance with clientId, clientSecret and customHeaders': { - topic: new OAuth2("clientId", "clientSecret", undefined, undefined, undefined, - { 'SomeHeader': '123' }), - 'When GETing': { - 'we should see the custom headers mixed into headers property in options passed to http-library' : function(oa) { - oa._executeRequest= function( http_library, options, callback ) { - assert.equal(options.headers["SomeHeader"], "123"); + 'When we do not use the authorization header': { + 'and call get': { + 'we should pass NOT provide an authorization header and the accessToken should be being passed to _request': function (oa) { + oa._request = function (method, url, headers, postBody, accessToken, callback) { + assert.isUndefined(headers['Authorization']); + assert.equal(accessToken, 'abcd5'); }; - oa.get("", {}); - }, + oa.useAuthorizationHeaderforGET(false); + oa.get('', 'abcd5'); + } } - }, - 'Given an OAuth2 instance with a clientId and clientSecret': { - topic: new OAuth2("clientId", "clientSecret"), - 'When POSTing': { - 'we should see a given string being sent to the request' : function(oa) { - var bodyWritten= false; - oa._chooseHttpLibrary= function() { + } + }, + 'Given an OAuth2 instance with clientId, clientSecret and customHeaders': { + topic: new OAuth2('clientId', 'clientSecret', null, null, null, { 'SomeHeader': '123' }), + 'When GETing': { + 'we should see the custom headers mixed into headers property in options passed to http-library': function (oa) { + oa._executeRequest = function (httpLibrary, options, callback) { + assert.equal(options.headers['SomeHeader'], '123'); + }; + oa.get('', {}); + } + } + }, + 'Given an OAuth2 instance with a clientId and clientSecret': { + topic: new OAuth2('clientId', 'clientSecret'), + 'When POSTing': { + 'we should see a given string being sent to the request': function (oa) { + var bodyWritten = false; + oa._chooseHttpLibrary = function () { + return { + request: function (options) { + assert.equal(options.headers['Content-Type'], 'text/plain'); + assert.equal(options.headers['Content-Length'], 26); + assert.equal(options.method, 'POST'); return { - request: function(options) { - assert.equal(options.headers["Content-Type"], "text/plain"); - assert.equal(options.headers["Content-Length"], 26); - assert.equal(options.method, "POST"); - return { - end: function() {}, - on: function() {}, - write: function(body) { - bodyWritten= true; - assert.isNotNull(body); - assert.equal(body, "THIS_IS_A_POST_BODY_STRING") - } - } + end: function () {}, + on: function () {}, + write: function (body) { + bodyWritten = true; + assert.isNotNull(body); + assert.equal(body, 'THIS_IS_A_POST_BODY_STRING'); } }; } - oa._request("POST", "", {"Content-Type":"text/plain"}, "THIS_IS_A_POST_BODY_STRING"); - assert.ok( bodyWritten ); - }, - 'we should see a given buffer being sent to the request' : function(oa) { - var bodyWritten= false; - oa._chooseHttpLibrary= function() { + }; + }; + oa._request('POST', '', { 'Content-Type': 'text/plain' }, 'THIS_IS_A_POST_BODY_STRING'); + assert.ok(bodyWritten); + }, + 'we should see a given buffer being sent to the request': function (oa) { + var bodyWritten = false; + oa._chooseHttpLibrary = function () { + return { + request: function (options) { + assert.equal(options.headers['Content-Type'], 'application/octet-stream'); + assert.equal(options.headers['Content-Length'], 4); + assert.equal(options.method, 'POST'); return { - request: function(options) { - assert.equal(options.headers["Content-Type"], "application/octet-stream"); - assert.equal(options.headers["Content-Length"], 4); - assert.equal(options.method, "POST"); - return { - end: function() {}, - on: function() {}, - write: function(body) { - bodyWritten= true; - assert.isNotNull(body); - assert.equal(4, body.length) - } - } + end: function () {}, + on: function () {}, + write: function (body) { + bodyWritten = true; + assert.isNotNull(body); + assert.equal(4, body.length); } }; } - oa._request("POST", "", {"Content-Type":"application/octet-stream"}, new Buffer([1,2,3,4])); - assert.ok( bodyWritten ); - } - }, - 'When PUTing': { - 'we should see a given string being sent to the request' : function(oa) { - var bodyWritten= false; - oa._chooseHttpLibrary= function() { + }; + }; + oa._request('POST', '', { 'Content-Type': 'application/octet-stream' }, new Buffer([1, 2, 3, 4])); + assert.ok(bodyWritten); + } + }, + 'When PUTing': { + 'we should see a given string being sent to the request': function (oa) { + var bodyWritten = false; + oa._chooseHttpLibrary = function () { + return { + request: function (options) { + assert.equal(options.headers['Content-Type'], 'text/plain'); + assert.equal(options.headers['Content-Length'], 25); + assert.equal(options.method, 'PUT'); return { - request: function(options) { - assert.equal(options.headers["Content-Type"], "text/plain"); - assert.equal(options.headers["Content-Length"], 25); - assert.equal(options.method, "PUT"); - return { - end: function() {}, - on: function() {}, - write: function(body) { - bodyWritten= true; - assert.isNotNull(body); - assert.equal(body, "THIS_IS_A_PUT_BODY_STRING") - } - } + end: function () {}, + on: function () {}, + write: function (body) { + bodyWritten = true; + assert.isNotNull(body); + assert.equal(body, 'THIS_IS_A_PUT_BODY_STRING'); } }; } - oa._request("PUT", "", {"Content-Type":"text/plain"}, "THIS_IS_A_PUT_BODY_STRING"); - assert.ok( bodyWritten ); - }, - 'we should see a given buffer being sent to the request' : function(oa) { - var bodyWritten= false; - oa._chooseHttpLibrary= function() { + }; + }; + oa._request('PUT', '', { 'Content-Type': 'text/plain' }, 'THIS_IS_A_PUT_BODY_STRING'); + assert.ok(bodyWritten); + }, + 'we should see a given buffer being sent to the request': function (oa) { + var bodyWritten = false; + oa._chooseHttpLibrary = function () { + return { + request: function (options) { + assert.equal(options.headers['Content-Type'], 'application/octet-stream'); + assert.equal(options.headers['Content-Length'], 4); + assert.equal(options.method, 'PUT'); return { - request: function(options) { - assert.equal(options.headers["Content-Type"], "application/octet-stream"); - assert.equal(options.headers["Content-Length"], 4); - assert.equal(options.method, "PUT"); - return { - end: function() {}, - on: function() {}, - write: function(body) { - bodyWritten= true; - assert.isNotNull(body); - assert.equal(4, body.length) - } - } + end: function () {}, + on: function () {}, + write: function (body) { + bodyWritten = true; + assert.isNotNull(body); + assert.equal(4, body.length); } }; } - oa._request("PUT", "", {"Content-Type":"application/octet-stream"}, new Buffer([1,2,3,4])); - assert.ok( bodyWritten ); - } - } - }, - 'When the user passes in the User-Agent in customHeaders': { - topic: new OAuth2("clientId", "clientSecret", undefined, undefined, undefined, - { 'User-Agent': '123Agent' }), - 'When calling get': { - 'we should see the User-Agent mixed into headers property in options passed to http-library' : function(oa) { - oa._executeRequest= function( http_library, options, callback ) { - assert.equal(options.headers["User-Agent"], "123Agent"); }; - oa.get("", {}); - } + }; + oa._request('PUT', '', { 'Content-Type': 'application/octet-stream' }, new Buffer([1, 2, 3, 4])); + assert.ok(bodyWritten); } - }, - 'When the user does not pass in a User-Agent in customHeaders': { - topic: new OAuth2("clientId", "clientSecret", undefined, undefined, undefined, - undefined), - 'When calling get': { - 'we should see the default User-Agent mixed into headers property in options passed to http-library' : function(oa) { - oa._executeRequest= function( http_library, options, callback ) { - assert.equal(options.headers["User-Agent"], "Node-oauth"); - }; - oa.get("", {}); - } + } + }, + 'When the user passes in the User-Agent in customHeaders': { + topic: new OAuth2('clientId', 'clientSecret', null, null, null, { 'User-Agent': '123Agent' }), + 'When calling get': { + 'we should see the User-Agent mixed into headers property in options passed to http-library': function (oa) { + oa._executeRequest = function (httpLibrary, options, callback) { + assert.equal(options.headers['User-Agent'], '123Agent'); + }; + oa.get('', {}); + } + } + }, + 'When the user does not pass in a User-Agent in customHeaders': { + topic: new OAuth2('clientId', 'clientSecret', null, null, null, null), + 'When calling get': { + 'we should see the default User-Agent mixed into headers property in options passed to http-library': function (oa) { + oa._executeRequest = function (httpLibrary, options, callback) { + assert.equal(options.headers['User-Agent'], 'Node-oauth'); + }; + oa.get('', {}); } } + } }).export(module); diff --git a/tests/oauthpromise-tests.js b/tests/oauthpromise-tests.js new file mode 100644 index 00000000..b4f63a85 --- /dev/null +++ b/tests/oauthpromise-tests.js @@ -0,0 +1,1045 @@ +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * Copyright (C) 2016 Rudolf Olah + * + * 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 . + */ + +var vows = require('vows'), + assert = require('assert'), + DummyResponse= require('./shared').DummyResponse, + DummyRequest= require('./shared').DummyRequest, + events = require('events'), + OAuth= require('../lib/oauth-promise').OAuth, + OAuthEcho= require('../lib/oauth').OAuthEcho, + crypto = require('crypto'); + +//Valid RSA keypair used to test RSA-SHA1 signature method +var RsaPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\n" + + "MIICXQIBAAKBgQDizE4gQP5nPQhzof/Vp2U2DDY3UY/Gxha2CwKW0URe7McxtnmE\n" + + "CrZnT1n/YtfrrCNxY5KMP4o8hMrxsYEe05+1ZGFT68ztms3puUxilU5E3BQMhz1t\n" + + "JMJEGcTt8nZUlM4utli7fHgDtWbhvqvYjRMGn3AjyLOfY8XZvnFkGjipvQIDAQAB\n" + + "AoGAKgk6FcpWHOZ4EY6eL4iGPt1Gkzw/zNTcUsN5qGCDLqDuTq2Gmk2t/zn68VXt\n" + + "tVXDf/m3qN0CDzOBtghzaTZKLGhnSewQ98obMWgPcvAsb4adEEeW1/xigbMiaW2X\n" + + "cu6GhZxY16edbuQ40LRrPoVK94nXQpj8p7w4IQ301Sm8PSECQQD1ZlOj4ugvfhEt\n" + + "exi4WyAaM45fylmN290UXYqZ8SYPI/VliDytIlMfyq5Rv+l+dud1XDPrWOQ0ImgV\n" + + "HJn7uvoZAkEA7JhHNmHF9dbdF9Koj86K2Cl6c8KUu7U7d2BAuB6pPkt8+D8+y4St\n" + + "PaCmN4oP4X+sf5rqBYoXywHlqEei2BdpRQJBAMYgR4cZu7wcXGIL8HlnmROObHSK\n" + + "OqN9z5CRtUV0nPW8YnQG+nYOMG6KhRMbjri750OpnYF100kEPmRNI0VKQIECQE8R\n" + + "fQsRleTYz768ahTVQ9WF1ySErMwmfx8gDcD6jjkBZVxZVpURXAwyehopi7Eix/VF\n" + + "QlxjkBwKIEQi3Ks297kCQQCL9by1bueKDMJO2YX1Brm767pkDKkWtGfPS+d3xMtC\n" + + "KJHHCqrS1V+D5Q89x5wIRHKxE5UMTc0JNa554OxwFORX\n" + + "-----END RSA PRIVATE KEY-----"; + +var RsaPublicKey = "-----BEGIN PUBLIC KEY-----\n" + + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDizE4gQP5nPQhzof/Vp2U2DDY3\n" + + "UY/Gxha2CwKW0URe7McxtnmECrZnT1n/YtfrrCNxY5KMP4o8hMrxsYEe05+1ZGFT\n" + + "68ztms3puUxilU5E3BQMhz1tJMJEGcTt8nZUlM4utli7fHgDtWbhvqvYjRMGn3Aj\n" + + "yLOfY8XZvnFkGjipvQIDAQAB\n" + + "-----END PUBLIC KEY-----"; + +vows.describe('OAuth-Promise').addBatch({ + 'When newing OAuth': { + topic: new OAuth(null, null, null, null, null, null, "PLAINTEXT"), + 'followRedirects is enabled by default': function (oa) { + assert.equal(oa._oa._clientOptions.followRedirects, true); + } + }, + 'When generating the signature base string described in http://oauth.net/core/1.0/#sig_base_example': { + topic: new OAuth(null, null, null, null, null, null, "HMAC-SHA1"), + 'we get the expected result string': function (oa) { + var result= oa._createSignatureBase( + "GET", "http://photos.example.net/photos", + "file=vacation.jpg&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1191242096&oauth_token=nnch734d00sl2jdk&oauth_version=1.0&size=original" + ); + assert.equal(result, "GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal"); + } + }, + 'When generating the signature with RSA-SHA1': { + topic: new OAuth(null, null, null, RsaPrivateKey, null, null, "RSA-SHA1"), + 'we get a valid oauth signature': function (oa) { + var signatureBase = "GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal"; + var oauthSignature = oa._createSignature(signatureBase, "xyz4992k83j47x0b"); + + assert.equal( oauthSignature, "qS4rhWog7GPgo4ZCJvUdC/1ZAax/Q4Ab9yOBvgxSopvmKUKp5rso+Zda46GbyN2hnYDTiA/g3P/d/YiPWa454BEBb/KWFV83HpLDIoqUUhJnlXX9MqRQQac0oeope4fWbGlfTdL2PXjSFJmvfrzybERD/ZufsFtVrQKS3QBpYiw="); + + //now check that given the public key we can verify this signature + var verifier = crypto.createVerify("RSA-SHA1").update(signatureBase); + var valid = verifier.verify(RsaPublicKey, oauthSignature, 'base64'); + assert.ok( valid, "Signature could not be verified with RSA public key"); + } + }, + 'When generating the signature base string with PLAINTEXT': { + topic: new OAuth(null, null, null, null, null, null, "PLAINTEXT"), + 'we get the expected result string': function (oa) { + var result= oa._getSignature("GET", "http://photos.example.net/photos", + "file=vacation.jpg&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=PLAINTEXT&oauth_timestamp=1191242096&oauth_token=nnch734d00sl2jdk&oauth_version=1.0&size=original", + "test"); + assert.equal( result, "&test"); + } + }, + 'When normalising a url': { + topic: new OAuth(null, null, null, null, null, null, "HMAC-SHA1"), + 'default ports should be stripped': function(oa) { + assert.equal( oa._normalizeUrl("https://somehost.com:443/foo/bar"), "https://somehost.com/foo/bar" ); + }, + 'should leave in non-default ports from urls for use in signature generation': function(oa) { + assert.equal( oa._normalizeUrl("https://somehost.com:446/foo/bar"), "https://somehost.com:446/foo/bar" ); + assert.equal( oa._normalizeUrl("http://somehost.com:81/foo/bar"), "http://somehost.com:81/foo/bar" ); + }, + 'should add a trailing slash when no path at all is present': function(oa) { + assert.equal(oa._normalizeUrl("http://somehost.com"), "http://somehost.com/"); + } + }, + 'When making an array out of the arguments hash' : { + topic: new OAuth(null, null, null, null, null, null, "HMAC-SHA1"), + 'flatten out arguments that are arrays' : function(oa) { + var parameters= {"z": "a", + "a": ["1", "2"], + "1": "c" }; + var parameterResults= oa._makeArrayOfArgumentsHash(parameters); + assert.equal(parameterResults.length, 4); + assert.equal(parameterResults[0][0], "1"); + assert.equal(parameterResults[1][0], "z"); + assert.equal(parameterResults[2][0], "a"); + assert.equal(parameterResults[3][0], "a"); + } + }, + 'When ordering the request parameters' : { + topic: new OAuth(null, null, null, null, null, null, "HMAC-SHA1"), + 'Order them by name' : function(oa) { + var parameters= {"z": "a", + "a": "b", + "1": "c" }; + var parameterResults= oa._sortRequestParams(oa._makeArrayOfArgumentsHash(parameters)); + assert.equal(parameterResults[0][0], "1"); + assert.equal(parameterResults[1][0], "a"); + assert.equal(parameterResults[2][0], "z"); + }, + 'If two parameter names are the same then order by the value': function(oa) { + var parameters= {"z": "a", + "a": ["z", "b", "b", "a", "y"], + "1": "c" }; + var parameterResults= oa._sortRequestParams(oa._makeArrayOfArgumentsHash(parameters)); + assert.equal(parameterResults[0][0], "1"); + assert.equal(parameterResults[1][0], "a"); + assert.equal(parameterResults[1][1], "a"); + assert.equal(parameterResults[2][0], "a"); + assert.equal(parameterResults[2][1], "b"); + assert.equal(parameterResults[3][0], "a"); + assert.equal(parameterResults[3][1], "b"); + assert.equal(parameterResults[4][0], "a"); + assert.equal(parameterResults[4][1], "y"); + assert.equal(parameterResults[5][0], "a"); + assert.equal(parameterResults[5][1], "z"); + assert.equal(parameterResults[6][0], "z"); + } + }, + 'When normalising the request parameters': { + topic: new OAuth(null, null, null, null, null, null, "HMAC-SHA1"), + 'the resulting parameters should be encoded and ordered as per http://tools.ietf.org/html/rfc5849#section-3.1 (3.4.1.3.2)' : function(oa) { + var parameters= {"b5" : "=%3D", + "a3": ["a", "2 q"], + "c@": "", + "a2": "r b", + "oauth_consumer_key": "9djdj82h48djs9d2", + "oauth_token":"kkk9d7dh3k39sjv7", + "oauth_signature_method": "HMAC-SHA1", + "oauth_timestamp": "137131201", + "oauth_nonce": "7d8f3e4a", + "c2" : ""}; + var normalisedParameterString= oa._normaliseRequestParams(parameters); + assert.equal(normalisedParameterString, "a2=r%20b&a3=2%20q&a3=a&b5=%3D%253D&c%40=&c2=&oauth_consumer_key=9djdj82h48djs9d2&oauth_nonce=7d8f3e4a&oauth_signature_method=HMAC-SHA1&oauth_timestamp=137131201&oauth_token=kkk9d7dh3k39sjv7"); + } + }, + 'When preparing the parameters for use in signing': { + topic: new OAuth(null, null, null, null, null, null, "HMAC-SHA1"), + 'We need to be wary of node\'s auto object creation from foo[bar] style url parameters' : function(oa) { + var result= oa._prepareParameters( "", "", "", "http://foo.com?foo[bar]=xxx&bar[foo]=yyy", {} ); + assert.equal( result[0][0], "bar[foo]"); + assert.equal( result[0][1], "yyy"); + assert.equal( result[1][0], "foo[bar]"); + assert.equal( result[1][1], "xxx"); + } + }, + 'When signing a url': { + topic: function() { + var oa= new OAuth(null, null, "consumerkey", "consumersecret", "1.0", null, "HMAC-SHA1"); + oa._oa._getTimestamp= function(){ return "1272399856"; }; + oa._oa._getNonce= function(){ return "ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp"; }; + return oa; + }, + 'Provide a valid signature when no token present': function(oa) { + assert.equal( oa.signUrl("http://somehost.com:3323/foo/poop?bar=foo"), "http://somehost.com:3323/foo/poop?bar=foo&oauth_consumer_key=consumerkey&oauth_nonce=ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1272399856&oauth_version=1.0&oauth_signature=7ytO8vPSLut2GzHjU9pn1SV9xjc%3D"); + }, + 'Provide a valid signature when a token is present': function(oa) { + assert.equal( oa.signUrl("http://somehost.com:3323/foo/poop?bar=foo", "token"), "http://somehost.com:3323/foo/poop?bar=foo&oauth_consumer_key=consumerkey&oauth_nonce=ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1272399856&oauth_token=token&oauth_version=1.0&oauth_signature=9LwCuCWw5sURtpMroIolU3YwsdI%3D"); + }, + 'Provide a valid signature when a token and a token secret is present': function(oa) { + assert.equal( oa.signUrl("http://somehost.com:3323/foo/poop?bar=foo", "token", "tokensecret"), "http://somehost.com:3323/foo/poop?bar=foo&oauth_consumer_key=consumerkey&oauth_nonce=ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1272399856&oauth_token=token&oauth_version=1.0&oauth_signature=zeOR0Wsm6EG6XSg0Vw%2FsbpoSib8%3D"); + } + }, + 'When getting a request token': { + topic: function() { + var oa= new OAuth(null, null, "consumerkey", "consumersecret", "1.0", null, "HMAC-SHA1"); + oa._getTimestamp= function(){ return "1272399856"; }; + oa._getNonce= function(){ return "ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp"; }; + oa._performSecureRequest= function(){ return this.requestArguments = arguments; }; + return oa; + }, + 'Use the HTTP method in the client options': function(oa) { + oa.setClientOptions({ requestTokenHttpMethod: "GET" }); + oa.getOAuthRequestToken(function() {}).nodeify(function() { + assert.equal(oa.requestArguments[2], "GET"); + }); + }, + 'Use a POST by default': function(oa) { + oa.setClientOptions({}); + oa.getOAuthRequestToken(function() {}).nodeify(function() { + assert.equal(oa.requestArguments[2], "POST"); + }); + } + }, + 'When getting an access token': { + topic: function() { + var oa = new OAuth(null, null, "consumerkey", "consumersecret", "1.0", null, "HMAC-SHA1"); + oa._getTimestamp = function() { return "1272399856"; }; + oa._getNonce = function() { return "ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp"; }; + oa._performSecureRequest= function() { + return this._oa.requestArguments = arguments; + }; + return oa; + }, + 'Use the HTTP method in the client options': function(oa) { + oa.setClientOptions({ accessTokenHttpMethod: "GET" }); + oa.getOAuthAccessToken(function() {}).nodeify(function() { + assert.equal(oa._oa.requestArguments[2], "GET"); + }); + }, + 'Use a POST by default': function(oa) { + oa.setClientOptions({}); + oa.getOAuthAccessToken(function() {}).nodeify(function() { + assert.equal(oa._oa.requestArguments[2], "POST"); + }); + } + }, + 'When get authorization header' : { + topic: function() { + var oa= new OAuth(null, null, "consumerkey", "consumersecret", "1.0", null, "HMAC-SHA1"); + oa._oa._getTimestamp = function() { return "1272399856"; }; + oa._oa._getNonce = function() { return "ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp"; }; + return oa; + }, + 'Provide a valid signature when a token and a token secret is present': function(oa) { + assert.equal( oa.authHeader("http://somehost.com:3323/foo/poop?bar=foo", "token", "tokensecret"), 'OAuth oauth_consumer_key="consumerkey",oauth_nonce="ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1272399856",oauth_token="token",oauth_version="1.0",oauth_signature="zeOR0Wsm6EG6XSg0Vw%2FsbpoSib8%3D"'); + }, + 'Support variable whitespace separating the arguments': function(oa) { + oa._oa._oauthParameterSeperator= ", "; + assert.equal( oa.authHeader("http://somehost.com:3323/foo/poop?bar=foo", "token", "tokensecret"), 'OAuth oauth_consumer_key="consumerkey", oauth_nonce="ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1272399856", oauth_token="token", oauth_version="1.0", oauth_signature="zeOR0Wsm6EG6XSg0Vw%2FsbpoSib8%3D"'); + } + }, + 'When get the OAuth Echo authorization header': { + topic: function () { + var realm = "http://foobar.com/"; + var verifyCredentials = "http://api.foobar.com/verify.json"; + var oa = new OAuthEcho(realm, verifyCredentials, "consumerkey", "consumersecret", "1.0A", "HMAC-SHA1"); + oa._getTimestamp= function(){ return "1272399856"; }; + oa._getNonce= function(){ return "ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp"; }; + return oa; + }, + 'Provide a valid signature when a token and token secret is present': function (oa) { + assert.equal( oa.authHeader("http://somehost.com:3323/foo/poop?bar=foo", "token", "tokensecret"), 'OAuth realm="http://foobar.com/",oauth_consumer_key="consumerkey",oauth_nonce="ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1272399856",oauth_token="token",oauth_version="1.0A",oauth_signature="0rr1LhSxACX2IEWRq3uCb4IwtOs%3D"'); + } + }, + 'When non standard ports are used': { + topic: function() { + var oa= new OAuth(null, null, null, null, null, null, "HMAC-SHA1"), + mockProvider= {}; + + oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + assert.equal(headers.Host, "somehost.com:8080"); + assert.equal(hostname, "somehost.com"); + assert.equal(port, "8080"); + return { + on: function() {}, + end: function() {} + }; + }; + return oa; + }, + 'getProtectedResource should correctly define the host headers': function(oa) { + oa.getProtectedResource("http://somehost.com:8080", "GET", "oauth_token", null, function(){}); + } + }, + 'When building the OAuth Authorization header': { + topic: new OAuth(null, null, null, null, null, null, "HMAC-SHA1"), + 'All provided oauth arguments should be concatentated correctly' : function(oa) { + var parameters= [ + ["oauth_timestamp", "1234567"], + ["oauth_nonce", "ABCDEF"], + ["oauth_version", "1.0"], + ["oauth_signature_method", "HMAC-SHA1"], + ["oauth_consumer_key", "asdasdnm2321b3"]]; + assert.equal(oa._buildAuthorizationHeaders(parameters), 'OAuth oauth_timestamp="1234567",oauth_nonce="ABCDEF",oauth_version="1.0",oauth_signature_method="HMAC-SHA1",oauth_consumer_key="asdasdnm2321b3"'); + }, + '*Only* Oauth arguments should be concatentated, others should be disregarded' : function(oa) { + var parameters= [ + ["foo", "2343"], + ["oauth_timestamp", "1234567"], + ["oauth_nonce", "ABCDEF"], + ["bar", "dfsdfd"], + ["oauth_version", "1.0"], + ["oauth_signature_method", "HMAC-SHA1"], + ["oauth_consumer_key", "asdasdnm2321b3"], + ["foobar", "asdasdnm2321b3"]]; + assert.equal(oa._buildAuthorizationHeaders(parameters), 'OAuth oauth_timestamp="1234567",oauth_nonce="ABCDEF",oauth_version="1.0",oauth_signature_method="HMAC-SHA1",oauth_consumer_key="asdasdnm2321b3"'); + }, + '_buildAuthorizationHeaders should not depends on Array.prototype.toString' : function(oa) { + var _toString = Array.prototype.toString; + Array.prototype.toString = function(){ return '[Array] ' + this.length; }; // toString overwrite example used in jsdom. + var parameters= [ + ["foo", "2343"], + ["oauth_timestamp", "1234567"], + ["oauth_nonce", "ABCDEF"], + ["bar", "dfsdfd"], + ["oauth_version", "1.0"], + ["oauth_signature_method", "HMAC-SHA1"], + ["oauth_consumer_key", "asdasdnm2321b3"], + ["foobar", "asdasdnm2321b3"]]; + assert.equal(oa._buildAuthorizationHeaders(parameters), 'OAuth oauth_timestamp="1234567",oauth_nonce="ABCDEF",oauth_version="1.0",oauth_signature_method="HMAC-SHA1",oauth_consumer_key="asdasdnm2321b3"'); + Array.prototype.toString = _toString; + } + }, + 'When performing the Secure Request' : { + topic: new OAuth("http://foo.com/RequestToken", + "http://foo.com/AccessToken", + "anonymous", "anonymous", + "1.0A", "http://foo.com/callback", "HMAC-SHA1"), + 'using the POST method' : { + 'Any passed extra_params should form part of the POST body': function(oa) { + var post_body_written= false; + var op= oa._oa._createClient; + try { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return { + write: function(post_body){ + post_body_written= true; + assert.equal(post_body,"scope=foobar%2C1%2C2"); + } + }; + }; + oa._oa._performSecureRequest("token", "token_secret", 'POST', 'http://foo.com/protected_resource', {"scope": "foobar,1,2"}); + assert.equal(post_body_written, true); + } + finally { + oa._oa._createClient= op; + } + } + } + }, + 'When performing a secure' : { + topic: new OAuth("http://foo.com/RequestToken", + "http://foo.com/AccessToken", + "anonymous", "anonymous", + "1.0A", "http://foo.com/callback", "HMAC-SHA1"), + 'POST' : { + 'if no callback is passed' : { + 'it should return a Promise object': function(oa) { + var promise = oa.post('http://foo.com/blah', 'token', 'token_secret', 'BLAH', 'text/plain'); + assert.isObject(promise); + } + }, + 'if the post_body is a buffer' : { + "It should be passed through as is, and the original content-type (if specified) should be passed through": function(oa) { + var op= oa._oa._createClient; + try { + var callbackCalled= false; + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + assert.equal(headers["Content-Type"], "image/jpeg"); + return { + write: function(data){ + callbackCalled= true; + assert.equal(data.length, 4); + }, + on: function() {}, + end: function() { + } + }; + }; + oa.post("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40]), "image/jpeg").nodeify(function() { + assert.equal(callbackCalled, true); + }); + } + finally { + oa._oa._createClient= op; + } + }, + "It should be passed through as is, and no content-type is specified.": function(oa) { + //Should probably actually set application/octet-stream, but to avoid a change in behaviour + // will just document (here) that the library will set it to application/x-www-form-urlencoded + var op= oa._oa._createClient; + try { + var callbackCalled= false; + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + assert.equal(headers["Content-Type"], "application/x-www-form-urlencoded"); + return { + write: function(data){ + callbackCalled= true; + assert.equal(data.length, 4); + }, + on: function() {}, + end: function() { + } + }; + }; + oa.post("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40])).nodeify(function() { + assert.equal(callbackCalled, true); + }); + } + finally { + oa._oa._createClient= op; + } + } + }, + 'if the post_body is not a string or a buffer' : { + "It should be url encoded and the content type set to be x-www-form-urlencoded": function(oa) { + var op = oa._oa._createClient; + try { + var callbackCalled= false; + oa._oa._createClient= function(port, hostname, method, path, headers, sshEnabled) { + assert.equal(headers["Content-Type"], "application/x-www-form-urlencoded"); + return { + write: function(data) { + callbackCalled = true; + assert.equal(data, "foo=1%2C2%2C3&bar=1%2B2"); + }, + on: function() {}, + end: function() { + } + }; + }; + oa.post("http://foo.com/blah", "token", "token_secret", { "foo": "1,2,3", "bar": "1+2" }).nodeify(function() { + assert.equal(callbackCalled, true); + }); + } finally { + oa._oa._createClient= op; + } + } + }, + 'if the post_body is a string' : { + "and it contains non ascii (7/8bit) characters" : { + "the content length should be the byte count, and not the string length" : function(oa) { + var testString= "Tôi yêu node"; + var testStringLength= testString.length; + var testStringBytesLength= Buffer.byteLength(testString); + assert.notEqual(testStringLength, testStringBytesLength); // Make sure we're testing a string that differs between byte-length and char-length! + + var op= oa._oa._createClient; + try { + var callbackCalled= false; + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + assert.equal(headers["Content-length"], testStringBytesLength); + return { + write: function(data){ + callbackCalled= true; + assert.equal(data, testString); + }, + on: function() {}, + end: function() { + } + }; + }; + oa.post("http://foo.com/blah", "token", "token_secret", "Tôi yêu node").nodeify(function() { + assert.equal(callbackCalled, true); + }); + } + finally { + oa._oa._createClient= op; + } + } + }, + "and no post_content_type is specified" : { + "It should be written as is, with a content length specified, and the encoding should be set to be x-www-form-urlencoded" : function(oa) { + var op= oa._oa._createClient; + try { + var callbackCalled= false; + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + assert.equal(headers["Content-Type"], "application/x-www-form-urlencoded"); + assert.equal(headers["Content-length"], 23); + return { + write: function(data){ + callbackCalled= true; + assert.equal(data, "foo=1%2C2%2C3&bar=1%2B2"); + }, + on: function() {}, + end: function() { + } + }; + }; + oa.post("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2").nodeify(function() { + assert.equal(callbackCalled, true); + }); + } + finally { + oa._oa._createClient= op; + } + } + }, + "and a post_content_type is specified" : { + "It should be written as is, with a content length specified, and the encoding should be set to be as specified" : function(oa) { + var op= oa._oa._createClient; + try { + var callbackCalled= false; + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + assert.equal(headers["Content-Type"], "unicorn/encoded"); + assert.equal(headers["Content-length"], 23); + return { + write: function(data){ + callbackCalled= true; + assert.equal(data, "foo=1%2C2%2C3&bar=1%2B2"); + }, + on: function() {}, + end: function() { + } + }; + }; + oa.post("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2", "unicorn/encoded").nodeify(function() { + assert.equal(callbackCalled, true); + }); + } + finally { + oa._oa._createClient= op; + } + } + } + } + }, + 'GET' : { + 'if no callback is passed' : { + 'it should return a request object': function(oa) { + var promise= oa.get("http://foo.com/blah", "token", "token_secret"); + assert.isObject(promise); + } + }, + 'if a callback is passed' : { + "it should call the internal request's end method and return nothing": function(oa) { + var callbackCalled= false; + var op= oa._oa._createClient; + try { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return { + on: function() {}, + end: function() { + callbackCalled= true; + } + }; + }; + oa.get("http://foo.com/blah", "token", "token_secret", function(e,d) {}).nodeify(function() { + assert.equal(callbackCalled, true); + }); + } + finally { + oa._oa._createClient= op; + } + } + }, + }, + 'PUT' : { + 'if no callback is passed' : { + 'it should return a promise object': function(oa) { + var promise= oa.put("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain"); + assert.isObject(promise); + } + }, + 'if a callback is passed' : { + "it should call the internal request's end method and return nothing": function(oa) { + var callbackCalled= 0; + var op= oa._oa._createClient; + try { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return { + on: function() {}, + write: function(data) { + callbackCalled++; + }, + end: function() { + callbackCalled++; + } + }; + }; + oa.put("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain", function(e,d){}).nodeify(function() { + assert.equal(callbackCalled, 2); + }); + } + finally { + oa._oa._createClient= op; + } + } + }, + 'if the post_body is a buffer' : { + "It should be passed through as is, and the original content-type (if specified) should be passed through": function(oa) { + var op= oa._oa._createClient; + try { + var callbackCalled= false; + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + assert.equal(headers["Content-Type"], "image/jpeg"); + return { + write: function(data){ + callbackCalled= true; + assert.equal(data.length, 4); + }, + on: function() {}, + end: function() { + } + }; + }; + oa.put("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40]), "image/jpeg").nodeify(function() { + assert.equal(callbackCalled, true); + }); + } + finally { + oa._oa._createClient= op; + } + }, + "It should be passed through as is, and no content-type is specified.": function(oa) { + //Should probably actually set application/octet-stream, but to avoid a change in behaviour + // will just document (here) that the library will set it to application/x-www-form-urlencoded + var op= oa._oa._createClient; + try { + var callbackCalled= false; + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + assert.equal(headers["Content-Type"], "application/x-www-form-urlencoded"); + return { + write: function(data){ + callbackCalled= true; + assert.equal(data.length, 4); + }, + on: function() {}, + end: function() { + } + }; + }; + oa.put("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40])).nodeify(function() { + assert.equal(callbackCalled, true); + }); + } + finally { + oa._oa._createClient= op; + } + } + }, + 'if the post_body is not a string' : { + "It should be url encoded and the content type set to be x-www-form-urlencoded" : function(oa) { + var op= oa._oa._createClient; + try { + var callbackCalled= false; + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + assert.equal(headers["Content-Type"], "application/x-www-form-urlencoded"); + return { + write: function(data) { + callbackCalled= true; + assert.equal(data, "foo=1%2C2%2C3&bar=1%2B2"); + } + }; + }; + oa.put("http://foo.com/blah", "token", "token_secret", {"foo":"1,2,3", "bar":"1+2"}).nodeify(function() { + assert.equal(callbackCalled, true); + }); + } + finally { + oa._oa._createClient= op; + } + } + }, + 'if the post_body is a string' : { + "and no post_content_type is specified" : { + "It should be written as is, with a content length specified, and the encoding should be set to be x-www-form-urlencoded" : function(oa) { + var op= oa._oa._createClient; + try { + var callbackCalled= false; + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + assert.equal(headers["Content-Type"], "application/x-www-form-urlencoded"); + assert.equal(headers["Content-length"], 23); + return { + write: function(data) { + callbackCalled= true; + assert.equal(data, "foo=1%2C2%2C3&bar=1%2B2"); + } + }; + }; + oa.put("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2").nodeify(function() { + assert.equal(callbackCalled, true); + }); + } + finally { + oa._oa._createClient= op; + } + } + }, + "and a post_content_type is specified" : { + "It should be written as is, with a content length specified, and the encoding should be set to be as specified" : function(oa) { + var op= oa._oa._createClient; + try { + var callbackCalled= false; + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + assert.equal(headers["Content-Type"], "unicorn/encoded"); + assert.equal(headers["Content-length"], 23); + return { + write: function(data) { + callbackCalled= true; + assert.equal(data, "foo=1%2C2%2C3&bar=1%2B2"); + } + }; + }; + oa.put("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2", "unicorn/encoded").nodeify(function() { + assert.equal(callbackCalled, true); + }); + } + finally { + oa._oa._createClient= op; + } + } + } + } + }, + 'DELETE' : { + 'if no callback is passed' : { + 'it should return a promise object': function(oa) { + var promise = oa.delete("http://foo.com/blah", "token", "token_secret"); + assert.isObject(promise); + } + } + }, + 'Request With a Callback' : { + 'and a 200 response code is received' : { + 'it should callback successfully' : function(oa) { + var op= oa._oa._createClient; + var callbackCalled = false; + try { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest( new DummyResponse(200) ); + }; + oa._oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', {"scope": "foobar,1,2"}, null, null, function(error) { + // callback + callbackCalled= true; + assert.equal(error, undefined); + }); + assert.equal(callbackCalled, true); + } + finally { + oa._oa._createClient= op; + } + } + }, + 'and a 210 response code is received' : { + 'it should callback successfully' : function(oa) { + var op= oa._oa._createClient; + var callbackCalled = false; + try { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest( new DummyResponse(210) ); + }; + oa._oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', {"scope": "foobar,1,2"}, null, null, function(error) { + // callback + callbackCalled= true; + assert.equal(error, undefined); + }); + assert.equal(callbackCalled, true); + } + finally { + oa._oa._createClient= op; + } + } + }, + 'And A 301 redirect is received' : { + 'and there is a location header' : { + 'it should (re)perform the secure request but with the new location' : function(oa) { + var op= oa._oa._createClient; + var psr= oa._oa._performSecureRequest; + var responseCounter = 1; + var callbackCalled = false; + var DummyResponse =function() { + if( responseCounter == 1 ){ + this.statusCode= 301; + this.headers= {location:"http://redirectto.com"}; + responseCounter++; + } + else { + this.statusCode= 200; + } + }; + DummyResponse.prototype= events.EventEmitter.prototype; + DummyResponse.prototype.setEncoding= function() {}; + + try { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest( new DummyResponse() ); + }; + oa._oa._performSecureRequest= function( oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback ) { + if( responseCounter == 1 ) { + assert.equal(url, "http://originalurl.com"); + } + else { + assert.equal(url, "http://redirectto.com"); + } + return psr.call(oa._oa, oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback ); + }; + + oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', {"scope": "foobar,1,2"}, null, null, function() { + // callback + assert.equal(responseCounter, 2); + callbackCalled= true; + }); + assert.equal(callbackCalled, true); + } + finally { + oa._oa._createClient= op; + oa._oa._performSecureRequest= psr; + } + } + }, + 'but there is no location header' : { + 'it should execute the callback, passing the HTTP Response code' : function(oa) { + var op= oa._createClient; + var callbackCalled = false; + try { + oa._oa._createClient = function (port, hostname, method, path, headers, sshEnabled) { + return new DummyRequest(new DummyResponse(301)); + }; + oa._oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', { "scope": "foobar,1,2" }, null, null, function(error) { + assert.equal(error.statusCode, 301); + callbackCalled = true; + }); + assert.equal(callbackCalled, true); + } finally { + oa._oa._createClient = op; + } + } + }, + 'and followRedirect is true' : { + 'it should (re)perform the secure request but with the new location' : function(oa) { + var op = oa._oa._createClient; + var psr = oa._oa._performSecureRequest; + var responseCounter = 1; + var callbackCalled = false; + var DummyResponse = function() { + if (responseCounter === 1) { + this.statusCode = 301; + this.headers = { location: "http://redirectto.com" }; + responseCounter++; + } else { + this.statusCode = 200; + } + }; + DummyResponse.prototype = events.EventEmitter.prototype; + DummyResponse.prototype.setEncoding = function() {}; + + try { + oa._oa._createClient = function(port, hostname, method, path, headers, sshEnabled) { + return new DummyRequest(new DummyResponse()); + }; + oa._oa._performSecureRequest = function(oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback) { + if (responseCounter === 1) { + assert.equal(url, "http://originalurl.com"); + } else { + assert.equal(url, "http://redirectto.com"); + } + return psr.call(oa._oa, oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback); + }; + + oa._oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', { "scope": "foobar,1,2" }, null, null, function() { + assert.equal(responseCounter, 2); + callbackCalled = true; + }); + assert.equal(callbackCalled, true); + } finally { + oa._oa._createClient = op; + oa._oa._performSecureRequest = psr; + } + } + }, + 'and followRedirect is false': { + 'it should not perform the secure request with the new location': function(oa) { + var op = oa._oa._createClient; + oa.setClientOptions({ followRedirects: false }); + var DummyResponse = function() { + this.statusCode = 301; + this.headers = { location: 'http://redirectto.com' }; + }; + DummyResponse.prototype = events.EventEmitter.prototype; + DummyResponse.prototype.setEncoding = function() {}; + + try { + oa._oa._createClient = function(port, hostname, method, path, headers, sshEnabled) { + return new DummyRequest(new DummyResponse()); + }; + oa._oa._performSecureRequest('token', 'token_secret', 'POST', 'http://originalurl.com', { 'scope': 'foobar,1,2' }, null, null, function(res, data, response) { + assert.equal(res.statusCode, 301); + }); + } finally { + oa._oa._createClient = op; + oa.setClientOptions({ followRedirects: true }); + } + } + } + }, + 'And A 302 redirect is received' : { + 'and there is a location header' : { + 'it should (re)perform the secure request but with the new location' : function(oa) { + var op = oa._oa._createClient; + var psr = oa._oa._performSecureRequest; + var responseCounter = 1; + var callbackCalled = false; + var DummyResponse = function() { + if( responseCounter === 1 ){ + this.statusCode = 302; + this.headers = { location: "http://redirectto.com" }; + responseCounter++; + } else { + this.statusCode = 200; + } + }; + DummyResponse.prototype = events.EventEmitter.prototype; + DummyResponse.prototype.setEncoding = function() {}; + + try { + oa._oa._createClient= function(port, hostname, method, path, headers, sshEnabled) { + return new DummyRequest(new DummyResponse()); + }; + oa._oa._performSecureRequest = function(oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback) { + if (responseCounter === 1) { + assert.equal(url, "http://originalurl.com"); + } else { + assert.equal(url, "http://redirectto.com"); + } + return psr.call(oa._oa, oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback); + }; + + oa._oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', { "scope": "foobar,1,2" }, null, null, function() { + // callback + assert.equal(responseCounter, 2); + callbackCalled = true; + }); + assert.equal(callbackCalled, true); + } finally { + oa._oa._createClient = op; + oa._oa._performSecureRequest = psr; + } + } + }, + 'but there is no location header': { + 'it should execute the callback, passing the HTTP Response code': function(oa) { + var op = oa._oa._createClient; + var callbackCalled = false; + try { + + oa._oa._createClient = function(port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest(new DummyResponse(302)); + }; + oa._oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', { "scope": "foobar,1,2" }, null, null, function(error) { + assert.equal(error.statusCode, 302); + callbackCalled = true; + }); + assert.equal(callbackCalled, true); + + } finally { + oa._oa._createClient = op; + } + } + }, + 'and followRedirect is true': { + 'it should (re)perform the secure request but with the new location': function(oa) { + var op = oa._oa._createClient; + var psr = oa._oa._performSecureRequest; + var responseCounter = 1; + var callbackCalled = false; + var DummyResponse = function() { + + if (responseCounter === 1) { + this.statusCode = 302; + this.headers = { + location: 'http://redirectto.com' + }; + responseCounter++; + } else { + this.statusCode = 200; + } + + }; + DummyResponse.prototype = events.EventEmitter.prototype; + DummyResponse.prototype.setEncoding = function() {}; + + try { + + oa._oa._createClient = function(port, hostname, method, path, headers, sshEnabled) { + return new DummyRequest(new DummyResponse()); + }; + oa._oa._performSecureRequest = function(oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback) { + + if (responseCounter === 1) { + assert.equal(url, 'http://originalurl.com'); + } else { + assert.equal(url, 'http://redirectto.com'); + } + + return psr.call(oa._oa, oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback); + }; + oa._oa._performSecureRequest('token', 'token_secret', 'POST', 'http://originalurl.com', { 'scope': 'foobar,1,2' }, null, null, function() { + // callback + assert.equal(responseCounter, 2); + callbackCalled = true; + }); + assert.equal(callbackCalled, true); + + } finally { + + oa._oa._createClient = op; + oa._oa._performSecureRequest = psr; + + } + } + }, + 'and followRedirect is false': { + 'it should not perform the secure request with the new location': function(oa) { + var op = oa._oa._createClient; + oa.setClientOptions({ followRedirects: false }); + var DummyResponse = function() { + this.statusCode = 302; + this.headers = { + location: 'http://redirectto.com' + }; + }; + DummyResponse.prototype = events.EventEmitter.prototype; + DummyResponse.prototype.setEncoding = function() {}; + + try { + oa._oa._createClient= function(port, hostname, method, path, headers, sshEnabled) { + return new DummyRequest(new DummyResponse()); + }; + oa._oa._performSecureRequest('token', 'token_secret', 'POST', 'http://originalurl.com', { 'scope': 'foobar,1,2' }, null, null, function(res, data, response) { + // callback + assert.equal(res.statusCode, 302); + }); + } finally { + oa._createClient = op; + oa.setClientOptions({ followRedirects: true }); + } + } + } + } + } + } +}).export(module); diff --git a/tests/oauthtests.js b/tests/oauthtests.js index d36bfed7..d7e60e37 100644 --- a/tests/oauthtests.js +++ b/tests/oauthtests.js @@ -1,3 +1,22 @@ +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * + * 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 . + */ + var vows = require('vows'), assert = require('assert'), DummyResponse= require('./shared').DummyResponse, @@ -206,7 +225,17 @@ vows.describe('OAuth').addBatch({ oa.setClientOptions({}); oa.getOAuthAccessToken(function() {}); assert.equal(oa.requestArguments[2], "POST"); - } + }, + '': function(oa) { + var extraParams = { extra: 1, params: 2 }; + oa.getOAuthAccessToken(null, null, null, function callback() { }, extraParams); + assert.ok('extra' in oa.requestArguments[4]); + assert.ok('params' in oa.requestArguments[4]); + assert.ok('oauth_verifier' in oa.requestArguments[4]); + assert.equal(oa.requestArguments[4].extra, extraParams.extra); + assert.equal(oa.requestArguments[4].params, extraParams.params); + assert.equal(oa.requestArguments[4].oauth_verifier, null); + } }, 'When get authorization header' : { topic: function() { @@ -320,6 +349,73 @@ vows.describe('OAuth').addBatch({ oa._createClient= op; } } + }, + 'Passing "Content-Type" header to constructor should set _defaultContentType': function (){ + var expectedContentType = 'application/json'; + var oa = new OAuth("http://foo.com/RequestToken", + "http://foo.com/AccessToken", + "anonymous", "anonymous", + "1.0A", "http://foo.com/callback", "HMAC-SHA1", 32, {"Content-Type": expectedContentType}); + assert.equal(oa._defaultContentType, expectedContentType); + }, + 'Passing "Content-Type" header to constructor should not override contentType explicitly passed to _performSecureRequest': function (){ + var initialContentType = 'application/json'; + var expectedContentType = 'text/plain'; + var oa = new OAuth("http://foo.com/RequestToken", + "http://foo.com/AccessToken", + "anonymous", "anonymous", + "1.0A", "http://foo.com/callback", "HMAC-SHA1", 32, {"Content-Type": initialContentType}); + var createClientHeaders = null; + oa._createClient = function (port, hostname, method, path, headers, sshEnabled) { + createClientHeaders = headers; + return { + write: function (post_body) { + } + }; + }; + oa._performSecureRequest("token", "token_secret", 'POST', 'http://foo.com/protected_resource', {"scope": "foobar,1,2"}, '', expectedContentType); + assert.equal(createClientHeaders['Content-Type'], expectedContentType); + }, + 'Setting content-type on OAuth object should set content-type on request to value passed to setDefaultContentType': function (oa) { + var op = oa._createClient; + var opContentType = oa._defaultContentType; + var expectedContentType = 'application/json'; + oa.setDefaultContentType(expectedContentType); + var createClientHeaders = null; + try { + oa._createClient = function (port, hostname, method, path, headers, sshEnabled) { + createClientHeaders = headers; + return { + write: function (post_body) { + } + }; + }; + oa._performSecureRequest("token", "token_secret", 'POST', 'http://foo.com/protected_resource', {"scope": "foobar,1,2"}); + assert.equal(createClientHeaders['Content-Type'], expectedContentType); + } + finally { + oa._createClient = op; + oa._defaultContentType = opContentType; + } + }, + 'Not setting content-type on OAuth object should set content-type on request to application/x-www-form-urlencoded': function (oa) { + var createClientHeaders = null; + var op = oa._createClient; + try { + oa._createClient = function (port, hostname, method, path, headers, sshEnabled) { + createClientHeaders = headers; + return { + write: function (post_body) { + } + }; + }; + oa._performSecureRequest("token", "token_secret", 'POST', 'http://foo.com/protected_resource', {"scope": "foobar,1,2"}); + assert.equal(createClientHeaders['Content-Type'], 'application/x-www-form-urlencoded'); + } + finally { + oa.setDefaultContentType(null); + oa._createClient = op; + } } }, 'When performing a secure' : { diff --git a/tests/sha1tests.js b/tests/sha1tests.js index 18ba0ae3..f9c96530 100644 --- a/tests/sha1tests.js +++ b/tests/sha1tests.js @@ -1,13 +1,35 @@ -var vows = require('vows'), - assert = require('assert'); +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * + * 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. -vows.describe('SHA1 Hashing').addBatch({ - 'When using the SHA1 Hashing function': { - topic: require('../lib/sha1'), - 'we get the specified digest as described in http://oauth.net/core/1.0/#sig_base_example (A.5.2)': function (sha1) { - assert.equal (sha1.HMACSHA1( "kd94hf93k423kf44&pfkkdhi9sl3r4s00", - "GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal"), - "tR3+Ty81lMeYAr/Fid0kMTYa/WM="); - } + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +var vows = require("vows"); +var assert = require("assert"); +var sha1 = require("../lib/sha1"); + +vows.describe("SHA1 Hashing").addBatch({ + "When using the SHA1 Hashing function": { + topic: sha1, + "we get the specified digest as described in http://oauth.net/core/1.0/#sig_base_example (A.5.2)": function (sha1Object) { + var result = sha1Object.hmacsha1( + "kd94hf93k423kf44&pfkkdhi9sl3r4s00", + "GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal"); + var expected = "tR3+Ty81lMeYAr/Fid0kMTYa/WM="; + assert.equal(result, expected); } -}).export(module); \ No newline at end of file + } +}).export(module); diff --git a/tests/shared.js b/tests/shared.js index f4c80946..27d4b831 100644 --- a/tests/shared.js +++ b/tests/shared.js @@ -1,26 +1,50 @@ -var events = require('events'); - -exports.DummyResponse = function( statusCode ) { - this.statusCode= statusCode; - this.headers= {}; -} -exports.DummyResponse.prototype= events.EventEmitter.prototype; -exports.DummyResponse.prototype.setEncoding= function() {} - -exports.DummyRequest =function( response ) { - this.response= response; - this.responseSent= false; -} -exports.DummyRequest.prototype= events.EventEmitter.prototype; -exports.DummyRequest.prototype.write= function(post_body){} -exports.DummyRequest.prototype.write= function(post_body){ - this.responseSent= true; - this.emit('response',this.response); -} -exports.DummyRequest.prototype.end= function(){ - if(!this.responseSent) { - this.responseSent= true; - this.emit('response',this.response); +/** + * node-oauth-libre is a Node.js library for OAuth + * + * Copyright (C) 2010-2012 Ciaran Jessup + * + * 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 . + */ + +var events = require("events"); + +exports.DummyResponse = function(statusCode) { + this.statusCode = statusCode; + this.headers = {}; +}; + +exports.DummyResponse.prototype = events.EventEmitter.prototype; + +exports.DummyResponse.prototype.setEncoding = function() { +}; + +exports.DummyRequest = function(response) { + this.response = response; + this.responseSent = false; +}; + +exports.DummyRequest.prototype = events.EventEmitter.prototype; + +exports.DummyRequest.prototype.write = function(postBody) { + this.responseSent = true; + this.emit("response", this.response); +}; + +exports.DummyRequest.prototype.end = function() { + if (!this.responseSent) { + this.responseSent = true; + this.emit("response",this.response); } - this.response.emit('end'); -} \ No newline at end of file + this.response.emit("end"); +};