iOS - Trigger Password Recovery Email from Drupal
Asked Answered
L

3

15

In my iOS app, I need my users to be able to recover/reset their passwords. I'm using the Drupal iOS SDK in order to manage user login. Everything works, however I'm trying to figure out how to post the user's email address to the services end point in order to trigger the drupal password recovery email? E.g. user inputs email into UITextField, and taps a submit button. However there doesn't seem to be any documentation for this?

Code is as follows - I'm just not sure what method I should put inside of my sendButton? DIOSUser? DIOSSession?

DIOSUser.m

 + (void)userSendPasswordRecoveryEmailWithEmailAddress: (NSString*)email

                                              success:(void (^)(AFHTTPRequestOperation *operation, id responseObject)) success
                                              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure {

   NSString *path = [NSString stringWithFormat:@"user/request_new_password/%@", email];
     NSLog(@"This is the input email %@", email);

    [[DIOSSession sharedSession] sendRequestWithPath:path method:@"POST" params:nil success:success failure:failure];
}

ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];

    self.forgotField.returnKeyType = UIReturnKeyDone;
    [self.forgotField setDelegate:self];

    // Do any additional setup after loading the view from its nib.

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:tap];
}

- (IBAction)return:(id)sender {

     [self dismissViewControllerAnimated:YES completion:nil];

}
- (IBAction)sendButton:(id)sender {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Retrieving Password"
                                                    message:@"We're helping you retrieve your password! Please check your email in a few minutes for a rescue link."
                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];

}

Error log:

2017-07-12 22:29:34.264669-0700 myApp[4523:1331335] 
----- DIOS Failure -----
Status code: 404
URL: http://url.com/endpoint01/user/request_new_password/[email protected]
----- Response ----- 

----- Error ----- 
Request failed: not found (404)
Lyndel answered 17/2, 2017 at 1:55 Comment(2)
Have you tried suggestion mentioned in drupal.stackexchange.com/questions/215281/…Anthropomorphosis
Please try my answer , belowMinimize
L
0

I ended up accomplishing this with the below code - posting incase anyone else finds it useful! Two slightly different alternatives depending on your database structure:

- (IBAction)sendButton:(id)sender {

    [[DIOSSession sharedSession] getCSRFTokenWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *csrfToken = [NSString stringWithUTF8String:[responseObject bytes]];

    NSString *email = self.forgotField.text;

    NSString *urlString2 = [NSString stringWithFormat:@"http://myapp.com/endpoint01/user/request_new_password?name=%@",
                        email];
    NSDictionary *jsonBodyDict = @{@"name":email};
    NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];


    NSMutableURLRequest *request = [NSMutableURLRequest new];
    request.HTTPMethod = @"POST";

    // for alternative 1:
    [request setURL:[NSURL URLWithString:urlString2]];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setHTTPBody:jsonBodyData];

    // for alternative 2:
    [request setURL:[NSURL URLWithString:urlString2]];
         [request addValue:csrfToken forHTTPHeaderField:@"X-CSRF-Token"];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config
                                                          delegate:nil
                                                     delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData * _Nullable data,
                                                                NSURLResponse * _Nullable response,
                                                                NSError * _Nullable error) {
                                                NSLog(@"Yay, done! Check for errors in response!");

                                                NSHTTPURLResponse *asHTTPResponse = (NSHTTPURLResponse *) response;
                                                NSLog(@"The response is: %@", asHTTPResponse);
                                                // set a breakpoint on the last NSLog and investigate the response in the debugger

                                                // if you get data, you can inspect that, too. If it's JSON, do one of these:
                                                NSDictionary *forJSONObject = [NSJSONSerialization JSONObjectWithData:data
                                                                                                              options:kNilOptions
                                                                                                                error:nil];
                                                // or
                                                NSArray *forJSONArray = [NSJSONSerialization JSONObjectWithData:data
                                                                                                        options:kNilOptions
                                                                                                          error:nil];   

                                            }];
    [task resume];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Retrieving Password"
                                                        message:@"We're helping you retrieve your password! Please check your email in a few minutes for a rescue link."
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];

    }
Lyndel answered 20/7, 2017 at 16:14 Comment(0)
I
5

You should simply do the following, assuming forgotField takes emailID as input and you have proper validation to check valid email.

- (IBAction)sendButton:(id)sender {

        [DIOSUser userSendPasswordRecoveryEmailWithEmailAddress:self.forgotField.text 
success:^(AFHTTPRequestOperation *operation, id responseObject) failure:^( AFHTTPRequestOperation *operation , NSError *error )){

         if(!error){
                  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Retrieving Password"
                                                        message:@"We're helping you retrieve your password! Please check your email in a few minutes for a rescue link."
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
               [alert show];
         }

    }];

 }

Find the documentation here

Cheers.

Instruct answered 15/3, 2017 at 12:4 Comment(6)
You're awesome - though when I implement the above, console throws me a "Request failed - not found 404 - url: mywebsite/myendpoint/resetpassword/enteredemailaddress" error. Any idea why this might be?Lyndel
@Lyndel Looks like the SDK you are using is obsolete, try waterwheelInstruct
Even so, all other methods for DIOSUser work? It's simply the url that isn't found in this instance? What should that path look like instead?Lyndel
Yes the URL endpoint not found, you can dig into the function of DIOSUser how they are making the api endpoint call and you can modify your calls accordingly.Instruct
This answer should be accepted, why you don't accept answers of your Questions , accepting your answer will help others who is facing the same problem , @Lyndel see your un accepted answer : 1. #30698734 2 .#44815245Minimize
@Minimize When I type an email address into the field and submit, I get the error: Request failed: not found (404) - see edit above (addition of DIOSUser.m, and error log). Also note, Waterwheel is Swift, not obj-c?Lyndel
M
0

You can send reset request using below code :

     - (IBAction)sendButton:(id)sender {

     [DIOSUser userSendPasswordRecoveryEmailWithEmailAddress:self.txtForgotPassword.text
                                                                    success:^(AFHTTPRequestOperation *operation, id responseObject) {
     // Success Block   
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Retrieving Password" message:@"We have send you reset link to your email Please check your email." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
      [alert show];


        }failure:^( AFHTTPRequestOperation *operation , NSError *error ){

     // Failure Block
              if(!error){
       // error.description 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oopss" message: error.description delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
      [alert show];

             }
              }];
    }

I hope this will help you .

Minimize answered 19/7, 2017 at 13:49 Comment(0)
L
0

I ended up accomplishing this with the below code - posting incase anyone else finds it useful! Two slightly different alternatives depending on your database structure:

- (IBAction)sendButton:(id)sender {

    [[DIOSSession sharedSession] getCSRFTokenWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *csrfToken = [NSString stringWithUTF8String:[responseObject bytes]];

    NSString *email = self.forgotField.text;

    NSString *urlString2 = [NSString stringWithFormat:@"http://myapp.com/endpoint01/user/request_new_password?name=%@",
                        email];
    NSDictionary *jsonBodyDict = @{@"name":email};
    NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];


    NSMutableURLRequest *request = [NSMutableURLRequest new];
    request.HTTPMethod = @"POST";

    // for alternative 1:
    [request setURL:[NSURL URLWithString:urlString2]];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setHTTPBody:jsonBodyData];

    // for alternative 2:
    [request setURL:[NSURL URLWithString:urlString2]];
         [request addValue:csrfToken forHTTPHeaderField:@"X-CSRF-Token"];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config
                                                          delegate:nil
                                                     delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData * _Nullable data,
                                                                NSURLResponse * _Nullable response,
                                                                NSError * _Nullable error) {
                                                NSLog(@"Yay, done! Check for errors in response!");

                                                NSHTTPURLResponse *asHTTPResponse = (NSHTTPURLResponse *) response;
                                                NSLog(@"The response is: %@", asHTTPResponse);
                                                // set a breakpoint on the last NSLog and investigate the response in the debugger

                                                // if you get data, you can inspect that, too. If it's JSON, do one of these:
                                                NSDictionary *forJSONObject = [NSJSONSerialization JSONObjectWithData:data
                                                                                                              options:kNilOptions
                                                                                                                error:nil];
                                                // or
                                                NSArray *forJSONArray = [NSJSONSerialization JSONObjectWithData:data
                                                                                                        options:kNilOptions
                                                                                                          error:nil];   

                                            }];
    [task resume];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Retrieving Password"
                                                        message:@"We're helping you retrieve your password! Please check your email in a few minutes for a rescue link."
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];

    }
Lyndel answered 20/7, 2017 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.