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: 
<?php declare(strict_types=1);

    /**
     * Copyright (C) Apis Networks, Inc - All Rights Reserved.
     *
     * Unauthorized copying of this file, via any medium, is
     * strictly prohibited without consent. Any dissemination of
     * material herein is prohibited.
     *
     * For licensing inquiries email <licensing@apisnetworks.com>
     *
     * Written by Matt Saladna <matt@apisnetworks.com>, August 2018
     */
    trait ImpersonableTrait
    {
        /**
         * Login as requested credentials
         *
         * @param string      $site
         * @param string|null $user
         */
        protected function impersonateRole(string $site, string $user = null): string
        {
            $parent = \session_id();
            \Preferences::factory()->sync();
            $context = \Auth::context($user, $site);
            if (!\apnscpSession::restore_from_id($context->id, false)) {
                fatal("role mockup failed, cannot impersonate `%s'@`%s'", $context->username, $context->domain);
            }
            $this->setApnscpFunctionInterceptor(\apnscpFunctionInterceptor::factory($context));
            register_shutdown_function(function () use ($context, $parent) {
                /**
                 * need to be doubly sure the session isn't overwritten by initializeUser
                 * impersonation ends the active session + forces redirect to stabilize state
                 */
                $context->setImpersonator($parent);
            });

            \Auth::autoload()->setID($context->id)->authInfo(true);
            return $context->id;
        }

        protected function restoreImpersonator(\Auth_Info_User $auth): void
        {
            \Preferences::factory()->sync();
            if (null === ($parent = $auth->getImpersonator())) {
                return;
            }

            if (!\apnscpSession::restore_from_id($parent)) {
                fatal("role mockup failed, cannot restore parent ID `%s'", $parent);
            }
            $auth = \Auth::autoload()->setID($parent);
            $this->setApnscpFunctionInterceptor(\apnscpFunctionInterceptor::factory($auth->getProfile()));
            $auth->authInfo(true);
        }
    }