Class: Parse::Session

Inherits:
Object show all
Defined in:
lib/parse/model/classes/session.rb,
lib/parse/stack/generators/templates/model_session.rb

Overview

This class represents the data and columns contained in the standard Parse ‘_Session` collection. The Session class maintains per-device (or website) authentication information for a particular user. Whenever a User object is logged in, a new Session record, with a session token is generated. You may use a known active session token to find the corresponding user for that session. Deleting a Session record (and session token), effectively logs out the user, when making Parse requests on behalf of the user using the session token.

The default schema for the Session class is as follows:

class Parse::Session < Parse::Object
   # See Parse::Object for inherited properties...

   property :session_token
   property :created_with, :object
   property :expires_at, :date
   property :installation_id
   property :restricted, :boolean

   belongs_to :user

   # Installation where the installation_id matches.
   has_one :installation, ->{ where(installation_id: i.installation_id) }, scope_only: true
end

See Also:

Constant Summary

Constants inherited from Object

Object::BUILTIN_PARSE_CLASS_NAMES, Object::IDENTIFICATION_FIELDS, Object::VALID_ACL_POLICIES

Constants included from Core::Schema

Core::Schema::DEFAULT_PUBLIC_CLP, Core::Schema::SCHEMA_READONLY_CLASSES

Constants included from Core::Describe

Core::Describe::ALL_SECTIONS, Core::Describe::CORE_FIELD_KEYS, Core::Describe::LOCAL_SECTIONS, Core::Describe::NETWORK_SECTIONS

Constants included from Core::Indexing

Core::Indexing::MAX_INDEXES_PER_COLLECTION, Core::Indexing::PARSE_MANAGED_ARRAY_FIELDS, Core::Indexing::SENSITIVE_FIELDS

Constants included from Core::SearchIndexing

Core::SearchIndexing::ALLOWED_INDEX_TYPES, Core::SearchIndexing::INDEX_NAME_PATTERN

Constants included from Core::Fetching

Core::Fetching::NON_SERIALIZABLE_IVARS

Constants included from Core::ParseReference

Core::ParseReference::OBJECT_ID_LENGTH, Core::ParseReference::SEPARATOR

Constants included from Core::FieldGuards

Core::FieldGuards::GUARD_MODES

Constants included from Properties

Properties::BASE, Properties::BASE_FIELD_MAP, Properties::BASE_KEYS, Properties::CORE_FIELDS, Properties::DELETE_OP, Properties::PROTECTED_INITIALIZE_KEYS, Properties::PROTECTED_MASS_ASSIGNMENT_KEYS, Properties::TYPES

Constants inherited from Pointer

Pointer::ATTRIBUTES, Pointer::OBJECT_ID_FORMAT

Constants inherited from Model

Model::CLASS_AUDIENCE, Model::CLASS_INSTALLATION, Model::CLASS_JOB_SCHEDULE, Model::CLASS_JOB_STATUS, Model::CLASS_PRODUCT, Model::CLASS_PUSH_STATUS, Model::CLASS_ROLE, Model::CLASS_SCHEMA, Model::CLASS_SESSION, Model::CLASS_USER, Model::ID, Model::KEY_CLASS_NAME, Model::KEY_CREATED_AT, Model::KEY_OBJECT_ID, Model::KEY_UPDATED_AT, Model::OBJECT_ID, Model::TYPE_ACL, Model::TYPE_BYTES, Model::TYPE_DATE, Model::TYPE_FIELD, Model::TYPE_FILE, Model::TYPE_GEOPOINT, Model::TYPE_NUMBER, Model::TYPE_OBJECT, Model::TYPE_POINTER, Model::TYPE_POLYGON, Model::TYPE_RELATION

Instance Attribute Summary collapse

Attributes inherited from Object

#acl, #created_at, #id, #updated_at

Attributes inherited from Pointer

#id, #parse_class

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Object

#[], #[]=, #__type, #_resolve_acl_owner_id, #_resolve_default_acl, #acl_changed?, acl_owner_field, acl_policy, acl_policy_setting, #acl_was, #acl_will_change!, #after_create, #after_destroy, #after_save, #after_update, #after_validation, #apply_defaults!, #around_create, #around_destroy, #around_save, #around_update, #around_validation, #as_json, #autofetch_disabled?, #before_create, #before_destroy, #before_save, #before_update, #before_validation, build, #changed, #changed?, class_permissions, #clear_attribute_change!, #clear_changes!, #clear_partial_fetch_state!, default_acls, describe_access, #disable_autofetch!, #enable_autofetch!, #existed?, fetch_clp, #fetched?, #fetched_keys, #fetched_keys=, #field_was_fetched?, #filter_for_user, filter_results_for_user, #fully_fetched?, #has?, #has_selective_keys?, #initialize, #keys, master_only_class!, #nested_fetched_keys, #nested_fetched_keys=, #nested_keys_for, #new?, #parse_class, #partially_fetched?, #persisted?, pointer, #pretty, private_acl!, protect_fields, #reload!, roles_for_user, #rollback!, #run_after_create_callbacks, #run_after_delete_callbacks, #run_after_save_callbacks, #schema, set_class_access, set_clp, set_default_acl, set_default_clp, set_read_user_fields, set_write_user_fields, #twin, unlistable_class!, update_clp!, #updates, #validate!, webhook, webhook_function

Methods included from Core::Querying

#all, #count, #count_distinct, #cursor, #distinct, #each, #find, #find_cached, #first, #last_updated, #latest, #literal_where, #newest, #oldest, #query, #scope, #subscribe

Methods included from Core::Schema

#_default_class_level_permissions_for_upgrade, #auto_upgrade!, #create_schema, #fetch_schema, #reset_clp!, #schema, #update_schema

Methods included from Core::Describe

#describe

Methods included from Core::Indexing

#apply_indexes!, #indexes_plan, #mongo_geo_index, #mongo_index, #mongo_index_declarations, #mongo_relation_index

Methods included from Core::SearchIndexing

#apply_search_indexes!, #mongo_search_index, #mongo_search_index_declarations, #search_indexes_plan

Methods included from Agent::MetadataDSL

#agent_description, #agent_methods, included, #property_descriptions, #property_enum_descriptions

Methods included from Core::Actions

#_deleted?, #change_requests, #changes_applied!, #changes_payload, #create, #destroy, #destroy_request, #op_add!, #op_add_relation!, #op_add_unique!, #op_destroy!, #op_increment!, #op_remove!, #op_remove_relation!, #operate_field!, #prepare_save!, #relation_change_operations, #save, #save!, #set_attributes!, #update, #update!, #update_relations, #uri_path

Methods included from Core::Fetching

#autofetch!, #fetch, #fetch!, #fetch_cache!, #fetch_json, #fetch_object, #prepare_for_dirty_tracking!

Methods included from Associations::HasMany

has_many, #relation_changes?, #relation_updates, #relations

Methods included from Associations::BelongsTo

belongs_to, #key?

Methods included from Associations::HasOne

has_one

Methods included from Core::ParseReference

format, generate_object_id, parse

Methods included from Core::FieldGuards

#apply_field_guards!

Methods included from Core::EnhancedChangeTracking

included

Methods included from Properties

#apply_attributes!, #attribute_changes?, #attribute_updates, #attributes, #attributes=, #field_map, #fields, #format_operation, #format_value

Methods inherited from Pointer

#==, #[], #[]=, #__type, #attributes, #className, #fetch, #fetch_cache!, #fetch_json, #fetch_object, #fetched?, #hash, #initialize, #json_hash, #method_missing, #pointer, #pointer?, #present?, #respond_to_missing?, #sig

Methods inherited from Model

#dirty?, find_class

Methods included from Client::Connectable

#client

Constructor Details

This class inherits a constructor from Parse::Object

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Parse::Pointer

Instance Attribute Details

#created_withHash

Returns data on how this Session was created.

Returns:

  • (Hash)

    data on how this Session was created.



36
# File 'lib/parse/model/classes/session.rb', line 36

property :created_with, :object

#expires_atParse::Date

Returns when the session token expires.

Returns:



40
# File 'lib/parse/model/classes/session.rb', line 40

property :expires_at, :date

#installationParse::Installation (readonly)

Returns the Installation where the sessions installation_id field matches the installation_id field in the Installation collection. This is implemented as a has_one scope.

Returns:

Version:

  • 1.7.1



66
# File 'lib/parse/model/classes/session.rb', line 66

has_one :installation, -> { where(installation_id: i.installation_id) }, scope_only: true

#installation_idString

Returns The installation id from the Installation table.

Returns:

  • (String)

    The installation id from the Installation table.

See Also:



45
# File 'lib/parse/model/classes/session.rb', line 45

property :installation_id

#restrictedBoolean (readonly)

Returns whether this session token is restricted.

Returns:

  • (Boolean)

    whether this session token is restricted.



49
# File 'lib/parse/model/classes/session.rb', line 49

property :restricted, :boolean

#session_tokenString (readonly)

Returns the session token for this installation and user pair.

Returns:

  • (String)

    the session token for this installation and user pair.



53
# File 'lib/parse/model/classes/session.rb', line 53

property :session_token

#userUser (readonly)

This property is mapped as a ‘belongs_to` association with the User class. Every session instance is tied to a specific logged in user.

Returns:

  • (User)

    the user corresponding to this session.

See Also:



59
# File 'lib/parse/model/classes/session.rb', line 59

belongs_to :user

Class Method Details

.activeParse::Query

Query scope for active (non-expired) sessions.

Examples:

active_sessions = Parse::Session.active.all

Returns:

  • (Parse::Query)

    a query for sessions that haven’t expired



95
96
97
# File 'lib/parse/model/classes/session.rb', line 95

def active
  query(:expires_at.gte => Time.now)
end

.active_count_for_user(user) ⇒ Integer

Count active sessions for a specific user.

Examples:

count = Parse::Session.active_count_for_user(user)

Parameters:

Returns:

  • (Integer)

    count of active sessions



140
141
142
# File 'lib/parse/model/classes/session.rb', line 140

def active_count_for_user(user)
  for_user(user).where(:expires_at.gte => Time.now).count
end

.expiredParse::Query

Query scope for expired sessions.

Examples:

expired_sessions = Parse::Session.expired.all

Returns:



103
104
105
# File 'lib/parse/model/classes/session.rb', line 103

def expired
  query(:expires_at.lt => Time.now)
end

.for_user(user) ⇒ Parse::Query

Query scope for sessions belonging to a specific user.

Examples:

user_sessions = Parse::Session.for_user(user).all

Parameters:

Returns:



112
113
114
115
# File 'lib/parse/model/classes/session.rb', line 112

def for_user(user)
  user = Parse::User.pointer(user) if user.is_a?(String)
  query(user: user)
end

.revoke_all_for_user(user, except: nil) ⇒ Integer

Revoke (delete) all sessions for a specific user.

Examples:

# Revoke all sessions for a user
Parse::Session.revoke_all_for_user(user)

# Revoke all except current session
Parse::Session.revoke_all_for_user(user, except: current_session_token)

Parameters:

Returns:

  • (Integer)

    the number of sessions revoked



127
128
129
130
131
132
133
# File 'lib/parse/model/classes/session.rb', line 127

def revoke_all_for_user(user, except: nil)
  sessions = for_user(user)
  sessions = sessions.where(:session_token.ne => except) if except
  sessions_to_revoke = sessions.all
  sessions_to_revoke.each(&:destroy)
  sessions_to_revoke.count
end

.session(token, **opts) ⇒ Session

Return the Session record for this session token.

Parameters:

  • token (String)

    the session token

  • opts (Hash)

    additional keyword options forwarded to the underlying client request (e.g. cache: false, use_master_key: false, headers:).

Returns:

  • (Session)

    the session for this token, otherwise nil.



79
80
81
82
83
84
85
86
87
88
89
# File 'lib/parse/model/classes/session.rb', line 79

def session(token, **opts)
  # A stray :session_token in opts would be forwarded into the request
  # stack and silently override the positional token argument. Drop it
  # so the explicit token always wins.
  opts.delete(:session_token)
  response = client.fetch_session(token, **opts)
  if response.success?
    return Parse::Session.build response.result
  end
  nil
end

Instance Method Details

#expired?Boolean

Check if this session has expired.

Examples:

if session.expired?
  puts "Session has expired"
end

Returns:

  • (Boolean)

    true if the session has expired



155
156
157
158
# File 'lib/parse/model/classes/session.rb', line 155

def expired?
  return false if expires_at.nil?
  expires_at < Time.now
end

#expires_within?(duration) ⇒ Boolean

Check if this session expires within the given duration.

Examples:

if session.expires_within?(1.hour)
  puts "Session expires soon!"
end

Parameters:

  • duration (Integer)

    number of seconds

Returns:

  • (Boolean)

    true if session expires within the duration



188
189
190
191
# File 'lib/parse/model/classes/session.rb', line 188

def expires_within?(duration)
  return false if expires_at.nil?
  expires_at < (Time.now + duration)
end

#revoke!Boolean

Revoke (delete) this session, effectively logging out the user on this device.

Examples:

session.revoke!

Returns:

  • (Boolean)

    true if successfully revoked



197
198
199
# File 'lib/parse/model/classes/session.rb', line 197

def revoke!
  destroy
end

#time_remainingFloat?

Get the remaining time until this session expires.

Examples:

remaining = session.time_remaining
puts "Session expires in #{remaining / 3600} hours" if remaining

Returns:

  • (Float, nil)

    seconds remaining until expiration, nil if no expiration, 0 if already expired



175
176
177
178
179
# File 'lib/parse/model/classes/session.rb', line 175

def time_remaining
  return nil if expires_at.nil?
  remaining = expires_at.to_time - Time.now
  remaining > 0 ? remaining : 0
end

#valid?Boolean

Check if this session is still valid (not expired).

Examples:

if session.valid?
  puts "Session is still active"
end

Returns:

  • (Boolean)

    true if the session is still valid



166
167
168
# File 'lib/parse/model/classes/session.rb', line 166

def valid?
  !expired?
end