Created
May 2, 2017 20:25
-
-
Save cebe/ee7b62786d939ce73d237bde603cae3e to your computer and use it in GitHub Desktop.
allow basic auth for users not logged in
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SomeController extends yii\web\Controller | |
{ | |
/** | |
* @var array actions to authenticate via basicAuth if not logged in. | |
*/ | |
public $basicAuthActions = []; | |
/** | |
* Allow login via HTTP basic auth if iCal calendar url is used in Thunderbird or similar applications | |
*/ | |
public function beforeAction($action) | |
{ | |
// this has to come before calling the parent implementation | |
// so that we have a user instance to run access checks against | |
if (Yii::$app->user->isGuest && in_array($action->id, $this->basicAuthActions)) { | |
Yii::$app->user->enableSession = false; | |
$auth = new HttpBasicAuth(); | |
$auth->auth = function($username, $password) { | |
$user = User::findIdentityByName($username); | |
if (!$user || !$user->validatePassword($password)) { | |
return null; | |
} | |
return $user; | |
}; | |
$auth->beforeAction($action); | |
} | |
return parent::beforeAction($action); | |
} | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment