cannot take data from DB and use it in VUE script - json

I try to take data from DB and use it in VUE script, but in console I see message
GET http://lara7.test/api/furnitura 401 (Unauthorized)
In Chrome devtools Network tab I see response
furnitura
{"message":"Unauthenticated."}
Here is my code
routes\api.php
Route::middleware('auth:api')->group( function () {
Route::resource('furnitura', 'API\FurnituraController');
});
App\Http\Controllers\API\BaseController
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
abstract class BaseController extends Controller
{
public function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
'success' => false,
'message' => $error,
];
if(!empty($errorMessages)){
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
}
App\Http\Controllers\API\FurnituraController
namespace App\Http\Controllers\API;
class FurnituraController extends BaseController
{
public function index()
{
$furnitura = Furnitura::all();
return $this->sendResponse($furnitura->toArray(), 'Furnitura retrieved successfully.');
}
}
resources\js\app.js
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
...
...
mounted() {
console.log("Vue ROOT instance mounted");
axios.get('/api/furnitura').then(response => this.furnitura = response.data);
console.log(this.furnitura);
},

Maybe, you do not pass the auth: API middleware. You are getting 401 from middleware.
maybe you use token for user validation or API user validation that token is missing

Related

How to save data from a request to mysql in laravel

I would like to save the information that I am receiving in the response of a request, in this case the "access_token" field, to my mysql database, here is the code:
My controller,
here I make a post request to have the access token:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class AuthsController extends Controller
{
public function SocialAuth(Request $request)
{
$a = $request->input('auth_code');
// URL
$apiURL = 'https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/';
// POST Data
$postInput = [
'app_id' => '7112335319877287',
'secret' => '18f52730856f43ed821187bfa9283794ca360e',
'auth_code' => $a
];
// Headers
$headers = [
//...
];
$response = Http::withHeaders($headers)->post($apiURL, $postInput);
$statusCode = $response->getStatusCode();
$responseBody = json_decode($response->getBody(), true);
echo $statusCode; // status code
dd($responseBody); // body response
}
}
Response of my request, the value that I want to save to mysql is the access token
^ array:4 [▼
"code" => 0
"message" => "OK"
"request_id" => "202211281314430102451411010AF4AA0A"
"data" => array:3 [▼
"access_token" => "fbcaa610339b7aeb39eabf29346d06a4e7fe9"
"advertiser_ids" => array:1 [▶]
"scope" => array:18 [▶]
]
]
How can I save the access token in mysql?
create a table with the following columns, for storage:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTokenTableTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('token_table', function (Blueprint $table) {
$table->integer('id_token')->primary();
$table->string('token')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('token_table');
}
}
Use your token Model and save the data
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
// call your token Model class
use App\Models\TokenTable
class AuthsController extends Controller
{
public function SocialAuth(Request $request)
{
$a = $request->input('auth_code');
// URL
$apiURL = 'https://business-api.tiktok.com/open_api/v1.3/oauth2/access_token/';
// POST Data
$postInput = [
'app_id' => '7112335319877287',
'secret' => '18f52730856f43ed821187bfa9283794ca360e',
'auth_code' => $a
];
// Headers
$headers = [
//...
];
$response = Http::withHeaders($headers)->post($apiURL, $postInput);
$statusCode = $response->getStatusCode();
$responseBody = json_decode($response->getBody(), true);
echo $statusCode; // status code
//check if status code is 200
if($statusCode == 200){
TokenTable::create([
'token' => $responseBody['data']->access_token
]);
echo 'ok';
}
}
}
or this
if($statusCode == 200){
TokenTable::create([
'token' => $responseBody['data']['access_token']
]);
echo 'ok';
}

JWT token access from header

I am working with JWT token to make API in Laravel, I want to Make CRUD operation, I already test my API in Postman.
Now the issue is that I want to implement it via Laravel blade views, in postman I can set Authorization Bearer in header, How would I do that in Laravel application? Not in Postman, in short I want to set header, so I can access token in each every request.
Controller:
<?php
class NewController extends Controller
{
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
$token = auth()->attempt($credentials);
return $this->createNewToken($token);
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if ($validator->fails()) {
return response()->json(array(
"status" => false,
"errors" => $validator->errors()
), 400);
}
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)]
));
return response()->json([
'status' => true,
'message' => 'User successfully registered',
'user' => $user
], 201);
}
public function refresh()
{
return $this->createNewToken(auth()->refresh());
}
public function userProfile()
{
return $this->getAuthenticatedUser();
}
public function me()
{
$user = JWTAuth::parseToken()->authenticate();
return response()->json(array($user), 400);
}
protected function createNewToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => auth()->user()
]);
}
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'));
}
}
Routes:
'prefix' => 'auth',
], function ($router) {
Route::post('login', [App\Http\Controllers\NewController::class, 'login'])->name('apisignin');
Route::post('getauth', [App\Http\Controllers\NewController::class, 'getAuthenticatedUser'])->name('getAuthenticatedUser');
Route::post('userProfile', [App\Http\Controllers\NewController::class, 'userProfile']);
Route::post('me', [App\Http\Controllers\NewController::class, 'me']);
});

Laravel validation with custom json respons

