Class: Parse::User
- 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.signup(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.login(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
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
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
- #active_sessions ⇒ Array<Parse::Session>
A has_many relationship to all Session instances for this user.
- #auth_data ⇒ Hash
The auth data for this Parse::User.
- #email ⇒ String
Emails are optional in Parse, but if set, they must be unique.
- #session_token ⇒ String readonly
The session token if this user is logged in.
- #username ⇒ String
All Parse users have a username and must be globally unique.
Attributes inherited from Object
#acl, #created_at, #id, #updated_at
Attributes inherited from Pointer
Class Method Summary collapse
- .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.
- .create(body, **opts) ⇒ User
Creates a new Parse::User given a hash that maps to the fields defined in your Parse::User collection.
- .login(username, password) ⇒ User
Login and return a Parse::User with this username/password combination.
- .request_password_reset(email) ⇒ Boolean
Request a password reset for a registered email.
- .session(token, opts = {}) ⇒ User
Same as `session!` but returns nil if a user was not found or sesion token was invalid.
- .session!(token, opts = {}) ⇒ User
Return a Parse::User for this active session token.
- .signup(username, password, email = nil, body: {}) ⇒ Object
This method will signup a new user using the parameters below.
Instance Method Summary collapse
- #anonymous? ⇒ Boolean
True if this user is anonymous.
- #anonymous_id ⇒ String
Returns the anonymous identifier only if this user is anonymous.
- #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.
- #link_auth_data!(service_name, **data) ⇒ Object
Adds the third-party authentication data to for a given service.
- #logged_in? ⇒ Boolean
True if this user has a session token.
- #login!(passwd = nil) ⇒ Boolean
Login and get a session token for this user.
- #logout ⇒ Boolean
Invalid the current session token for this logged in user.
- #password=(value) ⇒ String
You may set a password for this user when you are creating them.
- #request_password_reset ⇒ Boolean
Request a password reset for this user.
- #session ⇒ Session
The session corresponding to the user's session token.
- #signup!(passwd = nil) ⇒ Boolean
You may set a password for this user when you are creating them.
- #unlink_auth_data!(service_name) ⇒ Boolean
Removes third-party authentication data for this user.
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
Methods included from Associations::HasMany
has_many, #relation_changes?, #relation_updates, #relations
Methods included from Associations::BelongsTo
Methods included from Associations::HasOne
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
Methods included from Client::Connectable
Constructor Details
This class inherits a constructor from Parse::Object
Instance Attribute Details
#active_sessions ⇒ Array<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.
182 | # File 'lib/parse/model/classes/user.rb', line 182 has_many :active_sessions, as: :session |
#auth_data ⇒ Hash
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.
156 | # File 'lib/parse/model/classes/user.rb', line 156 property :auth_data, :object |
#email ⇒ String
Emails are optional in Parse, but if set, they must be unique.
161 | # File 'lib/parse/model/classes/user.rb', line 161 property :email |
#session_token ⇒ String
Returns 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 |
#username ⇒ String
All Parse users have a username and must be globally unique.
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.
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.
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.
382 383 384 385 | # File 'lib/parse/model/classes/user.rb', line 382 def self.login(username, password) response = client.login(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.
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.
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.
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.
372 373 374 375 376 | # File 'lib/parse/model/classes/user.rb', line 372 def self.signup(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.
190 191 192 | # File 'lib/parse/model/classes/user.rb', line 190 def anonymous? anonymous_id.nil? end |
#anonymous_id ⇒ String
Returns the anonymous identifier only if this user is anonymous.
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.
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 |
#link_auth_data!(service_name, **data) ⇒ Object
Adds the third-party authentication data to for a given service.
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.
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.
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.login(username.to_s, password.to_s) apply_attributes! response.result self.session_token.present? end |
#logout ⇒ Boolean
Invalid the current session token for this logged in user.
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!)
169 | # File 'lib/parse/model/classes/user.rb', line 169 property :password |
#request_password_reset ⇒ Boolean
Request a password reset for this user
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 |
#session ⇒ Session
Returns 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
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 signup_attrs = attribute_updates signup_attrs.except! *Parse::Properties::BASE_FIELD_MAP.flatten # first signup the user, then save any additional attributes response = client.create_user signup_attrs 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 |
#unlink_auth_data!(service_name) ⇒ Boolean
Removes third-party authentication data for this user
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 |