Fix user migration

This commit is contained in:
Nicolas Le Goff
2014-01-27 16:41:43 +01:00
parent 2973513519
commit 7c0d1e3d8d
16 changed files with 70 additions and 38 deletions

View File

@@ -54,7 +54,6 @@ class NativeAuthentication implements PasswordAuthenticationInterface
if (false === $user->isSaltedPassword()) { if (false === $user->isSaltedPassword()) {
// we need a quick update and continue // we need a quick update and continue
if ($this->oldEncoder->isPasswordValid($user->getPassword(), $password, $user->getNonce())) { if ($this->oldEncoder->isPasswordValid($user->getPassword(), $password, $user->getNonce())) {
$user->setSaltedPassword(true);
$this->userManipulator->setPassword($user, $password); $this->userManipulator->setPassword($user, $password);
} }
} }

View File

@@ -46,7 +46,7 @@ class WorkZone extends Helper
$basket = new BasketEntity(); $basket = new BasketEntity();
$basket->setName($this->app->trans('Default basket')); $basket->setName($this->app->trans('Default basket'));
$basket->setOwner($this->app['authentication']->getUser()); $basket->setUser($this->app['authentication']->getUser());
$this->app['EM']->persist($basket); $this->app['EM']->persist($basket);
$this->app['EM']->flush(); $this->app['EM']->flush();

View File

