Class: Parse::User

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

Overview

The main class representing the _User table in Parse. A user can either be signed up or anonymous. All users need to have a username and a password, with email being optional but globally unique if set. You may add additional properties by redeclaring the class to match your specific schema.

The default schema for the User class is as follows:

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

   property :auth_data, :object
   property :username
   property :password
   property :email

   has_many :active_sessions, as: :session
end

Signup

You can signup new users in two ways. You can either use a class method User.signup to create a new user with the minimum fields of username, password and email, or create a User object can call the #signup! method. If signup fails, it will raise the corresponding exception.

user = Parse::User.(username, password, email)

#or
user = Parse::User.new username: "user", password: "s3cret"
user.signup!

Login/Logout

With the User class, you can also perform login and logout functionality. The class special accessors for #session_token and #session to manage its authentication state. This will allow you to authenticate users as well as perform Parse queries as a specific user using their session token. To login a user, use the User.login method by supplying the corresponding username and password, or if you already have a user record, use #login! with the proper password.

user = Parse::User.(username,password)
user.session_token # session token from a Parse::Session
user.session # Parse::Session tied to the token

# You can login user records
user = Parse::User.first
user.session_token # nil

passwd = 'p_n7!-e8' # corresponding password
user.login!(passwd) # true

user.session_token # 'r:pnktnjyb996sj4p156gjtp4im'

# logout to delete the session
user.logout

If you happen to already have a valid session token, you can use it to retrieve the corresponding Parse::User.

# finds user with session token
user = Parse::User.session(session_token)

user.logout # deletes the corresponding session

OAuth-Login

You can signup users using third-party services like Facebook and Twitter as described in Signing Up and Logging In. To do this with Parse-Stack, you can call the User.autologin_service method by passing the service name and the corresponding authentication hash data. For a listing of supported third-party authentication services, see OAuth.

fb_auth = {}
fb_auth[:id] = "123456789"
fb_auth[:access_token] = "SaMpLeAAiZBLR995wxBvSGNoTrEaL"
fb_auth[:expiration_date] = "2025-02-21T23:49:36.353Z"

# signup or login a user with this auth data.
user = Parse::User.autologin_service(:facebook, fb_auth)

You may also combine both approaches of signing up a new user with a third-party service and set additional custom fields. For this, use the method User.create.

# or to signup a user with additional data, but linked to Facebook
data = {
  username: "johnsmith",
  name: "John",
  email: "[email protected]",
  authData: { facebook: fb_auth }
}
user = Parse::User.create data

Linking/Unlinking

You can link or unlink user accounts with third-party services like Facebook and Twitter as described in: Linking and Unlinking Users. To do this, you must first get the corresponding authentication data for the specific service, and then apply it to the user using the linking and unlinking methods. Each method returns true or false if the action was successful. For a listing of supported third-party authentication services, see OAuth.

user = Parse::User.first

fb_auth = { ... } # Facebook auth data

# Link this user's Facebook account with Parse
user.link_auth_data! :facebook, fb_auth

# Unlinks this user's Facebook account from Parse
user.unlink_auth_data! :facebook

See Also:

Constant Summary

Constants included from Properties

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

Constants inherited from Pointer

Pointer::ATTRIBUTES

Constants inherited from Model

Model::CLASS_INSTALLATION, Model::CLASS_PRODUCT, Model::CLASS_ROLE, 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_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, #after_create, #after_destroy, #after_save, #apply_defaults!, #as_json, #before_create, #before_destroy, #before_save, build, #clear_attribute_change!, #clear_changes!, #existed?, #initialize, #new?, #parse_class, #persisted?, pointer, #pretty, #reload!, #rollback!, #schema, set_default_acl, #twin, #updates, #validate!, webhook, webhook_function

Methods included from Core::Querying

#all, #count, #distinct, #each, #find, #first, #literal_where, #newest, #oldest, #query, #scope

Methods included from Core::Schema

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

Methods included from Core::Actions

#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!

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 Properties

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

Methods inherited from Pointer

