Ejemplo n.º 1
0
 public function doApprove()
 {
     $exist = Member::get()->filter(array('Email' => $this->Email))->first();
     if ($exist) {
         return false;
     }
     $member = new Member();
     $data = $this->toMap();
     unset($data['ID']);
     unset($data['ClassName']);
     unset($data['UnapprovedMember']);
     $member->update($data);
     $member->write();
     if ($this->MemberType === 'Organization') {
         $member->addToGroupByCode('organization');
         $organization = new Organization();
         $organization->AccountID = $member->ID;
         $organization->company_name = $this->OrganizationName;
         $organizationID = $organization->write();
         $member->OrganizationID = $organizationID;
         $member->write();
     } else {
         $member->addToGroupByCode('personal');
     }
     $this->setField('Approved', true);
     $this->write();
     return true;
 }
Ejemplo n.º 2
0
 function testDefaultPasswordEncryptionDoesntChangeExistingMembers()
 {
     $member = new Member();
     $member->Password = '******';
     $member->PasswordEncryption = 'sha1_v2.4';
     $member->write();
     $origAlgo = Security::get_password_encryption_algorithm();
     Security::set_password_encryption_algorithm('none');
     $member->Password = '******';
     $member->write();
     $this->assertEquals($member->PasswordEncryption, 'sha1_v2.4');
     $result = $member->checkPassword('mynewpassword');
     $this->assertTrue($result->valid());
     Security::set_password_encryption_algorithm($origAlgo);
 }
 /**
  * If the REMOTE_USER is set and is in the Member table, log that member in. If
  * not, and Config::inst()->get('AuthRemoteUserExtension', 'auto_create_user') is set, add that
  * Member to the configured group, and log the new user in. Otherwise, do nothing.
  */
 public function onAfterInit()
 {
     if (isset($_SERVER['REMOTE_USER'])) {
         $unique_identifier = $_SERVER['REMOTE_USER'];
     } elseif (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
         $unique_identifier = $_SERVER['REDIRECT_REMOTE_USER'];
     }
     if (isset($unique_identifier)) {
         $unique_identifier_field = Member::config()->unique_identifier_field;
         $member = Member::get()->filter($unique_identifier_field, $unique_identifier)->first();
         if ($member) {
             $member->logIn();
             $this->owner->redirectBack();
         } elseif (Config::inst()->get('AuthRemoteUserExtension', 'auto_create_user') && strlen(Config::inst()->get('AuthRemoteUserExtension', 'auto_user_group'))) {
             $group = Group::get()->filter('Title', Config::inst()->get('AuthRemoteUserExtension', 'auto_user_group'))->first();
             if ($group) {
                 $member = new Member();
                 $member->{$unique_identifier_field} = $unique_identifier;
                 $member->write();
                 $member->Groups()->add($group);
                 $member->logIn();
             }
         }
     }
 }
 /**
  * creates and logs in a temporary user.
  *
  */
 private function createAndLoginUser()
 {
     $this->username = "******";
     $this->password = rand(1000000000, 9999999999);
     //Make temporary admin member
     $adminMember = Member::get()->filter(array("Email" => $this->username))->first();
     if ($adminMember != NULL) {
         $adminMember->delete();
     }
     $this->member = new Member();
     $this->member->Email = $this->username;
     $this->member->Password = $this->password;
     $this->member->write();
     $adminGroup = Group::get()->filter(array("code" => "administrators"))->first();
     if (!$adminGroup) {
         user_error("No admin group exists");
     }
     $this->member->Groups()->add($adminGroup);
     curl_setopt($this->ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
     $loginUrl = Director::absoluteURL('/Security/LoginForm');
     curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "POST");
     curl_setopt($this->ch, CURLOPT_URL, $loginUrl);
     curl_setopt($this->ch, CURLOPT_POST, 1);
     curl_setopt($this->ch, CURLOPT_POSTFIELDS, 'Email=' . $this->username . '&Password='******'color:red'>There was an error logging in!</span><br />";
     }
 }
 /**
  * Performs the login, but will also create and sync the Member record on-the-fly, if not found.
  *
  * @param array $data
  * @param Form $form
  * @return bool|Member|void
  * @throws SS_HTTPResponse_Exception
  */
 public static function authenticate($data, Form $form = null)
 {
     $service = Injector::inst()->get('LDAPService');
     $result = $service->authenticate($data['Username'], $data['Password']);
     $success = $result['success'] === true;
     if (!$success) {
         if ($form) {
             $form->sessionMessage($result['message'], 'bad');
         }
         return;
     }
     $data = $service->getUserByUsername($result['identity']);
     if (!$data) {
         if ($form) {
             $form->sessionMessage(_t('LDAPAuthenticator.PROBLEMFINDINGDATA', 'There was a problem retrieving your user data'), 'bad');
         }
         return;
     }
     // LDAPMemberExtension::memberLoggedIn() will update any other AD attributes mapped to Member fields
     $member = Member::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
     if (!($member && $member->exists())) {
         $member = new Member();
         $member->GUID = $data['objectguid'];
         $member->write();
     }
     Session::clear('BackURL');
     return $member;
 }
 public function finish($data, $form)
 {
     parent::finish($data, $form);
     $steps = DataObject::get('MultiFormStep', "SessionID = {$this->session->ID}");
     if ($steps) {
         foreach ($steps as $step) {
             if ($step->class == 'Page2PersonalDetailsFormStep') {
                 $member = new Member();
                 $data = $step->loadData();
                 if ($data) {
                     $member->update($data);
                     $member->write();
                 }
             }
             if ($step->class == 'Page2OrganisationDetailsFormStep') {
                 $organisation = new Organisation();
                 $data = $step->loadData();
                 if ($data) {
                     $organisation->update($data);
                     if ($member && $member->ID) {
                         $organisation->MemberID = $member->ID;
                     }
                     $organisation->write();
                 }
             }
             // Debug::show($step->loadData()); // Shows the step data (unserialized by loadData)
         }
     }
     $controller = $this->getController();
     $controller->redirect($controller->Link() . 'finished');
 }
 /**
  * Test that a member can be authenticated via their temp id
  */
 public function testAuthenticateByTempID()
 {
     $member = new Member();
     $member->Email = '*****@*****.**';
     $member->PasswordEncryption = "sha1";
     $member->Password = "******";
     $member->write();
     // Make form
     $controller = new Security();
     $form = new Form($controller, 'Form', new FieldList(), new FieldList());
     // If the user has never logged in, then the tempid should be empty
     $tempID = $member->TempIDHash;
     $this->assertEmpty($tempID);
     // If the user logs in then they have a temp id
     $member->logIn(true);
     $tempID = $member->TempIDHash;
     $this->assertNotEmpty($tempID);
     // Test correct login
     $result = MemberAuthenticator::authenticate(array('tempid' => $tempID, 'Password' => 'mypassword'), $form);
     $this->assertNotEmpty($result);
     $this->assertEquals($result->ID, $member->ID);
     $this->assertEmpty($form->Message());
     // Test incorrect login
     $form->clearMessage();
     $result = MemberAuthenticator::authenticate(array('tempid' => $tempID, 'Password' => 'notmypassword'), $form);
     $this->assertEmpty($result);
     $this->assertEquals('The provided details don&#039;t seem to be correct. Please try again.', $form->Message());
     $this->assertEquals('bad', $form->MessageType());
 }
 function doSave($data, $form)
 {
     if (isset($data['Password']) && is_array($data['Password'])) {
         $data['Password'] = $data['Password']['_Password'];
     }
     // We need to ensure that the unique field is never overwritten
     $uniqueField = Member::get_unique_identifier_field();
     if (isset($data[$uniqueField])) {
         $SQL_unique = Convert::raw2sql($data[$uniqueField]);
         $existingUniqueMember = Member::get()->filter(array($uniqueField => $SQL_unique))->first();
         if ($existingUniqueMember && $existingUniqueMember->exists()) {
             if (Member::currentUserID() != $existingUniqueMember->ID) {
                 die("current member does not match enrolled member.");
                 return false;
             }
         }
     }
     $member = Member::currentUser();
     if (!$member) {
         $member = new Member();
     }
     $member->update($data);
     $member->write();
     $arrayExtraFields = array();
     if (isset($data["SelectedOption"])) {
         $arrayExtraFields["SelectedOption"] = $data["SelectedOption"];
     }
     if (isset($data["BookingCode"])) {
         $arrayExtraFields["BookingCode"] = $data["BookingCode"];
     }
     $this->controller->addAttendee($member, $arrayExtraFields);
     $this->redirect($this->getController()->Link("thankyou"));
     return;
 }
 private function createUser()
 {
     // create user
     $u = new Member();
     $u->write();
     $s = new \Ntb\SocialIdentity(['UserID' => 'foo_user', 'AuthService' => 'facebook', 'MemberID' => $u->ID]);
     $s->write();
 }
 /**
  * Assertion Consumer Service
  *
  * The user gets sent back here after authenticating with the IdP, off-site.
  * The earlier redirection to the IdP can be found in the SAMLAuthenticator::authenticate.
  *
  * After this handler completes, we end up with a rudimentary Member record (which will be created on-the-fly
  * if not existent), with the user already logged in. Login triggers memberLoggedIn hooks, which allows
  * LDAP side of this module to finish off loading Member data.
  *
  * @throws OneLogin_Saml2_Error
  */
 public function acs()
 {
     $auth = Injector::inst()->get('SAMLHelper')->getSAMLAuth();
     $auth->processResponse();
     $error = $auth->getLastErrorReason();
     if (!empty($error)) {
         SS_Log::log($error, SS_Log::ERR);
         Form::messageForForm("SAMLLoginForm_LoginForm", "Authentication error: '{$error}'", 'bad');
         Session::save();
         return $this->getRedirect();
     }
     if (!$auth->isAuthenticated()) {
         Form::messageForForm("SAMLLoginForm_LoginForm", _t('Member.ERRORWRONGCRED'), 'bad');
         Session::save();
         return $this->getRedirect();
     }
     $decodedNameId = base64_decode($auth->getNameId());
     // check that the NameID is a binary string (which signals that it is a guid
     if (ctype_print($decodedNameId)) {
         Form::messageForForm("SAMLLoginForm_LoginForm", "Name ID provided by IdP is not a binary GUID.", 'bad');
         Session::save();
         return $this->getRedirect();
     }
     // transform the NameId to guid
     $guid = LDAPUtil::bin_to_str_guid($decodedNameId);
     if (!LDAPUtil::validGuid($guid)) {
         $errorMessage = "Not a valid GUID '{$guid}' recieved from server.";
         SS_Log::log($errorMessage, SS_Log::ERR);
         Form::messageForForm("SAMLLoginForm_LoginForm", $errorMessage, 'bad');
         Session::save();
         return $this->getRedirect();
     }
     // Write a rudimentary member with basic fields on every login, so that we at least have something
     // if LDAP synchronisation fails.
     $member = Member::get()->filter('GUID', $guid)->limit(1)->first();
     if (!($member && $member->exists())) {
         $member = new Member();
         $member->GUID = $guid;
     }
     $attributes = $auth->getAttributes();
     foreach ($member->config()->claims_field_mappings as $claim => $field) {
         if (!isset($attributes[$claim][0])) {
             SS_Log::log(sprintf('Claim rule \'%s\' configured in LDAPMember.claims_field_mappings, but wasn\'t passed through. Please check IdP claim rules.', $claim), SS_Log::WARN);
             continue;
         }
         $member->{$field} = $attributes[$claim][0];
     }
     $member->SAMLSessionIndex = $auth->getSessionIndex();
     // This will throw an exception if there are two distinct GUIDs with the same email address.
     // We are happy with a raw 500 here at this stage.
     $member->write();
     // This will trigger LDAP update through LDAPMemberExtension::memberLoggedIn.
     // Both SAML and LDAP identify Members by the GUID field.
     $member->logIn();
     return $this->getRedirect();
 }
 public function testDeletesOpauthIdentityOnDelete()
 {
     $member = new Member(array('Email' => '*****@*****.**'));
     $member->write();
     $identity = new OpauthIdentity();
     $identity->write();
     $member->OpauthIdentities()->add($identity);
     $member->delete();
     $this->assertEquals(0, $member->OpauthIdentities()->Count());
 }
 protected function createMember()
 {
     $email = $this->getValidEmailInput();
     if ($email !== false) {
         $member = new Member(['Email' => $email, 'Password' => $this->getPasswordFromInputOrEmail($email), 'FirstName' => $this->getFirstNameFromInputOrEmail($email), 'Surname' => $this->getLastNameInput()]);
         $member->write();
         return $member;
     }
     return false;
 }
 function requireDefaultRecords()
 {
     $hasTestMembers = DataObject::get('Member')->find('Email', '*****@*****.**');
     if (!$hasTestMembers) {
         foreach ($this->data() as $name) {
             $member = new Member(array('FirstName' => $name, 'FirstName' => 'Smith', 'Email' => "{$name}@test.com"));
             $member->write();
         }
         DB::alteration_message("Added default records to Member table", "created");
     }
 }
