Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Store user id of creator #519

Open
strtob opened this issue Nov 14, 2024 · 1 comment
Open

Feature: Store user id of creator #519

strtob opened this issue Nov 14, 2024 · 1 comment

Comments

@strtob
Copy link

strtob commented Nov 14, 2024

Hi,

Great Extension! What about storing the user id of the user, who created the job a this time? Could be helpful in case of userstamp, grants etc.

Best,
Tobi

@strtob
Copy link
Author

strtob commented Nov 14, 2024

... in a way like this:

/**
 * Class AbstractJob
 *
 * An abstract class for jobs that require the user context of the creator.
 * This class captures and stores the `userId` of the user creating the job and sets
 * the application's user identity during job execution.
 */
abstract class AbstractJob extends BaseObject
{
    /**
     * @var int|null $userId Stores the ID of the user who created the job
     */
    public $userId;

    /**
     * AbstractJob constructor.
     * Automatically sets the `userId` based on the currently logged-in user.
     *
     * @param array $config The configuration array
     */
    public function __construct($config = [])
    {
        $this->userId = Yii::$app->user->id;  // Capture the current user ID
        parent::__construct($config);
    }

    /**
     * Sets the user identity in Yii based on the `userId` property.
     * This method can be called in the child class to set the current user context.
     *
     * @return bool Returns true if the user was successfully impersonated, false otherwise.
     */
    protected function setUserContext()
    {
        $user = \app\models\User::findOne($this->userId);
        
        if ($user) {
            Yii::$app->user->setIdentity($user);  // Impersonate the user
            return true;
        }
        
        Yii::error("User with ID {$this->userId} not found for impersonation.");
        return false;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant