Skip to content

Feature: Store user id of creator #519

Open

Description

@strtob

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

Activity

  1. strtob commented on Nov 14, 2024

    @strtob
    Author

    ... 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions