stocktwits 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (49) hide show
  1. data/.document +5 -0
  2. data/.gitignore +21 -0
  3. data/LICENSE +20 -0
  4. data/README +0 -0
  5. data/README.rdoc +17 -0
  6. data/Rakefile +63 -0
  7. data/VERSION +1 -0
  8. data/app/controllers/sessions_controller.rb +68 -0
  9. data/app/models/stocktwits/basic_user.rb +64 -0
  10. data/app/models/stocktwits/generic_user.rb +123 -0
  11. data/app/models/stocktwits/oauth_user.rb +46 -0
  12. data/app/models/stocktwits/plain_user.rb +53 -0
  13. data/app/views/sessions/_login.html.erb +18 -0
  14. data/app/views/sessions/new.html.erb +5 -0
  15. data/config/routes.rb +6 -0
  16. data/generators/stocktwits/USAGE +12 -0
  17. data/generators/stocktwits/stocktwits_generator.rb +42 -0
  18. data/generators/stocktwits/templates/migration.rb +20 -0
  19. data/generators/stocktwits/templates/stocktwits.yml +66 -0
  20. data/generators/stocktwits/templates/user.rb +5 -0
  21. data/lib/stocktwits.rb +103 -0
  22. data/lib/stocktwits/controller_extensions.rb +72 -0
  23. data/lib/stocktwits/cryptify.rb +30 -0
  24. data/lib/stocktwits/dispatcher/basic.rb +46 -0
  25. data/lib/stocktwits/dispatcher/oauth.rb +26 -0
  26. data/lib/stocktwits/dispatcher/plain.rb +44 -0
  27. data/lib/stocktwits/dispatcher/shared.rb +42 -0
  28. data/rails/init.rb +6 -0
  29. data/spec/application.rb +1 -0
  30. data/spec/controllers/controller_extensions_spec.rb +162 -0
  31. data/spec/controllers/sessions_controller_spec.rb +221 -0
  32. data/spec/debug.log +397 -0
  33. data/spec/fixtures/config/twitter_auth.yml +17 -0
  34. data/spec/fixtures/factories.rb +28 -0
  35. data/spec/fixtures/fakeweb.rb +18 -0
  36. data/spec/fixtures/stocktwits.rb +5 -0
  37. data/spec/models/stocktwits/basic_user_spec.rb +138 -0
  38. data/spec/models/stocktwits/generic_user_spec.rb +146 -0
  39. data/spec/models/stocktwits/oauth_user_spec.rb +100 -0
  40. data/spec/schema.rb +25 -0
  41. data/spec/spec.opts +1 -0
  42. data/spec/spec_helper.rb +107 -0
  43. data/spec/stocktwits/cryptify_spec.rb +51 -0
  44. data/spec/stocktwits/dispatcher/basic_spec.rb +83 -0
  45. data/spec/stocktwits/dispatcher/oauth_spec.rb +72 -0
  46. data/spec/stocktwits/dispatcher/shared_spec.rb +26 -0
  47. data/spec/stocktwits_spec.rb +173 -0
  48. data/stocktwits.gemspec +116 -0
  49. metadata +158 -0
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
data/.gitignore ADDED
@@ -0,0 +1,21 @@
1
+ ## MAC OS
2
+ .DS_Store
3
+
4
+ ## TEXTMATE
5
+ *.tmproj
6
+ tmtags
7
+
8
+ ## EMACS
9
+ *~
10
+ \#*
11
+ .\#*
12
+
13
+ ## VIM
14
+ *.swp
15
+
16
+ ## PROJECT::GENERAL
17
+ coverage
18
+ rdoc
19
+ pkg
20
+
21
+ ## PROJECT::SPECIFIC
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 Elad Meidar
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README ADDED
File without changes
data/README.rdoc ADDED
@@ -0,0 +1,17 @@
1
+ = stocktwits
2
+
3
+ Description goes here.
4
+
5
+ == Note on Patches/Pull Requests
6
+
7
+ * Fork the project.
8
+ * Make your feature addition or bug fix.
9
+ * Add tests for it. This is important so I don't break it in a
10
+ future version unintentionally.
11
+ * Commit, do not mess with rakefile, version, or history.
12
+ (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
13
+ * Send me a pull request. Bonus points for topic branches.
14
+
15
+ == Copyright
16
+
17
+ Copyright (c) 2010 Elad Meidar. See LICENSE for details.
data/Rakefile ADDED
@@ -0,0 +1,63 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+ require 'spec/rake/spectask'
4
+
5
+ begin
6
+ require 'jeweler'
7
+ Jeweler::Tasks.new do |gem|
8
+ gem.name = "stocktwits"
9
+ gem.summary = %Q{ Stocktwits.com API wrapper}
10
+ gem.description = %Q{ Provide an OAuth, Basic HTTP authentication and plain interfaces to the StockTwits API.}
11
+ gem.email = "elad@eizesus.com"
12
+ gem.homepage = "http://github.com/eladmeidar/stocktwits"
13
+ gem.authors = ["Elad Meidar"]
14
+ gem.add_development_dependency "thoughtbot-shoulda", ">= 0"
15
+ gem.add_dependency 'ezcrypto'
16
+ gem.add_dependency 'oauth'
17
+ gem.add_dependency 'json'
18
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
19
+ end
20
+ Jeweler::GemcutterTasks.new
21
+ rescue LoadError
22
+ puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
23
+ end
24
+
25
+ require 'rake/testtask'
26
+ Rake::TestTask.new(:test) do |test|
27
+ test.libs << 'lib' << 'test'
28
+ test.pattern = 'test/**/test_*.rb'
29
+ test.verbose = true
30
+ end
31
+
32
+ begin
33
+ require 'rcov/rcovtask'
34
+ Rcov::RcovTask.new do |test|
35
+ test.libs << 'test'
36
+ test.pattern = 'test/**/test_*.rb'
37
+ test.verbose = true
38
+ end
39
+ rescue LoadError
40
+ task :rcov do
41
+ abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
42
+ end
43
+ end
44
+
45
+ task :test => :check_dependencies
46
+
47
+ desc 'Default: run specs.'
48
+ task :default => :spec
49
+ desc 'Run the specs'
50
+ Spec::Rake::SpecTask.new(:spec) do |t|
51
+ t.spec_opts = ['--colour --format progress --loadby mtime --reverse']
52
+ t.spec_files = FileList['spec/**/*_spec.rb']
53
+ end
54
+
55
+ require 'rake/rdoctask'
56
+ Rake::RDocTask.new do |rdoc|
57
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
58
+
59
+ rdoc.rdoc_dir = 'rdoc'
60
+ rdoc.title = "stocktwits #{version}"
61
+ rdoc.rdoc_files.include('README*')
62
+ rdoc.rdoc_files.include('lib/**/*.rb')
63
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.0.0
@@ -0,0 +1,68 @@
1
+ class SessionsController < ApplicationController
2
+ unloadable
3
+
4
+ def new
5
+ if Stocktwits.oauth?
6
+ oauth_callback = request.protocol + request.host_with_port + '/oauth_callback'
7
+ @request_token = Stocktwits.consumer.get_request_token({:oauth_callback=>oauth_callback})
8
+ session[:request_token] = @request_token.token
9
+ session[:request_token_secret] = @request_token.secret
10
+
11
+ url = @request_token.authorize_url
12
+ url << "&oauth_callback=#{CGI.escape(Stocktwits.oauth_callback)}" if Stocktwits.oauth_callback?
13
+ redirect_to url
14
+ else
15
+ # we don't have to do anything, it's just a simple form for HTTP basic!
16
+ end
17
+ end
18
+
19
+ def create
20
+ logout_keeping_session!
21
+ if user = User.authenticate(params[:login], params[:password])
22
+ self.current_user = user
23
+ authentication_succeeded and return
24
+ else
25
+ authentication_failed('Unable to verify your credentials through Stocktwits. Please try again.', '/login') and return
26
+ end
27
+ end
28
+
29
+ def oauth_callback
30
+ unless session[:request_token] && session[:request_token_secret]
31
+ authentication_failed('No authentication information was found in the session. Please try again.') and return
32
+ end
33
+
34
+ unless params[:oauth_token].blank? || session[:request_token] == params[:oauth_token]
35
+ authentication_failed('Authentication information does not match session information. Please try again.') and return
36
+ end
37
+
38
+ @request_token = OAuth::RequestToken.new(Stocktwits.consumer, session[:request_token], session[:request_token_secret])
39
+
40
+ oauth_verifier = params["oauth_verifier"]
41
+ @access_token = @request_token.get_access_token(:oauth_verifier => oauth_verifier)
42
+
43
+ # The request token has been invalidated
44
+ # so we nullify it in the session.
45
+ session[:request_token] = nil
46
+ session[:request_token_secret] = nil
47
+
48
+ @user = User.identify_or_create_from_access_token(@access_token)
49
+
50
+ session[:user_id] = @user.id
51
+
52
+ cookies[:remember_token] = @user.remember_me
53
+
54
+ authentication_succeeded
55
+ rescue Net::HTTPServerException => e
56
+ case e.message
57
+ when '401 "Unauthorized"'
58
+ authentication_failed('This authentication request is no longer valid. Please try again.') and return
59
+ else
60
+ authentication_failed('There was a problem trying to authenticate you. Please try again.') and return
61
+ end
62
+ end
63
+
64
+ def destroy
65
+ logout_keeping_session!
66
+ redirect_back_or_default('/')
67
+ end
68
+ end
@@ -0,0 +1,64 @@
1
+ require 'net/http'
2
+
3
+ module Stocktwits
4
+ module BasicUser
5
+ def self.included(base)
6
+ base.class_eval do
7
+ attr_protected :crypted_password, :salt
8
+ end
9
+
10
+ base.extend Stocktwits::BasicUser::ClassMethods
11
+ end
12
+
13
+ module ClassMethods
14
+ def verify_credentials(login, password)
15
+ response = Stocktwits.net.start { |http|
16
+ request = Net::HTTP::Get.new('/account/verify_credentials.json')
17
+ request.basic_auth login, password
18
+ http.request(request)
19
+ }
20
+
21
+ if response.code == '200'
22
+ JSON.parse(response.body)
23
+ else
24
+ false
25
+ end
26
+ end
27
+
28
+ def authenticate(login, password)
29
+ if stocktwits_hash = verify_credentials(login, password)
30
+ user = identify_or_create_from_stocktwits_hash_and_password(stocktwits_hash, password)
31
+ user
32
+ else
33
+ nil
34
+ end
35
+ end
36
+
37
+ def identify_or_create_from_stocktwits_hash_and_password(stocktwits_hash, password)
38
+ if user = User.find_by_stocktwits_id(stocktwits_hash['id'].to_s)
39
+ user.login = stocktwits_hash['screen_name']
40
+ user.assign_stocktwits_attributes(stocktwits_hash)
41
+ user.password = password
42
+ user.save
43
+ user
44
+ else
45
+ user = User.new_from_stocktwits_hash(stocktwits_hash)
46
+ user.password = password
47
+ user.save
48
+ user
49
+ end
50
+ end
51
+ end
52
+
53
+ def password=(new_password)
54
+ encrypted = Stocktwits::Cryptify.encrypt(new_password)
55
+ self.crypted_password = encrypted[:encrypted_data]
56
+ self.salt = encrypted[:salt]
57
+ end
58
+
59
+ def password
60
+ Stocktwits::Cryptify.decrypt(self.crypted_password, self.salt)
61
+ end
62
+ end
63
+ end
64
+
@@ -0,0 +1,123 @@
1
+ module Stocktwits
2
+ class GenericUser < ActiveRecord::Base
3
+ attr_protected :stocktwits_id, :remember_token, :remember_token_expires_at
4
+
5
+ STOCKTWITS_FIELDS = ["avatar_url_thumb",
6
+ "avatar_url_medium",
7
+ #"profile",
8
+ "following_count",
9
+ #"id",
10
+ "updates_count",
11
+ "avatar_url_large",
12
+ "last_name",
13
+ "followers_count",
14
+ "recommended",
15
+ "bio",
16
+ # "login",
17
+ "first_name"]
18
+
19
+ STOCKTWITS_PROFILE_FIELDS = ["approach",
20
+ "location",
21
+ "title",
22
+ "risk_profile",
23
+ "focus",
24
+ #"id",
25
+ "long_short",
26
+ "qualifications",
27
+ "user_id",
28
+ "investment_style",
29
+ "website",
30
+ "asset_classes_traded",
31
+ "bio",
32
+ "capitalization_bias",
33
+ "holding_period",
34
+ "education",
35
+ "industry",
36
+ "personal_interests",
37
+ "trading_experience"]
38
+
39
+ # with_options :if => :utilize_default_validations do |v|
40
+ # v.validates_presence_of :login, :stocktwits_id
41
+ # v.validates_format_of :login, :with => /\A[a-z0-9_]+\z/i
42
+ # v.validates_length_of :login, :in => 1..15
43
+ # v.validates_uniqueness_of :login, :case_sensitive => false
44
+ # v.validates_uniqueness_of :stocktwits_id, :message => "ID has already been taken."
45
+ # v.validates_uniqueness_of :remember_token, :allow_blank => true
46
+ # end
47
+
48
+ def self.table_name; 'users' end
49
+
50
+ def self.new_from_stocktwits_hash(hash)
51
+ raise ArgumentError, "Expected a 'user' key in attributes hash, got: #{hash.keys.inspect}" unless hash.key?('user')
52
+ hash = hash['user']
53
+ raise ArgumentError, "Invalid hash: must include login." unless hash.key?('login')
54
+
55
+ raise ArgumentError, 'Invalid hash: must include id.' unless hash.key?('id')
56
+
57
+ user = User.new
58
+ user.stocktwits_id = hash['id'].to_s
59
+ user.login = hash['login']
60
+
61
+ user.assign_stocktwits_attributes(hash)
62
+
63
+ user
64
+ end
65
+
66
+ def self.from_remember_token(token)
67
+ first(:conditions => ["remember_token = ? AND remember_token_expires_at > ?", token, Time.now])
68
+ end
69
+
70
+ def assign_stocktwits_attributes(hash)
71
+ STOCKTWITS_FIELDS.each do |att|
72
+ send("#{att}=", hash[att.to_s]) if self.respond_to?("#{att}=")
73
+ end
74
+
75
+ STOCKTWITS_PROFILE_FIELDS.each do |att|
76
+ send("#{att}=", hash['profile'][att.to_s]) if self.respond_to?("#{att}=")
77
+ end
78
+ end
79
+
80
+ def update_stocktwits_attributes(hash)
81
+ assign_stocktwits_attributes(hash)
82
+ save
83
+ end
84
+
85
+ if Stocktwits.oauth?
86
+ include Stocktwits::OauthUser
87
+ elsif Stocktwits.basic?
88
+ include Stocktwits::BasicUser
89
+ else
90
+ include Stocktwits::PlainUser
91
+ end
92
+
93
+ def utilize_default_validations
94
+ true
95
+ end
96
+
97
+ def stocktwits
98
+ if Stocktwits.oauth?
99
+ Stocktwits::Dispatcher::Oauth.new(self)
100
+ elsif Stocktwits.basic?
101
+ Stocktwits::Dispatcher::Basic.new(self)
102
+ else
103
+ Stocktwits::Dispatcher::Plain.new(self)
104
+ end
105
+ end
106
+
107
+ def remember_me
108
+ return false unless respond_to?(:remember_token)
109
+
110
+ self.remember_token = ActiveSupport::SecureRandom.hex(10)
111
+ self.remember_token_expires_at = Time.now + Stocktwits.remember_for.days
112
+
113
+ save
114
+
115
+ {:value => self.remember_token, :expires => self.remember_token_expires_at}
116
+ end
117
+
118
+ def forget_me
119
+ self.remember_token = self.remember_token_expires_at = nil
120
+ self.save
121
+ end
122
+ end
123
+ end
@@ -0,0 +1,46 @@
1
+ module Stocktwits
2
+ module OauthUser
3
+ def self.included(base)
4
+ base.class_eval do
5
+ attr_protected :access_token, :access_secret
6
+ end
7
+
8
+ base.extend Stocktwits::OauthUser::ClassMethods
9
+ base.extend Stocktwits::Dispatcher::Shared
10
+ end
11
+
12
+ module ClassMethods
13
+ def identify_or_create_from_access_token(token, secret=nil)
14
+ raise ArgumentError, 'Must authenticate with an OAuth::AccessToken or the string access token and secret.' unless (token && secret) || token.is_a?(OAuth::AccessToken)
15
+
16
+ token = OAuth::AccessToken.new(Stocktwits.consumer, token, secret) unless token.is_a?(OAuth::AccessToken)
17
+
18
+ response = token.get(Stocktwits.path_prefix + '/account/verify_credentials.json')
19
+ user_info = handle_response(response)
20
+
21
+ if user = User.find_by_stocktwits_id(user_info['id'].to_s)
22
+ user.login = user_info['screen_name']
23
+ user.assign_stocktwits_attributes(user_info)
24
+ user.access_token = token.token
25
+ user.access_secret = token.secret
26
+ user.save
27
+ user
28
+ else
29
+ User.create_from_stocktwits_hash_and_token(user_info, token)
30
+ end
31
+ end
32
+
33
+ def create_from_stocktwits_hash_and_token(user_info, access_token)
34
+ user = User.new_from_stocktwits_hash(user_info)
35
+ user.access_token = access_token.token
36
+ user.access_secret = access_token.secret
37
+ user.save
38
+ user
39
+ end
40
+ end
41
+
42
+ def token
43
+ OAuth::AccessToken.new(Stocktwits.consumer, access_token, access_secret)
44
+ end
45
+ end
46
+ end