First things first: This is quite similar to this, yet different.
I'm trying to get authentication/login for Element-API for Craft 3 to work. Meaning I would like to restrict access to certain endpoints that require the client to be logged in and also (essentially, this is the question) have a way to login via the API (or a different way, but preferably over the API).
This is what I got so far:
<?php
use Craft;
use craft\elements\Entry;
use craft\helpers\UrlHelper;
function requireLogin(){
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With");
if (!Craft::$app->user->isGuest) {
// you are authenticated
} else {
// check params
$loginName = Craft::$app->request->getQueryParam('loginName');
$password = Craft::$app->request->getQueryParam('password');
if (Craft::$app->user->login($loginName, $password)) {
// login success
$user = Craft::$app->userSession->getUser();
} else {
// login fails echo message
$errorCode = Craft::$app->userSession->getLoginErrorCode();
$errorMessage = Craft::$app->userSession->getLoginErrorMessage($errorCode, $loginName);
Craft::$app->end(JsonHelper::encode(array('data' => array( ['status' => 'error','message' =>'wrong login'] ))));
}
}
}
return [
...
using requireLogin();
inside the transformer
of the given endpoint.
Most of this is copied from the before mentioned, related link. But as I'm no PHP developer I kind of struggle getting it to work. The error I get is the following with this code:
Argument 1 passed to yii\web\User::login() must be an instance of yii\web\IdentityInterface, null given as a result of
Craft::$app->user->login($loginName, $password)
I do understand whats happening and am capable of reading the error, but I'm not very familiar with yii
, nor PHP. If someone could point out what needs to be done, which problems also might occur of if I'm on the wrong track or even post a working solution, I would be very grateful.