#==, #[], #[]=, #__type, #attributes, #className, #fetch, #fetched?, #hash, #initialize, #json_hash, #pointer, #pointer?, #present?, #sig

Methods inherited from Model

find_class

Methods included from Client::Connectable

#client

Constructor Details

This class inherits a constructor from Parse::Object

Instance Attribute Details

#active_sessionsArray<Parse::Session>

A has_many relationship to all Session instances for this user. This will query the _Session collection for all sessions which have this user in it's `user` column.

Returns:

Version:

  • 1.7.1



182
# File 'lib/parse/model/classes/user.rb', line 182

has_many :active_sessions, as: :session

#auth_dataHash

The auth data for this Parse::User. Depending on how this user is authenticated or logged in, the contents may be different, especially if you are using another third-party authentication mechanism like Facebook/Twitter.

Returns:

  • (Hash)

    Auth data hash object.



156
# File 'lib/parse/model/classes/user.rb', line 156

property :auth_data, :object

#emailString

Emails are optional in Parse, but if set, they must be unique.

Returns:

  • (String)

    The email field.



161
# File 'lib/parse/model/classes/user.rb', line 161

property :email

#session_tokenString

Returns The session token if this user is logged in.

Returns:

  • (String)

    The session token if this user is logged in.



149
150
151
# File 'lib/parse/model/classes/user.rb', line 149

def session_token
  @session_token
end

#usernameString

All Parse users have a username and must be globally unique.

Returns:

  • (String)

    The user's username.



174
# File 'lib/parse/model/classes/user.rb', line 174

property :username

Class Method Details

.autologin_service(service_name, auth_data, body: {}) ⇒ User

Automatically and implicitly signup a user if it did not already exists and authenticates them (login) using third-party authentication data. May raise exceptions similar to `create` depending on what you provide the body parameter.

Parameters:

  • service_name (Symbol)

    the name of the service key (ex. :facebook)

  • auth_data (Hash)

    the specific service data to place in the user's auth-data for this service.

  • body (Hash) (defaults to: {})

    any additional User related fields or properties when signing up this User record.

Returns:

  • (User)

    a logged in user, or nil.

See Also:



361
362
363
364
# File 'lib/parse/model/classes/user.rb', line 361

def self.autologin_service(service_name, auth_data, body: {})
  body = body.merge({ authData: { service_name => auth_data } })
  self.create(body)
end

.create(body, **opts) ⇒ User

Creates a new Parse::User given a hash that maps to the fields defined in your Parse::User collection.

Parameters:

  • body (Hash)

    The hash containing the Parse::User fields. The field `username` and `password` are required.

  • opts (Hash)

    a customizable set of options

Options Hash (**opts):

  • :master_key (Boolean)

    Whether the master key should be used for this request.

Returns:

  • (User)

    Returns a successfully created Parse::User.

Raises:



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/parse/model/classes/user.rb', line 333

def self.create(body, **opts)
  response = client.create_user(body, opts: opts)
  if response.success?
    body.delete :password # clear password before merging
    return Parse::User.build body.merge(response.result)
  end

  case response.code
  when Parse::Response::ERROR_USERNAME_MISSING
    raise Parse::Error::UsernameMissingError, response
  when Parse::Response::ERROR_PASSWORD_MISSING
    raise Parse::Error::PasswordMissingError, response
  when Parse::Response::ERROR_USERNAME_TAKEN
    raise Parse::Error::UsernameTakenError, response
  when Parse::Response::ERROR_EMAIL_TAKEN
    raise Parse::Error::EmailTakenError, response
  end
  raise Parse::Client::ResponseError, response
end

.login(username, password) ⇒ User

Login and return a Parse::User with this username/password combination.

Parameters:

  • username (String)

    the user's username

  • password (String)

    the user's password

Returns:

  • (User)

    a logged in user for the provided username. Returns nil otherwise.



382
383
384
385
# File 'lib/parse/model/classes/user.rb', line 382

def self.(username, password)
  response = client.(username.to_s, password.to_s)
  response.success? ? Parse::User.build(response.result) : nil
end

.request_password_reset(email) ⇒ Boolean

Request a password reset for a registered email.

Examples:

user = Parse::User.first

# pass a user object
Parse::User.request_password_reset user
# or email
Parse::User.request_password_reset("[email protected]")

Parameters:

  • email (String)

    The user's email address.

Returns:

  • (Boolean)

    True/false if successful.



397
398
399
400
401
402
# File 'lib/parse/model/classes/user.rb', line 397

def self.request_password_reset(email)
  email = email.email if email.is_a?(Parse::User)
  return false if email.blank?
  response = client.request_password_reset(email)
  response.success?
end

.session(token, opts = {}) ⇒ User

Same as `session!` but returns nil if a user was not found or sesion token was invalid.

Returns:

  • (User)

    the user matching this active token, otherwise nil.

See Also:

  • #session!


407
408
409
410
411
# File 'lib/parse/model/classes/user.rb', line 407

def self.session(token, opts = {})
  self.session! token, opts
rescue Parse::Error::InvalidSessionTokenError => e
  nil
end

.session!(token, opts = {}) ⇒ User

Return a Parse::User for this active session token.

Returns:

  • (User)

    the user matching this active token

Raises:

  • (InvalidSessionTokenError)

    Invalid session token.

See Also:



417
418
419
420
421
422
# File 'lib/parse/model/classes/user.rb', line 417

def self.session!(token, opts = {})
  # support Parse::Session objects
  token = token.session_token if token.respond_to?(:session_token)
  response = client.current_user(token, opts)
  response.success? ? Parse::User.build(response.result) : nil
end

.signup(username, password, email = nil, body: {}) ⇒ Object

This method will signup a new user using the parameters below. The required fields to create a user in Parse is the username and password fields. The email field is optional. Both username and email (if provided), must be unique. At a minimum, it is recommended you perform a query using the supplied username first to verify do not already have an account with that username. This method will raise all the exceptions from the similar `create` method.

See Also:



372
373
374
375
376
# File 'lib/parse/model/classes/user.rb', line 372

def self.(username, password, email = nil, body: {})
  body = body.merge({ username: username, password: password })
  body[:email] = email if email.present?
  self.create(body)
end

Instance Method Details

#anonymous?Boolean

Returns true if this user is anonymous.

Returns:

  • (Boolean)

    true if this user is anonymous.



190
191
192
# File 'lib/parse/model/classes/user.rb', line 190

def anonymous?
  anonymous_id.nil?
end

#anonymous_idString

Returns the anonymous identifier only if this user is anonymous.

Returns:

  • (String)

    The anonymous identifier for this anonymous user.

See Also:



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

def anonymous_id
  auth_data["anonymous"]["id"] if auth_data.present? && auth_data["anonymous"].is_a?(Hash)
end

#any_session!String

If the current session token for this instance is nil, this method finds the most recent active Parse::Session token for this user and applies it to the instance. The user instance will now be authenticated and logged in with the selected session token. Useful if you need to call save or destroy methods on behalf of a logged in user.

Returns:

  • (String)

    The session token or nil if no session was found for this user.



429
430
431
432
433
434
435
# File 'lib/parse/model/classes/user.rb', line 429

def any_session!
  unless @session_token.present?
    _active_session = active_sessions(restricted: false, order: :updated_at.desc).first
    self.session_token = _active_session.session_token if _active_session.present?
  end
  @session_token
end

Adds the third-party authentication data to for a given service.

Parameters:

  • service_name (Symbol)

    The name of the service (ex. :facebook)

  • data (Hash)

    The body of the OAuth data. Dependent on each service.

Raises:



205
206
207
208
209
# File 'lib/parse/model/classes/user.rb', line 205

def link_auth_data!(service_name, **data)
  response = client.set_service_auth_data(id, service_name, data)
  raise Parse::Client::ResponseError, response if response.error?
  apply_attributes!(response.result)
end

#logged_in?Boolean

Returns true if this user has a session token.

Returns:

  • (Boolean)

    true if this user has a session token.



230
231
232
# File 'lib/parse/model/classes/user.rb', line 230

def logged_in?
  self.session_token.present?
end

#login!(passwd = nil) ⇒ Boolean

Login and get a session token for this user.

Parameters:

  • passwd (String) (defaults to: nil)

    The password for this user.

Returns:

  • (Boolean)

    True/false if we received a valid session token.



290
291
292
293
294
295
# File 'lib/parse/model/classes/user.rb', line 290

def login!(passwd = nil)
  self.password = passwd || self.password
  response = client.(username.to_s, password.to_s)
  apply_attributes! response.result
  self.session_token.present?
end

#logoutBoolean

Invalid the current session token for this logged in user.

Returns:

  • (Boolean)

    True/false if successful



299
300
301
302
303
304
305
306
# File 'lib/parse/model/classes/user.rb', line 299

def logout
  return true if self.session_token.blank?
  client.logout session_token
  self.session_token = nil
  true
rescue => e
  false
end

#password=(value) ⇒ String

You may set a password for this user when you are creating them. Parse never returns a Parse::User's password when a record is fetched. Therefore, normally this getter is nil. While this API exists, it is recommended you use either the #login! or #signup! methods. (see #login!)

Returns:

  • (String)

    The password you set.



169
# File 'lib/parse/model/classes/user.rb', line 169

property :password

#request_password_resetBoolean

Request a password reset for this user

Returns:

  • (Boolean)

    true if it was successful requested. false otherwise.

See Also:



237
238
239
240
# File 'lib/parse/model/classes/user.rb', line 237

def request_password_reset
  return false if email.nil?
  Parse::User.request_password_reset(email)
end

#sessionSession

Returns the session corresponding to the user's session token.

Returns:

  • (Session)

    the session corresponding to the user's session token.



315
316
317
318
319
320
321
# File 'lib/parse/model/classes/user.rb', line 315

def session
  if @session.blank? && @session_token.present?
    response = client.fetch_session(@session_token)
    @session ||= Parse::Session.new(response.result)
  end
  @session
end

#signup!(passwd = nil) ⇒ Boolean

You may set a password for this user when you are creating them. Parse never returns a

Parameters:

  • passwd (defaults to: nil)

    The user's password to be used for signing up.

Returns:

  • (Boolean)

    True if signup it was successful. If it fails an exception is thrown.

Raises:



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/parse/model/classes/user.rb', line 251

def signup!(passwd = nil)
  self.password = passwd || password
  if username.blank?
    raise Parse::Error::UsernameMissingError, "Signup requires a username."
  end

  if password.blank?
    raise Parse::Error::PasswordMissingError, "Signup requires a password."
  end

   = attribute_updates
  .except! *Parse::Properties::BASE_FIELD_MAP.flatten

  # first signup the user, then save any additional attributes
  response = client.create_user 

  if response.success?
    apply_attributes! response.result
    return true
  end

  case response.code
  when Parse::Response::ERROR_USERNAME_MISSING
    raise Parse::Error::UsernameMissingError, response
  when Parse::Response::ERROR_PASSWORD_MISSING
    raise Parse::Error::PasswordMissingError, response
  when Parse::Response::ERROR_USERNAME_TAKEN
    raise Parse::Error::UsernameTakenError, response
  when Parse::Response::ERROR_EMAIL_TAKEN
    raise Parse::Error::EmailTakenError, response
  when Parse::Response::ERROR_EMAIL_INVALID
    raise Parse::Error::InvalidEmailAddress, response
  end
  raise Parse::Client::ResponseError, response
end

Removes third-party authentication data for this user

Parameters:

  • service_name (Symbol)

    The name of the third-party service (ex. :facebook)

Returns:

  • (Boolean)

    True/false if successful.

Raises:



215
216
217
218
219
# File 'lib/parse/model/classes/user.rb', line 215

def unlink_auth_data!(service_name)
  response = client.set_service_auth_data(id, service_name, nil)
  raise Parse::Client::ResponseError, response if response.error?
  apply_attributes!(response.result)
end