<?php
namespace Kzl\FrameworkBundle\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\PropertyChangedListener;
use Doctrine\ORM\Mapping as ORM;
use Kzl\FrameworkBundle\Common\KzlFrameworkStatic;
use Kzl\FrameworkBundle\Model\TenantAwareInterface;
use Kzl\FrameworkBundle\Repository\LoginUserRepository;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* LoginUser.
*
* @ORM\Table(name="login_user")
* @ORM\Entity
* @ApiResource(
* normalizationContext={"groups" = {"read"}},
* denormalizationContext={"groups" = {"write"}},
* itemOperations={
* "get",
* "patch",
* "delete",
* "put",
* "get_login_user_data" = {
* "method" = "GET",
* "path" = "/{subfolder}/custom/get_login_user_data/{id}",
* "controller" = "Kzl\FrameworkBundle\Api\GetLoginUserDataController",
* "read"=false,
* "openapi_context" = {
* "parameters" = {
* {
* "name" = "id",
* "in" = "path",
* "type" = "string",
* "required" = true,
* },
* },
* },
* },
* "change_login_user_item" = {
* "method" = "GET",
* "path" = "/{subfolder}/custom/change_login_user_item/{id}/{itemName}/{value}",
* "controller" = "Kzl\FrameworkBundle\Api\ChangeLoginUserItem",
* "read"=false,
* "openapi_context" = {
* "parameters" = {
* {
* "name" = "id",
* "in" = "path",
* "type" = "string",
* "required" = true,
* },
* {
* "name" = "itemName",
* "in" = "path",
* "type" = "string",
* "required" = true,
* },
* {
* "name" = "value",
* "in" = "path",
* "type" = "string",
* "required" = true,
* },
* },
* },
* },
* "new_login_user" = {
* "method" = "POST",
* "path" = "/{subfolder}/custom/new_login_user",
* "controller" = "Kzl\FrameworkBundle\Api\EditLoginUserController",
* "read"=false,
* },
* "delete_login_user" = {
* "method" = "GET",
* "path" = "/{subfolder}/custom/delete_login_user/{userId}",
* "controller" = "Kzl\FrameworkBundle\Api\DeleteLoginUserController",
* "read"=false,
* "openapi_context" = {
* "parameters" = {
* {
* "name" = "userId",
* "in" = "path",
* "type" = "string",
* "required" = true,
* },
* },
* },
* },
* }
* )
*/
class LoginUser implements \Serializable, UserInterface, PasswordAuthenticatedUserInterface, TenantAwareInterface
{
/**
* @var integer
*/
private $dNo;
/**
* Get dNo.
*
* @return integer
*/
public function getId()
{
return $this->dNo;
}
/**
* @var string
*/
private $tenantCd;
/**
* @var string
*/
private $first_name;
/**
* @var string
*/
private $last_name;
/**
* @var string
*/
private $email_address;
/**
* @var string
*/
private $username;
/**
* @var string
*/
private $login_id;
/**
* @var string
*/
private $algorithm;
/**
* @var string
*/
private $salt;
/**
* @var string
*/
private $roles = [];
/**
* @var string
*/
private $password;
/**
* @var boolean
*/
private $is_active;
/**
* @var boolean
*/
private $is_super_admin;
/**
* @var \DateTime
*/
private $last_login;
/**
* @var string
*/
private $subject;
/**
* @var \DateTime
*/
private $created_at;
/**
* @var \DateTime
*/
private $updated_at;
/**
* 暗号化してない状態のパスワードを保持する
* DBには保存させない。
* (ユーザ管理編集のために使用).
*/
private $plain_password;
/**
* Get the value of tenantId.
*
* @return int
*/
public function getTenantId()
{
return $this->tenantCd;
}
/**
* Set the value of tenantId.
*
* @return self
*/
public function setTenantId($tenantCd)
{
$this->tenantCd = $tenantCd;
return $this;
}
/**
* Set first_name.
*
* @param string $firstName
*
* @return LoginUser
*/
public function setFirstName($firstName)
{
$this->first_name = $firstName;
return $this;
}
/**
* Get first_name.
*
* @return string
*/
public function getFirstName()
{
return $this->first_name;
}
/**
* Set last_name.
*
* @param string $lastName
*
* @return LoginUser
*/
public function setLastName($lastName)
{
$this->last_name = $lastName;
return $this;
}
/**
* Get last_name.
*
* @return string
*/
public function getLastName()
{
return $this->last_name;
}
/**
* Set email_address.
*
* @param string $emailAddress
*
* @return LoginUser
*/
public function setEmailAddress($emailAddress)
{
$this->email_address = $emailAddress;
return $this;
}
/**
* Get email_address.
*
* @return string
*/
public function getEmailAddress()
{
return $this->email_address;
}
/**
* Set username.
*
* @param string $username
*
* @return LoginUser
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->username;
}
/**
* @deprecated since Symfony 5.3, use getUserIdentifier instead
*/
public function getUsername(): string
{
return (string) $this->username;
}
// /**
// * Get username.
// *
// * @return string
// */
// public function getUsername()
// {
// return $this->username;
// }
/**
* Set algorithm.
*
* @param string $algorithm
*
* @return LoginUser
*/
public function setAlgorithm($algorithm)
{
$this->algorithm = $algorithm;
return $this;
}
/**
* Get algorithm.
*
* @return string
*/
public function getAlgorithm()
{
return $this->algorithm;
}
/**
* Set salt.
*
* @param string $salt
*
* @return LoginUser
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Get salt.
*
* @return string
*/
public function getSalt()
{
// return $this->salt;
return '';
}
/**
* Set password.
*
* @return LoginUser
*/
public function setPassword(string $password): self
{
// パスワードが設定されていたら更新
if ($password && !empty($password)) {
$this->password = $password;
}
return $this;
}
/**
* Get password.
*
* @return string
*
* @see PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}
/**
* Set is_active.
*
* @param bool $isActive
*
* @return LoginUser
*/
public function setIsActive($isActive)
{
$this->is_active = $isActive;
return $this;
}
/**
* Get is_active.
*
* @return bool
*/
public function getIsActive()
{
return $this->is_active;
}
/**
* Set is_super_admin.
*
* @param bool $isSuperAdmin
*
* @return LoginUser
*/
public function setIsSuperAdmin($isSuperAdmin)
{
$this->is_super_admin = $isSuperAdmin;
return $this;
}
/**
* Get is_super_admin.
*
* @return bool
*/
public function getIsSuperAdmin()
{
return $this->is_super_admin;
}
/**
* Set last_login.
*
* @param \DateTime $lastLogin
*
* @return LoginUser
*/
public function setLastLogin($lastLogin)
{
$this->last_login = $lastLogin;
return $this;
}
/**
* Get last_login.
*
* @return \DateTime
*/
public function getLastLogin()
{
return $this->last_login;
}
/**
* Set created_at.
*
* @param \DateTime $createdAt
*
* @return LoginUser
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at.
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set updated_at.
*
* @param \DateTime $updatedAt
*
* @return LoginUser
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
return $this;
}
/**
* Get updated_at.
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* Set plain_password.
*
* @return LoginUser
*/
public function setPlainPassword($plainPassword)
{
$this->plain_password = $plainPassword;
return $this;
}
/**
* Set subject.
*
* @param $subject
*
* @return LoginUser
*/
public function setSubject($subject)
{
$this->subject = $subject;
return $this;
}
/**
* Get subject.
*
* @return
*/
public function getSubject()
{
return $this->subject;
}
/**
* Get plain_password.
*
* @return \DateTime
*/
public function getPlainPassword()
{
return $this->plain_password;
}
// ---------- UserInterface実装 -----------------
public function eraseCredentials()
{
}
// /**
// * 権限取得.
// */
// public function getRoles()
// {
// // ADMIN固定
// return array('ROLE_USER');
// // return array('ROLE_ALLOWED_TO_ADMIN');
// }
/**
* 権限取得.
*/
public function getRoles()
{
// ADMIN固定
return array('ROLE_ADMIN');
}
// ------------ 認証用メソッド -----------------
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->is_active;
}
// ---------- 以下追加処理 -------------
public function __construct()
{
//初期値の設定
$this->algorithm = 'sha1';
$this->is_active = true;
$this->is_super_admin = false;
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
}
public function __toString()
{
return $this->toArray();
}
public function equals(UserInterface $user)
{
return $user->getUsername() === $this->username;
}
/**
* @ORM\PostLoad
*/
public function doPostLoad()
{
// Add your code here
}
private $_changeValues;
/**
* @ORM\PrePersist
*/
public function doPreUpdate()
{
// ** 変更された値をログへ記録
// 1)変更値取得
if ($this->_listeners) {
foreach ($this->_listeners as $listener) {
// 変更項目
$changeSet = $listener->getEntityChangeSet($this);
foreach ($changeSet as $item => $values) {
// 監視対象なら変更値を保存
if (LoginUserRepository::isLogTargetItem($item)) {
if ($item == 'is_active' || $item == 'is_super_admin') {
// 文字列で変更値を格納する
$values[0] = KzlFrameworkStatic::getUseFlgToString($values[0]);
$values[1] = KzlFrameworkStatic::getUseFlgToString($values[1]);
}
foreach ($values as $key => $value) {
if (is_null($value) || KzlFrameworkStatic::isNotValue($value)) {
$values[$key] = KzlFrameworkStatic::LOG_EMPTT_STRING;
}
}
//変更値を保持しておく
$this->_changeValues[LoginUserRepository::$log_target_list[$item]] = $values;
}
}//end foreach $changeSet
} // end foreach $_listeners
} //end if
// 新規の時は作成日を設定
if (null === $this->created_at) {
$this->setCreatedAt(new \DateTime());
}
// 更新日を設定
$this->setUpdatedAt(new \DateTime());
KzlFrameworkStatic::setNewDNo($this);
KzlFrameworkStatic::setTenantCd($this);
}
public function getChangeVelues()
{
if ($this->_changeValues) {
return $this->_changeValues;
}
return false;
}
public function writeLog()
{
// $logStr = '';$str='';
// $values= $this->_changeValues;
// $itemName = $this->getUsername();
// if($values){
// foreach($values as $columnName=>$value){
// $beforeValue= array_shift($value);
// $afterValue= array_shift($value);
// //パスワードの場合は別の文章
// if($columnName == 'パスワード'){
// $str = KzlFrameworkStatic::getTrans('ユーザ管理').': 「'.$itemName.'」の'.$columnName.'を変更しました。';
// }else{
// //パスワードの以外の場合の文章
//// $str = KzlFrameworkStatic::getLogger()->getInfoChangeStr(KzlFrameworkStatic::getTrans('ユーザ管理'), $itemName, $columnName, $beforeValue, $afterValue);
// $str = KzlFrameworkStatic::getTrans('ユーザ管理').': 「'.$itemName.'」の'.$columnName.'を '.$beforeValue.' → '.$afterValue.' に変更しました。';
// }
// if($logStr === ''){
// $logStr = $str;
// } else {
// $logStr .= "\n".$str;
// }
// }
//
// }
// KzlFrameworkStatic::getLogger()->info($logStr);
}
// -------------------- 以下 追加処理 ---------------------------------------------
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
//USERNAME (ユーザID )
$metadata->addPropertyConstraint('login_id', new Assert\NotBlank([
]));
$metadata->addPropertyConstraint('login_id', new Assert\Length([
'max' => 128,
]));
$metadata->addPropertyConstraint('login_id', new Assert\Regex([
'pattern' => KzlFrameworkStatic::ID_PATTERN,
]));
$metadata->addConstraint(new UniqueEntity([
'fields' => ['login_id', 'tenantCd'],
'errorPath' => 'login_id',
]));
//パスワード 新規の時は必須
$metadata->addPropertyConstraint('plain_password', new Assert\NotBlank([
'groups' => ['add'],
]));
$metadata->addPropertyConstraint('plain_password', new Assert\Length([
'max' => 20,
]));
$metadata->addPropertyConstraint('plain_password', new Assert\Regex([
'pattern' => KzlFrameworkStatic::ID_PATTERN,
'message' => KzlFrameworkStatic::ID_PATTERN_VALIDATE_MSG,
]));
//苗字
$metadata->addPropertyConstraint('first_name', new Assert\Length([
'max' => 255,
]));
//名前
$metadata->addPropertyConstraint('last_name', new Assert\Length([
'max' => 255,
]));
// メール
$metadata->addPropertyConstraint('email_address', new Assert\Email([
]));
}
/**
* 最終ログイン日を「M月D日 H:i:s」で取得.
*/
public function getLastLoginToString()
{
// 「YYYY年M月D日 H:i」で表示
if ($this->last_login) {
return $this->last_login->format('Y年n月j日 H:i');
}
return null;
}
/**
* @var \Kzl\JinjiKoukaBundle\Entity\userRole
*/
private $userRole;
/**
* Set userRole.
*
* @param \Kzl\JinjiKoukaBundle\Entity\userRole $userRole
*
* @return LoginUser
*/
public function setUserRole(\Kzl\FrameworkBundle\Entity\userRole $userRole = null)
{
$this->userRole = $userRole;
return $this;
}
/**
* Get userRole.
*
* @return \Kzl\JinjiKoukaBundle\Entity\userRole
*/
public function getUserRole()
{
return $this->userRole;
}
/**
* @var \Doctrine\Common\Collections\Collection
*/
private $user_role;
/**
* Add user_role.
*
* @param \Kzl\JinjiKoukaBundle\Entity\UserRole $userRole
*
* @return LoginUser
*/
public function addUserRole(\Kzl\FrameworkBundle\Entity\UserRole $userRole)
{
$this->user_role[] = $userRole;
return $this;
}
/**
* Remove user_role.
*
* @param \Kzl\JinjiKoukaBundle\Entity\UserRole $userRole
*/
public function removeUserRole(\Kzl\FrameworkBundle\Entity\UserRole $userRole)
{
$this->user_role->removeElement($userRole);
}
//-------------------------------------------------------------------
// NotifyPropertyChanged 実装
private $_listeners = [];
// /**
// * 値変更のイベントリスナー 呼ばれていないので一旦非表示(220420)
// *
// * @param \Doctrine\Common\PropertyChangedListener $listener
// */
// public function addPropertyChangedListener(PropertyChangedListener $listener)
// {
// $this->_listeners[] = $listener;
// }
/**
* 変更前・変更後の値をイベントリスナーに保存する.
*
* @param type $propName
* @param type $oldValue
* @param type $newValue
*/
protected function _onPropertyChanged($propName, $oldValue, $newValue)
{
if ($this->_listeners) {
foreach ($this->_listeners as $listener) {
$listener->propertyChanged($this, $propName, $oldValue, $newValue);
}
}
}
public function __sleep()
{
return [
'dNo',
'username',
'is_active',
'is_super_admin',
'email_address',
];
}
/*
public function __wakeup() {
;
}
*/
public function getFullname()
{
return $this->getLastName().' '.$this->getFirstName();
}
/**
* ログ出力用ユーザ名.
*
* @return string
*/
public function getLoggingUserName()
{
return $this->getLoginId();
}
/**
* Get the value of dNo.
*
* @return integer
*/
public function getDNo()
{
return $this->dNo;
}
/**
* Set the value of dNo.
*
* @param int $dNo
*
* @return self
*/
public function setDNo($dNo)
{
$this->dNo = $dNo;
return $this;
}
/**
* Get the value of tenantCd.
*
* @return string
*/
public function getTenantCd()
{
return $this->tenantCd;
}
/**
* Set the value of tenantCd.
*
* @param string $tenantCd
*
* @return self
*/
public function setTenantCd($tenantCd)
{
$this->tenantCd = $tenantCd;
return $this;
}
/** @see \Serializable::serialize() */
public function serialize()
{
return serialize([
$this->dNo,
$this->username,
$this->password,
$this->salt,
$this->tenantCd,
$this->is_active,
$this->is_super_admin,
]);
}
/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
list(
$this->dNo,
$this->username,
$this->password,
$this->salt,
$this->tenantCd,
$this->is_active,
$this->is_super_admin) = unserialize($serialized);
}
/**
* Get the value of login_id.
*
* @return string
*/
public function getLoginId()
{
return $this->login_id;
}
/**
* Set the value of login_id.
*
* @param string $login_id
*
* @return self
*/
public function setLoginId($login_id)
{
$this->login_id = $login_id;
return $this;
}
/**
* マルチテナント対応ログインID設定処理.
*
* @return void
*/
public function setTenantLoginId()
{
if ($this->getTenantCd() && $this->getLoginId()) {
$this->setUsername($this->getTenantCd().'@'.$this->getLoginId());
}
}
public function toArray()
{
return [
'dNo' => $this->getId(),
'loginId' => $this->getLoginId(),
'firstName' => $this->getFirstName(),
'lastName' => $this->getLastName(),
'emailAddress' => $this->getEmailAddress(),
'lastLogin' => $this->getLastLogin(),
'isActive' => $this->getIsActive(),
'subject' => $this->getSubject(),
];
}
/**
* 権限確認用リストの取得.
* 権限が複数ある場合は利用可>メニューに表示するのみ>無効の順で適用
*/
public function getUserHasRoleList()
{
$em = KzlFrameworkStatic::getDoctrine()->getManager();
$userRoleIdList = $em->getRepository(UserRole::class)->getUserRoleListByLoginUserId($this->getId(), true);
$roleModuleList = $em->getRepository(RoleModule::class)->getRoleModuleListByRoleIds($userRoleIdList, false);
$roleList = [];
foreach ($roleModuleList as $rm) {
//一つ目は無条件に代入
if(!isset($roleList[$rm['functionName']][$rm['actionName']])){
$roleList[$rm['functionName']][$rm['actionName']]['useFlg'] = $rm['useFlg'];
$roleList[$rm['functionName']][$rm['actionName']]['showFlg'] = $rm['showFlg'];
}else{
//二つ目以降はfalseなら上書きしない
if($rm['useFlg']){
$roleList[$rm['functionName']][$rm['actionName']]['useFlg'] = $rm['useFlg'];
}
if($rm['showFlg']){
$roleList[$rm['functionName']][$rm['actionName']]['showFlg'] = $rm['showFlg'];
}
}
}
return $roleList;
}
}