How can I mock a validation provider in Cakephp - cakephp

I have a validator that checks if a vat-number is correct. In order to do that it calls an external service. This external call slows the tests down and is unreliable, so I would like to mock it, but I don't understand how I could do it.
public function validationDefault(Validator $validator)
{
$validator->setProvider('vat', 'App\Model\Validation\VatValidation');
$validator->add('vat_no', 'isValidVatNo', [
'rule' => 'validVatNumber',
'provider' => 'vat',
]);
}
And this is the validation provider:
<?php
namespace App\Model\Validation;
use Cake\Core\Configure;
use Cake\Validation\Validation;
use VatNumberCheck\Utility\Model\VatNumberCheck;
class VatValidation extends Validation
{
public static function validVatNumber($check)
{
$vatNumberCheck = new VatNumberCheck();
try {
return $vatNumberCheck->check($check);
} catch (InternalErrorException $e) {
return false;
}
}
}

public function testValidationFail() {
$VatValidator = $this->getMockBuilder('Cake\Validation\Validator')
->setMethods(['validVatNumber'])
->getMock();
$VatValidator->expects($this->any())
->method('validVatNumber')
->will($this->returnValue(false));
$this->Users->getValidator()->setProvider('vat', $VatValidator);
$user = $this->Users->newEntity([
'vat_no' => 'asdf',
]);
$errors = $user->errors();
$this->assertArrayHasKey('vat_no', $errors);
}

Related

How to register afterMarshal in CakePHP 4.1

I noticed that there is new afterMarshal event in 4.1.
Where to put it? In Table model? And how?
I want to do some work with results every time it's loaded.
Thanks for help
For Encryption and Decryption through model in 'CAKEPHP 4'
public $encryptedFields = ['first_name','last_name'];
public function beforeSave($event, $entity, $options)
{
foreach($this->encryptedFields as $fieldName)
{ if($entity->has($fieldName))
{ $entity->set($fieldName, encodeBeforeSave($entity->get($fieldName)));}
} return true;
}
public function beforeFind( $event, $query, $options)
{ $query->formatResults(
function ($results)
{ return $results->map(function ($row){
foreach($this->encryptedFields as $fieldName)
{
if(isset($row[$fieldName]) && !empty($row[$fieldName]) )
{
$row[$fieldName] = decodeBeforefind($row[$fieldName]);
}
}
return $row;
});
}
);
}

Laravel + JWT Authentication not working on my side

