Registration user with uploading image - api

i tried to create API using Laravel 8 and here are my code for register new user
public function register(Request $request)
{
$validasi = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'user_id' => 'unique:users',
'password' => 'required|string|min:8',
'foto_ktp' => 'file|mimes:png,jpg',
]);
try {
$fileName = time() . $request->file('foto_ktp')->getClientOriginalName();
$path = $request->file('foto_ktp')->storeAs('uploads/foto_ktp', $fileName);
$validasi['foto_ktp'] = $path;
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'user_id' => $request->id,
'foto_ktp' => $request->foto_ktp,
'password' => Hash::make($request->password),
]);
$user->save();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'data' => $user,
'message' => 'Account Has Successfully Created',
'token' => $token,
'token_type' => 'Bearer',
'code' => 200
]);
} catch (\Exception $e) {
return response()->json([
'message' => 'Something wrong, user was not resgistered successfully',
'errors' => $e->getMessage(),
]);
}
}
when i tried the routes of API in Postman, the data will return like this
{
"data": {
"name": "test",
"email": "test#gmail.com",
"updated_at": "2023-01-02T06:54:01.000000Z",
"created_at": "2023-01-02T06:54:01.000000Z",
"id": 22,
"foto_ktp": {}
},
"message": "Account Has Successfully Created",
"token": "19|RXUZB40Oc35XCY4OMU6TPpqLJsmTRdFVpqsdNaS5",
"token_type": "Bearer",
"code": 200
}
foto_ktp will return {} and i checked it in database, foto_ktp field will store this data C:\xampp\tmp\php53D.tmp
I'm quite new in Laravel and i have tried to search any references but i haven't gotten it. Is there any suggestion what should i do? I used Laravel 8 for developing the API

Related

cakephp $this->Auth->identify() always return false

I have two environments in cakephp 3.9 , both same code and same SO etc... Both in AWS hosted. I have created an API that works fine in staging but not in production, I always get FALSE when the user login with the email and pwd to get the JWT token. The weird thing it is that it works perfectly in the same environment in staging.
In the endpoint, I have this
/**
* Get JWT token
*/
public function token()
{
$user = $this->Auth->identify();
$roleQuery = TableRegistry::getTableLocator()->get('UsersRoles');
// Get user role
$role = $roleQuery
->find()
->select(['role_id'])
->where(['user_id' => $user['id']])
->first();
if (!$user) {
// throw new UnauthorizedException('Invalid login details');
$this->set([
'success' => false,
'data' => [
"code" => 401,
'message' => 'Invalid login details',
],
'_serialize' => ['success', 'data']
]);
} else{
$tokenId = base64_encode(32);
$issuedAt = time();
$key = Security::salt();
// $email = $user['email'];
$this->set([
'msg' => 'Login successfully',
'success' => true,
// 'user' => $user,
'data' => [
'token' => JWT::encode([
'alg' => 'HS256',
'id' => $user['id'],
'sub' => $user['id'],
'iat' => time(),
'exp' => time() + 86400,
],
$key)
],
'_serialize' => ['success', 'data', 'key']
]);
}
}
}
And the configuration for this environment
'Api' => [
'auth' => [
'storage' => 'Memory',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email'
],
],
'ADmad/JwtAuth.Jwt' => [
'parameter' => 'token',
'userModel' => 'Users',
// 'scope' => ['Users.status' => 1],
'fields' => [
'id' => 'id'
],
'queryDatasource' => true
]
],
'unauthorizedRedirect' => false,
'checkAuthIn' => 'Controller.initialize'
],
],
In the ApiController I have these two methods to load the components etc...
public function initialize(): void
{
parent::initialize();
$this->loadComponent('Security');
$this->loadComponent('RequestHandler');
$this->loadComponent('Auth', Configure::read('Api.auth'));
$this->Auth->allow([
'token'
]);
}
public function beforeFilter(Event $event): void
{
$this->Security->setConfig('unlockedActions', [
'token'
]);
}
I always get the same response in production
{
"success": false,
"data": {
"code": 401,
"message": "Invalid login details"
}
}
Well, after a few hours I fixed the problem. It was a very very stupid thing, I just forgot to add the https protocol to the URL in Rester (plugin similar to Postman) before call the endpoint, that's it!!!.

Laravel 7 Passport with different and multiple Models

I am currently developing an API with Laravel 7 and I want to authenticate users coming from different applications with Passport : 3 applications communicate with the API, so 3 different user tables.
It's working fine with the User model provided but when I use my own model, I can't login : it responds "Bad credentials" with the good credentials.
So my question is : Is it possible to use a different model from User provided and also multiple model at the same time for each APP/Client ?
Here is a diagram of the structure I want : Diagram
My App\User :
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable{
use Notifiable, HasApiTokens;
....
}
Here is my login function :
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Bad credentials'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
$token->expires_at = Carbon::now()->addHours(1);
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
]);
}
}
My config/auth
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'userstest',
],
'api' => [
'driver' => 'passport',
'provider' => 'userstest',
'hash' => false,
],
], 'providers' => [
'userstest' => [
'driver' => 'eloquent',
'model' => App\User::class,
],

Laravel 8: after successful log in Auth session destroying on its own whenever I'm trying to redirect it to another route

web.php
Route::get('/', [AdminLoginController::class, 'index'])->name('admin.login');
Route::post('/login', [AdminLoginController::class, 'login'])->name('admin.login.submit');
Route::group(['middleware' => 'admin.middle' ] , function() {
Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('admin.dashboard');
});
AdminLoginController.php
public function login(Request $request)
{
$validator = Validator::make($request->all(),[
'email' => 'required|email:rfc,dns|exists:admins,email',
'password' => 'required',
],[
'email.required' => "Email is required",
'email.email' => "Email is invlaid",
'email.exists' => "Email does not exist",
'password.required' => "Password is required"
]);
if($validator->fails())
{
$this->sendResponse(400,$validator->errors()->first(),[]);
}
else
{
if (Auth::guard('admin')->attempt(["email" => $request->email , "password" => $request->password])) {
$this->sendResponse(
200,
"Successfully Logged In",
[
'location' => route('admin.dashboard')
]);
}
else {
$this->sendResponse(
500,
"Email or Password is incorrect",
[]);
}
}
}
AdminAuthenticate.php
class AdminAuthentication
{
public function handle(Request $request, Closure $next)
{
if (Auth::guard('admin')->check())
{
if (Auth::guard('admin')->user()){
return $next($request);
}
}
return redirect('/admin');
}
}
Maybe your sendResponse is not set corresponding headers (Set-cookie)? It looks like you mixing api responses with responses for browser.

SERVICE UNAVAILABLE error at REST API calling

My API route in routes/api.php file is like below.
Route::post('/register', [RegisterController::class, 'register']);
My register function of RegisterController is like below
public function register(RegistrationValidate $request)
{
$user = User::create([
'username' => request('username'),
'email' => request('email'),
'full_name' => request('full_name'),
'store_name' => request('store_name'),
'store_logo' => $fileName,
'password' => Hash::make(request('password')),
]);
$token = $user->createToken($this->clientToken())->accessToken;
return response()->json([
'user' => $user,
'token' => $token,
], 201);
}
I am getting SERVICE UNAVAILABLE error like below
I used php artisan up command and clear the cache. But the result is as like before.

Guzzle Api Connection to Emarsys

I try to get contactdata from emarsys with guzzle like this
$client = new Client([
'base_uri' => 'www.ApiUrl.com',
]);
$request = $client->request($requestType, $endPoint, [
'query' => $sQuery,
'debug' => true,
'body' => $sPostFields,
'headers' => [
'Content-type: application/json;charset="utf-8"',
],
]);
i always get 400 Bad Request.
try this way :
use GuzzleHttp\Client;
$client = new \GuzzleHttp\Client();
$response = $client->request('POST','www.ApiUrl.com',[
'headers' => [
'content-type' => 'application/x-www-form-urlencoded'
],
'form_params' => [
'name'=>$name,
'to' =>$email,
],
]);