EncryptAllPasswordsTask.php
2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/**
 * Encrypt all passwords
 *
 * Action to encrypt all *clear text* passwords in the database according
 * to the current settings.
 * If the current settings are so that passwords shouldn't be encrypted,
 * an explanation will be printed out.
 *
 * To run this action, the user needs to have administrator rights!
 * 
 * @package framework
 * @subpackage tasks
 */
class EncryptAllPasswordsTask extends BuildTask {
	protected $title = 'Encrypt all passwords tasks';
	
	protected $description = 'Convert all plaintext passwords on the Member table to the default encryption/hashing
		algorithm. Note: This mainly applies to passwords in SilverStripe 2.1 or earlier, passwords in newer versions
		are hashed by default.';
	
	public function init() {
		parent::init();
		
		if(!Permission::check('ADMIN')) {
			return Security::permissionFailure($this);
		}
	}
	
	public function run($request) {
		$algo = Security::config()->password_encryption_algorithm;
		if($algo == 'none') {
			$this->debugMessage('Password encryption disabled');
			return;
		}
		// Are there members with a clear text password?
		$members = DataObject::get(
			"Member", 
			"\"PasswordEncryption\" = 'none' AND \"Password\" IS NOT NULL"
		);
		if(!$members) {
			$this->debugMessage('No passwords to encrypt');
			return;
		}
		// Encrypt the passwords...
		$this->debugMessage('Encrypting all passwords');
		$this->debugMessage(sprintf(
			'The passwords will be encrypted using the %s algorithm',
			$algo
		));
		foreach($members as $member) {
			// Force the update of the member record, as new passwords get
			// automatically encrypted according to the settings, this will do all
			// the work for us
			$member->PasswordEncryption = $algo;
			$member->forceChange();
			$member->write();
			
			$this->debugMessage(sprintf('Encrypted credentials for member #%d;', $member->ID));
		}
	}
	
	/**
	 * @todo This should really be taken care of by TestRunner
	 */
	protected function debugMessage($msg) {
		if(class_exists('SapphireTest', false) && !SapphireTest::is_running_test()) {
			Debug::message($msg);
		}
	}
}