pax_global_header 0000666 0000000 0000000 00000000064 13111303321 0014476 g ustar 00root root 0000000 0000000 52 comment=a11909aafc72f850d1669cc7cc9fbb4af0604c8e
oauth-ruby-0.5.3/ 0000775 0000000 0000000 00000000000 13111303321 0013602 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/.codeclimate.yml 0000664 0000000 0000000 00000000305 13111303321 0016652 0 ustar 00root root 0000000 0000000 ---
engines:
duplication:
enabled: true
config:
languages:
- ruby
fixme:
enabled: true
rubocop:
enabled: true
ratings:
paths:
- "**.rb"
exclude_paths:
- test/
oauth-ruby-0.5.3/.gemtest 0000664 0000000 0000000 00000000000 13111303321 0015241 0 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/.gitignore 0000664 0000000 0000000 00000000044 13111303321 0015570 0 ustar 00root root 0000000 0000000 .bundle
Gemfile.lock
coverage
*.gem
oauth-ruby-0.5.3/.rubocop.yml 0000664 0000000 0000000 00000112355 13111303321 0016063 0 ustar 00root root 0000000 0000000 AllCops:
DisabledByDefault: true
#################### Lint ################################
Lint/AmbiguousOperator:
Description: >-
Checks for ambiguous operators in the first argument of a
method invocation without parentheses.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#parens-as-args'
Enabled: true
Lint/AmbiguousRegexpLiteral:
Description: >-
Checks for ambiguous regexp literals in the first argument of
a method invocation without parenthesis.
Enabled: true
Lint/AssignmentInCondition:
Description: "Don't use assignment in conditions."
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#safe-assignment-in-condition'
Enabled: true
Lint/BlockAlignment:
Description: 'Align block ends correctly.'
Enabled: true
Lint/CircularArgumentReference:
Description: "Don't refer to the keyword argument in the default value."
Enabled: true
Lint/ConditionPosition:
Description: >-
Checks for condition placed in a confusing position relative to
the keyword.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#same-line-condition'
Enabled: true
Lint/Debugger:
Description: 'Check for debugger calls.'
Enabled: true
Lint/DefEndAlignment:
Description: 'Align ends corresponding to defs correctly.'
Enabled: true
Lint/DeprecatedClassMethods:
Description: 'Check for deprecated class method calls.'
Enabled: true
Lint/DuplicateMethods:
Description: 'Check for duplicate methods calls.'
Enabled: true
Lint/EachWithObjectArgument:
Description: 'Check for immutable argument given to each_with_object.'
Enabled: true
Lint/ElseLayout:
Description: 'Check for odd code arrangement in an else block.'
Enabled: true
Lint/EmptyEnsure:
Description: 'Checks for empty ensure block.'
Enabled: true
Lint/EmptyInterpolation:
Description: 'Checks for empty string interpolation.'
Enabled: true
Lint/EndAlignment:
Description: 'Align ends correctly.'
Enabled: true
Lint/EndInMethod:
Description: 'END blocks should not be placed inside method definitions.'
Enabled: true
Lint/EnsureReturn:
Description: 'Do not use return in an ensure block.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-return-ensure'
Enabled: true
Lint/Eval:
Description: 'The use of eval represents a serious security risk.'
Enabled: true
Lint/FormatParameterMismatch:
Description: 'The number of parameters to format/sprint must match the fields.'
Enabled: true
Lint/HandleExceptions:
Description: "Don't suppress exception."
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#dont-hide-exceptions'
Enabled: true
Lint/InvalidCharacterLiteral:
Description: >-
Checks for invalid character literals with a non-escaped
whitespace character.
Enabled: true
Lint/LiteralInCondition:
Description: 'Checks of literals used in conditions.'
Enabled: true
Lint/LiteralInInterpolation:
Description: 'Checks for literals used in interpolation.'
Enabled: true
Lint/Loop:
Description: >-
Use Kernel#loop with break rather than begin/end/until or
begin/end/while for post-loop tests.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#loop-with-break'
Enabled: true
Lint/NestedMethodDefinition:
Description: 'Do not use nested method definitions.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-nested-methods'
Enabled: true
Lint/NonLocalExitFromIterator:
Description: 'Do not use return in iterator to cause non-local exit.'
Enabled: true
Lint/ParenthesesAsGroupedExpression:
Description: >-
Checks for method calls with a space before the opening
parenthesis.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#parens-no-spaces'
Enabled: true
Lint/RequireParentheses:
Description: >-
Use parentheses in the method call to avoid confusion
about precedence.
Enabled: true
Lint/RescueException:
Description: 'Avoid rescuing the Exception class.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-blind-rescues'
Enabled: true
Lint/ShadowingOuterLocalVariable:
Description: >-
Do not use the same name as outer local variable
for block arguments or block local variables.
Enabled: true
Lint/StringConversionInInterpolation:
Description: 'Checks for Object#to_s usage in string interpolation.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-to-s'
Enabled: true
Lint/UnderscorePrefixedVariableName:
Description: 'Do not use prefix `_` for a variable that is used.'
Enabled: true
Lint/UnneededDisable:
Description: >-
Checks for rubocop:disable comments that can be removed.
Note: this cop is not disabled when disabling all cops.
It must be explicitly disabled.
Enabled: true
Lint/UnusedBlockArgument:
Description: 'Checks for unused block arguments.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#underscore-unused-vars'
Enabled: true
Lint/UnusedMethodArgument:
Description: 'Checks for unused method arguments.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#underscore-unused-vars'
Enabled: true
Lint/UnreachableCode:
Description: 'Unreachable code.'
Enabled: true
Lint/UselessAccessModifier:
Description: 'Checks for useless access modifiers.'
Enabled: true
Lint/UselessAssignment:
Description: 'Checks for useless assignment to a local variable.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#underscore-unused-vars'
Enabled: true
Lint/UselessComparison:
Description: 'Checks for comparison of something with itself.'
Enabled: true
Lint/UselessElseWithoutRescue:
Description: 'Checks for useless `else` in `begin..end` without `rescue`.'
Enabled: true
Lint/UselessSetterCall:
Description: 'Checks for useless setter call to a local variable.'
Enabled: true
Lint/Void:
Description: 'Possible use of operator/literal/variable in void context.'
Enabled: true
###################### Metrics ####################################
Metrics/AbcSize:
Description: >-
A calculated magnitude based on number of assignments,
branches, and conditions.
Reference: 'http://c2.com/cgi/wiki?AbcMetric'
Enabled: false
Max: 20
Metrics/BlockNesting:
Description: 'Avoid excessive block nesting'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#three-is-the-number-thou-shalt-count'
Enabled: true
Max: 4
Metrics/ClassLength:
Description: 'Avoid classes longer than 250 lines of code.'
Enabled: true
Max: 250
Metrics/CyclomaticComplexity:
Description: >-
A complexity metric that is strongly correlated to the number
of test cases needed to validate a method.
Enabled: true
Metrics/LineLength:
Description: 'Limit lines to 80 characters.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#80-character-limits'
Enabled: false
Metrics/MethodLength:
Description: 'Avoid methods longer than 30 lines of code.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#short-methods'
Enabled: true
Max: 30
Metrics/ModuleLength:
Description: 'Avoid modules longer than 250 lines of code.'
Enabled: true
Max: 250
Metrics/ParameterLists:
Description: 'Avoid parameter lists longer than three or four parameters.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#too-many-params'
Enabled: true
Metrics/PerceivedComplexity:
Description: >-
A complexity metric geared towards measuring complexity for a
human reader.
Enabled: false
##################### Performance #############################
Performance/Count:
Description: >-
Use `count` instead of `select...size`, `reject...size`,
`select...count`, `reject...count`, `select...length`,
and `reject...length`.
Enabled: true
Performance/Detect:
Description: >-
Use `detect` instead of `select.first`, `find_all.first`,
`select.last`, and `find_all.last`.
Reference: 'https://github.com/JuanitoFatas/fast-ruby#enumerabledetect-vs-enumerableselectfirst-code'
Enabled: true
Performance/FlatMap:
Description: >-
Use `Enumerable#flat_map`
instead of `Enumerable#map...Array#flatten(1)`
or `Enumberable#collect..Array#flatten(1)`
Reference: 'https://github.com/JuanitoFatas/fast-ruby#enumerablemaparrayflatten-vs-enumerableflat_map-code'
Enabled: true
EnabledForFlattenWithoutParams: false
# If enabled, this cop will warn about usages of
# `flatten` being called without any parameters.
# This can be dangerous since `flat_map` will only flatten 1 level, and
# `flatten` without any parameters can flatten multiple levels.
Performance/ReverseEach:
Description: 'Use `reverse_each` instead of `reverse.each`.'
Reference: 'https://github.com/JuanitoFatas/fast-ruby#enumerablereverseeach-vs-enumerablereverse_each-code'
Enabled: true
Performance/Sample:
Description: >-
Use `sample` instead of `shuffle.first`,
`shuffle.last`, and `shuffle[Fixnum]`.
Reference: 'https://github.com/JuanitoFatas/fast-ruby#arrayshufflefirst-vs-arraysample-code'
Enabled: true
Performance/Size:
Description: >-
Use `size` instead of `count` for counting
the number of elements in `Array` and `Hash`.
Reference: 'https://github.com/JuanitoFatas/fast-ruby#arraycount-vs-arraysize-code'
Enabled: true
Performance/StringReplacement:
Description: >-
Use `tr` instead of `gsub` when you are replacing the same
number of characters. Use `delete` instead of `gsub` when
you are deleting characters.
Reference: 'https://github.com/JuanitoFatas/fast-ruby#stringgsub-vs-stringtr-code'
Enabled: true
##################### Rails ##################################
Rails/ActionFilter:
Description: 'Enforces consistent use of action filter methods.'
Enabled: false
Rails/Date:
Description: >-
Checks the correct usage of date aware methods,
such as Date.today, Date.current etc.
Enabled: false
Rails/Delegate:
Description: 'Prefer delegate method for delegations.'
Enabled: false
Rails/FindBy:
Description: 'Prefer find_by over where.first.'
Enabled: false
Rails/FindEach:
Description: 'Prefer all.find_each over all.find.'
Enabled: false
Rails/HasAndBelongsToMany:
Description: 'Prefer has_many :through to has_and_belongs_to_many.'
Enabled: false
Rails/Output:
Description: 'Checks for calls to puts, print, etc.'
Enabled: false
Rails/ReadWriteAttribute:
Description: >-
Checks for read_attribute(:attr) and
write_attribute(:attr, val).
Enabled: false
Rails/ScopeArgs:
Description: 'Checks the arguments of ActiveRecord scopes.'
Enabled: false
Rails/TimeZone:
Description: 'Checks the correct usage of time zone aware methods.'
StyleGuide: 'https://github.com/bbatsov/rails-style-guide#time'
Reference: 'http://danilenko.org/2012/7/6/rails_timezones'
Enabled: false
Rails/Validation:
Description: 'Use validates :attribute, hash of validations.'
Enabled: false
################## Style #################################
Style/AccessModifierIndentation:
Description: Check indentation of private/protected visibility modifiers.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#indent-public-private-protected'
Enabled: false
Style/AccessorMethodName:
Description: Check the naming of accessor methods for get_/set_.
Enabled: false
Style/Alias:
Description: 'Use alias_method instead of alias.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#alias-method'
Enabled: false
Style/AlignArray:
Description: >-
Align the elements of an array literal if they span more than
one line.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#align-multiline-arrays'
Enabled: false
Style/AlignHash:
Description: >-
Align the elements of a hash literal if they span more than
one line.
Enabled: false
Style/AlignParameters:
Description: >-
Align the parameters of a method call if they span more
than one line.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-double-indent'
Enabled: false
Style/AndOr:
Description: 'Use &&/|| instead of and/or.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-and-or-or'
Enabled: false
Style/ArrayJoin:
Description: 'Use Array#join instead of Array#*.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#array-join'
Enabled: false
Style/AsciiComments:
Description: 'Use only ascii symbols in comments.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#english-comments'
Enabled: false
Style/AsciiIdentifiers:
Description: 'Use only ascii symbols in identifiers.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#english-identifiers'
Enabled: false
Style/Attr:
Description: 'Checks for uses of Module#attr.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#attr'
Enabled: false
Style/BeginBlock:
Description: 'Avoid the use of BEGIN blocks.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-BEGIN-blocks'
Enabled: false
Style/BarePercentLiterals:
Description: 'Checks if usage of %() or %Q() matches configuration.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#percent-q-shorthand'
Enabled: false
Style/BlockComments:
Description: 'Do not use block comments.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-block-comments'
Enabled: false
Style/BlockEndNewline:
Description: 'Put end statement of multiline block on its own line.'
Enabled: false
Style/BlockDelimiters:
Description: >-
Avoid using {...} for multi-line blocks (multiline chaining is
always ugly).
Prefer {...} over do...end for single-line blocks.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#single-line-blocks'
Enabled: false
Style/BracesAroundHashParameters:
Description: 'Enforce braces style around hash parameters.'
Enabled: false
Style/CaseEquality:
Description: 'Avoid explicit use of the case equality operator(===).'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-case-equality'
Enabled: false
Style/CaseIndentation:
Description: 'Indentation of when in a case/when/[else/]end.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#indent-when-to-case'
Enabled: false
Style/CharacterLiteral:
Description: 'Checks for uses of character literals.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-character-literals'
Enabled: false
Style/ClassAndModuleCamelCase:
Description: 'Use CamelCase for classes and modules.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#camelcase-classes'
Enabled: false
Style/ClassAndModuleChildren:
Description: 'Checks style of children classes and modules.'
Enabled: false
Style/ClassCheck:
Description: 'Enforces consistent use of `Object#is_a?` or `Object#kind_of?`.'
Enabled: false
Style/ClassMethods:
Description: 'Use self when defining module/class methods.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#def-self-class-methods'
Enabled: false
Style/ClassVars:
Description: 'Avoid the use of class variables.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-class-vars'
Enabled: false
Style/ClosingParenthesisIndentation:
Description: 'Checks the indentation of hanging closing parentheses.'
Enabled: false
Style/ColonMethodCall:
Description: 'Do not use :: for method call.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#double-colons'
Enabled: false
Style/CommandLiteral:
Description: 'Use `` or %x around command literals.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#percent-x'
Enabled: false
Style/CommentAnnotation:
Description: 'Checks formatting of annotation comments.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#annotate-keywords'
Enabled: false
Style/CommentIndentation:
Description: 'Indentation of comments.'
Enabled: false
Style/ConstantName:
Description: 'Constants should use SCREAMING_SNAKE_CASE.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#screaming-snake-case'
Enabled: false
Style/DefWithParentheses:
Description: 'Use def with parentheses when there are arguments.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#method-parens'
Enabled: false
Style/DeprecatedHashMethods:
Description: 'Checks for use of deprecated Hash methods.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#hash-key'
Enabled: false
Style/Documentation:
Description: 'Document classes and non-namespace modules.'
Enabled: false
Style/DotPosition:
Description: 'Checks the position of the dot in multi-line method calls.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#consistent-multi-line-chains'
Enabled: false
Style/DoubleNegation:
Description: 'Checks for uses of double negation (!!).'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-bang-bang'
Enabled: false
Style/EachWithObject:
Description: 'Prefer `each_with_object` over `inject` or `reduce`.'
Enabled: false
Style/ElseAlignment:
Description: 'Align elses and elsifs correctly.'
Enabled: false
Style/EmptyElse:
Description: 'Avoid empty else-clauses.'
Enabled: false
Style/EmptyLineBetweenDefs:
Description: 'Use empty lines between defs.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#empty-lines-between-methods'
Enabled: false
Style/EmptyLines:
Description: "Don't use several empty lines in a row."
Enabled: false
Style/EmptyLinesAroundAccessModifier:
Description: "Keep blank lines around access modifiers."
Enabled: false
Style/EmptyLinesAroundBlockBody:
Description: "Keeps track of empty lines around block bodies."
Enabled: false
Style/EmptyLinesAroundClassBody:
Description: "Keeps track of empty lines around class bodies."
Enabled: false
Style/EmptyLinesAroundModuleBody:
Description: "Keeps track of empty lines around module bodies."
Enabled: false
Style/EmptyLinesAroundMethodBody:
Description: "Keeps track of empty lines around method bodies."
Enabled: false
Style/EmptyLiteral:
Description: 'Prefer literals to Array.new/Hash.new/String.new.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#literal-array-hash'
Enabled: false
Style/EndBlock:
Description: 'Avoid the use of END blocks.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-END-blocks'
Enabled: false
Style/EndOfLine:
Description: 'Use Unix-style line endings.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#crlf'
Enabled: false
Style/EvenOdd:
Description: 'Favor the use of Fixnum#even? && Fixnum#odd?'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#predicate-methods'
Enabled: false
Style/ExtraSpacing:
Description: 'Do not use unnecessary spacing.'
Enabled: false
Style/FileName:
Description: 'Use snake_case for source file names.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#snake-case-files'
Enabled: false
Style/InitialIndentation:
Description: >-
Checks the indentation of the first non-blank non-comment line in a file.
Enabled: false
Style/FirstParameterIndentation:
Description: 'Checks the indentation of the first parameter in a method call.'
Enabled: false
Style/FlipFlop:
Description: 'Checks for flip flops'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-flip-flops'
Enabled: false
Style/For:
Description: 'Checks use of for or each in multiline loops.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-for-loops'
Enabled: false
Style/FormatString:
Description: 'Enforce the use of Kernel#sprintf, Kernel#format or String#%.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#sprintf'
Enabled: false
Style/GlobalVars:
Description: 'Do not introduce global variables.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#instance-vars'
Reference: 'http://www.zenspider.com/Languages/Ruby/QuickRef.html'
Enabled: false
Style/GuardClause:
Description: 'Check for conditionals that can be replaced with guard clauses'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals'
Enabled: false
Style/HashSyntax:
Description: >-
Prefer Ruby 1.9 hash syntax { a: 1, b: 2 } over 1.8 syntax
{ :a => 1, :b => 2 }.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#hash-literals'
Enabled: false
Style/IfUnlessModifier:
Description: >-
Favor modifier if/unless usage when you have a
single-line body.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#if-as-a-modifier'
Enabled: false
Style/IfWithSemicolon:
Description: 'Do not use if x; .... Use the ternary operator instead.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-semicolon-ifs'
Enabled: false
Style/IndentationConsistency:
Description: 'Keep indentation straight.'
Enabled: false
Style/IndentationWidth:
Description: 'Use 2 spaces for indentation.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#spaces-indentation'
Enabled: false
Style/IndentArray:
Description: >-
Checks the indentation of the first element in an array
literal.
Enabled: false
Style/IndentHash:
Description: 'Checks the indentation of the first key in a hash literal.'
Enabled: false
Style/InfiniteLoop:
Description: 'Use Kernel#loop for infinite loops.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#infinite-loop'
Enabled: false
Style/Lambda:
Description: 'Use the new lambda literal syntax for single-line blocks.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#lambda-multi-line'
Enabled: false
Style/LambdaCall:
Description: 'Use lambda.call(...) instead of lambda.(...).'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#proc-call'
Enabled: false
Style/LeadingCommentSpace:
Description: 'Comments should start with a space.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#hash-space'
Enabled: false
Style/LineEndConcatenation:
Description: >-
Use \ instead of + or << to concatenate two string literals at
line end.
Enabled: false
Style/MethodCallParentheses:
Description: 'Do not use parentheses for method calls with no arguments.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-args-no-parens'
Enabled: false
Style/MethodDefParentheses:
Description: >-
Checks if the method definitions have or don't have
parentheses.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#method-parens'
Enabled: false
Style/MethodName:
Description: 'Use the configured style when naming methods.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#snake-case-symbols-methods-vars'
Enabled: false
Style/ModuleFunction:
Description: 'Checks for usage of `extend self` in modules.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#module-function'
Enabled: false
Style/MultilineBlockChain:
Description: 'Avoid multi-line chains of blocks.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#single-line-blocks'
Enabled: false
Style/MultilineBlockLayout:
Description: 'Ensures newlines after multiline block do statements.'
Enabled: false
Style/MultilineIfThen:
Description: 'Do not use then for multi-line if/unless.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-then'
Enabled: false
Style/MultilineOperationIndentation:
Description: >-
Checks indentation of binary operations that span more than
one line.
Enabled: false
Style/MultilineTernaryOperator:
Description: >-
Avoid multi-line ?: (the ternary operator);
use if/unless instead.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-multiline-ternary'
Enabled: false
Style/NegatedIf:
Description: >-
Favor unless over if for negative conditions
(or control flow or).
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#unless-for-negatives'
Enabled: false
Style/NegatedWhile:
Description: 'Favor until over while for negative conditions.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#until-for-negatives'
Enabled: false
Style/NestedTernaryOperator:
Description: 'Use one expression per branch in a ternary operator.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-nested-ternary'
Enabled: false
Style/Next:
Description: 'Use `next` to skip iteration instead of a condition at the end.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals'
Enabled: false
Style/NilComparison:
Description: 'Prefer x.nil? to x == nil.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#predicate-methods'
Enabled: false
Style/NonNilCheck:
Description: 'Checks for redundant nil checks.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-non-nil-checks'
Enabled: false
Style/Not:
Description: 'Use ! instead of not.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#bang-not-not'
Enabled: false
Style/NumericLiterals:
Description: >-
Add underscores to large numeric literals to improve their
readability.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#underscores-in-numerics'
Enabled: false
Style/OneLineConditional:
Description: >-
Favor the ternary operator(?:) over
if/then/else/end constructs.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#ternary-operator'
Enabled: false
Style/OpMethod:
Description: 'When defining binary operators, name the argument other.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#other-arg'
Enabled: false
Style/OptionalArguments:
Description: >-
Checks for optional arguments that do not appear at the end
of the argument list
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#optional-arguments'
Enabled: false
Style/ParallelAssignment:
Description: >-
Check for simple usages of parallel assignment.
It will only warn when the number of variables
matches on both sides of the assignment.
This also provides performance benefits
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#parallel-assignment'
Enabled: false
Style/ParenthesesAroundCondition:
Description: >-
Don't use parentheses around the condition of an
if/unless/while.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-parens-if'
Enabled: false
Style/PercentLiteralDelimiters:
Description: 'Use `%`-literal delimiters consistently'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#percent-literal-braces'
Enabled: false
Style/PercentQLiterals:
Description: 'Checks if uses of %Q/%q match the configured preference.'
Enabled: false
Style/PerlBackrefs:
Description: 'Avoid Perl-style regex back references.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-perl-regexp-last-matchers'
Enabled: false
Style/PredicateName:
Description: 'Check the names of predicate methods.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#bool-methods-qmark'
Enabled: false
Style/Proc:
Description: 'Use proc instead of Proc.new.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#proc'
Enabled: false
Style/RaiseArgs:
Description: 'Checks the arguments passed to raise/fail.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#exception-class-messages'
Enabled: false
Style/RedundantBegin:
Description: "Don't use begin blocks when they are not needed."
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#begin-implicit'
Enabled: false
Style/RedundantException:
Description: "Checks for an obsolete RuntimeException argument in raise/fail."
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-explicit-runtimeerror'
Enabled: false
Style/RedundantReturn:
Description: "Don't use return where it's not required."
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-explicit-return'
Enabled: false
Style/RedundantSelf:
Description: "Don't use self where it's not needed."
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-self-unless-required'
Enabled: false
Style/RegexpLiteral:
Description: 'Use / or %r around regular expressions.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#percent-r'
Enabled: false
Style/RescueEnsureAlignment:
Description: 'Align rescues and ensures correctly.'
Enabled: false
Style/RescueModifier:
Description: 'Avoid using rescue in its modifier form.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-rescue-modifiers'
Enabled: false
Style/SelfAssignment:
Description: >-
Checks for places where self-assignment shorthand should have
been used.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#self-assignment'
Enabled: false
Style/Semicolon:
Description: "Don't use semicolons to terminate expressions."
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-semicolon'
Enabled: false
Style/SignalException:
Description: 'Checks for proper usage of fail and raise.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#fail-method'
Enabled: false
Style/SingleLineBlockParams:
Description: 'Enforces the names of some block params.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#reduce-blocks'
Enabled: false
Style/SingleLineMethods:
Description: 'Avoid single-line methods.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-single-line-methods'
Enabled: false
Style/SpaceBeforeFirstArg:
Description: >-
Checks that exactly one space is used between a method name
and the first argument for method calls without parentheses.
Enabled: true
Style/SpaceAfterColon:
Description: 'Use spaces after colons.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#spaces-operators'
Enabled: false
Style/SpaceAfterComma:
Description: 'Use spaces after commas.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#spaces-operators'
Enabled: false
Style/SpaceAroundKeyword:
Description: 'Use spaces around keywords.'
Enabled: false
Style/SpaceAfterMethodName:
Description: >-
Do not put a space between a method name and the opening
parenthesis in a method definition.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#parens-no-spaces'
Enabled: false
Style/SpaceAfterNot:
Description: Tracks redundant space after the ! operator.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-space-bang'
Enabled: false
Style/SpaceAfterSemicolon:
Description: 'Use spaces after semicolons.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#spaces-operators'
Enabled: false
Style/SpaceBeforeBlockBraces:
Description: >-
Checks that the left block brace has or doesn't have space
before it.
Enabled: false
Style/SpaceBeforeComma:
Description: 'No spaces before commas.'
Enabled: false
Style/SpaceBeforeComment:
Description: >-
Checks for missing space between code and a comment on the
same line.
Enabled: false
Style/SpaceBeforeSemicolon:
Description: 'No spaces before semicolons.'
Enabled: false
Style/SpaceInsideBlockBraces:
Description: >-
Checks that block braces have or don't have surrounding space.
For blocks taking parameters, checks that the left brace has
or doesn't have trailing space.
Enabled: false
Style/SpaceAroundBlockParameters:
Description: 'Checks the spacing inside and after block parameters pipes.'
Enabled: false
Style/SpaceAroundEqualsInParameterDefault:
Description: >-
Checks that the equals signs in parameter default assignments
have or don't have surrounding space depending on
configuration.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#spaces-around-equals'
Enabled: false
Style/SpaceAroundOperators:
Description: 'Use a single space around operators.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#spaces-operators'
Enabled: false
Style/SpaceInsideBrackets:
Description: 'No spaces after [ or before ].'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-spaces-braces'
Enabled: false
Style/SpaceInsideHashLiteralBraces:
Description: "Use spaces inside hash literal braces - or don't."
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#spaces-operators'
Enabled: false
Style/SpaceInsideParens:
Description: 'No spaces after ( or before ).'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-spaces-braces'
Enabled: false
Style/SpaceInsideRangeLiteral:
Description: 'No spaces inside range literals.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-space-inside-range-literals'
Enabled: false
Style/SpaceInsideStringInterpolation:
Description: 'Checks for padding/surrounding spaces inside string interpolation.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#string-interpolation'
Enabled: false
Style/SpecialGlobalVars:
Description: 'Avoid Perl-style global variables.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-cryptic-perlisms'
Enabled: false
Style/StringLiterals:
Description: 'Checks if uses of quotes match the configured preference.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#consistent-string-literals'
Enabled: false
Style/StringLiteralsInInterpolation:
Description: >-
Checks if uses of quotes inside expressions in interpolated
strings match the configured preference.
Enabled: false
Style/StructInheritance:
Description: 'Checks for inheritance from Struct.new.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-extend-struct-new'
Enabled: false
Style/SymbolLiteral:
Description: 'Use plain symbols instead of string symbols when possible.'
Enabled: false
Style/SymbolProc:
Description: 'Use symbols as procs instead of blocks when possible.'
Enabled: false
Style/Tab:
Description: 'No hard tabs.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#spaces-indentation'
Enabled: false
Style/TrailingBlankLines:
Description: 'Checks trailing blank lines and final newline.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#newline-eof'
Enabled: false
Style/TrailingCommaInArguments:
Description: 'Checks for trailing comma in parameter lists.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-params-comma'
Enabled: false
Style/TrailingCommaInLiteral:
Description: 'Checks for trailing comma in literals.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas'
Enabled: false
Style/TrailingWhitespace:
Description: 'Avoid trailing whitespace.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-whitespace'
Enabled: false
Style/TrivialAccessors:
Description: 'Prefer attr_* methods to trivial readers/writers.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#attr_family'
Enabled: false
Style/UnlessElse:
Description: >-
Do not use unless with else. Rewrite these with the positive
case first.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-else-with-unless'
Enabled: false
Style/UnneededCapitalW:
Description: 'Checks for %W when interpolation is not needed.'
Enabled: false
Style/UnneededPercentQ:
Description: 'Checks for %q/%Q when single quotes or double quotes would do.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#percent-q'
Enabled: false
Style/TrailingUnderscoreVariable:
Description: >-
Checks for the usage of unneeded trailing underscores at the
end of parallel variable assignment.
Enabled: false
Style/VariableInterpolation:
Description: >-
Don't interpolate global, instance and class variables
directly in strings.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#curlies-interpolate'
Enabled: false
Style/VariableName:
Description: 'Use the configured style when naming variables.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#snake-case-symbols-methods-vars'
Enabled: false
Style/WhenThen:
Description: 'Use when x then ... for one-line cases.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#one-line-cases'
Enabled: false
Style/WhileUntilDo:
Description: 'Checks for redundant do after while or until.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-multiline-while-do'
Enabled: false
Style/WhileUntilModifier:
Description: >-
Favor modifier while/until usage when you have a
single-line body.
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#while-as-a-modifier'
Enabled: false
Style/WordArray:
Description: 'Use %w or %W for arrays of words.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#percent-w'
Enabled: false
oauth-ruby-0.5.3/.travis.yml 0000664 0000000 0000000 00000000361 13111303321 0015713 0 ustar 00root root 0000000 0000000 language: ruby
rvm:
- "ruby-head"
- "2.4.0"
- "2.3"
- "2.2"
- "2.1"
- "2.0"
addons:
code_climate:
repo_token: 8f697ca756250f0c2c54170ae27e8a9c459d18a0236903b11291c88291b3aac9
after_success:
- bundle exec codeclimate-test-reporter
oauth-ruby-0.5.3/Gemfile 0000664 0000000 0000000 00000000047 13111303321 0015076 0 ustar 00root root 0000000 0000000 source 'https://rubygems.org'
gemspec
oauth-ruby-0.5.3/HISTORY 0000664 0000000 0000000 00000024055 13111303321 0014674 0 ustar 00root root 0000000 0000000 === CURRENT
=== 0.5.3 2017-05-24
* Removing legacy scripts (James Pinto)
* Fix #145 - broken CLI required loading active_support (James Pinto)
=== 0.5.2 2017-05-17
* Adding a development dependency that had not been mentioned (James Pinto)
* Use assert_nil so as to silence a Minitest 6 deprecation warning (James Pinto)
* Stop bundling tests files in the gem (Michal Papis)
* Minor cleanup on tests (James Pinto)
* TravisCI no longer needs libcurl-dev (James Pinto)
* Nokogiri 1.7 does not accept Ruby 2.0 (James Pinto)
* Upgrading to CodeClimate 1.0 (James Pinto)
* Adding support to Ruby 2.4 and head (James Pinto)
* Locking gemspec to Rails 4 so as to allow our next version for Rails 5 (James Pinto)
* Fix #113 adding paths when a full URL has been specified (James Pinto)
* moving development dependency to gemspec (James Pinto)
* Silencing 'Net::HTTPResponse#header is obsolete' (James Pinto)
* Silencing some test warnings (James Pinto)
* Silencing 'loading in progress, circular require considered harmful' (James Pinto)
* Silence 'URI.escape obsolete' (James Pinto)
* Refactored CLI (James Pinto)
* Bug Fix, webmock 2.0 has introduced a new bug (James Pinto)
* Moving test files into test/units/ (James Pinto)
* Adding CodeClimate (James Pinto)
* Reimplementing #82 - Debug Output Option (James Pinto)
* Making a test/support dir (James Pinto)
* Fix #177 - Adjusting to webmock latest recommended implementation for minitest (James Pinto)
* Adding support to Ruby 2.4 and head (James Pinto)
* Upgrading to CodeClimate 1.0 (James Pinto)
* Nokogiri 1.7 does not accept Ruby 2.0 (James Pinto)
=== 0.5.1 2016-02-29
* Proper handling for empty query string in RequestToken#build_authorize_url (midchildan,
Harald Sitter)
* Loosen some development dependencies. Add libcurl-dev to travis
* Add license info to the gemspec (Robert Reiz)
* Fixes to travis config. Switch to rubygems for installation and loading
* Remove obsolete comment (Arthur Nogueira Neves)
* Remove jeweler from gemspec
* Replace calls to String#blank? with its implementation (Sergio Gil Pérez de la Manga)
=== 0.5.0 2016-02-20
* Fix ability to pass in an authorize url with a query string (Roger Smith)
* Add support for HTTP PATCH method (Richard Huang)
* Allow reading private key from a string (Khaja Minhajuddin)
* Fix bug in signature verification (r-stu31)
* Use standard key name (`oauth_token_secret`) in Token#to_query (Craig Walker)
* Fix error in CLI when using `query` without supplying a method (grafikchaos)
* Compatibility fix for Typhoeus >= 0.5.0 (Chad Feller)
* Add rest-client proxy (Khem Veasna)
* Rails 3+ / ActiveSupport::SafeBuffer patch (Clif Reeder)
* Handle `nil` token gracefully for RequestToken#authorize_url (Brian John)
* Replace jeweler with real spec and bundler tasks
* Extract version to separate file
* Fix typhoeus compatibility (Vladimir Mikhailov)
* Use OpenSSL for all digest and hashing. Remove signature methods not defined by OAuth spec.
Add byebug. (Kevin Hughes)
* Fix oauth cli option parser on Ruby 2.2 (Felix Bünemann)
* Change token requests to exclude `oauth_body_hash`. Update doc links in comments. (John Remmen)
* Update gemspec for security fixes. Convert to Minitest. Add .travis.yml. (Kevin Hughes)
* Allow reading certificate file path from environment variable. Add CentOS cert file path
(Danil Vlasov)
* Fix some warnings (amatsuda)
* Various fixes/updates to README (Evan Arnold, Jonathan Camenisch, Brian John, Ankur Sethi)
=== 0.4.7 2012-09-03
* Fix merging paths if the path is not empty
* Set a configurable timeout for all requests (Rick Olson)
* Fix nested hash params in Consumer#request (Ernie Miller)
=== 0.4.6 2012-04-21
* Fixed nested attributes in #normalize (Shaliko Usubov)
* Make use the path component of the :site parameter (Jonathon M. Abbott)
* Fixed post body's being dropped in 1.9 (Steven Hammond)
* Fixed PUT request handling (Anton Panasenko)
=== 0.4.5 2011-06-25
* Add explicit require for rsa/sha1 (Juris Galang)
* Use webmock to mock all http-requests in tests (Adrian Feldman)
* Add gemtest support (Adrian Feldman)
* Fix POST Requests with Typhoeus proxy (niedhui)
* Mention Typhoeus require in the README (Kim Ahlström)
* Fix incorrect hardcoded port (Ian Taylor)
* Use Net::HTTPGenericRequest (Jakub Kuźma)
=== 0.4.4 2010-10-31
* Fix LoadError rescue in tests: return can't be used in this context (Hans de Graaff)
* HTTP headers should be strings. (seancribbs)
* ensure consumer uri gets set back to original config even if an error occurs (Brian Finney)
* Yahoo uses & to split records in OAuth headers (Brian Finney)
* Added support for Rails 3 in client/action_controller_request (Pelle)
== 0.4.3 2010-09-01
* Fix for em-http proxy (ichverstehe)
== 0.4.2 2010-08-13
* Fixed compatibility with Ruby 1.9.2 (ecavazos)
* Fixed the em-http request proxy (Joshua Hull)
* Fix for oauth proxy string manipulation (Jakub Suder)
* Added Bundler (rc) Gemfile for easier dev/testing
== 0.4.1 2010-06-16
* Added support for using OAuth with proxies (Marsh Gardiner)
* Rails 3 Compatibility fixes (Pelle Braendgaard)
* Fixed load errors on tests for missing (non-required) libraries
== 0.4.0 2010-04-22
* Added computation of oauth_body_hash as per OAuth Request Body Hash 1.0
Draft 4 (Michael Reinsch)
* Added the optional `oauth_session_handle` parameter for the Yahoo implementation (Will Bailey)
* Better marshalling implementation (Yoan Blanc)
* Added optional block to OAuth::Consumer.get_*_token (Neill Pearman)
* Exclude `oauth_callback` with :exclude_callback (Neill Pearman)
* Strip extraneous spaces and line breaks from access_token responses
(observed in the wild with Yahoo!'s OAuth+OpenID hybrid) (Eric Hartmann)
* Stop double-escaping PLAINTEXT signatures (Jimmy Zimmerman)
* OAuth::Client::Helper won't override the specified `oauth_version`
(Philip Kromer)
* Support for Ruby 1.9 (Aaron Quint, Corey Donahoe, et al)
* Fixed an encoding / multibyte issue (成田 一生)
* Replaced hoe with Jeweler (Aaron Quint)
* Support for Typhoeus (Bill Kocik)
* Support for em-http (EventMachine) (Darcy Laycock)
* Support for curb (André Luis Leal Cardoso Junior)
* New website (Aaron Quint)
== 0.3.6 2009-09-14
* Added -B CLI option to use the :body authentication scheme (Seth)
* Respect `--method` in `authorize` CLI command (Seth)
* Support POST and PUT with raw bodies (Yu-Shan Fung et al)
* Test clean-up (Xavier Shay, Hannes Tydén)
* Added :ca_file consumer option to allow consumer specific certificate
override. (Pelle)
== 0.3.5 2009-06-03
* `query` CLI command to access protected resources (Seth)
* Added -H, -Q CLI options for specifying the authentication scheme (Seth)
* Added -O CLI option for specifying a file containing options (Seth)
* Support streamable body contents for large request bodies (Seth Cousins)
* Support for OAuth 1.0a (Seth)
* Added proxy support to OAuth::Consumer (Marshall Huss)
* Added --scope CLI option for Google's 'scope' parameter (Seth)
== 0.3.4 2009-05-06
* OAuth::Client::Helper uses OAuth::VERSION (chadisfaction)
* Fix OAuth::RequestProxy::ActionControllerRequest's handling of params
(Tristan Groléat)
== 0.3.3 2009-05-04
* Corrected OAuth XMPP namespace (Seth)
* Improved error handling for invalid Authorization headers (Matt Sanford)
* Fixed signatures for non-ASCII under $KCODE other than 'u' (Matt Sanford)
* Fixed edge cases in ActionControllerRequestProxy where params were being
incorrectly signed (Marcos Wright Kuhns)
* Support for arguments in OAuth::Consumer#get_access_token (Matt Sanford)
* Add gem version to user-agent header (Matt Sanford)
* Handle input from aggressive form encoding libraries (Matt Wood)
== 0.3.2 2009-03-23
* 2xx statuses should be treated as success (Anders Conbere)
* Support applications using the MethodOverride Rack middleware (László Bácsi)
* `authorize` command for `oauth` CLI (Seth)
* Initial support for Problem Reporting extension (Seth)
* Verify SSL certificates if CA certificates are available (Seth)
* Fixed ActionController parameter escaping behavior (Thiago Arrais, László
Bácsi, Brett Gibson, et al)
* Fixed signature calculation when both options and a block were provided to
OAuth::Signature::Base#initialize (Seth)
* Added help to the 'oauth' CLI (Seth)
* Fixed a problem when attempting to normalize MockRequest URIs (Seth)
== 0.3.1 2009-1-26
* Fixed a problem with relative and absolute token request paths. (Michael
Wood)
== 0.3.0 2009-1-25
* Support ActionController::Request from Edge Rails (László Bácsi)
* Correctly handle multi-valued parameters (Seth)
* Added #normalized_parameters to OAuth::RequestProxy::Base (Pelle)
* OAuth::Signature.sign and friends now yield the RequestProxy instead of the
token when the passed block's arity is 1. (Seth)
* Token requests are made to the configured URL rather than generating a
potentially incorrect one. (Kellan Elliott-McCrea)
* Command-line app for generating signatures. (Seth)
* Improved test-cases and compatibility for encoding issues. (Pelle)
== 0.2.7 2008-9-10 The lets fix the last release release
* Fixed plain text signatures (Andrew Arrow)
* Fixed RSA requests using OAuthTokens. (Philip Lipu Tsai)
== 0.2.6 2008-9-9 The lets RSA release
* Improved support for Ruby 1.8.7 (Bill Kocik)
* Fixed RSA verification to support RSA providers
now using Ruby and RSA
* Improved RSA testing
* Omit token when signing with RSA
* Added support for 'private_key_file' option for RSA signatures (Chris Mear)
* Fixed several edge cases where params were being incorrectly signed (Scott
Hill)
* Fixed RSA signing (choonkeat)
== 0.2.2 2008-2-22 Lets actually support SSL release
* Use HTTPS when required.
== 0.2 2008-1-19 All together now release
This is a big release, where we have merged the efforts of various parties into one common library.
This means there are definitely some API changes you should be aware of. They should be minimal
but please have a look at the unit tests.
== 0.1.2 2007-12-1
* Fixed checks for missing OAuth params to improve performance
* Includes Pat's fix for getting the realm out.
== 0.1.1 2007-11-26
* First release as a GEM
* Moved all non-Rails functionality from the Rails plugin:
http://code.google.com/p/oauth-plugin/
oauth-ruby-0.5.3/LICENSE 0000664 0000000 0000000 00000002076 13111303321 0014614 0 ustar 00root root 0000000 0000000 Copyright (c) 2007 Blaine Cook, Larry Halff, Pelle Braendgaard
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. oauth-ruby-0.5.3/README.rdoc 0000664 0000000 0000000 00000006106 13111303321 0015413 0 ustar 00root root 0000000 0000000 = Ruby OAuth
== Status
{
}[https://travis-ci.org/oauth-xx/oauth-ruby]
== What
This is a RubyGem for implementing both OAuth clients and servers in Ruby applications.
See the OAuth specs http://oauth.net/core/1.0/
== Installing
sudo gem install oauth
The source code is now hosted on the OAuth GitHub Project http://github.com/oauth-xx/oauth-ruby
== The basics
This is a ruby library which is intended to be used in creating Ruby Consumer and Service Provider applications. It is NOT a Rails plugin, but could easily be used for the foundation for such a Rails plugin.
As a matter of fact it has been pulled out from an OAuth Rails GEM (https://rubygems.org/gems/oauth-plugin https://github.com/pelle/oauth-plugin) which now uses this gem as a dependency.
== Demonstration of usage
We need to specify the oauth_callback url explicitly, otherwise it defaults to "oob" (Out of Band)
@callback_url = "http://127.0.0.1:3000/oauth/callback"
Create a new consumer instance by passing it a configuration hash:
@consumer = OAuth::Consumer.new("key","secret", :site => "https://agree2")
Start the process by requesting a token
@request_token = @consumer.get_request_token(:oauth_callback => @callback_url)
session[:token] = request_token.token
session[:token_secret] = request_token.secret
redirect_to @request_token.authorize_url(:oauth_callback => @callback_url)
When user returns create an access_token
hash = { oauth_token: session[:token], oauth_token_secret: session[:token_secret]}
request_token = OAuth::RequestToken.from_hash(@consumer, hash)
@access_token = @request_token.get_access_token
@photos = @access_token.get('/photos.xml')
Now that you have an access token, you can use Typhoeus to interact with the OAuth provider if you choose.
require 'oauth/request_proxy/typhoeus_request'
oauth_params = {:consumer => oauth_consumer, :token => access_token}
hydra = Typhoeus::Hydra.new
req = Typhoeus::Request.new(uri, options) # :method needs to be specified in options
oauth_helper = OAuth::Client::Helper.new(req, oauth_params.merge(:request_uri => uri))
req.options[:headers].merge!({"Authorization" => oauth_helper.header}) # Signs the request
hydra.queue(req)
hydra.run
@response = req.response
== More Information
* RDoc: http://rdoc.info/github/oauth-xx/oauth-ruby/master/frames
* Mailing List/Google Group: http://groups.google.com/group/oauth-ruby
== How to submit patches
The source code is now hosted on the OAuth GitHub Project http://github.com/oauth-xx/oauth-ruby
To submit a patch, please fork the oauth project and create a patch with tests. Once you're happy with it send a pull request and post a message to the google group.
== License
This code is free to use under the terms of the MIT license.
== Contact
OAuth Ruby has been created and maintained by a large number of talented individuals.
The current maintainer is Aaron Quint (quirkey).
Comments are welcome. Send an email to via the OAuth Ruby mailing list http://groups.google.com/group/oauth-ruby
oauth-ruby-0.5.3/Rakefile 0000664 0000000 0000000 00000000456 13111303321 0015254 0 ustar 00root root 0000000 0000000 %w[rubygems rake rake/clean rake/testtask fileutils bundler].each { |f| require f }
Bundler::GemHelper.install_tasks
Rake::TestTask.new do |t|
t.libs << "test"
t.test_files = FileList['test/**/*test*.rb']
t.verbose = true
end
Dir['tasks/**/*.rake'].each { |t| load t }
task :default => :test
oauth-ruby-0.5.3/TODO 0000664 0000000 0000000 00000002116 13111303321 0014272 0 ustar 00root root 0000000 0000000 Common use-cases should be streamlined:
* I have a URL that I want to sign (given consumer key/secret, optional
token/secret, optional nonce/timestamp).
* I have a URL that I want to sign AND I want to see what the components
(e.g. signature base string, etc.) are while it's being signed (i.e. verbose
signing).
* I have a URL that I want to sign and I only want the signature.
* I have a URL that I want to sign and I want something suitable to put in
{the header, the querystring, XMPP}.
* I want to make a query to an OAuth-enabled web service (with sensible
errors, if available).
* I want to host an OAuth-enabled web service.
* I want to test my OAuth-enabled web service (i.e. test helpers)
Example applications for:
* Ning
* Fire Eagle
* Google (blogger, contacts)
* Twitter
* YOS / YQL
* Netflix
In addition to providing best practices of use, these can also be part of
the pre-release checks to make sure that there have been no regressions.
Random TODOs:
* finish CLI
* sensible Exception hierarchy
* Tokens as Modules
* don't tie to Net::HTTP
* Take a look at Curb HTTP Verbs oauth-ruby-0.5.3/bin/ 0000775 0000000 0000000 00000000000 13111303321 0014352 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/bin/oauth 0000775 0000000 0000000 00000000376 13111303321 0015426 0 ustar 00root root 0000000 0000000 #!/usr/bin/env ruby
require_relative "../lib/oauth"
require 'oauth/cli'
Signal.trap("INT") { puts; exit(1) } # don't dump a backtrace on a ^C
ARGV << 'help' if ARGV.empty?
command = ARGV.shift
OAuth::CLI.new(STDOUT, STDIN, STDERR, command, ARGV).run
oauth-ruby-0.5.3/examples/ 0000775 0000000 0000000 00000000000 13111303321 0015420 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/examples/yql.rb 0000775 0000000 0000000 00000002220 13111303321 0016551 0 ustar 00root root 0000000 0000000 #!/usr/bin/env ruby -rubygems
# Sample queries:
# ./yql.rb --consumer-key --consumer-secret "show tables"
# ./yql.rb --consumer-key --consumer-secret "select * from flickr.photos.search where text='Cat' limit 10"
require 'oauth'
require 'optparse'
require 'json'
require 'pp'
options = {}
option_parser = OptionParser.new do |opts|
opts.banner = "Usage: #{$0} [options] "
opts.on("--consumer-key KEY", "Specifies the consumer key to use.") do |v|
options[:consumer_key] = v
end
opts.on("--consumer-secret SECRET", "Specifies the consumer secret to use.") do |v|
options[:consumer_secret] = v
end
end
option_parser.parse!
query = ARGV.pop
query = STDIN.read if query == "-"
if options[:consumer_key].nil? || options[:consumer_secret].nil? || query.nil?
puts option_parser.help
exit 1
end
consumer = OAuth::Consumer.new \
options[:consumer_key],
options[:consumer_secret],
:site => "http://query.yahooapis.com"
access_token = OAuth::AccessToken.new(consumer)
response = access_token.request(:get, "/v1/yql?q=#{OAuth::Helper.escape(query)}&format=json")
rsp = JSON.parse(response.body)
pp rsp
oauth-ruby-0.5.3/lib/ 0000775 0000000 0000000 00000000000 13111303321 0014350 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/lib/oauth.rb 0000664 0000000 0000000 00000000454 13111303321 0016020 0 ustar 00root root 0000000 0000000 root = File.dirname(__FILE__)
$LOAD_PATH << root unless $LOAD_PATH.include?(root)
require 'oauth/version'
require 'oauth/oauth'
require 'oauth/core_ext'
require 'oauth/client/helper'
require 'oauth/signature/hmac/sha1'
require 'oauth/signature/rsa/sha1'
require 'oauth/request_proxy/mock_request'
oauth-ruby-0.5.3/lib/oauth/ 0000775 0000000 0000000 00000000000 13111303321 0015470 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/lib/oauth/cli.rb 0000664 0000000 0000000 00000002443 13111303321 0016567 0 ustar 00root root 0000000 0000000 require 'optparse'
require 'oauth/cli/base_command'
require 'oauth/cli/help_command'
require 'oauth/cli/query_command'
require 'oauth/cli/authorize_command'
require 'oauth/cli/sign_command'
require 'oauth/cli/version_command'
require 'active_support/core_ext/string/inflections'
module OAuth
class CLI
def self.puts_red(string)
puts "\033[0;91m#{string}\033[0m"
end
ALIASES = {
'h' => 'help',
'v' => 'version',
'q' => 'query',
'a' => 'authorize',
's' => 'sign',
}
def initialize(stdout, stdin, stderr, command, arguments)
klass = get_command_class(parse_command(command))
@command = klass.new(stdout, stdin, stderr, arguments)
@help_command = HelpCommand.new(stdout, stdin, stderr, [])
end
def run
@command.run
end
private
def get_command_class(command)
Object.const_get("OAuth::CLI::#{command.camelize}Command")
end
def parse_command(command)
case command = command.to_s.downcase
when '--version', '-v'
'version'
when '--help', '-h', nil, ''
'help'
when *ALIASES.keys
ALIASES[command]
when *ALIASES.values
command
else
OAuth::CLI.puts_red "Command '#{command}' not found"
'help'
end
end
end
end
oauth-ruby-0.5.3/lib/oauth/cli/ 0000775 0000000 0000000 00000000000 13111303321 0016237 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/lib/oauth/cli/authorize_command.rb 0000664 0000000 0000000 00000004064 13111303321 0022300 0 ustar 00root root 0000000 0000000 class OAuth::CLI
class AuthorizeCommand < BaseCommand
def required_options
[:uri]
end
def _run
request_token = get_request_token
if request_token.callback_confirmed?
puts "Server appears to support OAuth 1.0a; enabling support."
options[:version] = "1.0a"
end
puts "Please visit this url to authorize:"
puts request_token.authorize_url
# parameters for OAuth 1.0a
oauth_verifier = ask_user_for_verifier
verbosely_get_access_token(request_token, oauth_verifier)
end
def get_request_token
consumer = get_consumer
scope_options = options[:scope] ? { "scope" => options[:scope] } : {}
consumer.get_request_token({ :oauth_callback => options[:oauth_callback] }, scope_options)
rescue OAuth::Unauthorized => e
alert "A problem occurred while attempting to authorize:"
alert e
alert e.request.body
end
def get_consumer
OAuth::Consumer.new \
options[:oauth_consumer_key],
options[:oauth_consumer_secret],
:access_token_url => options[:access_token_url],
:authorize_url => options[:authorize_url],
:request_token_url => options[:request_token_url],
:scheme => options[:scheme],
:http_method => options[:method].to_s.downcase.to_sym
end
def ask_user_for_verifier
if options[:version] == "1.0a"
puts "Please enter the verification code provided by the SP (oauth_verifier):"
@stdin.gets.chomp
else
puts "Press return to continue..."
@stdin.gets
nil
end
end
def verbosely_get_access_token(request_token, oauth_verifier)
access_token = request_token.get_access_token(:oauth_verifier => oauth_verifier)
puts "Response:"
access_token.params.each do |k,v|
puts " #{k}: #{v}" unless k.is_a?(Symbol)
end
rescue OAuth::Unauthorized => e
alert "A problem occurred while attempting to obtain an access token:"
alert e
alert e.request.body
end
end
end
oauth-ruby-0.5.3/lib/oauth/cli/base_command.rb 0000664 0000000 0000000 00000013411 13111303321 0021174 0 ustar 00root root 0000000 0000000 class OAuth::CLI
class BaseCommand
def initialize(stdout, stdin, stderr, arguments)
@stdout, @stdin, @stderr = stdout, stdin, stderr
@options = {}
option_parser.parse!(arguments)
end
def run
missing = required_options - options.keys
if missing.empty?
_run
else
show_missing(missing)
puts option_parser.help
end
end
def required_options
[]
end
protected
attr_reader :options
def show_missing(array)
array = array.map { |s| "--#{s}" }.join(' ')
OAuth::CLI.puts_red "Options missing to OAuth CLI: #{array}"
end
def xmpp?
options[:xmpp]
end
def verbose?
options[:verbose]
end
def puts(string=nil)
@stdout.puts(string)
end
def alert(string=nil)
@stderr.puts(string)
end
def parameters
@parameters ||= begin
escaped_pairs = options[:params].collect do |pair|
if pair =~ /:/
Hash[*pair.split(":", 2)].collect do |k,v|
[CGI.escape(k.strip), CGI.escape(v.strip)] * "="
end
else
pair
end
end
querystring = escaped_pairs * "&"
cli_params = CGI.parse(querystring)
{
"oauth_consumer_key" => options[:oauth_consumer_key],
"oauth_nonce" => options[:oauth_nonce],
"oauth_timestamp" => options[:oauth_timestamp],
"oauth_token" => options[:oauth_token],
"oauth_signature_method" => options[:oauth_signature_method],
"oauth_version" => options[:oauth_version]
}.reject { |_k,v| v.nil? || v == "" }.merge(cli_params)
end
end
def option_parser
@option_parser ||= OptionParser.new do |opts|
opts.banner = "Usage: oauth [ARGS]"
_option_parser_defaults
_option_parser_common(opts)
_option_parser_sign_and_query(opts)
_option_parser_authorization(opts)
end
end
def _option_parser_defaults
options[:oauth_nonce] = OAuth::Helper.generate_key
options[:oauth_signature_method] = "HMAC-SHA1"
options[:oauth_timestamp] = OAuth::Helper.generate_timestamp
options[:oauth_version] = "1.0"
options[:method] = :post
options[:params] = []
options[:scheme] = :header
options[:version] = "1.0"
end
def _option_parser_common(opts)
## Common Options
opts.on("-B", "--body", "Use the request body for OAuth parameters.") do
options[:scheme] = :body
end
opts.on("--consumer-key KEY", "Specifies the consumer key to use.") do |v|
options[:oauth_consumer_key] = v
end
opts.on("--consumer-secret SECRET", "Specifies the consumer secret to use.") do |v|
options[:oauth_consumer_secret] = v
end
opts.on("-H", "--header", "Use the 'Authorization' header for OAuth parameters (default).") do
options[:scheme] = :header
end
opts.on("-Q", "--query-string", "Use the query string for OAuth parameters.") do
options[:scheme] = :query_string
end
opts.on("-O", "--options FILE", "Read options from a file") do |v|
arguments = open(v).readlines.map { |l| l.chomp.split(" ") }.flatten
options2 = parse_options(arguments)
options.merge!(options2)
end
end
def _option_parser_sign_and_query(opts)
opts.separator("\n options for signing and querying")
opts.on("--method METHOD", "Specifies the method (e.g. GET) to use when signing.") do |v|
options[:method] = v
end
opts.on("--nonce NONCE", "Specifies the none to use.") do |v|
options[:oauth_nonce] = v
end
opts.on("--parameters PARAMS", "Specifies the parameters to use when signing.") do |v|
options[:params] << v
end
opts.on("--signature-method METHOD", "Specifies the signature method to use; defaults to HMAC-SHA1.") do |v|
options[:oauth_signature_method] = v
end
opts.on("--token TOKEN", "Specifies the token to use.") do |v|
options[:oauth_token] = v
end
opts.on("--secret SECRET", "Specifies the token secret to use.") do |v|
options[:oauth_token_secret] = v
end
opts.on("--timestamp TIMESTAMP", "Specifies the timestamp to use.") do |v|
options[:oauth_timestamp] = v
end
opts.on("--realm REALM", "Specifies the realm to use.") do |v|
options[:realm] = v
end
opts.on("--uri URI", "Specifies the URI to use when signing.") do |v|
options[:uri] = v
end
opts.on("--version [VERSION]", "Specifies the OAuth version to use.") do |v|
options[:oauth_version] = v
end
opts.on("--no-version", "Omit oauth_version.") do
options[:oauth_version] = nil
end
opts.on("--xmpp", "Generate XMPP stanzas.") do
options[:xmpp] = true
options[:method] ||= "iq"
end
opts.on("-v", "--verbose", "Be verbose.") do
options[:verbose] = true
end
end
def _option_parser_authorization(opts)
opts.separator("\n options for authorization")
opts.on("--access-token-url URL", "Specifies the access token URL.") do |v|
options[:access_token_url] = v
end
opts.on("--authorize-url URL", "Specifies the authorization URL.") do |v|
options[:authorize_url] = v
end
opts.on("--callback-url URL", "Specifies a callback URL.") do |v|
options[:oauth_callback] = v
end
opts.on("--request-token-url URL", "Specifies the request token URL.") do |v|
options[:request_token_url] = v
end
opts.on("--scope SCOPE", "Specifies the scope (Google-specific).") do |v|
options[:scope] = v
end
end
end
end
oauth-ruby-0.5.3/lib/oauth/cli/help_command.rb 0000664 0000000 0000000 00000001062 13111303321 0021211 0 ustar 00root root 0000000 0000000 class OAuth::CLI
class HelpCommand < BaseCommand
def run
puts <<-EOT
Usage: oauth COMMAND [ARGS]
Available oauth commands are:
a, authorize Obtain an access token and secret for a user
q, query Query a protected resource
s, sign Generate an OAuth signature
In addition to those, there are:
v, version Displays the current version of the library (or --version, -v)
h, help Displays this help (or --help, -h)
Tip: All commands can be run without args for specific help.
EOT
end
end
end
oauth-ruby-0.5.3/lib/oauth/cli/query_command.rb 0000664 0000000 0000000 00000001616 13111303321 0021433 0 ustar 00root root 0000000 0000000 class OAuth::CLI
class QueryCommand < BaseCommand
extend OAuth::Helper
def required_options
[:oauth_consumer_key, :oauth_consumer_secret, :oauth_token, :oauth_token_secret]
end
def _run
consumer = OAuth::Consumer.new(options[:oauth_consumer_key], options[:oauth_consumer_secret], scheme: options[:scheme])
access_token = OAuth::AccessToken.new(consumer, options[:oauth_token], options[:oauth_token_secret])
# append params to the URL
uri = URI.parse(options[:uri])
params = parameters.map { |k,v| Array(v).map { |v2| "#{OAuth::Helper.escape(k)}=#{OAuth::Helper.escape(v2)}" } * "&" }
uri.query = [uri.query, *params].reject { |x| x.nil? } * "&"
puts uri.to_s
response = access_token.request(options[:method].to_s.downcase.to_sym, uri.to_s)
puts "#{response.code} #{response.message}"
puts response.body
end
end
end
oauth-ruby-0.5.3/lib/oauth/cli/sign_command.rb 0000664 0000000 0000000 00000004626 13111303321 0021232 0 ustar 00root root 0000000 0000000 class OAuth::CLI
class SignCommand < BaseCommand
def required_options
[:oauth_consumer_key, :oauth_consumer_secret, :oauth_token, :oauth_token_secret]
end
def _run
request = OAuth::RequestProxy.proxy \
"method" => options[:method],
"uri" => options[:uri],
"parameters" => parameters
if verbose?
puts_verbose_parameters(request)
end
request.sign! \
:consumer_secret => options[:oauth_consumer_secret],
:token_secret => options[:oauth_token_secret]
if verbose?
puts_verbose_request(request)
else
puts request.oauth_signature
end
end
def puts_verbose_parameters(request)
puts "OAuth parameters:"
request.oauth_parameters.each do |k,v|
puts " " + [k, v] * ": "
end
puts
if request.non_oauth_parameters.any?
puts "Parameters:"
request.non_oauth_parameters.each do |k,v|
puts " " + [k, v] * ": "
end
puts
end
end
def puts_verbose_request(request)
puts "Method: #{request.method}"
puts "URI: #{request.uri}"
puts "Normalized params: #{request.normalized_parameters}" unless options[:xmpp]
puts "Signature base string: #{request.signature_base_string}"
if xmpp?
puts
puts "XMPP Stanza:"
puts xmpp_output(request)
puts
puts "Note: You may want to use bare JIDs in your URI."
puts
else
puts "OAuth Request URI: #{request.signed_uri}"
puts "Request URI: #{request.signed_uri(false)}"
puts "Authorization header: #{request.oauth_header(:realm => options[:realm])}"
end
puts "Signature: #{request.oauth_signature}"
puts "Escaped signature: #{OAuth::Helper.escape(request.oauth_signature)}"
end
def xmpp_output(request)
<<-EOS
#{request.oauth_consumer_key}
#{request.oauth_token}
#{request.oauth_signature_method}
#{request.oauth_signature}
#{request.oauth_timestamp}
#{request.oauth_nonce}
#{request.oauth_version}
EOS
end
end
end
oauth-ruby-0.5.3/lib/oauth/cli/version_command.rb 0000664 0000000 0000000 00000000175 13111303321 0021752 0 ustar 00root root 0000000 0000000 class OAuth::CLI
class VersionCommand < BaseCommand
def run
puts "OAuth Gem #{OAuth::VERSION}"
end
end
end
oauth-ruby-0.5.3/lib/oauth/client.rb 0000664 0000000 0000000 00000000047 13111303321 0017274 0 ustar 00root root 0000000 0000000 module OAuth
module Client
end
end
oauth-ruby-0.5.3/lib/oauth/client/ 0000775 0000000 0000000 00000000000 13111303321 0016746 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/lib/oauth/client/action_controller_request.rb 0000664 0000000 0000000 00000003542 13111303321 0024567 0 ustar 00root root 0000000 0000000 if defined? ActionDispatch
require 'oauth/request_proxy/rack_request'
require 'action_dispatch/testing/test_process'
else
require 'oauth/request_proxy/action_controller_request'
require 'action_controller/test_process'
end
module ActionController
class Base
if defined? ActionDispatch
def process_with_new_base_test(request, response=nil)
request.apply_oauth! if request.respond_to?(:apply_oauth!)
super(request, response)
end
else
def process_with_oauth(request, response=nil)
request.apply_oauth! if request.respond_to?(:apply_oauth!)
process_without_oauth(request, response)
end
alias_method_chain :process, :oauth
end
end
class TestRequest
def self.use_oauth=(bool)
@use_oauth = bool
end
def self.use_oauth?
@use_oauth
end
def configure_oauth(consumer = nil, token = nil, options = {})
@oauth_options = { :consumer => consumer,
:token => token,
:scheme => 'header',
:signature_method => nil,
:nonce => nil,
:timestamp => nil }.merge(options)
end
def apply_oauth!
return unless ActionController::TestRequest.use_oauth? && @oauth_options
@oauth_helper = OAuth::Client::Helper.new(self, @oauth_options.merge(:request_uri => (respond_to?(:fullpath) ? fullpath : request_uri)))
@oauth_helper.amend_user_agent_header(env)
self.send("set_oauth_#{@oauth_options[:scheme]}")
end
def set_oauth_header
env['Authorization'] = @oauth_helper.header
end
def set_oauth_parameters
@query_parameters = @oauth_helper.parameters_with_oauth
@query_parameters.merge!(:oauth_signature => @oauth_helper.signature)
end
def set_oauth_query_string
end
end
end
oauth-ruby-0.5.3/lib/oauth/client/em_http.rb 0000664 0000000 0000000 00000010735 13111303321 0020741 0 ustar 00root root 0000000 0000000 require 'em-http'
require 'oauth/helper'
require 'oauth/request_proxy/em_http_request'
# Extensions for em-http so that we can use consumer.sign! with an EventMachine::HttpClient
# instance. This is purely syntactic sugar.
class EventMachine::HttpClient
attr_reader :oauth_helper
# Add the OAuth information to an HTTP request. Depending on the options[:scheme] setting
# this may add a header, additional query string parameters, or additional POST body parameters.
# The default scheme is +header+, in which the OAuth parameters as put into the +Authorization+
# header.
#
# * http - Configured Net::HTTP instance, ignored in this scenario except for getting host.
# * consumer - OAuth::Consumer instance
# * token - OAuth::Token instance
# * options - Request-specific options (e.g. +request_uri+, +consumer+, +token+, +scheme+,
# +signature_method+, +nonce+, +timestamp+)
#
# This method also modifies the User-Agent header to add the OAuth gem version.
#
# See Also: {OAuth core spec version 1.0, section 5.4.1}[http://oauth.net/core/1.0#rfc.section.5.4.1]
def oauth!(http, consumer = nil, token = nil, options = {})
options = { :request_uri => normalized_oauth_uri(http),
:consumer => consumer,
:token => token,
:scheme => 'header',
:signature_method => nil,
:nonce => nil,
:timestamp => nil }.merge(options)
@oauth_helper = OAuth::Client::Helper.new(self, options)
self.__send__(:"set_oauth_#{options[:scheme]}")
end
# Create a string suitable for signing for an HTTP request. This process involves parameter
# normalization as specified in the OAuth specification. The exact normalization also depends
# on the options[:scheme] being used so this must match what will be used for the request
# itself. The default scheme is +header+, in which the OAuth parameters as put into the +Authorization+
# header.
#
# * http - Configured Net::HTTP instance
# * consumer - OAuth::Consumer instance
# * token - OAuth::Token instance
# * options - Request-specific options (e.g. +request_uri+, +consumer+, +token+, +scheme+,
# +signature_method+, +nonce+, +timestamp+)
#
# See Also: {OAuth core spec version 1.0, section 9.1.1}[http://oauth.net/core/1.0#rfc.section.9.1.1]
def signature_base_string(http, consumer = nil, token = nil, options = {})
options = { :request_uri => normalized_oauth_uri(http),
:consumer => consumer,
:token => token,
:scheme => 'header',
:signature_method => nil,
:nonce => nil,
:timestamp => nil }.merge(options)
OAuth::Client::Helper.new(self, options).signature_base_string
end
# This code was lifted from the em-http-request because it was removed from
# the gem June 19, 2010
# see: http://github.com/igrigorik/em-http-request/commit/d536fc17d56dbe55c487eab01e2ff9382a62598b
def normalize_uri
@normalized_uri ||= begin
uri = @uri.dup
encoded_query = encode_query(@uri, @options[:query])
path, query = encoded_query.split("?", 2)
uri.query = query unless encoded_query.empty?
uri.path = path
uri
end
end
protected
def combine_query(path, query, uri_query)
combined_query = if query.kind_of?(Hash)
query.map { |k, v| encode_param(k, v) }.join('&')
else
query.to_s
end
if !uri_query.to_s.empty?
combined_query = [combined_query, uri_query].reject {|part| part.empty?}.join("&")
end
combined_query.to_s.empty? ? path : "#{path}?#{combined_query}"
end
# Since we expect to get the host etc details from the http instance (...),
# we create a fake url here. Surely this is a horrible, horrible idea?
def normalized_oauth_uri(http)
uri = URI.parse(normalize_uri.path)
uri.host = http.address
uri.port = http.port
if http.respond_to?(:use_ssl?) && http.use_ssl?
uri.scheme = "https"
else
uri.scheme = "http"
end
uri.to_s
end
def set_oauth_header
headers = (self.options[:head] ||= {})
headers['Authorization'] = @oauth_helper.header
end
def set_oauth_body
raise NotImplementedError, 'please use the set_oauth_header method instead'
end
def set_oauth_query_string
raise NotImplementedError, 'please use the set_oauth_header method instead'
end
end
oauth-ruby-0.5.3/lib/oauth/client/helper.rb 0000664 0000000 0000000 00000006067 13111303321 0020563 0 ustar 00root root 0000000 0000000 require 'oauth/client'
require 'oauth/consumer'
require 'oauth/helper'
require 'oauth/token'
require 'oauth/signature/hmac/sha1'
module OAuth::Client
class Helper
include OAuth::Helper
def initialize(request, options = {})
@request = request
@options = options
@options[:signature_method] ||= 'HMAC-SHA1'
end
def options
@options
end
def nonce
options[:nonce] ||= generate_key
end
def timestamp
options[:timestamp] ||= generate_timestamp
end
def oauth_parameters
{
'oauth_body_hash' => options[:body_hash],
'oauth_callback' => options[:oauth_callback],
'oauth_consumer_key' => options[:consumer].key,
'oauth_token' => options[:token] ? options[:token].token : '',
'oauth_signature_method' => options[:signature_method],
'oauth_timestamp' => timestamp,
'oauth_nonce' => nonce,
'oauth_verifier' => options[:oauth_verifier],
'oauth_version' => (options[:oauth_version] || '1.0'),
'oauth_session_handle' => options[:oauth_session_handle]
}.reject { |k,v| v.to_s == "" }
end
def signature(extra_options = {})
OAuth::Signature.sign(@request, { :uri => options[:request_uri],
:consumer => options[:consumer],
:token => options[:token],
:unsigned_parameters => options[:unsigned_parameters]
}.merge(extra_options) )
end
def signature_base_string(extra_options = {})
OAuth::Signature.signature_base_string(@request, { :uri => options[:request_uri],
:consumer => options[:consumer],
:token => options[:token],
:parameters => oauth_parameters}.merge(extra_options) )
end
def token_request?
@options[:token_request].eql?(true)
end
def hash_body
@options[:body_hash] = OAuth::Signature.body_hash(@request, :parameters => oauth_parameters)
end
def amend_user_agent_header(headers)
@oauth_ua_string ||= "OAuth gem v#{OAuth::VERSION}"
# Net::HTTP in 1.9 appends Ruby
if headers['User-Agent'] && headers['User-Agent'] != 'Ruby'
headers['User-Agent'] += " (#{@oauth_ua_string})"
else
headers['User-Agent'] = @oauth_ua_string
end
end
def header
parameters = oauth_parameters
parameters.merge!('oauth_signature' => signature(options.merge(:parameters => parameters)))
header_params_str = parameters.sort.map { |k,v| "#{k}=\"#{escape(v)}\"" }.join(', ')
realm = "realm=\"#{options[:realm]}\", " if options[:realm]
"OAuth #{realm}#{header_params_str}"
end
def parameters
OAuth::RequestProxy.proxy(@request).parameters
end
def parameters_with_oauth
oauth_parameters.merge(parameters)
end
end
end
oauth-ruby-0.5.3/lib/oauth/client/net_http.rb 0000664 0000000 0000000 00000012012 13111303321 0021114 0 ustar 00root root 0000000 0000000 require 'oauth/helper'
require 'oauth/request_proxy/net_http'
class Net::HTTPGenericRequest
include OAuth::Helper
attr_reader :oauth_helper
# Add the OAuth information to an HTTP request. Depending on the options[:scheme] setting
# this may add a header, additional query string parameters, or additional POST body parameters.
# The default scheme is +header+, in which the OAuth parameters as put into the +Authorization+
# header.
#
# * http - Configured Net::HTTP instance
# * consumer - OAuth::Consumer instance
# * token - OAuth::Token instance
# * options - Request-specific options (e.g. +request_uri+, +consumer+, +token+, +scheme+,
# +signature_method+, +nonce+, +timestamp+)
#
# This method also modifies the User-Agent header to add the OAuth gem version.
#
# See Also: {OAuth core spec version 1.0, section 5.4.1}[http://oauth.net/core/1.0#rfc.section.5.4.1],
# {OAuth Request Body Hash 1.0 Draft 4}[http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/drafts/4/spec.html,
# http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html#when_to_include]
def oauth!(http, consumer = nil, token = nil, options = {})
helper_options = oauth_helper_options(http, consumer, token, options)
@oauth_helper = OAuth::Client::Helper.new(self, helper_options)
@oauth_helper.amend_user_agent_header(self)
@oauth_helper.hash_body if oauth_body_hash_required?
self.send("set_oauth_#{helper_options[:scheme]}")
end
# Create a string suitable for signing for an HTTP request. This process involves parameter
# normalization as specified in the OAuth specification. The exact normalization also depends
# on the options[:scheme] being used so this must match what will be used for the request
# itself. The default scheme is +header+, in which the OAuth parameters as put into the +Authorization+
# header.
#
# * http - Configured Net::HTTP instance
# * consumer - OAuth::Consumer instance
# * token - OAuth::Token instance
# * options - Request-specific options (e.g. +request_uri+, +consumer+, +token+, +scheme+,
# +signature_method+, +nonce+, +timestamp+)
#
# See Also: {OAuth core spec version 1.0, section 5.4.1}[http://oauth.net/core/1.0#rfc.section.5.4.1],
# {OAuth Request Body Hash 1.0 Draft 4}[http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/drafts/4/spec.html,
# http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html#when_to_include]
def signature_base_string(http, consumer = nil, token = nil, options = {})
helper_options = oauth_helper_options(http, consumer, token, options)
@oauth_helper = OAuth::Client::Helper.new(self, helper_options)
@oauth_helper.hash_body if oauth_body_hash_required?
@oauth_helper.signature_base_string
end
private
def oauth_helper_options(http, consumer, token, options)
{ :request_uri => oauth_full_request_uri(http,options),
:consumer => consumer,
:token => token,
:scheme => 'header',
:signature_method => nil,
:nonce => nil,
:timestamp => nil }.merge(options)
end
def oauth_full_request_uri(http,options)
uri = URI.parse(self.path)
uri.host = http.address
uri.port = http.port
if options[:request_endpoint] && options[:site]
is_https = options[:site].match(%r(^https://))
uri.host = options[:site].gsub(%r(^https?://), '')
uri.port ||= is_https ? 443 : 80
end
if http.respond_to?(:use_ssl?) && http.use_ssl?
uri.scheme = "https"
else
uri.scheme = "http"
end
uri.to_s
end
def oauth_body_hash_required?
!@oauth_helper.token_request? && request_body_permitted? && !content_type.to_s.downcase.start_with?("application/x-www-form-urlencoded")
end
def set_oauth_header
self['Authorization'] = @oauth_helper.header
end
# FIXME: if you're using a POST body and query string parameters, this method
# will move query string parameters into the body unexpectedly. This may
# cause problems with non-x-www-form-urlencoded bodies submitted to URLs
# containing query string params. If duplicate parameters are present in both
# places, all instances should be included when calculating the signature
# base string.
def set_oauth_body
self.set_form_data(@oauth_helper.stringify_keys(@oauth_helper.parameters_with_oauth))
params_with_sig = @oauth_helper.parameters.merge(:oauth_signature => @oauth_helper.signature)
self.set_form_data(@oauth_helper.stringify_keys(params_with_sig))
end
def set_oauth_query_string
oauth_params_str = @oauth_helper.oauth_parameters.map { |k,v| [escape(k), escape(v)] * "=" }.join("&")
uri = URI.parse(path)
if uri.query.to_s == ""
uri.query = oauth_params_str
else
uri.query = uri.query + "&" + oauth_params_str
end
@path = uri.to_s
@path << "&oauth_signature=#{escape(oauth_helper.signature)}"
end
end
oauth-ruby-0.5.3/lib/oauth/consumer.rb 0000664 0000000 0000000 00000032776 13111303321 0017667 0 ustar 00root root 0000000 0000000 require 'net/http'
require 'net/https'
require 'oauth/oauth'
require 'oauth/client/net_http'
require 'oauth/errors'
require 'cgi'
module OAuth
class Consumer
# determine the certificate authority path to verify SSL certs
CA_FILES = %W(#{ENV['SSL_CERT_FILE']} /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt /usr/share/curl/curl-ca-bundle.crt)
CA_FILES.each do |ca_file|
if File.exist?(ca_file)
CA_FILE = ca_file
break
end
end
CA_FILE = nil unless defined?(CA_FILE)
@@default_options = {
# Signature method used by server. Defaults to HMAC-SHA1
:signature_method => 'HMAC-SHA1',
# default paths on site. These are the same as the defaults set up by the generators
:request_token_path => '/oauth/request_token',
:authorize_path => '/oauth/authorize',
:access_token_path => '/oauth/access_token',
:proxy => nil,
# How do we send the oauth values to the server see
# http://oauth.net/core/1.0/#consumer_req_param for more info
#
# Possible values:
#
# :header - via the Authorize header (Default) ( option 1. in spec)
# :body - url form encoded in body of POST request ( option 2. in spec)
# :query_string - via the query part of the url ( option 3. in spec)
:scheme => :header,
# Default http method used for OAuth Token Requests (defaults to :post)
:http_method => :post,
# Add a custom ca_file for consumer
# :ca_file => '/etc/certs.pem'
# Possible values:
#
# nil, false - no debug output
# true - uses $stdout
# some_value - uses some_value
:debug_output => nil,
:oauth_version => "1.0"
}
attr_accessor :options, :key, :secret
attr_writer :site, :http
# Create a new consumer instance by passing it a configuration hash:
#
# @consumer = OAuth::Consumer.new(key, secret, {
# :site => "http://term.ie",
# :scheme => :header,
# :http_method => :post,
# :request_token_path => "/oauth/example/request_token.php",
# :access_token_path => "/oauth/example/access_token.php",
# :authorize_path => "/oauth/example/authorize.php"
# })
#
# Start the process by requesting a token
#
# @request_token = @consumer.get_request_token
# session[:request_token] = @request_token
# redirect_to @request_token.authorize_url
#
# When user returns create an access_token
#
# @access_token = @request_token.get_access_token
# @photos=@access_token.get('/photos.xml')
#
def initialize(consumer_key, consumer_secret, options = {})
@key = consumer_key
@secret = consumer_secret
# ensure that keys are symbols
@options = @@default_options.merge(options.inject({}) do |opts, (key, value)|
opts[key.to_sym] = value
opts
end)
end
# The default http method
def http_method
@http_method ||= @options[:http_method] || :post
end
def debug_output
@debug_output ||= begin
case @options[:debug_output]
when nil, false
when true
$stdout
else
@options[:debug_output]
end
end
end
# The HTTP object for the site. The HTTP Object is what you get when you do Net::HTTP.new
def http
@http ||= create_http
end
# Contains the root URI for this site
def uri(custom_uri = nil)
if custom_uri
@uri = custom_uri
@http = create_http # yike, oh well. less intrusive this way
else # if no custom passed, we use existing, which, if unset, is set to site uri
@uri ||= URI.parse(site)
end
end
def get_access_token(request_token, request_options = {}, *arguments, &block)
response = token_request(http_method, (access_token_url? ? access_token_url : access_token_path), request_token, request_options, *arguments, &block)
OAuth::AccessToken.from_hash(self, response)
end
# Makes a request to the service for a new OAuth::RequestToken
#
# @request_token = @consumer.get_request_token
#
# To include OAuth parameters:
#
# @request_token = @consumer.get_request_token \
# :oauth_callback => "http://example.com/cb"
#
# To include application-specific parameters:
#
# @request_token = @consumer.get_request_token({}, :foo => "bar")
#
# TODO oauth_callback should be a mandatory parameter
def get_request_token(request_options = {}, *arguments, &block)
# if oauth_callback wasn't provided, it is assumed that oauth_verifiers
# will be exchanged out of band
request_options[:oauth_callback] ||= OAuth::OUT_OF_BAND unless request_options[:exclude_callback]
if block_given?
response = token_request(http_method,
(request_token_url? ? request_token_url : request_token_path),
nil,
request_options,
*arguments, &block)
else
response = token_request(http_method, (request_token_url? ? request_token_url : request_token_path), nil, request_options, *arguments)
end
OAuth::RequestToken.from_hash(self, response)
end
# Creates, signs and performs an http request.
# It's recommended to use the OAuth::Token classes to set this up correctly.
# request_options take precedence over consumer-wide options when signing
# a request.
# arguments are POST and PUT bodies (a Hash, string-encoded parameters, or
# absent), followed by additional HTTP headers.
#
# @consumer.request(:get, '/people', @token, { :scheme => :query_string })
# @consumer.request(:post, '/people', @token, {}, @person.to_xml, { 'Content-Type' => 'application/xml' })
#
def request(http_method, path, token = nil, request_options = {}, *arguments)
if path !~ /^\//
@http = create_http(path)
_uri = URI.parse(path)
path = "#{_uri.path}#{_uri.query ? "?#{_uri.query}" : ""}"
end
# override the request with your own, this is useful for file uploads which Net::HTTP does not do
req = create_signed_request(http_method, path, token, request_options, *arguments)
return nil if block_given? and yield(req) == :done
rsp = http.request(req)
# check for an error reported by the Problem Reporting extension
# (http://wiki.oauth.net/ProblemReporting)
# note: a 200 may actually be an error; check for an oauth_problem key to be sure
if !(headers = rsp.to_hash["www-authenticate"]).nil? &&
(h = headers.select { |hdr| hdr =~ /^OAuth / }).any? &&
h.first =~ /oauth_problem/
# puts "Header: #{h.first}"
# TODO doesn't handle broken responses from api.login.yahoo.com
# remove debug code when done
params = OAuth::Helper.parse_header(h.first)
# puts "Params: #{params.inspect}"
# puts "Body: #{rsp.body}"
raise OAuth::Problem.new(params.delete("oauth_problem"), rsp, params)
end
rsp
end
# Creates and signs an http request.
# It's recommended to use the Token classes to set this up correctly
def create_signed_request(http_method, path, token = nil, request_options = {}, *arguments)
request = create_http_request(http_method, path, *arguments)
sign!(request, token, request_options)
request
end
# Creates a request and parses the result as url_encoded. This is used internally for the RequestToken and AccessToken requests.
def token_request(http_method, path, token = nil, request_options = {}, *arguments)
request_options[:token_request] ||= true
response = request(http_method, path, token, request_options, *arguments)
case response.code.to_i
when (200..299)
if block_given?
yield response.body
else
# symbolize keys
# TODO this could be considered unexpected behavior; symbols or not?
# TODO this also drops subsequent values from multi-valued keys
CGI.parse(response.body).inject({}) do |h,(k,v)|
h[k.strip.to_sym] = v.first
h[k.strip] = v.first
h
end
end
when (300..399)
# this is a redirect
uri = URI.parse(response['location'])
response.error! if uri.path == path # careful of those infinite redirects
self.token_request(http_method, uri.path, token, request_options, arguments)
when (400..499)
raise OAuth::Unauthorized, response
else
response.error!
end
end
# Sign the Request object. Use this if you have an externally generated http request object you want to sign.
def sign!(request, token = nil, request_options = {})
request.oauth!(http, self, token, options.merge(request_options))
end
# Return the signature_base_string
def signature_base_string(request, token = nil, request_options = {})
request.signature_base_string(http, self, token, options.merge(request_options))
end
def site
@options[:site].to_s
end
def request_endpoint
return nil if @options[:request_endpoint].nil?
@options[:request_endpoint].to_s
end
def scheme
@options[:scheme]
end
def request_token_path
@options[:request_token_path]
end
def authorize_path
@options[:authorize_path]
end
def access_token_path
@options[:access_token_path]
end
# TODO this is ugly, rewrite
def request_token_url
@options[:request_token_url] || site + request_token_path
end
def request_token_url?
@options.has_key?(:request_token_url)
end
def authorize_url
@options[:authorize_url] || site + authorize_path
end
def authorize_url?
@options.has_key?(:authorize_url)
end
def access_token_url
@options[:access_token_url] || site + access_token_path
end
def access_token_url?
@options.has_key?(:access_token_url)
end
def proxy
@options[:proxy]
end
protected
# Instantiates the http object
def create_http(_url = nil)
if !request_endpoint.nil?
_url = request_endpoint
end
if _url.nil? || _url[0] =~ /^\//
our_uri = URI.parse(site)
else
our_uri = URI.parse(_url)
end
if proxy.nil?
http_object = Net::HTTP.new(our_uri.host, our_uri.port)
else
proxy_uri = proxy.is_a?(URI) ? proxy : URI.parse(proxy)
http_object = Net::HTTP.new(our_uri.host, our_uri.port, proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password)
end
http_object.use_ssl = (our_uri.scheme == 'https')
if @options[:ca_file] || CA_FILE
http_object.ca_file = @options[:ca_file] || CA_FILE
http_object.verify_mode = OpenSSL::SSL::VERIFY_PEER
http_object.verify_depth = 5
else
http_object.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
http_object.read_timeout = http_object.open_timeout = @options[:timeout] || 30
http_object.open_timeout = @options[:open_timeout] if @options[:open_timeout]
http_object.ssl_version = @options[:ssl_version] if @options[:ssl_version]
http_object.set_debug_output(debug_output) if debug_output
http_object
end
# create the http request object for a given http_method and path
def create_http_request(http_method, path, *arguments)
http_method = http_method.to_sym
if [:post, :put, :patch].include?(http_method)
data = arguments.shift
end
# if the base site contains a path, add it now
# only add if the site host matches the current http object's host
# (in case we've specified a full url for token requests)
uri = URI.parse(site)
path = uri.path + path if uri.path && uri.path != '/' && uri.host == http.address
headers = arguments.first.is_a?(Hash) ? arguments.shift : {}
case http_method
when :post
request = Net::HTTP::Post.new(path,headers)
request["Content-Length"] = '0' # Default to 0
when :put
request = Net::HTTP::Put.new(path,headers)
request["Content-Length"] = '0' # Default to 0
when :patch
request = Net::HTTP::Patch.new(path,headers)
request["Content-Length"] = '0' # Default to 0
when :get
request = Net::HTTP::Get.new(path,headers)
when :delete
request = Net::HTTP::Delete.new(path,headers)
when :head
request = Net::HTTP::Head.new(path,headers)
else
raise ArgumentError, "Don't know how to handle http_method: :#{http_method.to_s}"
end
if data.is_a?(Hash)
request.body = OAuth::Helper.normalize(data)
request.content_type = 'application/x-www-form-urlencoded'
elsif data
if data.respond_to?(:read)
request.body_stream = data
if data.respond_to?(:length)
request["Content-Length"] = data.length.to_s
elsif data.respond_to?(:stat) && data.stat.respond_to?(:size)
request["Content-Length"] = data.stat.size.to_s
else
raise ArgumentError, "Don't know how to send a body_stream that doesn't respond to .length or .stat.size"
end
else
request.body = data.to_s
request["Content-Length"] = request.body.length.to_s
end
end
request
end
def marshal_dump(*args)
{:key => @key, :secret => @secret, :options => @options}
end
def marshal_load(data)
initialize(data[:key], data[:secret], data[:options])
end
end
end
oauth-ruby-0.5.3/lib/oauth/core_ext.rb 0000664 0000000 0000000 00000002267 13111303321 0017634 0 ustar 00root root 0000000 0000000 # these are to backport methods from 1.8.7/1.9.1 to 1.8.6
class Object
unless method_defined?(:tap)
def tap
yield self
self
end
end
end
class String
unless method_defined?(:bytesize)
def bytesize
self.size
end
end
unless method_defined?(:bytes)
def bytes
require 'enumerator'
Enumerable::Enumerator.new(self, :each_byte)
end
end
end
# TODO: Work around URI.escape obsolete method
#
# 21/May/2016 - We are silencing a warning introduced in 2009
# https://github.com/ruby/ruby/commit/238b979f1789f95262a267d8df6239806f2859cc
#
# The only clear alternative to this problem is to invoke CGI.escape instead
# but that one does not take a secondary argument so we can pass OAuth::RESERVED_CHARACTERS
# As of today, ignoring this secondary argument would introduce 44 errors on our tests
# 181 runs, 511 assertions, 44 failures, 0 errors, 0 skips
#
# If you have a proper way to work around this so we don't need to override ruby core code
# Please send us a Pull Request
module URI
module Escape
def escape(*arg)
DEFAULT_PARSER.escape(*arg)
end
def unescape(*arg)
DEFAULT_PARSER.unescape(*arg)
end
end
end
oauth-ruby-0.5.3/lib/oauth/errors.rb 0000664 0000000 0000000 00000000140 13111303321 0017324 0 ustar 00root root 0000000 0000000 require 'oauth/errors/error'
require 'oauth/errors/unauthorized'
require 'oauth/errors/problem'
oauth-ruby-0.5.3/lib/oauth/errors/ 0000775 0000000 0000000 00000000000 13111303321 0017004 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/lib/oauth/errors/error.rb 0000664 0000000 0000000 00000000065 13111303321 0020463 0 ustar 00root root 0000000 0000000 module OAuth
class Error < StandardError
end
end
oauth-ruby-0.5.3/lib/oauth/errors/problem.rb 0000664 0000000 0000000 00000000411 13111303321 0020765 0 ustar 00root root 0000000 0000000 module OAuth
class Problem < OAuth::Unauthorized
attr_reader :problem, :params
def initialize(problem, request = nil, params = {})
super(request)
@problem = problem
@params = params
end
def to_s
problem
end
end
end
oauth-ruby-0.5.3/lib/oauth/errors/unauthorized.rb 0000664 0000000 0000000 00000000331 13111303321 0022047 0 ustar 00root root 0000000 0000000 module OAuth
class Unauthorized < OAuth::Error
attr_reader :request
def initialize(request = nil)
@request = request
end
def to_s
[request.code, request.message] * " "
end
end
end
oauth-ruby-0.5.3/lib/oauth/helper.rb 0000664 0000000 0000000 00000007264 13111303321 0017305 0 ustar 00root root 0000000 0000000 require 'openssl'
require 'base64'
module OAuth
module Helper
extend self
# Escape +value+ by URL encoding all non-reserved character.
#
# See Also: {OAuth core spec version 1.0, section 5.1}[http://oauth.net/core/1.0#rfc.section.5.1]
def escape(value)
_escape(value.to_s.to_str)
rescue ArgumentError
_escape(value.to_s.to_str.force_encoding(Encoding::UTF_8))
end
def _escape(string)
URI.escape(string, OAuth::RESERVED_CHARACTERS)
end
def unescape(value)
URI.unescape(value.gsub('+', '%2B'))
end
# Generate a random key of up to +size+ bytes. The value returned is Base64 encoded with non-word
# characters removed.
def generate_key(size=32)
Base64.encode64(OpenSSL::Random.random_bytes(size)).gsub(/\W/, '')
end
alias_method :generate_nonce, :generate_key
def generate_timestamp #:nodoc:
Time.now.to_i.to_s
end
# Normalize a +Hash+ of parameter values. Parameters are sorted by name, using lexicographical
# byte value ordering. If two or more parameters share the same name, they are sorted by their value.
# Parameters are concatenated in their sorted order into a single string. For each parameter, the name
# is separated from the corresponding value by an "=" character, even if the value is empty. Each
# name-value pair is separated by an "&" character.
#
# See Also: {OAuth core spec version 1.0, section 9.1.1}[http://oauth.net/core/1.0#rfc.section.9.1.1]
def normalize(params)
params.sort.map do |k, values|
if values.is_a?(Array)
# make sure the array has an element so we don't lose the key
values << nil if values.empty?
# multiple values were provided for a single key
values.sort.collect do |v|
[escape(k),escape(v)] * "="
end
elsif values.is_a?(Hash)
normalize_nested_query(values, k)
else
[escape(k),escape(values)] * "="
end
end * "&"
end
#Returns a string representation of the Hash like in URL query string
# build_nested_query({:level_1 => {:level_2 => ['value_1','value_2']}}, 'prefix'))
# #=> ["prefix%5Blevel_1%5D%5Blevel_2%5D%5B%5D=value_1", "prefix%5Blevel_1%5D%5Blevel_2%5D%5B%5D=value_2"]
def normalize_nested_query(value, prefix = nil)
case value
when Array
value.map do |v|
normalize_nested_query(v, "#{prefix}[]")
end.flatten.sort
when Hash
value.map do |k, v|
normalize_nested_query(v, prefix ? "#{prefix}[#{k}]" : k)
end.flatten.sort
else
[escape(prefix), escape(value)] * "="
end
end
# Parse an Authorization / WWW-Authenticate header into a hash. Takes care of unescaping and
# removing surrounding quotes. Raises a OAuth::Problem if the header is not parsable into a
# valid hash. Does not validate the keys or values.
#
# hash = parse_header(headers['Authorization'] || headers['WWW-Authenticate'])
# hash['oauth_timestamp']
# #=>"1234567890"
#
def parse_header(header)
# decompose
params = header[6,header.length].split(/[,=&]/)
# odd number of arguments - must be a malformed header.
raise OAuth::Problem.new("Invalid authorization header") if params.size % 2 != 0
params.map! do |v|
# strip and unescape
val = unescape(v.strip)
# strip quotes
val.sub(/^\"(.*)\"$/, '\1')
end
# convert into a Hash
Hash[*params.flatten]
end
def stringify_keys(hash)
new_h = {}
hash.each do |k, v|
new_h[k.to_s] = v.is_a?(Hash) ? stringify_keys(v) : v
end
new_h
end
end
end
oauth-ruby-0.5.3/lib/oauth/oauth.rb 0000664 0000000 0000000 00000001001 13111303321 0017125 0 ustar 00root root 0000000 0000000 module OAuth
# request tokens are passed between the consumer and the provider out of
# band (i.e. callbacks cannot be used), per section 6.1.1
OUT_OF_BAND = "oob"
# required parameters, per sections 6.1.1, 6.3.1, and 7
PARAMETERS = %w(oauth_callback oauth_consumer_key oauth_token
oauth_signature_method oauth_timestamp oauth_nonce oauth_verifier
oauth_version oauth_signature oauth_body_hash)
# reserved character regexp, per section 5.1
RESERVED_CHARACTERS = /[^a-zA-Z0-9\-\.\_\~]/
end
oauth-ruby-0.5.3/lib/oauth/oauth_test_helper.rb 0000664 0000000 0000000 00000001517 13111303321 0021537 0 ustar 00root root 0000000 0000000 require 'action_controller'
require 'action_controller/test_process'
module OAuth
module OAuthTestHelper
def mock_incoming_request_with_query(request)
incoming = ActionController::TestRequest.new(request.to_hash)
incoming.request_uri = request.path
incoming.host = request.uri.host
incoming.env["SERVER_PORT"] = request.uri.port
incoming.env['REQUEST_METHOD'] = request.http_method
incoming
end
def mock_incoming_request_with_authorize_header(request)
incoming = ActionController::TestRequest.new
incoming.request_uri = request.path
incoming.host = request.uri.host
incoming.env["HTTP_AUTHORIZATION"] = request.to_auth_string
incoming.env["SERVER_PORT"] = request.uri.port
incoming.env['REQUEST_METHOD'] = request.http_method
incoming
end
end
end
oauth-ruby-0.5.3/lib/oauth/request_proxy.rb 0000664 0000000 0000000 00000001212 13111303321 0020742 0 ustar 00root root 0000000 0000000 module OAuth
module RequestProxy
def self.available_proxies #:nodoc:
@available_proxies ||= {}
end
def self.proxy(request, options = {})
return request if request.kind_of?(OAuth::RequestProxy::Base)
klass = available_proxies[request.class]
# Search for possible superclass matches.
if klass.nil?
request_parent = available_proxies.keys.find { |rc| request.kind_of?(rc) }
klass = available_proxies[request_parent]
end
raise UnknownRequestType, request.class.to_s unless klass
klass.new(request, options)
end
class UnknownRequestType < Exception; end
end
end
oauth-ruby-0.5.3/lib/oauth/request_proxy/ 0000775 0000000 0000000 00000000000 13111303321 0020421 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/lib/oauth/request_proxy/action_controller_request.rb 0000664 0000000 0000000 00000004754 13111303321 0026250 0 ustar 00root root 0000000 0000000 require 'active_support'
require "active_support/version"
require 'action_controller'
require 'uri'
if
Gem::Version.new(ActiveSupport::VERSION::STRING) < Gem::Version.new("3")
then # rails 2.x
require 'action_controller/request'
unless ActionController::Request::HTTP_METHODS.include?("patch")
ActionController::Request::HTTP_METHODS << "patch"
ActionController::Request::HTTP_METHOD_LOOKUP["PATCH"] = :patch
ActionController::Request::HTTP_METHOD_LOOKUP["patch"] = :patch
end
elsif
Gem::Version.new(ActiveSupport::VERSION::STRING) < Gem::Version.new("4")
then # rails 3.x
require 'action_dispatch/http/request'
unless ActionDispatch::Request::HTTP_METHODS.include?("patch")
ActionDispatch::Request::HTTP_METHODS << "patch"
ActionDispatch::Request::HTTP_METHOD_LOOKUP["PATCH"] = :patch
ActionDispatch::Request::HTTP_METHOD_LOOKUP["patch"] = :patch
end
else # rails 4.x - already has patch
require 'action_dispatch/http/request'
end
module OAuth::RequestProxy
class ActionControllerRequest < OAuth::RequestProxy::Base
proxies(defined?(ActionDispatch::AbstractRequest) ? ActionDispatch::AbstractRequest : ActionDispatch::Request)
def method
request.method.to_s.upcase
end
def uri
request.url
end
def parameters
if options[:clobber_request]
options[:parameters] || {}
else
params = request_params.merge(query_params).merge(header_params)
params.stringify_keys! if params.respond_to?(:stringify_keys!)
params.merge(options[:parameters] || {})
end
end
# Override from OAuth::RequestProxy::Base to avoid roundtrip
# conversion to Hash or Array and thus preserve the original
# parameter names
def parameters_for_signature
params = []
params << options[:parameters].to_query if options[:parameters]
unless options[:clobber_request]
params << header_params.to_query
params << request.query_string unless query_string_blank?
if request.post? && request.content_type.to_s.downcase.start_with?("application/x-www-form-urlencoded")
params << request.raw_post
end
end
params.
join('&').split('&').
reject { |s| s.match(/\A\s*\z/) }.
map { |p| p.split('=').map{|esc| CGI.unescape(esc)} }.
reject { |kv| kv[0] == 'oauth_signature'}
end
protected
def query_params
request.query_parameters
end
def request_params
request.request_parameters
end
end
end
oauth-ruby-0.5.3/lib/oauth/request_proxy/base.rb 0000664 0000000 0000000 00000010503 13111303321 0021657 0 ustar 00root root 0000000 0000000 require 'oauth/request_proxy'
require 'oauth/helper'
module OAuth::RequestProxy
class Base
include OAuth::Helper
def self.proxies(klass)
OAuth::RequestProxy.available_proxies[klass] = self
end
attr_accessor :request, :options, :unsigned_parameters
def initialize(request, options = {})
@request = request
@unsigned_parameters = (options[:unsigned_parameters] || []).map {|param| param.to_s}
@options = options
end
## OAuth parameters
def oauth_callback
parameters['oauth_callback']
end
def oauth_consumer_key
parameters['oauth_consumer_key']
end
def oauth_nonce
parameters['oauth_nonce']
end
def oauth_signature
# TODO can this be nil?
[parameters['oauth_signature']].flatten.first || ""
end
def oauth_signature_method
case parameters['oauth_signature_method']
when Array
parameters['oauth_signature_method'].first
else
parameters['oauth_signature_method']
end
end
def oauth_timestamp
parameters['oauth_timestamp']
end
def oauth_token
parameters['oauth_token']
end
def oauth_verifier
parameters['oauth_verifier']
end
def oauth_version
parameters["oauth_version"]
end
# TODO deprecate these
alias_method :consumer_key, :oauth_consumer_key
alias_method :token, :oauth_token
alias_method :nonce, :oauth_nonce
alias_method :timestamp, :oauth_timestamp
alias_method :signature, :oauth_signature
alias_method :signature_method, :oauth_signature_method
## Parameter accessors
def parameters
raise NotImplementedError, "Must be implemented by subclasses"
end
def parameters_for_signature
parameters.select { |k,v| not signature_and_unsigned_parameters.include?(k) }
end
def oauth_parameters
parameters.select { |k,v| OAuth::PARAMETERS.include?(k) }.reject { |k,v| v == "" }
end
def non_oauth_parameters
parameters.reject { |k,v| OAuth::PARAMETERS.include?(k) }
end
def signature_and_unsigned_parameters
unsigned_parameters+["oauth_signature"]
end
# See 9.1.2 in specs
def normalized_uri
u = URI.parse(uri)
"#{u.scheme.downcase}://#{u.host.downcase}#{(u.scheme.downcase == 'http' && u.port != 80) || (u.scheme.downcase == 'https' && u.port != 443) ? ":#{u.port}" : ""}#{(u.path && u.path != '') ? u.path : '/'}"
end
# See 9.1.1. in specs Normalize Request Parameters
def normalized_parameters
normalize(parameters_for_signature)
end
def sign(options = {})
OAuth::Signature.sign(self, options)
end
def sign!(options = {})
parameters["oauth_signature"] = sign(options)
@signed = true
signature
end
# See 9.1 in specs
def signature_base_string
base = [method, normalized_uri, normalized_parameters]
base.map { |v| escape(v) }.join("&")
end
# Has this request been signed yet?
def signed?
@signed
end
# URI, including OAuth parameters
def signed_uri(with_oauth = true)
if signed?
if with_oauth
params = parameters
else
params = non_oauth_parameters
end
[uri, normalize(params)] * "?"
else
STDERR.puts "This request has not yet been signed!"
end
end
# Authorization header for OAuth
def oauth_header(options = {})
header_params_str = oauth_parameters.map { |k,v| "#{k}=\"#{escape(v)}\"" }.join(', ')
realm = "realm=\"#{options[:realm]}\", " if options[:realm]
"OAuth #{realm}#{header_params_str}"
end
def query_string_blank?
if uri = request.env['REQUEST_URI']
uri.split('?', 2)[1].nil?
else
request.query_string.match(/\A\s*\z/)
end
end
protected
def header_params
%w( X-HTTP_AUTHORIZATION Authorization HTTP_AUTHORIZATION ).each do |header|
next unless request.env.include?(header)
header = request.env[header]
next unless header[0,6] == 'OAuth '
# parse the header into a Hash
oauth_params = OAuth::Helper.parse_header(header)
# remove non-OAuth parameters
oauth_params.reject! { |k,v| k !~ /^oauth_/ }
return oauth_params
end
return {}
end
end
end
oauth-ruby-0.5.3/lib/oauth/request_proxy/curb_request.rb 0000664 0000000 0000000 00000002563 13111303321 0023457 0 ustar 00root root 0000000 0000000 require 'oauth/request_proxy/base'
require 'curb'
require 'uri'
require 'cgi'
module OAuth::RequestProxy::Curl
class Easy < OAuth::RequestProxy::Base
# Proxy for signing Curl::Easy requests
# Usage example:
# oauth_params = {:consumer => oauth_consumer, :token => access_token}
# req = Curl::Easy.new(uri)
# oauth_helper = OAuth::Client::Helper.new(req, oauth_params.merge(:request_uri => uri))
# req.headers.merge!({"Authorization" => oauth_helper.header})
# req.http_get
# response = req.body_str
proxies ::Curl::Easy
def method
nil
end
def uri
options[:uri].to_s
end
def parameters
if options[:clobber_request]
options[:parameters]
else
post_parameters.merge(query_parameters).merge(options[:parameters] || {})
end
end
private
def query_parameters
query = URI.parse(request.url).query
return(query ? CGI.parse(query) : {})
end
def post_parameters
post_body = {}
# Post params are only used if posting form data
if (request.headers['Content-Type'] && request.headers['Content-Type'].to_s.downcase.start_with?("application/x-www-form-urlencoded"))
request.post_body.split("&").each do |str|
param = str.split("=")
post_body[param[0]] = param[1]
end
end
post_body
end
end
end
oauth-ruby-0.5.3/lib/oauth/request_proxy/em_http_request.rb 0000664 0000000 0000000 00000003104 13111303321 0024154 0 ustar 00root root 0000000 0000000 require 'oauth/request_proxy/base'
# em-http also uses adddressable so there is no need to require uri.
require 'em-http'
require 'cgi'
module OAuth::RequestProxy::EventMachine
class HttpRequest < OAuth::RequestProxy::Base
# A Proxy for use when you need to sign EventMachine::HttpClient instances.
# It needs to be called once the client is construct but before data is sent.
# Also see oauth/client/em-http
proxies ::EventMachine::HttpClient
# Request in this con
def method
request.method
end
def uri
request.normalize_uri.to_s
end
def parameters
if options[:clobber_request]
options[:parameters]
else
all_parameters
end
end
protected
def all_parameters
merged_parameters({}, post_parameters, query_parameters, options[:parameters])
end
def query_parameters
CGI.parse(request.normalize_uri.query.to_s)
end
def post_parameters
headers = request.options[:head] || {}
form_encoded = headers['Content-Type'].to_s.downcase.start_with?("application/x-www-form-urlencoded")
if ['POST', 'PUT'].include?(method) && form_encoded
CGI.parse(request.normalize_body.to_s)
else
{}
end
end
def merged_parameters(params, *extra_params)
extra_params.compact.each do |params_pairs|
params_pairs.each_pair do |key, value|
if params.has_key?(key)
params[key] += value
else
params[key] = [value].flatten
end
end
end
params
end
end
end
oauth-ruby-0.5.3/lib/oauth/request_proxy/jabber_request.rb 0000664 0000000 0000000 00000001603 13111303321 0023743 0 ustar 00root root 0000000 0000000 require 'xmpp4r'
require 'oauth/request_proxy/base'
module OAuth
module RequestProxy
class JabberRequest < OAuth::RequestProxy::Base
proxies Jabber::Iq
proxies Jabber::Presence
proxies Jabber::Message
def parameters
return @params if @params
@params = {}
oauth = @request.get_elements('//oauth').first
return @params unless oauth
%w( oauth_token oauth_consumer_key oauth_signature_method oauth_signature
oauth_timestamp oauth_nonce oauth_version ).each do |param|
next unless element = oauth.first_element(param)
@params[param] = element.text
end
@params
end
def method
@request.name
end
def uri
[@request.from.strip.to_s, @request.to.strip.to_s].join("&")
end
def normalized_uri
uri
end
end
end
end
oauth-ruby-0.5.3/lib/oauth/request_proxy/mock_request.rb 0000664 0000000 0000000 00000002133 13111303321 0023446 0 ustar 00root root 0000000 0000000 require 'oauth/request_proxy/base'
module OAuth
module RequestProxy
# RequestProxy for Hashes to facilitate simpler signature creation.
# Usage:
# request = OAuth::RequestProxy.proxy \
# "method" => "iq",
# "uri" => [from, to] * "&",
# "parameters" => {
# "oauth_consumer_key" => oauth_consumer_key,
# "oauth_token" => oauth_token,
# "oauth_signature_method" => "HMAC-SHA1"
# }
#
# signature = OAuth::Signature.sign \
# request,
# :consumer_secret => oauth_consumer_secret,
# :token_secret => oauth_token_secret,
class MockRequest < OAuth::RequestProxy::Base
proxies Hash
def parameters
@request["parameters"]
end
def method
@request["method"]
end
def normalized_uri
super
rescue
# if this is a non-standard URI, it may not parse properly
# in that case, assume that it's already been normalized
uri
end
def uri
@request["uri"]
end
end
end
end
oauth-ruby-0.5.3/lib/oauth/request_proxy/net_http.rb 0000664 0000000 0000000 00000003232 13111303321 0022573 0 ustar 00root root 0000000 0000000 require 'oauth/request_proxy/base'
require 'net/http'
require 'uri'
require 'cgi'
module OAuth::RequestProxy::Net
module HTTP
class HTTPRequest < OAuth::RequestProxy::Base
proxies ::Net::HTTPGenericRequest
def method
request.method
end
def uri
options[:uri].to_s
end
def parameters
if options[:clobber_request]
options[:parameters]
else
all_parameters
end
end
def body
request.body
end
private
def all_parameters
request_params = CGI.parse(query_string)
# request_params.each{|k,v| request_params[k] = [nil] if v == []}
if options[:parameters]
options[:parameters].each do |k,v|
if request_params.has_key?(k) && v
request_params[k] << v
else
request_params[k] = [v]
end
end
end
request_params
end
def query_string
params = [ query_params, auth_header_params ]
params << post_params if (method.to_s.upcase == 'POST' || method.to_s.upcase == 'PUT') && form_url_encoded?
params.compact.join('&')
end
def form_url_encoded?
request['Content-Type'] != nil && request['Content-Type'].to_s.downcase.start_with?('application/x-www-form-urlencoded')
end
def query_params
URI.parse(request.path).query
end
def post_params
request.body
end
def auth_header_params
return nil unless request['Authorization'] && request['Authorization'][0,5] == 'OAuth'
request['Authorization']
end
end
end
end
oauth-ruby-0.5.3/lib/oauth/request_proxy/rack_request.rb 0000664 0000000 0000000 00000001572 13111303321 0023443 0 ustar 00root root 0000000 0000000 require 'oauth/request_proxy/base'
require 'uri'
require 'rack'
module OAuth::RequestProxy
class RackRequest < OAuth::RequestProxy::Base
proxies Rack::Request
def method
request.env["rack.methodoverride.original_method"] || request.request_method
end
def uri
request.url
end
def parameters
if options[:clobber_request]
options[:parameters] || {}
else
params = request_params.merge(query_params).merge(header_params)
params.merge(options[:parameters] || {})
end
end
def signature
parameters['oauth_signature']
end
protected
def query_params
request.GET
end
def request_params
if request.content_type and request.content_type.to_s.downcase.start_with?("application/x-www-form-urlencoded")
request.POST
else
{}
end
end
end
end
oauth-ruby-0.5.3/lib/oauth/request_proxy/rest_client_request.rb 0000664 0000000 0000000 00000002505 13111303321 0025033 0 ustar 00root root 0000000 0000000 require 'oauth/request_proxy/base'
require 'rest-client'
require 'uri'
require 'cgi'
module OAuth::RequestProxy::RestClient
class Request < OAuth::RequestProxy::Base
proxies RestClient::Request
def method
request.method.to_s.upcase
end
def uri
request.url
end
def parameters
if options[:clobber_request]
options[:parameters] || {}
else
post_parameters.merge(query_params).merge(options[:parameters] || {})
end
end
protected
def query_params
query = URI.parse(request.url).query
query ? CGI.parse(query) : {}
end
def request_params
end
def post_parameters
# Post params are only used if posting form data
if method == 'POST' || method == 'PUT'
OAuth::Helper.stringify_keys(query_string_to_hash(request.payload.to_s) || {})
else
{}
end
end
private
def query_string_to_hash(query)
keyvals = query.split('&').inject({}) do |result, q|
k,v = q.split('=')
if !v.nil?
result.merge({k => v})
elsif !result.key?(k)
result.merge({k => true})
else
result
end
end
keyvals
end
end
end oauth-ruby-0.5.3/lib/oauth/request_proxy/typhoeus_request.rb 0000664 0000000 0000000 00000002614 13111303321 0024401 0 ustar 00root root 0000000 0000000 require 'oauth/request_proxy/base'
require 'typhoeus'
require 'typhoeus/request'
require 'uri'
require 'cgi'
module OAuth::RequestProxy::Typhoeus
class Request < OAuth::RequestProxy::Base
# Proxy for signing Typhoeus::Request requests
# Usage example:
# oauth_params = {:consumer => oauth_consumer, :token => access_token}
# req = Typhoeus::Request.new(uri, options)
# oauth_helper = OAuth::Client::Helper.new(req, oauth_params.merge(:request_uri => uri))
# req.options[:headers].merge!({"Authorization" => oauth_helper.header})
# hydra = Typhoeus::Hydra.new()
# hydra.queue(req)
# hydra.run
# response = req.response
proxies Typhoeus::Request
def method
request_method = request.options[:method].to_s.upcase
request_method.empty? ? 'GET' : request_method
end
def uri
options[:uri].to_s
end
def parameters
if options[:clobber_request]
options[:parameters]
else
post_parameters.merge(query_parameters).merge(options[:parameters] || {})
end
end
private
def query_parameters
query = URI.parse(request.url).query
query ? CGI.parse(query) : {}
end
def post_parameters
# Post params are only used if posting form data
if method == 'POST'
OAuth::Helper.stringify_keys(request.options[:params] || {})
else
{}
end
end
end
end
oauth-ruby-0.5.3/lib/oauth/server.rb 0000664 0000000 0000000 00000003000 13111303321 0017314 0 ustar 00root root 0000000 0000000 require 'oauth/helper'
require 'oauth/consumer'
module OAuth
# This is mainly used to create consumer credentials and can pretty much be ignored if you want to create your own
class Server
include OAuth::Helper
attr_accessor :base_url
@@server_paths = {
:request_token_path => "/oauth/request_token",
:authorize_path => "/oauth/authorize",
:access_token_path => "/oauth/access_token"
}
# Create a new server instance
def initialize(base_url, paths = {})
@base_url = base_url
@paths = @@server_paths.merge(paths)
end
def generate_credentials
[generate_key(16), generate_key]
end
def generate_consumer_credentials(params = {})
Consumer.new(*generate_credentials)
end
# mainly for testing purposes
def create_consumer
creds = generate_credentials
Consumer.new(creds[0], creds[1],
{
:site => base_url,
:request_token_path => request_token_path,
:authorize_path => authorize_path,
:access_token_path => access_token_path
})
end
def request_token_path
@paths[:request_token_path]
end
def request_token_url
base_url + request_token_path
end
def authorize_path
@paths[:authorize_path]
end
def authorize_url
base_url + authorize_path
end
def access_token_path
@paths[:access_token_path]
end
def access_token_url
base_url + access_token_path
end
end
end
oauth-ruby-0.5.3/lib/oauth/signature.rb 0000664 0000000 0000000 00000003017 13111303321 0020017 0 ustar 00root root 0000000 0000000 module OAuth
module Signature
# Returns a list of available signature methods
def self.available_methods
@available_methods ||= {}
end
# Build a signature from a +request+.
#
# Raises UnknownSignatureMethod exception if the signature method is unknown.
def self.build(request, options = {}, &block)
request = OAuth::RequestProxy.proxy(request, options)
klass = available_methods[
(request.signature_method ||
((c = request.options[:consumer]) && c.options[:signature_method]) ||
"").downcase]
raise UnknownSignatureMethod, request.signature_method unless klass
klass.new(request, options, &block)
end
# Sign a +request+
def self.sign(request, options = {}, &block)
self.build(request, options, &block).signature
end
# Verify the signature of +request+
def self.verify(request, options = {}, &block)
self.build(request, options, &block).verify
end
# Create the signature base string for +request+. This string is the normalized parameter information.
#
# See Also: {OAuth core spec version 1.0, section 9.1.1}[http://oauth.net/core/1.0#rfc.section.9.1.1]
def self.signature_base_string(request, options = {}, &block)
self.build(request, options, &block).signature_base_string
end
# Create the body hash for a request
def self.body_hash(request, options = {}, &block)
self.build(request, options, &block).body_hash
end
class UnknownSignatureMethod < Exception; end
end
end
oauth-ruby-0.5.3/lib/oauth/signature/ 0000775 0000000 0000000 00000000000 13111303321 0017471 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/lib/oauth/signature/base.rb 0000664 0000000 0000000 00000004572 13111303321 0020740 0 ustar 00root root 0000000 0000000 require 'oauth/signature'
require 'oauth/helper'
require 'oauth/request_proxy/base'
require 'base64'
module OAuth::Signature
class Base
include OAuth::Helper
attr_accessor :options
attr_reader :token_secret, :consumer_secret, :request
def self.implements(signature_method = nil)
return @implements if signature_method.nil?
@implements = signature_method
OAuth::Signature.available_methods[@implements] = self
end
def initialize(request, options = {}, &block)
raise TypeError unless request.kind_of?(OAuth::RequestProxy::Base)
@request = request
@options = options
## consumer secret was determined beforehand
@consumer_secret = options[:consumer].secret if options[:consumer]
# presence of :consumer_secret option will override any Consumer that's provided
@consumer_secret = options[:consumer_secret] if options[:consumer_secret]
## token secret was determined beforehand
@token_secret = options[:token].secret if options[:token]
# presence of :token_secret option will override any Token that's provided
@token_secret = options[:token_secret] if options[:token_secret]
# override secrets based on the values returned from the block (if any)
if block_given?
# consumer secret and token secret need to be looked up based on pieces of the request
secrets = yield block.arity == 1 ? request : [token, consumer_key, nonce, request.timestamp]
if secrets.is_a?(Array) && secrets.size == 2
@token_secret = secrets[0]
@consumer_secret = secrets[1]
end
end
end
def signature
Base64.encode64(digest).chomp.gsub(/\n/,'')
end
def ==(cmp_signature)
signature == cmp_signature
end
def verify
self == self.request.signature
end
def signature_base_string
request.signature_base_string
end
def body_hash
raise_instantiation_error
end
private
def token
request.token
end
def consumer_key
request.consumer_key
end
def nonce
request.nonce
end
def secret
"#{escape(consumer_secret)}{escape(token_secret)}"
end
def digest
raise_instantiation_error
end
def raise_instantiation_error
raise NotImplementedError, "Cannot instantiate #{self.class.name} class directly."
end
end
end
oauth-ruby-0.5.3/lib/oauth/signature/hmac/ 0000775 0000000 0000000 00000000000 13111303321 0020401 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/lib/oauth/signature/hmac/sha1.rb 0000664 0000000 0000000 00000000574 13111303321 0021570 0 ustar 00root root 0000000 0000000 require 'oauth/signature/base'
module OAuth::Signature::HMAC
class SHA1 < OAuth::Signature::Base
implements 'hmac-sha1'
def body_hash
Base64.encode64(OpenSSL::Digest::SHA1.digest(request.body || '')).chomp.gsub(/\n/,'')
end
private
def digest
OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha1'), secret, signature_base_string)
end
end
end
oauth-ruby-0.5.3/lib/oauth/signature/plaintext.rb 0000664 0000000 0000000 00000000605 13111303321 0022027 0 ustar 00root root 0000000 0000000 require 'oauth/signature/base'
module OAuth::Signature
class PLAINTEXT < Base
implements 'plaintext'
def signature
signature_base_string
end
def ==(cmp_signature)
signature.to_s == cmp_signature.to_s
end
def signature_base_string
secret
end
def body_hash
nil
end
private
def secret
super
end
end
end
oauth-ruby-0.5.3/lib/oauth/signature/rsa/ 0000775 0000000 0000000 00000000000 13111303321 0020256 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/lib/oauth/signature/rsa/sha1.rb 0000664 0000000 0000000 00000002410 13111303321 0021434 0 ustar 00root root 0000000 0000000 require 'oauth/signature/base'
module OAuth::Signature::RSA
class SHA1 < OAuth::Signature::Base
implements 'rsa-sha1'
def ==(cmp_signature)
public_key.verify(OpenSSL::Digest::SHA1.new, Base64.decode64(cmp_signature.is_a?(Array) ? cmp_signature.first : cmp_signature), signature_base_string)
end
def public_key
if consumer_secret.is_a?(String)
decode_public_key
elsif consumer_secret.is_a?(OpenSSL::X509::Certificate)
consumer_secret.public_key
else
consumer_secret
end
end
def body_hash
Base64.encode64(OpenSSL::Digest::SHA1.digest(request.body || '')).chomp.gsub(/\n/,'')
end
private
def decode_public_key
case consumer_secret
when /-----BEGIN CERTIFICATE-----/
OpenSSL::X509::Certificate.new( consumer_secret).public_key
else
OpenSSL::PKey::RSA.new( consumer_secret)
end
end
def digest
private_key = OpenSSL::PKey::RSA.new(
if options[:private_key_file]
IO.read(options[:private_key_file])
elsif options[:private_key]
options[:private_key]
else
consumer_secret
end
)
private_key.sign(OpenSSL::Digest::SHA1.new, signature_base_string)
end
end
end
oauth-ruby-0.5.3/lib/oauth/token.rb 0000664 0000000 0000000 00000000333 13111303321 0017134 0 ustar 00root root 0000000 0000000 # this exists for backwards-compatibility
require 'oauth/tokens/token'
require 'oauth/tokens/server_token'
require 'oauth/tokens/consumer_token'
require 'oauth/tokens/request_token'
require 'oauth/tokens/access_token'
oauth-ruby-0.5.3/lib/oauth/tokens/ 0000775 0000000 0000000 00000000000 13111303321 0016773 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/lib/oauth/tokens/access_token.rb 0000664 0000000 0000000 00000007114 13111303321 0021764 0 ustar 00root root 0000000 0000000 module OAuth
# The Access Token is used for the actual "real" web service calls that you perform against the server
class AccessToken < ConsumerToken
# The less intrusive way. Otherwise, if we are to do it correctly inside consumer,
# we need to restructure and touch more methods: request(), sign!(), etc.
def request(http_method, path, *arguments)
request_uri = URI.parse(path)
site_uri = consumer.uri
is_service_uri_different = (request_uri.absolute? && request_uri != site_uri)
begin
consumer.uri(request_uri) if is_service_uri_different
@response = super(http_method, path, *arguments)
ensure
# NOTE: reset for wholesomeness? meaning that we admit only AccessToken service calls may use different URIs?
# so reset in case consumer is still used for other token-management tasks subsequently?
consumer.uri(site_uri) if is_service_uri_different
end
@response
end
# Make a regular GET request using AccessToken
#
# @response = @token.get('/people')
# @response = @token.get('/people', { 'Accept'=>'application/xml' })
#
def get(path, headers = {})
request(:get, path, headers)
end
# Make a regular HEAD request using AccessToken
#
# @response = @token.head('/people')
#
def head(path, headers = {})
request(:head, path, headers)
end
# Make a regular POST request using AccessToken
#
# @response = @token.post('/people')
# @response = @token.post('/people', { :name => 'Bob', :email => 'bob@mailinator.com' })
# @response = @token.post('/people', { :name => 'Bob', :email => 'bob@mailinator.com' }, { 'Accept' => 'application/xml' })
# @response = @token.post('/people', nil, {'Accept' => 'application/xml' })
# @response = @token.post('/people', @person.to_xml, { 'Accept'=>'application/xml', 'Content-Type' => 'application/xml' })
#
def post(path, body = '', headers = {})
request(:post, path, body, headers)
end
# Make a regular PUT request using AccessToken
#
# @response = @token.put('/people/123')
# @response = @token.put('/people/123', { :name => 'Bob', :email => 'bob@mailinator.com' })
# @response = @token.put('/people/123', { :name => 'Bob', :email => 'bob@mailinator.com' }, { 'Accept' => 'application/xml' })
# @response = @token.put('/people/123', nil, { 'Accept' => 'application/xml' })
# @response = @token.put('/people/123', @person.to_xml, { 'Accept' => 'application/xml', 'Content-Type' => 'application/xml' })
#
def put(path, body = '', headers = {})
request(:put, path, body, headers)
end
# Make a regular PATCH request using AccessToken
#
# @response = @token.patch('/people/123')
# @response = @token.patch('/people/123', { :name => 'Bob', :email => 'bob@mailinator.com' })
# @response = @token.patch('/people/123', { :name => 'Bob', :email => 'bob@mailinator.com' }, { 'Accept' => 'application/xml' })
# @response = @token.patch('/people/123', nil, { 'Accept' => 'application/xml' })
# @response = @token.patch('/people/123', @person.to_xml, { 'Accept' => 'application/xml', 'Content-Type' => 'application/xml' })
#
def patch(path, body = '', headers = {})
request(:patch, path, body, headers)
end
# Make a regular DELETE request using AccessToken
#
# @response = @token.delete('/people/123')
# @response = @token.delete('/people/123', { 'Accept' => 'application/xml' })
#
def delete(path, headers = {})
request(:delete, path, headers)
end
end
end
oauth-ruby-0.5.3/lib/oauth/tokens/consumer_token.rb 0000664 0000000 0000000 00000001725 13111303321 0022360 0 ustar 00root root 0000000 0000000 module OAuth
# Superclass for tokens used by OAuth Clients
class ConsumerToken < Token
attr_accessor :consumer, :params
attr_reader :response
def self.from_hash(consumer, hash)
token = self.new(consumer, hash[:oauth_token], hash[:oauth_token_secret])
token.params = hash
token
end
def initialize(consumer, token="", secret="")
super(token, secret)
@consumer = consumer
@params = {}
end
# Make a signed request using given http_method to the path
#
# @token.request(:get, '/people')
# @token.request(:post, '/people', @person.to_xml, { 'Content-Type' => 'application/xml' })
#
def request(http_method, path, *arguments)
@response = consumer.request(http_method, path, self, {}, *arguments)
end
# Sign a request generated elsewhere using Net:HTTP::Post.new or friends
def sign!(request, options = {})
consumer.sign!(request, self, options)
end
end
end
oauth-ruby-0.5.3/lib/oauth/tokens/request_token.rb 0000664 0000000 0000000 00000002337 13111303321 0022215 0 ustar 00root root 0000000 0000000 module OAuth
# The RequestToken is used for the initial Request.
# This is normally created by the Consumer object.
class RequestToken < ConsumerToken
# Generate an authorization URL for user authorization
def authorize_url(params = nil)
return nil if self.token.nil?
params = (params || {}).merge(:oauth_token => self.token)
build_authorize_url(consumer.authorize_url, params)
end
def callback_confirmed?
params[:oauth_callback_confirmed] == "true"
end
# exchange for AccessToken on server
def get_access_token(options = {}, *arguments)
response = consumer.token_request(consumer.http_method, (consumer.access_token_url? ? consumer.access_token_url : consumer.access_token_path), self, options, *arguments)
OAuth::AccessToken.from_hash(consumer, response)
end
protected
# construct an authorization url
def build_authorize_url(base_url, params)
uri = URI.parse(base_url.to_s)
queries = {}
queries = Hash[URI.decode_www_form(uri.query)] if uri.query
# TODO doesn't handle array values correctly
queries.merge!(params) if params
uri.query = URI.encode_www_form(queries) if !queries.empty?
uri.to_s
end
end
end
oauth-ruby-0.5.3/lib/oauth/tokens/server_token.rb 0000664 0000000 0000000 00000000250 13111303321 0022023 0 ustar 00root root 0000000 0000000 module OAuth
# Used on the server for generating tokens
class ServerToken < Token
def initialize
super(generate_key(16), generate_key)
end
end
end
oauth-ruby-0.5.3/lib/oauth/tokens/token.rb 0000664 0000000 0000000 00000000521 13111303321 0020436 0 ustar 00root root 0000000 0000000 module OAuth
# Superclass for the various tokens used by OAuth
class Token
include OAuth::Helper
attr_accessor :token, :secret
def initialize(token, secret)
@token = token
@secret = secret
end
def to_query
"oauth_token=#{escape(token)}&oauth_token_secret=#{escape(secret)}"
end
end
end
oauth-ruby-0.5.3/lib/oauth/version.rb 0000664 0000000 0000000 00000000045 13111303321 0017501 0 ustar 00root root 0000000 0000000 module OAuth
VERSION = "0.5.3"
end
oauth-ruby-0.5.3/oauth.gemspec 0000664 0000000 0000000 00000003252 13111303321 0016271 0 ustar 00root root 0000000 0000000 # -*- encoding: utf-8 -*-
lib = File.expand_path("../lib/", __FILE__)
$:.unshift lib unless $:.include?(lib)
require "oauth/version"
Gem::Specification.new do |spec|
spec.name = "oauth"
spec.version = OAuth::VERSION
spec.license = "MIT"
spec.authors = ["Pelle Braendgaard", "Blaine Cook", "Larry Halff", "Jesse Clark", "Jon Crosby", "Seth Fitzsimmons", "Matt Sanford", "Aaron Quint"]
spec.email = "oauth-ruby@googlegroupspec.com"
spec.summary = "OAuth Core Ruby implementation"
spec.executables = ["oauth"]
spec.files = Dir.glob("lib/**/*.rb")
#spec.test_files = Dir.glob("test/**/*.rb") + Dir.glob('test/keys/*')
spec.extra_rdoc_files = [ "LICENSE", "README.rdoc", "TODO" ]
# This gem will work with 2.0 or greater...
spec.required_ruby_version = '>= 2.0'
# Nokogiri 1.7 does not accept Ruby 2.0
spec.add_development_dependency("nokogiri", "~> 1.6.8") if RUBY_VERSION < "2.1"
spec.add_development_dependency("rake")
spec.add_development_dependency("minitest")
spec.add_development_dependency("byebug")
spec.add_development_dependency("actionpack", "~> 4.0")
spec.add_development_dependency("iconv")
spec.add_development_dependency("rack", "~> 1.0")
spec.add_development_dependency("rack-test")
spec.add_development_dependency("mocha", ">= 0.9.12")
spec.add_development_dependency("typhoeus", ">= 0.1.13")
spec.add_development_dependency("em-http-request", "0.2.11")
spec.add_development_dependency("curb")
spec.add_development_dependency("webmock", "< 2.0")
spec.add_development_dependency("codeclimate-test-reporter")
spec.add_development_dependency("simplecov")
spec.add_development_dependency("rest-client")
end
oauth-ruby-0.5.3/test/ 0000775 0000000 0000000 00000000000 13111303321 0014561 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/test/cases/ 0000775 0000000 0000000 00000000000 13111303321 0015657 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/test/cases/oauth_case.rb 0000664 0000000 0000000 00000000751 13111303321 0020322 0 ustar 00root root 0000000 0000000 require 'minitest/autorun'
require 'oauth/signature'
require 'oauth/request_proxy/mock_request'
class OAuthCase < Minitest::Test
# avoid whining about a lack of tests
def run(*args)
@method_name ||= nil
return if @method_name.to_s == "default_test"
super
end
protected
# Creates a fake request
def request(params={},method='GET',uri="http://photos.example.net/photos")
OAuth::RequestProxy.proxy({'parameters'=>params,'method'=>method,'uri'=>uri})
end
end
oauth-ruby-0.5.3/test/cases/spec/ 0000775 0000000 0000000 00000000000 13111303321 0016611 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/test/cases/spec/1_0-final/ 0000775 0000000 0000000 00000000000 13111303321 0020257 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/test/cases/spec/1_0-final/test_construct_request_url.rb 0000664 0000000 0000000 00000004637 13111303321 0026333 0 ustar 00root root 0000000 0000000 require File.expand_path('../../../oauth_case', __FILE__)
# See http://oauth.net/core/1.0/#anchor14
#
#9.1.2. Construct Request URL
#
#The Signature Base String includes the request absolute URL, tying the signature to a specific endpoint. The URL used in the Signature Base String MUST include the scheme, authority, and path, and MUST exclude the query and fragment as defined by [RFC3986] section 3.
#
#If the absolute request URL is not available to the Service Provider (it is always available to the Consumer), it can be constructed by combining the scheme being used, the HTTP Host header, and the relative HTTP request URL. If the Host header is not available, the Service Provider SHOULD use the host name communicated to the Consumer in the documentation or other means.
#
#The Service Provider SHOULD document the form of URL used in the Signature Base String to avoid ambiguity due to URL normalization. Unless specified, URL scheme and authority MUST be lowercase and include the port number; http default port 80 and https default port 443 MUST be excluded.
#
#For example, the request:
#
# HTTP://Example.com:80/resource?id=123
#Is included in the Signature Base String as:
#
# http://example.com/resource
class ConstructRequestUrlTest < OAuthCase
def test_from_spec
assert_request_url("http://example.com/resource","HTTP://Example.com:80/resource?id=123")
end
def test_simple_url_with_ending_slash
assert_request_url("http://example.com/","http://example.com/")
end
def test_simple_url_without_ending_slash
assert_request_url("http://example.com/","http://example.com")
end
def test_of_normalized_http
assert_request_url("http://example.com/resource","http://example.com/resource")
end
def test_of_https
assert_request_url("https://example.com/resource","HTTPS://Example.com:443/resource?id=123")
end
def test_of_normalized_https
assert_request_url("https://example.com/resource","https://example.com/resource")
end
def test_of_http_with_non_standard_port
assert_request_url("http://example.com:8080/resource","http://example.com:8080/resource")
end
def test_of_https_with_non_standard_port
assert_request_url("https://example.com:8080/resource","https://example.com:8080/resource")
end
protected
def assert_request_url(expected,given,message=nil)
assert_equal expected, request({},'GET',given).normalized_uri, message
end
end
oauth-ruby-0.5.3/test/cases/spec/1_0-final/test_normalize_request_parameters.rb 0000664 0000000 0000000 00000005523 13111303321 0027643 0 ustar 00root root 0000000 0000000 require File.expand_path('../../../oauth_case', __FILE__)
# See http://oauth.net/core/1.0/#anchor14
#
# 9.1.1. Normalize Request Parameters
#
# The request parameters are collected, sorted and concatenated into a normalized string:
#
# Parameters in the OAuth HTTP Authorization header excluding the realm parameter.
# Parameters in the HTTP POST request body (with a content-type of application/x-www-form-urlencoded).
# HTTP GET parameters added to the URLs in the query part (as defined by [RFC3986] section 3).
# The oauth_signature parameter MUST be excluded.
#
# The parameters are normalized into a single string as follows:
#
# Parameters are sorted by name, using lexicographical byte value ordering.
# If two or more parameters share the same name, they are sorted by their value. For example:
#
# a=1, c=hi%20there, f=25, f=50, f=a, z=p, z=t
# Parameters are concatenated in their sorted order into a single string. For each parameter,
# the name is separated from the corresponding value by an ‘=’ character (ASCII code 61), even
# if the value is empty. Each name-value pair is separated by an ‘&’ character (ASCII code 38). For example:
# a=1&c=hi%20there&f=25&f=50&f=a&z=p&z=t
#
class NormalizeRequestParametersTest < OAuthCase
def test_parameters_for_signature
params={"a"=>1, "c"=>"hi there", "f"=>"a", "z"=>"t"}
assert_equal params,request(params).parameters_for_signature
end
def test_parameters_for_signature_removes_oauth_signature
params={"a"=>1, "c"=>"hi there", "f"=>"a", "z"=>"t"}
assert_equal params,request(params.merge({'oauth_signature'=>'blalbla'})).parameters_for_signature
end
def test_spec_example
assert_normalized 'a=1&c=hi%20there&f=25&f=50&f=a&z=p&z=t', { 'a' => 1, 'c' => 'hi there', 'f' => ['25', '50', 'a'], 'z' => ['p', 't'] }
end
def test_sorts_parameters_correctly
# values for 'f' are scrambled
assert_normalized 'a=1&c=hi%20there&f=5&f=70&f=a&z=p&z=t', { 'a' => 1, 'c' => 'hi there', 'f' => ['a', '70', '5'], 'z' => ['p', 't'] }
end
def test_empty
assert_normalized "",{}
end
# These are from the wiki http://wiki.oauth.net/TestCases
# in the section Normalize Request Parameters
# Parameters have already been x-www-form-urlencoded (i.e. + = )
def test_wiki1
assert_normalized "name=",{"name"=>nil}
end
def test_wiki2
assert_normalized "a=b",{'a'=>'b'}
end
def test_wiki3
assert_normalized "a=b&c=d",{'a'=>'b','c'=>'d'}
end
def test_wiki4
assert_normalized "a=x%20y&a=x%21y",{'a'=>["x!y","x y"]}
end
def test_wiki5
assert_normalized "x=a&x%21y=a",{"x!y"=>'a','x'=>'a'}
end
protected
def assert_normalized(expected,params,message=nil)
assert_equal expected, normalize_request_parameters(params), message
end
def normalize_request_parameters(params={})
request(params).normalized_parameters
end
end
oauth-ruby-0.5.3/test/cases/spec/1_0-final/test_parameter_encodings.rb 0000664 0000000 0000000 00000004124 13111303321 0025655 0 ustar 00root root 0000000 0000000 require File.expand_path('../../../oauth_case', __FILE__)
# See http://oauth.net/core/1.0/#encoding_parameters
#
# 5.1. Parameter Encoding
#
# All parameter names and values are escaped using the [RFC3986] percent-encoding (%xx) mechanism.
# Characters not in the unreserved character set ([RFC3986] section 2.3) MUST be encoded. Characters
# in the unreserved character set MUST NOT be encoded. Hexadecimal characters in encodings MUST be
# upper case. Text names and values MUST be encoded as UTF-8 octets before percent-encoding them per [RFC3629].
#
# unreserved = ALPHA, DIGIT, '-', '.', '_', '~'
#
class ParameterEncodingTest < OAuthCase
def test_encodings_alpha_num
assert_encoding 'abcABC123', 'abcABC123'
end
def test_encodings_non_escaped
assert_encoding '-._~', '-._~'
end
def test_encodings_percent
assert_encoding '%25', '%'
end
def test_encodings_plus
assert_encoding '%2B', '+'
end
def test_encodings_space
assert_encoding '%20', ' '
end
def test_encodings_query_param_symbols
assert_encoding '%26%3D%2A', '&=*'
end
def test_encodings_unicode_lf
assert_encoding '%0A', unicode_to_utf8('U+000A')
end
def test_encodings_unicode_space
assert_encoding '%20', unicode_to_utf8('U+0020')
end
def test_encodings_unicode_007f
assert_encoding '%7F', unicode_to_utf8('U+007F')
end
def test_encodings_unicode_0080
assert_encoding '%C2%80', unicode_to_utf8('U+0080')
end
def test_encoding_unicode_2708
assert_encoding '%E2%9C%88', unicode_to_utf8('U+2708')
end
def test_encodings_unicode_3001
assert_encoding '%E3%80%81', unicode_to_utf8('U+3001')
end
protected
def unicode_to_utf8(unicode)
return unicode if unicode =~ /\A[[:space:]]*\z/m
str = ''
unicode.scan(/(U\+(?:[[:digit:][:xdigit:]]{4,5}|10[[:digit:][:xdigit:]]{4})|.)/mu) do
c = $1
if c =~ /^U\+/
str << [c[2..-1].hex].pack('U*')
else
str << c
end
end
str
end
def assert_encoding(expected, given, message = nil)
assert_equal expected, OAuth::Helper.escape(given), message
end
end
oauth-ruby-0.5.3/test/cases/spec/1_0-final/test_signature_base_strings.rb 0000664 0000000 0000000 00000005532 13111303321 0026414 0 ustar 00root root 0000000 0000000 require File.expand_path('../../../oauth_case', __FILE__)
# See http://oauth.net/core/1.0/#anchor14
#
# 9.1. Signature Base String
#
# The Signature Base String is a consistent reproducible concatenation of the request elements
# into a single string. The string is used as an input in hashing or signing algorithms. The
# HMAC-SHA1 signature method provides both a standard and an example of using the Signature
# Base String with a signing algorithm to generate signatures. All the request parameters MUST
# be encoded as described in Parameter Encoding prior to constructing the Signature Base String.
#
class SignatureBaseStringTest < OAuthCase
def test_A_5_1
parameters={
'oauth_consumer_key'=>'dpf43f3p2l4k3l03',
'oauth_token'=>'nnch734d00sl2jdk',
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>'1191242096',
'oauth_nonce'=>'kllo9940pd9333jh',
'oauth_version'=>'1.0',
'file'=>'vacation.jpg',
'size'=>'original'
}
sbs='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'
assert_signature_base_string sbs,parameters,'GET',"http://photos.example.net/photos"
end
# These are from the wiki http://wiki.oauth.net/TestCases
# in the section Concatenate Test Elements
def test_wiki_1_simple_with_ending_slash
parameters={
'n'=>'v'
}
sbs='GET&http%3A%2F%2Fexample.com%2F&n%3Dv'
assert_signature_base_string sbs,parameters,'GET',"http://example.com/"
end
def test_wiki_2_simple_without_ending_slash
parameters={
'n'=>'v'
}
sbs='GET&http%3A%2F%2Fexample.com%2F&n%3Dv'
assert_signature_base_string sbs,parameters,'GET',"http://example.com"
end
def test_wiki_2_request_token
parameters={
'oauth_version'=>'1.0',
'oauth_consumer_key'=>'dpf43f3p2l4k3l03',
'oauth_timestamp'=>'1191242090',
'oauth_nonce'=>'hsu94j3884jdopsl',
'oauth_signature_method'=>'PLAINTEXT',
'oauth_signature'=>'ignored' }
sbs='POST&https%3A%2F%2Fphotos.example.net%2Frequest_token&oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dhsu94j3884jdopsl%26oauth_signature_method%3DPLAINTEXT%26oauth_timestamp%3D1191242090%26oauth_version%3D1.0'
assert_signature_base_string sbs,parameters,'POST',"https://photos.example.net/request_token"
end
protected
def assert_signature_base_string(expected,params={},method='GET',uri="http://photos.example.net/photos",message="Signature Base String does not match")
assert_equal expected, signature_base_string(params,method,uri), message
end
def signature_base_string(params={},method='GET',uri="http://photos.example.net/photos")
request(params,method,uri).signature_base_string
end
end
oauth-ruby-0.5.3/test/integration/ 0000775 0000000 0000000 00000000000 13111303321 0017104 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/test/integration/consumer_test.rb 0000664 0000000 0000000 00000034421 13111303321 0022327 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
module Integration
class ConsumerTest < Minitest::Test
def setup
@consumer=OAuth::Consumer.new(
'consumer_key_86cad9', '5888bf0345e5d237',
{
:site=>"http://blabla.bla",
:proxy=>"http://user:password@proxy.bla:8080",
:request_token_path=>"/oauth/example/request_token.php",
:access_token_path=>"/oauth/example/access_token.php",
:authorize_path=>"/oauth/example/authorize.php",
:scheme=>:header,
:http_method=>:get
})
@token = OAuth::ConsumerToken.new(@consumer,'token_411a7f', '3196ffd991c8ebdb')
@request_uri = URI.parse('http://example.com/test?key=value')
@request_parameters = { 'key' => 'value' }
@nonce = 225579211881198842005988698334675835446
@timestamp = "1199645624"
@consumer.http=Net::HTTP.new(@request_uri.host, @request_uri.port)
end
def test_that_signing_auth_headers_on_get_requests_works
request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s)
@token.sign!(request, {:nonce => @nonce, :timestamp => @timestamp})
assert_equal 'GET', request.method
assert_equal '/test?key=value', request.path
assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\"".delete(',').split.sort, request['authorization'].delete(',').split.sort
end
def test_that_setting_signature_method_on_consumer_effects_signing
require 'oauth/signature/plaintext'
request = Net::HTTP::Get.new(@request_uri.path)
consumer = @consumer.dup
consumer.options[:signature_method] = 'PLAINTEXT'
token = OAuth::ConsumerToken.new(consumer, 'token_411a7f', '3196ffd991c8ebdb')
token.sign!(request, {:nonce => @nonce, :timestamp => @timestamp})
refute_match( /oauth_signature_method="HMAC-SHA1"/, request['authorization'])
assert_match( /oauth_signature_method="PLAINTEXT"/, request['authorization'])
end
def test_that_setting_signature_method_on_consumer_effects_signature_base_string
require 'oauth/signature/plaintext'
request = Net::HTTP::Get.new(@request_uri.path)
consumer = @consumer.dup
consumer.options[:signature_method] = 'PLAINTEXT'
request = Net::HTTP::Get.new('/')
signature_base_string = consumer.signature_base_string(request)
refute_match( /HMAC-SHA1/, signature_base_string)
assert_equal( "#{consumer.secret}&", signature_base_string)
end
def test_that_plaintext_signature_works
# Invalid test because server expects double-escaped signature
require 'oauth/signature/plaintext'
# consumer = OAuth::Consumer.new("key", "secret",
# :site => "http://term.ie", :signature_method => 'PLAINTEXT')
# access_token = OAuth::AccessToken.new(consumer, 'accesskey', 'accesssecret')
# response = access_token.get("/oauth/example/echo_api.php?echo=hello")
# assert_equal 'echo=hello', response.body
end
def test_that_signing_auth_headers_on_post_requests_works
request = Net::HTTP::Post.new(@request_uri.path)
request.set_form_data( @request_parameters )
@token.sign!(request, {:nonce => @nonce, :timestamp => @timestamp})
# assert_equal "",request.oauth_helper.signature_base_string
assert_equal 'POST', request.method
assert_equal '/test', request.path
assert_equal 'key=value', request.body
assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\"".delete(',').split.sort, request['authorization'].delete(',').split.sort
end
def test_that_signing_post_params_works
request = Net::HTTP::Post.new(@request_uri.path)
request.set_form_data( @request_parameters )
@token.sign!(request, {:scheme => 'body', :nonce => @nonce, :timestamp => @timestamp})
assert_equal 'POST', request.method
assert_equal '/test', request.path
assert_match(/key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=26g7wHTtNO6ZWJaLltcueppHYiI%3[Dd]&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0/, request.body.split("&").sort.join("&"))
assert_nil request['authorization']
end
def test_that_using_auth_headers_on_get_on_create_signed_requests_works
request=@consumer.create_signed_request(:get,@request_uri.path+ "?" + request_parameters_to_s,@token,{:nonce => @nonce, :timestamp => @timestamp},@request_parameters)
assert_equal 'GET', request.method
assert_equal '/test?key=value', request.path
assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\"".delete(',').split.sort, request['authorization'].delete(',').split.sort
end
def test_that_using_auth_headers_on_post_on_create_signed_requests_works
request=@consumer.create_signed_request(:post,@request_uri.path,@token,{:nonce => @nonce, :timestamp => @timestamp},@request_parameters,{})
assert_equal 'POST', request.method
assert_equal '/test', request.path
assert_equal 'key=value', request.body
assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\"".delete(',').split.sort, request['authorization'].delete(',').split.sort
end
def test_that_signing_post_params_works_2
request=@consumer.create_signed_request(:post,@request_uri.path,@token,{:scheme => 'body', :nonce => @nonce, :timestamp => @timestamp},@request_parameters,{})
assert_equal 'POST', request.method
assert_equal '/test', request.path
assert_match(/key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=26g7wHTtNO6ZWJaLltcueppHYiI%3[Dd]&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0/, request.body.split("&").sort.join("&"))
assert_nil request['authorization']
end
def test_step_by_step_token_request
stub_test_ie
@consumer=OAuth::Consumer.new(
"key",
"secret",
{
:site=>"http://term.ie",
:request_token_path=>"/oauth/example/request_token.php",
:access_token_path=>"/oauth/example/access_token.php",
:authorize_path=>"/oauth/example/authorize.php",
:scheme=>:header
})
options={:nonce=>'nonce',:timestamp=>Time.now.to_i.to_s}
request = Net::HTTP::Get.new("/oauth/example/request_token.php")
signature_base_string=@consumer.signature_base_string(request,nil,options)
assert_equal "GET&http%3A%2F%2Fterm.ie%2Foauth%2Fexample%2Frequest_token.php&oauth_consumer_key%3Dkey%26oauth_nonce%3D#{options[:nonce]}%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D#{options[:timestamp]}%26oauth_version%3D1.0",signature_base_string
@consumer.sign!(request, nil,options)
assert_equal 'GET', request.method
assert_nil request.body
response=@consumer.http.request(request)
assert_equal "200",response.code
assert_equal "oauth_token=requestkey&oauth_token_secret=requestsecret",response.body
end
def test_get_token_sequence
stub_test_ie
@consumer=OAuth::Consumer.new(
"key",
"secret",
{
:site=>"http://term.ie",
:request_token_path=>"/oauth/example/request_token.php",
:access_token_path=>"/oauth/example/access_token.php",
:authorize_path=>"/oauth/example/authorize.php"
})
assert_equal "http://term.ie/oauth/example/request_token.php",@consumer.request_token_url
assert_equal "http://term.ie/oauth/example/access_token.php",@consumer.access_token_url
assert !@consumer.request_token_url?, "Should not use fully qualified request token url"
assert !@consumer.access_token_url?, "Should not use fully qualified access token url"
assert !@consumer.authorize_url?, "Should not use fully qualified url"
@request_token=@consumer.get_request_token
assert @request_token
assert_equal "requestkey",@request_token.token
assert_equal "requestsecret",@request_token.secret
assert_equal "http://term.ie/oauth/example/authorize.php?oauth_token=requestkey",@request_token.authorize_url
@access_token=@request_token.get_access_token
assert @access_token
assert_equal "accesskey",@access_token.token
assert_equal "accesssecret",@access_token.secret
@response=@access_token.get("/oauth/example/echo_api.php?ok=hello&test=this")
assert @response
assert_equal "200",@response.code
assert_equal( "ok=hello&test=this",@response.body)
@response=@access_token.post("/oauth/example/echo_api.php",{'ok'=>'hello','test'=>'this'})
assert @response
assert_equal "200",@response.code
assert_equal( "ok=hello&test=this",@response.body)
end
def test_get_token_sequence_using_fqdn
stub_test_ie
@consumer=OAuth::Consumer.new(
"key",
"secret",
{
:site=>"http://term.ie",
:request_token_url=>"http://term.ie/oauth/example/request_token.php",
:access_token_url=>"http://term.ie/oauth/example/access_token.php",
:authorize_url=>"http://term.ie/oauth/example/authorize.php"
})
assert_equal "http://term.ie/oauth/example/request_token.php",@consumer.request_token_url
assert_equal "http://term.ie/oauth/example/access_token.php",@consumer.access_token_url
assert @consumer.request_token_url?, "Should use fully qualified request token url"
assert @consumer.access_token_url?, "Should use fully qualified access token url"
assert @consumer.authorize_url?, "Should use fully qualified url"
@request_token=@consumer.get_request_token
assert @request_token
assert_equal "requestkey",@request_token.token
assert_equal "requestsecret",@request_token.secret
assert_equal "http://term.ie/oauth/example/authorize.php?oauth_token=requestkey",@request_token.authorize_url
@access_token=@request_token.get_access_token
assert @access_token
assert_equal "accesskey",@access_token.token
assert_equal "accesssecret",@access_token.secret
@response=@access_token.get("/oauth/example/echo_api.php?ok=hello&test=this")
assert @response
assert_equal "200",@response.code
assert_equal( "ok=hello&test=this",@response.body)
@response=@access_token.post("/oauth/example/echo_api.php",{'ok'=>'hello','test'=>'this'})
assert @response
assert_equal "200",@response.code
assert_equal( "ok=hello&test=this",@response.body)
end
# This test does an actual https request (the result doesn't matter)
# to initialize the same way as get_request_token does. Can be any
# site that supports https.
#
# It also generates "warning: using default DH parameters." which I
# don't know how to get rid of
# def test_serialization_with_https
# consumer = OAuth::Consumer.new('token', 'secret', :site => 'https://plazes.net')
# consumer.http.verify_mode = OpenSSL::SSL::VERIFY_NONE
# consumer.http.get('/')
#
# assert_nothing_raised do
# # Specifically this should not raise TypeError: no marshal_dump
# # is defined for class OpenSSL::SSL::SSLContext
# Marshal.dump(consumer)
# end
# end
#
def test_get_request_token_with_custom_arguments
stub_test_ie
@consumer=OAuth::Consumer.new(
"key",
"secret",
{
:site=>"http://term.ie",
:request_token_path=>"/oauth/example/request_token.php",
:access_token_path=>"/oauth/example/access_token.php",
:authorize_path=>"/oauth/example/authorize.php"
})
@consumer.get_request_token({}, {:scope => "http://www.google.com/calendar/feeds http://picasaweb.google.com/data"})
# Because this is a POST request, create_http_request should take the first element of *arguments
# and turn it into URL-encoded data in the body of the POST.
end
def test_post_with_body_stream
stub_test_ie
@consumer=OAuth::Consumer.new(
"key",
"secret",
{
:site=>"http://term.ie",
:request_token_path=>"/oauth/example/request_token.php",
:access_token_path=>"/oauth/example/access_token.php",
:authorize_path=>"/oauth/example/authorize.php"
})
@request_token=@consumer.get_request_token
@access_token=@request_token.get_access_token
request_body_string = "Hello, hello, hello"
request_body_stream = StringIO.new( request_body_string )
@response=@access_token.post("/oauth/example/echo_api.php",request_body_stream)
assert @response
assert_equal "200",@response.code
request_body_file = File.open(__FILE__)
@response=@access_token.post("/oauth/example/echo_api.php",request_body_file)
assert @response
assert_equal "200",@response.code
# unfortunately I don't know of a way to test that the body data was received correctly since the test server at http://term.ie
# echos back any non-oauth parameters but not the body. However, this does test that the request is still correctly signed
# (including the Content-Length header) and that the server received Content-Length bytes of body since it won't process the
# request & respond until the full body length is received.
end
private
def request_parameters_to_s
@request_parameters.map { |k,v| "#{k}=#{v}" }.join("&")
end
end
end
oauth-ruby-0.5.3/test/keys/ 0000775 0000000 0000000 00000000000 13111303321 0015534 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/test/keys/rsa.cert 0000664 0000000 0000000 00000001166 13111303321 0017204 0 ustar 00root root 0000000 0000000 -----BEGIN CERTIFICATE-----
MIIBpjCCAQ+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAZMRcwFQYDVQQDDA5UZXN0
IFByaW5jaXBhbDAeFw03MDAxMDEwODAwMDBaFw0zODEyMzEwODAwMDBaMBkxFzAV
BgNVBAMMDlRlc3QgUHJpbmNpcGFsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB
gQC0YjCwIfYoprq/FQO6lb3asXrxLlJFuCvtinTF5p0GxvQGu5O3gYytUvtC2JlY
zypSRjVxwxrsuRcP3e641SdASwfrmzyvIgP08N4S0IFzEURkV1wp/IpH7kH41Etb
mUmrXSwfNZsnQRE5SYSOhh+LcK2wyQkdgcMv11l4KoBkcwIDAQABMA0GCSqGSIb3
DQEBBQUAA4GBAGZLPEuJ5SiJ2ryq+CmEGOXfvlTtEL2nuGtr9PewxkgnOjZpUy+d
4TvuXJbNQc8f4AMWL/tO9w0Fk80rWKp9ea8/df4qMq5qlFWlx6yOLQxumNOmECKb
WpkUQDIDJEoFUzKMVuJf4KO/FJ345+BNLGgbJ6WujreoM1X/gYfdnJ/J
-----END CERTIFICATE----- oauth-ruby-0.5.3/test/keys/rsa.pem 0000664 0000000 0000000 00000001623 13111303321 0017026 0 ustar 00root root 0000000 0000000 -----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALRiMLAh9iimur8V
A7qVvdqxevEuUkW4K+2KdMXmnQbG9Aa7k7eBjK1S+0LYmVjPKlJGNXHDGuy5Fw/d
7rjVJ0BLB+ubPK8iA/Tw3hLQgXMRRGRXXCn8ikfuQfjUS1uZSatdLB81mydBETlJ
hI6GH4twrbDJCR2Bwy/XWXgqgGRzAgMBAAECgYBYWVtleUzavkbrPjy0T5FMou8H
X9u2AC2ry8vD/l7cqedtwMPp9k7TubgNFo+NGvKsl2ynyprOZR1xjQ7WgrgVB+mm
uScOM/5HVceFuGRDhYTCObE+y1kxRloNYXnx3ei1zbeYLPCHdhxRYW7T0qcynNmw
rn05/KO2RLjgQNalsQJBANeA3Q4Nugqy4QBUCEC09SqylT2K9FrrItqL2QKc9v0Z
zO2uwllCbg0dwpVuYPYXYvikNHHg+aCWF+VXsb9rpPsCQQDWR9TT4ORdzoj+Nccn
qkMsDmzt0EfNaAOwHOmVJ2RVBspPcxt5iN4HI7HNeG6U5YsFBb+/GZbgfBT3kpNG
WPTpAkBI+gFhjfJvRw38n3g/+UeAkwMI2TJQS4n8+hid0uus3/zOjDySH3XHCUno
cn1xOJAyZODBo47E+67R4jV1/gzbAkEAklJaspRPXP877NssM5nAZMU0/O/NGCZ+
3jPgDUno6WbJn5cqm8MqWhW1xGkImgRk+fkDBquiq4gPiT898jusgQJAd5Zrr6Q8
AO/0isr/3aa6O6NLQxISLKcPDk2NOccAfS/xOtfOz4sJYM3+Bs4Io9+dZGSDCA54
Lw03eHTNQghS0A==
-----END PRIVATE KEY----- oauth-ruby-0.5.3/test/support/ 0000775 0000000 0000000 00000000000 13111303321 0016275 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/test/support/minitest_helpers.rb 0000664 0000000 0000000 00000002221 13111303321 0022175 0 ustar 00root root 0000000 0000000 module OAuth
module MinitestHelpers
def assert_matching_headers(expected, actual)
# transform into sorted arrays
auth_intro, auth_params = actual.split(' ', 2)
assert_equal auth_intro, 'OAuth'
expected = expected.split(/(,|\s)/).reject {|v| v == '' || v =~ /^[\,\s]+/}.sort
auth_params = auth_params.split(/(,|\s)/).reject {|v| v == '' || v =~ /^[\,\s]+/}.sort
assert_equal expected, auth_params
end
def stub_test_ie
stub_request(:any, "http://term.ie/oauth/example/request_token.php").to_return(:body => "oauth_token=requestkey&oauth_token_secret=requestsecret")
stub_request(:post, "http://term.ie/oauth/example/access_token.php").to_return(:body => "oauth_token=accesskey&oauth_token_secret=accesssecret")
stub_request(:get, %r{http://term\.ie/oauth/example/echo_api\.php\?.+}).to_return(lambda {|request| {:body => request.uri.query}})
stub_request(:post, "http://term.ie/oauth/example/echo_api.php").to_return(lambda {|request| {:body => request.body}})
end
end
end
# TODO: When dropping support to Ruby 2.0, stop using send
Minitest::Test.send(:include, OAuth::MinitestHelpers)
oauth-ruby-0.5.3/test/test_helper.rb 0000664 0000000 0000000 00000000667 13111303321 0017435 0 ustar 00root root 0000000 0000000 # ensure test env
ENV['RACK_ENV'] = 'test'
# simplecov, Travis will call codeclimate
require 'simplecov'
SimpleCov.start
# require third-party code
require 'byebug'
require 'stringio'
require 'minitest/autorun'
require 'mocha/mini_test'
require 'rack/test'
require 'webmock/minitest'
# require our lib
$LOAD_PATH << File.dirname(__FILE__) + '/../lib/'
require 'oauth'
# require our support code
require 'support/minitest_helpers'
oauth-ruby-0.5.3/test/units/ 0000775 0000000 0000000 00000000000 13111303321 0015723 5 ustar 00root root 0000000 0000000 oauth-ruby-0.5.3/test/units/test_access_token.rb 0000664 0000000 0000000 00000001350 13111303321 0021747 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
class TestAccessToken < Minitest::Test
def setup
@fake_response = {
:user_id => 5734758743895,
:oauth_token => "key",
:oauth_token_secret => "secret"
}
# setup a fake req. token. mocking Consumer would be more appropriate...
@access_token = OAuth::AccessToken.from_hash(
OAuth::Consumer.new("key", "secret", {}),
@fake_response
)
end
def test_provides_response_parameters
assert @access_token
assert_respond_to @access_token, :params
end
def test_access_token_makes_non_oauth_response_params_available
assert @access_token.params[:user_id]
assert_equal 5734758743895, @access_token.params[:user_id]
end
end
oauth-ruby-0.5.3/test/units/test_action_controller_request_proxy.rb 0000664 0000000 0000000 00000013046 13111303321 0026044 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
require 'oauth/request_proxy/action_controller_request'
class ActionControllerRequestProxyTest < Minitest::Test
def request_proxy(request_method = :get, uri_params = {}, body_params = {})
request = ActionDispatch::TestRequest.new
request.request_uri = '/'
case request_method
when :post
request.env['REQUEST_METHOD'] = 'POST'
when :put
request.env['REQUEST_METHOD'] = 'PUT'
when :patch
request.env['REQUEST_METHOD'] = 'PATCH'
end
request.env['REQUEST_URI'] = '/'
request.env['RAW_POST_DATA'] = body_params.to_query
request.env['QUERY_STRING'] = body_params.to_query
request.env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
yield request if block_given?
OAuth::RequestProxy::ActionControllerRequest.new(request, :parameters => uri_params)
end
def test_that_proxy_simple_get_request_works_with_query_params
request_proxy = request_proxy(:get, {'key'=>'value'})
expected_parameters = [["key", "value"]]
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'GET', request_proxy.method
end
def test_that_proxy_simple_post_request_works_with_query_params
request_proxy = request_proxy(:post, {'key'=>'value'})
expected_parameters = [["key", "value"]]
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'POST', request_proxy.method
end
def test_that_proxy_simple_put_request_works_with_query_params
request_proxy = request_proxy(:put, {'key'=>'value'})
expected_parameters = [["key", "value"]]
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'PUT', request_proxy.method
end
def test_that_proxy_simple_patch_request_works_with_query_params
request_proxy = request_proxy(:patch, {'key'=>'value'})
expected_parameters = [["key", "value"]]
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'PATCH', request_proxy.method
end
def test_that_proxy_simple_get_request_works_with_post_params
request_proxy = request_proxy(:get, {}, {'key'=>'value'})
expected_parameters = []
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'GET', request_proxy.method
end
def test_that_proxy_simple_post_request_works_with_post_params
request_proxy = request_proxy(:post, {}, {'key'=>'value'})
expected_parameters = [["key", "value"]]
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'POST', request_proxy.method
end
def test_that_proxy_simple_put_request_works_with_post_params
request_proxy = request_proxy(:put, {}, {'key'=>'value'})
expected_parameters = []
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'PUT', request_proxy.method
end
def test_that_proxy_simple_patch_request_works_with_post_params
request_proxy = request_proxy(:patch, {}, {'key'=>'value'})
expected_parameters = []
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'PATCH', request_proxy.method
end
def test_that_proxy_simple_get_request_works_with_mixed_params
request_proxy = request_proxy(:get, {'key'=>'value'}, {'key2'=>'value2'})
expected_parameters = [["key", "value"]]
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'GET', request_proxy.method
end
def test_that_proxy_simple_post_request_works_with_mixed_params
request_proxy = request_proxy(:post, {'key'=>'value'}, {'key2'=>'value2'})
expected_parameters = [["key", "value"],["key2", "value2"]]
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'POST', request_proxy.method
end
def test_that_proxy_simple_put_request_works_with_mixed_params
request_proxy = request_proxy(:put, {'key'=>'value'}, {'key2'=>'value2'})
expected_parameters = [["key", "value"]]
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'PUT', request_proxy.method
end
def test_that_proxy_simple_patch_request_works_with_mixed_params
request_proxy = request_proxy(:patch, {'key'=>'value'}, {'key2'=>'value2'})
expected_parameters = [["key", "value"]]
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'PATCH', request_proxy.method
end
def test_parameter_keys_should_preserve_brackets_from_hash
assert_equal(
[["message[body]", "This is a test"]],
request_proxy(:post, { :message => { :body => 'This is a test' }}).parameters_for_signature
)
end
def test_parameter_values_with_amps_should_not_break_parameter_parsing
assert_equal(
[['message[body]', 'http://foo.com/?a=b&c=d']],
request_proxy(:post, { :message => { :body => 'http://foo.com/?a=b&c=d'}}).parameters_for_signature
)
end
def test_parameter_keys_should_preserve_brackets_from_array
assert_equal(
[["foo[]", "123"], ["foo[]", "456"]],
request_proxy(:post, { :foo => [123, 456] }).parameters_for_signature.sort
)
end
# TODO disabled; ActionController::TestRequest does not appear to parse
# QUERY_STRING
def x_test_query_string_parameter_values_should_be_cgi_unescaped
request = request_proxy do |r|
r.env['QUERY_STRING'] = 'url=http%3A%2F%2Ffoo.com%2F%3Fa%3Db%26c%3Dd'
end
assert_equal(
[['url', 'http://foo.com/?a=b&c=d']],
request.parameters_for_signature.sort
)
end
end
oauth-ruby-0.5.3/test/units/test_cli.rb 0000664 0000000 0000000 00000025776 13111303321 0020077 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
require 'oauth/cli'
class TestCLI < Minitest::Test
def test_parse
assert_equal 'version', parse('-v')
assert_equal 'version', parse('--version')
assert_equal 'help', parse('-h')
assert_equal 'help', parse('--help')
assert_equal 'help', parse('-H')
assert_equal 'help', parse('--HELP')
assert_equal 'help', parse('')
assert_equal 'help', parse(nil)
assert_equal 'help', parse('NotACommand')
assert_equal 'help' , parse('h')
assert_equal 'version' , parse('v')
assert_equal 'query' , parse('q')
assert_equal 'authorize' , parse('a')
assert_equal 'sign' , parse('s')
assert_equal 'help' , parse('help')
assert_equal 'version' , parse('version')
assert_equal 'query' , parse('query')
assert_equal 'authorize' , parse('authorize')
assert_equal 'sign' , parse('sign')
assert_equal 'help' , parse('H')
assert_equal 'version' , parse('V')
assert_equal 'query' , parse('Q')
assert_equal 'authorize' , parse('A')
assert_equal 'sign' , parse('S')
assert_equal 'help' , parse('HELP')
assert_equal 'version' , parse('VERSION')
assert_equal 'query' , parse('QUERY')
assert_equal 'authorize' , parse('AUTHORIZE')
assert_equal 'sign' , parse('SIGN')
end
def test_help_empty
out = run_command
assert_match(/Usage: /, out)
end
def test_help
out = run_command(%w[help])
assert_match(/Usage: /, out)
end
def test_version
out = run_command(%w[version])
assert_equal "OAuth Gem #{OAuth::VERSION}\n", out
end
def test_query_empty
out = run_command(%w[query])
assert_equal help_output, out
end
def test_sign_empty
out = run_command(%w[sign])
assert_equal help_output, out
end
def test_authorize_empty
out = run_command(%w[authorize])
assert_equal help_output, out
end
def test_query
consumer = Minitest::Mock.new
access_token = MiniTest::Mock.new
response = MiniTest::Mock.new
consumer_new = lambda { |oauth_consumer_key, oauth_consumer_secret, options|
expected_options = {:scheme=>:header}
assert_equal 'oauth_consumer_key', oauth_consumer_key
assert_equal 'oauth_consumer_secret', oauth_consumer_secret
assert_equal expected_options, options
consumer
}
access_token_new = lambda { |consumer1, token, secret|
assert_equal consumer1.object_id, consumer.object_id
assert_equal 'TOKEN', token
assert_equal 'SECRET', secret
access_token
}
# mock expects:
# method return arguments
#-------------------------------------------------------------
response.expect( :code , '!code!')
response.expect( :message , '!message!')
response.expect( :body , '!body!')
access_token.expect(:request , response , [:post, "http://example.com/oauth/url?oauth_consumer_key=oauth_consumer_key&oauth_nonce=GENERATE_KEY&oauth_timestamp=GENERATE_TIMESTAMP&oauth_token=TOKEN&oauth_signature_method=HMAC-SHA1&oauth_version=1.0"])
OAuth::Helper.stub(:generate_key, 'GENERATE_KEY') do
OAuth::Helper.stub(:generate_timestamp, 'GENERATE_TIMESTAMP') do
OAuth::AccessToken.stub(:new, access_token_new) do
OAuth::Consumer.stub(:new, consumer_new) do
out = run_command %w[query
--consumer-key oauth_consumer_key
--consumer-secret oauth_consumer_secret
--token TOKEN
--secret SECRET
--uri http://example.com/oauth/url
]
assert_equal out, <<-EXPECTED
http://example.com/oauth/url?oauth_consumer_key=oauth_consumer_key&oauth_nonce=GENERATE_KEY&oauth_timestamp=GENERATE_TIMESTAMP&oauth_token=TOKEN&oauth_signature_method=HMAC-SHA1&oauth_version=1.0
!code! !message!
!body!
EXPECTED
end
end
end
end
end
def test_authorize
access_token = MiniTest::Mock.new
consumer = MiniTest::Mock.new
request_token = MiniTest::Mock.new
consumer_new = lambda { |oauth_consumer_key, oauth_consumer_secret, options|
expected_options = {:access_token_url=>nil, :authorize_url=>nil, :request_token_url=>nil, :scheme=>:header, :http_method=>:get}
assert_equal 'oauth_consumer_key', oauth_consumer_key
assert_equal 'oauth_consumer_secret', oauth_consumer_secret
assert_equal expected_options, options
consumer
}
# mock expects:
# method return arguments
#----------------------------------------------------------------------
access_token.expect( :params , {})
consumer.expect( :get_request_token , request_token , [{:oauth_callback=>nil} , {}])
request_token.expect( :callback_confirmed? , false)
request_token.expect( :authorize_url , "!url1!")
request_token.expect( :get_access_token , access_token, [{:oauth_verifier=>nil}])
OAuth::Helper.stub(:generate_key, 'GENERATE_KEY') do
OAuth::Helper.stub(:generate_timestamp, 'GENERATE_TIMESTAMP') do
OAuth::Consumer.stub(:new, consumer_new) do
out = run_command %w[authorize
--consumer-key oauth_consumer_key
--consumer-secret oauth_consumer_secret
--method GET
--uri http://example.com/oauth/url
]
assert_equal out, <<-EXPECTED
Please visit this url to authorize:
!url1!
Press return to continue...
Response:
EXPECTED
end
end
end
end
def test_sign
access_token = MiniTest::Mock.new
consumer = MiniTest::Mock.new
request_token = MiniTest::Mock.new
consumer_new = lambda { |oauth_consumer_key, oauth_consumer_secret, options|
expected_options = {:access_token_url=>nil, :authorize_url=>nil, :request_token_url=>nil, :scheme=>:header, :http_method=>:get}
assert_equal 'oauth_consumer_key', oauth_consumer_key
assert_equal 'oauth_consumer_secret', oauth_consumer_secret
assert_equal expected_options, options
consumer
}
# mock expects:
# method return arguments
#----------------------------------------------------------------------
access_token.expect( :params , {})
consumer.expect( :get_request_token , request_token , [{:oauth_callback=>nil} , {}])
request_token.expect( :callback_confirmed? , false)
request_token.expect( :authorize_url , "!url1!")
request_token.expect( :get_access_token , access_token, [{:oauth_verifier=>nil}])
out = []
OAuth::Helper.stub(:generate_key, 'GENERATE_KEY') do
OAuth::Helper.stub(:generate_timestamp, 'GENERATE_TIMESTAMP') do
OAuth::Consumer.stub(:new, consumer_new) do
out.push run_command %w[sign
--consumer-key oauth_consumer_key
--consumer-secret oauth_consumer_secret
--method GET
--token TOKEN
--secret SECRET
--uri http://example.com/oauth/url
-v
]
out.push run_command %w[sign
--consumer-key oauth_consumer_key
--consumer-secret oauth_consumer_secret
--method GET
--token TOKEN
--secret SECRET
--uri http://example.com/oauth/url
]
end
end
end
assert_equal out.pop, <<-EXPECTED
MujZyJYT5ix2s388yF8sExvPIgA=
EXPECTED
assert_equal out.pop, <<-EXPECTED
OAuth parameters:
oauth_consumer_key: oauth_consumer_key
oauth_nonce: GENERATE_KEY
oauth_timestamp: GENERATE_TIMESTAMP
oauth_token: TOKEN
oauth_signature_method: HMAC-SHA1
oauth_version: 1.0
Method: GET
URI: http://example.com/oauth/url
Normalized params: oauth_consumer_key=oauth_consumer_key&oauth_nonce=GENERATE_KEY&oauth_signature_method=HMAC-SHA1&oauth_timestamp=GENERATE_TIMESTAMP&oauth_token=TOKEN&oauth_version=1.0
Signature base string: GET&http%3A%2F%2Fexample.com%2Foauth%2Furl&oauth_consumer_key%3Doauth_consumer_key%26oauth_nonce%3DGENERATE_KEY%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3DGENERATE_TIMESTAMP%26oauth_token%3DTOKEN%26oauth_version%3D1.0
OAuth Request URI: http://example.com/oauth/url?oauth_consumer_key=oauth_consumer_key&oauth_nonce=GENERATE_KEY&oauth_signature=MujZyJYT5ix2s388yF8sExvPIgA%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=GENERATE_TIMESTAMP&oauth_token=TOKEN&oauth_version=1.0
Request URI: http://example.com/oauth/url?
Authorization header: OAuth oauth_consumer_key=\"oauth_consumer_key\", oauth_nonce=\"GENERATE_KEY\", oauth_timestamp=\"GENERATE_TIMESTAMP\", oauth_token=\"TOKEN\", oauth_signature_method=\"HMAC-SHA1\", oauth_version=\"1.0\", oauth_signature=\"MujZyJYT5ix2s388yF8sExvPIgA%3D\"
Signature: MujZyJYT5ix2s388yF8sExvPIgA=
Escaped signature: MujZyJYT5ix2s388yF8sExvPIgA%3D
EXPECTED
end
private
def run_command(arguments=[])
s = StringIO.new
command = arguments.shift
OAuth::CLI.new(s, StringIO.new, StringIO.new, command, arguments).run
s.rewind
s.read
end
def parse(command)
cli = OAuth::CLI.new(StringIO.new, StringIO.new, StringIO.new, command, [])
cli.send(:parse_command, command)
end
def help_output
<<-EXPECTED
Usage: oauth [ARGS]
-B, --body Use the request body for OAuth parameters.
--consumer-key KEY Specifies the consumer key to use.
--consumer-secret SECRET Specifies the consumer secret to use.
-H, --header Use the 'Authorization' header for OAuth parameters (default).
-Q, --query-string Use the query string for OAuth parameters.
-O, --options FILE Read options from a file
options for signing and querying
--method METHOD Specifies the method (e.g. GET) to use when signing.
--nonce NONCE Specifies the none to use.
--parameters PARAMS Specifies the parameters to use when signing.
--signature-method METHOD Specifies the signature method to use; defaults to HMAC-SHA1.
--token TOKEN Specifies the token to use.
--secret SECRET Specifies the token secret to use.
--timestamp TIMESTAMP Specifies the timestamp to use.
--realm REALM Specifies the realm to use.
--uri URI Specifies the URI to use when signing.
--version [VERSION] Specifies the OAuth version to use.
--no-version Omit oauth_version.
--xmpp Generate XMPP stanzas.
-v, --verbose Be verbose.
options for authorization
--access-token-url URL Specifies the access token URL.
--authorize-url URL Specifies the authorization URL.
--callback-url URL Specifies a callback URL.
--request-token-url URL Specifies the request token URL.
--scope SCOPE Specifies the scope (Google-specific).
EXPECTED
end
end
oauth-ruby-0.5.3/test/units/test_consumer.rb 0000664 0000000 0000000 00000022514 13111303321 0021146 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
# This performs testing against Andy Smith's test server http://term.ie/oauth/example/
# Thanks Andy.
# This also means you have to be online to be able to run these.
class ConsumerTest < Minitest::Test
def setup
@consumer=OAuth::Consumer.new(
'consumer_key_86cad9', '5888bf0345e5d237',
{
:site=>"http://blabla.bla",
:proxy=>"http://user:password@proxy.bla:8080",
:request_token_path=>"/oauth/example/request_token.php",
:access_token_path=>"/oauth/example/access_token.php",
:authorize_path=>"/oauth/example/authorize.php",
:scheme=>:header,
:http_method=>:get
})
@token = OAuth::ConsumerToken.new(@consumer,'token_411a7f', '3196ffd991c8ebdb')
@request_uri = URI.parse('http://example.com/test?key=value')
@request_parameters = { 'key' => 'value' }
@nonce = 225579211881198842005988698334675835446
@timestamp = "1199645624"
@consumer.http=Net::HTTP.new(@request_uri.host, @request_uri.port)
end
def test_initializer
assert_equal "consumer_key_86cad9",@consumer.key
assert_equal "5888bf0345e5d237",@consumer.secret
assert_equal "http://blabla.bla",@consumer.site
assert_equal "http://user:password@proxy.bla:8080",@consumer.proxy
assert_equal "/oauth/example/request_token.php",@consumer.request_token_path
assert_equal "/oauth/example/access_token.php",@consumer.access_token_path
assert_equal "http://blabla.bla/oauth/example/request_token.php",@consumer.request_token_url
assert_equal "http://blabla.bla/oauth/example/access_token.php",@consumer.access_token_url
assert_equal "http://blabla.bla/oauth/example/authorize.php",@consumer.authorize_url
assert_equal :header,@consumer.scheme
assert_equal :get,@consumer.http_method
assert_nil @consumer.debug_output
end
def test_defaults
@consumer=OAuth::Consumer.new(
"key",
"secret",
{
:site=>"http://twitter.com"
})
assert_equal "key",@consumer.key
assert_equal "secret",@consumer.secret
assert_equal "http://twitter.com",@consumer.site
assert_nil @consumer.proxy
assert_equal "/oauth/request_token",@consumer.request_token_path
assert_equal "/oauth/access_token",@consumer.access_token_path
assert_equal "http://twitter.com/oauth/request_token",@consumer.request_token_url
assert_equal "http://twitter.com/oauth/access_token",@consumer.access_token_url
assert_equal "http://twitter.com/oauth/authorize",@consumer.authorize_url
assert_equal :header,@consumer.scheme
assert_equal :post,@consumer.http_method
assert_nil @consumer.debug_output
end
def test_debug_output_true
@consumer=OAuth::Consumer.new(
"key",
"secret",
{
:debug_output=>true
})
assert_equal $stdout,@consumer.debug_output
end
def test_debug_output
stringio = StringIO.new
@consumer=OAuth::Consumer.new(
"key",
"secret",
{
:debug_output=>stringio
})
assert_equal stringio,@consumer.debug_output
end
def test_site_without_path
@consumer=OAuth::Consumer.new(
"key",
"secret",
{
:site=>"http://twitter.com"
})
request = stub(:oauth! => nil)
http = stub(:request => stub(:to_hash => {}), :address => "identi.ca")
Net::HTTP::Get.expects(:new).with('/people', {}).returns(request)
@consumer.expects(:create_http).returns(http)
@consumer.request(:get, '/people', nil, {})
end
def test_site_with_path
@consumer=OAuth::Consumer.new(
"key",
"secret",
{
:site=>"http://identi.ca/api"
})
request = stub(:oauth! => nil)
http = stub(:request => stub(:to_hash => {}), :address => "identi.ca")
Net::HTTP::Get.expects(:new).with('/api/people', {}).returns(request)
@consumer.expects(:create_http).returns(http)
@consumer.request(:get, '/people', nil, {})
end
def test_post_of_nested_params_maintains_nesting
@consumer=OAuth::Consumer.new(
"key",
"secret",
{
:site=>"http://twitter.com"
})
request = @consumer.create_signed_request(
:post,
'/people',
nil,
{},
{
:key => {
:subkey => 'value'
}
})
assert_equal 'key%5Bsubkey%5D=value', request.body
assert_equal request.content_type, 'application/x-www-form-urlencoded'
end
def test_override_paths
@consumer=OAuth::Consumer.new(
"key",
"secret",
{
:site=>"http://twitter.com",
:request_token_url=>"http://oauth.twitter.com/request_token",
:access_token_url=>"http://oauth.twitter.com/access_token",
:authorize_url=>"http://site.twitter.com/authorize"
})
assert_equal "key",@consumer.key
assert_equal "secret",@consumer.secret
assert_equal "http://twitter.com",@consumer.site
assert_equal "/oauth/request_token",@consumer.request_token_path
assert_equal "/oauth/access_token",@consumer.access_token_path
assert_equal "http://oauth.twitter.com/request_token",@consumer.request_token_url
assert_equal "http://oauth.twitter.com/access_token",@consumer.access_token_url
assert_equal "http://site.twitter.com/authorize",@consumer.authorize_url
assert_equal :header,@consumer.scheme
assert_equal :post,@consumer.http_method
end
def test_getting_tokens_doesnt_add_paths_if_full_url_is_specified
@consumer = OAuth::Consumer.new(
"key",
"secret",
{
:site => "https://api.mysite.co.nz/v1",
:request_token_url => "https://authentication.mysite.co.nz/Oauth/RequestToken"
})
stub_request(:post, "https://authentication.mysite.co.nz/Oauth/RequestToken").to_return(:body => "success", :status => 200)
@consumer.get_request_token
end
def test_token_request_identifies_itself_as_a_token_request
request_options = {}
@consumer.stubs(:request).returns(create_stub_http_response)
@consumer.token_request(:post, '/', 'token', request_options) {}
assert_equal true, request_options[:token_request]
end
def test_that_token_response_should_be_uri_parameter_format_as_default
@consumer.expects(:request).returns(create_stub_http_response("oauth_token=token&oauth_token_secret=secret"))
hash = @consumer.token_request(:get, "")
assert_equal "token", hash[:oauth_token]
assert_equal "secret", hash[:oauth_token_secret]
end
def test_can_provided_a_block_to_interpret_token_response
@consumer.expects(:request).returns(create_stub_http_response)
hash = @consumer.token_request(:get, '') {{ :oauth_token => 'token', :oauth_token_secret => 'secret' }}
assert_equal 'token', hash[:oauth_token]
assert_equal 'secret', hash[:oauth_token_secret]
end
def test_token_request_follows_redirect
redirect_url = @request_uri.clone
redirect_url.path = "/oauth/example/request_token_redirect.php"
stub_request(:get, /.*#{@request_uri.path}/).to_return(:status => 301, :headers => {'Location' => redirect_url.to_s})
stub_request(:get, /.*#{redirect_url.path}/).to_return(:body => "oauth_token=token&oauth_token_secret=secret")
hash = @consumer.token_request(:get, @request_uri.path) {{ :oauth_token => 'token', :oauth_token_secret => 'secret' }}
assert_equal 'token', hash[:oauth_token]
assert_equal 'secret', hash[:oauth_token_secret]
end
def test_that_can_provide_a_block_to_interpret_a_request_token_response
@consumer.expects(:request).returns(create_stub_http_response)
token = @consumer.get_request_token {{ :oauth_token => 'token', :oauth_token_secret => 'secret' }}
assert_equal 'token', token.token
assert_equal 'secret', token.secret
end
def test_that_block_is_not_mandatory_for_getting_an_access_token
stub_token = mock
@consumer.expects(:request).returns(create_stub_http_response("oauth_token=token&oauth_token_secret=secret"))
token = @consumer.get_access_token(stub_token)
assert_equal 'token', token.token
assert_equal 'secret', token.secret
end
def test_that_can_provide_a_block_to_interpret_an_access_token_response
stub_token = mock
@consumer.expects(:request).returns(create_stub_http_response)
token = @consumer.get_access_token(stub_token) {{ :oauth_token => 'token', :oauth_token_secret => 'secret' }}
assert_equal 'token', token.token
assert_equal 'secret', token.secret
end
def test_that_not_setting_ignore_callback_will_include_oauth_callback_in_request_options
request_options = {}
@consumer.stubs(:request).returns(create_stub_http_response)
@consumer.get_request_token(request_options) {{ :oauth_token => 'token', :oauth_token_secret => 'secret' }}
assert_equal 'oob', request_options[:oauth_callback]
end
def test_that_setting_ignore_callback_will_exclude_oauth_callback_in_request_options
request_options = { :exclude_callback=> true }
@consumer.stubs(:request).returns(create_stub_http_response)
@consumer.get_request_token(request_options) {{ :oauth_token => 'token', :oauth_token_secret => 'secret' }}
assert_nil request_options[:oauth_callback]
end
private
def create_stub_http_response expected_body=nil
stub_http_response = stub
stub_http_response.stubs(:code).returns(200)
stub_http_response.stubs(:body).tap {|expectation| expectation.returns(expected_body) unless expected_body.nil? }
return stub_http_response
end
end
oauth-ruby-0.5.3/test/units/test_curb_request_proxy.rb 0000664 0000000 0000000 00000006034 13111303321 0023256 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
begin
require 'oauth/request_proxy/curb_request'
require 'curb'
class CurbRequestProxyTest < Minitest::Test
def test_that_proxy_simple_get_request_works
request = Curl::Easy.new('/test?key=value')
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value'})
expected_parameters = {'key' => ['value']}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
end
def test_that_proxy_simple_post_request_works_with_arguments
request = Curl::Easy.new('/test')
params = {'key' => 'value'}
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params})
expected_parameters = {'key' => 'value'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
end
def test_that_proxy_simple_post_request_works_with_form_data
request = Curl::Easy.new('/test')
request.post_body = 'key=value'
request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'})
expected_parameters = {'key' => 'value'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
end
def test_that_proxy_simple_put_request_works_with_arguments
request = Curl::Easy.new('/test')
params = {'key' => 'value'}
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params})
expected_parameters = {'key' => 'value'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
end
def test_that_proxy_simple_put_request_works_with_form_data
request = Curl::Easy.new('/test')
request.post_body = 'key=value'
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'})
expected_parameters = {}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
end
def test_that_proxy_post_request_works_with_mixed_parameter_sources
request = Curl::Easy.new('/test?key=value')
request.post_body = 'key2=value2'
request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value', :parameters => {'key3' => 'value3'}})
expected_parameters = {'key' => ['value'], 'key2' => 'value2', 'key3' => 'value3'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
end
end
rescue LoadError => e
warn "! problems loading curb, skipping these tests: #{e}"
end
oauth-ruby-0.5.3/test/units/test_em_http_client.rb 0000664 0000000 0000000 00000007176 13111303321 0022320 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
begin
require 'oauth/client/em_http'
class EmHttpClientTest < Minitest::Test
def setup
@consumer = OAuth::Consumer.new('consumer_key_86cad9', '5888bf0345e5d237')
@token = OAuth::Token.new('token_411a7f', '3196ffd991c8ebdb')
@request_uri = URI.parse('http://example.com/test?key=value')
@request_parameters = { 'key' => 'value' }
@nonce = 225579211881198842005988698334675835446
@timestamp = "1199645624"
# This is really unneeded I guess.
@http = Net::HTTP.new(@request_uri.host, @request_uri.port)
end
def test_that_using_auth_headers_on_get_requests_works
request = create_client
request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp})
assert_equal 'GET', request.method
assert_equal '/test', request.normalize_uri.path
assert_equal "key=value", request.normalize_uri.query
assert_equal_authz_headers "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\"", authz_header(request)
end
def test_that_using_auth_headers_on_get_requests_works_with_plaintext
require 'oauth/signature/plaintext'
c = OAuth::Consumer.new('consumer_key_86cad9', '5888bf0345e5d237',{
:signature_method => 'PLAINTEXT'
})
request = create_client
request.oauth!(@http, c, @token, {:nonce => @nonce, :timestamp => @timestamp, :signature_method => 'PLAINTEXT'})
assert_equal 'GET', request.method
assert_equal '/test', request.normalize_uri.path
assert_equal "key=value", request.normalize_uri.query
assert_equal_authz_headers "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"PLAINTEXT\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"5888bf0345e5d237%263196ffd991c8ebdb\", oauth_version=\"1.0\"", authz_header(request)
end
def test_that_using_auth_headers_on_post_requests_works
request = create_client(:uri => "http://example.com/test", :method => "POST", :body => @request_parameters, :head => {"Content-Type" => "application/x-www-form-urlencoded"})
request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp})
assert_equal 'POST', request.method
assert_equal '/test', request.uri.path
assert_equal 'key=value', request.normalize_body
assert_equal_authz_headers "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\"", authz_header(request)
end
protected
def create_client(options = {})
method = options.delete(:method) || "GET"
uri = options.delete(:uri) || @request_uri.to_s
client = EventMachine::HttpClient.new("")
client.uri = URI.parse(uri)
client.method = method.to_s.upcase
client.options = options
client
end
def authz_header(request)
headers = request.options[:head] || {}
headers['Authorization'].to_s
end
def assert_equal_authz_headers(expected, actual)
assert !actual.nil?
assert_equal expected[0,6], actual[0, 6]
assert_equal expected[6..1].split(', ').sort, actual[6..1].split(', ').sort
end
end
rescue LoadError => e
warn "! problem loading em-http, skipping these tests: #{e}"
end
oauth-ruby-0.5.3/test/units/test_em_http_request_proxy.rb 0000664 0000000 0000000 00000013502 13111303321 0023761 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
begin
require 'em-http'
require 'oauth/request_proxy/em_http_request'
class EmHttpRequestProxyTest < Minitest::Test
def test_request_proxy_works_with_simple_request
proxy = create_request_proxy
assert_equal({}, proxy.parameters)
end
def test_request_proxy_works_with_query_string_params
assert_equal({"name" => ["Fred"]}, create_request_proxy(:query => "name=Fred").parameters)
assert_equal({"name" => ["Fred"]}, create_request_proxy(:query => {:name => "Fred"}).parameters)
proxy = create_request_proxy(:query => {:name => "Fred"}, :uri => "http://example.com/?awesome=true")
assert_equal({"name" => ["Fred"], "awesome" => ["true"]}, proxy.parameters)
end
def test_request_proxy_works_with_post_body_params_with_correct_content_type
proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "POST"
assert_equal({}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "POST", :body => "a=1"
assert_equal({"a" => ["1"]}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "POST", :body => {"a" => 1}
assert_equal({"a" => ["1"]}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "PUT"
assert_equal({}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "PUT", :body => "a=1"
assert_equal({"a" => ["1"]}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "PUT", :body => {"a" => 1}
assert_equal({"a" => ["1"]}, proxy.parameters)
end
def test_request_proxy_ignore_post_body_with_invalid_content_type
proxy = create_request_proxy :head => {'Content-Type' => 'text/plain'}, :method => "POST"
assert_equal({}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'text/plain'}, :method => "POST", :body => "a=1"
assert_equal({}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'text/plain'}, :method => "POST", :body => {"a" => 1}
assert_equal({}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'text/plain'}, :method => "PUT"
assert_equal({}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'text/plain'}, :method => "PUT", :body => "a=1"
assert_equal({}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'text/plain'}, :method => "PUT", :body => {"a" => 1}
assert_equal({}, proxy.parameters)
end
def test_request_proxy_ignores_post_body_with_invalid_method
proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "DELETE"
assert_equal({}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "DELETE", :body => "a=1"
assert_equal({}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "DELETE", :body => {"a" => 1}
assert_equal({}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "GET"
assert_equal({}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "GET", :body => "a=1"
assert_equal({}, proxy.parameters)
proxy = create_request_proxy :head => {'Content-Type' => 'application/x-www-form-urlencoded'}, :method => "GET", :body => {"a" => 1}
assert_equal({}, proxy.parameters)
end
def test_request_proxy_works_with_argument_params
assert_equal({"a" => ["1"]}, create_request_proxy(:proxy_options => {:parameters => {"a" => "1"}}).parameters)
end
def test_request_proxy_works_with_mixed_params
proxy = create_request_proxy(:proxy_options => {:parameters => {"a" => "1"}},:query => {"c" => "1"}, :uri => "http://example.com/test?b=1")
assert_equal({"a" => ["1"], "b" => ["1"], "c" => ["1"]}, proxy.parameters)
proxy = create_request_proxy(:proxy_options => {:parameters => {"a" => "1"}}, :body => {"b" => "1"}, :query => {"c" => "1"},
:uri => "http://example.com/test?d=1", :method => "POST", :head => {"Content-Type" => "application/x-www-form-urlencoded"})
assert_equal({"a" => ["1"], "b" => ["1"], "c" => ["1"], "d" => ["1"]}, proxy.parameters)
end
def test_request_has_the_correct_uri
assert_equal "http://example.com/", create_request_proxy.uri
assert_equal "http://example.com/?a=1", create_request_proxy(:query => "a=1").uri
assert_equal "http://example.com/?a=1", create_request_proxy(:query => {"a" => "1"}).uri
end
def test_request_proxy_has_correct_method
assert_equal "GET", create_request_proxy(:method => "GET").method
assert_equal "PUT", create_request_proxy(:method => "PUT").method
assert_equal "POST", create_request_proxy(:method => "POST").method
assert_equal "DELETE", create_request_proxy(:method => "DELETE").method
end
protected
def create_client(options = {})
method = options.delete(:method) || "GET"
uri = options.delete(:uri) || "http://example.com/"
client = EventMachine::HttpClient.new("")
client.uri = URI.parse(uri)
client.method = method.to_s.upcase
client.options = options
client
end
def create_request_proxy(opts = {})
arguments = opts.delete(:proxy_options) || {}
OAuth::RequestProxy.proxy(create_client(opts), arguments)
end
end
rescue LoadError => e
warn "! problem loading em-http, skipping these tests: #{e}"
end
oauth-ruby-0.5.3/test/units/test_hmac_sha1.rb 0000664 0000000 0000000 00000001750 13111303321 0021136 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
class TestSignatureHmacSha1 < Minitest::Test
def test_that_hmac_sha1_implements_hmac_sha1
assert OAuth::Signature.available_methods.include?('hmac-sha1')
end
def test_that_get_request_from_oauth_test_cases_produces_matching_signature
request = Net::HTTP::Get.new('/photos?file=vacation.jpg&size=original&oauth_version=1.0&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_token=nnch734d00sl2jdk&oauth_timestamp=1191242096&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1')
consumer = OAuth::Consumer.new('dpf43f3p2l4k3l03', 'kd94hf93k423kf44')
token = OAuth::Token.new('nnch734d00sl2jdk', 'pfkkdhi9sl3r4s00')
signature = OAuth::Signature.sign(request, { :consumer => consumer,
:token => token,
:uri => 'http://photos.example.net/photos' } )
assert_equal 'tR3+Ty81lMeYAr/Fid0kMTYa/WM=', signature
end
end
oauth-ruby-0.5.3/test/units/test_net_http_client.rb 0000664 0000000 0000000 00000044116 13111303321 0022500 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
class NetHTTPClientTest < Minitest::Test
def setup
@consumer = OAuth::Consumer.new('consumer_key_86cad9', '5888bf0345e5d237')
@token = OAuth::Token.new('token_411a7f', '3196ffd991c8ebdb')
@request_uri = URI.parse('http://example.com/test?key=value')
@request_parameters = { 'key' => 'value' }
@nonce = 225579211881198842005988698334675835446
@timestamp = "1199645624"
@http = Net::HTTP.new(@request_uri.host, @request_uri.port)
end
def test_that_using_auth_headers_on_get_requests_works
request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s)
request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp})
assert_equal 'GET', request.method
assert_equal '/test?key=value', request.path
correct_sorted_params = "oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\""
auth_intro = request['authorization'].split(' ', 2).first
assert_equal auth_intro, 'OAuth'
assert_matching_headers correct_sorted_params, request['authorization']
end
def test_that_using_auth_headers_on_get_requests_works_with_plaintext
require 'oauth/signature/plaintext'
c = OAuth::Consumer.new('consumer_key_86cad9', '5888bf0345e5d237',{
:signature_method => 'PLAINTEXT'
})
request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s)
request.oauth!(@http, c, @token, {:nonce => @nonce, :timestamp => @timestamp, :signature_method => 'PLAINTEXT'})
assert_equal 'GET', request.method
assert_equal '/test?key=value', request.path
assert_matching_headers "oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"PLAINTEXT\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"5888bf0345e5d237%263196ffd991c8ebdb\", oauth_version=\"1.0\"", request['authorization']
end
def test_that_using_auth_headers_on_post_requests_works
request = Net::HTTP::Post.new(@request_uri.path)
request.set_form_data( @request_parameters )
request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp})
assert_equal 'POST', request.method
assert_equal '/test', request.path
assert_equal 'key=value', request.body
correct_sorted_params = "oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\""
assert_matching_headers correct_sorted_params, request['authorization']
end
def test_that_using_auth_headers_on_post_requests_with_data_works
request = Net::HTTP::Post.new(@request_uri.path)
request.body = "data"
request.content_type = 'text/ascii'
request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp})
assert_equal 'POST', request.method
assert_equal '/test', request.path
assert_equal 'data', request.body
assert_equal 'text/ascii', request.content_type
assert_matching_headers "oauth_nonce=\"225579211881198842005988698334675835446\", oauth_body_hash=\"oXyaqmHoChv3HQ2FCvTluqmAC70%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"0DA6pGTapdHSqC15RZelY5rNLDw%3D\", oauth_version=\"1.0\"", request['authorization']
end
def test_that_body_hash_is_obmitted_when_token_request
request = Net::HTTP::Post.new(@request_uri.path)
request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp, :token_request => true})
assert_no_match(/oauth_body_hash/, request['authorization'])
end
def test_that_body_hash_is_obmitted_when_no_algorithm_is_defined
request = Net::HTTP::Post.new(@request_uri.path)
request.body = "data"
request.content_type = 'text/ascii'
request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp, :signature_method => 'plaintext'})
assert_equal 'POST', request.method
assert_equal '/test', request.path
assert_equal 'data', request.body
assert_equal 'text/ascii', request.content_type
assert_matching_headers "oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"plaintext\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"5888bf0345e5d237%263196ffd991c8ebdb\", oauth_version=\"1.0\"", request['authorization']
end
def test_that_version_is_added_to_existing_user_agent
request = Net::HTTP::Post.new(@request_uri.path)
request['User-Agent'] = "MyApp"
request.set_form_data( @request_parameters )
request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp})
assert_equal "MyApp (OAuth gem v#{OAuth::VERSION})", request['User-Agent']
end
def test_that_version_is_set_when_no_user_agent
request = Net::HTTP::Post.new(@request_uri.path)
request.set_form_data( @request_parameters )
request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp})
assert_equal "OAuth gem v#{OAuth::VERSION}", request['User-Agent']
end
def test_that_using_get_params_works
request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s)
request.oauth!(@http, @consumer, @token, {:scheme => 'query_string', :nonce => @nonce, :timestamp => @timestamp})
assert_equal 'GET', request.method
uri = URI.parse(request.path)
assert_equal '/test', uri.path
assert_nil uri.fragment
assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=1oO2izFav1GP4kEH2EskwXkCRFg%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join("&")
assert_nil request['authorization']
end
def test_that_using_get_params_works_with_plaintext
request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s)
request.oauth!(@http, @consumer, @token, {:scheme => 'query_string', :nonce => @nonce, :timestamp => @timestamp, :signature_method => 'PLAINTEXT'})
assert_equal 'GET', request.method
uri = URI.parse(request.path)
assert_equal '/test', uri.path
assert_nil uri.fragment
assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=5888bf0345e5d237%263196ffd991c8ebdb&oauth_signature_method=PLAINTEXT&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join("&")
assert_nil request['authorization']
end
def test_that_using_post_params_works
request = Net::HTTP::Post.new(@request_uri.path)
request.set_form_data( @request_parameters )
request.oauth!(@http, @consumer, @token, {:scheme => 'body', :nonce => @nonce, :timestamp => @timestamp})
assert_equal 'POST', request.method
assert_equal '/test', request.path
assert_match(/key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=26g7wHTtNO6ZWJaLltcueppHYiI%3[Dd]&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0/, request.body.split("&").sort.join("&"))
assert_nil request['authorization']
end
def test_that_using_post_params_works_with_plaintext
request = Net::HTTP::Post.new(@request_uri.path)
request.set_form_data( @request_parameters )
request.oauth!(@http, @consumer, @token, {:scheme => 'body', :nonce => @nonce, :timestamp => @timestamp, :signature_method => 'PLAINTEXT'})
assert_equal 'POST', request.method
assert_equal '/test', request.path
assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=5888bf0345e5d237%263196ffd991c8ebdb&oauth_signature_method=PLAINTEXT&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", request.body.split("&").sort.join("&")
assert_nil request['authorization']
end
def test_that_using_post_body_works
request = Net::HTTP::Post.new(@request_uri.path)
request['content-type'] = 'application/x-www-form-urlencoded'
request.body = 'this is a test of the emergency broad cast system. This is only a test.'
request.oauth!(@http, @consumer, @token, {:nonce => @nonce, :timestamp => @timestamp})
assert_equal 'POST', request.method
assert_equal '/test', request.path
assert_match(/OAuth oauth_consumer_key="consumer_key_86cad9", oauth_nonce="225579211881198842005988698334675835446", oauth_signature="%2[fF]DMMBOJzQ6JmEaXlAXDLGtD1z2I%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1199645624", oauth_token="token_411a7f", oauth_version="1.0"/, request['authorization'].split("&").sort.join("&"))
# assert_nil request['authorization']
end
def test_that_using_post_with_uri_params_works
request = Net::HTTP::Post.new(@request_uri.path + "?" + request_parameters_to_s)
request.set_form_data( {} ) # just to make sure we have a correct mime type and thus no body hash
request.oauth!(@http, @consumer, @token, {:scheme => 'query_string', :nonce => @nonce, :timestamp => @timestamp})
assert_equal 'POST', request.method
uri = URI.parse(request.path)
assert_equal '/test', uri.path
assert_nil uri.fragment
assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=26g7wHTtNO6ZWJaLltcueppHYiI%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join('&')
assert_equal "", request.body
assert_nil request['authorization']
end
def test_that_using_post_with_uri_and_form_params_works
request = Net::HTTP::Post.new(@request_uri.path + "?" + request_parameters_to_s)
request.set_form_data( { 'key2' => 'value2' } )
request.oauth!(@http, @consumer, @token, {:scheme => :query_string, :nonce => @nonce, :timestamp => @timestamp})
assert_equal 'POST', request.method
uri = URI.parse(request.path)
assert_equal '/test', uri.path
assert_nil uri.fragment
assert_equal "key=value&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=4kSU8Zd1blWo3W6qJH7eaRTMkg0%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join('&')
assert_equal "key2=value2", request.body
assert_nil request['authorization']
end
def test_that_using_post_with_uri_and_data_works
request = Net::HTTP::Post.new(@request_uri.path + "?" + request_parameters_to_s)
request.body = "data"
request.content_type = 'text/ascii'
request.oauth!(@http, @consumer, @token, {:scheme => :query_string, :nonce => @nonce, :timestamp => @timestamp})
assert_equal 'POST', request.method
uri = URI.parse(request.path)
assert_equal '/test', uri.path
assert_nil uri.fragment
assert_equal "data", request.body
assert_equal 'text/ascii', request.content_type
assert_equal "key=value&oauth_body_hash=oXyaqmHoChv3HQ2FCvTluqmAC70%3D&oauth_consumer_key=consumer_key_86cad9&oauth_nonce=225579211881198842005988698334675835446&oauth_signature=MHRKU42iVHU4Ke9kBUDa9Zw6IAM%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1199645624&oauth_token=token_411a7f&oauth_version=1.0", uri.query.split("&").sort.join('&')
assert_nil request['authorization']
end
def test_example_from_specs
consumer=OAuth::Consumer.new("dpf43f3p2l4k3l03","kd94hf93k423kf44")
token = OAuth::Token.new('nnch734d00sl2jdk', 'pfkkdhi9sl3r4s00')
request_uri = URI.parse('http://photos.example.net/photos?file=vacation.jpg&size=original')
nonce = 'kllo9940pd9333jh'
timestamp = "1191242096"
http = Net::HTTP.new(request_uri.host, request_uri.port)
request = Net::HTTP::Get.new(request_uri.path + "?" + request_uri.query)
signature_base_string=request.signature_base_string(http, consumer, token, {:nonce => nonce, :timestamp => timestamp})
assert_equal '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',signature_base_string
# request = Net::HTTP::Get.new(request_uri.path + "?" + request_uri.query)
request.oauth!(http, consumer, token, {:nonce => nonce, :timestamp => timestamp, :realm=>"http://photos.example.net/"})
assert_equal 'GET', request.method
correct_sorted_params = 'oauth_nonce="kllo9940pd9333jh", oauth_signature_method="HMAC-SHA1", oauth_token="nnch734d00sl2jdk", oauth_timestamp="1191242096", oauth_consumer_key="dpf43f3p2l4k3l03", oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D", oauth_version="1.0"'.split(', ').sort
correct_sorted_params.unshift 'OAuth realm="http://photos.example.net/"'
assert_equal correct_sorted_params, request['authorization'].split(', ').sort
end
def test_step_by_step_token_request
token_response = "oauth_token=requestkey&oauth_token_secret=requestsecret"
stub_request(:get, %r{http://term\.ie/oauth/example/request_token\.php(\?.*)?}).to_return(:body => token_response)
consumer=OAuth::Consumer.new(
"key",
"secret")
request_uri = URI.parse('http://term.ie/oauth/example/request_token.php')
nonce = rand(2**128).to_s
timestamp = Time.now.to_i.to_s
http = Net::HTTP.new(request_uri.host, request_uri.port)
request = Net::HTTP::Get.new(request_uri.path)
signature_base_string=request.signature_base_string(http, consumer, nil, {:scheme=>:query_string,:nonce => nonce, :timestamp => timestamp})
assert_equal "GET&http%3A%2F%2Fterm.ie%2Foauth%2Fexample%2Frequest_token.php&oauth_consumer_key%3Dkey%26oauth_nonce%3D#{nonce}%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D#{timestamp}%26oauth_version%3D1.0",signature_base_string
# request = Net::HTTP::Get.new(request_uri.path)
request.oauth!(http, consumer, nil, {:scheme=>:query_string,:nonce => nonce, :timestamp => timestamp})
assert_equal 'GET', request.method
assert_nil request.body
assert_nil request['authorization']
# assert_equal 'OAuth oauth_nonce="kllo9940pd9333jh", oauth_signature_method="HMAC-SHA1", oauth_token="", oauth_timestamp="'+timestamp+'", oauth_consumer_key="key", oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D", oauth_version="1.0"', request['authorization']
response=http.request(request)
assert_equal "200",response.code
# assert_equal request['authorization'],response.body
assert_equal token_response, response.body
end
def test_that_put_bodies_signed
request = Net::HTTP::Put.new(@request_uri.path)
request.body = "baz"
request["Content-Type"] = "application/xml"
signature_base_string=request.signature_base_string(@http, @consumer, nil, { :nonce => @nonce, :timestamp => @timestamp })
assert_equal "PUT&http%3A%2F%2Fexample.com%2Ftest&oauth_body_hash%3DDvAa1AWdFoH9K%252B%252F2AHm3f6wH27k%253D%26oauth_consumer_key%3Dconsumer_key_86cad9%26oauth_nonce%3D225579211881198842005988698334675835446%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1199645624%26oauth_version%3D1.0", signature_base_string
end
def test_that_put_bodies_not_signed_even_if_form_urlencoded
request = Net::HTTP::Put.new(@request_uri.path)
request.set_form_data( { 'key2' => 'value2' } )
signature_base_string=request.signature_base_string(@http, @consumer, nil, { :nonce => @nonce, :timestamp => @timestamp })
assert_equal "PUT&http%3A%2F%2Fexample.com%2Ftest&key2%3Dvalue2%26oauth_consumer_key%3Dconsumer_key_86cad9%26oauth_nonce%3D225579211881198842005988698334675835446%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1199645624%26oauth_version%3D1.0", signature_base_string
end
def test_that_post_bodies_signed_if_form_urlencoded
request = Net::HTTP::Post.new(@request_uri.path)
request.set_form_data( { 'key2' => 'value2' } )
signature_base_string=request.signature_base_string(@http, @consumer, nil, { :nonce => @nonce, :timestamp => @timestamp })
assert_equal "POST&http%3A%2F%2Fexample.com%2Ftest&key2%3Dvalue2%26oauth_consumer_key%3Dconsumer_key_86cad9%26oauth_nonce%3D225579211881198842005988698334675835446%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1199645624%26oauth_version%3D1.0", signature_base_string
end
def test_that_post_bodies_signed_if_other_content_type
request = Net::HTTP::Post.new(@request_uri.path)
request.body = "baz"
request["Content-Type"] = "application/xml"
signature_base_string=request.signature_base_string(@http, @consumer, nil, { :nonce => @nonce, :timestamp => @timestamp })
assert_equal "POST&http%3A%2F%2Fexample.com%2Ftest&oauth_body_hash%3DDvAa1AWdFoH9K%252B%252F2AHm3f6wH27k%253D%26oauth_consumer_key%3Dconsumer_key_86cad9%26oauth_nonce%3D225579211881198842005988698334675835446%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1199645624%26oauth_version%3D1.0", signature_base_string
end
def test_that_site_address_is_not_modified_in_place
options = { :site => 'http://twitter.com', :request_endpoint => 'http://api.twitter.com' }
request = Net::HTTP::Get.new(@request_uri.path + "?" + request_parameters_to_s)
request.oauth!(@http, @consumer, @token, options)
assert_equal "http://twitter.com", options[:site]
assert_equal "http://api.twitter.com", options[:request_endpoint]
end
protected
def assert_no_match exp, act, msg = "Expected #{act.inspect} to not match #{exp.inspect}"
assert act !~ exp, msg
end
def request_parameters_to_s
@request_parameters.map { |k,v| "#{k}=#{v}" }.join("&")
end
end
oauth-ruby-0.5.3/test/units/test_net_http_request_proxy.rb 0000664 0000000 0000000 00000006160 13111303321 0024150 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
class NetHTTPRequestProxyTest < Minitest::Test
def test_that_proxy_simple_get_request_works
request = Net::HTTP::Get.new('/test?key=value')
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value'})
expected_parameters = {'key' => ['value']}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'GET', request_proxy.method
end
def test_that_proxy_simple_post_request_works_with_arguments
request = Net::HTTP::Post.new('/test')
params = {'key' => 'value'}
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params})
expected_parameters = {'key' => ['value']}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'POST', request_proxy.method
end
def test_that_proxy_simple_post_request_works_with_form_data
request = Net::HTTP::Post.new('/test')
params = {'key' => 'value'}
request.set_form_data(params)
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'})
expected_parameters = {'key' => ['value']}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'POST', request_proxy.method
end
def test_that_proxy_simple_put_request_works_with_argugments
request = Net::HTTP::Put.new('/test')
params = {'key' => 'value'}
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params})
expected_parameters = {'key' => ['value']}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'PUT', request_proxy.method
end
def test_that_proxy_simple_put_request_works_with_form_data
request = Net::HTTP::Put.new('/test')
params = {'key' => 'value'}
request.set_form_data(params)
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'})
expected_parameters = {'key' => ['value']}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'PUT', request_proxy.method
end
def test_that_proxy_post_request_uses_post_parameters
request = Net::HTTP::Post.new('/test?key=value')
request.set_form_data({'key2' => 'value2'})
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value', :parameters => {'key3' => 'value3'}})
expected_parameters = {'key' => ['value'], 'key2' => ['value2'], 'key3' => ['value3']}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'POST', request_proxy.method
end
end
oauth-ruby-0.5.3/test/units/test_oauth_helper.rb 0000664 0000000 0000000 00000007254 13111303321 0021776 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
class TestOAuthHelper < Minitest::Test
def test_parse_valid_header
header = 'OAuth ' \
'realm="http://example.com/method", ' \
'oauth_consumer_key="vince_clortho", ' \
'oauth_token="token_value", ' \
'oauth_signature_method="HMAC-SHA1", ' \
'oauth_signature="signature_here", ' \
'oauth_timestamp="1240004133", oauth_nonce="nonce", ' \
'oauth_version="1.0" '
params = OAuth::Helper.parse_header(header)
assert_equal "http://example.com/method", params['realm']
assert_equal "vince_clortho", params['oauth_consumer_key']
assert_equal "token_value", params['oauth_token']
assert_equal "HMAC-SHA1", params['oauth_signature_method']
assert_equal "signature_here", params['oauth_signature']
assert_equal "1240004133", params['oauth_timestamp']
assert_equal "nonce", params['oauth_nonce']
assert_equal "1.0", params['oauth_version']
end
def test_parse_header_ill_formed
header = "OAuth garbage"
assert_raises OAuth::Problem do
OAuth::Helper.parse_header(header)
end
end
def test_parse_header_contains_equals
header = 'OAuth ' \
'realm="http://example.com/method", ' \
'oauth_consumer_key="vince_clortho", ' \
'oauth_token="token_value", ' \
'oauth_signature_method="HMAC-SHA1", ' \
'oauth_signature="signature_here_with_=", ' \
'oauth_timestamp="1240004133", oauth_nonce="nonce", ' \
'oauth_version="1.0" '
assert_raises OAuth::Problem do
OAuth::Helper.parse_header(header)
end
end
def test_parse_valid_header_with_and_signs
header = 'OAuth ' \
'realm="http://example.com/method"&' \
'oauth_consumer_key="vince_clortho"&' \
'oauth_token="token_value"&' \
'oauth_signature_method="HMAC-SHA1"&' \
'oauth_signature="signature_here"&' \
'oauth_timestamp="1240004133"&oauth_nonce="nonce"&' \
'oauth_version="1.0"'
params = OAuth::Helper.parse_header(header)
assert_equal "http://example.com/method", params['realm']
assert_equal "vince_clortho", params['oauth_consumer_key']
assert_equal "token_value", params['oauth_token']
assert_equal "HMAC-SHA1", params['oauth_signature_method']
assert_equal "signature_here", params['oauth_signature']
assert_equal "1240004133", params['oauth_timestamp']
assert_equal "nonce", params['oauth_nonce']
assert_equal "1.0", params['oauth_version']
end
def test_normalize
params = {
'oauth_nonce' => 'nonce',
'weight' => { :value => "65" },
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => "1240004133",
'oauth_consumer_key' => 'vince_clortho',
'oauth_token' => 'token_value',
'oauth_version' => "1.0"
}
assert_equal("oauth_consumer_key=vince_clortho&oauth_nonce=nonce&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1240004133&oauth_token=token_value&oauth_version=1.0&weight%5Bvalue%5D=65", OAuth::Helper.normalize(params))
end
def test_normalize_nested_query
assert_equal([], OAuth::Helper.normalize_nested_query({}))
assert_equal(["foo=bar"], OAuth::Helper.normalize_nested_query({:foo => 'bar'}))
assert_equal(["prefix%5Bfoo%5D=bar"], OAuth::Helper.normalize_nested_query({:foo => 'bar'}, 'prefix'))
assert_equal(["prefix%5Buser%5D%5Bage%5D=12",
"prefix%5Buser%5D%5Bdate%5D=2011-10-05",
"prefix%5Buser%5D%5Btwitter_id%5D=123"], OAuth::Helper.normalize_nested_query({:user => {:twitter_id => 123, :date => '2011-10-05', :age => 12}}, 'prefix'))
end
end
oauth-ruby-0.5.3/test/units/test_rack_request_proxy.rb 0000664 0000000 0000000 00000003347 13111303321 0023247 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
require 'oauth/request_proxy/rack_request'
class RackRequestProxyTest < Minitest::Test
def test_that_proxy_simple_get_request_works
request = Rack::Request.new(Rack::MockRequest.env_for('http://example.com/test?key=value'))
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value'})
expected_parameters = {'key' => 'value'}
assert_equal expected_parameters, request_proxy.parameters
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'GET', request_proxy.method
end
def test_that_proxy_simple_post_request_works
request = Rack::Request.new(Rack::MockRequest.env_for('http://example.com/test', :method => 'POST'))
params = {'key' => 'value'}
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params})
expected_parameters = {'key' => 'value'}
assert_equal expected_parameters, request_proxy.parameters
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'POST', request_proxy.method
end
def test_that_proxy_post_and_get_request_works
request = Rack::Request.new(Rack::MockRequest.env_for('http://example.com/test?key=value', :method => 'POST', :input => 'key2=value2'))
params = {'key2' => 'value2'}
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value', :parameters => params})
expected_parameters = {'key' => 'value', 'key2' => 'value2'}
assert_equal expected_parameters, request_proxy.parameters
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'POST', request_proxy.method
end
end
oauth-ruby-0.5.3/test/units/test_request_token.rb 0000664 0000000 0000000 00000003471 13111303321 0022204 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
class StubbedToken < OAuth::RequestToken
define_method :build_authorize_url_promoted do |root_domain, params|
build_authorize_url root_domain, params
end
end
class TestRequestToken < Minitest::Test
def setup
# setup a fake req. token. mocking Consumer would be more appropriate...
@request_token = OAuth::RequestToken.new(
OAuth::Consumer.new("key", "secret", {}),
"key",
"secret"
)
end
def test_request_token_builds_authorize_url_connectly_with_additional_params
auth_url = @request_token.authorize_url({:oauth_callback => "github.com"})
assert auth_url
assert_match(/oauth_token/, auth_url)
assert_match(/oauth_callback/, auth_url)
end
def test_request_token_builds_authorize_url_connectly_with_no_or_nil_params
# we should only have 1 key in the url returned if we didn't pass anything.
# this is the only required param to authenticate the client.
auth_url = @request_token.authorize_url(nil)
assert auth_url
assert_match(/\?oauth_token=/, auth_url)
auth_url = @request_token.authorize_url
assert auth_url
assert_match(/\?oauth_token=/, auth_url)
end
def test_request_token_returns_nil_authorize_url_when_token_is_nil
@request_token.token = nil
assert_nil @request_token.authorize_url
end
#TODO: mock out the Consumer to test the Consumer/AccessToken interaction.
def test_get_access_token
end
def test_build_authorize_url
@stubbed_token = StubbedToken.new(nil, nil, nil)
assert_respond_to @stubbed_token, :build_authorize_url_promoted
url = @stubbed_token.build_authorize_url_promoted(
"http://github.com/oauth/authorize",
{:foo => "bar bar"})
assert url
assert_equal "http://github.com/oauth/authorize?foo=bar+bar", url
end
end
oauth-ruby-0.5.3/test/units/test_rest_client_request_proxy.rb 0000664 0000000 0000000 00000007472 13111303321 0024645 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
begin
require 'oauth/request_proxy/rest_client_request'
require 'rest-client'
class RestlClientRequestProxyTest < Minitest::Test
def test_that_proxy_simple_get_request_works
request = ::RestClient::Request.new(method: :get, url: "http://example.com/test?key=value")
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value'})
expected_parameters = {'key' => ['value']}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'GET', request_proxy.method
end
def test_that_proxy_simple_post_request_works_with_arguments
request = ::RestClient::Request.new(method: :post, url: "http://example.com/test")
params = {'key' => 'value'}
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params})
expected_parameters = {'key' => 'value'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'POST', request_proxy.method
end
def test_that_proxy_simple_post_request_works_with_form_data
request = ::RestClient::Request.new(method: :post, url: "http://example.com/test",
payload: {'key' => 'value'},
headers: {'Content-Type' => 'application/x-www-form-urlencoded'})
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'})
expected_parameters = {'key' => 'value'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'POST', request_proxy.method
end
def test_that_proxy_simple_put_request_works_with_arguments
request = ::RestClient::Request.new(method: :put, url: "http://example.com/test")
params = {'key' => 'value'}
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params})
expected_parameters = {'key' => 'value'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'PUT', request_proxy.method
end
def test_that_proxy_simple_put_request_works_with_form_data
request = ::RestClient::Request.new(method: :put, url: "http://example.com/test",
payload: {'key' => 'value'},
headers: {'Content-Type' => 'application/x-www-form-urlencoded'})
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'})
expected_parameters = {'key' => 'value'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'PUT', request_proxy.method
end
def test_that_proxy_post_request_works_with_mixed_parameter_sources
request = ::RestClient::Request.new(url: 'http://example.com/test?key=value',
method: :post,
payload: {'key2' => 'value2'},
headers: {'Content-Type' => 'application/x-www-form-urlencoded'})
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value', :parameters => {'key3' => 'value3'}})
expected_parameters = {'key' => ['value'], 'key2' => 'value2', 'key3' => 'value3'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'POST', request_proxy.method
end
end
rescue LoadError => e
warn "! problem loading rest-client, skipping these tests: #{e}"
end
oauth-ruby-0.5.3/test/units/test_rsa_sha1.rb 0000664 0000000 0000000 00000007635 13111303321 0021023 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
require 'oauth/consumer'
require 'oauth/signature/rsa/sha1'
class TestSignatureRsaSha1 < Minitest::Test
def setup
@request = Net::HTTP::Get.new("/photos?file=vacaction.jpg&size=original&oauth_version=1.0&oauth_consumer_key=#{consumer_key}&oauth_timestamp=1196666512&oauth_nonce=13917289812797014437&oauth_signature_method=RSA-SHA1")
@consumer = OAuth::Consumer.new(consumer_key, pkey_rsa)
end
def test_that_rsa_sha1_implements_rsa_sha1
assert OAuth::Signature.available_methods.include?('rsa-sha1')
end
def test_that_get_request_from_oauth_test_cases_produces_matching_signature_base_string
sbs = OAuth::Signature.signature_base_string(@request, { :consumer => @consumer,
:uri => 'http://photos.example.net/photos' } )
assert_equal 'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacaction.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3D13917289812797014437%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1196666512%26oauth_version%3D1.0%26size%3Doriginal', sbs
end
def test_that_get_request_from_oauth_test_cases_produces_matching_signature
signature = OAuth::Signature.sign(@request, { :consumer => @consumer,
:uri => 'http://photos.example.net/photos' } )
assert_equal 'jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE=', signature
end
def test_that_get_request_from_oauth_test_cases_produces_matching_signature_using_private_key_file
@consumer = OAuth::Consumer.new(consumer_key,nil)
signature = OAuth::Signature.sign(@request, { :consumer => @consumer,
:private_key_file=>pem_path,
:uri => 'http://photos.example.net/photos' } )
assert_equal 'jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE=', signature
end
def test_that_get_request_from_oauth_test_cases_verifies_signature
@request = Net::HTTP::Get.new("/photos?oauth_signature_method=RSA-SHA1&oauth_version=1.0&oauth_consumer_key=#{consumer_key}&oauth_timestamp=1196666512&oauth_nonce=13917289812797014437&file=vacaction.jpg&size=original&oauth_signature=jvTp%2FwX1TYtByB1m%2BPbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2%2F9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW%2F%2Fe%2BRinhejgCuzoH26dyF8iY2ZZ%2F5D1ilgeijhV%2FvBka5twt399mXwaYdCwFYE%3D")
@consumer = OAuth::Consumer.new(consumer_key, x509_certificate)
assert OAuth::Signature.verify(@request, { :consumer => @consumer,
:uri => 'http://photos.example.net/photos' } )
end
def test_that_get_request_from_oauth_test_cases_verifies_signature_with_pem
@request = Net::HTTP::Get.new("/photos?oauth_signature_method=RSA-SHA1&oauth_version=1.0&oauth_consumer_key=#{consumer_key}&oauth_timestamp=1196666512&oauth_nonce=13917289812797014437&file=vacaction.jpg&size=original&oauth_signature=jvTp%2FwX1TYtByB1m%2BPbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2%2F9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW%2F%2Fe%2BRinhejgCuzoH26dyF8iY2ZZ%2F5D1ilgeijhV%2FvBka5twt399mXwaYdCwFYE%3D")
assert OAuth::Signature.verify(@request, { :consumer => @consumer,
:uri => 'http://photos.example.net/photos' } )
end
private
def consumer_key
'dpf43f3p2l4k3l03'
end
def x509_certificate
OpenSSL::X509::Certificate.new(IO.read(cert_path))
end
def pkey_rsa
OpenSSL::PKey::RSA.new(IO.read(pem_path))
end
def cert_path
File.dirname(__FILE__) + "/../keys/rsa.cert"
end
def pem_path
File.dirname(__FILE__) + "/../keys/rsa.pem"
end
end
oauth-ruby-0.5.3/test/units/test_server.rb 0000664 0000000 0000000 00000002657 13111303321 0020627 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
require 'oauth/server'
class ServerTest < Minitest::Test
def setup
@server=OAuth::Server.new "http://test.com"
end
def test_default_paths
assert_equal "/oauth/request_token",@server.request_token_path
assert_equal "/oauth/authorize",@server.authorize_path
assert_equal "/oauth/access_token",@server.access_token_path
end
def test_default_urls
assert_equal "http://test.com/oauth/request_token",@server.request_token_url
assert_equal "http://test.com/oauth/authorize",@server.authorize_url
assert_equal "http://test.com/oauth/access_token",@server.access_token_url
end
def test_generate_consumer_credentials
consumer=@server.generate_consumer_credentials
assert consumer.key
assert consumer.secret
end
def test_create_consumer
@consumer=@server.create_consumer
assert @consumer
assert @consumer.key
assert @consumer.secret
assert_equal "http://test.com",@consumer.site
assert_equal "/oauth/request_token",@consumer.request_token_path
assert_equal "/oauth/authorize",@consumer.authorize_path
assert_equal "/oauth/access_token",@consumer.access_token_path
assert_equal "http://test.com/oauth/request_token",@consumer.request_token_url
assert_equal "http://test.com/oauth/authorize",@consumer.authorize_url
assert_equal "http://test.com/oauth/access_token",@consumer.access_token_url
end
end
oauth-ruby-0.5.3/test/units/test_signature.rb 0000664 0000000 0000000 00000000767 13111303321 0021322 0 ustar 00root root 0000000 0000000 # -*- encoding: utf-8 -*-
require File.expand_path('../../test_helper', __FILE__)
class TestOauth < Minitest::Test
def test_parameter_escaping_kcode_invariant
%w(n N e E s S u U).each do |kcode|
assert_equal '%E3%81%82', OAuth::Helper.escape('あ'),
"Failed to correctly escape Japanese under $KCODE = #{kcode}"
assert_equal '%C3%A9', OAuth::Helper.escape('é'),
"Failed to correctly escape e+acute under $KCODE = #{kcode}"
end
end
end
oauth-ruby-0.5.3/test/units/test_signature_base.rb 0000664 0000000 0000000 00000001440 13111303321 0022301 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
require 'oauth/signature/base'
require 'net/http'
class SignatureBaseTest < Minitest::Test
def test_that_initialize_requires_one_request_argument
assert_raises ArgumentError do
OAuth::Signature::Base.new()
end
end
def test_that_initialize_requires_a_valid_request_argument
request = nil
assert_raises TypeError do
OAuth::Signature::Base.new(request) { |token|
# just a stub
}
end
end
def test_that_initialize_succeeds_when_the_request_proxy_is_valid
# this isn't quite valid, but it will do.
raw_request = Net::HTTP::Get.new('/test')
request = OAuth::RequestProxy.proxy(raw_request)
OAuth::Signature::Base.new(request) { |token|
# just a stub
}
end
end
oauth-ruby-0.5.3/test/units/test_signature_hmac_sha1.rb 0000664 0000000 0000000 00000003267 13111303321 0023224 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
require 'oauth/signature/hmac/sha1'
class SignatureHMACSHA1Test < Minitest::Test
def test_that_verify_returns_true_when_the_request_signature_is_right
request = OAuth::RequestProxy::MockRequest.new(
'method' => 'POST',
'uri' => 'https://photos.example.net/initialize',
'parameters' => {
'oauth_consumer_key' => 'dpf43f3p2l4k3l03',
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => '137131200',
'oauth_nonce' => 'wIjqoS',
'oauth_callback' => 'http://printer.example.com/ready',
'oauth_version' => '1.0',
'oauth_signature' => 'xcHYBV3AbyoDz7L4dV10P3oLCjY='
}
)
assert OAuth::Signature::HMAC::SHA1.new(request, :consumer_secret => 'kd94hf93k423kf44').verify
end
def test_that_verify_returns_false_when_the_request_signature_is_wrong
# Test a bug in the OAuth::Signature::Base#== method: when the Base64.decode64 method is
# used on the "self" and "other" signature (as in version 0.4.7), the result may be incorrectly "true".
request = OAuth::RequestProxy::MockRequest.new(
'method' => 'POST',
'uri' => 'https://photos.example.net/initialize',
'parameters' => {
'oauth_consumer_key' => 'dpf43f3p2l4k3l03',
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => '137131200',
'oauth_nonce' => 'wIjqoS',
'oauth_callback' => 'http://printer.example.com/ready',
'oauth_version' => '1.0',
'oauth_signature' => 'xcHYBV3AbyoDz7L4dV10P3oLCjZ='
}
)
assert !OAuth::Signature::HMAC::SHA1.new(request, :consumer_secret => 'kd94hf93k423kf44').verify
end
end
oauth-ruby-0.5.3/test/units/test_signature_plain_text.rb 0000664 0000000 0000000 00000003342 13111303321 0023541 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
require 'oauth/signature/plaintext'
class TestSignaturePlaintext < Minitest::Test
def test_that_plaintext_implements_plaintext
assert OAuth::Signature.available_methods.include?('plaintext')
end
def test_that_get_request_from_oauth_test_cases_produces_matching_signature
request = Net::HTTP::Get.new('/photos?file=vacation.jpg&size=original&oauth_version=1.0&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_token=nnch734d00sl2jdk&oauth_signature=kd94hf93k423kf44%26&oauth_timestamp=1191242096&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=PLAINTEXT')
consumer = OAuth::Consumer.new('dpf43f3p2l4k3l03','kd94hf93k423kf44')
token = OAuth::Token.new('nnch734d00sl2jdk', nil)
assert OAuth::Signature.verify(request, { :consumer => consumer,
:token => token,
:uri => 'http://photos.example.net/photos' } )
end
def test_that_get_request_from_oauth_test_cases_produces_matching_signature_part_two
request = Net::HTTP::Get.new('/photos?file=vacation.jpg&size=original&oauth_version=1.0&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_token=nnch734d00sl2jdk&oauth_signature=kd94hf93k423kf44%26pfkkdhi9sl3r4s00&oauth_timestamp=1191242096&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=PLAINTEXT')
consumer = OAuth::Consumer.new('dpf43f3p2l4k3l03','kd94hf93k423kf44')
token = OAuth::Token.new('nnch734d00sl2jdk', 'pfkkdhi9sl3r4s00')
assert OAuth::Signature.verify(request, { :consumer => consumer,
:token => token,
:uri => 'http://photos.example.net/photos' } )
end
end
oauth-ruby-0.5.3/test/units/test_token.rb 0000664 0000000 0000000 00000000465 13111303321 0020434 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
require 'oauth/token'
class TestToken < Minitest::Test
def setup
end
def test_token_constructor_produces_valid_token
token = OAuth::Token.new('xyz', '123')
assert_equal 'xyz', token.token
assert_equal '123', token.secret
end
end
oauth-ruby-0.5.3/test/units/test_typhoeus_request_proxy.rb 0000664 0000000 0000000 00000010734 13111303321 0024205 0 ustar 00root root 0000000 0000000 require File.expand_path('../../test_helper', __FILE__)
begin
require 'oauth/request_proxy/typhoeus_request'
require 'typhoeus'
class TyphoeusRequestProxyTest < Minitest::Test
def test_that_proxy_simple_get_request_works
request = ::Typhoeus::Request.new('/test?key=value')
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value'})
expected_parameters = {'key' => ['value']}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'GET', request_proxy.method
end
def test_that_proxy_simple_post_request_works_with_arguments
request = Typhoeus::Request.new('/test', :method => :post)
params = {'key' => 'value'}
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params})
expected_parameters = {'key' => 'value'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'POST', request_proxy.method
end
def test_that_proxy_simple_post_request_works_with_form_data
request = Typhoeus::Request.new('/test', :method => :post,
:params => {'key' => 'value'},
:headers => {'Content-Type' => 'application/x-www-form-urlencoded'})
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'})
expected_parameters = {'key' => ['value']}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'POST', request_proxy.method
end
def test_that_proxy_simple_put_request_works_with_arguments
request = Typhoeus::Request.new('/test', :method => :put)
params = {'key' => 'value'}
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params})
expected_parameters = {'key' => 'value'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'PUT', request_proxy.method
end
def test_that_proxy_simple_put_request_works_with_form_data
request = Typhoeus::Request.new('/test', :method => :put, :params => {'key' => 'value'})
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'})
expected_parameters = {'key' => ['value']}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'PUT', request_proxy.method
end
def test_that_proxy_simple_patch_request_works_with_arguments
request = Typhoeus::Request.new('/test', :method => :patch)
params = {'key' => 'value'}
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test', :parameters => params})
expected_parameters = {'key' => 'value'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'PATCH', request_proxy.method
end
def test_that_proxy_simple_patch_request_works_with_form_data
request = Typhoeus::Request.new('/test', :method => :patch, :params => {'key' => 'value'})
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test'})
expected_parameters = {'key' => ['value']}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'PATCH', request_proxy.method
end
def test_that_proxy_post_request_works_with_mixed_parameter_sources
request = Typhoeus::Request.new('/test?key=value',
:method => :post,
:params => {'key2' => 'value2'},
:headers => {'Content-Type' => 'application/x-www-form-urlencoded'})
request_proxy = OAuth::RequestProxy.proxy(request, {:uri => 'http://example.com/test?key=value', :parameters => {'key3' => 'value3'}})
expected_parameters = {'key' => ['value'], 'key2' => ['value2'], 'key3' => 'value3'}
assert_equal expected_parameters, request_proxy.parameters_for_signature
assert_equal 'http://example.com/test', request_proxy.normalized_uri
assert_equal 'POST', request_proxy.method
end
end
rescue LoadError => e
warn "! problem loading typhoeus, skipping these tests: #{e}"
end