Cuando intento hacer el login desde el navegador, me devuelve el mensaje de error "login failed" (que lo arroja desde dentro del servicio de JwtAuth), lo extraño es que si lo hago desde postman con las mismas credenciales, me loguea correctamente devolviendo el token. Que podria estar mal? el código lo he revisado varias veces.
He hecho pruebas y he conseguido que me devuelva el token poniendole la contraseña encriptada, pero si le pongo admin (que es la contraseña que le puse al usuario) sin mas: "login failed".
Añado fotos de mi código, porque la verdad no veo el error por ningún lado, y el fallo esta en que no debe de encriptar la contraseña para compararla con la que hay en la base de datos, porque no tengo errores en consola ni nada, es extrañisimo esto, o me comi algo o no lo entiendo...
JwtAuth service:
<?php
namespace AppBundle\Services;
use Firebase\JWT\JWT;
class JwtAuth{
public $manager;
public $key;
public function __construct($manager){
$this-> manager = $manager;
$this-> key = 'soytuclavesecreta12344321';
}
public function signup($email,$password, $getHash = null){
//Buscamos en la base de datos el usuario con findOneBy
$user = $this->manager->getRepository('BackendBundle:User')->findOneBy(array(
"email" => $email,
"password" => $password
));
$signup = false;
if(is_object($user)){
$signup = true;
}
if($signup ==true){
//generar token
$token = array(
'sub' => $user->getId(),
'email' => $user->getEmail(),
'name' => $user->getName(),
'surname' => $user->getSurname(),
'iat' => time(),
'exp' => time()+(7*24*60*60)
);
$jwt = JWT::encode($token, $this->key, 'HS256');
$decoded = JWT::decode($jwt, $this->key, array('HS256'));
if($getHash == null){
$data = $jwt;
}else{
$data = $decoded;
}
}else{
$data = array(
'status' => 'error',
'data'=> 'Login failed'
);
}
return $data;
}
public function checkToken($jwt,$getIdentity = false){
$auth = false;
try{
$decoded = JWT::decode($jwt, $this->key, array('HS256'));
}catch(\UnexpectedValueException $e){
$auth = false;
}catch(\DomainException $e){
$auth = false;
}
if(is_object($decoded) && isset($decoded -> sub)){
$auth = true;
}else{
$auth = false;
}
if($getIdentity == false){
return $auth;
}else{
return $decoded;
}
}
}
login component:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import {UserService} from '../services/user.service';
@Component({
selector: 'login',
templateUrl: '../views/login.html',
providers: [UserService]
})
export class LoginComponent implements OnInit{
public title: string;
public user;
public identity;
public token;
constructor(
private _route: ActivatedRoute,
private _router: Router,
private _userService: UserService
){
this.title = 'Identifícate';
this.user = {
"email":"",
"password":"",
"gethash": "false"
};
}
ngOnInit(){
console.log('El componente login.component ha sido cargado');
console.log(JSON.parse(localStorage.getItem('identity')));
this.logout();
this.redirectIfIdentity();
}
onSubmit(){
console.log(this.user);
this._userService.signup(this.user).subscribe(
response => {
this.identity = response;
if(this.identity.length <= 1){
console.log('Error en el servidor');
}{
if(!this.identity.status){
localStorage.setItem('identity', JSON.stringify(this.identity));
//get token
this.user.getHash=null;
this._userService.signup(this.user).subscribe(
response => {
this.token = response;
if(this.identity.length <= 1){
console.log('Error en el servidor');
}{
if(this.identity.status){
localStorage.setItem('token', JSON.stringify(this.identity));
//window.location.href= "/";
}
}
},
error => {
console.log(<any>error)
}
);
}
}
},
error => {
console.log(<any>error)
}
);
}
user service:
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import "rxjs/add/operator/map";
import { Observable } from 'rxjs/Observable';
import { GLOBAL } from './global';
@Injectable()
export class UserService{
public url: string;
public identity;
public token;
constructor(private _http: Http){
this.url = GLOBAL.url;
}
signup(user_to_login){
let json = JSON.stringify(user_to_login);
let params = "json="+json;
let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
return this._http.post(this.url+'/login', params, {headers: headers})
.map(res => res.json());
}
login html:
<div class="col-md-12">
<h3>{{title}}</h3>
<div class="identity_alert alert alert-success" *ngIf= "identity && identity.sub">
Te has logueado correctamente Bienvenido {{identity.email}}
</div>
<div class="identity_alert alert alert-danger" *ngIf= "identity && identity.data">
No te has logueado correctamente
</div>
<form #loginForm="ngForm" (ngSubmit)="onSubmit()" class = "col-md-7 no-padding">
<p>
<label>Email:</label>
<input type="email" class="form-control" name="email" #email="ngModel" [(ngModel)]="user.email" required/>
<span *ngIf="!email.valid && email.touched">El email no es válido</span>
</p>
<p>
<label>Contraseña:</label>
<input type="password" class="form-control" name="password" #password="ngModel" [(ngModel)]="user.password"
required/>
<span *ngIf="!password.valid && password.touched">La contraseña no es válida</span>
</p>
<input type="submit" value="Entrar" class="btn btn-primary"[disabled]="!loginForm.form.valid"/>
</form>
</div>
Adjunto tambien imagenes del navegador:
Antes de hacer el login:
Logueando con contraseña normal:
Logueando con la contraseña encriptada de la bd:
Muchas gracias anticipadas.
Edito: Se me olvido poner el codigo del Controlador que se encarga de la encriptacion de la contraseña:
class DefaultController extends Controller
{
public function indexAction(Request $request){
// replace this example code with whatever you need
return $this->render('default/index.html.twig', [
'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
]);
}
public function loginAction(Request $request){
$helpers = $this->get(Helpers::class);
//Recibir json por POST
$json = $request->get('json', null);
//Arrray a devolver
$data = array(
'status' => 'error',
'data' => 'Send json via POST !'
);
if($json != null){
//Convertimos json a un objeto de php
$params = json_decode($json);
$email = (isset($params->email)) ? $params->email : null;
$password = (isset($params->password)) ? $params->password : null;
$getHash = (isset($params->getHash)) ? $params->getHash : null;
$emailConstraint = new Assert\Email();
$emailConstraint->message = "This email is not valid";
$validate_email = $this->get("validator")->validate($email, $emailConstraint);
//Cifrar la contraseña
$pwd = hash('sha256',$password);
if($email != null && count($validate_email) == 0 && $password != null){
$jwt_auth = $this->get(JwtAuth::class);
if($getHash == null || $getHash ==false){
$signup = $jwt_auth->signup($email, $password);
}else{
$signup = $jwt_auth->signup($email, $password, true);
}
return $this->json($signup);
}else{
$data = array(
'status' => 'Error',
'data' => 'Email or password incorrect'
);
}
}
return $helpers->json($data);
}