AnsweredAssumed Answered

Password reset using php and resfull services

Question asked by michaelc on Apr 8, 2011
I thought I would toss this out here as an example.
it's not the best, I am new with this product.
it's based on Gery Wright of Zaizi article
http://zaizi.wordpress.com/2009/03/11/adding-password-reset-feature-to-alfresco-share-login/

But I did it in PHP and then made a restfull call.
I did it this way because it's just me and I need to produce as much as possible with the least amount of resources.


To slingshot-login.ftl I added a button and the following JS code.

   YAHOO.util.Event.addListener(button1, "click", resetPassword);
   function resetPassword(e)
   {
       var userName = document.getElementById("username");
       if (userName.value > " " ) {
       Alfresco.util.Ajax.request(
            {
               url: "/services/Reset.php",
               method: "POST",
               requestContentType: "application/json",
               responseContentType: "application/json",
               dataObj:
                   { "user" : userName.value  },
            failureCallback:
         {  // error was returned
               fn: function(response) {
                  Alfresco.util.PopupManager.displayMessage(
                  {
                     text: response.json.message
                  });                 
                  
               },
               scope: this            
          },
            successCallback:
         {
               fn: function(response) {
                 messageTitle = "Password Reset";
                 Alfresco.util.PopupManager.displayPrompt(
               {
                  title: Alfresco.util.message(messageTitle),
                  text: Alfresco.util.message(response.json.message),
                  buttons: [
                     {
                        text: Alfresco.util.message("button.ok"),
                        handler: function error_onOk()
                        {
                           this.destroy();
                           YAHOO.util.Dom.get("username").focus();
                           YAHOO.util.Dom.get("username").select();
                        },
                           isDefault: true
                     }]      
                  });
                  },
                  scope: this            
         }                           
         });               
       }else{
         Alfresco.util.PopupManager.displayPrompt(
         {
            title: Alfresco.util.message(messageTitle),
            text: Alfresco.util.message("message.required"),
            buttons: [
            {
               text: Alfresco.util.message("button.ok"),
               handler: function error_onOk()
               {
                  this.destroy();
                  YAHOO.util.Dom.get("username").focus();
                  YAHOO.util.Dom.get("username").select();
               },
               isDefault: true
            }]      
         });
      } 
   }

this called the backend code that would reset the password and send an email

<?php
//————————————————————————//
//  $Id:                                                                  $
//  Module: Reset
//  Description:   Controller Module for the Reset password Process
//  This will Call a restful service to reset the  user password to the system
//  Author: Michael C Ford
//  Create data : March 2011
//———————————————————————–/
// Check request user exists
// make password call
// send email
// Return result
//
header('Content-type: application/json');
error_reporting(E_ERROR | E_PARSE);
require_once('Utility.php');
require_once 'RESTclient.php';
require_once('EmailSubmit.php');
   
   $cesrlog->debug('Begin reset');
   $responce = "{success: false}";
    $userUrlPassword = $_SERVER['SERVER_NAME']."/alfresco/service/api/person/changepassword/";
    $userUrlGet      = $_SERVER['SERVER_NAME']."/alfresco/service/api/people/";
    $action         = "POST";
    $contextType    = "application/json";
    $data = file_get_contents("php://input");
    $jsonData = json_decode($data);
   
    $userUrlGet = $userUrlGet . $jsonData->user;
    $userUrlPassword = $userUrlPassword . $jsonData->user;
    $cesrlog->debug('URL '.$userUrlGet);  
   $inputs = array();
    $request = RestClient::get(
              $userUrlGet,
              $inputs,
              $accessUser,
              $accessPassword);
    // user exists change there password
    if ($request->getResponseCode() == '200' ) {
         //  allowed e-mails
         $userObj =  json_decode($request->getResponse());
        if (!$userObj->enabled){
            die ('{"success" : "false" , "message" : "User is disabled and can not have a password change"}');
         }
         if ($userObj->skype == "unsubscribe"){
            die ('{"success" : "false" , "message" : "User is unsubscribed and can not receive email"}');
         }
         //  valid e-mail address  any value is assumed to be valid at this point.
        if (!$userObj->email > " "){
            die ('{"success" : "false" , "message" : "User can not receive email no email address on file"}');
         }
         // Now change the users password
         $newPassword = createPassword();
         $inputs = '{"newpw":"'. $newPassword .'"}';
       $request = RestClient::post(
                  $userUrlPassword,
                    $inputs,
                    $accessUser,
                    $accessPassword);   

       if ($request->getResponseCode() == '200' ) {
          $responseObj =  json_decode($request->getResponse());
          if ($responseObj->success){

             $emailObj = new EmailSubmit();
             $emailObj->setSubject('CESR confidential email');
             $emailObj->setMessage(createEmail( $userObj,$newPassword,$_SERVER['SERVER_NAME']));
             $emailObj->setTo($userObj->email);
             if ($emailObj->send()){
                print '{"success" : "true" , "message" : "Password has been sent to your email"}';
             }else{
                print '{"success" : "false" , "message" : "Email falure, please contact cesr.support@kp.org"}';
             }
          }else{
              print '{"success" : "false" , "message" : "Password could not be changed"}';
          }
       }          
   }else{
        $response = json_decode($request->getResponse());
        print '{"success" : "false" , "message" : "' .  $response->message . '"}';
   }
//          Build the email body
function createEmail( $userObj,$password, $server) {
   Logger::$log->debug("reset:createEmail(" . json_encode($userObj) . ", " . $password .")");
   $messageBody = "Greetings " . $userObj->firstName . " " . $userObj->lastName . " \n";
   $messageBody = $messageBody . "   You have just requested a password reset or your account has been activated.\n";
   $messageBody = $messageBody . "   Your user id for the CESR website is " . $userObj->userName . "\n";   
   $messageBody = $messageBody . "   with the password of " . $password . "\n\n";
   $messageBody = $messageBody . "   you may change this password by clicking this link http://" . $server . "/share/page/user/A447738/ \n";   
   $messageBody = $messageBody . "     and entering the password you would prefer.   \n\n";
   $messageBody = $messageBody . "   if you have any problems or questions please contact cesr.support@kp.org\n\n       Regards,\n  CESR Website Team";   
   return $messageBody;
}
//          Generate a password for the user
function createPassword() {
   Logger::$log->debug("reset:createPassword()");

    $chars = "abc!@#$%defghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;

    while ($i <= 8) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }
    Logger::$log->debug("return " . $pass);
    return $pass;


Outcomes