Trouble with laravel (NotFoundHttpException) - php

I'm getting this error.
Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException
I have a login view with a form, I validate the form with ajax, without a problem. When I try to return a view once I've successfuly logged in.
if ($validation->fails()){
return Response::json(array( 'success' => false, 'errors' => $validation->getMessageBag()->toArray() ));
}else if(Auth::attempt($loginData)){
$usuario=Usuario::find(Input::get('rut'));
return View::make('logged')->with(array('nombre' => $usuario->primer_nombre.' '.$usuario->apellido_paterno.' '.$usuario->apellido_materno,
'rut' => $usuario->id_usuario,
'tipo' => $usuario->id_tipo));
}else{ return Response::json(array( 'exists' => false, 'message' => 'El usuario no existe o la contraseña es inválida.' )); }
I guess the problem is in the last else statement,I get an 404 error.

This is the route:
Route::post('ingresar','LoginController#login');
The action on the form is ingresar then I use the login method in LoginController
public function login(){
if(Request::ajax()){
//validamos el formulario.
$loginData = array(
'id_usuario' => Input::get('rut'),
'password' => Input::get('password')
);
$rules = array(
'rut' => 'required',
'password' => 'required',
);
$messages = array(
'required' => 'El campo :attribute es obligatorio.',
);
$validation = Validator::make(Input::all(), $rules, $messages);
if ($validation->fails()){
return Response::json(array(
'success' => false,
'errors' => $validation->getMessageBag()->toArray()
));
}else if(Auth::attempt($loginData)){
$usuario=Usuario::find(Input::get('rut'));
return View::make('logged')->with(array('nombre' => $usuario->primer_nombre.' '.$usuario->apellido_paterno.' '.$usuario->apellido_materno,
'rut' => $usuario->id_usuario,
'tipo' => $usuario->id_tipo));
}else{
return Response::json(array(
'exists' => false,
'message' => 'El usuario no existe o la contraseña es inválida.'
));
}
}
}

Related

Why do I get 419 error on login made in api.php?

I've been researching for all internet why do I get this error when I try to POST on the login api route:
Status 419
unknown status
Version HTTP/1.1
Transferred 6.94 KB (6.46 KB size)
Referrer Policy strict-origin-when-cross-origin
This is what I have on my UserController.php:
public function userSignUp(Request $request) {
$validator = Validator::make($request->all(), [
"name" => "required",
"email" => "required|email",
"password" => "required",
]);
if($validator->fails()) {
return response()->json(["status" => "failed", "message" => "validation_error", "errors" => $validator->errors()]);
}
$userDataArray = array(
"name" => $request->name,
"email" => $request->email,
"password" => md5($request->password),
);
$user_status = User::where("email", $request->email)->first();
if(!is_null($user_status)) {
return response()->json(["status" => "failed", "success" => false, "message" => "Ooops! Email ya registrado anteriormente"]);
}
$user = User::create($userDataArray);
if(!is_null($user)) {
return response()->json(["status" => $this->status_code, "success" => true, "message" => "Registro completado correctamente", "data" => $user]);
}
else {
return response()->json(["status" => "failed", "success" => false, "message" => "Fallo al registrar"]);
}
}
// ------------ [ User Login ] -------------------
public function userLogin(Request $request) {
$attr = $request->validate([
'email' => 'required|string|email|',
'password' => 'required|string|min:6'
]);
if (!Auth::attempt($attr)) {
return response()->json([
'message' => 'Invalid login details'
], 401);
}
$token = auth()->user()->createToken('auth_token')->plainTextToken;
$user = auth()->user();
$respon = [
'status' => 'success',
'msg' => 'Login successfully',
'content' => [
'status_code' => 200,
'access_token' => $token,
'token_type' => 'Bearer',
'user_name' => $user->name,
'user_email' => $user->email,
'user_id' => $user->id,
]
];
return response()->json($respon, 200);
}
And I have these routes on api.php:
Route::post("login", [UserController::class, "userLogin"]);
Route::post("register", [UserController::class, "userSignUp"]);
These routes works perfectly on the RESTED add-on on Firefox. This is on api.php, I shouldn't have any problem with csrf token.

How to get validation when saving multiple records with newEntities() CakePhp 3.x?

For some reason I am not getting any validation errors when saving multiple records. I can grab the errors using print_r($user->errors()); but they are not automatically injected into the form like when adding a single user. According to the docs "Validating entities before saving is done automatically when using the newEntity(), newEntities()." I am not sure if there is a specific way to set up the form to make it return validation for multiple records or if you have to do special validation in the model for inputs that have indexes or what?
view:
<div class="page-wrap">
<div class="form">
<h1>Join Now</h1>
<?php
echo $this->Form->create(null, ['controller' => 'users', 'action' => 'addMultiple']);
echo $this->Form->input('1.full_name');
echo $this->Form->input('1.username');
echo $this->Form->input('1.email');
echo $this->Form->input('1.password');
echo $this->Form->input('1.password_confirmation', array('type' => 'password'));
if ($current_user['role'] === 1 && isset($logged_in)) {
echo $this->Form->input('1.role', ['type' => 'select', 'options' => ['1' => 'Admin', '2' => 'Editor', '3' => 'Author', '4' => 'Reader'], 'default' => '4']);
}
echo $this->Form->input('2.full_name');
echo $this->Form->input('2.username');
echo $this->Form->input('2.email');
echo $this->Form->input('2.password');
echo $this->Form->input('2.password_confirmation', array('type' => 'password'));
if ($current_user['role'] === 1 && isset($logged_in)) {
echo $this->Form->input('2.role', ['type' => 'select', 'options' => ['1' => 'Admin', '2' => 'Editor', '3' => 'Author', '4' => 'Reader'], 'default' => '4']);
}
echo $this->Form->button(__('Sign Up'));
echo $this->Form->end();
?>
</div>
</div>
Controller:
public function addMultiple()
{
$users = $this->Users->newEntities($this->request->data());
if ($this->request->is('post')) {
foreach($users as $user) {
if( empty($this->request->session()->read('Auth.User')) || $this->request->session()->read('Auth.User.role') !== 1 ) {
$user->role = 4;
}
if ($this->Users->save($user)) {
$this->Flash->success(__('You have been added.'));
} else {
$this->Flash->error(__('You could not be added. Please, try again.'));
}
}
}
}
Table:
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('MembershipOrders', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->hasMany('MembershipOrders', [
'foreignKey' => 'affiliate_token',
'joinType' => 'INNER'
]);
}
public function validationDefault(Validator $validator)
{
$validator
->notEmpty('full_name', 'A full name is required')
->add('full_name', 'notBlank', [
'rule' => 'notBlank',
'message' => __('A full name is required'),
]);
$validator
->notEmpty('username', 'A username is required')
->add('username', [
'notBlank' => [
'rule' => 'notBlank',
'message' => __('A username is required'),
]
]);
$validator
->notEmpty('email', 'An email is required')
->add('email', [
'notBlank' => [
'rule' => 'notBlank',
'message' => __('A full name is required'),
],
'unique' => [
'rule' => 'validateUnique',
'provider' => 'table',
'message' => __('That email has already been used.'),
]
]);
$validator
->notEmpty('old_password', 'You must enter your old password is required')
->add('old_password', 'notBlank', [
'rule' => 'notBlank',
'message' => __('Your old password is required'),
]);
$validator
->notEmpty('password', 'A password is required')
->add('password', 'notBlank', [
'rule' => 'notBlank',
'message' => __('A full name is required'),
]);
$validator
->notEmpty('password_confirmation', 'Password confirmation is required')
->add('password_confirmation',
'comareWith', [
'rule' => ['compareWith', 'password'],
'message' => 'Passwords do not match.'
]);
$validator
->notEmpty('role', 'A role is required')
->add('role', 'inList', [
'rule' => ['inList', ['1', '2', '3', '4']],
'message' => 'Please enter a valid role'
]);
return $validator;
}
You can use 'addNestedMany()' : http://book.cakephp.org/3.0/en/core-libraries/validation.html#nesting-validators
You have to pass the entity object to the Form->create(... function, instead of passing nullas the following:
echo $this->Form->create($user, .....

CakePHP 3- Validation for changing password don't work

I am making a app with cakephp 3, now i am tring to make a function that allow users change their passwords. The problem is that the validation of the password doesn't work. I don't know if i am doing correctly.
Here is the chage_password.ctp file:
<div class="users form large-9 medium-9 columns">
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Actualice su contraseña') ?></legend>
<?= $this->Form->input('password1',['type'=>'password' ,'label'=>'Ingrese Contraseña']) ?>
<?= $this->Form->input('password2',['type' => 'password' , 'label'=>'Reescriba su Contraseña'])?>
</fieldset>
<?= $this->Form->button(__('Agregar')) ?>
<?= $this->Form->end() ?>
Here is the changePassword function in the UsersControler.php:
public function changePassword($id)
{
$user_data=$this->Users->get($id);
if (!empty($this->request->data)) {
$user = $this->Users->patchEntity($user_data, [
'password' => $this->request->data['password1']
],
['validate' => 'password']
);
$time = Time::now();
$user->set('fecha_cambio_password',$time);
if ($this->Users->save($user)) {
$this->Flash->success('Contraseña Actualizada');
$this->redirect('/users/login');
} else {
debug($user);die;
$this->Flash->error('No se pudo actualizar la contraseña!');
}
}
}
And finally the validation in UsersTable.php:
public function validationPassword(Validator $validator)
{
$validator
->add('password1', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'El largo minimo es 6',
]
])
->add('password1',[
'match'=>[
'rule'=> ['compareWith','password2'],
'message'=>'Los campos no coinciden',
]
])
->notEmpty('password1');
$validator
->add('password2', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'El largo minimo es 6',
]
])
->add('password2',[
'match'=>[
'rule'=> ['compareWith','password1'],
'message'=>'Los campos no coinciden',
]
])
->notEmpty('password2');
return $validator;
}
I found the solution!
You need to pass the password fields in the 2nd argument of the patchEntity() method
$user = $this->Users->patchEntity($user, [
'old_password' => $this->request->data['old_password'],
'password' => $this->request->data['password1'],
'password1' => $this->request->data['password1'],
'password2' => $this->request->data['password2']
],
['validate' => 'password']
);
In order to check the old password you need to modify your current validator as follows:
public function validationPassword(Validator $validator )
{
$validator
->add('old_password','custom',[
'rule'=> function($value, $context){
$user = $this->get($context['data']['id']);
if ($user) {
if ((new DefaultPasswordHasher)->check($value, $user->password)) {
return true;
}
}
return false;
},
'message'=>'The old password is not correct!',
])
->notEmpty('old_password');
$validator
->add('password1', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'Min value is 6',
]
])
->add('password1',[
'match'=>[
'rule'=> ['compareWith','password2'],
'message'=>'Los campos no coinciden',
]
])
->notEmpty('password1');
$validator
->add('password2', [
'length' => [
'rule' => ['minLength', 6],
'message' => 'El largo minimo es 6',
]
])
->add('password2',[
'match'=>[
'rule'=> ['compareWith','password1'],
'message'=>'Los campos no coinciden',
]
])
->notEmpty('password2');
return $validator;
}
Cheers!

CakePHP's login system

I'm trying to write an application in CakePHP. I ran into a problem with it's login system I need help with.
I set up a database table called users containing the fields id, username and password. Password is of type varchar and its length is 50.
My User.php model looks like this:
<?php
App::uses('AppModel', 'Model');
class User extends AppModel {
public $validate = array(
'id' => array(
'rule' => 'blank',
'on' => 'create'
),
'username' => array(
'alphaNumeric' => array(
'required' => true,
'rule' => 'alphaNumeric',
'message' => 'Alleen letters en cijfers zijn toegestaan'
),
'between' => array(
'rule' => array('between', 5, 20),
'message' => 'Gebruikersnaam moet tussen de 5 en 20 tekens zijn'
),
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Dit veld mag niet leeg zijn'
)
),
'password' => array(
'between' => array(
'rule' => array('between', 5, 50),
'message' => 'Wachtwoord moet tussen de 5 en 50 tekens zijn',
'required' => true
),
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Dit veld mag niet leeg zijn'
)
)
);
public function beforeSave($options = array()) {
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
}
return true;
}
}
?>
In my UsersController.php I have the login function like this:
//login function. Logs in a user
public function login() {
//if already logged in
if ($this->Session->check('Auth.user')) {
$this->redirect(array('action' => 'index'));
}
$user = $this->User->findById(2);
debug($user);
if ($this->request->is('post')) {
debug($this->request->data['User']['password']);
debug($this->request->data);
debug(AuthComponent::password($this->request->data['User']['password']));
debug($user['User']['password']);
if ($user['User']['password'] == AuthComponent::password($this->request->data['User']['password'])) {
echo 'user pw == hashed request data pw <br />';
}
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Gebruikersnaam of wachtwoord is onjuist.'));
}
}
}
As you can see, I've added a lot of debugging information. The check that checks if the password hashed is the same as the one in the database even works.
This is my Auth component in my AppController.php:
'Auth' => array(
'authenticate' => array('Form'),
'loginAction' => array(
'controller' => 'Users',
'action' => 'login'
),
'loginRedirect' => array(
'controller' => 'Users',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'Users',
'action' => 'login'
),
'authError' => 'U moet ingelogd zijn om deze pagina te bezoeken.'
)
The problem is, that everything seems to be correct, yet it gives me the error message of incorrect username or password every time. I even tried not encrypting the password at all, but that didn't work either. What am I doing wrong and how do I fix it?
P.S: I'm not really experienced with cakephp, so I'm sorry if I made an obvious mistake. I used the tutorial on the cakephp website.
Edit:
So I was changing some of the debug prints to use the method debug(), and I also deleted a certain part from the auth component, which had something to do with passwordhasher. I just tried to login again and now the login completely works. I guess that part is what was causing the problem to exist.
This is the code I had:
'Form' => array(
'passwordHasher' => array(
'className' => 'Simple',
'hashType' => 'sha256'
)
)
I changed this to just 'Form' and now it works.
Basically, by using:
'authenticate' => array(
'Form' => array
'passwordHasher' => array(
'className' => 'Simple',
'hashType' => 'sha256'
)
)
),
you were telling the AuthComponent::login() method to use the sha256 hashType when doing the password check in your login action.
However, in the User::beforeSave() callback, you were using the old AuthComponent::password() method to hash and store the password in the database. This method does not accept a hashType parameter and defaults the hashType to sha1. If you do want to proceed with sha256 and the code above, change your beforeSave() method to use the new SimplePasswordHasher as shown here. (I am assuming you are on Cake 2.4.x)

Password validation in symfony forms

I'm new to this and I have a problem lares from making a long time, I have the following code.
<?php
class RegistroUsuariosForm extends sfForm {
public function configure() {
$this->setWidgets(array(
'password1' => new sfWidgetFormInputPassword(),
'password2' => new sfWidgetFormInputPassword(),
'avatar' => new sfWidgetFormInputFile(),
));
$this->widgetSchema->setLabels(array(
'password1' => 'Password',
'password2' => 'Repetir Contraseña',
'avatar' => 'Imagen a mostrar'
));
$this->widgetSchema->setNameFormat('RegUsuario[%s]');
$this->validatorSchema->setPostValidator(new sfValidatorSchemaCompare('password1', '==', 'password2',
array(),
array('invalid' => 'Las contraseñas no son iguales')));
$this->setValidators(array(
'password1' => new sfValidatorString(array('min_length' => 4),
array('required' => 'Campo obligatorio',
'min_length' => 'Minimo %min_length% caracteres.',)),
'password2' => new sfValidatorString(array('min_length' => 4),
array('required' => 'Campo obligatorio',
'min_length' => 'Minimo %min_length% caracteres.',)),
'avatar' => new sfValidatorFile(
array(
'required' => false,
'max_size' => (1048576 * 2),
'mime_types' => 'web_images',
),
array(
'required' => 'Campo obligatorio',
'max_size' => 'El archivo es muy grande (máximo de 2Mb).',
'mime_types' => 'El tipo de archivo es invalido (%mime_type%).',
'partial' => 'El archivo subido fue sólo parcialmente cargado.',
'no_tmp_dir' => 'Falta la carpeta temporal.',
'cant_write' => 'No se pudo guardar el archivo en el servidor.',
'extension' => 'De carga del archivo se detuvo, por extensión.'
)),
));
}
}
public function executeActivarinvitacion(sfWebRequest $request) {
$key = $request->getParameter('key');
$this->formulario = new RegistroUsuariosForm();
if (($dato = Invitaciones::TraerDatosDeInvitacion($key))) {
$this->key = $key;
if ($request->isMethod('post')) {
$RegUsuario = $request->getParameter('RegUsuario');
$Avatar = $request->getFiles('RegUsuario');
$this->formulario = new RegistroUsuariosForm();
$this->formulario->bind($RegUsuario, $Avatar);
if ($this->formulario->isValid()) {
echo $RegUsuario['password1'];
echo ' - '.$RegUsuario['password2'];
exit();
}
}
} else {
$this->forward404();
}
$this->usuario = $dato['usuario'];
$this->correo = $dato['correo'];
}
The validation of the password just does not work, does anyone know what?
sfForm->setValidators() internally re-creates a new validatorSchema, so your previously set form validator is just cleared. Just put the call to $this->validatorSchema->setPostValidator() below the rest and it should work.

Categories