Ejemplo n.º 14
0
 public function testCMSAccess()
 {
     $members = Member::get()->byIDs($this->allFixtureIDs('Member'));
     foreach ($members as $member) {
         $this->assertTrue(Permission::checkMember($member, 'CMS_ACCESS'));
     }
     $member = new Member();
     $member->update(array('FirstName' => 'No CMS', 'Surname' => 'Access', 'Email' => '*****@*****.**'));
     $member->write();
     $this->assertFalse(Permission::checkMember($member, 'CMS_ACCESS'));
 }
 public function testFindOrCreateMemberOverwriteExistingFields()
 {
     $member = new Member(array('Email' => '*****@*****.**', 'FirstName' => 'Existing', 'Surname' => 'Existing'));
     $member->write();
     $identity = OpauthIdentity::factory(array('auth' => array('provider' => 'Facebook', 'uid' => 999, 'info' => array('email' => '*****@*****.**', 'first_name' => 'New', 'last_name' => 'New'))));
     $member = $identity->findOrCreateMember(array('overwriteExistingFields' => false));
     $this->assertEquals('Existing', $member->FirstName, 'Does not overwrite unless requested');
     $identity = OpauthIdentity::factory(array('auth' => array('provider' => 'Facebook', 'uid' => 999, 'info' => array('email' => '*****@*****.**', 'first_name' => 'New', 'last_name' => 'New'))));
     $member = $identity->findOrCreateMember(array('overwriteExistingFields' => array('FirstName')));
     $this->assertEquals('New', $member->FirstName, 'Overwrites existing fields if requested');
     $this->assertEquals('Existing', $member->Surname, 'Does not overwrite fields if not present in whitelist');
 }
 function activate($data, $form, $request)
 {
     //Check if there's a temp member with a Verification Code equal to this
     //if there is, register the new member and log him in
     //if not, tell him the code is wrong
     //Check if this member already exists
     $tempMember = TempMember::codeExists($data);
     if (!$tempMember) {
         $form->sessionMessage(_t("Register.REGISTRATION ERROR", "There's no account waiting for activation with this code.\n\t\t\t\t\t\t\t\t\t If you already have an account log in here <a href=\"my-events/\">here</a>"), 'bad');
         Director::redirectBack();
         return;
     }
     // Create a new Member object
     $member = new Member();
     $member->FirstName = $tempMember->FirstName;
     $member->Surname = $tempMember->Surname;
     $member->Phone = $tempMember->Phone;
     $member->Email = $tempMember->Email;
     $member->Password = $tempMember->Password;
     $member->ReceiveMail = $tempMember->ReceiveMail;
     $member->ReceiveMail = $tempMember->ReceiveMail;
     $member->RequestListedAsPresenter = $tempMember->RequestListedAsPresenter;
     $member->LocationAddress = $tempMember->LocationAddress;
     $member->LocationLatitude = $tempMember->LocationLatitude;
     $member->LocationLongitude = $tempMember->LocationLongitude;
     $member->Description = $tempMember->Description;
     // Write to db.
     // This needs to happen before we add it to a group
     $member->write();
     if ($tempMember->RequestListedAsPresenter) {
         $presentorApproval = new PresentorApproval();
         $presentorApproval->MemberID = $member->ID;
         $presentorApproval->MemberName = $tempMember->FirstName . ' ' . $tempMember->Surname;
         $presentorApproval->Message = $tempMember->Description;
         $presentorApproval->Email = $tempMember->Email;
         $presentorApproval->Confirmation = 'Pending';
         $presentorApproval->IsDone = false;
         $presentorApproval->write();
     }
     $tempMember->delete();
     $member->logIn();
     // Add the member to User Group
     // Check if it exists first
     if ($group = DataObject::get_one('Group', 'ID = 3')) {
         $member->Groups()->add($group);
         // Redirect based on URL
         // TO EDIT
         Director::redirect('SuccessVerification');
     } else {
         $form->sessionMessage(_t("Register.REGISTRATION ERROR", "Your registration wasn't successful please try again"), 'bad');
         Director::redirectBack();
     }
 }
 /**
  * Copy user details from vBulletin to SilverStripe member
  */
 function createNewUser($bbUserID)
 {
     $tablePrefix = self::$table_prefix ? self::$table_prefix . '_' : '';
     $SQL_userID = (int) $_COOKIE['bbuserid'];
     $userInfo = DB::query("SELECT * FROM {$tablePrefix}user WHERE userid = {$SQL_userID}")->record();
     $m = new Member();
     $m->VBulletinUserID = $userInfo['userid'];
     $m->VBulletinUsername = $userInfo['username'];
     $m->FirstName = $userInfo['username'];
     $m->Email = $userInfo['email'];
     $m->write();
     return $m;
 }
 function testRun()
 {
     $m = new Member();
     $m->Password = '******';
     $m->PasswordEncryption = 'none';
     $m->write();
     $t = new EncryptAllPasswordsTask();
     $t->run(null);
     $m = DataObject::get_by_id('Member', $m->ID);
     $this->assertEquals($m->PasswordEncryption, 'sha1_v2.4');
     $this->assertNotEquals($m->Password, 'plain');
     $result = $m->checkPassword('plain');
     $this->assertTrue($result->valid());
 }
 /**
  * Adds or modifies a job on the website.
  *
  * @param array $data
  * @param Form $form
  */
 public function doJobForm()
 {
     $data = $this->request->postVars();
     $form = new JobBoardForm($this);
     $form->loadDataFrom($data);
     $existed = false;
     if (!isset($data['JobID']) && !$data['JobID']) {
         $job = new Job();
     } else {
         $job = Job::get()->byId($data['JobID']);
         $existed = true;
         if ($job && !$job->canEdit()) {
             return $this->owner->httpError(404);
         } else {
             $job = new Job();
         }
     }
     $form->saveInto($job);
     $job->isActive = true;
     $job->write();
     Session::set('JobID', $job->ID);
     $member = Member::get()->filter(array('Email' => $data['Email']))->first();
     if (!$member) {
         $member = new Member();
         $member->Email = $SQL_email;
         $member->FirstName = isset($data['Company']) ? $data['Company'] : false;
         $password = Member::create_new_password();
         $member->Password = $password;
         $member->write();
         $member->addToGroupByCode('job-posters', _t('Jobboard.JOBPOSTERSGROUP', 'Job Posters'));
     }
     $member->logIn();
     $job->MemberID = $member->ID;
     $job->write();
     if (!$existed) {
         $email = new Email();
         $email->setSubject($data['EmailSubject']);
         $email->setFrom($data['EmailFrom']);
         $email->setTo($member->Email);
         // send the welcome email.
         $email->setTemplate('JobPosting');
         $email->populateTemplate(array('Member' => $member, 'Password' => isset($password) ? $password : false, 'FirstPost' => $password ? true : false, 'Holder' => $this, 'Job' => $job));
         if ($notify = $form->getController()->getJobNotifyAddress()) {
             $email->setBcc($notify);
         }
         $email->send();
     }
     return $this->redirect($data['BackURL']);
 }
 /**
  * Provide custom Silverstripe authentication logic for a SimpleSAMLphp authentication source
  * to authenticate a user
  */
 public function authenticate()
 {
     $attributes = $this->getAttributes();
     $email = $attributes["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"][0];
     $member = Member::get()->filter('Email', $email)->first();
     //If the member does not exist in Silverstripe, create them
     if (!$member) {
         $member = new Member();
         $member->Username = $attributes["http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname"][0];
         $member->FirstName = $attributes["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"][0];
         $member->Surname = $attributes["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"][0];
         $member->Email = $attributes["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"][0];
         $member->write();
     }
     return $member;
 }
 /**
  * Provide custom Silverstripe authentication logic for a SimpleSAMLphp authentication source
  * to authenticate a user
  */
 public function authenticate()
 {
     $attributes = $this->getAttributes();
     $email = $attributes['mail'][0];
     $member = Member::get()->filter('Email', $email)->first();
     //If the member does not exist in Silverstripe, create them
     if (!$member) {
         $member = new Member();
         $member->Username = $attributes['sAMAccountName'][0];
         $member->FirstName = $attributes['givenName'][0];
         $member->Surname = $attributes['sn'][0];
         $member->Email = $attributes['mail'][0];
         $member->write();
     }
     return $member;
 }
 public function testNoLegacyPasswordHashMigrationOnIncompatibleAlgorithm()
 {
     Config::inst()->update('PasswordEncryptor', 'encryptors', array('crc32' => array('PasswordEncryptor_PHPHash' => 'crc32')));
     $field = Member::config()->unique_identifier_field;
     $member = new Member();
     $member->{$field} = '*****@*****.**';
     $member->PasswordEncryption = "crc32";
     $member->Password = "******";
     $member->write();
     $data = array('Email' => $member->{$field}, 'Password' => 'mypassword');
     MemberAuthenticator::authenticate($data);
     $member = DataObject::get_by_id('Member', $member->ID);
     $this->assertEquals($member->PasswordEncryption, "crc32");
     $result = $member->checkPassword('mypassword');
     $this->assertTrue($result->valid());
 }
 function testOverwriteExistingImport()
 {
     $author1 = new Member();
     $author1->FirstName = 'author1_first_old';
     $author1->Email = '*****@*****.**';
     $author1->write();
     $loader = new MemberCsvBulkLoader();
     $results = $loader->load('sapphire/tests/security/MemberCsvBulkLoaderTest.csv');
     $created = $results->Created()->toArray();
     $this->assertEquals(count($created), 1);
     $updated = $results->Updated()->toArray();
     $this->assertEquals(count($updated), 1);
     $this->assertEquals($created[0]->Email, '*****@*****.**');
     $this->assertEquals($updated[0]->Email, '*****@*****.**');
     $this->assertEquals($updated[0]->FirstName, 'author1_first');
 }
 public function testHashHidden()
 {
     $field = new ConfirmedPasswordField('Password', 'Password', 'valueA');
     $field->setCanBeEmpty(true);
     $this->assertEquals('valueA', $field->Value());
     $this->assertEquals('valueA', $field->children->fieldByName($field->getName() . '[_Password]')->Value());
     $this->assertEquals('valueA', $field->children->fieldByName($field->getName() . '[_ConfirmPassword]')->Value());
     $member = new Member();
     $member->Password = "******";
     $member->write();
     $form = new Form($this, 'Form', new FieldList($field), new FieldList());
     $form->loadDataFrom($member);
     $this->assertEquals('', $field->Value());
     $this->assertEquals('', $field->children->fieldByName($field->getName() . '[_Password]')->Value());
     $this->assertEquals('', $field->children->fieldByName($field->getName() . '[_ConfirmPassword]')->Value());
 }
 public function testOverwriteExistingImport()
 {
     $author1 = new Member();
     $author1->FirstName = 'author1_first_old';
     $author1->Email = '*****@*****.**';
     $author1->write();
     $loader = new MemberCsvBulkLoader();
     $results = $loader->load($this->getCurrentRelativePath() . '/MemberCsvBulkLoaderTest.csv');
     $created = $results->Created()->toArray();
     $this->assertEquals(count($created), 1);
     $updated = $results->Updated()->toArray();
     $this->assertEquals(count($updated), 1);
     $this->assertEquals($created[0]->Email, '*****@*****.**');
     $this->assertEquals($updated[0]->Email, '*****@*****.**');
     $this->assertEquals($updated[0]->FirstName, 'author1_first');
 }
Ejemplo n.º 26
0
 public function AddMember($results)
 {
     //set up new member
     $member = new Member();
     $member->FirstName = Convert::raw2sql($results->name->first);
     $member->Surname = Convert::raw2sql($results->name->last);
     $member->Email = Convert::raw2sql($results->email);
     $member->Gender = Convert::raw2sql($results->gender);
     $member->Address = Convert::raw2sql($this->GetAddress($results));
     $member->Username = Convert::raw2sql($results->username);
     $member->Phone = Convert::raw2sql($results->phone);
     $member->Cell = Convert::raw2sql($results->cell);
     $member->ProfilePic = Convert::raw2sql($results->picture->thumbnail);
     $member->changePassword($results->password);
     $member->write();
     return $this->Success($results);
 }
 public function go($request)
 {
     // Only accept if it's an ajax request
     if ($this->request->isAjax()) {
         $mobilenumber = Convert::raw2sql($_POST['mobilenumber']);
         $errors = array();
         // DO some checking
         if (empty($mobilenumber)) {
             $errors[] = "Please enter a mobile number";
         }
         // check to see if there is already a member with this mobile number
         $member = Member::get_one("Member", "MobileNumber = {$mobilenumber}");
         if ($member && empty($member->MobileConfirm) && !empty($mobilenumber)) {
             $errors[] = "A user already exists with that mobile number.";
         }
         if ($errors) {
             $returnArray = array();
             $returnArray["success"] = false;
             $returnArray["errorstring"] = "<div class=\"alert alert-info\">" . implode(", ", $errors) . "</div>";
             return json_encode($returnArray);
         } else {
             // Create the member
             if (!$member) {
                 $member = new Member();
             }
             $member->MobileNumber = $mobilenumber;
             $member->MobileConfirm = mt_rand(100000, 999999);
             $memberID = $member->write();
             // Now send a text message to confirm the account
             if ($memberID) {
                 $config = Config::inst()->get('TelstraAPI', 'Keys');
                 $sms = new TelstraSMS($config['consumer'], $config['secret'], $mobilenumber, "Your NextHit verification code is: " . $member->MobileConfirm);
                 $sms->send();
                 // register a session with the mobile number
                 Session::set("RegisterNumber", $mobilenumber);
                 Session::set("RegisterMemberID", $memberID);
                 $returnArray = array();
                 $returnArray["success"] = true;
                 $returnArray["nextstep"] = "step2";
                 return json_encode($returnArray);
             }
         }
     } else {
         $this->redirect($this->Link(), 404);
     }
 }
 public function testAuthenticateUserToken()
 {
     $member = new Member();
     $member->Email = "*****@*****.**";
     $member->Password = "******";
     $member->write();
     $this->assertNotNull($member->Token);
     $this->assertNotNull($member->AuthPrivateKey);
     $token = $member->ID . ":" . $member->userToken();
     // create an authenticator and see what we get back
     $tokenAuth = new TokenAuthenticator();
     $user = $tokenAuth->authenticate($token);
     $this->assertEquals($member->ID, $user->ID);
     $token = "42:" . $member->userToken();
     $user = $tokenAuth->authenticate($token);
     $this->assertNull($user);
 }
 public function run($request)
 {
     // get all users from LDAP, but only get the attributes we need.
     // this is useful to avoid holding onto too much data in memory
     // especially in the case where getUser() would return a lot of users
     $users = $this->ldapService->getUsers(array_merge(array('objectguid', 'samaccountname', 'useraccountcontrol', 'memberof'), array_keys(Config::inst()->get('Member', 'ldap_field_mappings'))));
     $start = time();
     $count = 0;
     foreach ($users as $data) {
         $member = Member::get()->filter('GUID', $data['objectguid'])->limit(1)->first();
         if (!($member && $member->exists())) {
             // create the initial Member with some internal fields
             $member = new Member();
             $member->GUID = $data['objectguid'];
             $member->write();
             $this->log(sprintf('Creating new Member (ID: %s, GUID: %s, sAMAccountName: %s)', $member->ID, $data['objectguid'], $data['samaccountname']));
         } else {
             $this->log(sprintf('Updating existing Member "%s" (ID: %s, GUID: %s, sAMAccountName: %s)', $member->getName(), $member->ID, $data['objectguid'], $data['samaccountname']));
         }
         // sync attributes from LDAP to the Member record
         // this is also responsible for putting the user into mapped groups
         try {
             $this->ldapService->updateMemberFromLDAP($member, $data);
         } catch (Exception $e) {
             $this->log($e->getMessage());
         }
         // cleanup object from memory
         $member->destroy();
         $count++;
     }
     // remove Member records that were previously imported, but no longer exist in the directory
     // NOTE: DB::query() here is used for performance and so we don't run out of memory
     if ($this->config()->destructive) {
         foreach (DB::query('SELECT "ID", "GUID" FROM "Member" WHERE "IsImportedFromLDAP" = 1') as $record) {
             if (!isset($users[$record['GUID']])) {
                 $member = Member::get()->byId($record['ID']);
                 $member->delete();
                 $this->log(sprintf('Removing Member "%s" (GUID: %s) that no longer exists in LDAP.', $member->getName(), $member->GUID));
                 // cleanup object from memory
                 $member->destroy();
             }
         }
     }
     $end = time() - $start;
     $this->log(sprintf('Done. Processed %s records. Duration: %s seconds', $count, round($end, 0)));
 }
 public function testLinksExistingMembers()
 {
     if (!class_exists('Comment')) {
         $this->markTestSkipped('"Comment" module not installed');
     }
     // Data matching comments.csv fixture
     $user1 = new Member(array('Nickname' => 'user1'));
     $user1->write();
     $user2 = new Member(array('Nickname' => 'user2'));
     $user2->write();
     $loader = new DrupalBlogCommentBulkLoader();
     $result = $loader->load(BASE_PATH . '/drupal-blog-importer/tests/fixtures/comments.csv');
     $created = $result->Created();
     $comment1 = $created->find('Subject', 'comment1 subject');
     $this->assertEquals($comment1->AuthorID, $user1->ID);
     $comment2 = $created->find('Subject', 'comment2 subject');
     $this->assertEquals($comment2->AuthorID, $user1->ID);
     $comment3 = $created->find('Subject', 'comment3 subject');
     $this->assertEquals($comment3->AuthorID, $user2->ID);
 }