Guest User

Untitled

a guest
May 26th, 2018
372
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.33 KB | None | 0 0
  1. ## payment_card.rb
  2.  
  3. class PaymentCard < ActiveRecord::Base
  4. class CIMPaymentProfileCreationError < StandardError; end
  5. include SharedGateway
  6. include ActiveMerchant::RequiresParameters
  7.  
  8. belongs_to :user
  9.  
  10. attr_accessor :full_number, :cvs
  11.  
  12. VALID_MONTHS = (1..12).collect{|m| [m, m]}
  13. VALID_YEARS = (Time.now.year..Time.now.year + 10).collect{|y| [y, y]}
  14. VALID_CARD_TYPES = %w(visa mastercard discover).collect{|c| [c.capitalize, c]}
  15.  
  16.  
  17. validates_presence_of :first_name, :last_name
  18. validates_presence_of :full_number, :on => :create
  19.  
  20. after_save :deactivate_other_payment_cards
  21. after_create :create_payment_profile_id
  22. after_create :process_card
  23.  
  24. def full_number_before_typecast
  25. self.full_number
  26. end
  27.  
  28. def self.create_or_activate_payment_card(user, params)
  29. # If we have an existing card, activate it and return it
  30. logger.debug {"message here #{:number}"}
  31. existing_card = PaymentCard.find(:first, :conditions => {:user_id => user.id,
  32. :month => params[:month], :year => params[:year], :number => params[:full_number].to_s.last(4)
  33. })
  34. existing_card.activate! and return existing_card if existing_card
  35. else
  36. # Otherwise, create one and generate the CIM payment profile id for it
  37. new_card = user.payment_cards.build(params)
  38. begin
  39. new_card.save
  40. rescue CIMPaymentProfileCreationError => e
  41. Rails.logger.error e
  42. new_card.errors.add_to_base("Credit card is invalid.")
  43. end
  44. new_card
  45. end
  46.  
  47. def activate!
  48. self.is_active = true
  49. self.save
  50. end
  51.  
  52. private
  53. def deactivate_other_payment_cards
  54. if self.is_active == true
  55. self.user.payment_cards.reject{|c| c.id == self.id}.each do |card|
  56. card.update_attribute(:is_active, false)
  57. end
  58. end
  59. end
  60.  
  61. def create_payment_profile_id
  62. # More magical dwarven knowledge here
  63.  
  64. card = CreditCard.new(:year => self.year, :month => self.month, :number => self.full_number)
  65. profile = {
  66. :customer_type => 'individual', # Optional
  67. :payment => { :credit_card => card }
  68. }
  69. response = gateway.create_customer_payment_profile(:customer_profile_id => self.user.customer_profile_id, :payment_profile => profile)
  70. self.customer_payment_profile_id = response.params['customer_payment_profile_id']
  71. raise CIMPaymentProfileCreationError, "could not create a customer payment profile id for user #{self.inspect}" unless self.customer_payment_profile_id
  72. end
  73.  
  74. def process_card
  75. if payment_card.valid?
  76.  
  77. # Create a gateway object to the TrustCommerce service
  78. gateway = ActiveMerchant::Billing::AuthorizeNetCimGateway.new(
  79. :login => 'TestMerchant',
  80. :password => 'password'
  81. )
  82.  
  83. # Authorize for $10 dollars (1000 cents)
  84. response = gateway.authorize(:amount, credit_card)
  85.  
  86. if response.success?
  87.  
  88. # Capture the money
  89. gateway.capture(:amount, response.authorization)
  90. else
  91. raise StandardError, response.message
  92. end
  93. end
  94. end
  95. end
  96. #
  97. # def set_new_payment_information(info)
  98. # requires!(info, :expiration_month, :expiration_year, :card_number)
  99. #
  100. # # if we have a matching card already, activate it and return true
  101. # existing_card = self.payment_cards.find(:first,
  102. # :conditions => {
  103. # :shadowed_card_number => shadow(info[:card_number]),
  104. # :expiration_year => info[:expiration_year].to_i,
  105. # :expiration_month => info[:expiration_month].to_i
  106. # })
  107. #
  108. # existing_card.activate! and return true if existing_card
  109. #
  110. # # else update remote payment_profile
  111. # card = CreditCard.new(:year => info[:expiration_year], :month => info[:expiration_month], :number => info[:card_number])
  112. # profile = {
  113. # :customer_type => 'individual', # Optional
  114. # :payment => {
  115. # :credit_card => card
  116. # }
  117. # }
  118. # response = gateway.create_customer_payment_profile(:customer_profile_id => self.customer_profile_id, :payment_profile => profile)
  119. # require 'pp'
  120. # pp response
  121. # new_customer_payment_profile_id = response.params['customer_payment_profile_id']
  122. # # return false if we couldn't create the remote payment profile
  123. #
  124. # Merb.logger.error("Could not create remote profile for billing_profile: #{self.inspect}") and return false unless new_customer_payment_profile_id
  125. #
  126. # shadowed_card = shadow(info[:card_number])
  127. # payment_card = self.payment_cards.build(:customer_payment_profile_id => new_customer_payment_profile_id,
  128. # :shadowed_card_number => shadowed_card,
  129. # :expiration_month => info[:expiration_month],
  130. # :expiration_year => info[:expiration_year])
  131. # # return false if we had an issue saving this payment card
  132. # unless payment_card.save
  133. # self.errors.add_to_base("Could not save the new payment card.")
  134. # return false
  135. # end
  136. #
  137. #
  138. # # create new payment_card, set payment_profile_id, set to active - this is now handled by acts as state machine
  139. # # loop through payment_cards, setting inactive - this is now handled by acts as state machine
  140. # payment_card.activate!
  141. # true
  142. # end
  143.  
  144. ## user.rb
  145.  
  146. require 'digest/sha1'
  147. require 'Teroformed'
  148. class User < ActiveRecord::Base
  149. RANDOM_LIMIT = 1000
  150. include SharedGateway
  151. class CIMProfileCreationError < StandardError; end
  152. # Virtual attribute for the unencrypted password
  153. attr_accessor :password
  154.  
  155. validate :generate_unique_cim_key
  156.  
  157. validates_presence_of :login
  158. validates_presence_of :email
  159. validates_presence_of :password, :if => :password_required?
  160. validates_presence_of :password_confirmation, :if => :password_required?
  161. validates_length_of :password, :within => 4..40, :if => :password_required?
  162. validates_confirmation_of :password, :if => :password_required?
  163. validates_presence_of :first_name, :last_name
  164. validates_length_of :login, :within => 3..40
  165. validates_length_of :email, :within => 3..100
  166. validates_uniqueness_of :login, :case_sensitive => false
  167. validates_format_of :email, :with => /(^([^@\s]+)@((?:[-_a-z0-9]+\.)+[a-z]{2,})$)|(^$)/i
  168.  
  169. has_many :permissions
  170. has_many :roles, :through => :permissions
  171. belongs_to :sponsor,
  172. :class_name => "User",
  173. :foreign_key => "sponsor_id"
  174. has_many :sponsored,
  175. :class_name => "User",
  176. :foreign_key => "sponsor_id",
  177. :order => "created_at"
  178. has_many :subscriptions
  179. has_many :payment_cards
  180.  
  181. before_save :encrypt_password
  182. before_create :make_activation_code
  183.  
  184. before_create :set_sponsor_code
  185. after_create :create_tero_user
  186. after_update :update_tero_user
  187.  
  188. after_create :persist_to_authorize_net
  189.  
  190. # prevents a user from submitting a crafted form that bypasses activation
  191. # anything else you want your user to change should be added here.
  192. attr_accessible :login, :email, :password, :password_confirmation, :first_name, :last_name, :sponsor_code, :code_used, :company_name, :title, :website_address, :address_one, :address_two, :city, :state, :zip_code, :tel_num, :alt_tel_num, :fax_num, :ip_address
  193.  
  194. class ActivationCodeNotFound < StandardError; end
  195. class AlreadyActivated < StandardError
  196. attr_reader :user, :message;
  197. def initialize(user, message=nil)
  198. @message, @user = message, user
  199. end
  200. end
  201.  
  202. # Finds the user with the corresponding activation code, activates their account and returns the user.
  203. #
  204. # Raises:
  205. # +User::ActivationCodeNotFound+ if there is no user with the corresponding activation code
  206. # +User::AlreadyActivated+ if the user with the corresponding activation code has already activated their account
  207. def self.find_and_activate!(activation_code)
  208. raise ArgumentError if activation_code.nil?
  209. user = find_by_activation_code(activation_code)
  210. raise ActivationCodeNotFound if !user
  211. raise AlreadyActivated.new(user) if user.active?
  212. user.send(:activate!)
  213. user
  214. end
  215.  
  216. def active?
  217. # the presence of an activation date means they have activated
  218. !activated_at.nil?
  219. end
  220.  
  221. # Returns true if the user has just been activated.
  222. def pending?
  223. @activated
  224. end
  225.  
  226. # Authenticates a user by their login name and unencrypted password. Returns the user or nil.
  227. # Updated 2/20/08
  228. def self.authenticate(login, password)
  229. u = find :first, :conditions => ['login = ?', login] # need to get the salt
  230. u && u.authenticated?(password) ? u : nil
  231. end
  232.  
  233. # Encrypts some data with the salt.
  234. def self.encrypt(password, salt)
  235. Digest::SHA1.hexdigest("–#{salt}–#{password}–")
  236. end
  237.  
  238. # Encrypts the password with the user salt
  239. def encrypt(password)
  240. self.class.encrypt(password, salt)
  241. end
  242.  
  243. def authenticated?(password)
  244. crypted_password == encrypt(password)
  245. end
  246.  
  247. def remember_token?
  248. remember_token_expires_at && Time.now.utc < remember_token_expires_at
  249. end
  250.  
  251. # These create and unset the fields required for remembering users between browser closes
  252. def remember_me
  253. remember_me_for 2.weeks
  254. end
  255.  
  256. def remember_me_for(time)
  257. remember_me_until time.from_now.utc
  258. end
  259.  
  260. def remember_me_until(time)
  261. self.remember_token_expires_at = time
  262. self.remember_token = encrypt("#{email}–#{remember_token_expires_at}")
  263. save(false)
  264. end
  265.  
  266. def forget_me
  267. self.remember_token_expires_at = nil
  268. self.remember_token = nil
  269. save(false)
  270. end
  271.  
  272. def forgot_password
  273. @forgotten_password = true
  274. self.make_password_reset_code
  275. end
  276.  
  277. def reset_password
  278. # First update the password_reset_code before setting the
  279. # reset_password flag to avoid duplicate email notifications.
  280. update_attribute(:password_reset_code, nil)
  281. @reset_password = true
  282. end
  283.  
  284. # used in user_observer
  285. def recently_forgot_password?
  286. @forgotten_password
  287. end
  288.  
  289. def recently_reset_password?
  290. @reset_password
  291. end
  292.  
  293. def self.find_for_forget(email)
  294. find :first, :conditions => ['email = ? and activated_at IS NOT NULL', email]
  295. end
  296.  
  297. def has_role?(rolename)
  298. self.roles.find_by_rolename(rolename) ? true : false
  299. end
  300.  
  301. def code_used=(code)
  302. self.sponsor = User.find_by_sponsor_code(code)
  303. write_attribute(:code_used, code)
  304. end
  305.  
  306. def track_referrals
  307. @track_referrals ||= User.find_all_by_code_used(sponsor_code)
  308. end
  309.  
  310. def second_level_referrals
  311. @second_level ||= self.track_referrals.map {|refs| refs.track_referrals}.flatten!
  312. end
  313.  
  314. def full_name
  315. "#{last_name}, #{first_name}"
  316. end
  317.  
  318. def create_or_set_payment_card(params)
  319. PaymentCard.create_or_activate_payment_card(self, params)
  320. end
  321.  
  322. protected
  323.  
  324. # before filter
  325. def encrypt_password
  326. return if password.blank?
  327. self.salt = Digest::SHA1.hexdigest("–#{Time.now.to_s}–#{login}–") if new_record?
  328. self.crypted_password = encrypt(password)
  329. end
  330.  
  331. def password_required?
  332. crypted_password.blank? || !password.blank?
  333. end
  334.  
  335. def make_activation_code
  336. self.activation_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )
  337. end
  338.  
  339. def make_password_reset_code
  340. self.password_reset_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )
  341. end
  342.  
  343. private
  344.  
  345. def create_tero_user
  346. tero = Teroformed.new
  347. logger.info tero.add_user(:username => self.login, :new_password => self.password, :firstname => self.first_name, :lastname => self.last_name, :keyword_num => '1')
  348. end
  349.  
  350. def update_tero_user
  351. tero = Teroformed.new
  352. logger.info tero.update_user(:username => self.login, :new_password => self.password, :firstname => self.first_name, :lastname => self.last_name, :keyword_num => '1')
  353. end
  354.  
  355. def persist_to_authorize_net
  356. response = gateway.create_customer_profile({:profile =>{:merchant_customer_id => self.cim_key}})
  357. if response.authorization
  358. self.customer_profile_id = response.authorization
  359. self.save
  360. else
  361. Rails.logger.error response.message
  362. raise CIMProfileCreationError, "could not create CIM profile"
  363. end
  364. end
  365.  
  366. def generate_unique_cim_key
  367. return true if self.cim_key?
  368. prefix = AppConfig.cim_prefix
  369. while true do
  370. digest = Digest::SHA1.hexdigest("--#{Time.now}--#{rand(RANDOM_LIMIT)}--").last(5)
  371. time = Time.now.to_i
  372. potential_key = "#{prefix}_#{digest}_#{time}"
  373. potential_dup = User.find_by_cim_key(potential_key)
  374. if potential_dup
  375. return true if potential_dup.id == self.id
  376. else
  377. self.cim_key = potential_key
  378. break
  379. end
  380. end
  381. true
  382. end
  383.  
  384. def activate!
  385. @activated = true
  386. self.update_attribute(:activated_at, Time.now.utc)
  387. end
  388.  
  389. def set_sponsor_code
  390. loop do
  391. self.sponsor_code = generate_sponsor_code
  392. break if sponsor_code_is_unique?
  393. end
  394. end
  395.  
  396. def generate_sponsor_code
  397. rand(99999000) + 1000
  398. end
  399.  
  400. def sponsor_code_is_unique?
  401. !User.find_by_sponsor_code(sponsor_code)
  402. end
  403. end
Add Comment
Please, Sign In to add comment