
The code to the video
I am trying out a new format of supplementing my videos with the relevant code-pieces and publishing them as an article. Please let me know if this is helpful or annoying. TY
UserModel.php
changes to the default outgoing method
/** * @param array $transactionResult * @return array */privatestaticfunctionoutgoing(array$transactionResult):array{if(isset($transactionResult['password'])){unset($transactionResult['password']);}elseif(!empty($transactionResult)){foreach($transactionResultas$i=>$single){$transactionResult[$i]=self::outgoing($single);}}return$transactionResult;}
changes to the default incoming method
/** * @param array $transactionResult * @return array */privatestaticfunctionoutgoing(array$transactionResult):array{if(isset($transactionResult['password'])){unset($transactionResult['password']);}elseif(!empty($transactionResult)){foreach($transactionResultas$i=>$single){$transactionResult[$i]=self::outgoing($single);}}return$transactionResult;}
the login method
/** * @throws RouteException */staticfunctionlogin($credentials){$foundUser=self::$db->easy('user.id user.password',['email'=>$credentials['email']]);if(empty($foundUser)||!password_verify($credentials['password'],$foundUser[0]['password'])){thrownewRouteException('Unauthorized',401);}returnself::get($foundUser[0]['id']);}
AuthController.php
The final version of our authorization controller.
NOTE: In the video, I forgot to address how my IDE automatically includes use-commands. Make sure you include those.
<?phpnamespaceNeoan3\Component\Auth;useNeoan3\Core\RouteException;useNeoan3\Frame\Demo;useNeoan3\Model\User\UserModel;useNeoan3\Model\User\UserModelWrapper;useNeoan3\Provider\Auth\Authorization;useNeoan3\Provider\Model\InitModel;/** * Class AuthController * @package Neoan3\Component\Auth * * Generated by neoan3-cli for neoan3 v3.* */classAuthControllerextendsDemo{/** * GET: api.v1/auth * GET: api.v1/auth/{id} * GET: api.v1/auth?{query-string} * @return array */#[Authorization('restrict',['admin'])]functiongetAuth():array{return$this->authObject->getPayload();}/** * POST: api.v1/auth * @param string $mode * @param array $body * @return array * @throws \Neoan3\Core\RouteException */#[InitModel(UserModel::class)]functionpostAuth(string$mode="Login",array$body=[]):array{if($mode==='Register'){// create user$newUser=newUserModelWrapper($body);try{$newUser->store()->rehydrate();$user=$newUser->toArray();}catch(\Exception$e){thrownewRouteException('Malformed input',406);}}else{// try login$user=UserModel::login($body);}$authObject=$this->Auth->assign($user['id'],['all'],['email'=>$user['email']]);return['token'=>$authObject->getToken()];}}
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse