How to reset a password using parse api? - ios

I am using parse api as a service provider and data center so all my user information is stored in parse server and now i want to add a feature to my ios app for reseting a password but don't know how can i reset a password using parse api.
Can anyone help to know how can i use parse api to reset password of a user ?

PFUser.requestPasswordResetForEmailInBackground(emailTextField.text, block: { (succeeded: Bool, error: NSError?) -> Void in
if error == nil {
if succeeded { // SUCCESSFULLY SENT TO EMAIL
println("Reset email sent to your inbox");
}
else { // SOME PROBLEM OCCURED
}
}
else { //ERROR OCCURED, DISPLAY ERROR MESSAGE
println(error!.description);
}
});

Related

Getting Twitter profile info with Firebase Auth Swift

I'm trying to get basic details of a user signing into my app with their Twitter account. I am able to sign them in but not too sure where to go from here.
I'm pretty sure I need to use this get request but am unsure how to structure the request. Am also a little lost which token I include.
I haven't had much experience with the REST API as you could tell. I have Postman set up so if someone could point me in the right direction about accessing the data I could take it from there.
Thanks
#IBAction func twitterSignupPress() {
provider.getCredentialWith(nil) { credential, error in
if error != nil {
print("Error attempting to sign up using Twitter: \(error!)")
} else {
Auth.auth().signIn(with: credential!) { authResult, error in
if error != nil {
print("Error with Twitter signin")
} else {
print("Successful signin using Twitter")
let oAuthCredential = authResult?.credential as! OAuthCredential
print(oAuthCredential.accessToken!) // Prints token
print(oAuthCredential.idToken) // Prints nil
}
}
}
}
}
Was as simple as adding authResult?.additionalUserInfo?.profile

Re-using access token in Firebase 3

I have an iOS app that uses Firebase as a backend for authentication.
Once a user logs in and then closes the app, I don't want the user to have to re-enter their email and password. My approach is to save the access token after a successful login to the Keychain, and then when the user comes back to the app, use the token from the keychain to signin.
I've tried using the method FIRAuth.auth()?.signInWithCustomToken(customToken) { (user, error) in but that's not quite right as that's for when using custom tokens, which is not what I'm doing.
Is there a way for me to do this?
// login with email / password
FIRAuth.auth()?.signInWithEmail(email, password: password, completion: { (firebaseUser, error) in
if error == nil {
FIRAuth.auth()!.currentUser!.getTokenWithCompletion({ (token, error) in
if error == nil {
// save token to keychain
} else {
print(error)
}
})
} else {
print(error)
}
})
// user comes back to app
do {
// get saved token from keychain
if let myToken = try keychain.get("token") {
FIRAuth.auth()?.signInWithCustomToken(myToken, completion: { (user: FIRUser?, error: NSError?) in
if error == nil {
// show post login screen
} else {
}
})
}
} catch {
// error getting token from keychain
}
}
I was approaching this problem in the wrong way. Saving a token is appropriate when using a 3rd party authentication provider, like Facebook, Google, etc and getting an OAuth token in return from one of those services.
In my case when logging in using email and password, a token is not required and instead the password can be securely saved in the Keychain and used later for login.

How do I run a Cloud Code on Heroku?

With the Parse's announcement of their retirement, I have migrated my Parse Server onto Heroku. With my still neophyte knowledge of Heroku, I do not know if they have a similar function to that of Cloud Code, but I do know that a few months ago Parse Introduced a Heroku + Parse feature that allows you to run Cloud Code on any node.js environment, particularly Heroku.
My dilemma is, I have already migrated my server from parse to Heroku prior to learning about this feature :/ , so I cannot run any parse cloud code form my terminal because there is no existing server there anymore. So the question is, how can I emulate this following Cloud Code in Heroku & How do I adjust my swift?
Cloud Code:
// Use Parse.Cloud.define to define as many cloud functions as you want.
// For example:
Parse.Cloud.define("isLoginRedundant", function(request, response) {
Parse.Cloud.useMasterKey();
var sessionQuery = new Parse.Query(Parse.Session);
sessionQuery.equalTo("user", request.user);
sessionQuery.find().then(function(sessions) {
response.success( { isRedundant: sessions.length>1 } );
}, function(error) {
response.error(error);
});
});
and here is my swift back in xcode:
PFUser.logInWithUsernameInBackground(userName!, password: passWord!) {
(user, error) -> Void in
if (user != nil) {
// don't do the segue until we know it's unique login
// pass no params to the cloud in swift (not sure if [] is the way to say that)
PFCloud.callFunctionInBackground("isLoginRedundant", withParameters: [:]) {
(response: AnyObject?, error: NSError?) -> Void in
let dictionary = response as! [String:Bool]
var isRedundant : Bool
isRedundant = dictionary["isRedundant"]!
if (isRedundant) {
// I think you can adequately undo everything about the login by logging out
PFUser.logOutInBackgroundWithBlock() { (error: NSError?) -> Void in
// update the UI to say, login rejected because you're logged in elsewhere
// maybe do a segue here?
let redundantSession: String = "you are already logged in on another device"
self.failedMessage(redundantSession)
self.activityIND.stopAnimating()
self.loginSecond.userInteractionEnabled = true
}
} else {
// good login and non-redundant, do the segue
self.performSegueWithIdentifier("loginSuccess", sender: self)
}
}
} else {
// login failed for typical reasons, update the UI
dispatch_async(dispatch_get_main_queue()) {
self.activityIND.stopAnimating()
self.loginSecond.userInteractionEnabled = true
if let message = error?.userInfo["error"] as? String
where message == "invalid login parameters" {
let localizedMessage = NSLocalizedString(message, comment: "Something isn't right, check the username and password fields and try again")
print(localizedMessage)
self.failedMessage(localizedMessage)
}else if let secondMessage = error?.userInfo["error"] as? String
where secondMessage == "The Internet connection appears to be offline." {
self.failedMessage(secondMessage)
}
}
}
}
I would first checkout the example repo and read the parse-server documentation. Parse server supports cloud code out of the box and you simply specify which file contains your functions and triggers in the parse-server config. The link you posted with the integration between parse and heroku is not relevant for parse-server.

custom login for firebase in swift

I have to implement a chat platform using firebase and swift.
I know how to create a user using emailid :
firebase.createUser(emailTextField, password: passwordTextField.text) { (error:NSError!) -> Void in
if (error != nil){
print(error.localizedDescription)
self.displayMessage(error)
} else{
print("New user created")
self.requestUsername()
}
}
But I am not taking any email id or other accounts. I want to create a custom user. For that they have mentioned to use the secure JWT Token and then use this :
let ref = Firebase(url: "https://<YOUR-FIREBASE-APP>.firebaseio.com/")
ref.authWithCustomToken(AUTH_TOKEN, withCompletionBlock: { error, authData in
if error != nil {
println("Login failed! \(error)")
} else {
println("Login succeeded! \(authData)")
}
})
But they have not mentioned how to generate secure JWT Token in swift.
Anyone know?
Here is the link i referred:
How to login in firebase
As you probably noticed, there is no helper library from Firebase for minting custom tokens on iOS. There is however a set of instructions on how to mint tokens here: https://www.firebase.com/docs/ios/guide/login/custom.html#section-tokens-without-helpers
Minting tokens in a client-app is in general a VERY bad idea, since it requires that you have your Firebase's secret in your app, where any user can find it.

How to change PFUser password in Swift?

I've tried updating the same way you would update a PFUser's email and even tried converting obj-c code (from other questions); neither worked. I also have no idea how to use Cloud Code (well...I installed it but I don't know how to pass information into Cloud Code or how to use JavaScript). Is there a way to update a users password without having to send the reset email?
You can not change a user's password that way for security reasons. You have two choices
Password Reset Email
Cloud Code Function to Reset the Password
As I understand that you do not know JavaScript, here is a cloud code function that you can use to reset the user's password, as well as a way to call the function using Swift.
Function (in JavaScript):
Parse.Cloud.define("changeUserPassword", function(request, response) {
// Set up to modify user data
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("username", request.params.username); // find all the women
query.first({
success: function(myUser) {
// Successfully retrieved the object.
myUser.set("password", request.params.newPassword);
myUser.save(null, {
success: function(myUser) {
// The user was saved successfully.
response.success("Successfully updated user.");
},
error: function(myUser, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
response.error("Could not save changes to user.");
}
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
});
Swift code to call the above function:
PFCloud.callFunctionInBackground("changeUserPassword", withParameters: ["username" : "MyCoolUsername", "newPassword" : passwordField.text]) {
(result: AnyObject?, error: NSError?) -> Void in
if (error == nil) {
// result is "Successfully updated user."
}
}
Good luck!
Yes, password can be changed without Cloud Code and e-mail. After changing "password" field for current user session is reset, but you can restore it by calling PFUser.logInWithUsername again.
let currentUser = PFUser.current()
currentUser!.password = "<new_password>"
currentUser!.saveInBackground() { (successed, error) in
if successed {
PFUser.logInWithUsername(inBackground: currentUser!.email!, password: currentUser!.password!) { (user, error) in
// Your code here...
}
}
}

Resources