module SoundcloudAuth class GenericUser < ActiveRecord::Base attr_protected :soundcloud_id, :remember_token, :remember_token_expires_at SOUNDCLOUD_ATTRIBUTES = [ :plan, :avatar_url, :website_title, :permalink, :city, :uri, :country, :username, :discogs_name, :website, :full_name, :followers_count, :description, :permalink_url, :followings_count, :track_count, :myspace_name ] with_options :if => :utilize_default_validations do |v| v.validates_presence_of :soundcloud_id v.validates_uniqueness_of :soundcloud_id, :message => "ID has already been taken." v.validates_uniqueness_of :remember_token, :allow_blank => true end def self.table_name; 'users' end def self.new_from_soundcloud_hash(hash) raise ArgumentError, 'Invalid hash: must include id.' unless hash.key?('id') user = User.new user.soundcloud_id = hash['id'].to_s SOUNDCLOUD_ATTRIBUTES.each do |att| user.send("#{att}=", hash[att.to_s]) if user.respond_to?("#{att}=") end user end def self.from_remember_token(token) first(:conditions => ["remember_token = ? AND remember_token_expires_at > ?", token, Time.now]) end def assign_soundcloud_attributes(hash) SOUNDCLOUD_ATTRIBUTES.each do |att| send("#{att}=", hash[att.to_s]) if respond_to?("#{att}=") end end def update_soundcloud_attributes(hash) assign_soundcloud_attributes(hash) save end def self.identify_or_create_from_access_token(token, secret=nil) raise ArgumentError, 'Must authenticate with an OAuth::AccessToken or the string access token and secret.' unless (token && secret) || token.is_a?(OAuth::AccessToken) token = OAuth::AccessToken.new(SoundcloudAuth.consumer, token, secret) unless token.is_a?(OAuth::AccessToken) user_info = JSON.parse(token.get(SoundcloudAuth.path_prefix + '/me.json')) if user = User.find_by_soundcloud_id(user_info['id'].to_s) user.assign_soundcloud_attributes(user_info) user.access_token = token.token user.access_secret = token.secret user.save user else User.create_from_soundcloud_hash_and_token(user_info, token) end end def self.create_from_soundcloud_hash_and_token(user_info, access_token) user = User.new_from_soundcloud_hash(user_info) user.access_token = access_token.token user.access_secret = access_token.secret user.save user end def utilize_default_validations true end def soundcloud # OAuth::AccessToken.new(TwitterAuth.consumer, access_token, access_secret) end def remember_me return false unless respond_to?(:remember_token) self.remember_token = ActiveSupport::SecureRandom.hex(10) self.remember_token_expires_at = Time.now + SoundcloudAuth.remember_for.days save {:value => self.remember_token, :expires => self.remember_token_expires_at} end def forget_me self.remember_token = self.remember_token_expires_at = nil self.save end end end