am following up This tutorial to learn the jwt cool stuff. but when am testing the first bit of the server API with POSTMAN only the id,password fields are the one being inserted in the database. When I try to login with POSTMAN I get
MethodNotAllowedHttpException in RouteCollection.php line 218: from the server preview
my routes
Route::post('api/register', 'TokenAuthController#register');
Route::post('api/authenticate', 'TokenAuthController#authenticate');
Route::get('api/authenticate/user', 'TokenAuthController#getAuthenticatedUser');
my controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Hash;
class TokenAuthController extends Controller
{
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
try {
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
// if no errors are encountered we can return a JWT
return response()->json(compact('token'));
}
public function getAuthenticatedUser()
{
try {
if (!$user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
return response()->json(compact('user'));
}
public function register(Request $request)
{
$newuser = $request->all();
$password = Hash::make($request->input('password'));
$newuser['password'] = $password;
return User::create($newuser);
}
}
I don't know where am messing out this code.

FOSUserBundle: Success target after password reset according to roles

After the user did reset his password using the password reset of FOSUserBundle, by default he is redirected to the FOSUserProfile. I want to redirect to a different route according to their role. Is this possible and if yes, how?
I do this code but it redirect all kind of users
namespace Acme\UserBundle\EventListener;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Listener responsible to change the redirection at the end of the password resetting
*/
class PasswordResettingListener implements EventSubscriberInterface {
private $router;
public function __construct(UrlGeneratorInterface $router) {
$this->router = $router;
}
public static function getSubscribedEvents() {
return [
FOSUserEvents::RESETTING_RESET_SUCCESS => 'onPasswordResettingSuccess',
];
}
public function onPasswordResettingSuccess(FormEvent $event) {
$url = $this->router->generate('homepage');
$event->setResponse(new RedirectResponse($url));
}
}
And then I registering it as a service with
services:
acme_user.password_resetting:
class: Acme\UserBundle\EventListener\PasswordResettingListener
arguments: [ "#router" ]
tags:
- { name: kernel.event_subscriber }
Based on your version of Symfony you can choose one of the approaches described in: http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
For example you can use security.authorization_checker service:
Inject it into your service:
services:
acme_user.password_resetting:
class: Acme\UserBundle\EventListener\PasswordResettingListener
arguments: [ "#router", "#security.authorization_checker" ]
tags:
- { name: kernel.event_subscriber }
Then in your actual service:
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
/**
* Listener responsible to change the redirection at the end of the password resetting
*/
class PasswordResettingListener implements EventSubscriberInterface {
private $router;
private $authorizationChecker;
public function __construct(UrlGeneratorInterface $router, AuthorizationChecker $authorizationChecker) {
$this->authorizationChecker = $authorizationChecker;
$this->router = $router;
}
public static function getSubscribedEvents() {
return [
FOSUserEvents::RESETTING_RESET_SUCCESS => 'onPasswordResettingSuccess',
];
}
public function onPasswordResettingSuccess(FormEvent $event) {
//$url = $this->router->generate('homepage');
//$event->setResponse(new RedirectResponse($url));
if (false === $this->authorizationChecker->isGranted('ROLE_ADMIN')) {
// redirect somewhere
} else {
// redirect elsewhere
}
}
}

Codeigniter - Array dont work correctly

Whenever I call this function, I get the user_id correctly but the password isnt checked...
Model:
<?php
class Prometheus_model extends CI_Model {
var $tables = array(
'bots' => 'bots',
'users' => 'users'
);
function __construct() {
parent::__construct();
}
public function tablename($table = NULL) {
if(! isset($table)) return FALSE;
return $this->tables[$table];
}
public function get($table, $where = array(), $order = NULL) {
$this->db->where($where);
if(isset($order)) {
$this->db->order_by($order);
}
$q = $this->db->get_where($this->tablename($table),$where);
$result = $q->result_array();
// You should use $q->num_rows() to detect the number of returned rows
if($q->num_rows()) {
return $result[0];
}
return $result;
}
public function update($table, $where = array(), $data) {
$this->db->update($this->tablename($table),$data,$where);
return $this->db->affected_rows();
}
public function insert($table, $data) {
$this->db->insert($this->tablename($table),$data);
return $this->db->insert_id();
}
public function delete($table, $where = array()) {
$this->db->delete($this->tablename($table),$where);
return $this->db->affected_rows();
}
public function explicit($query) {
$q = $this->db->query($query);
if(is_object($q)) {
return $q->result_array();
} else {
return $q;
}
}
public function num_rows($table, $where = NULL) {
if(isset($where)){
$this->db->where($where);
}
$q = $this->db->get($table);
return $q->num_rows();
}
public function get_bot_data_by_hw_id($bot_hw_id) {
$q = $this->get('bots', array('bot_hw_id' => $bot_hw_id));
return $q;
}
public function check_user_data($user_incredials, $user_password) {
if($this->num_rows('users', array('user_name' => $user_incredials, 'user_password' => $this->encrypt->decode($user_password))) == 1){
$q = $this->get('users', array('user_name' => $this->security->xss_clean($user_incredials)));
return $q['user_id'];
}
return FALSE;
}
}
?>
My function-calling at the controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
public function index(){
if($this->input->post('user_login')){
var_dump($this->prometheus_model->check_user_data($this->input->post('user_incredials'), $this->input->post('user_password')));
}
$this->load->view('login_index');
}
}
How can i fixx this ?
In your check_user_data() method you are using
if($this->num_rows('users', array('user_name' => $user_incredials, 'user_password' => $this->encrypt->decode($user_password))) == 1)
I think (logically) following code
$this->encrypt->decode($user_password)
should be
$this->encrypt->encode($user_password)
because, you are calling num_rows() method and it is
public function num_rows($table, $where = NULL)
{
if(isset($where)){
$this->db->where($where);
}
$q = $this->db->get($table);
return $q->num_rows();
}
which is actually querying the data base something like, for example,
select * from USERS where user_name = 'heera' and password = decode('abcde12345')
In this case, the password you are trying to match is need to be encrypted using encode (not decode) method, because the user has given you a non-encrypted (plain) password and the password saved in the database is already encrypted, so encode the plain password using encode method before you query the database to match with already encoded passwords.

Cakephp Render XML errors in custom Exception.renderer

Based on the information here: Using a custom renderer with Exception.renderer to handle application exceptions
I'm creating a custom error renderer that renders in XML format.
Below is the sample code for the render function in app/Lib/Error/AppExceptionRenderer:
public function render() {
if (isset($this->controller->request->params['xml'])) {
$this->controller->viewClass = "MyXml";
$error = array(
'app' => array(
'error' => 'An unexpected error has occured.'
)
);
$this->controller->set('error', $error);
$this->controller->set('_serialize', 'error');
}
}
However nothing gets returned. I have done some echo within the if condition and that shows.
So is it because the viewClass is not initialized while its in AppExceptionRenderer::render() stage?
There were no errors either.
"MyXml" viewClass works perfectly in normal controllers too.
So apparently I was missing the render and send methods.
Here's the full working example.
<?php
class AppExceptionRenderer extends ExceptionRenderer {
public function __construct($exception) {
parent::__construct($exception);
}
public function render() {
// Handle errors
if (isset($this->controller->request->params['xml'])) {
Cakelog::error($this->error->getMessage());
$this->controller->viewClass = "MyXml";
$error = array(
'app' => array(
'error' => 'An illegal operation has been detected.'
)
);
$this->controller->set('error', $error);
$this->controller->set('_serialize', 'error');
$cakeResponseObject = $this->controller->render();
$this->controller->response->send($cakeResponseObject);
} else {
if ($this->method) {
call_user_func_array(array($this, $this->method), array($this->error));
}
}
}
}

Resources