I am currently controlling the login with a WebService in laravel using the following library: JWTAuth
Here is the method in laravel:
public function userAuth(Request $request)
{
$usuario = $request->input('usuario');
$password = $request->input('password');
$token = null;
try
{
if (!$token = JWTAuth::attempt(['usuario' => $usuario, 'password' => $password]))
{
$this->records = Array();
$this->message = 'Datos incorrectos';
$this->result = false;
$statusCode = 200;
$response = [
'message' => $this->message,
'result' => $this->result,
'records' => $this->records,
];
return response()->json($response, $statusCode);
}
else
{
$this->records = Auth::user();
$this->message = 'Autenticado exitosamente';
$this->result = true;
$statusCode = 200;
$response = [
'message' => $this->message,
'result' => $this->result,
'records' => $this->records,
];
return response()->json($response, $statusCode,compact('token'));
}
}
catch (JWTException $ex)
{
return response()->json(['error' => 'somthing_went_wrong'], 500);
}
}
If the user and password parameters are correct, assign a token:
{"message": "Autenticado exitosamente","result": true,"records": {
"id": 1,
"usuario": "admin",
"nombre": "Administrador",
"email": "[email protected]",
"idtipousuario": 1,
"telefono": 54203090,
"estado": 1,
"created_at": "2017-02-13 18:34:01",
"updated_at": "2017-02-13 18:34:01"}}
The WebService tests it in postman and the token returns it correctly in the header (Headers)
token →eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDhcL3Npc3RlbWFlcnBcL3B1YmxpY1wvd3NcL2xvZ2luSldUIiwiaWF0IjoxNDkxNzE1OTQwLCJleHAiOjE0OTE3MTk1NDAsIm5iZiI6MTQ5MTcxNTk0MCwianRpIjoiMDJkNDYwZWMxM2M1YjE5NDhjNjBmNzYxYWFmYTlmYzUifQ.lpAclBBP6QjH7b8E9ZnyQ09jrqVc4sS3gvo4LK0daAU
With Angularjs in the app.state.js file I have the following code where I control the public and private views in such a way that in the browser if the person is not logged in with their token, they will not be able to access any view other than the login:
.run(['$state', '$rootScope', function($state, $rootScope){
var token = 'token'; //Viene el Token
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
if (toState.module === 'private' && !token) {
console.log("Debe iniciar sesion");
$state.go('login');
e.preventDefault();
} else if (toState.module === 'public' && token) {
console.log("Contenido mostrado con credenciales correctas y token");
e.preventDefault();
$state.go('restricted.dashboard');
};
});
}
]);
The problem is that I do not know in what way I can use the token that comes in the WebService of the function run([])
and thus access the private routes if the token comes.