This is my rest.php file
<?php
chdir('../../..');
require_once 'SugarWebServiceImplv4_1_custom.php';
$webservice_path = 'service/core/SugarRestService.php';
$webservice_class = 'SugarRestService';
$webservice_impl_class = 'SugarWebServiceImplv4_1_custom';
$registry_path = 'custom/service/v4_1_custom/registry.php';
$registry_class = 'registry_v4_1_custom';
$location = 'custom/service/v4_1_custom/rest.php';
require_once 'service/core/webservice.php';
This is my SugarWebServiceImplv4_1_custom.php file where i have written custom methods
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
if(!defined('sugarEntry')){
define('sugarEntry', true);
}
require_once 'service/v4_1/SugarWebServiceImplv4_1.php';
class SugarWebServiceImplv4_1_custom extends SugarWebServiceImplv4_1
{
public function custom_test($username)
{
$arr = array ('a'=>$username,'b'=>22,'c'=>32,'d'=>44,'e'=>55);
return json_encode($arr);
die;
}
}
This is my registry.php file where i have registered my custom method
<?php
require_once 'service/v4_1/registry.php';
class registry_v4_1_custom extends registry_v4_1
{
protected function registerFunction()
{
parent::registerFunction();
$this->serviceClass->registerFunction('custom_test',
array(
'username'=>'xsd:string),
array(
'return'=>'tns:get_array')
);
}
}
The problem is when i am passing the the data through get method Like this
http://www.example.com/custom/service/v4_1_custom/rest.php?method=custom_test&input_type=json&response_type=json&rest_data=
{"username":"some
username"}
i am getting the result but i dont know how to pass it through post method through IOS application. I tried to pass it but I am not getting anything in username.
I checked the response through curl as well , it is working using curl, But i have to connect it to IOS.
Help will be appreciated
Actually we are building a Hybrid app for IOS using Angular 5 and Ionic 3
Here is the code
auth-services.ts
public login(credentials){
if(credentials.username === null || credentials.password === null){
return Observable.throw("Please enter credentials");
} else {
this.username1 = credentials.username;
this.password1 = credentials.password;
return Observable.create(observer =>{
// At this point make a request to your backend to make a real check!
this.method1 = "custom_test";
this.inputType = "JSON";
this.responseType = "JSON";
this.encryptionValue = "PLAIN";
this.bodyData = {}; //get method calling
console.log(JSON.stringify(this.bodyData));
//Sending the Username and Password to the Web Server for authentication. Change the URL Get the response message
this.servicesProvider.restApi("post","http://exmaple.com/custom/service/v4_1_custom/rest.php",this.bodyData).then(
(res) => {
console.log("Response stringify :",JSON.stringify(res));
console.log("Response parse :", res);
console.log("Status :",res.status);
this.response = res.status; //TODO: Replace res.username with res.message as we have to check for user exist or not.
if(this.response == "success out") {
this.success = true;
this.storage.set("status",this.response); //Username value stored in localstorage
this.currentUser = new User('Simon', 'saimon#devdactic.com');
observer.next(this.success);
observer.complete();
} else {
this.success = false;
observer.next(this.success);
observer.complete();
}
}
);
}
Here is the services.ts file. this is a common rest api file for sending rest api requests.
restApi(method,url,data) {
console.log("inside restApi");
switch(method) {
case 'post' : {
console.log("Inside Post Method");
/*
return this.httpClient.post(url,data)
.subscribe(
(res:any) => {
console.log("POST response below");
console.log(res.username);
this.responseData = JSON.stringify(res);
console.log("ResponseData Value");
console.log(this.responseData);
return this.responseData;
}); */
let headers = new Headers({'content-type':'application/json'});
let options = new RequestOptions({ headers:this.headers });
this.responseFromFunction = this.http.post(url,data).toPromise()
.then(this.extractData)
.catch(this.handleError);
break;
}
case 'get' : {
console.log("Inside Get Method");
let headers = new Headers({'content-type':'application/json'});
let options = new RequestOptions({ headers:this.headers });
this.responseFromFunction = this.http.get(url, options).toPromise()
.then(this.extractData)
.catch(this.handleError);
break;
}
case 'put' : {
console.log("Inside Put Method");
this.responseFromFunction = this.httpClient.put(url,data)
.subscribe((res:any) => {
console.log(res);
});
break;
}
case 'delete' : {
console.log("Inside Delete Method");
this.responseFromFunction = this.httpClient.delete(url)
.subscribe((res:any) => {
console.log(res);
});
break;
}
default : {
this.responseFromFunction = {"message":"error"};
console.log("Unknow Method Entered. Or write method in small lowercase only");
// return "Invalid Method";
}
}
console.log("Outside switch case");
console.log(this.responseFromFunction);
return this.responseFromFunction;
}
private extractData(res: Response) {
// console.log("Resp :", res.json());
// console.log("Stringy :", JSON.stringify(res));
return res.json();
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
here is the postman response
I am not getting how to pass username in rest_data
IF you are using Angular 5 then :
Documentation read it
Making a POST request
Apps often POST data to a server. They POST when submitting a form. In the following example, the HeroesService posts when adding a hero to the database.
app/heroes/heroes.service.ts (addHero)
/** POST: add a new hero to the database */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
catchError(this.handleError('addHero', hero))
);
}
The HttpClient.post() method is similar to get() in that it has a type parameter (you're expecting the server to return the new hero) and it takes a resource URL.
It takes two more parameters:
hero - the data to POST in the body of the request.
`httpOptions` - the method options which, in this case, specify required headers.
Of course it catches errors in much the same manner described above.
The HeroesComponent initiates the actual POST operation by subscribing to the Observable returned by this service method.
app/heroes/heroes.component.ts (addHero)
this.heroesService.addHero(newHero)
.subscribe(hero => this.heroes.push(hero));
When the server responds successfully with the newly added hero, the component adds that hero to the displayed heroes list.
Edited Answer:
I saw your postman screenshot you are passing username
This link will help you
Related
Hi I am using cakephp as backend and want to generate a custom token for my website which will be used on my client side.
Below is my code to generate a custom code
$activatedOfferwall = $session->read('ActiveOfferwall'); // 0209341c-da14-46b9-b3c9-8410472e13d2
$factory = (new Factory)->withServiceAccount(\App\Model\Constants\FirebaseConstants::JSON_FILE)->withDatabaseUri(\App\Model\Constants\FirebaseConstants::DEFAULT_URL);
$auth = $factory->createAuth();
$customToken = $auth->createCustomToken($activatedOfferwall['UserHash']);
Log::debug(json_encode($customToken));
and the fire base rules are
but this always returns an empty json. What am I missing here?
For someone who is looking, I found the solution. Rules had to be
$generator = CustomTokenGenerator::withClientEmailAndPrivateKey(
$email,
$privateKey
);
$token = $generator->createCustomToken('anthony#gmail.com');
and then send the token on the client side
firebase.auth().signInWithCustomToken(usertoken)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
firebase.auth().currentUser.getIdToken( /* forceRefresh */ true).then(function(idToken) {
console.log(idToken)
}).catch(function(error) {
// Handle error
});
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(error);
// ...
});
it's not only about the rules. if you are using the package kreait/laravel-firebase (https://firebase-php.readthedocs.io/en/stable/overview.html)
you will have to get the token with it's own method like this:
$firebaseCustomToken = $firebaseAuth->createCustomToken($user->id);
$CustomToken = $firebaseCustomToken->toString(); // like this will return the customToken
hope this helps someone
Reference of the git change here: https://github.com/kreait/firebase-php/commit/8b45c07d922364ba9298fa07cbe7ea676c1d05f4
I am new to Angular9, I have tried to save data by calling a php API from my angular9 application, but geting the following error.
I have test this service from postman, which is working fine and save data successfully
Access to XMLHttpRequest at 'http://127.0.0.1/angularCRUDservices/user/saveEmployee' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
**Please Note:** get method is working fine to fetch data,
my Angular service:
reqHeader = new HttpHeaders(
{
'Content-Type': 'application/json',
'No-Auth':'True',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Header':'Access-Control-Allow-Origin,X-Requested-With,Content-Type,Access',
'Access-Control-Allow-Methods':'GET,POST,DELETE,PATCH,PUT,OPTIONS'
}
);
constructor(private httpClient:HttpClient){}
saveEmployee(formData:Employee){
console.log(formData);
this.httpClient.post<{response:any,success:boolean}>("http://127.0.0.1/angularCRUDservices/user/saveEmployee",formData,{
headers : this.reqHeader
})
.subscribe((response)=>{
console.log(response);
})
}
php service code:
setting headers in constructor:
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('user_model','usr');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Header: Access-Control-Allow-Origin,X-Requested-With,Content-Type,Access');
header("Access-Control-Allow-Methods: GET,POST,DELETE,PATCH,PUT,OPTIONS");
header('Content-Type: application/json, charset=utf-8');
}
service:
public function saveEmployee()
{
$input = array();
try
{
$UserID = $this->input->post('id');
$input['name'] = $this->input->post('name');
$input['gender'] = $this->input->post('gender');
$input['email'] = $this->input->post('email');
$input['mobile'] = $this->input->post('mobile');
$input['department'] = 'test';//$this->input->post('department');
$input['isActive'] = 1;//$this->input->post('isActive');
$input['photo'] = 'testphoto';//$this->input->post('photo');
$output["response"] = $this->usr->saveUser($input,$UserID); // call model query to save data into DB
$output["success"] = true;
}
catch (Exception $ex)
{
$output["success"] = false;
$output["error"] = $ex->getMessage();
}
echo json_encode((object)$output);
exit;
}
if this is for development and not production,you can use a proxy to get arround the issue. add a json file to your root project named 'proxy.configuration.json'
remember to change the target to your api in the example below
{
"/api/*": {
"target": "https://localhost:44362",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
then run ng serve --proxy-config proxy.config.json
you have to add Authorization header key in Access-Control-Allow-Headers(in the backend)
Access-Control-Allow-Headers: Authorization (when you give like this it accepts specified headers only.means if you want to accept another key like authorization you have to mention that key name)
or
you can give like this also
Access-Control-Allow-Headers: *
I have been struggling with a strange issue for about a week now. I have searched through the answers here and elsewhere on the internet and I'm not quite sure what my specific issue might be. I do however think the error message I am getting doesn't have anything to do with my actual error. I thank you for any help or suggestions you might have.
My setup is as follows (all running locally):
Frontend website - Angular - running on standard ng serve
Backend API - PHP / MySQL - hosted locally via XAMPP
The error:
{"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"http://192.168.64.2/resourcer/api/menu/47693eb3-ca82-467b-af68-020150a5e4a6","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://192.168.64.2/resourcer/api/menu/47693eb3-ca82-467b-af68-020150a5e4a6: 0 Unknown Error","error":{"isTrusted":true}}
The concept:
Log in, authenticate on the php side, get jwt token.
The jwt token has a property called 'access'. I use this to return the menu based on the role.
Once I receive the jwt, I set the user object, append the jwt to bearer token auth header.
Call the retrieve menu call with the access property received from the server.
All of this works up until I change user. I have added 2 users to test the different menu items coming back, and when I log a user out (clear local storage), I try the second user's credentials.
I log in successfully, get the jwt and the user object, but when I request the menu I get the error message. I cannot get past this at all. The only way this gets fixed is by commenting all the code required to return the menu and just echo 'ok'. Then I do a request, get the ok, uncomment the code and then it's all back to normal until I log out again.
Have no idea what on earth is going on. Here is my code:
Angular Interceptor Service:
export class InterceptorService implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
const currentUser = this.authService.currentUserValue;
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json',
Authorization: `Bearer ${currentUser.token}`,
},
});
} else {
request = request.clone({
setHeaders: {
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json',
},
});
}
return next.handle(request);
}
}
Angular Auth Service:
signIn(signinCredentials: AuthCredentials) {
return this.dataService.signIn(signinCredentials).pipe(
map((data) => {
const helper = new JwtHelperService();
const decoded = helper.decodeToken(data.jwt);
const user: User = decoded.data;
user.token = data.jwt;
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
return user;
}),
);
}
logout() {
localStorage.removeItem('currentUser');
localStorage.removeItem('navItems');
this.currentUserSubject.next(null);
}
Angular Login Page:
signIn() {
this.submitted = true;
this.loading = true;
this.authService
.signIn(this.signinCredentials)
.pipe(first())
.subscribe(
(data) => {
this.currentUser = this.authService.currentUserValue;
this.getMenu();
},
(error) => {
this.error = error;
this.loading = false;
},
);
}
getMenu() {
this.dataService.getNavigationItems(this.currentUser.access).subscribe(
(menu) => {
if (menu) {
this.envService.setNavItems(menu.menu);
this.router.navigate([this.returnUrl]);
} else {
this.authService.logout();
location.reload(true);
}
},
(error) => {
this.authService.logout();
location.reload(true);
},
);
}
Now on my PHP side, I use an .htaccess file to redirect my URL:
RewriteEngine on
RewriteRule app/api/ app/api/index.php
PHP Index:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Origin, Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
define('PROJECT_ROOT_PATH', __DIR__);
include_once 'config/db.php';
--- Controller imports etc happen here
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode('/', $uri);
$requestMethod = $_SERVER["REQUEST_METHOD"];
$headerToken = getBearerToken();
if (isset($uri[3])) {
switch ($uri[3]) {
case 'users':
$userId = null;
if (isset($uri[4])) {
$userId = (int) $uri[4];
}
$controller = new UserController($db, $requestMethod, $userId, $headerToken);
$controller->processRequest();
break;
case 'companies':
$companyReference = null;
if (isset($uri[4])) {
$companyReference = $uri[4];
}
$controller = new CompanyController($db, $requestMethod, $companyReference, $headerToken);
$controller->processRequest();
break;
case 'login':
$controller = new LoginController($db);
$controller->login();
break;
case 'menu':
$roleGuid = null;
if (isset($uri[4])) {
$roleGuid = $uri[4];
}
$controller = new MenuController($db, $roleGuid, $headerToken);
$controller->getMenuItems();
break;
default:
header("HTTP/1.1 404 Not Found");
exit();
}
} else {
header("HTTP/1.1 404 Not Found");
exit();
}
function getAuthorizationHeader()
{
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
} else if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
function getBearerToken()
{
$headers = getAuthorizationHeader();
if (!empty($headers)) {
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
return null;
}
When I mentioned that I comment out the controller code with an echo ok, and it works, happens in this index file.
I'm stumped.
I am integrating Laravel into a legacy php app. The login page used to directly post to verifyUser.php which also started a Symfony Session.
The new architecture now posts to a laravel api which makes a Guzzle post to verifyUser.php.
javascript:
$(document).ready(function(){
$('#signIn').submit(function(){
var a = $('#email').val();
$.post('/api/login', { //this used to post to verifyUser.php
Username: $('#email').val(),
Password: $('#password').val()
}, function(data){
if(data['credentials'] == true){
console.log('credentials true');
console.log(data['uri']);
window.location.href=data['uri'];
} else {
$('#errMsg').html(data['errMsg']);
$('.alert').show();
}
}, 'json');
return false;
});
controller functions:
public function authenticate(Request $request) //aka api/login endpoint
{
//...
$legacyRes = $this->authenticateLegacy($request);
//...
}
private function authenticateLegacy(Request $request)
{
$response = null;
try {
$response = $this->client->post('/admin/verifyUser.php', [
'form_params' => ['Username' => $request->get('Username'),
'Password' => $request->get('Password')]
]);
}
catch(Exception $exception){
Log::error('Errrererererer', [$exception->getMessage()]);
}
$body = (string)$response->getBody();
Log::info('BODY:', [$body]);
return $body;
}
I have left out verifyUser.php because I have tested it and it returns the expected results.
When using the browser, the session information doesn't seem to get set. But according to my post responses, everything should be working.
Is this because I am routing the request through guzzle?
Posting under my answer to show updated code:
private function authenticateLegacy(Request $request)
{
//...
//parse cookie id from guzzle response
$body = (string)$response->getBody();
$cookie = $response->getHeader('Set-Cookie'); //PHPSESSID=SOMEID; path=/
$cookieBite = explode(';', $cookie)[0]; ////PHPSESSID=SOMEID
$cookieId = explode('=', $cookieBite)[1];
$data = json_decode($body, true);
$data['session'] = $cookieId;
return $data;
}
In the action:
public function authenticate(Request $request)
{
//...
$legacyRes = $this->authenticateLegacy($request);
//...
// this will have the session id in the body but will also
// set the cookie for the client so I don't have
// to set document.cookie w/ js
return response($legacyRes, 200)
->withCookie('PHPSESSID', $legacyRes['session']);
}
I assume your legacy endpoint uses cookies to identify a user's session.
A successfull request to the legacy endpoint returns a Set-Cookie header.
Guzzle doesn't forward this Set-Cookie header from the API response to the browser - you'll have to program this behaviour into the "wrapping" application.
You will need to tell guzzle to explicitly pass the corresponding Cookie header to the legacy api (to maintain the user's login state) when sending any further requests.
In order to achieve this you'll need to save this cookie within your new application (i.e. in the user's session or in database) and then pass it within a Cookie header along with all further requests you make to the legacy API.
EDIT:
Read the discussion about the bug at: https://github.com/tymondesigns/jwt-auth/issues/83
MY ORIGINAL QUESTION:
I'm implement with jwt-auth my protected resources that require an authenticated user with bellow code:
Route::group(['middleware' => ['before' => 'jwt.auth', 'after' => 'jwt.refresh']], function() {
// Protected routes
});
When user 'sign in' on API an Authorization token is created, and sent on response Authorization header to client application that call the resource. So, client applications when intercept a Authorization token on header of any response, set a variable/session/whatever with this token value, to send again to API on next request.
The first request for a protected resource after 'login' works fine, but the next client application request to API with a refreshed token, gives the following error (API mount all responses in json format):
{
"error": "token_invalid"
}
What can be happen with refreshed tokens? My refresh token implementation (set as a after middleware) is wrong? Or isn't necessary to manually refresh all Authorization token that come with client apps requests?
UPDATE:
I update the jwt-auth RefreshToken middleware as propose here, but the token_invalid persist.
BUG:
I guess that I found what happens. Note that in the refresh method, old token is added to blacklist cache case enabled:
// Tymon\JWTAuth\JWTManager
public function refresh(Token $token)
{
$payload = $this->decode($token);
if ($this->blacklistEnabled) {
// invalidate old token
$this->blacklist->add($payload);
}
// return the new token
return $this->encode(
$this->payloadFactory->setRefreshFlow()->make([
'sub' => $payload['sub'],
'iat' => $payload['iat']
])
);
}
And note that in add to blacklist method the key is the jti param from old token payload:
// Tymon\JWTAuth\Blacklist
public function add(Payload $payload)
{
$exp = Utils::timestamp($payload['exp']);
// there is no need to add the token to the blacklist
// if the token has already expired
if ($exp->isPast()) {
return false;
}
// add a minute to abate potential overlap
$minutes = $exp->diffInMinutes(Utils::now()->subMinute());
$this->storage->add($payload['jti'], [], $minutes);
return true;
}
Thus, when has on blacklist method is called, the old token jti param is the same that the new, so the new token is in blacklist:
// Tymon\JWTAuth\Blacklist
public function has(Payload $payload)
{
return $this->storage->has($payload['jti']);
}
If you don't need the blacklist functionality just set to false on jwt.php configuration file. But I can't say if it expose to some security vulnerability.
Read the discussion about the bug at: https://github.com/tymondesigns/jwt-auth/issues/83
When I get this issue, the solution that I found to get my project working was to generate a new token with data from older token on each new request.
My solution, that works for me, is bad, ugly, and can generate more issues if you have many async requests and your API(or business core) server is slow.
For now is working, but I will investigate more this issue, cause after 0.5.3 version the issue continues.
E.g:
Request 1 (GET /login):
Some guest data on token
Request 2 (POST /login response):
User data merged with guest data on old token generating a new token
Procedural code example(you can do better =) ), you can run this on routes.php out of routes, I say that is ugly haha:
// ----------------------------------------------------------------
// AUTH TOKEN WORK
// ----------------------------------------------------------------
$authToken = null;
$getAuthToken = function() use ($authToken, $Response) {
if($authToken === null) {
$authToken = JWTAuth::parseToken();
}
return $authToken;
};
$getLoggedUser = function() use ($getAuthToken) {
return $getAuthToken()->authenticate();
};
$getAuthPayload = function() use ($getAuthToken) {
try {
return $getAuthToken()->getPayload();
} catch (Exception $e) {
return [];
}
};
$mountAuthPayload = function($customPayload) use ($getLoggedUser, $getAuthPayload) {
$currentPayload = [];
try {
$currentAuthPayload = $getAuthPayload();
if(count($currentAuthPayload)) {
$currentPayload = $currentAuthPayload->toArray();
}
try {
if($user = $getLoggedUser()) {
$currentPayload['user'] = $user;
}
$currentPayload['isGuest'] = false;
} catch (Exception $e) {
// is guest
}
} catch(Exception $e) {
// Impossible to parse token
}
foreach ($customPayload as $key => $value) {
$currentPayload[$key] = $value;
}
return $currentPayload;
};
// ----------------------------------------------------------------
// AUTH TOKEN PAYLOAD
// ----------------------------------------------------------------
try {
$getLoggedUser();
$payload = ['isGuest' => false];
} catch (Exception $e) {
$payload = ['isGuest' => true];
}
try {
$payload = $mountAuthPayload($payload);
} catch (Exception $e) {
// Make nothing cause token is invalid, expired, etc., or not exists.
// Like a guest session. Create a token without user data.
}
Some route(simple example to save user mobile device):
Route::group(['middleware' => ['before' => 'jwt.auth', 'after' => 'jwt.refresh']], function () use ($getLoggedUser, $mountAuthPayload) {
Route::post('/session/device', function () use ($Response, $getLoggedUser, $mountAuthPayload) {
$Response = new \Illuminate\Http\Response();
$user = $getLoggedUser();
// code to save on database the user device from current "session"...
$payload = app('tymon.jwt.payload.factory')->make($mountAuthPayload(['device' => $user->device->last()->toArray()]));
$token = JWTAuth::encode($payload);
$Response->header('Authorization', 'Bearer ' . $token);
$responseContent = ['setted' => 'true'];
$Response->setContent($responseContent);
return $Response;
});
});