@@ -67,14 +67,14 @@ class User
private $password; private $password;
/** /**
* @ORM\Column(type="string", length=16, nullable=true) * @ORM\Column(type="string", length=64, nullable=true)
*/ */
private $nonce; private $nonce;
/** /**
* @ORM\Column(type="boolean", name="salted_password") * @ORM\Column(type="boolean", name="salted_password")
*/ */
private $saltedPassword = false; private $saltedPassword = true;
/** /**
* @ORM\Column(type="string", length=64, name="first_name") * @ORM\Column(type="string", length=64, name="first_name")

View File

@@ -78,11 +78,10 @@ class UserRepository extends EntityRepository
public function findRealUserByLogin($login) public function findRealUserByLogin($login)
{ {
$qb = $this->createQueryBuilder('u'); $qb = $this->createQueryBuilder('u');
$qb->where($qb->expr()->eq('u.login', $qb->expr()->literal($login))) $qb->where($qb->expr()->eq('u.login', $qb->expr()->literal($login)))
->andWhere($qb->expr()->isNotNull('u.email')) ->andWhere($qb->expr()->isNotNull('u.email'))
->andWhere($qb->expr()->isNull('u.modelOf')) ->andWhere($qb->expr()->isNull('u.modelOf'))
->andWhere($qb->expr()->eq('u.guest', $qb->expr()->literal('0'))) ->andWhere($qb->expr()->eq('u.guest', $qb->expr()->literal(false)))
->andWhere($qb->expr()->eq('u.deleted', $qb->expr()->literal(false))); ->andWhere($qb->expr()->eq('u.deleted', $qb->expr()->literal(false)));
return $qb->getQuery()->getOneOrNullResult(); return $qb->getQuery()->getOneOrNullResult();

View File

@@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Setup;
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Doctrine\ORM\Tools\SchemaTool; use Doctrine\ORM\Tools\SchemaTool;
use Alchemy\Phrasea\Model\Entities\User;
class Installer class Installer
{ {

View File

@@ -28,6 +28,8 @@ class Upgrade39 implements PreSchemaUpgradeInterface
private $backupFeeds = false; private $backupFeeds = false;
private $migrateUsers = false; private $migrateUsers = false;
private $tablesStatus;
private static $users = []; private static $users = [];
/** /**
@@ -264,17 +266,18 @@ class Upgrade39 implements PreSchemaUpgradeInterface
$em->getConnection()->beginTransaction(); $em->getConnection()->beginTransaction();
try { try {
foreach ($tables as $tableName => $fields) { foreach ($tables as $tableName => $fields) {
if (false === $this->tableExists($em, $tableName)) {
continue;
}
$this->doUpdateFields($em, $tableName, $fields); $this->doUpdateFields($em, $tableName, $fields);
} }
$em->getConnection()->commit(); $em->getConnection()->commit();
// restore indexes
$this->indexes($em, 'restore');
} catch (\Exception $e) { } catch (\Exception $e) {
$em->getConnection()->rollback(); $em->getConnection()->rollback();
// restore indexes
$this->indexes($em, 'restore');
throw $e; throw $e;
} }
// restore indexes
$this->indexes($em, 'restore');
} }
/** /**
@@ -286,21 +289,21 @@ class Upgrade39 implements PreSchemaUpgradeInterface
private function indexes(EntityManager $em, $action) private function indexes(EntityManager $em, $action)
{ {
if ($action === 'drop') { if ($action === 'drop') {
if ($this->indexExists($em, 'demand', 'PRIMARY')) { if ($this->tableExists($em, 'demand') && $this->indexExists($em, 'demand', 'PRIMARY')) {
$em->getConnection()->executeQuery('ALTER TABLE demand DROP PRIMARY KEY'); $em->getConnection()->executeQuery('ALTER TABLE demand DROP PRIMARY KEY');
} }
if ($this->indexExists($em, 'UsrListsContent', 'unique_usr_per_list')) { if ($this->tableExists($em, 'UsrListsContent') && $this->indexExists($em, 'UsrListsContent', 'unique_usr_per_list')) {
$em->getConnection()->executeQuery('ALTER TABLE UsrListsContent DROP INDEX `unique_usr_per_list`'); $em->getConnection()->executeQuery('ALTER TABLE UsrListsContent DROP INDEX `unique_usr_per_list`');
} }
} }
if ($action === 'restore') { if ($action === 'restore') {
if (!$this->indexExists($em, 'demand', 'PRIMARY')) { if ($this->tableExists($em, 'demand') && !$this->indexExists($em, 'demand', 'PRIMARY')) {
$em->getConnection()->executeQuery('ALTER TABLE demand ADD PRIMARY KEY (`usr_id`, `base_id`, `en_cours`);'); $em->getConnection()->executeQuery('ALTER TABLE demand ADD PRIMARY KEY (`usr_id`, `base_id`, `en_cours`);');
} }
if (!$this->indexExists($em, 'UsrListsContent', 'unique_usr_per_list')) { if ($this->tableExists($em, 'UsrListsContent') && !$this->indexExists($em, 'UsrListsContent', 'unique_usr_per_list')) {
$em->getConnection()->executeQuery('ALTER TABLE UsrListsContent ADD INDEX `unique_usr_per_list` (`user_id`, `list_id`);'); $em->getConnection()->executeQuery('ALTER TABLE UsrListsContent ADD INDEX `unique_usr_per_list` (`user_id`, `list_id`);');
} }
} }
@@ -426,6 +429,9 @@ class Upgrade39 implements PreSchemaUpgradeInterface
$sql = 'ALTER TABLE %s CHANGE '.($direction === 'up' ? 'usr_id user_id' : 'user_id usr_id').' INT'; $sql = 'ALTER TABLE %s CHANGE '.($direction === 'up' ? 'usr_id user_id' : 'user_id usr_id').' INT';
foreach ($tables as $tableName) { foreach ($tables as $tableName) {
if (false === $this->tableExists($em, $tableName)) {
continue;
}
$em->getConnection()->executeQuery(sprintf($sql, $tableName)); $em->getConnection()->executeQuery(sprintf($sql, $tableName));
} }
} }
@@ -513,11 +519,34 @@ class Upgrade39 implements PreSchemaUpgradeInterface
$em->getEventManager()->addEventSubscriber(new TimestampableListener()); $em->getEventManager()->addEventSubscriber(new TimestampableListener());
} }
private function tableExists(EntityManager $em , $tableName)
{
if (null === $this->tablesStatus) {
$this->tablesStatus = array_map(function($row) {
return $row['Name'];
}, $em->createNativeQuery(
"SHOW TABLE STATUS",
new ResultSetMapping()
)->getResult());
}
return in_array($tableName, $this->tablesStatus);
}
private function hasNonceColumn(EntityManager $em)
{
return (Boolean) $em->createNativeQuery(
"SHOW FIELDS FROM usr WHERE Field = 'nonce';",
new ResultSetMapping()
)->getOneOrNullResult();
}
/** /**
* Sets user entity from usr table. * Sets user entity from usr table.
*/ */
private function updateUsers(EntityManager $em, $conn) private function updateUsers(EntityManager $em, $conn)
{ {
if ($this->hasNonceColumn($em)) {
$sql = 'SELECT activite, adresse, create_db, canchgftpprofil, canchgprofil, ville, $sql = 'SELECT activite, adresse, create_db, canchgftpprofil, canchgprofil, ville,
societe, pays, usr_mail, fax, usr_prenom, geonameid, invite, fonction, societe, pays, usr_mail, fax, usr_prenom, geonameid, invite, fonction,
last_conn, lastModel, usr_nom, ldap_created, locale, usr_login, last_conn, lastModel, usr_nom, ldap_created, locale, usr_login,
@@ -525,6 +554,16 @@ class Upgrade39 implements PreSchemaUpgradeInterface
request_notifications, salted_password, usr_sexe, tel, timezone, cpostal, usr_creationdate, request_notifications, salted_password, usr_sexe, tel, timezone, cpostal, usr_creationdate,
usr_modificationdate usr_modificationdate
FROM usr'; FROM usr';
} else {
$sql = 'SELECT activite, adresse, create_db, canchgftpprofil, canchgprofil, ville,
societe, pays, usr_mail, fax, usr_prenom, geonameid, invite, fonction,
last_conn, lastModel, usr_nom, ldap_created, locale, usr_login,
mail_notifications, NULL as nonce, usr_password, push_list, mail_locked,
request_notifications, "0" as salted_password, usr_sexe, tel, timezone, cpostal, usr_creationdate,
usr_modificationdate
FROM usr';
}
$stmt = $conn->prepare($sql); $stmt = $conn->prepare($sql);
$stmt->execute(); $stmt->execute();
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
@@ -536,9 +575,9 @@ class Upgrade39 implements PreSchemaUpgradeInterface
$user = new User(); $user = new User();
$user->setActivity($row['activite']); $user->setActivity($row['activite']);
$user->setAddress($row['adresse']); $user->setAddress($row['adresse']);
$user->setAdmin(!!$row['create_db']); $user->setAdmin((Boolean) $row['create_db']);
$user->setCanChangeFtpProfil(!!$row['canchgftpprofil']); $user->setCanChangeFtpProfil((Boolean) $row['canchgftpprofil']);
$user->setCanChangeProfil(!!$row['canchgprofil']); $user->setCanChangeProfil((Boolean) $row['canchgprofil']);
$user->setCity($row['ville']); $user->setCity($row['ville']);
$user->setCompany($row['societe']); $user->setCompany($row['societe']);
$user->setCountry((string) $row['pays']); $user->setCountry((string) $row['pays']);
@@ -548,11 +587,11 @@ class Upgrade39 implements PreSchemaUpgradeInterface
if ($row['geonameid'] > 0) { if ($row['geonameid'] > 0) {
$user->setGeonameId($row['geonameid']); $user->setGeonameId($row['geonameid']);
} }
$user->setGuest(!!$row['invite']); $user->setGuest((Boolean) $row['invite']);
$user->setJob($row['fonction']); $user->setJob($row['fonction']);
$user->setLastConnection(new \DateTime($row['last_conn'])); $user->setLastConnection(new \DateTime($row['last_conn']));
$user->setLastName($row['usr_nom']); $user->setLastName($row['usr_nom']);
$user->setLdapCreated(!!$row['ldap_created']); $user->setLdapCreated((Boolean) $row['ldap_created']);
try { try {
$user->setLocale($row['locale']); $user->setLocale($row['locale']);
} catch (\InvalidArgumentException $e ) { } catch (\InvalidArgumentException $e ) {
@@ -565,13 +604,13 @@ class Upgrade39 implements PreSchemaUpgradeInterface
$user->setDeleted(true); $user->setDeleted(true);
} }
$user->setMailLocked(!!$row['mail_locked']); $user->setMailLocked((Boolean) $row['mail_locked']);
$user->setMailNotificationsActivated(!!$row['mail_notifications']); $user->setMailNotificationsActivated((Boolean) $row['mail_notifications']);
$user->setNonce($row['nonce']); $user->setNonce($row['nonce']);
$user->setPassword($row['usr_password']); $user->setPassword($row['usr_password']);
$user->setPushList($row['push_list']); $user->setPushList($row['push_list']);
$user->setRequestNotificationsActivated(!!$row['request_notifications']); $user->setRequestNotificationsActivated((Boolean) $row['request_notifications']);
$user->setSaltedPassword(!!$row['salted_password']); $user->setSaltedPassword((Boolean) $row['salted_password']);
switch ($row['usr_sexe']) { switch ($row['usr_sexe']) {
case 0: case 0:

View File

@@ -10,6 +10,7 @@
*/ */
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Doctrine\ORM\Query;
class patch_320alpha2a implements patchInterface class patch_320alpha2a implements patchInterface
{ {
@@ -57,7 +58,9 @@ class patch_320alpha2a implements patchInterface
public function apply(base $appbox, Application $app) public function apply(base $appbox, Application $app)
{ {
$dql = 'SELECT u FROM Alchemy\Phrasea\Model\Entities\User u WHERE u.nonce IS NULL'; $dql = 'SELECT u FROM Alchemy\Phrasea\Model\Entities\User u WHERE u.nonce IS NULL';
$users = $app['EM']->createQuery($dql)->getResult(); $q = $app['EM']->createQuery($dql);
$q->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);
$users = $q->getResult();
$n = 0; $n = 0;
foreach ($users as $user) { foreach ($users as $user) {

View File

@@ -97,7 +97,6 @@ class patch_320alpha4a implements patchInterface
$xp_struct = $databox->get_xpath_structure(); $xp_struct = $databox->get_xpath_structure();
foreach ($sxe->description->children() as $fname => $field) { foreach ($sxe->description->children() as $fname => $field) {
$src = trim(isset($field['src']) ? $field['src'] : ''); $src = trim(isset($field['src']) ? $field['src'] : '');
if (array_key_exists($src, $phrasea_maps)) { if (array_key_exists($src, $phrasea_maps)) {
$src = $phrasea_maps[$src]; $src = $phrasea_maps[$src];

View File

@@ -214,7 +214,7 @@ class patch_360alpha1a implements patchInterface
$stmt->execute(); $stmt->execute();
$stmt->closeCursor(); $stmt->closeCursor();
$sql = 'SELECT usr_id, basket_id, p.id as participant_id $sql = 'SELECT user_id, basket_id, p.id as participant_id
FROM ValidationParticipants p, ValidationSessions s FROM ValidationParticipants p, ValidationSessions s
WHERE p.ValidationSession_Id = s.id'; WHERE p.ValidationSession_Id = s.id';
@@ -236,7 +236,7 @@ class patch_360alpha1a implements patchInterface
$params = [ $params = [
':participant_id' => $row['participant_id'], ':participant_id' => $row['participant_id'],
':basket_id' => $row['basket_id'], ':basket_id' => $row['basket_id'],
':usr_id' => $row['usr_id'], ':usr_id' => $row['user_id'],
]; ];
$stmt->execute($params); $stmt->execute($params);
} }

View File

@@ -56,7 +56,7 @@ class patch_360alpha2a implements patchInterface
*/ */
public function apply(base $appbox, Application $app) public function apply(base $appbox, Application $app)
{ {
$app['EM']->executeQuery('UPDATE Alchemy\Phrasea\Model\Entities\User u SET u.email = NULL WHERE u.email IS NOT NULL AND u.delete = 1'); $app['EM']->getConnection()->executeQuery('UPDATE Users u SET u.email = NULL WHERE u.email IS NOT NULL AND u.deleted = 1');
return true; return true;
} }

View File

@@ -68,7 +68,6 @@ class patch_370alpha4a implements patchInterface
$tagBasename = new \Alchemy\Phrasea\Metadata\Tag\TfBasename(); $tagBasename = new \Alchemy\Phrasea\Metadata\Tag\TfBasename();
foreach ($rs as $row) { foreach ($rs as $row) {
if (strpos(strtolower($row['src']), 'tf-parentdir') !== false) { if (strpos(strtolower($row['src']), 'tf-parentdir') !== false) {
$update[] = ['id' => $row['id'], 'src' => $tagDirname->getTagname()]; $update[] = ['id' => $row['id'], 'src' => $tagDirname->getTagname()];
} }

View File

@@ -56,7 +56,6 @@ class patch_370alpha5a implements patchInterface
*/ */
public function apply(base $databox, Application $app) public function apply(base $databox, Application $app)
{ {
$sql = 'SELECT id, src FROM metadatas_structure'; $sql = 'SELECT id, src FROM metadatas_structure';
$stmt = $databox->get_connection()->prepare($sql); $stmt = $databox->get_connection()->prepare($sql);
$stmt->execute(); $stmt->execute();

View File

@@ -76,13 +76,10 @@ class patch_370alpha6a implements patchInterface
$subdefgroups = $databox->get_subdef_structure(); $subdefgroups = $databox->get_subdef_structure();
foreach ($subdefgroups as $groupname => $subdefs) { foreach ($subdefgroups as $groupname => $subdefs) {
foreach ($subdefs as $name => $subdef) { foreach ($subdefs as $name => $subdef) {
$this->addScreenDeviceOption($subdefgroups, $subdef, $groupname); $this->addScreenDeviceOption($subdefgroups, $subdef, $groupname);
if (in_array($name, ['preview', 'thumbnail'])) { if (in_array($name, ['preview', 'thumbnail'])) {
if ($name == 'thumbnail' || $subdef->getSubdefType()->getType() != \Alchemy\Phrasea\Media\Subdef\Subdef::TYPE_VIDEO) { if ($name == 'thumbnail' || $subdef->getSubdefType()->getType() != \Alchemy\Phrasea\Media\Subdef\Subdef::TYPE_VIDEO) {
$this->addMobileSubdefImage($subdefgroups, $subdef, $groupname); $this->addMobileSubdefImage($subdefgroups, $subdef, $groupname);
} else { } else {

View File

@@ -88,11 +88,9 @@ class patch_370alpha7a implements patchInterface
$i = 0; $i = 0;
foreach ($rs as $row) { foreach ($rs as $row) {
$filePath = $app['root.path'] . '/tmp/lazaret/' . $row['filepath']; $filePath = $app['root.path'] . '/tmp/lazaret/' . $row['filepath'];
if (file_exists($filePath)) { if (file_exists($filePath)) {
$spec = new ImageSpec(); $spec = new ImageSpec();
$spec->setResizeMode(ImageSpec::RESIZE_MODE_INBOUND_FIXEDRATIO); $spec->setResizeMode(ImageSpec::RESIZE_MODE_INBOUND_FIXEDRATIO);

View File

@@ -241,7 +241,7 @@
<span style="font-weight:bold;font-size:14px;word-wrap: break-word;"> <span style="font-weight:bold;font-size:14px;word-wrap: break-word;">
{{ basId| bas_labels(app) }} {{ basId| bas_labels(app) }}
</span> </span>
{% set btn_value = row['usr_id'] ~ "_" ~ basId %} {% set btn_value = user.getId() ~ "_" ~ basId %}
<div class="btn-group btn-single-action" style="margin:auto auto 5px 0;"> <div class="btn-group btn-single-action" style="margin:auto auto 5px 0;">
<button data-event="deny" value="{{ btn_value }}" type="button" name="deny[]" class="btn deny-checker" title="{{ 'admin:: refuser l\'acces' | trans }}"> <button data-event="deny" value="{{ btn_value }}" type="button" name="deny[]" class="btn deny-checker" title="{{ 'admin:: refuser l\'acces' | trans }}">
<img title="{{ 'admin:: refuser l\'acces' | trans }}" src='/skins/icons/delete.gif' /> <img title="{{ 'admin:: refuser l\'acces' | trans }}" src='/skins/icons/delete.gif' />

View File

@@ -181,7 +181,6 @@ class NativeAuthenticationTest extends \PhraseanetTestCase
$user->expects($this->any())->method('isSaltedPassword')->will($this->returnValue(false)); $user->expects($this->any())->method('isSaltedPassword')->will($this->returnValue(false));
$user->expects($this->any())->method('getPassword')->will($this->returnValue($encoded)); $user->expects($this->any())->method('getPassword')->will($this->returnValue($encoded));
$user->expects($this->any())->method('getNonce')->will($this->returnValue($nonce)); $user->expects($this->any())->method('getNonce')->will($this->returnValue($nonce));
$user->expects($this->once())->method('setSaltedPassword')->with($this->equalTo(true));
$manipulator = $this->getUserManipulatorMock($user); $manipulator = $this->getUserManipulatorMock($user);