lib/volt/volt/users.rb in volt-0.8.22.beta2 vs lib/volt/volt/users.rb in volt-0.8.22
- old
+ new
@@ -1,18 +1,80 @@
module Volt
+ class << self
+ # Get the user_id from the cookie
+ def user_id
+ user_id_signature = self.user_id_signature
- # Login the user, return a promise for success
- def self.login(username, password)
- UserTasks.login(username, password).then do |result|
+ if user_id_signature.nil?
+ return nil
+ else
+ index = user_id_signature.index(':')
+ user_id = user_id_signature[0...index]
- # Assign the user_id cookie for the user
- $page.cookies._user_id = result
+ if RUBY_PLATFORM != 'opal'
+ hash = user_id_signature[(index+1)..-1]
- # Pass nil back
- nil
+ # Make sure the user hash matches
+ if BCrypt::Password.new(hash) != "#{Volt.config.app_secret}::#{user._id}"
+ # user id has been tampered with, reject
+ raise "user id or hash has been tampered with"
+ end
+
+ end
+
+ return user_id
+ end
end
- end
- def self.logout
- $page.cookies.delete(:user_id)
+ # True if the user is logged in and the user is loaded
+ def user?
+ !!user
+ end
+
+ # Return the current user.
+ def user
+ user_id = self.user_id
+ if user_id
+ return $page.store._users.find_one(_id: user_id)
+ else
+ return nil
+ end
+ end
+
+ # Login the user, return a promise for success
+ def login(username, password)
+ UserTasks.login(username, password).then do |result|
+
+ # Assign the user_id cookie for the user
+ $page.cookies._user_id = result
+
+ # Pass nil back
+ nil
+ end
+ end
+
+ def logout
+ $page.cookies.delete(:user_id)
+ end
+
+
+ private
+
+ # Fetches the user_id+signature from the correct spot depending on client
+ # or server, does not verify it.
+ def user_id_signature
+ if Volt.client?
+ user_id_signature = $page.cookies._user_id
+ else
+ # Check meta for the user id and validate it
+ meta_data = Thread.current['meta']
+ if meta_data
+ user_id_signature = meta_data['user_id']
+ else
+ user_id_signature = nil
+ end
+ end
+
+ user_id_signature
+ end
end
end
\ No newline at end of file