From 0ed2589eba0c85a6a94a9fbac880af1dc5140118 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 8 Feb 2016 17:38:39 -0500 Subject: [PATCH 01/90] updated package.json --- package.json | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index 1a555333..24809ab5 100644 --- a/package.json +++ b/package.json @@ -1,19 +1,28 @@ -{ "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", + "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 ", + "contributors": [ + { + "name": "Rudolf Olah", + "email": "omouse@gmail.com" + } + ] + "repository": { "type":"git", "url":"http://github.com/omouse/node-oauth.git" }, + "devDependencies": { "vows": "0.5.x" } , "scripts": { "test": "make test" } , "licenses" : - [ { "type" : "MIT" - , "url" : "http://github.com/ciaranj/node-oauth/raw/master/LICENSE" + [ { "type" : "GPL" + , "url" : "http://github.com/omouse/node-oauth/raw/master/LICENSE" } ] } From 4a834fdd4c332e887ecbb9ef3f87594d3527f206 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 8 Feb 2016 17:43:21 -0500 Subject: [PATCH 02/90] Update and rename LICENSE to LICENSE.mit --- LICENSE | 8 -------- LICENSE.mit | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 8 deletions(-) delete mode 100644 LICENSE create mode 100644 LICENSE.mit diff --git a/LICENSE b/LICENSE deleted file mode 100644 index f8049f8c..00000000 --- a/LICENSE +++ /dev/null @@ -1,8 +0,0 @@ -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/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. From 9aefed6e1d85fd0ea166c8542519370931c49c39 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 8 Feb 2016 17:43:46 -0500 Subject: [PATCH 03/90] Create LICENSE --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. From 3894b87bcf05de1b8ce90092e8cdf0c055928c78 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 8 Feb 2016 17:47:16 -0500 Subject: [PATCH 04/90] license information using gpl v3 + mit see this StackOverflow answer for more info: http://programmers.stackexchange.com/a/178252/7433 --- Readme.md | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/Readme.md b/Readme.md index 89132102..c577307f 100644 --- a/Readme.md +++ b/Readme.md @@ -1,24 +1,24 @@ -node-oauth -=========== +# node-oauth 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 +## License and Copyright -Installation -============== +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. + +# Installation $ npm install oauth -Examples -========== +# Examples To run examples/tests install Mocha `$ npm install -g mocha` and run `$ mocha you-file-name.js`: @@ -76,8 +76,7 @@ describe('OAuth2',function(){ }); ``` -Change History -============== +# Change History * 0.9.14 - OAuth2: Extend 'successful' token responses to include anything in the 2xx range. * 0.9.13 @@ -156,8 +155,7 @@ Change History * 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) -Contributors (In no particular order) -===================================== +# Contributors (In no particular order) * Evan Prodromou * Jose Ignacio Andres From e918cc7df08df06cfe387f518009ea035d04d3cf Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 8 Feb 2016 21:15:10 -0500 Subject: [PATCH 05/90] better example in readme --- Readme.md | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index c577307f..6eabfdb5 100644 --- a/Readme.md +++ b/Readme.md @@ -52,8 +52,43 @@ describe('OAuth1.0',function(){ ``` ## OAuth2.0 + +### Usage + +```javascript +var OAuth2 = require('oauth').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); + } + } +); +``` + +### Test + ```javascript -describe('OAuth2',function(){ +describe('OAuth2',function() { var OAuth = require('oauth'); it('gets bearer token', function(done){ From 0331b58d34d0983781db40c2a12658a4e26b0d00 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Tue, 9 Feb 2016 10:45:41 -0500 Subject: [PATCH 06/90] renamed package from oauth to oauth-libre --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 24809ab5..44888b1b 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name" : "oauth", + "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.", "version": "0.9.14", "directories": { From 86dbae515a55cb30969ed51977f7c19a1d352f4e Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Tue, 9 Feb 2016 10:46:37 -0500 Subject: [PATCH 07/90] renamed from oauth to oauth-libre --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 6eabfdb5..c150bb76 100644 --- a/Readme.md +++ b/Readme.md @@ -15,7 +15,7 @@ If you go to the original project and modify the code there, your changes will b # Installation - $ npm install oauth + npm install oauth-libre # Examples From 202ec07a04729cff26147fb75604147fcb6f0294 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Sun, 20 Mar 2016 12:53:18 -0400 Subject: [PATCH 08/90] OAuth2 Promises Support Added bluebird as a dependency Using Bluebird's promisifyAll and an object that delegates methods to the OAuth2 implementation to be able to support promises. Copied tests from oauth2 to oauth2promises. Existing tests are passing with some small corrections. --- index.js | 3 +- lib/oauth2-promise.js | 38 +++++ package.json | 5 +- tests/oauth2promise-tests.js | 290 +++++++++++++++++++++++++++++++++++ 4 files changed, 334 insertions(+), 2 deletions(-) create mode 100644 lib/oauth2-promise.js create mode 100644 tests/oauth2promise-tests.js diff --git a/index.js b/index.js index e20716dd..8e012af9 100644 --- a/index.js +++ b/index.js @@ -1,3 +1,4 @@ exports.OAuth = require("./lib/oauth").OAuth; exports.OAuthEcho = require("./lib/oauth").OAuthEcho; -exports.OAuth2 = require("./lib/oauth2").OAuth2; \ No newline at end of file +exports.OAuth2 = require("./lib/oauth2").OAuth2; +exports.PromiseOAuth2 = require("./lib/oauth2-promise").OAuth2; diff --git a/lib/oauth2-promise.js b/lib/oauth2-promise.js new file mode 100644 index 00000000..da949fcd --- /dev/null +++ b/lib/oauth2-promise.js @@ -0,0 +1,38 @@ +var Promise = require('bluebird'); +var _OAuth2 = require('./oauth2').OAuth2; + +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); +}; + +// Promisfied public API for OAuth2 +OAuth2.prototype.getOAuthAccessToken = function() { + return this._oa.getOAuthAccessTokenAsync.apply(this._oa, arguments); +}; + +OAuth2.prototype.get = function() { + return this._oa.getAsync.apply(this._oa, arguments); +}; + +// delegates PromiseOAuth2.methodName to OAuth2.methodName +var delegatedMethods = [ + 'buildAuthHeader', + 'getAuthorizeUrl', + 'setAuthMethod', + 'useAuthorizationHeaderforGET', + + // Required for testing + '_executeRequest', + '_request' +]; + +delegatedMethods.forEach(delegate); + +function delegate(methodName) { + OAuth2.prototype[methodName] = function() { + return this._oa[methodName].apply(this._oa, arguments); + }; +} + +exports.OAuth2 = OAuth2; diff --git a/package.json b/package.json index 44888b1b..5b06a6f3 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,10 @@ } ] "repository": { "type":"git", "url":"http://github.com/omouse/node-oauth.git" }, - "devDependencies": { + "dependencies": { + "bluebird": "^3.3.4" + }, + "devDependencies": { "vows": "0.5.x" } , "scripts": { diff --git a/tests/oauth2promise-tests.js b/tests/oauth2promise-tests.js new file mode 100644 index 00000000..86e75009 --- /dev/null +++ b/tests/oauth2promise-tests.js @@ -0,0 +1,290 @@ +var vows = require('vows'), + assert = require('assert'), + DummyResponse= require('./shared').DummyResponse, + DummyRequest= require('./shared').DummyRequest, + https = require('https'), + OAuth2= require('../lib/oauth2-promise').OAuth2, + 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 http_library= { + 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", {} ); + } + }, + '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"} ); + } + }, + '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"} ); + } + }, + '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"); + } + } + }, + '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"); + } + } + } + }, + '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"); + }; + 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", 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("", {}); + } + } + }, + '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("", {}); + } + } + } +}).export(module); From 795cc48ecab4c21f67dae30af69dd098322f0862 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Sun, 20 Mar 2016 12:58:10 -0400 Subject: [PATCH 09/90] package.json formatting and bumped version Version is now 0.9.15, added links to both GPL and MIT licenses. --- package.json | 52 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 22 deletions(-) diff --git a/package.json b/package.json index 44888b1b..4dffce5d 100644 --- a/package.json +++ b/package.json @@ -1,28 +1,36 @@ { - "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.", - "version": "0.9.14", - "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.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.", + "version": "0.9.15", + "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": { "vows": "0.5.x" - } -, "scripts": { + }, + "scripts": { "test": "make test" - } -, "licenses" : - [ { "type" : "GPL" - , "url" : "http://github.com/omouse/node-oauth/raw/master/LICENSE" + }, + "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" } ] } From a2d5c8e77b96639cd9359b55a1607c72ef7d9cbb Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Sun, 20 Mar 2016 15:55:33 -0400 Subject: [PATCH 10/90] whitespace cleanup --- Readme.md | 72 +++++++++++++++++++++++++++---------------------------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/Readme.md b/Readme.md index c150bb76..d2616010 100644 --- a/Readme.md +++ b/Readme.md @@ -41,17 +41,17 @@ describe('OAuth1.0',function(){ 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 @@ -92,14 +92,14 @@ describe('OAuth2',function() { var OAuth = require('oauth'); 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( '', @@ -140,55 +140,55 @@ describe('OAuth2',function() { - 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) From dc0d8440ffbffaf74b54b106a073b20c1e9058e6 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Fri, 25 Mar 2016 19:17:47 -0400 Subject: [PATCH 11/90] license info re: patches --- Readme.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index d2616010..290b399b 100644 --- a/Readme.md +++ b/Readme.md @@ -7,12 +7,16 @@ Also provides rudimentary OAuth2 support, tested against facebook, github, fours ## 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. +**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 From bff7e8bb1cd6e31cf20b34a2a7c259cf7644bbfd Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Fri, 25 Mar 2016 19:37:14 -0400 Subject: [PATCH 12/90] work in progress, OAuth 1 promises support --- index.js | 1 + lib/oauth-promise.js | 58 ++ tests/oauthpromise-tests.js | 1068 +++++++++++++++++++++++++++++++++++ 3 files changed, 1127 insertions(+) create mode 100644 lib/oauth-promise.js create mode 100644 tests/oauthpromise-tests.js diff --git a/index.js b/index.js index 8e012af9..80be24bb 100644 --- a/index.js +++ b/index.js @@ -1,4 +1,5 @@ exports.OAuth = require("./lib/oauth").OAuth; exports.OAuthEcho = require("./lib/oauth").OAuthEcho; exports.OAuth2 = require("./lib/oauth2").OAuth2; +exports.PromiseOAuth = require("./lib/oauth-promise").OAuth; exports.PromiseOAuth2 = require("./lib/oauth2-promise").OAuth2; diff --git a/lib/oauth-promise.js b/lib/oauth-promise.js new file mode 100644 index 00000000..56f11925 --- /dev/null +++ b/lib/oauth-promise.js @@ -0,0 +1,58 @@ +var Promise = require('bluebird'); +var _OAuth = require('./oauth').OAuth; + +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); +}; + +// Promisifed public API for OAuth +var delegatedPromiseMethods = [ + 'delete', + 'get', + 'getOAuthAccessToken', + 'getOAuthRequestToken', + 'post', + 'put', + 'signUrl' +]; + +delegatedPromiseMethods.forEach(asyncDelegate); + +// delegates PromiseOAuth.methodName to OAuth.methodName +var delegatedMethods = [ + 'authHeader', + 'getProtectedResource', + 'setClientOptions', + + // Required for testing + '_buildAuthorizationHeaders', + '_createSignature', + '_createSignatureBase', + '_encodeData', + '_getNonce', + '_getSignature', + '_getTimestamp', + '_makeArrayOfArgumentsHash', + '_normaliseRequestParams', + '_normalizeUrl', + '_performSecureRequest', + '_prepareParameters', + '_sortRequestParams' +]; + +delegatedMethods.forEach(delegate); + +function delegate(methodName) { + OAuth.prototype[methodName] = function() { + return this._oa[methodName].apply(this._oa, arguments); + }; +} + +function asyncDelegate(methodName) { + OAuth.prototype[methodName] = function() { + return this._oa[methodName + 'Async'].apply(this._oa, arguments); + }; +} + +exports.OAuth = OAuth; diff --git a/tests/oauthpromise-tests.js b/tests/oauthpromise-tests.js new file mode 100644 index 00000000..9099ae28 --- /dev/null +++ b/tests/oauthpromise-tests.js @@ -0,0 +1,1068 @@ +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').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._getTimestamp= function(){ return "1272399856"; } + 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._getTimestamp = function() { return "1272399856"; }; + 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._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._createClient; + try { + 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._performSecureRequest("token", "token_secret", 'POST', 'http://foo.com/protected_resource', {"scope": "foobar,1,2"}); + assert.equal(post_body_written, true); + } + finally { + 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 request object': function(oa) { + var request= oa.post("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain") + assert.isObject(request); + assert.equal(request.method, "POST"); + request.end(); + } + }, + '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._createClient; + try { + oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return { + write: function(){}, + on: function() {}, + end: function() { + callbackCalled= true; + } + }; + } + var request= oa.post("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain", function(e,d){}) + assert.equal(callbackCalled, true); + assert.isUndefined(request); + } + finally { + 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._createClient; + try { + var callbackCalled= false; + 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() { + } + }; + }; + var request= oa.post("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40]), "image/jpeg"); + assert.equal(callbackCalled, true); + } + finally { + 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._createClient; + try { + var callbackCalled= false; + 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() { + } + }; + }; + var request= oa.post("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40])); + assert.equal(callbackCalled, true); + } + finally { + 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._createClient; + try { + var callbackCalled= false; + 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() { + } + }; + }; + var request= oa.post("http://foo.com/blah", "token", "token_secret", {"foo":"1,2,3", "bar":"1+2"}); + assert.equal(callbackCalled, true); + } + finally { + 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._createClient; + try { + var callbackCalled= false; + 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() { + } + }; + }; + var request= oa.post("http://foo.com/blah", "token", "token_secret", "Tôi yêu node"); + assert.equal(callbackCalled, true); + } + finally { + 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._createClient; + try { + var callbackCalled= false; + 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() { + } + }; + }; + var request= oa.post("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2"); + assert.equal(callbackCalled, true); + } + finally { + 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._createClient; + try { + var callbackCalled= false; + 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() { + } + }; + }; + var request= oa.post("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2", "unicorn/encoded"); + assert.equal(callbackCalled, true); + } + finally { + oa._createClient= op; + } + } + } + } + }, + 'GET' : { + 'if no callback is passed' : { + 'it should return a request object': function(oa) { + var request= oa.get("http://foo.com/blah", "token", "token_secret"); + assert.isObject(request); + assert.equal(request.method, "GET"); + request.end(); + } + }, + '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._createClient; + try { + oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return { + on: function() {}, + end: function() { + callbackCalled= true; + } + }; + }; + var request= oa.get("http://foo.com/blah", "token", "token_secret", function(e,d) {}); + assert.equal(callbackCalled, true); + assert.isUndefined(request); + } + finally { + oa._createClient= op; + } + } + }, + }, + 'PUT' : { + 'if no callback is passed' : { + 'it should return a request object': function(oa) { + var request= oa.put("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain"); + assert.isObject(request); + assert.equal(request.method, "PUT"); + request.end(); + } + }, + '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._createClient; + try { + oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return { + on: function() {}, + write: function(data) { + callbackCalled++; + }, + end: function() { + callbackCalled++; + } + }; + }; + var request= oa.put("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain", function(e,d){}); + assert.equal(callbackCalled, 2); + assert.isUndefined(request); + } + finally { + 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._createClient; + try { + var callbackCalled= false; + 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() { + } + }; + }; + var request= oa.put("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40]), "image/jpeg"); + assert.equal(callbackCalled, true); + } + finally { + 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._createClient; + try { + var callbackCalled= false; + 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() { + } + }; + }; + var request= oa.put("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40])); + assert.equal(callbackCalled, true); + } + finally { + 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._createClient; + try { + var callbackCalled= false; + 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"); + } + }; + }; + var request= oa.put("http://foo.com/blah", "token", "token_secret", {"foo":"1,2,3", "bar":"1+2"}); + assert.equal(callbackCalled, true); + } + finally { + 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._createClient; + try { + var callbackCalled= false; + 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"); + } + }; + }; + var request= oa.put("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2"); + assert.equal(callbackCalled, true); + } + finally { + 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._createClient; + try { + var callbackCalled= false; + 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"); + } + }; + }; + var request= oa.put("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2", "unicorn/encoded"); + assert.equal(callbackCalled, true); + } + finally { + oa._createClient= op; + } + } + } + } + }, + 'DELETE' : { + 'if no callback is passed' : { + 'it should return a request object': function(oa) { + var request= oa.delete("http://foo.com/blah", "token", "token_secret"); + assert.isObject(request); + assert.equal(request.method, "DELETE"); + request.end(); + } + }, + '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._createClient; + try { + oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return { + on: function() {}, + end: function() { + callbackCalled= true; + } + }; + }; + var request= oa.delete("http://foo.com/blah", "token", "token_secret", function(e,d) {}); + assert.equal(callbackCalled, true); + assert.isUndefined(request); + } + finally { + oa._createClient= op; + } + } + } + }, + 'Request With a Callback' : { + 'and a 200 response code is received' : { + 'it should callback successfully' : function(oa) { + var op= oa._createClient; + var callbackCalled = false; + try { + oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest( new DummyResponse(200) ); + }; + 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._createClient= op; + } + } + }, + 'and a 210 response code is received' : { + 'it should callback successfully' : function(oa) { + var op= oa._createClient; + var callbackCalled = false; + try { + oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest( new DummyResponse(210) ); + }; + 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._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._createClient; + var psr= 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._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest( new DummyResponse() ); + }; + 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, 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._createClient= op; + 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._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest( new DummyResponse(301) ); + }; + oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', {"scope": "foobar,1,2"}, null, null, function(error) { + // callback + assert.equal(error.statusCode, 301); + callbackCalled= true; + }); + assert.equal(callbackCalled, true); + } + finally { + oa._createClient= op; + } + } + }, + 'and followRedirect is true' : { + 'it should (re)perform the secure request but with the new location' : function(oa) { + var op= oa._createClient; + var psr= 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._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest( new DummyResponse() ); + }; + 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, 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._createClient= op; + oa._performSecureRequest= psr; + } + } + }, + 'and followRedirect is false' : { + 'it should not perform the secure request with the new location' : function(oa) { + var op= 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._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest( new DummyResponse() ); + } + oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', {"scope": "foobar,1,2"}, null, null, function(res, data, response) { + // callback + assert.equal(res.statusCode, 301); + }); + } + finally { + 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._createClient; + var psr= 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._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest( new DummyResponse() ); + } + 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, 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._createClient= op; + 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._createClient = function(port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest(new DummyResponse(302)); + }; + oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', {"scope": "foobar,1,2"}, null, null, function(error) { + // callback + assert.equal(error.statusCode, 302); + callbackCalled = true; + }); + assert.equal(callbackCalled, true); + } + finally { + oa._createClient= op; + } + } + }, + 'and followRedirect is true' : { + 'it should (re)perform the secure request but with the new location' : function(oa) { + var op= oa._createClient; + var psr= 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._createClient = function(port, hostname, method, path, headers, sshEnabled) { + return new DummyRequest(new DummyResponse()); + }; + 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, 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._createClient= op; + oa._performSecureRequest= psr; + } + } + }, + 'and followRedirect is false' : { + 'it should not perform the secure request with the new location' : function(oa) { + var op= 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._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + return new DummyRequest( new DummyResponse() ); + }; + 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); From b9d4105c336da4e93c0f92df6c568f2bc48b661f Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 28 Mar 2016 09:54:06 -0400 Subject: [PATCH 13/90] Code style cleanup #8 --- tests/shared.js | 45 +++++++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/tests/shared.js b/tests/shared.js index f4c80946..648539eb 100644 --- a/tests/shared.js +++ b/tests/shared.js @@ -1,26 +1,31 @@ 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.DummyResponse = function(statusCode) { + this.statusCode = statusCode; + this.headers = {}; +}; -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; +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 +}; From 6a599c64e73231ca263fa3542b70cb4c489f958c Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 28 Mar 2016 09:54:44 -0400 Subject: [PATCH 14/90] OAuth1 fixing more broken tests #4 and some code style cleanup #8 --- lib/oauth-promise.js | 1 + tests/oauthpromise-tests.js | 275 ++++++++++++++++++------------------ 2 files changed, 138 insertions(+), 138 deletions(-) diff --git a/lib/oauth-promise.js b/lib/oauth-promise.js index 56f11925..1904e45a 100644 --- a/lib/oauth-promise.js +++ b/lib/oauth-promise.js @@ -33,6 +33,7 @@ var delegatedMethods = [ '_getNonce', '_getSignature', '_getTimestamp', + '_isParameterNameAnOAuthParameter', '_makeArrayOfArgumentsHash', '_normaliseRequestParams', '_normalizeUrl', diff --git a/tests/oauthpromise-tests.js b/tests/oauthpromise-tests.js index 9099ae28..6ab52a1b 100644 --- a/tests/oauthpromise-tests.js +++ b/tests/oauthpromise-tests.js @@ -53,9 +53,9 @@ vows.describe('OAuth').addBatch({ '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'); @@ -81,7 +81,7 @@ vows.describe('OAuth').addBatch({ 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/") + assert.equal(oa._normalizeUrl("http://somehost.com"), "http://somehost.com/"); } }, 'When making an array out of the arguments hash' : { @@ -104,7 +104,7 @@ vows.describe('OAuth').addBatch({ var parameters= {"z": "a", "a": "b", "1": "c" }; - var parameterResults= oa._sortRequestParams(oa._makeArrayOfArgumentsHash(parameters)) + 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"); @@ -113,7 +113,7 @@ vows.describe('OAuth').addBatch({ var parameters= {"z": "a", "a": ["z", "b", "b", "a", "y"], "1": "c" }; - var parameterResults= oa._sortRequestParams(oa._makeArrayOfArgumentsHash(parameters)) + 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"); @@ -149,17 +149,17 @@ vows.describe('OAuth').addBatch({ 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") + 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._getTimestamp= function(){ return "1272399856"; } - oa._getNonce= function(){ return "ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp"; } + oa._getTimestamp= function(){ return "1272399856"; }; + oa._getNonce= function(){ return "ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp"; }; return oa; }, 'Provide a valid signature when no token present': function(oa) { @@ -175,9 +175,9 @@ vows.describe('OAuth').addBatch({ '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; } + 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) { @@ -236,8 +236,8 @@ vows.describe('OAuth').addBatch({ 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"; } + 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) { @@ -257,11 +257,11 @@ vows.describe('OAuth').addBatch({ 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(){}) + oa.getProtectedResource("http://somehost.com:8080", "GET", "oauth_token", null, function(){}); } }, 'When building the OAuth Authorization header': { @@ -320,7 +320,7 @@ vows.describe('OAuth').addBatch({ assert.equal(post_body,"scope=foobar%2C1%2C2"); } }; - } + }; oa._performSecureRequest("token", "token_secret", 'POST', 'http://foo.com/protected_resource', {"scope": "foobar,1,2"}); assert.equal(post_body_written, true); } @@ -338,7 +338,7 @@ vows.describe('OAuth').addBatch({ 'POST' : { 'if no callback is passed' : { 'it should return a request object': function(oa) { - var request= oa.post("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain") + var request= oa.post("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain"); assert.isObject(request); assert.equal(request.method, "POST"); request.end(); @@ -357,8 +357,8 @@ vows.describe('OAuth').addBatch({ callbackCalled= true; } }; - } - var request= oa.post("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain", function(e,d){}) + }; + var request= oa.post("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain", function(e,d){}); assert.equal(callbackCalled, true); assert.isUndefined(request); } @@ -373,7 +373,7 @@ vows.describe('OAuth').addBatch({ try { var callbackCalled= false; oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { - assert.equal(headers["Content-Type"], "image/jpeg") + assert.equal(headers["Content-Type"], "image/jpeg"); return { write: function(data){ callbackCalled= true; @@ -418,15 +418,15 @@ vows.describe('OAuth').addBatch({ } }, '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._createClient; + "It should be url encoded and the content type set to be x-www-form-urlencoded": function(oa) { + var op = oa._createClient; try { var callbackCalled= false; - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + 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; + write: function(data) { + callbackCalled = true; assert.equal(data, "foo=1%2C2%2C3&bar=1%2B2"); }, on: function() {}, @@ -434,10 +434,9 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.post("http://foo.com/blah", "token", "token_secret", {"foo":"1,2,3", "bar":"1+2"}); + var request = oa.post("http://foo.com/blah", "token", "token_secret", { "foo": "1,2,3", "bar": "1+2" }); assert.equal(callbackCalled, true); - } - finally { + } finally { oa._createClient= op; } } @@ -839,64 +838,58 @@ vows.describe('OAuth').addBatch({ var op= oa._createClient; var callbackCalled = false; try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { - return new DummyRequest( new DummyResponse(301) ); + oa._oa._createClient = function (port, hostname, method, path, headers, sshEnabled) { + return new DummyRequest(new DummyResponse(301)); }; - oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', {"scope": "foobar,1,2"}, null, null, function(error) { - // callback + 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; + callbackCalled = true; }); assert.equal(callbackCalled, true); - } - finally { - oa._createClient= op; + } 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._createClient; - var psr= oa._performSecureRequest; + 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"}; + var DummyResponse = function() { + if (responseCounter === 1) { + this.statusCode = 301; + this.headers = { location: "http://redirectto.com" }; responseCounter++; - } - else { - this.statusCode= 200; + } else { + this.statusCode = 200; } }; - DummyResponse.prototype= events.EventEmitter.prototype; + DummyResponse.prototype = events.EventEmitter.prototype; DummyResponse.prototype.setEncoding = function() {}; try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { - return new DummyRequest( new DummyResponse() ); + oa._oa._createClient = function(port, hostname, method, path, headers, sshEnabled) { + return new DummyRequest(new DummyResponse()); }; - oa._performSecureRequest= function( oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback ) { - if( responseCounter == 1 ) { + 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 { + } else { assert.equal(url, "http://redirectto.com"); } - return psr.call(oa, oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback ); + 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 + oa._oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', { "scope": "foobar,1,2" }, null, null, function() { assert.equal(responseCounter, 2); - callbackCalled= true; + callbackCalled = true; }); - assert.equal(callbackCalled, true) - } - finally { - oa._createClient= op; - oa._performSecureRequest= psr; + assert.equal(callbackCalled, true); + } finally { + oa._oa._createClient = op; + oa._oa._performSecureRequest = psr; } } }, @@ -907,22 +900,20 @@ vows.describe('OAuth').addBatch({ var DummyResponse =function() { this.statusCode= 301; this.headers= {location:"http://redirectto.com"}; - } + }; DummyResponse.prototype= events.EventEmitter.prototype; - DummyResponse.prototype.setEncoding= function() {} + DummyResponse.prototype.setEncoding= function() {}; try { oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { return new DummyRequest( new DummyResponse() ); - } - oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', {"scope": "foobar,1,2"}, null, null, function(res, data, response) { - // callback + }; + 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._createClient= op; - oa.setClientOptions({followRedirects:true}); + } finally { + oa._createClient = op; + oa.setClientOptions({ followRedirects: true }); } } } @@ -930,135 +921,143 @@ vows.describe('OAuth').addBatch({ '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._createClient; - var psr= oa._performSecureRequest; + 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"}; + var DummyResponse = function() { + if( responseCounter === 1 ){ + this.statusCode = 302; + this.headers = { location: "http://redirectto.com" }; responseCounter++; } else { - this.statusCode= 200; + this.statusCode = 200; } }; - DummyResponse.prototype= events.EventEmitter.prototype; + DummyResponse.prototype = events.EventEmitter.prototype; DummyResponse.prototype.setEncoding = function() {}; try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { - return new DummyRequest( new DummyResponse() ); - } - oa._performSecureRequest= function( oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback ) { - if( responseCounter == 1 ) { + 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, oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback ) - } + 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() { + 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._createClient= op; - oa._performSecureRequest= psr; + } 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; + '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._createClient = function(port, hostname, method, path, headers, sshEnabled ) { + + oa._oa._createClient = function(port, hostname, method, path, headers, sshEnabled ) { return new DummyRequest(new DummyResponse(302)); }; - oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', {"scope": "foobar,1,2"}, null, null, function(error) { - // callback + 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._createClient= op; + + } 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._createClient; - var psr= oa._performSecureRequest; + '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"}; + + if (responseCounter === 1) { + this.statusCode = 302; + this.headers = { + location: 'http://redirectto.com' + }; responseCounter++; } else { - this.statusCode= 200; + this.statusCode = 200; } + }; - DummyResponse.prototype= events.EventEmitter.prototype; + DummyResponse.prototype = events.EventEmitter.prototype; DummyResponse.prototype.setEncoding = function() {}; try { - oa._createClient = function(port, hostname, method, path, headers, sshEnabled) { + + oa._oa._createClient = function(port, hostname, method, path, headers, sshEnabled) { return new DummyRequest(new DummyResponse()); }; - 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"); + 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"); + assert.equal(url, 'http://redirectto.com'); } - return psr.call(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() { + 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._createClient= op; - oa._performSecureRequest= psr; + + } 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._createClient; + '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"}; + var DummyResponse = function() { + this.statusCode = 302; + this.headers = { + location: 'http://redirectto.com' + }; }; - DummyResponse.prototype= events.EventEmitter.prototype; - DummyResponse.prototype.setEncoding= function() {}; + DummyResponse.prototype = events.EventEmitter.prototype; + DummyResponse.prototype.setEncoding = function() {}; try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { - return new DummyRequest( new DummyResponse() ); + oa._oa._createClient= function(port, hostname, method, path, headers, sshEnabled) { + return new DummyRequest(new DummyResponse()); }; - oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', {"scope": "foobar,1,2"}, null, null, function(res, data, response) { + 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}); + } finally { + oa._createClient = op; + oa.setClientOptions({ followRedirects: true }); } } } From 6f0970059cd31dfadd8c63246b00dc76e4dc23c7 Mon Sep 17 00:00:00 2001 From: Oleg Zdornyy Date: Sun, 3 Apr 2016 02:51:34 -0400 Subject: [PATCH 15/90] Working OAuth 1.0 example + promisifyAll given multiargs:true --- examples/promise-twitter-example.js | 106 ++++++++++++++++++++++++++++ lib/oauth-promise.js | 2 +- 2 files changed, 107 insertions(+), 1 deletion(-) create mode 100644 examples/promise-twitter-example.js diff --git a/examples/promise-twitter-example.js b/examples/promise-twitter-example.js new file mode 100644 index 00000000..d677c093 --- /dev/null +++ b/examples/promise-twitter-example.js @@ -0,0 +1,106 @@ +/* +* +* 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'; + +var reqTokenSecrets = {}; // Hash that contains the req_token:req_token_secret key vals + + +/* + 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/lib/oauth-promise.js b/lib/oauth-promise.js index 1904e45a..c4527f6b 100644 --- a/lib/oauth-promise.js +++ b/lib/oauth-promise.js @@ -3,7 +3,7 @@ var _OAuth = require('./oauth').OAuth; 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); + this._oa.prototype = Promise.promisifyAll(_OAuth.prototype, { multiArgs: true }); }; // Promisifed public API for OAuth From d59643f7e78be1b2f466b99b984e57b9cb892549 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Sun, 3 Apr 2016 02:55:26 -0400 Subject: [PATCH 16/90] multiArgs for oauth2-promises "Setting multiArgs to true means the resulting promise will always fulfill with an array of the callback's success value(s). This is needed because promises only support a single success value while some callback API's have multiple success value. The default is to ignore all but the first success value of a callback function." explanation is here: http://bluebirdjs.com/docs/api/promise.promisifyall.html#option-multiargs fixes #10 --- lib/oauth2-promise.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/oauth2-promise.js b/lib/oauth2-promise.js index da949fcd..7e3e61be 100644 --- a/lib/oauth2-promise.js +++ b/lib/oauth2-promise.js @@ -3,7 +3,7 @@ var _OAuth2 = require('./oauth2').OAuth2; 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); + this._oa.prototype = Promise.promisifyAll(_OAuth2.prototype, { multiArgs: true }); }; // Promisfied public API for OAuth2 From f938c91262579ef4c419cafd1238e0586d06f5e5 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Sun, 3 Apr 2016 03:24:23 -0400 Subject: [PATCH 17/90] another example of twitter oauth promises related to #4 --- examples/twitter-oauth-promises.js | 40 ++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 examples/twitter-oauth-promises.js diff --git a/examples/twitter-oauth-promises.js b/examples/twitter-oauth-promises.js new file mode 100644 index 00000000..8dddf9ef --- /dev/null +++ b/examples/twitter-oauth-promises.js @@ -0,0 +1,40 @@ +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(err) { + console.log('Error: ' + error); +}); From 32c187509be0860156d69f03f2453448c2a73948 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 13:39:33 -0400 Subject: [PATCH 18/90] Fixed broken OAuth Promises test Needed to use the _oa raw client instead of the oa client which is the promisfied wrapper. The test is "and followRedirect is false it should not perform the secure request with the new location". related to #4 --- tests/oauthpromise-tests.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/oauthpromise-tests.js b/tests/oauthpromise-tests.js index 6ab52a1b..37eb9d9f 100644 --- a/tests/oauthpromise-tests.js +++ b/tests/oauthpromise-tests.js @@ -895,7 +895,7 @@ vows.describe('OAuth').addBatch({ }, 'and followRedirect is false' : { 'it should not perform the secure request with the new location' : function(oa) { - var op= oa._createClient; + var op = oa._oa._createClient; oa.setClientOptions({ followRedirects: false }); var DummyResponse =function() { this.statusCode= 301; @@ -905,14 +905,14 @@ vows.describe('OAuth').addBatch({ DummyResponse.prototype.setEncoding= function() {}; try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { return new DummyRequest( new DummyResponse() ); + oa._oa._createClient = function(port, hostname, method, path, headers, sshEnabled) { }; - oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', { "scope": "foobar,1,2" }, null, null, function(res, data, response) { + 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._createClient = op; + oa._oa._createClient = op; oa.setClientOptions({ followRedirects: true }); } } From 7549aed04acb915591216fb2ece3e6c532320480 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 13:40:53 -0400 Subject: [PATCH 19/90] cleanup of a test #8 --- tests/oauthpromise-tests.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/oauthpromise-tests.js b/tests/oauthpromise-tests.js index 37eb9d9f..63d827f0 100644 --- a/tests/oauthpromise-tests.js +++ b/tests/oauthpromise-tests.js @@ -893,20 +893,20 @@ vows.describe('OAuth').addBatch({ } } }, - 'and followRedirect is false' : { - 'it should not perform the secure request with the new location' : function(oa) { + '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"}; + var DummyResponse = function() { + this.statusCode = 301; + this.headers = { location: 'http://redirectto.com' }; }; - DummyResponse.prototype= events.EventEmitter.prototype; - DummyResponse.prototype.setEncoding= function() {}; + DummyResponse.prototype = events.EventEmitter.prototype; + DummyResponse.prototype.setEncoding = function() {}; try { - return new DummyRequest( new DummyResponse() ); 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); From 6944fd1521ffdec9c9baa389f49b494a1cf0234b Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 13:44:33 -0400 Subject: [PATCH 20/90] Moved bluebird to optionalDependencies instead of being a required dependency, related to #4 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 2f10f01b..9a4b397e 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,7 @@ "url": "https://github.com/omouse/node-oauth-libre/raw/master/LICENSE.mit" } ], - "dependencies": { + "optionalDependencies": { "bluebird": "^3.3.4" } } From 68ad4a21468fd0940e9eb64715b910129da7a1b5 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 13:48:41 -0400 Subject: [PATCH 21/90] signUrl is delegated instead of promisified The function returns a string value immediately and is not asynchronous, this fixes three broken unit tests in oauthpromise-tests.js. related to #4 --- lib/oauth-promise.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/oauth-promise.js b/lib/oauth-promise.js index c4527f6b..3ba8acee 100644 --- a/lib/oauth-promise.js +++ b/lib/oauth-promise.js @@ -13,8 +13,7 @@ var delegatedPromiseMethods = [ 'getOAuthAccessToken', 'getOAuthRequestToken', 'post', - 'put', - 'signUrl' + 'put' ]; delegatedPromiseMethods.forEach(asyncDelegate); @@ -24,6 +23,7 @@ var delegatedMethods = [ 'authHeader', 'getProtectedResource', 'setClientOptions', + 'signUrl', // Required for testing '_buildAuthorizationHeaders', From ac96d9f53574eb766db46d227ece337ceba1a6e4 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 13:50:13 -0400 Subject: [PATCH 22/90] Fixed more broken tests, #4 --- tests/oauthpromise-tests.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/oauthpromise-tests.js b/tests/oauthpromise-tests.js index 63d827f0..6f8148ab 100644 --- a/tests/oauthpromise-tests.js +++ b/tests/oauthpromise-tests.js @@ -158,8 +158,8 @@ vows.describe('OAuth').addBatch({ 'When signing a url': { 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._oa._getTimestamp= function(){ return "1272399856"; }; + oa._oa._getNonce= function(){ return "ybHPeOEkAUJ3k2wJT9Xb43MjtSgTvKqp"; }; return oa; }, 'Provide a valid signature when no token present': function(oa) { From 20d89a9433be562701996189156ea6e2da5677f7 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 14:46:25 -0400 Subject: [PATCH 23/90] All tests for OAuth Promise are passing, #4 --- tests/oauthpromise-tests.js | 266 +++++++++++++++--------------------- 1 file changed, 112 insertions(+), 154 deletions(-) diff --git a/tests/oauthpromise-tests.js b/tests/oauthpromise-tests.js index 6f8148ab..47d2e6fb 100644 --- a/tests/oauthpromise-tests.js +++ b/tests/oauthpromise-tests.js @@ -31,7 +31,7 @@ var RsaPublicKey = "-----BEGIN PUBLIC KEY-----\n" + "yLOfY8XZvnFkGjipvQIDAQAB\n" + "-----END PUBLIC KEY-----"; -vows.describe('OAuth').addBatch({ +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) { @@ -219,15 +219,15 @@ vows.describe('OAuth').addBatch({ 'When get authorization header' : { 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._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._oauthParameterSeperator= ", "; + 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"'); } }, @@ -311,9 +311,9 @@ vows.describe('OAuth').addBatch({ '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._createClient; + var op= oa._oa._createClient; try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { return { write: function(post_body){ post_body_written= true; @@ -321,11 +321,11 @@ vows.describe('OAuth').addBatch({ } }; }; - oa._performSecureRequest("token", "token_secret", 'POST', 'http://foo.com/protected_resource', {"scope": "foobar,1,2"}); + oa._oa._performSecureRequest("token", "token_secret", 'POST', 'http://foo.com/protected_resource', {"scope": "foobar,1,2"}); assert.equal(post_body_written, true); } finally { - oa._createClient= op; + oa._oa._createClient= op; } } } @@ -337,42 +337,17 @@ vows.describe('OAuth').addBatch({ "1.0A", "http://foo.com/callback", "HMAC-SHA1"), 'POST' : { 'if no callback is passed' : { - 'it should return a request object': function(oa) { - var request= oa.post("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain"); - assert.isObject(request); - assert.equal(request.method, "POST"); - request.end(); - } - }, - '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._createClient; - try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { - return { - write: function(){}, - on: function() {}, - end: function() { - callbackCalled= true; - } - }; - }; - var request= oa.post("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain", function(e,d){}); - assert.equal(callbackCalled, true); - assert.isUndefined(request); - } - finally { - oa._createClient= op; - } + '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._createClient; + var op= oa._oa._createClient; try { var callbackCalled= false; - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { assert.equal(headers["Content-Type"], "image/jpeg"); return { write: function(data){ @@ -384,20 +359,21 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.post("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40]), "image/jpeg"); - assert.equal(callbackCalled, true); + 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._createClient= op; + 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._createClient; + var op= oa._oa._createClient; try { var callbackCalled= false; - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { assert.equal(headers["Content-Type"], "application/x-www-form-urlencoded"); return { write: function(data){ @@ -409,20 +385,21 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.post("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40])); - assert.equal(callbackCalled, true); + oa.post("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40])).nodeify(function() { + assert.equal(callbackCalled, true); + }); } finally { - oa._createClient= op; + 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._createClient; + var op = oa._oa._createClient; try { var callbackCalled= false; - oa._createClient= function(port, hostname, method, path, headers, sshEnabled) { + oa._oa._createClient= function(port, hostname, method, path, headers, sshEnabled) { assert.equal(headers["Content-Type"], "application/x-www-form-urlencoded"); return { write: function(data) { @@ -434,10 +411,11 @@ vows.describe('OAuth').addBatch({ } }; }; - var request = oa.post("http://foo.com/blah", "token", "token_secret", { "foo": "1,2,3", "bar": "1+2" }); - assert.equal(callbackCalled, true); + oa.post("http://foo.com/blah", "token", "token_secret", { "foo": "1,2,3", "bar": "1+2" }).nodeify(function() { + assert.equal(callbackCalled, true); + }); } finally { - oa._createClient= op; + oa._oa._createClient= op; } } }, @@ -449,10 +427,10 @@ vows.describe('OAuth').addBatch({ 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._createClient; + var op= oa._oa._createClient; try { var callbackCalled= false; - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { assert.equal(headers["Content-length"], testStringBytesLength); return { write: function(data){ @@ -464,20 +442,21 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.post("http://foo.com/blah", "token", "token_secret", "Tôi yêu node"); - assert.equal(callbackCalled, true); + oa.post("http://foo.com/blah", "token", "token_secret", "Tôi yêu node").nodeify(function() { + assert.equal(callbackCalled, true); + }); } finally { - oa._createClient= op; + 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._createClient; + var op= oa._oa._createClient; try { var callbackCalled= false; - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + 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 { @@ -490,20 +469,21 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.post("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2"); - assert.equal(callbackCalled, true); + oa.post("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2").nodeify(function() { + assert.equal(callbackCalled, true); + }); } finally { - oa._createClient= op; + 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._createClient; + var op= oa._oa._createClient; try { var callbackCalled= false; - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { assert.equal(headers["Content-Type"], "unicorn/encoded"); assert.equal(headers["Content-length"], 23); return { @@ -516,11 +496,12 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.post("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2", "unicorn/encoded"); - assert.equal(callbackCalled, true); + 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._createClient= op; + oa._oa._createClient= op; } } } @@ -529,18 +510,16 @@ vows.describe('OAuth').addBatch({ 'GET' : { 'if no callback is passed' : { 'it should return a request object': function(oa) { - var request= oa.get("http://foo.com/blah", "token", "token_secret"); - assert.isObject(request); - assert.equal(request.method, "GET"); - request.end(); + 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._createClient; + var op= oa._oa._createClient; try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { return { on: function() {}, end: function() { @@ -548,31 +527,29 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.get("http://foo.com/blah", "token", "token_secret", function(e,d) {}); - assert.equal(callbackCalled, true); - assert.isUndefined(request); + oa.get("http://foo.com/blah", "token", "token_secret", function(e,d) {}).nodeify(function() { + assert.equal(callbackCalled, true); + }); } finally { - oa._createClient= op; + oa._oa._createClient= op; } } }, }, 'PUT' : { 'if no callback is passed' : { - 'it should return a request object': function(oa) { - var request= oa.put("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain"); - assert.isObject(request); - assert.equal(request.method, "PUT"); - request.end(); + '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._createClient; + var op= oa._oa._createClient; try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { return { on: function() {}, write: function(data) { @@ -583,21 +560,21 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.put("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain", function(e,d){}); - assert.equal(callbackCalled, 2); - assert.isUndefined(request); + oa.put("http://foo.com/blah", "token", "token_secret", "BLAH", "text/plain", function(e,d){}).nodeify(function() { + assert.equal(callbackCalled, 2); + }); } finally { - oa._createClient= op; + 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._createClient; + var op= oa._oa._createClient; try { var callbackCalled= false; - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { assert.equal(headers["Content-Type"], "image/jpeg"); return { write: function(data){ @@ -609,20 +586,21 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.put("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40]), "image/jpeg"); - assert.equal(callbackCalled, true); + 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._createClient= op; + 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._createClient; + var op= oa._oa._createClient; try { var callbackCalled= false; - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { assert.equal(headers["Content-Type"], "application/x-www-form-urlencoded"); return { write: function(data){ @@ -634,20 +612,21 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.put("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40])); - assert.equal(callbackCalled, true); + oa.put("http://foo.com/blah", "token", "token_secret", new Buffer([10,20,30,40])).nodeify(function() { + assert.equal(callbackCalled, true); + }); } finally { - oa._createClient= op; + 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._createClient; + var op= oa._oa._createClient; try { var callbackCalled= false; - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { assert.equal(headers["Content-Type"], "application/x-www-form-urlencoded"); return { write: function(data) { @@ -656,21 +635,22 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.put("http://foo.com/blah", "token", "token_secret", {"foo":"1,2,3", "bar":"1+2"}); - assert.equal(callbackCalled, true); + oa.put("http://foo.com/blah", "token", "token_secret", {"foo":"1,2,3", "bar":"1+2"}).nodeify(function() { + assert.equal(callbackCalled, true); + }); } finally { - oa._createClient= op; + 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._createClient; + var op= oa._oa._createClient; try { var callbackCalled= false; - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + 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 { @@ -680,20 +660,21 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.put("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2"); - assert.equal(callbackCalled, true); + oa.put("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2").nodeify(function() { + assert.equal(callbackCalled, true); + }); } finally { - oa._createClient= op; + 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._createClient; + var op= oa._oa._createClient; try { var callbackCalled= false; - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { assert.equal(headers["Content-Type"], "unicorn/encoded"); assert.equal(headers["Content-length"], 23); return { @@ -703,11 +684,12 @@ vows.describe('OAuth').addBatch({ } }; }; - var request= oa.put("http://foo.com/blah", "token", "token_secret", "foo=1%2C2%2C3&bar=1%2B2", "unicorn/encoded"); - assert.equal(callbackCalled, true); + 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._createClient= op; + oa._oa._createClient= op; } } } @@ -715,46 +697,22 @@ vows.describe('OAuth').addBatch({ }, 'DELETE' : { 'if no callback is passed' : { - 'it should return a request object': function(oa) { - var request= oa.delete("http://foo.com/blah", "token", "token_secret"); - assert.isObject(request); - assert.equal(request.method, "DELETE"); - request.end(); - } - }, - '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._createClient; - try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { - return { - on: function() {}, - end: function() { - callbackCalled= true; - } - }; - }; - var request= oa.delete("http://foo.com/blah", "token", "token_secret", function(e,d) {}); - assert.equal(callbackCalled, true); - assert.isUndefined(request); - } - finally { - oa._createClient= op; - } + '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._createClient; + var op= oa._oa._createClient; var callbackCalled = false; try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { return new DummyRequest( new DummyResponse(200) ); }; - oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', {"scope": "foobar,1,2"}, null, null, function(error) { + 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); @@ -762,19 +720,19 @@ vows.describe('OAuth').addBatch({ assert.equal(callbackCalled, true); } finally { - oa._createClient= op; + oa._oa._createClient= op; } } }, 'and a 210 response code is received' : { 'it should callback successfully' : function(oa) { - var op= oa._createClient; + var op= oa._oa._createClient; var callbackCalled = false; try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { return new DummyRequest( new DummyResponse(210) ); }; - oa._performSecureRequest("token", "token_secret", 'POST', 'http://originalurl.com', {"scope": "foobar,1,2"}, null, null, function(error) { + 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); @@ -782,15 +740,15 @@ vows.describe('OAuth').addBatch({ assert.equal(callbackCalled, true); } finally { - oa._createClient= op; + 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._createClient; - var psr= oa._performSecureRequest; + var op= oa._oa._createClient; + var psr= oa._oa._performSecureRequest; var responseCounter = 1; var callbackCalled = false; var DummyResponse =function() { @@ -807,17 +765,17 @@ vows.describe('OAuth').addBatch({ DummyResponse.prototype.setEncoding= function() {}; try { - oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { + oa._oa._createClient= function( port, hostname, method, path, headers, sshEnabled ) { return new DummyRequest( new DummyResponse() ); }; - oa._performSecureRequest= function( oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback ) { + 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, oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback ); + 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() { @@ -828,8 +786,8 @@ vows.describe('OAuth').addBatch({ assert.equal(callbackCalled, true); } finally { - oa._createClient= op; - oa._performSecureRequest= psr; + oa._oa._createClient= op; + oa._oa._performSecureRequest= psr; } } }, From 38de8690abf4e84886d102bd6833e3e483bdba59 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 15:21:59 -0400 Subject: [PATCH 24/90] OAuth2 Promise get method returns data, #4 When using the promise, it would pass the response and an IncomingMessage object. We only need to pass the data object from the response. --- lib/oauth2-promise.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/oauth2-promise.js b/lib/oauth2-promise.js index 7e3e61be..2851ff08 100644 --- a/lib/oauth2-promise.js +++ b/lib/oauth2-promise.js @@ -12,7 +12,9 @@ OAuth2.prototype.getOAuthAccessToken = function() { }; OAuth2.prototype.get = function() { - return this._oa.getAsync.apply(this._oa, arguments); + return this._oa.getAsync.apply(this._oa, arguments).then(function(res) { + return res[0]; + }); }; // delegates PromiseOAuth2.methodName to OAuth2.methodName From 67dc8818564455a6bb04916442f324015e0ba4a2 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 15:23:08 -0400 Subject: [PATCH 25/90] github oauth2 example using promises, #4 --- examples/github-oauth2.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 examples/github-oauth2.js diff --git a/examples/github-oauth2.js b/examples/github-oauth2.js new file mode 100644 index 00000000..e1623c4c --- /dev/null +++ b/examples/github-oauth2.js @@ -0,0 +1,34 @@ +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; + +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); +} From 3441d3f3247164877b7852907ad49e25c452a667 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 15:27:13 -0400 Subject: [PATCH 26/90] example of using oauth2 promises in readme #4 --- Readme.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/Readme.md b/Readme.md index c150bb76..be126125 100644 --- a/Readme.md +++ b/Readme.md @@ -22,6 +22,55 @@ If you go to the original project and modify the code there, your changes will b To run examples/tests install Mocha `$ npm install -g mocha` and run `$ mocha you-file-name.js`: +## Using Promises + +Using promises is *optional*. + +Install the bluebird promises library: + + npm install bluebird + +An example of using oauth-libre with Promises: + +``` +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); +} +``` + +Note that in the first line you must explicitly import OAuth2 with promises. + ## OAuth1.0 ```javascript From df76c2452b29aa95acaee0c3698678f3ae8eb59c Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 16:41:25 -0400 Subject: [PATCH 27/90] Added copyright and license notices closes #3 --- examples/express-gdata/server.js | 19 +++++++++++++++++++ examples/github-example.js | 19 +++++++++++++++++++ examples/github-oauth2.js | 19 +++++++++++++++++++ examples/promise-twitter-example.js | 20 ++++++++++++++++++++ examples/term.ie.oauth-HMAC-SHA1.js | 19 +++++++++++++++++++ examples/twitter-example.js | 19 +++++++++++++++++++ examples/twitter-oauth-promises.js | 19 +++++++++++++++++++ index.js | 20 ++++++++++++++++++++ lib/_utils.js | 22 +++++++++++++++++++++- lib/oauth-promise.js | 19 +++++++++++++++++++ lib/oauth.js | 19 +++++++++++++++++++ lib/oauth2-promise.js | 19 +++++++++++++++++++ lib/oauth2.js | 19 +++++++++++++++++++ lib/sha1.js | 2 +- tests/oauth2promise-tests.js | 20 ++++++++++++++++++++ tests/oauth2tests.js | 19 +++++++++++++++++++ tests/oauthpromise-tests.js | 20 ++++++++++++++++++++ tests/oauthtests.js | 19 +++++++++++++++++++ tests/sha1tests.js | 21 ++++++++++++++++++++- tests/shared.js | 19 +++++++++++++++++++ 20 files changed, 369 insertions(+), 3 deletions(-) diff --git a/examples/express-gdata/server.js b/examples/express-gdata/server.js index 3c7bf7fe..ba0435eb 100644 --- a/examples/express-gdata/server.js +++ b/examples/express-gdata/server.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 express = require('express'), OAuth = require('oauth').OAuth, querystring = require('querystring'); diff --git a/examples/github-example.js b/examples/github-example.js index 1a388bdb..a10c7af4 100644 --- a/examples/github-example.js +++ b/examples/github-example.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 http = require('http'); var qs = require('querystring'); // var OAuth = require('oauth'), OAuth2 = OAuth.OAuth2; diff --git a/examples/github-oauth2.js b/examples/github-oauth2.js index e1623c4c..a7276b39 100644 --- a/examples/github-oauth2.js +++ b/examples/github-oauth2.js @@ -1,3 +1,22 @@ +/** + * 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 = ''; diff --git a/examples/promise-twitter-example.js b/examples/promise-twitter-example.js index d677c093..a5bf277a 100644 --- a/examples/promise-twitter-example.js +++ b/examples/promise-twitter-example.js @@ -1,3 +1,23 @@ +/** + * 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 diff --git a/examples/term.ie.oauth-HMAC-SHA1.js b/examples/term.ie.oauth-HMAC-SHA1.js index 91af05db..d96e55be 100644 --- a/examples/term.ie.oauth-HMAC-SHA1.js +++ b/examples/term.ie.oauth-HMAC-SHA1.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 util= require('util') var OAuth= require('../lib/oauth').OAuth; diff --git a/examples/twitter-example.js b/examples/twitter-example.js index 90b6adcb..e8290c76 100644 --- a/examples/twitter-example.js +++ b/examples/twitter-example.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 http = require('http'); var OAuth = require('../lib/oauth.js').OAuth; var nodeUrl = require('url'); diff --git a/examples/twitter-oauth-promises.js b/examples/twitter-oauth-promises.js index 8dddf9ef..657b5fdf 100644 --- a/examples/twitter-oauth-promises.js +++ b/examples/twitter-oauth-promises.js @@ -1,3 +1,22 @@ +/** + * 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 diff --git a/index.js b/index.js index 80be24bb..687dc8d9 100644 --- a/index.js +++ b/index.js @@ -1,3 +1,23 @@ +/** + * 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 . + */ + exports.OAuth = require("./lib/oauth").OAuth; exports.OAuthEcho = require("./lib/oauth").OAuthEcho; exports.OAuth2 = require("./lib/oauth2").OAuth2; diff --git a/lib/_utils.js b/lib/_utils.js index 69fc3009..ed7eba57 100644 --- a/lib/_utils.js +++ b/lib/_utils.js @@ -1,4 +1,24 @@ +/** + * 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 . + */ + + // 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 +} diff --git a/lib/oauth-promise.js b/lib/oauth-promise.js index 3ba8acee..3ce27955 100644 --- a/lib/oauth-promise.js +++ b/lib/oauth-promise.js @@ -1,3 +1,22 @@ +/** + * 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; diff --git a/lib/oauth.js b/lib/oauth.js index 50dccf99..2664215b 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'), diff --git a/lib/oauth2-promise.js b/lib/oauth2-promise.js index 2851ff08..89b5f014 100644 --- a/lib/oauth2-promise.js +++ b/lib/oauth2-promise.js @@ -1,3 +1,22 @@ +/** + * 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; diff --git a/lib/oauth2.js b/lib/oauth2.js index 94ed662c..b4802437 100644 --- a/lib/oauth2.js +++ b/lib/oauth2.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 querystring= require('querystring'), crypto= require('crypto'), https= require('https'), diff --git a/lib/sha1.js b/lib/sha1.js index d73277a6..c6589032 100644 --- a/lib/sha1.js +++ b/lib/sha1.js @@ -331,4 +331,4 @@ function bit_rol(num, cnt) exports.HMACSHA1= function(key, data) { return b64_hmac_sha1(key, data); -} \ No newline at end of file +} diff --git a/tests/oauth2promise-tests.js b/tests/oauth2promise-tests.js index 86e75009..39fde24a 100644 --- a/tests/oauth2promise-tests.js +++ b/tests/oauth2promise-tests.js @@ -1,3 +1,23 @@ +/** + * 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, diff --git a/tests/oauth2tests.js b/tests/oauth2tests.js index 134f85bc..09cad1ad 100644 --- a/tests/oauth2tests.js +++ b/tests/oauth2tests.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, diff --git a/tests/oauthpromise-tests.js b/tests/oauthpromise-tests.js index 47d2e6fb..b4f63a85 100644 --- a/tests/oauthpromise-tests.js +++ b/tests/oauthpromise-tests.js @@ -1,3 +1,23 @@ +/** + * 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, diff --git a/tests/oauthtests.js b/tests/oauthtests.js index d36bfed7..a1db6f9b 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, diff --git a/tests/sha1tests.js b/tests/sha1tests.js index 18ba0ae3..022119b5 100644 --- a/tests/sha1tests.js +++ b/tests/sha1tests.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'); @@ -10,4 +29,4 @@ vows.describe('SHA1 Hashing').addBatch({ "tR3+Ty81lMeYAr/Fid0kMTYa/WM="); } } -}).export(module); \ No newline at end of file +}).export(module); diff --git a/tests/shared.js b/tests/shared.js index 648539eb..9fbe7c9e 100644 --- a/tests/shared.js +++ b/tests/shared.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 events = require('events'); exports.DummyResponse = function(statusCode) { From 01fa956f196124abbc808731b836dfc8aafe0b4b Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 16:45:35 -0400 Subject: [PATCH 28/90] alphabetical order of contributors --- Readme.md | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/Readme.md b/Readme.md index ec7a8d03..176ae7eb 100644 --- a/Readme.md +++ b/Readme.md @@ -243,31 +243,31 @@ describe('OAuth2',function() { * 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) -# Contributors (In no particular order) +# Contributors (In first-name alphabetical order) +* AJ ONeal +* Andreas Knecht +* Andrew Martins - http://www.andrewmartens.com +* Brian Park - http://github.com/yaru22 +* 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/ +* 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 * Patrick Negri - http://github.com/pnegri +* Pieter Joost van de Sande - https://github.com/pjvds +* Raoul Millais +* 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 From 693426b7d6f8471212e588f0e146eed226dc2fce Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 16:46:35 -0400 Subject: [PATCH 29/90] added Rudolf and Oleg as contributors --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index 176ae7eb..06837a5d 100644 --- a/Readme.md +++ b/Readme.md @@ -263,9 +263,11 @@ describe('OAuth2',function() { * Luke Baker - http://github.com/lukebaker * Mark Wubben - http://equalmedia.com/ * 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 - http://neverfriday.com * Ryan LeFevre - http://meltingice.net * Tang Bo Hao - http://github.com/btspoony * Ted Goddard From c10a14c03f7fcc9ee0f8d76784eee4520e58f307 Mon Sep 17 00:00:00 2001 From: Alex Nuccio Date: Wed, 20 Apr 2016 16:51:46 -0400 Subject: [PATCH 30/90] added PATCH to conditions for adding a post_body to requests related to #11 --- lib/oauth2.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/oauth2.js b/lib/oauth2.js index b4802437..8e625dfb 100644 --- a/lib/oauth2.js +++ b/lib/oauth2.js @@ -167,7 +167,7 @@ exports.OAuth2.prototype._executeRequest= function( http_library, options, post_ callback(e); }); - if( (options.method == 'POST' || options.method == 'PUT') && post_body ) { + if( (options.method == 'POST' || options.method == 'PUT' || options.method == 'PATCH') && post_body ) { request.write(post_body); } request.end(); From c30298ebd51eed8375b5f5cc5fca582d22464abc Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 16:52:33 -0400 Subject: [PATCH 31/90] OAuth1 PATCH support, #11 --- lib/oauth.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/oauth.js b/lib/oauth.js index 2664215b..9539b8c3 100644 --- a/lib/oauth.js +++ b/lib/oauth.js @@ -358,7 +358,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") @@ -441,13 +441,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; From 0866d95cc3710eff74c7534de7d47d03002915bf Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 16:53:36 -0400 Subject: [PATCH 32/90] added contributor, #11 --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 06837a5d..0a4d8a2b 100644 --- a/Readme.md +++ b/Readme.md @@ -246,6 +246,7 @@ describe('OAuth2',function() { # 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 From 086e4c593a31051b0c2f7b61f69cfadabde43d04 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 17:08:51 -0400 Subject: [PATCH 33/90] removed old instructions for running examples, #2 --- Readme.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/Readme.md b/Readme.md index 0a4d8a2b..af9741a2 100644 --- a/Readme.md +++ b/Readme.md @@ -24,8 +24,6 @@ the GPLv3 bits if they want to use them in a proprietary project # Examples -To run examples/tests install Mocha `$ npm install -g mocha` and run `$ mocha you-file-name.js`: - ## Using Promises Using promises is *optional*. From a0a396c32d2dd65cd3b25237ce3d9f148e36bf42 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 17:52:52 -0400 Subject: [PATCH 34/90] instructions for running web-based github example related to #2 --- Readme.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Readme.md b/Readme.md index af9741a2..55d4b03f 100644 --- a/Readme.md +++ b/Readme.md @@ -162,6 +162,24 @@ describe('OAuth2',function() { }); ``` +## 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` + +### 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: ..." # Change History * 0.9.14 - OAuth2: Extend 'successful' token responses to include anything in the 2xx range. From 4102234c97d6e5f5c04deaa008a366fd180c9074 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 18:36:50 -0400 Subject: [PATCH 35/90] optional dependencies for google auth example Dependencies: * body-parser * express * express-session * morgan related to #2 --- package.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 9a4b397e..2251afcc 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,10 @@ } ], "optionalDependencies": { - "bluebird": "^3.3.4" + "body-parser": "^1.15.0", + "bluebird": "^3.3.4", + "express": "^4.13.4", + "express-session": "^1.13.0", + "morgan": "^1.7.0" } } From 7ffc57dbe9003e1f14e137709742ae4714ff9c8d Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 20 Apr 2016 18:39:26 -0400 Subject: [PATCH 36/90] in progress google auth fixup, #2 --- Readme.md | 16 ++ examples/express-gdata/server.js | 268 ++++++++++++++----------------- 2 files changed, 140 insertions(+), 144 deletions(-) diff --git a/Readme.md b/Readme.md index 55d4b03f..ed154dda 100644 --- a/Readme.md +++ b/Readme.md @@ -167,6 +167,8 @@ describe('OAuth2',function() { Included with the source code are examples of using a web-based interface to login with: * Github: `examples/github-example.js` +* Google: `examples/express-gdata/server.js` +* Twitter: `examples/twitter-example.js` ### Example: Authentication with Github @@ -180,6 +182,20 @@ Included with the source code are examples of using a web-based interface to log 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 Google + +1. Create Google Account +1. Create credentials in Google APIs Developer Console +1. Create OAuth Client ID, Web Application +1. Set the Authorized redirect URIs to `http://localhost:8080/google_cb` +1. Install express and its dependencies: `npm install express morgan body-parser express-session` +1. Run the web server: `node examples/express-gdata/server.js` +1. Open the website: `http://localhost:8080` +1. + +### Example: Authentication with Twitter + # Change History * 0.9.14 - OAuth2: Extend 'successful' token responses to include anything in the 2xx range. diff --git a/examples/express-gdata/server.js b/examples/express-gdata/server.js index ba0435eb..44e6e2f9 100644 --- a/examples/express-gdata/server.js +++ b/examples/express-gdata/server.js @@ -2,6 +2,7 @@ * 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 @@ -17,171 +18,150 @@ * along with this program. If not, see . */ -var express = require('express'), - OAuth = require('oauth').OAuth, - querystring = require('querystring'); +var express = require('express'); +var logger = require('morgan'); +var bodyParser = require('body-parser'); +var session = require('express-session'); +var querystring = require('querystring'); +var OAuth = require('../../index').OAuth; // 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" +var app = express(); +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: true })); +app.use(session({ + resave: true, + saveUninitialized: true, + secret: "skjghskdjfhbqigohqdiouk" })); // Home Page app.get('/', function(req, res){ - if(!req.session.oauth_access_token) { - res.redirect("/google_login"); - } - else { - res.redirect("/google_contacts"); - } + 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); - } - }) + + var getRequestTokenUrl = "https://accounts.google.com/o/oauth2/v2/auth"; + + // GData specifid: scopes that wa want access to + var gdataScopes = [ + querystring.escape("https://www.googleapis.com/auth/calendar") + ]; + + var url = getRequestTokenUrl + "?scope=" + gdataScopes.join('+'); + var callbackUrl = "http://localhost:8080/google_cb"; + if (req.params['action'] && req.params['action'] != "") { + callbackUrl += "?action=" + querystring.escape(req.param['action']); + } + var oa = new OAuth( + url, + "https://www.google.com/accounts/OAuthGetAccessToken", + "anonymous", + "anonymous", + "1.0", + callbackUrl, + "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"); - } - - }); - + + // 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(); + 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 } - }); - }); - + 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"); +app.listen(8080); +console.log("listening on http://localhost:8080"); From 294b050247d8991a73a64d9332403b74465c67ce Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Fri, 27 May 2016 10:00:48 -0400 Subject: [PATCH 37/90] updated package.json and readme for 0.9.15-alpha this is for publishing to NPM --- In the future I would prefer to not rely on the centralized repo of NPM and provide a git url to download the package --- Readme.md | 3 +-- package.json | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Readme.md b/Readme.md index 55d4b03f..8d8761bc 100644 --- a/Readme.md +++ b/Readme.md @@ -19,8 +19,7 @@ the GPLv3 bits if they want to use them in a proprietary project # Installation - npm install oauth-libre - + npm install oauth-libre@0.9.15-alpha # Examples diff --git a/package.json b/package.json index 2251afcc..9f80fa90 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "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.", - "version": "0.9.15", + "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.15-alpha", "directories": { "lib": "./lib" }, From bf657e80cfea17a26bc7527a29b897f25a9efe2d Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Fri, 27 May 2016 10:13:49 -0400 Subject: [PATCH 38/90] revert, the tag name is latest not 0.9.15-alpha fuck NPM --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 8d8761bc..2a666b8f 100644 --- a/Readme.md +++ b/Readme.md @@ -19,7 +19,7 @@ the GPLv3 bits if they want to use them in a proprietary project # Installation - npm install oauth-libre@0.9.15-alpha + npm install oauth-libre # Examples From 244d7594e116d92d8002e09901346d763700d476 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 29 Jun 2016 13:55:17 -0400 Subject: [PATCH 39/90] removed Google OAuth server example #2 --- Readme.md | 12 +- examples/express-gdata/server.js | 167 ------------------ .../express-gdata/views/google_calendars.ejs | 21 --- .../express-gdata/views/google_contacts.ejs | 24 --- examples/express-gdata/views/layout.ejs | 9 - 5 files changed, 3 insertions(+), 230 deletions(-) delete mode 100644 examples/express-gdata/server.js delete mode 100644 examples/express-gdata/views/google_calendars.ejs delete mode 100644 examples/express-gdata/views/google_contacts.ejs delete mode 100644 examples/express-gdata/views/layout.ejs diff --git a/Readme.md b/Readme.md index ed154dda..fae6baeb 100644 --- a/Readme.md +++ b/Readme.md @@ -167,9 +167,10 @@ describe('OAuth2',function() { Included with the source code are examples of using a web-based interface to login with: * Github: `examples/github-example.js` -* Google: `examples/express-gdata/server.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 @@ -185,14 +186,7 @@ Included with the source code are examples of using a web-based interface to log ### Example: Authentication with Google -1. Create Google Account -1. Create credentials in Google APIs Developer Console -1. Create OAuth Client ID, Web Application -1. Set the Authorized redirect URIs to `http://localhost:8080/google_cb` -1. Install express and its dependencies: `npm install express morgan body-parser express-session` -1. Run the web server: `node examples/express-gdata/server.js` -1. Open the website: `http://localhost:8080` -1. +*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 diff --git a/examples/express-gdata/server.js b/examples/express-gdata/server.js deleted file mode 100644 index 44e6e2f9..00000000 --- a/examples/express-gdata/server.js +++ /dev/null @@ -1,167 +0,0 @@ -/** - * 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 express = require('express'); -var logger = require('morgan'); -var bodyParser = require('body-parser'); -var session = require('express-session'); -var querystring = require('querystring'); -var OAuth = require('../../index').OAuth; - -// Setup the Express.js server -var app = express(); -app.use(logger('dev')); -app.use(bodyParser.json()); -app.use(bodyParser.urlencoded({ extended: true })); -app.use(session({ - resave: true, - saveUninitialized: true, - 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://accounts.google.com/o/oauth2/v2/auth"; - - // GData specifid: scopes that wa want access to - var gdataScopes = [ - querystring.escape("https://www.googleapis.com/auth/calendar") - ]; - - var url = getRequestTokenUrl + "?scope=" + gdataScopes.join('+'); - var callbackUrl = "http://localhost:8080/google_cb"; - if (req.params['action'] && req.params['action'] != "") { - callbackUrl += "?action=" + querystring.escape(req.param['action']); - } - var oa = new OAuth( - url, - "https://www.google.com/accounts/OAuthGetAccessToken", - "anonymous", - "anonymous", - "1.0", - callbackUrl, - "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_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(8080); -console.log("listening on http://localhost:8080"); 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 From 74bfb5585614f8157970491e3a31ab97e50de353 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 29 Jun 2016 14:38:56 -0400 Subject: [PATCH 40/90] twitter server example updated, #2 --- Readme.md | 10 +++ examples/twitter-example.js | 139 ++++++++++++++++++++---------------- 2 files changed, 86 insertions(+), 63 deletions(-) diff --git a/Readme.md b/Readme.md index fae6baeb..026834f3 100644 --- a/Readme.md +++ b/Readme.md @@ -190,6 +190,16 @@ The Google example was removed due to the need for a custom Google-specific OAut ### 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.14 - OAuth2: Extend 'successful' token responses to include anything in the 2xx range. diff --git a/examples/twitter-example.js b/examples/twitter-example.js index e8290c76..e8b695a1 100644 --- a/examples/twitter-example.js +++ b/examples/twitter-example.js @@ -22,73 +22,86 @@ var OAuth = require('../lib/oauth.js').OAuth; var nodeUrl = require('url'); var clientID = ''; var clientSecret = ''; -var callbackURL = ''; +var callbackURL = 'http://localhost:8080/callback'; -oa = new OAuth( - 'https://api.twitter.com/oauth/request_token', - 'https://api.twitter.com/oauth/access_token', - clientID, - clientSecret, - '1.0', - callbackURL, - 'HMAC-SHA1' +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' ); 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; - } + 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) - res.end(JSON.stringify(error)); - return; - } - try { - console.log(JSON.parse(twitterResponseData)); - } catch (parseError) { - console.log(parseError); - } - console.log(twitterResponseData); - response.end(twitterResponseData); - }); - }; - - oa.getOAuthAccessToken(urlObj.query.oauth_token, oAuthTokenSecret, - urlObj.query.oauth_verifier, - getOAuthRequestTokenCallback); - - } + 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); From 8161fd5647eb95d1efe91abe87a5b5f1eefdf28d Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 29 Jun 2016 15:23:07 -0400 Subject: [PATCH 41/90] 0.9.15 beta release Readme.md: Updated change history with 0.9.15 details package.json: updated version to 0.9.15-beta --- Readme.md | 5 +++++ package.json | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index faea8286..de3bc043 100644 --- a/Readme.md +++ b/Readme.md @@ -200,6 +200,11 @@ The Google example was removed due to the need for a custom Google-specific OAut 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.15 + - Promises for OAuth1 and OAuth2 with multiArgs + - PATCH support for OAuth1 and OAuth2 + - GPLv3+ licensing + - Code examples updated, tested and working * 0.9.14 - OAuth2: Extend 'successful' token responses to include anything in the 2xx range. * 0.9.13 diff --git a/package.json b/package.json index 9f80fa90..347c6dfa 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "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.15-alpha", + "version": "0.9.15-beta", "directories": { "lib": "./lib" }, From 65382cc8cb669ca094faef127640f85df8bac4e1 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Sun, 14 Aug 2016 18:48:00 -0400 Subject: [PATCH 42/90] Update Readme.md --- Readme.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Readme.md b/Readme.md index de3bc043..7f38e88b 100644 --- a/Readme.md +++ b/Readme.md @@ -1,4 +1,7 @@ # node-oauth + +[![Flattr This](http://button.flattr.com/flattr-badge-large.png)](https://flattr.com/submit/auto?fid=y0jx3j&url=https%3A%2F%2Fgithub.com%2Fomouse%2Fnode-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! From f1ad06861b5f392ba1831526e649fee628e276ca Mon Sep 17 00:00:00 2001 From: "Georges W. Haddad" Date: Wed, 9 Nov 2016 15:27:50 +0200 Subject: [PATCH 43/90] added function to set http options --- lib/oauth.js | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/oauth.js b/lib/oauth.js index 9539b8c3..182ab903 100644 --- a/lib/oauth.js +++ b/lib/oauth.js @@ -272,9 +272,18 @@ 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); } +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(), From 5ac22f5bf75a3d928859c05a9a73e73957a03c49 Mon Sep 17 00:00:00 2001 From: Carlos Castillo Oporta Date: Tue, 29 Nov 2016 15:01:40 -0600 Subject: [PATCH 44/90] Add a library that use node-oauth-libre --- Readme.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Readme.md b/Readme.md index 7f38e88b..153a4810 100644 --- a/Readme.md +++ b/Readme.md @@ -8,6 +8,10 @@ Tested against Twitter (http://twitter.com), term.ie (http://term.ie/oauth/examp 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) +## Related Libraries + +- [pasport-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.** From 3bc4760f9218e471ea0791ca3b98dfe65f5625d6 Mon Sep 17 00:00:00 2001 From: Carlos Castillo Oporta Date: Fri, 2 Dec 2016 11:40:05 -0600 Subject: [PATCH 45/90] Spelling error fixed --- Readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 153a4810..48c9841d 100644 --- a/Readme.md +++ b/Readme.md @@ -10,7 +10,7 @@ Also provides rudimentary OAuth2 support, tested against facebook, github, fours ## Related Libraries -- [pasport-oauth2-libre](https://github.com/caco0516/passport-oauth2-libre) Passport OAuth2 Strategy using node-oauth-libre. +- [passport-oauth2-libre](https://github.com/caco0516/passport-oauth2-libre) Passport OAuth2 Strategy using node-oauth-libre. ## License and Copyright From bfc837a9b365d808e6f0f03f6fde80d7f10616fa Mon Sep 17 00:00:00 2001 From: Carlos Castillo Oporta Date: Wed, 7 Dec 2016 09:51:11 -0600 Subject: [PATCH 46/90] Adds Authorization header with encrypted base64 data for token request POST --- lib/oauth2.js | 6 ++++-- tests/oauth2tests.js | 13 +++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/oauth2.js b/lib/oauth2.js index 8e625dfb..753665cb 100644 --- a/lib/oauth2.js +++ b/lib/oauth2.js @@ -22,7 +22,8 @@ var querystring= require('querystring'), https= require('https'), http= require('http'), URL= require('url'), - OAuthUtils= require('./_utils'); + OAuthUtils= require('./_utils'), + Buffer = require('buffer').Buffer; exports.OAuth2= function(clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders) { this._clientId= clientId; @@ -188,7 +189,8 @@ exports.OAuth2.prototype.getOAuthAccessToken= function(code, params, callback) { var post_data= querystring.stringify( params ); var post_headers= { - 'Content-Type': 'application/x-www-form-urlencoded' + 'Content-Type': 'application/x-www-form-urlencoded', + 'Authorization': 'Basic ' + Buffer.from(this._clientId + ':' + this._clientSecret).toString('base64') }; diff --git a/tests/oauth2tests.js b/tests/oauth2tests.js index 09cad1ad..a71ba4ff 100644 --- a/tests/oauth2tests.js +++ b/tests/oauth2tests.js @@ -66,6 +66,19 @@ vows.describe('OAuth2').addBatch({ assert.equal( refresh_token, "refresh"); }); }, + '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 = Buffer.from(headerSplit[1], 'base64').toString('ascii'); + assert.equal(decodedAuthHeader,"clientId:clientSecret"); + callback(null, "access_token=access&refresh_token=refresh"); + }; + oa.getOAuthAccessToken("", {}, function(error, access_token, refresh_token) { }); + } + , '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) { From 99aa79e1c48db1b7d631c895375f2ab25037df6a Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 18:23:27 -0500 Subject: [PATCH 47/90] comment and code formatting --- lib/oauth.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/oauth.js b/lib/oauth.js index 182ab903..5b5f1aac 100644 --- a/lib/oauth.js +++ b/lib/oauth.js @@ -273,13 +273,19 @@ exports.OAuth.prototype._createClient= function( port, hostname, method, path, h httpModel= http; } - for(var k in this._httpOptions) { - options[k]= this._httpOptions[k]; + 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; } From b2646570d78c901a153aa80ac01fc1fcc3fa336e Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 18:25:37 -0500 Subject: [PATCH 48/90] added george-haddad as contributor --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 48c9841d..d7eb963b 100644 --- a/Readme.md +++ b/Readme.md @@ -304,6 +304,7 @@ The Google example was removed due to the need for a custom Google-specific OAut * 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 From 5c43ba83e11d49418129e9c69b76bfc07099ad2d Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 18:29:13 -0500 Subject: [PATCH 49/90] updated change history --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index d7eb963b..a38c918c 100644 --- a/Readme.md +++ b/Readme.md @@ -212,6 +212,8 @@ The Google example was removed due to the need for a custom Google-specific OAut - 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 * 0.9.14 - OAuth2: Extend 'successful' token responses to include anything in the 2xx range. * 0.9.13 From 249a194fe9b70078fcdd687dbf3b47e4132d4a78 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 18:36:52 -0500 Subject: [PATCH 50/90] TravisCI support --- .travis.yml | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .travis.yml 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" From e1ce516da2508253327e8682a37079aa6c49fc30 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 18:39:18 -0500 Subject: [PATCH 51/90] travici build badge and gpl3 license badge --- Readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Readme.md b/Readme.md index a38c918c..7daefa85 100644 --- a/Readme.md +++ b/Readme.md @@ -1,5 +1,7 @@ # node-oauth +[![Build Status](https://travis-ci.org/omouse/node-oauth-libre.svg)](https://travis-ci.org/omouse/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%2Fomouse%2Fnode-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. From c0bce926ee7bc68c77198df834dbd8da87264d6c Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 18:44:54 -0500 Subject: [PATCH 52/90] buffer.from is not compatible with older versions of node --- lib/oauth2.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/oauth2.js b/lib/oauth2.js index 753665cb..bd5ef0d9 100644 --- a/lib/oauth2.js +++ b/lib/oauth2.js @@ -190,7 +190,7 @@ exports.OAuth2.prototype.getOAuthAccessToken= function(code, params, callback) { var post_data= querystring.stringify( params ); var post_headers= { 'Content-Type': 'application/x-www-form-urlencoded', - 'Authorization': 'Basic ' + Buffer.from(this._clientId + ':' + this._clientSecret).toString('base64') + 'Authorization': 'Basic ' + new Buffer(this._clientId + ':' + this._clientSecret).toString('base64') }; From 0210c0a256407b2edacf894345206448d7a6fa47 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 18:51:43 -0500 Subject: [PATCH 53/90] workaround for oauth2 basic authorization to handle older and newer versions of node --- lib/oauth2.js | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/oauth2.js b/lib/oauth2.js index bd5ef0d9..42843d02 100644 --- a/lib/oauth2.js +++ b/lib/oauth2.js @@ -188,11 +188,17 @@ exports.OAuth2.prototype.getOAuthAccessToken= function(code, params, callback) { params[codeParam]= code; var post_data= querystring.stringify( params ); + var authorization = 'Basic '; + var clientIdAndSecret = this._clientId + ':' + this._clientSecret; + if (typeof Buffer.from === 'function') { // node 6 and above + authorization += Buffer.from(clientIdAndSecret).toString('base64'); + } else { // node 5.11 and below + authorization += new Buffer(clientIdAndSecret, 'base64').toString(); + } var post_headers= { - 'Content-Type': 'application/x-www-form-urlencoded', - 'Authorization': 'Basic ' + new Buffer(this._clientId + ':' + this._clientSecret).toString('base64') - }; - + 'Content-Type': 'application/x-www-form-urlencoded', + 'Authorization': authorization + }; this._request("POST", this._getAccessTokenUrl(), post_headers, post_data, null, function(error, data, response) { if( error ) callback(error); From cbb0723b2c9cd8177754a490bc878a08b182f55a Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 18:56:42 -0500 Subject: [PATCH 54/90] only using buffer constructor --- lib/oauth2.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/lib/oauth2.js b/lib/oauth2.js index 42843d02..3630d5f5 100644 --- a/lib/oauth2.js +++ b/lib/oauth2.js @@ -190,11 +190,7 @@ exports.OAuth2.prototype.getOAuthAccessToken= function(code, params, callback) { var post_data= querystring.stringify( params ); var authorization = 'Basic '; var clientIdAndSecret = this._clientId + ':' + this._clientSecret; - if (typeof Buffer.from === 'function') { // node 6 and above - authorization += Buffer.from(clientIdAndSecret).toString('base64'); - } else { // node 5.11 and below - authorization += new Buffer(clientIdAndSecret, 'base64').toString(); - } + authorization += new Buffer(clientIdAndSecret, 'base64').toString(); var post_headers= { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': authorization From c85ce3170140feae0027475ee1fe90c39149e4cb Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 19:06:51 -0500 Subject: [PATCH 55/90] setup and teardown for client id and secret for getoauthtokenaccess test --- tests/oauth2tests.js | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/tests/oauth2tests.js b/tests/oauth2tests.js index a71ba4ff..325d402f 100644 --- a/tests/oauth2tests.js +++ b/tests/oauth2tests.js @@ -66,19 +66,27 @@ vows.describe('OAuth2').addBatch({ assert.equal( refresh_token, "refresh"); }); }, - '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 = Buffer.from(headerSplit[1], 'base64').toString('ascii'); - assert.equal(decodedAuthHeader,"clientId:clientSecret"); - callback(null, "access_token=access&refresh_token=refresh"); - }; - oa.getOAuthAccessToken("", {}, function(error, access_token, refresh_token) { }); - } - , + 'we should correctly send Authorization header encoded Base64 for token request': function (oa) { + var originalClientId = oa._clientId; + var originalClientSecret = oa._clientSecret; + oa._clientId = 'clientId'; + oa._clientSecret = 'clientSecret'; + 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 = Buffer.from(headerSplit[1], 'base64').toString('ascii'); + assert.equal(decodedAuthHeader,"clientId:clientSecret"); + callback(null, "access_token=access&refresh_token=refresh"); + }; + oa.getOAuthAccessToken("", {}, function(error, access_token, refresh_token) { + oa._clientId = originalClientId; + oa._clientSecret = originalClientSecret; + }); + }, '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) { From 1b6fbd15171e7dc9bd305341b061b5fb2377c707 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 19:24:35 -0500 Subject: [PATCH 56/90] fixed tests, and use of buffer base64 --- lib/oauth2.js | 12 ++++++++---- tests/oauth2tests.js | 10 ++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/lib/oauth2.js b/lib/oauth2.js index 3630d5f5..16a373ca 100644 --- a/lib/oauth2.js +++ b/lib/oauth2.js @@ -180,6 +180,12 @@ exports.OAuth2.prototype.getAuthorizeUrl= function( params ) { return this._baseSite + this._authorizeUrl + "?" + querystring.stringify(params); } +exports.OAuth2.prototype._getAuthorizationHeader = function() { + var clientIdAndSecret = this._clientId + ':' + this._clientSecret; + var clientInfoAsBase64 = new Buffer(clientIdAndSecret).toString('base64'); + return 'Basic ' + clientInfoAsBase64.toString(); +} + exports.OAuth2.prototype.getOAuthAccessToken= function(code, params, callback) { var params= params || {}; params['client_id'] = this._clientId; @@ -188,12 +194,10 @@ exports.OAuth2.prototype.getOAuthAccessToken= function(code, params, callback) { params[codeParam]= code; var post_data= querystring.stringify( params ); - var authorization = 'Basic '; - var clientIdAndSecret = this._clientId + ':' + this._clientSecret; - authorization += new Buffer(clientIdAndSecret, 'base64').toString(); + var post_headers= { 'Content-Type': 'application/x-www-form-urlencoded', - 'Authorization': authorization + 'Authorization': this._getAuthorizationHeader() }; this._request("POST", this._getAccessTokenUrl(), post_headers, post_data, null, function(error, data, response) { diff --git a/tests/oauth2tests.js b/tests/oauth2tests.js index 325d402f..c38c295e 100644 --- a/tests/oauth2tests.js +++ b/tests/oauth2tests.js @@ -66,6 +66,16 @@ vows.describe('OAuth2').addBatch({ assert.equal( refresh_token, "refresh"); }); }, + '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 = Buffer.from(headerSplit[1], 'base64').toString('ascii'); + assert.equal(decodedAuthHeader, 'hello:world'); + }, 'we should correctly send Authorization header encoded Base64 for token request': function (oa) { var originalClientId = oa._clientId; var originalClientSecret = oa._clientSecret; From bceb68ce301ce650eb8be8e34589e9e4b2eb45b1 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 19:25:09 -0500 Subject: [PATCH 57/90] fixing styling based on codacy, #8 --- lib/oauth2-promise.js | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/lib/oauth2-promise.js b/lib/oauth2-promise.js index 89b5f014..432ba5a7 100644 --- a/lib/oauth2-promise.js +++ b/lib/oauth2-promise.js @@ -17,8 +17,8 @@ * along with this program. If not, see . */ -var Promise = require('bluebird'); -var _OAuth2 = require('./oauth2').OAuth2; +var Promise = require("bluebird"); +var _OAuth2 = require("./oauth2").OAuth2; var OAuth2 = function(clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders) { this._oa = new _OAuth2(clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders); @@ -38,22 +38,22 @@ OAuth2.prototype.get = function() { // delegates PromiseOAuth2.methodName to OAuth2.methodName var delegatedMethods = [ - 'buildAuthHeader', - 'getAuthorizeUrl', - 'setAuthMethod', - 'useAuthorizationHeaderforGET', + "buildAuthHeader", + "getAuthorizeUrl", + "setAuthMethod", + "useAuthorizationHeaderforGET", // Required for testing - '_executeRequest', - '_request' + "_executeRequest", + "_request" ]; -delegatedMethods.forEach(delegate); - function delegate(methodName) { OAuth2.prototype[methodName] = function() { return this._oa[methodName].apply(this._oa, arguments); }; } +delegatedMethods.forEach(delegate); + exports.OAuth2 = OAuth2; From 9152ac56bb722c863408606103e969d75e8932c9 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 19:30:16 -0500 Subject: [PATCH 58/90] supporting latest node in tests for now --- .travis.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1528af29..b948d744 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,7 +2,3 @@ language: node_js node_js: - "node" - "5.11" - - "4.4" - - "4.3" - - "0.12" - - "0.10" From 668dad6a2d19043704b15f2b36669793fef848a3 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 19:34:13 -0500 Subject: [PATCH 59/90] code cleanup, #8 --- lib/_utils.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/_utils.js b/lib/_utils.js index ed7eba57..5baa645e 100644 --- a/lib/_utils.js +++ b/lib/_utils.js @@ -19,6 +19,6 @@ // Returns true if this is a host that closes *before* it ends?!?! -module.exports.isAnEarlyCloseHost= function( hostName ) { - return hostName && hostName.match(".*google(apis)?.com$") -} +module.exports.isAnEarlyCloseHost = function(hostName) { + return hostName && hostName.match(".*google(apis)?.com$"); +}; From 9ab9208b9d2d6dc9bd7ac476ea0547bac21d26de Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 19:40:16 -0500 Subject: [PATCH 60/90] code cleanup #8 --- lib/oauth.js | 2 +- lib/sha1.js | 2 +- tests/sha1tests.js | 23 +++++++++++++---------- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/lib/oauth.js b/lib/oauth.js index 5b5f1aac..7be7cfd0 100644 --- a/lib/oauth.js +++ b/lib/oauth.js @@ -234,7 +234,7 @@ 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; diff --git a/lib/sha1.js b/lib/sha1.js index c6589032..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); } diff --git a/tests/sha1tests.js b/tests/sha1tests.js index 022119b5..f9c96530 100644 --- a/tests/sha1tests.js +++ b/tests/sha1tests.js @@ -17,16 +17,19 @@ * along with this program. If not, see . */ -var vows = require('vows'), - assert = require('assert'); +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: 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="); - } +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); From bb7e53f48446e39fe7bd669439fe206067dd5a58 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 19:42:47 -0500 Subject: [PATCH 61/90] code cleanup #8 --- examples/github-oauth2.js | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/examples/github-oauth2.js b/examples/github-oauth2.js index a7276b39..6bae8cf4 100644 --- a/examples/github-oauth2.js +++ b/examples/github-oauth2.js @@ -17,37 +17,37 @@ * along with this program. If not, see . */ -var OAuth2 = require('../index').PromiseOAuth2; +var OAuth2 = require("../index").PromiseOAuth2; -var clientId = ''; -var clientSecret = ''; +var clientId = ""; +var clientSecret = ""; // Fill these in: -var user = 'USER'; -var personalAccessToken = 'PERSONAL_ACCESS_TOKEN'; +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 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'; +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); + console.log(json[i]["id"] + ": " + json[i].type); } }) .catch(function(err) { - console.log('Error: ' + err); + console.log("Error: " + err); }); - -function jsonParse(data) { - return JSON.parse(data); -} From 3fee7e6e499820aa54a7cdaae4d54585709c46a7 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 19:43:57 -0500 Subject: [PATCH 62/90] code cleanup #8 --- examples/twitter-oauth-promises.js | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/examples/twitter-oauth-promises.js b/examples/twitter-oauth-promises.js index 657b5fdf..97039448 100644 --- a/examples/twitter-oauth-promises.js +++ b/examples/twitter-oauth-promises.js @@ -17,21 +17,21 @@ * along with this program. If not, see . */ -var OAuth = require('../index').PromiseOAuth; +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 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 consumerKey = "your consumer key"; +var consumerSecret = "your consumer secret"; var client = new OAuth( requestUrl, accessUrl, @@ -44,16 +44,16 @@ var client = new OAuth( ); // Making a request to the API -var url = 'https://api.twitter.com/1.1/statuses/home_timeline.json'; +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'; +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(err) { - console.log('Error: ' + error); + console.log("Data: " + data); + console.log("Response: " + response); +}).catch(function(error) { + console.log("Error: " + error); }); From a4a16b57870397e99d58447dd904e2603b3a093e Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 19:57:10 -0500 Subject: [PATCH 63/90] code cleanup #8 --- examples/github-example.js | 129 ++++++++++++++-------------- examples/promise-twitter-example.js | 94 ++++++++++---------- examples/term.ie.oauth-HMAC-SHA1.js | 65 ++++++++------ examples/twitter-example.js | 43 +++++----- tests/shared.js | 8 +- 5 files changed, 171 insertions(+), 168 deletions(-) diff --git a/examples/github-example.js b/examples/github-example.js index a10c7af4..e5932e8b 100644 --- a/examples/github-example.js +++ b/examples/github-example.js @@ -17,76 +17,75 @@ * along with this program. If not, see . */ -var http = require('http'); -var qs = require('querystring'); -// var OAuth = require('oauth'), OAuth2 = OAuth.OAuth2; -var OAuth2 = require('../lib/oauth2.js').OAuth2; +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 */ +var clientID = ""; +var clientSecret = ""; +var oauth2 = new OAuth2( + clientID, + clientSecret, + "https://github.com/", + "login/oauth/authorize", + "login/oauth/access_token", + null /** Custom headers */ +); 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 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" + }); - /** - * 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]); + /** + * 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/promise-twitter-example.js b/examples/promise-twitter-example.js index a5bf277a..afdf9691 100644 --- a/examples/promise-twitter-example.js +++ b/examples/promise-twitter-example.js @@ -17,52 +17,48 @@ * 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'); + * + * 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. + * + */ -const callbackURL = 'http://localhost:5000/oauth_callback'; -const yourConsumerKey = 'INSERT YOUR CONSUMER KEY HERE'; -const yourConsumerSecret = 'INSERT YOUR CONSUMER SECRET KEY HERE'; +var http = require("http"); +var oauth = require("../lib/oauth-promise").OAuth; +var express = require("express"); -var reqTokenSecrets = {}; // Hash that contains the req_token:req_token_secret key vals +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! - */ + 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', + "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' + "HMAC-SHA1" ); var app = express(); -app.get('/', function(req, res){ - - +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: @@ -70,9 +66,8 @@ app.get('/', function(req, res){ data[1]: oauth_token_secret data[2]: results - */ + */ requestTokenPromise.then(function(data){ - // Extract data var oauthToken = data[0]; var oauthTokenSecret = data[1]; @@ -81,7 +76,8 @@ app.get('/', function(req, res){ reqTokenSecrets[oauthToken] = oauthTokenSecret; // Redirect user to Twitter Auth - var redirectURL = 'https://api.twitter.com/oauth/authorize'+'?oauth_token='+oauthToken; + var redirectURL = "https://api.twitter.com/oauth/authorize" + + "?oauth_token=" + oauthToken; res.redirect(redirectURL); }); @@ -89,38 +85,38 @@ app.get('/', function(req, res){ }); -app.get('/oauth_callback', function(req, res){ +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 + // 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); + 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){ - + */ + 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); - }); - + // 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'); + 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 d96e55be..cce4f83b 100644 --- a/examples/term.ie.oauth-HMAC-SHA1.js +++ b/examples/term.ie.oauth-HMAC-SHA1.js @@ -16,35 +16,44 @@ * 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 util= require('util') +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 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") - -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, oauth_token, oauth_token_secret, results) { + if (error) { + util.puts("error :" + error); + return; + } + 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) { util.puts(data); - }); + }); }); - } -}) +}); diff --git a/examples/twitter-example.js b/examples/twitter-example.js index e8b695a1..088703e7 100644 --- a/examples/twitter-example.js +++ b/examples/twitter-example.js @@ -17,65 +17,64 @@ * along with this program. If not, see . */ -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'; +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"; var oa = new OAuth( - 'https://api.twitter.com/oauth/request_token', - 'https://api.twitter.com/oauth/access_token', + "https://api.twitter.com/oauth/request_token", + "https://api.twitter.com/oauth/access_token", clientID, clientSecret, - '1.0', + "1.0", callbackURL, - 'HMAC-SHA1' + "HMAC-SHA1" ); http.createServer(function (request, response) { oa.getOAuthRequestToken(function (error, oAuthToken, oAuthTokenSecret, results) { var urlObj = nodeUrl.parse(request.url, true); var handlers = { - '/': function (request, response) { + "/": function (request, response) { /** * Creating an anchor with authURL as href and sending as response */ - oa.getOAuthRequestToken(function(error) { + oa.getOAuthRequestToken(function (error) { var statusCode; var body; var authURL; if (error) { statusCode = 401; - body = 'Error: ' + error.data; + body = "Error: " + error.data; } else { statusCode = 200; - authURL = 'https://api.twitter.com/oauth/authorize?oauth_token=' + oAuthToken; - body = ' Get Code '; + authURL = "https://api.twitter.com/oauth/authorize?oauth_token=" + oAuthToken; + body = " Get Code "; } response.writeHead(statusCode, { - 'Content-Length': body.length, - 'Content-Type': 'text/html' + "Content-Length": body.length, + "Content-Type": "text/html" }); response.end(body); }); }, - '/callback': function (request, response) { + "/callback": function (request, response) { /** Obtaining access_token */ - var getOAuthRequestTokenCallback = function (error, oAuthAccessToken, - oAuthAccessTokenSecret, results) { + var getOAuthRequestTokenCallback = function (error, oAuthAccessToken, oAuthAccessTokenSecret, results) { if (error) { console.log(error); response.end(JSON.stringify({ - message: 'Error occured while getting access token', + message: "Error occured while getting access token", error: error })); return; } oa.get( - 'https://api.twitter.com/1.1/account/verify_credentials.json', + "https://api.twitter.com/1.1/account/verify_credentials.json", oAuthAccessToken, oAuthAccessTokenSecret, function (error, twitterResponseData, result) { diff --git a/tests/shared.js b/tests/shared.js index 9fbe7c9e..27d4b831 100644 --- a/tests/shared.js +++ b/tests/shared.js @@ -17,7 +17,7 @@ * along with this program. If not, see . */ -var events = require('events'); +var events = require("events"); exports.DummyResponse = function(statusCode) { this.statusCode = statusCode; @@ -38,13 +38,13 @@ exports.DummyRequest.prototype = events.EventEmitter.prototype; exports.DummyRequest.prototype.write = function(postBody) { this.responseSent = true; - this.emit('response', this.response); + this.emit("response", this.response); }; exports.DummyRequest.prototype.end = function() { if (!this.responseSent) { this.responseSent = true; - this.emit('response',this.response); + this.emit("response",this.response); } - this.response.emit('end'); + this.response.emit("end"); }; From 31f5331c1059e2f9e2c93220c9e19f66ee7c37eb Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 20:02:54 -0500 Subject: [PATCH 64/90] camel case cleanup #8 --- examples/term.ie.oauth-HMAC-SHA1.js | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/examples/term.ie.oauth-HMAC-SHA1.js b/examples/term.ie.oauth-HMAC-SHA1.js index cce4f83b..d632daec 100644 --- a/examples/term.ie.oauth-HMAC-SHA1.js +++ b/examples/term.ie.oauth-HMAC-SHA1.js @@ -16,7 +16,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -var util = require("util") +var util = require("util"); var OAuth = require("../lib/oauth").OAuth; var oa = new OAuth( @@ -29,29 +29,29 @@ var oa = new OAuth( "HMAC-SHA1" ); -oa.getOAuthRequestToken(function(error, oauth_token, oauth_token_secret, results) { +oa.getOAuthRequestToken(function(error, oauthToken, oauthTokenSecret, results) { if (error) { util.puts("error :" + error); return; } - util.puts("oauth_token :" + oauth_token); - util.puts("oauth_token_secret :" + oauth_token_secret); + 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( - 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); + 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", - oauth_access_token, - oauth_access_token_secret, + oauthAccessToken, + oauthAccessTokenSecret, function (error, data, response) { util.puts(data); }); From 57106a07b97f4c5d24957c09cebae44782a07208 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 20:23:11 -0500 Subject: [PATCH 65/90] more code cleanup #8 --- examples/promise-twitter-example.js | 4 +- tests/oauth2tests.js | 545 ++++++++++++++-------------- 2 files changed, 273 insertions(+), 276 deletions(-) diff --git a/examples/promise-twitter-example.js b/examples/promise-twitter-example.js index afdf9691..a7c60232 100644 --- a/examples/promise-twitter-example.js +++ b/examples/promise-twitter-example.js @@ -29,7 +29,7 @@ */ var http = require("http"); -var oauth = require("../lib/oauth-promise").OAuth; +var OAuth = require("../lib/oauth-promise").OAuth; var express = require("express"); const callbackURL = "http://localhost:5000/oauth_callback"; @@ -42,7 +42,7 @@ var reqTokenSecrets = {}; /* STEP 1 - init the OAuth Client! */ -var oa = new oauth( +var oa = new OAuth( "https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", yourConsumerKey, // CONSUMER KEY diff --git a/tests/oauth2tests.js b/tests/oauth2tests.js index a71ba4ff..90e525c8 100644 --- a/tests/oauth2tests.js +++ b/tests/oauth2tests.js @@ -17,306 +17,303 @@ * along with this program. If not, see . */ -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'); +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() { - 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); - } +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 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 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 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 = Buffer.from(headerSplit[1], 'base64').toString('ascii'); - assert.equal(decodedAuthHeader,"clientId:clientSecret"); - callback(null, "access_token=access&refresh_token=refresh"); - }; - oa.getOAuthAccessToken("", {}, function(error, access_token, refresh_token) { }); + "we should treat a 200 response as a success": function (oa) { + var callbackCalled = false; + var httpLibrary = { + request: function () { + return new DummyRequest(new DummyResponse(200)); } - , - '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._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 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 = Buffer.from(headerSplit[1], "base64").toString("ascii"); + assert.equal(decodedAuthHeader, "clientId: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( 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"); - }); - } + 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"); + }); }, - '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", {} ); - } + "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"); + }); }, - '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 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"); + }); }, - '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 ); + "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.getOAuthAccessToken("sdsds2", {grant_type:"refresh_token"} ); + oa.useAuthorizationHeaderforGET(true); + oa.get("", "abcd5"); } }, - '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"); - } - } - }, - '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() { - 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") - } - } + } + }, + "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 (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 { + 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() { - 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": "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 { + 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() { - 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("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 { + 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() { - 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": "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 { + 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", 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 (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", 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 (httpLibrary, options, callback) { + assert.equal(options.headers["User-Agent"], "Node-oauth"); + }; + oa.get("", {}); } } + } }).export(module); From 7828afdf5abaf6016ed80402a8ed337502f4988b Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 20:28:52 -0500 Subject: [PATCH 66/90] more more more code cleanup #8 --- tests/oauth2tests.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/oauth2tests.js b/tests/oauth2tests.js index 90e525c8..297fe0d3 100644 --- a/tests/oauth2tests.js +++ b/tests/oauth2tests.js @@ -185,7 +185,7 @@ vows.describe("OAuth2").addBatch({ } }, "Given an OAuth2 instance with clientId, clientSecret and customHeaders": { - topic: new OAuth2("clientId", "clientSecret", undefined, undefined, undefined, { "SomeHeader": "123" }), + 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) { @@ -212,9 +212,9 @@ vows.describe("OAuth2").addBatch({ write: function (body) { bodyWritten = true; assert.isNotNull(body); - assert.equal(body, "THIS_IS_A_POST_BODY_STRING") + assert.equal(body, "THIS_IS_A_POST_BODY_STRING"); } - } + }; } }; } @@ -235,9 +235,9 @@ vows.describe("OAuth2").addBatch({ write: function (body) { bodyWritten = true; assert.isNotNull(body); - assert.equal(4, body.length) + assert.equal(4, body.length); } - } + }; } }; } @@ -260,9 +260,9 @@ vows.describe("OAuth2").addBatch({ write: function (body) { bodyWritten = true; assert.isNotNull(body); - assert.equal(body, "THIS_IS_A_PUT_BODY_STRING") + assert.equal(body, "THIS_IS_A_PUT_BODY_STRING"); } - } + }; } }; } @@ -295,7 +295,7 @@ vows.describe("OAuth2").addBatch({ } }, "When the user passes in the User-Agent in customHeaders": { - topic: new OAuth2("clientId", "clientSecret", undefined, undefined, undefined, { "User-Agent": "123Agent" }), + 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) { @@ -306,7 +306,7 @@ vows.describe("OAuth2").addBatch({ } }, "When the user does not pass in a User-Agent in customHeaders": { - topic: new OAuth2("clientId", "clientSecret", undefined, undefined, undefined, undefined), + 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) { From e8ac8ce40aef7bbecb2fc1e5283e1aa7851e1055 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 20:42:24 -0500 Subject: [PATCH 67/90] coding style fixes #8 --- tests/oauth2promise-tests.js | 524 +++++++++++++++++------------------ 1 file changed, 262 insertions(+), 262 deletions(-) diff --git a/tests/oauth2promise-tests.js b/tests/oauth2promise-tests.js index 39fde24a..59b67c53 100644 --- a/tests/oauth2promise-tests.js +++ b/tests/oauth2promise-tests.js @@ -18,293 +18,293 @@ * along with this program. If not, see . */ -var vows = require('vows'), - assert = require('assert'), - DummyResponse= require('./shared').DummyResponse, - DummyRequest= require('./shared').DummyRequest, - https = require('https'), - OAuth2= require('../lib/oauth2-promise').OAuth2, - url = require('url'); +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 http_library= { - 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); - } +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"); + }); }, - '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); - }; + "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( 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"); - }); - } + 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"); + }); }, - '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", {} ); - } + "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"); + }); }, - '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 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"); + }); }, - '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 ); + "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.getOAuthAccessToken("sdsds2", {grant_type:"refresh_token"} ); + oa.useAuthorizationHeaderforGET(true); + oa.get("", "abcd5"); } }, - '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"); - } - } - }, - '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 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"); } } }, - '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 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.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._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") - } - } + } + }, + "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 (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": "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("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": "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", 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", 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 (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", 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 (httpLibrary, options, callback) { + assert.equal(options.headers["User-Agent"], "Node-oauth"); + }; + oa.get("", {}); } } + } }).export(module); From 1906355dae9ec6683d3db55694939ba0009bd5e6 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 20:49:34 -0500 Subject: [PATCH 68/90] more cleanup of code #8 --- lib/oauth-promise.js | 92 +++++++++++++++++++++++++------------------- 1 file changed, 52 insertions(+), 40 deletions(-) diff --git a/lib/oauth-promise.js b/lib/oauth-promise.js index 3ce27955..ca408abc 100644 --- a/lib/oauth-promise.js +++ b/lib/oauth-promise.js @@ -17,62 +17,74 @@ * along with this program. If not, see . */ -var Promise = require('bluebird'); -var _OAuth = require('./oauth').OAuth; +var Promise = require("bluebird"); +var _OAuth = require("./oauth").OAuth; +/** + * Constructor for Promisified OAuth1 object. Creates the original + * class and delegates most methods to it. + */ 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 }); }; -// Promisifed public API for OAuth +/** + * Delegates the method in the Promisified OAuth1 class to the + * original class. + */ +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"). + */ +function asyncDelegate(methodName) { + OAuth.prototype[methodName] = function() { + return this._oa[methodName + "Async"].apply(this._oa, arguments); + }; +} + +/** Promisifed public API for OAuth */ var delegatedPromiseMethods = [ - 'delete', - 'get', - 'getOAuthAccessToken', - 'getOAuthRequestToken', - 'post', - 'put' + "delete", + "get", + "getOAuthAccessToken", + "getOAuthRequestToken", + "post", + "put" ]; delegatedPromiseMethods.forEach(asyncDelegate); -// delegates PromiseOAuth.methodName to OAuth.methodName +/** delegates PromiseOAuth.methodName to OAuth.methodName */ var delegatedMethods = [ - 'authHeader', - 'getProtectedResource', - 'setClientOptions', - 'signUrl', + "authHeader", + "getProtectedResource", + "setClientOptions", + "signUrl", // Required for testing - '_buildAuthorizationHeaders', - '_createSignature', - '_createSignatureBase', - '_encodeData', - '_getNonce', - '_getSignature', - '_getTimestamp', - '_isParameterNameAnOAuthParameter', - '_makeArrayOfArgumentsHash', - '_normaliseRequestParams', - '_normalizeUrl', - '_performSecureRequest', - '_prepareParameters', - '_sortRequestParams' + "_buildAuthorizationHeaders", + "_createSignature", + "_createSignatureBase", + "_encodeData", + "_getNonce", + "_getSignature", + "_getTimestamp", + "_isParameterNameAnOAuthParameter", + "_makeArrayOfArgumentsHash", + "_normaliseRequestParams", + "_normalizeUrl", + "_performSecureRequest", + "_prepareParameters", + "_sortRequestParams" ]; delegatedMethods.forEach(delegate); -function delegate(methodName) { - OAuth.prototype[methodName] = function() { - return this._oa[methodName].apply(this._oa, arguments); - }; -} - -function asyncDelegate(methodName) { - OAuth.prototype[methodName] = function() { - return this._oa[methodName + 'Async'].apply(this._oa, arguments); - }; -} - exports.OAuth = OAuth; From 766554fab387c2ed0174b6489d3f62defa61f55f Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 20:53:44 -0500 Subject: [PATCH 69/90] yep, more code cleanup #8 --- tests/oauth2promise-tests.js | 54 ++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/tests/oauth2promise-tests.js b/tests/oauth2promise-tests.js index 59b67c53..5f86593d 100644 --- a/tests/oauth2promise-tests.js +++ b/tests/oauth2promise-tests.js @@ -31,8 +31,8 @@ vows.describe("OAuth2-Promise").addBatch({ 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= { + var callbackCalled = false; + var httpLibrary = { request: function () { return new DummyRequest(new DummyResponse(201)); } @@ -51,7 +51,7 @@ vows.describe("OAuth2-Promise").addBatch({ } }; oa._executeRequest(httpLibrary, {}, null, function (err, result, response) { - callbackCalled= true; + callbackCalled = true; assert.equal(err, null); }); assert.ok(callbackCalled); @@ -121,7 +121,7 @@ vows.describe("OAuth2-Promise").addBatch({ "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); + assert.isTrue(post_body.indexOf("code=xsds23") !== -1); }; oa.getOAuthAccessToken("xsds23", {grant_type: "refresh_toucan" }); } @@ -129,9 +129,9 @@ vows.describe("OAuth2-Promise").addBatch({ "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); + 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" }); } @@ -173,11 +173,11 @@ vows.describe("OAuth2-Promise").addBatch({ } }, "Given an OAuth2 instance with clientId, clientSecret and customHeaders": { - topic: new OAuth2("clientId", "clientSecret", undefined, undefined, undefined, + 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) { + oa._executeRequest = function (httpLibrary, options, callback) { assert.equal(options.headers["SomeHeader"], "123"); }; oa.get("", {}); @@ -188,7 +188,7 @@ vows.describe("OAuth2-Promise").addBatch({ topic: new OAuth2("clientId", "clientSecret"), "When POSTing": { "we should see a given string being sent to the request": function (oa) { - var bodyWritten= false; + var bodyWritten = false; oa._oa._chooseHttpLibrary = function () { return { request: function (options) { @@ -199,11 +199,11 @@ vows.describe("OAuth2-Promise").addBatch({ end: function () {}, on: function () {}, write: function (body) { - bodyWritten= true; + bodyWritten = true; assert.isNotNull(body); - assert.equal(body, "THIS_IS_A_POST_BODY_STRING") + assert.equal(body, "THIS_IS_A_POST_BODY_STRING"); } - } + }; } }; } @@ -211,7 +211,7 @@ vows.describe("OAuth2-Promise").addBatch({ assert.ok(bodyWritten); }, "we should see a given buffer being sent to the request": function (oa) { - var bodyWritten= false; + var bodyWritten = false; oa._oa._chooseHttpLibrary = function () { return { request: function (options) { @@ -222,11 +222,11 @@ vows.describe("OAuth2-Promise").addBatch({ end: function () {}, on: function () {}, write: function (body) { - bodyWritten= true; + bodyWritten = true; assert.isNotNull(body); - assert.equal(4, body.length) + assert.equal(4, body.length); } - } + }; } }; } @@ -236,7 +236,7 @@ vows.describe("OAuth2-Promise").addBatch({ }, "When PUTing": { "we should see a given string being sent to the request": function (oa) { - var bodyWritten= false; + var bodyWritten = false; oa._oa._chooseHttpLibrary = function () { return { request: function (options) { @@ -247,11 +247,11 @@ vows.describe("OAuth2-Promise").addBatch({ end: function () {}, on: function () {}, write: function (body) { - bodyWritten= true; + bodyWritten = true; assert.isNotNull(body); - assert.equal(body, "THIS_IS_A_PUT_BODY_STRING") + assert.equal(body, "THIS_IS_A_PUT_BODY_STRING"); } - } + }; } }; } @@ -259,7 +259,7 @@ vows.describe("OAuth2-Promise").addBatch({ assert.ok(bodyWritten); }, "we should see a given buffer being sent to the request": function (oa) { - var bodyWritten= false; + var bodyWritten = false; oa._oa._chooseHttpLibrary = function () { return { request: function (options) { @@ -270,11 +270,11 @@ vows.describe("OAuth2-Promise").addBatch({ end: function () {}, on: function () {}, write: function (body) { - bodyWritten= true; + bodyWritten = true; assert.isNotNull(body); assert.equal(4, body.length) } - } + }; } }; } @@ -284,7 +284,7 @@ vows.describe("OAuth2-Promise").addBatch({ } }, "When the user passes in the User-Agent in customHeaders": { - topic: new OAuth2("clientId", "clientSecret", undefined, undefined, undefined, + 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) { @@ -296,8 +296,8 @@ vows.describe("OAuth2-Promise").addBatch({ } }, "When the user does not pass in a User-Agent in customHeaders": { - topic: new OAuth2("clientId", "clientSecret", undefined, undefined, undefined, - undefined), + 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) { From 668eb088e3207a097c5e8dacfa3293cd22d6e13e Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 20:56:44 -0500 Subject: [PATCH 70/90] mhm more cleanup #8 --- tests/oauth2tests.js | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/oauth2tests.js b/tests/oauth2tests.js index 297fe0d3..27c5cc00 100644 --- a/tests/oauth2tests.js +++ b/tests/oauth2tests.js @@ -125,7 +125,7 @@ vows.describe("OAuth2").addBatch({ "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); + assert.isTrue(postBody.indexOf("code=xsds23") !== -1); }; oa.getOAuthAccessToken("xsds23", {}); } @@ -133,19 +133,19 @@ vows.describe("OAuth2").addBatch({ "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); + assert.isTrue(postBody.indexOf("code=xsds23") !== -1); }; - oa.getOAuthAccessToken("xsds23", {grant_type: "refresh_toucan" }); + 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); + 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" }); + oa.getOAuthAccessToken("sdsds2", { "grant_type": "refresh_token" }); } }, "When we use the authorization header": { @@ -217,7 +217,7 @@ vows.describe("OAuth2").addBatch({ }; } }; - } + }; oa._request("POST", "", { "Content-Type": "text/plain" }, "THIS_IS_A_POST_BODY_STRING"); assert.ok(bodyWritten); }, @@ -265,7 +265,7 @@ vows.describe("OAuth2").addBatch({ }; } }; - } + }; oa._request("PUT", "", { "Content-Type": "text/plain" }, "THIS_IS_A_PUT_BODY_STRING"); assert.ok(bodyWritten); }, @@ -283,12 +283,12 @@ vows.describe("OAuth2").addBatch({ write: function (body) { bodyWritten = true; assert.isNotNull(body); - assert.equal(4, body.length) + assert.equal(4, body.length); } - } + }; } }; - } + }; oa._request("PUT", "", { "Content-Type": "application/octet-stream" }, new Buffer([1,2,3,4])); assert.ok(bodyWritten); } From 28de1caee6dbc6dc026d936fefbe3ddf2456c13a Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 21:20:58 -0500 Subject: [PATCH 71/90] refactoring duplicate code #8 --- lib/oauth.js | 66 ++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 49 insertions(+), 17 deletions(-) diff --git a/lib/oauth.js b/lib/oauth.js index 7be7cfd0..122a9072 100644 --- a/lib/oauth.js +++ b/lib/oauth.js @@ -587,29 +587,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); }; From 1bc766bd26a755074dfc5d6ba5aedca4b07cae07 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 26 Dec 2016 21:21:10 -0500 Subject: [PATCH 72/90] added jsdocs, #8 --- conf.json | 22 ++++++++++++++++++++++ package.json | 4 +++- 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 conf.json diff --git a/conf.json b/conf.json new file mode 100644 index 00000000..2d4e818e --- /dev/null +++ b/conf.json @@ -0,0 +1,22 @@ +{ + "opts": { + "destination": "api-docs" + }, + "tags": { + "allowUnknownTags": true, + "dictionaries": ["jsdoc","closure"] + }, + "source": { + "includePattern": ".+\\.js(doc|x)?$", + "excludePattern": "(^|\\/|\\\\)_", + "include": [ + "index.js", + "lib" + ] + }, + "plugins": [], + "templates": { + "cleverLinks": false, + "monospaceLinks": false + } +} diff --git a/package.json b/package.json index 347c6dfa..40d4ceee 100644 --- a/package.json +++ b/package.json @@ -18,10 +18,12 @@ "url": "http://github.com/omouse/node-oauth-libre.git" }, "devDependencies": { + "jsdoc": "^3.4.3", "vows": "0.5.x" }, "scripts": { - "test": "make test" + "test": "make test", + "build-docs": "jsdoc -c conf.json" }, "licenses": [ { From c7d9db7bcceb5f1af151f83d249dc632e1089938 Mon Sep 17 00:00:00 2001 From: bernard Date: Tue, 27 Dec 2016 11:27:31 +0200 Subject: [PATCH 73/90] move extra params to function call --- lib/oauth.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/oauth.js b/lib/oauth.js index 122a9072..bb4c72c9 100644 --- a/lib/oauth.js +++ b/lib/oauth.js @@ -487,8 +487,7 @@ exports.OAuth.prototype.setClientOptions= function(options) { this._clientOptions= mergedOptions; }; -exports.OAuth.prototype.getOAuthAccessToken= function(oauth_token, oauth_token_secret, oauth_verifier, callback) { - var extraParams= {}; +exports.OAuth.prototype.getOAuthAccessToken= function(oauth_token, oauth_token_secret, oauth_verifier, callback, extraParams = {}) { if( typeof oauth_verifier == "function" ) { callback= oauth_verifier; } else { From cdc6a59d13c60ff427e28108eea9d95d2f0c6c8b Mon Sep 17 00:00:00 2001 From: bernard Date: Tue, 27 Dec 2016 13:14:14 +0200 Subject: [PATCH 74/90] modify code to accomodate with previous ECMA Version --- lib/oauth.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/oauth.js b/lib/oauth.js index bb4c72c9..31132fda 100644 --- a/lib/oauth.js +++ b/lib/oauth.js @@ -487,7 +487,10 @@ exports.OAuth.prototype.setClientOptions= function(options) { this._clientOptions= mergedOptions; }; -exports.OAuth.prototype.getOAuthAccessToken= function(oauth_token, oauth_token_secret, oauth_verifier, callback, extraParams = {}) { +exports.OAuth.prototype.getOAuthAccessToken= function(oauth_token, oauth_token_secret, oauth_verifier, callback, extraParams) { + if(!extraParams) { + var extraParams = {}; + } if( typeof oauth_verifier == "function" ) { callback= oauth_verifier; } else { From 02de5b90848152ae3d23bb331a6bbf0f1553c342 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Tue, 27 Dec 2016 12:20:19 -0500 Subject: [PATCH 75/90] jsdoc comments, npm run build-docs to generate docs --- Readme.md | 6 ++ conf.json | 7 +- index.js | 29 ++++++ lib/_utils.js | 8 +- lib/oauth-promise.js | 86 +++++++++++++++- lib/oauth.js | 227 ++++++++++++++++++++++++++++++++++++++++-- lib/oauth2-promise.js | 22 +++- lib/oauth2.js | 176 +++++++++++++++++++++++++++++--- 8 files changed, 530 insertions(+), 31 deletions(-) diff --git a/Readme.md b/Readme.md index 7daefa85..84fafaee 100644 --- a/Readme.md +++ b/Readme.md @@ -30,6 +30,12 @@ the GPLv3 bits if they want to use them in a proprietary project npm install oauth-libre +# Build the Docs + +Requires JSDoc to be installed: + + npm run build-docs + # Examples ## Using Promises diff --git a/conf.json b/conf.json index 2d4e818e..0a393faa 100644 --- a/conf.json +++ b/conf.json @@ -1,15 +1,16 @@ { "opts": { - "destination": "api-docs" + "destination": "api-docs", + "readme": "Readme.md" }, "tags": { "allowUnknownTags": true, "dictionaries": ["jsdoc","closure"] }, "source": { - "includePattern": ".+\\.js(doc|x)?$", - "excludePattern": "(^|\\/|\\\\)_", + "includePattern": ".+\\.js(doc|x|on)?$", "include": [ + "Readme.md", "index.js", "lib" ] diff --git a/index.js b/index.js index 687dc8d9..36c0d05a 100644 --- a/index.js +++ b/index.js @@ -18,8 +18,37 @@ * 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; + +/** + * 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 5baa645e..c7b91651 100644 --- a/lib/_utils.js +++ b/lib/_utils.js @@ -17,8 +17,14 @@ * along with this program. If not, see . */ +/** @module OAuthUtils */ -// Returns true if this is a host that closes *before* it ends?!?! +/** + * 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 index ca408abc..305c694c 100644 --- a/lib/oauth-promise.js +++ b/lib/oauth-promise.js @@ -1,4 +1,4 @@ -/** +/* * node-oauth-libre is a Node.js library for OAuth * * Copyright (C) 2016 Rudolf Olah @@ -23,6 +23,8 @@ 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); @@ -32,6 +34,7 @@ var OAuth = function(requestUrl, accessUrl, consumerKey, consumerSecret, version /** * Delegates the method in the Promisified OAuth1 class to the * original class. + * @private */ function delegate(methodName) { OAuth.prototype[methodName] = function() { @@ -42,6 +45,7 @@ function delegate(methodName) { /** * 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() { @@ -49,23 +53,99 @@ function asyncDelegate(methodName) { }; } -/** Promisifed public API for OAuth */ 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 */ +/** + * 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 signUrl + * @memberof OAuthPromise + * @see OAuth#signUrl + */ "signUrl", // Required for testing diff --git a/lib/oauth.js b/lib/oauth.js index 122a9072..b087882f 100644 --- a/lib/oauth.js +++ b/lib/oauth.js @@ -1,4 +1,4 @@ -/** +/* * node-oauth-libre is a Node.js library for OAuth * * Copyright (C) 2010-2012 Ciaran Jessup @@ -25,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; @@ -56,6 +69,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; @@ -80,10 +106,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 { @@ -97,6 +136,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, " "); @@ -104,11 +151,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 =""; @@ -124,7 +185,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_" ) ) { @@ -135,7 +201,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 ) { @@ -154,8 +225,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 ) { @@ -174,7 +250,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) { @@ -187,6 +269,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 @@ -209,12 +297,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 ); @@ -239,12 +343,22 @@ exports.OAuth.prototype._createSignature= function(signatureBase, tokenSecret) { } 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; @@ -258,6 +372,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, @@ -339,6 +456,26 @@ 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); @@ -471,6 +608,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= {}, @@ -487,6 +629,14 @@ exports.OAuth.prototype.setClientOptions= function(options) { this._clientOptions= mergedOptions; }; +/** + * 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 + */ exports.OAuth.prototype.getOAuthAccessToken= function(oauth_token, oauth_token_secret, oauth_verifier, callback) { var extraParams= {}; if( typeof oauth_verifier == "function" ) { @@ -508,19 +658,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" ) { @@ -535,15 +714,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. @@ -563,7 +770,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; diff --git a/lib/oauth2-promise.js b/lib/oauth2-promise.js index 432ba5a7..0cb798d2 100644 --- a/lib/oauth2-promise.js +++ b/lib/oauth2-promise.js @@ -1,4 +1,4 @@ -/** +/* * node-oauth-libre is a Node.js library for OAuth * * Copyright (C) 2016 Rudolf Olah @@ -20,16 +20,29 @@ 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 }); }; -// Promisfied public API for OAuth2 +/** + * 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]; @@ -48,6 +61,11 @@ var delegatedMethods = [ "_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); diff --git a/lib/oauth2.js b/lib/oauth2.js index 753665cb..6ed77f29 100644 --- a/lib/oauth2.js +++ b/lib/oauth2.js @@ -1,4 +1,4 @@ -/** +/* * node-oauth-libre is a Node.js library for OAuth * * Copyright (C) 2010-2012 Ciaran Jessup @@ -25,50 +25,129 @@ var querystring= require('querystring'), OAuthUtils= require('./_utils'), Buffer = require('buffer').Buffer; +/** + * 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) { + /** @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 || {}; + + /** + * Whether or not to use the authorization header for a GET request + * @protected + * @default false + */ 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. +/** + * 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; } -// Sets the authorization method for Authorization header. -// e.g. Authorization: Bearer # "Bearer" is the authorization method. +/** + * 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 +/** + * 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 " +/** + * 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; }; +/** + * 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 http_library= https; // As this is OAUth2, we *assume* https unless told explicitly otherwise. @@ -78,6 +157,29 @@ exports.OAuth2.prototype._chooseHttpLibrary= function( parsedUrl ) { return http_library; }; +/** + * 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 + */ + +/** + * 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". + * + * @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} post_body The body to send if this is a POST request + * @param {string} access_token The access token + * @param {OAuth2~executeRequestCallback} callback The callback function to call when the request has been completed + */ exports.OAuth2.prototype._request= function(method, url, headers, post_body, access_token, callback) { var parsedUrl= URL.parse( url, true ); @@ -131,6 +233,21 @@ exports.OAuth2.prototype._request= function(method, url, headers, post_body, acc this._executeRequest( 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 post_body if the request method is a POST, PUT, or PATCH. + * + * @param {Object} http_library 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} post_body + * @param {OAuth2~executeRequestCallback} callback + * + * @see OAuthUtils#isAnEarlyCloseHost + */ exports.OAuth2.prototype._executeRequest= function( http_library, options, post_body, callback ) { // Some hosts *cough* google appear to close the connection early / send no content-length header // allow this behaviour. @@ -174,12 +291,36 @@ exports.OAuth2.prototype._executeRequest= function( http_library, options, post_ request.end(); } +/** + * Returns the fully-qualified authorization url including query + * string parameters. + * + * @param params Query string parameters + */ exports.OAuth2.prototype.getAuthorizeUrl= function( params ) { var params= params || {}; params['client_id'] = this._clientId; return this._baseSite + this._authorizeUrl + "?" + querystring.stringify(params); } +/** + * @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; @@ -218,11 +359,20 @@ exports.OAuth2.prototype.getOAuthAccessToken= function(code, params, callback) { }); } -// Deprecated +/** + * @deprecated + */ exports.OAuth2.prototype.getProtectedResource= function(url, access_token, callback) { this._request("GET", url, {}, "", access_token, callback ); } +/** + * Executes an OAuth2-authenticated GET request to the url provided + * + * @param {string} url The URL to make a request to + * @param {string} access_token OAuth 2.0 Access Token + * @param {OAuth2~executeRequestCallback} callback + */ exports.OAuth2.prototype.get= function(url, access_token, callback) { if( this._useAuthorizationHeaderForGET ) { var headers= {'Authorization': this.buildAuthHeader(access_token) } From c4c91edd39dd7363f63ad88dc546588d40e10843 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Tue, 27 Dec 2016 12:36:21 -0500 Subject: [PATCH 76/90] updated contributors and change history, #23 --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 84fafaee..97b201bf 100644 --- a/Readme.md +++ b/Readme.md @@ -222,6 +222,7 @@ The Google example was removed due to the need for a custom Google-specific OAut - 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 @@ -326,9 +327,10 @@ The Google example was removed due to the need for a custom Google-specific OAut * Patrick Negri - http://github.com/pnegri * Pieter Joost van de Sande - https://github.com/pjvds * Raoul Millais -* Rudolf Olah - http://neverfriday.com +* Rudolf Olah - https://neverfriday.com * Ryan LeFevre - http://meltingice.net * Tang Bo Hao - http://github.com/btspoony * Ted Goddard * bendiy - https://github.com/bendiy * rolandboon - http://rolandboon.com +* cr24osome - https://github.com/cr24osome From 5e4012f5b9fa7f1c8ac482f86bf0725b92e4d035 Mon Sep 17 00:00:00 2001 From: Carlos Castillo Oporta Date: Tue, 27 Dec 2016 14:57:37 -0600 Subject: [PATCH 77/90] Adds backward compatibility for test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We have to use both constructor because old constructor is deprecated but we still need it. And new node js versions don’t allow using old constructor. --- tests/oauth2tests.js | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/tests/oauth2tests.js b/tests/oauth2tests.js index c38c295e..f04d00f9 100644 --- a/tests/oauth2tests.js +++ b/tests/oauth2tests.js @@ -72,8 +72,14 @@ vows.describe('OAuth2').addBatch({ var authHeaderContent = oa._getAuthorizationHeader(); var headerSplit = authHeaderContent.split(' '); assert.equal(headerSplit[0], 'Basic'); - - var decodedAuthHeader = Buffer.from(headerSplit[1], 'base64').toString('ascii'); + 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, 'hello:world'); }, 'we should correctly send Authorization header encoded Base64 for token request': function (oa) { @@ -87,8 +93,14 @@ vows.describe('OAuth2').addBatch({ var headerSplit = authHeaderContent.split(' '); assert.equal("Basic", headerSplit[0]); - - var decodedAuthHeader = Buffer.from(headerSplit[1], 'base64').toString('ascii'); + 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,"clientId:clientSecret"); callback(null, "access_token=access&refresh_token=refresh"); }; From c2f2e48f65bdbb1af5b6fa4b223214aa30a0b362 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Tue, 27 Dec 2016 19:52:26 -0500 Subject: [PATCH 78/90] Revert "supporting latest node in tests for now" This reverts commit 9152ac56bb722c863408606103e969d75e8932c9. --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index b948d744..1528af29 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,3 +2,7 @@ language: node_js node_js: - "node" - "5.11" + - "4.4" + - "4.3" + - "0.12" + - "0.10" From 0ec24dbd586d1eeda5ac670ecdaeea9e10f250f3 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Sat, 21 Jan 2017 14:12:51 -0500 Subject: [PATCH 79/90] Readme: updated notes --- Readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 97b201bf..a9bc8e74 100644 --- a/Readme.md +++ b/Readme.md @@ -46,7 +46,7 @@ Install the bluebird promises library: npm install bluebird -An example of using oauth-libre with Promises: +An example of using oauth-libre with OAuth2 and Promises to access the Github API: ``` var OAuth2 = require('oauth-libre').PromiseOAuth2; @@ -89,6 +89,8 @@ 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'); From c979706d80c33d6faf4925d3ab9a98c94d0b0894 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Sat, 21 Jan 2017 14:20:17 -0500 Subject: [PATCH 80/90] Readme: added caco0516 to list of contributors --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index a9bc8e74..83b0f354 100644 --- a/Readme.md +++ b/Readme.md @@ -310,6 +310,7 @@ The Google example was removed due to the need for a custom Google-specific OAut * 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 From 4f3b053cec6a3c30982a386b732b6004c577a461 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Sat, 21 Jan 2017 14:21:35 -0500 Subject: [PATCH 81/90] bumped version from 0.9.15-beta to 0.9.15, #25 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 40d4ceee..b6597d5c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "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.15-beta", + "version": "0.9.15", "directories": { "lib": "./lib" }, From 9782763755f3bf1aadea7af919af0b232efa1ee4 Mon Sep 17 00:00:00 2001 From: Carlos Castillo Oporta Date: Wed, 25 Jan 2017 13:12:23 -0600 Subject: [PATCH 82/90] hooks for oauth2 with event emitter api * Adds EventEmitter api to request for OAuth2 client This add to events first one if for before _request method executes and second one is after _request method executes. This commit also include test cases. * Adds OAuth2 example with hooks * Updates Readme * Replace ES6 style for backward compatibility * version bump to 0.9.16 * style changes to appease Codacy --- Readme.md | 57 ++++ examples/github-oauth2-authentication.js | 83 ++++++ lib/oauth2.js | 356 ++++++++++++++--------- package.json | 3 +- tests/oauth2tests.js | 326 ++++++++++++--------- 5 files changed, 549 insertions(+), 276 deletions(-) create mode 100644 examples/github-oauth2-authentication.js diff --git a/Readme.md b/Readme.md index 83b0f354..524ed5ca 100644 --- a/Readme.md +++ b/Readme.md @@ -152,6 +152,38 @@ oauth2.getOAuthAccessToken( ); ``` +### 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 + oa2.on('request:after', (status, response) => { + console.log('Status :' + JSON.stringify(status)); + console.log('Response : ' + JSON.stringify(response)); + }); +``` + ### Test ```javascript @@ -183,6 +215,7 @@ describe('OAuth2',function() { 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. @@ -200,6 +233,28 @@ The Google example was removed due to the need for a custom Google-specific OAut 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* @@ -217,6 +272,8 @@ The Google example was removed due to the need for a custom Google-specific OAut 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.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 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/lib/oauth2.js b/lib/oauth2.js index d2d48d37..0e4791f7 100644 --- a/lib/oauth2.js +++ b/lib/oauth2.js @@ -17,13 +17,16 @@ * along with this program. If not, see . */ -var querystring= require('querystring'), - crypto= require('crypto'), - https= require('https'), - http= require('http'), - URL= require('url'), - OAuthUtils= require('./_utils'), - Buffer = require('buffer').Buffer; +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 @@ -35,39 +38,40 @@ var querystring= require('querystring'), * @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) { +exports.OAuth2 = function (clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders) { + EventEmitter.call(this); /** @protected */ - this._clientId= clientId; + this._clientId = clientId; /** @protected */ - this._clientSecret= clientSecret; + this._clientSecret = clientSecret; /** @protected */ - this._baseSite= baseSite; + this._baseSite = baseSite; /** * @protected * @default "/oauth/authorize" */ - this._authorizeUrl= authorizePath || "/oauth/authorize"; + this._authorizeUrl = authorizePath || "/oauth/authorize"; /** * @protected * @default "/oauth/access_token" */ - this._accessTokenUrl= accessTokenPath || "/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"; + this._accessTokenName = "access_token"; /** * The authorization method to use * @protected * @default "Bearer" */ - this._authMethod= "Bearer"; + this._authMethod = "Bearer"; /** * Custom headers for each request @@ -81,8 +85,13 @@ exports.OAuth2= function(clientId, clientSecret, baseSite, authorizePath, access * @protected * @default false */ - this._useAuthorizationHeaderForGET= false; -} + this._useAuthorizationHeaderForGET = false; +}; + +/** + * inherits from EventEmitter should use extends for future versions + */ +util.inherits(exports.OAuth2, EventEmitter); /** * This 'hack' method is required for sites that don't use @@ -93,9 +102,9 @@ exports.OAuth2= function(clientId, clientSecret, baseSite, authorizePath, access * @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.setAccessTokenName = function (name) { + this._accessTokenName = name; +}; /** * Sets the authorization method for Authorization header. @@ -103,11 +112,10 @@ exports.OAuth2.prototype.setAccessTokenName= function ( name ) { * * @param {string} authMethod */ -exports.OAuth2.prototype.setAuthMethod = function ( 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 @@ -116,9 +124,9 @@ exports.OAuth2.prototype.setAuthMethod = function ( authMethod ) { * * @param {boolean} useIt */ -exports.OAuth2.prototype.useAuthorizationHeaderforGET = function(useIt) { - this._useAuthorizationHeaderForGET= useIt; -} +exports.OAuth2.prototype.useAuthorizationHeaderforGET = function (useIt) { + this._useAuthorizationHeaderForGET = useIt; +}; /** * Returns the access token url constructed from the baseSite and @@ -126,9 +134,9 @@ exports.OAuth2.prototype.useAuthorizationHeaderforGET = function(useIt) { * * @return {string} */ -exports.OAuth2.prototype._getAccessTokenUrl= function() { +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. @@ -137,8 +145,8 @@ exports.OAuth2.prototype._getAccessTokenUrl= function() { * @param {string} token * @return {string} */ -exports.OAuth2.prototype.buildAuthHeader= function(token) { - return this._authMethod + ' ' + token; +exports.OAuth2.prototype.buildAuthHeader = function (token) { + return this._authMethod + " " + token; }; /** @@ -148,13 +156,13 @@ exports.OAuth2.prototype.buildAuthHeader= function(token) { * * @return {Object} http or https library */ -exports.OAuth2.prototype._chooseHttpLibrary= function( parsedUrl ) { - var http_library= https; +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; }; /** @@ -173,90 +181,167 @@ exports.OAuth2.prototype._chooseHttpLibrary= function( parsedUrl ) { * 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} post_body The body to send if this is a POST request - * @param {string} access_token The access token + * @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(method, url, headers, post_body, access_token, callback) { - - var parsedUrl= URL.parse( url, true ); - if( parsedUrl.protocol == "https:" && !parsedUrl.port ) { - parsedUrl.port= 443; +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 }; - - this._executeRequest( http_library, options, post_body, callback ); -} + + /** + * 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. + */ + + /** + * 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)); + } +}; /** * 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 post_body if the request method is a POST, PUT, or PATCH. + * Sends the postBody if the request method is a POST, PUT, or PATCH. * - * @param {Object} http_library The HTTP or HTTPS library to use to execute the request + * @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} post_body + * @param {Buffer|null} postBody * @param {OAuth2~executeRequestCallback} callback * * @see OAuthUtils#isAnEarlyCloseHost */ -exports.OAuth2.prototype._executeRequest= function( http_library, options, post_body, callback ) { +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); @@ -264,32 +349,32 @@ 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' || options.method == 'PATCH') && post_body ) { - request.write(post_body); + if ((options.method === "POST" || options.method === "PUT" || options.method === "PATCH") && postBody) { + request.write(postBody); } request.end(); -} +}; /** * Returns the fully-qualified authorization url including query @@ -297,22 +382,22 @@ exports.OAuth2.prototype._executeRequest= function( http_library, options, post_ * * @param params Query string parameters */ -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.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(); -} +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 @@ -332,65 +417,64 @@ exports.OAuth2.prototype._getAuthorizationHeader = function() { * @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 post_data= querystring.stringify( params ); - - var post_headers= { - 'Content-Type': 'application/x-www-form-urlencoded', - 'Authorization': this._getAuthorizationHeader() +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(), post_headers, post_data, null, function(error, data, response) { - if( error ) callback(error); - else { + 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 ); -} +exports.OAuth2.prototype.getProtectedResource = function (url, accessToken, callback) { + this._request("GET", url, {}, "", accessToken, callback); +}; /** * Executes an OAuth2-authenticated GET request to the url provided * * @param {string} url The URL to make a request to - * @param {string} access_token OAuth 2.0 Access Token + * @param {string} accessToken OAuth 2.0 Access Token * @param {OAuth2~executeRequestCallback} 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= {}; +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/package.json b/package.json index b6597d5c..8323c734 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "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.15", + "version": "0.9.16", "directories": { "lib": "./lib" }, @@ -19,6 +19,7 @@ }, "devDependencies": { "jsdoc": "^3.4.3", + "randomstring": "^1.1.5", "vows": "0.5.x" }, "scripts": { diff --git a/tests/oauth2tests.js b/tests/oauth2tests.js index 45e58164..a9a533ad 100644 --- a/tests/oauth2tests.js +++ b/tests/oauth2tests.js @@ -17,19 +17,68 @@ * 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"); +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) { +vows.describe('OAuth2').addBatch({ + '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.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 () { @@ -42,7 +91,7 @@ vows.describe("OAuth2").addBatch({ }); assert.ok(callbackCalled); }, - "we should treat a 200 response as a success": function (oa) { + 'we should treat a 200 response as a success': function (oa) { var callbackCalled = false; var httpLibrary = { request: function () { @@ -56,198 +105,197 @@ vows.describe("OAuth2").addBatch({ assert.ok(callbackCalled); } }, - "When handling the access token response": { - "we should correctly extract the token if received as form-data": function (oa) { + '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"); + callback(null, 'access_token=access&refresh_token=refresh'); }; - oa.getOAuthAccessToken("", {}, function (error, accessToken, refreshToken) { - assert.equal(accessToken, "access"); - assert.equal(refreshToken, "refresh"); + oa.getOAuthAccessToken('', {}, function (error, accessToken, refreshToken) { + assert.equal(accessToken, 'access'); + assert.equal(refreshToken, 'refresh'); }); }, - "we should correctly create base64-encoded authorization header from client id and secret": function (oa) { - oa._clientId = "hello"; - oa._clientSecret = "world"; + '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 = ""; + var headerSplit = authHeaderContent.split(' '); + assert.equal(headerSplit[0], 'Basic'); + var decodedAuthHeader = ''; try { // newer node versions - decodedAuthHeader = Buffer.from(headerSplit[1], "base64").toString("ascii"); + decodedAuthHeader = Buffer.from(headerSplit[1], 'base64').toString('ascii'); } catch (e) { // node version 5 and older - decodedAuthHeader = new Buffer(headerSplit[1], "base64").toString("ascii"); + decodedAuthHeader = new Buffer(headerSplit[1], 'base64').toString('ascii'); } - assert.equal(decodedAuthHeader, oa._clientId + ":" + oa._clientSecret); + assert.equal(decodedAuthHeader, oa._clientId + ':' + oa._clientSecret); }, - "we should correctly send Authorization header encoded Base64 for token request": function (oa) { + '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 = ""; + 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"); + decodedAuthHeader = Buffer.from(headerSplit[1], 'base64').toString('ascii'); } catch (e) { // node version 5 and older - decodedAuthHeader = new Buffer(headerSplit[1], "base64").toString("ascii"); + decodedAuthHeader = new Buffer(headerSplit[1], 'base64').toString('ascii'); } - assert.equal(decodedAuthHeader, oa._clientId + ":" + oa._clientSecret); - callback(null, "access_token=access&refresh_token=refresh"); + 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.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"); + 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); + '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"); + 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) { + '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"); + 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) { + '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"); + 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"); + 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) { + '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); + assert.isTrue(postBody.indexOf('code=xsds23') !== -1); }; - oa.getOAuthAccessToken("xsds23", {}); + 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) { + '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); + assert.isTrue(postBody.indexOf('code=xsds23') !== -1); }; - oa.getOAuthAccessToken("xsds23", { "grant_type": "refresh_toucan" }); + 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) { + '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); + 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" }); + 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) { + '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.equal(headers['Authorization'], 'Bearer abcd5'); assert.isNull(accessToken); }; oa.useAuthorizationHeaderforGET(true); - oa.get("", "abcd5"); + 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) { + '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.equal(headers['Authorization'], 'Basic cdg2'); assert.isNull(accessToken); }; oa.useAuthorizationHeaderforGET(true); - oa.setAuthMethod("Basic"); - oa.get("", "cdg2"); + 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 accessToken should be being passed to _request": function (oa) { + '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"); + assert.isUndefined(headers['Authorization']); + assert.equal(accessToken, 'abcd5'); }; oa.useAuthorizationHeaderforGET(false); - oa.get("", "abcd5"); + 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) { + '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"); + assert.equal(options.headers['SomeHeader'], '123'); }; - oa.get("", {}); - }, + 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) { + '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 { + 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"); + assert.equal(body, 'THIS_IS_A_POST_BODY_STRING'); } }; } }; }; - oa._request("POST", "", { "Content-Type": "text/plain" }, "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) { + '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 { + 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) { @@ -258,44 +306,44 @@ vows.describe("OAuth2").addBatch({ }; } }; - } - oa._request("POST", "", { "Content-Type": "application/octet-stream" }, new Buffer([1,2,3,4])); + }; + 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) { + '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 { + 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"); + assert.equal(body, 'THIS_IS_A_PUT_BODY_STRING'); } }; } }; }; - oa._request("PUT", "", { "Content-Type": "text/plain" }, "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; + '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 { + 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) { @@ -307,30 +355,30 @@ vows.describe("OAuth2").addBatch({ } }; }; - oa._request("PUT", "", { "Content-Type": "application/octet-stream" }, new Buffer([1,2,3,4])); + 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) { + '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"); + assert.equal(options.headers['User-Agent'], '123Agent'); }; - oa.get("", {}); + 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) { + '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"); + assert.equal(options.headers['User-Agent'], 'Node-oauth'); }; - oa.get("", {}); + oa.get('', {}); } } } From 117202f11144c19bde5841d45e4dd07037a48dba Mon Sep 17 00:00:00 2001 From: Ryan Ausanka-Crues Date: Fri, 28 Jul 2017 19:18:35 -0700 Subject: [PATCH 83/90] Allow content-type header to be set when making requests (#30) * Allow passing Content-Type header to OAuth constructor to set _defaultContentType * Added _defaultContentType instance variable to OAuth * Added setDefaultContentType method to set Content-Type header to something other than application/x-www-form-urlencoded when creating a request with post/get/etc * README.md: Add setting content type to 'application/json' to the example for OAuth1 and change requires to reference 'oauth-libre' instead of 'oauth' --- Readme.md | 7 +++-- lib/oauth.js | 10 ++++++- tests/oauthtests.js | 67 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 4 deletions(-) diff --git a/Readme.md b/Readme.md index 524ed5ca..129a974f 100644 --- a/Readme.md +++ b/Readme.md @@ -93,7 +93,7 @@ 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( @@ -105,6 +105,7 @@ 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 @@ -123,7 +124,7 @@ describe('OAuth1.0',function(){ ### Usage ```javascript -var OAuth2 = require('oauth').OAuth2; +var OAuth2 = require('oauth-libre').OAuth2; console.log("Login here to get an authorization code: " + oauth2.getAuthorizeUrl()); @@ -188,7 +189,7 @@ This event is emitted after the request has been executed, we receive informatio ```javascript describe('OAuth2',function() { - var OAuth = require('oauth'); + var OAuth = require('oauth-libre'); it('gets bearer token', function(done){ var OAuth2 = OAuth.OAuth2; diff --git a/lib/oauth.js b/lib/oauth.js index 2767beed..25fe5758 100644 --- a/lib/oauth.js +++ b/lib/oauth.js @@ -60,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"} @@ -480,7 +485,7 @@ exports.OAuth.prototype._performSecureRequest= function( oauth_token, oauth_toke 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; @@ -628,6 +633,9 @@ exports.OAuth.prototype.setClientOptions= function(options) { this._clientOptions= mergedOptions; }; +exports.OAuth.prototype.setDefaultContentType= function(contentType) { + this._defaultContentType = contentType; +}; /** * Performs a request to retrieve the OAuth Access Token diff --git a/tests/oauthtests.js b/tests/oauthtests.js index 3a8a1740..d7e60e37 100644 --- a/tests/oauthtests.js +++ b/tests/oauthtests.js @@ -349,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' : { From 56441823eaf291012beee35ed761c2e9e4e30fbd Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Tue, 1 Aug 2017 20:53:03 -0400 Subject: [PATCH 84/90] 0.9.17 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8323c734..0ea345b0 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "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.16", + "version": "0.9.17", "directories": { "lib": "./lib" }, From fb18d9f646b69f319b0a0390446fcef73e73e9f6 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Tue, 1 Aug 2017 21:33:16 -0400 Subject: [PATCH 85/90] Readme.md: updated releases list to add 0.9.17 and updated contributors list to add @rausanka --- Readme.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Readme.md b/Readme.md index 129a974f..acd0828f 100644 --- a/Readme.md +++ b/Readme.md @@ -273,6 +273,8 @@ The Google example was removed due to the need for a custom Google-specific OAut 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 @@ -389,6 +391,7 @@ The Google example was removed due to the need for a custom Google-specific OAut * 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 * Ted Goddard From c9ac4ed235a656b8bb03793569c1f2df39972bda Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 23 Aug 2017 10:37:55 -0400 Subject: [PATCH 86/90] Create CODE_OF_CONDUCT.md --- CODE_OF_CONDUCT.md | 74 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 CODE_OF_CONDUCT.md 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/ From 4e08e57d7b1681490812c3b99051f1af65bafec6 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 23 Aug 2017 10:38:51 -0400 Subject: [PATCH 87/90] Create CONTRIBUTING.md --- CONTRIBUTING.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 CONTRIBUTING.md 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 From 55145e4d4d627cb962dc883ec38fe2e57ccf8a64 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Mon, 18 Sep 2017 16:40:04 -0400 Subject: [PATCH 88/90] readme: added section on how to help the project --- Readme.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Readme.md b/Readme.md index acd0828f..370f8556 100644 --- a/Readme.md +++ b/Readme.md @@ -10,6 +10,19 @@ Tested against Twitter (http://twitter.com), term.ie (http://term.ie/oauth/examp 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) +## 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. From 746a343245e48df5239bafc6a3bb532c5bdf0ab8 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Wed, 28 Feb 2018 11:00:28 -0500 Subject: [PATCH 89/90] oauth-promise: delegating setDefaultContentType (#32) --- lib/oauth-promise.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib/oauth-promise.js b/lib/oauth-promise.js index 305c694c..8165cdfc 100644 --- a/lib/oauth-promise.js +++ b/lib/oauth-promise.js @@ -139,6 +139,14 @@ var delegatedMethods = [ * @see OAuth#setClientOptions */ "setClientOptions", + + /** + * @instance + * @method setDefaultContentType + * @memberof OAuthPromise + * @see OAuth#setDefaultContentType + */ + "setDefaultContentType", /** * @instance From 6e2c3a5d097cf1f6249f17d7aaf458e5693c9663 Mon Sep 17 00:00:00 2001 From: Rudolf Olah Date: Thu, 6 Dec 2018 13:07:53 -0500 Subject: [PATCH 90/90] Update Readme.md --- Readme.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 370f8556..d43462f3 100644 --- a/Readme.md +++ b/Readme.md @@ -1,8 +1,10 @@ # node-oauth -[![Build Status](https://travis-ci.org/omouse/node-oauth-libre.svg)](https://travis-ci.org/omouse/node-oauth-libre) +[![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%2Fomouse%2Fnode-oauth-libre) +[![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.