Quick question.
Would it be possible to changes the JSON validation response of laravel?
This is for a custom API that I am building in Laravel.
Validation process
$validation = $this->validate(
$request, [
'user_id' => 'required',
]);
The response shows up like this in json
{
"message": "The given data was invalid.",
"errors": {
"user_id": [
"The user id field is required."
],
}
}
Preferable it would become something like this.
{
"common:" [
"status": "invalid",
"message": "Param xxxx is required",
],
}
What would be the best way to changes this?
Is it even possible?
Thank you.
You can do this, and it will be reflected globally.
Navigate to below folder and use Controller.php
app/Http/Controllers
use Illuminate\Http\Request;
Write below method in Controller.php and change response as you want.
public function validate(
Request $request,
array $rules,
array $messages = [],
array $customAttributes = [])
{
$validator = $this->getValidationFactory()
->make(
$request->all(),
$rules, $messages,
$customAttributes
);
if ($validator->fails()) {
$errors = (new \Illuminate\Validation\ValidationException($validator))->errors();
throw new \Illuminate\Http\Exceptions\HttpResponseException(response()->json(
[
'status' => false,
'message' => "Some fields are missing!",
'error_code' => 1,
'errors' => $errors
], \Illuminate\Http\JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
}
}
I have tried it with Laravel 5.6, maybe this is useful for you.
#Dev Ramesh solution is still perfectly valid for placing inline within your controller.
For those of you looking to abstract this logic out into a FormRequest, FormRequest has a handy override method called failedValidation. When this is hit, you can throw your own response exception, like so...
/**
* When we fail validation, override our default error.
*
* #param ValidatorContract $validator
*/
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
$errors = $this->validator->errors();
throw new \Illuminate\Http\Exceptions\HttpResponseException(
response()->json([
'errors' => $errors,
'message' => 'The given data was invalid.',
'testing' => 'Whatever custom data you want here...',
], 422)
);
}
I was searching for an answer to this and I think I found a better way. There is an exception handler in a default Laravel app - \App\Exceptions\Handler - and you can override the invalidJson method:
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
class Handler extends ExceptionHandler
{
// ...
protected function invalidJson($request, ValidationException $exception)
{
$errors = [];
foreach ($exception->errors() as $field => $messages) {
foreach ($messages as $message) {
$errors[] = [
'code' => $field,
'message' => $message,
];
}
}
return response()->json([
'error' => $errors,
], $exception->status);
}
}

Yii2 validate password in for RESTapi

If you do not use a password, the REST request passes. Otherwise, you get an error:
Error:
"name": "Unauthorized",
"message": "Your request was made with invalid credentials.",
"code": 0,
"status": 401,
"type": "yii\\web\\UnauthorizedHttpException"
Access in User model:
public static function findIdentityByAccessToken($username, $password = null)
{
// throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
//return static::findOne(['username' => $username]);
$user = static::findOne(['username' => $username]);
if ($user != null and $user->validatePassword($password)) {
return $user;
} else {
return null;
}
}
And validatePassword function:
public function validatePassword($password)
{
$hash = Yii::$app->getSecurity()->generatePasswordHash($password);
return Yii::$app->getSecurity()->validatePassword($password, $this->password_hash);
}
How to authenticate?
REST APIs work usually by authenticating using tokens. There are different types of auth tokens. This example is using basic auth:
Controller
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
];
return $behaviors;
}
You then need to add a authorization header to your request with the value
Basic base64_encode(username:password)

How to return JsonModel by default in ZF2?

Default ViewModel is not mandatory, I can return from controller just the array of data:
public function someAction()
{
//...
return array('result'=>$data);
}
But I can`t use this approach with Json. What should I do in dispatch event to wrap the results in JsonModel (for the appropriate accept header)?
Just create Base Controller for all your API controllers, and replace model in MvcEvent.
class JsonRestController extends AbstractRestfulController
{
public function onDispatch(MvcEvent $e)
{
$e->setViewModel(new JsonModel());
return parent::onDispatch($e);
}
}
You have to add a ViewJsonStrategy strategy to the view manager under your module.config.php:
'view_manager' => array(
'template_map' => array(
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
'strategies' => array(
'ViewJsonStrategy',
),
),
Then you can return a JsonModel in your action:
public function myAction()
{
$data = [1, 2, 3, 4];
return new JsonModel([
'data' => $data
]);
}
to get json data from controller you can echo json encoded data and exit. I use that for jquery ajax. i hope this is what you are looking for.
public function testAction()
{
$active = "some data";
echo json_encode(array('result' => $active));
exit();
}
then at jquery you can get this data like that
$.ajax({
type: 'GET',
url: '/index/time',
dataType: 'json',
error: function() {
$('#info').html('<p>Error on time calculation</p>');
},
success: function(data) {
data.result
}
});
Is really simple
Add as follows:
IndexController.php
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel; // Add this line
class IndexController extends AbstractActionController {
public function indexAction() {
// some index action
return new ViewModel();
}
public function apiAction() {
$person = array(
'first_name' => 'John',
'last_name' => 'Downe',
);
// Special attention to the next line
return new JsonModel(array(
'data' => $person,
));
}
}
api.phtml
<?php echo $this->json($this->data); ?>
Result:
{"first_name":"John","last_name":"Downe"}