Laravel Passport invalid_credentials on register - laravel-passport

I have a problem with Passport.
I have the messages:
"error": "invalid_credentials",
"message": "The user credentials were incorrect."
When I try the register or the login.
Yet the user is still stored in database.
Here are my codes:
AuthServiceProvider :
<?php
namespace App\Providers;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Carbon\Carbon;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addMinutes(1));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
}
}
RegisterController:
<?php
namespace App\Http\Controllers\Api\Auth;
use Illuminate\Http\Request;
//use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Controller;
use App\User;
use Laravel\Passport\Client;
class RegisterController extends Controller
{
private $client;
public function __construct(){
$this->client = Client::find(1);
}
public function register(Request $request){
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6'
]);
$user = User::create([
'name' => request('name'),
'email' => request('email'),
'password' => bcrypt('password')
/*'admin' => isset(request('admin'))*/
]);
$params = [
'grant_type' => 'password',
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'username' => request('email'),
'passord' => request('password'),
'scope' => '*'
];
$request->request->add($params);
$proxy = Request::create('oauth/token', 'POST');
return Route::dispatch($proxy);
}
}
LoginController:
<?php
namespace App\Http\Controllers\Api\Auth;
use Illuminate\Http\Request;
//use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Laravel\Passport\Client;
class LoginController extends Controller
{
//use IssueTokenTrait;
private $client;
public function __construct(){
$this->client = Client::find(1);
}
public function test(){
return 'Tu essaie de te loger !';
}
public function login(Request $request){
$this->validate($request, [
'username' => 'required',
'password' => 'required'
]);
$params = [
'grant_type' => 'password',
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'username' => request('username'),
'passord' => request('password'),
'scope' => '*'
];
$request->request->add($params);
$proxy = Request::create('oauth/token', 'POST');
return Route::dispatch($proxy);
}
public function refresh(Request $request){
$this->validate($request, [
'refresh_token' => 'required'
]);
$params = [
'grant_type' => 'refresh_token',
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'username' => request('username'),
'passord' => request('password')
];
$request->request->add($params);
$proxy = Request::create('oauth/token', 'POST');
return Route::dispatch($proxy);
}
public function logout(Request $request){
$accessToken = Auth::user()->token();
DB::table('oauth_refresh_tokens')
->where('access_token_id', $accessToken->id)
->update(['revoked' => true]);
$accessToken->revoke();
return response()->json([], 204);
}
}
So in the case of register, if the data is bad, I get the right messages.
But when they are good, I receive these two messages:
"error": "invalid_credentials",
"message": "The user credentials were incorrect."
Same in the case of login.
Can someone help me?

I finally found.
I put the solution here in case someone someday have the same problem.
It just has to change the code:
$user = User::create([
'name' => request('name'),
'email' => request('email'),
'password' => bcrypt('password')
/*'admin' => isset(request('admin'))*/
]);
in function register(Request $request) of the RegisterController
By:
$user = User::create([
'name' => request('name'),
'email' => request('email'),
'password' => Hash::make(request('password'))
/*'admin' => isset(request('admin'))*/
]);
and everything else will work (including login :)).

Related

Stripe java.lang.IllegalArgumentException: Invalid Setup Intent client secret:

E/App: Got error:
java.lang.IllegalArgumentException: Invalid Setup Intent client secret: pi_3LtYhHAZTS98jCaY3NVtpCAW_secret_yUvzN3ytPIexEVJGtOzvQCSOM
at com.stripe.android.model.SetupIntent$ClientSecret.
Here i added my all codes of java class and php api for the test but i got this above error on the same code so plz do my help
paymentSheet = new PaymentSheet(this, this::onPaymentSheetResult);
Fuel.INSTANCE.post("my api link",null).responseString(new Handler<String>() {
#Override
public void success(String s) {
try {
final JSONObject result = new JSONObject(s);
customerConfig = new PaymentSheet.CustomerConfiguration(
result.getString("customer"),
result.getString("ephemeralKey")
);
paymentIntentClientSecret = result.getString("paymentIntent");
PaymentConfiguration.init(getContext().getApplicationContext(), result.getString("publishableKey"));
} catch (JSONException e) { /* handle error */ }
}
#Override
public void failure(#NotNull FuelError fuelError) { /* handle error */ }
});
if(isset($action) && $action='pay' && isset($amount)){
\Stripe\Stripe::setApiKey('sk_test_qrdTKAz2kaeZEPZHK2OdrNpn');
// Use an existing Customer ID if this is a returning customer.
$userid = $_GET['u'];
$query_usr = "SELECT * FROM tbl_user WHERE user_id = '$userid'";
$r_usr = $conn->query($query_usr);
$user = $r_usr->fetch_assoc();
if($user['stripe_customer'] == NULL){
$customer = \Stripe\Customer::create([
'name' => $user['user_name'],
'email' => $user['user_email']
]);
$customer_id = $customer->id;
$conn->query("UPDATE tbl_user SET stripe_customer = '$customer_id' WHERE user_id = $userid");
}
else{
$customer_id = $user['stripe_customer'];
}
$ephemeralKey = \Stripe\EphemeralKey::create(
[
'customer' => $customer_id,
],
[
'stripe_version' => '2020-08-27',
]);
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => 1099,
'currency' => 'cad',
'customer' => $customer_id,
'automatic_payment_methods' => [
'enabled' => 'true',
],
]);
$si = \Stripe\SetupIntent::create([
'customer' => $customer_id
]);
$response['paymentIntent'] = $paymentIntent->client_secret;
$response['setupIntent'] = $si->client_secret;
$response['ephemeralKey']= $ephemeralKey->secret;
$response['customer']= $customer_id;
$response['publishableKey'] = 'pk_test_0aSL6prHXE16hsokTWYKk8Gz';
echo json_encode($response);
// return $response->withJson([
// 'paymentIntent' => $paymentIntent->client_secret,
// 'ephemeralKey' => $ephemeralKey->secret,
// 'customer' => $customer_id,
// 'publishableKey' => 'pk_live_8mBL0Iji2oVDpgmBAVwPiicC'
// ])->withStatus(200);
}
else
{
$response['error']=TRUE;
$response['error_msg']="Required Parameters are missing";
echo json_encode($response);
}
private void presentPaymentSheet() {
final PaymentSheet.Configuration configuration = new PaymentSheet.Configuration.Builder("!2min, Inc.")
.customer(customerConfig)
// Set `allowsDelayedPaymentMethods` to true if your business can handle payment methods
// that complete payment after a delay, like SEPA Debit and Sofort.
.allowsDelayedPaymentMethods(true).build();
paymentSheet.presentWithSetupIntent(
paymentIntentClientSecret,
configuration
);
}
private void onPaymentSheetResult(final PaymentSheetResult paymentSheetResult) {
if (paymentSheetResult instanceof PaymentSheetResult.Canceled) {
Log.d("cantag","Canceled");
} else if (paymentSheetResult instanceof PaymentSheetResult.Failed) {
Log.e("App", "Got error: ", ((PaymentSheetResult.Failed) paymentSheetResult).getError());
} else if (paymentSheetResult instanceof PaymentSheetResult.Completed) {
// Display for example, an order confirmation screen
Log.d("tcmp","Completed");
}
}
Based off the error message, you should be passing in a SetupIntent's client_secret - a SetupIntent id starts with si_ . However, you're passing in a PaymentIntent's client_secret - a PaymentIntent id starts with pi_
If you intend to use a PaymentIntent, you should follow the guide here : https://stripe.com/docs/payments/accept-a-payment?platform=android
If you intend to use a SetupIntent, you should follow the guide here : https://stripe.com/docs/payments/save-and-reuse?platform=android&ui=payment-sheet

"syntax error, unexpected token \"(\", expecting \"{\"" when attempting to login to laravel from ionic using passport authentication

I am attempting to create a login / registration process using an ionic 5 app and laravel 9. Registration works okay but when I attempt to login, laravel returns the error:
"syntax error, unexpected token \"(\", expecting \"{\""
login.page.ts
login(email: String, password: String) {
return this.http.post(this.env.API_URL + 'auth/login',
{email: email, password: password}
).pipe(
tap(token => {
this.global.storage.setItem('token', token)
.then(
() => {
//alert('Token Stored');
},
error => alert(error)
);
this.global.token = token;
this.global.isLoggedIn = true;
return token;
}),
);
}
Controller:
public function login(Request $request)
{
$data = [
'email' => $request['email'],
'password' => $request['password'],
];
try (auth()->attempt($data)) {
$tokenResult = auth()->user()->createToken('Pesacount-User-Access-Token');
$token = $tokenResult->accessToken;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'loginStatus' => 'Successful'
/***
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
*/
]);
return response()->json(['token' => $token], 200);
} catch (Exception $e) {
return response()->json(['error' => $e->getMessage()], 401);
}
}
According to the logs, the error is caused when running
try (auth()->attempt($data)) {
I was originally running laravel 5.6 and everything worked okay. Upgraded to laravel 9 and thats when the error started

Laravel Excel Multiple table primary_id save to another table as a foreign_id

I can successfully import Excel Data in Laravel and Insert into Database multiple tables. I am using maatwebsite/excel version 3 composer package and laravel version 5.8
How can I insert mamber_id value in licence_application table (foreign id) which is member table primary id.
ImportClass file:
class UsersImport implements ToCollection
{
/**
* #param Collection $collection
*/
public function collection(Collection $rows)
{
foreach ($rows as $row){
Member::create([
'full_name' => $row[0],
'father_name' => $row[1],
'mother_name' => $row[2],
'cell_number' => $row[3],
]);
LicenceApplication::create([
'member_id' => ???
'licence_category_name' => $row[4],
]);
LicenceSuccess::create([
'application_type' => $row[5],
]);
}
}
}
Controller file: ImporExcelController.php
public function import(Request $request)
{
$this->validate($request, [
'select_file' => 'required|mimes:xls,xlsx'
]);
$path = $request->file('select_file')->getRealPath();
$data = Excel::import(new UsersImport, $path);
return back()->with('success', 'Import data successfully!');
}
Excel file screenshot: https://imgur.com/a/XhxBRpW
Please help me how to solve this issue?
I solve this issue here is the code.
foreach ($rows as $row){
$memberId = Member::create([
'full_name' => $row['full_name'],
'father_name' => $row['father_name'],
'mother_name' => $row['mother_name'],
'cell_number' => $row['cell_number'],
]);
$applicationId = LicenceApplication::create([
'member_id' => $memberId->member_id,
'licence_category_name' => $row['licence_category_name'],
]);
LicenceSuccess::create([
'member_id' => $memberId->member_id,
'application_id' => $applicationId->application_id,
'application_type' => $row['application_type'],
]);
}

Yii2 pagination doesn't change page

My pager doesn't change to chosen page. When I click to the next page button it reloads the page. I also tried without Pjax container but the result was the same. I red the other posts but still can't figure it out. What I am doing is :
$categoriesProvider = new ActiveDataProvider([
'query' => Page::find()->where(['enable' => 1, 'id_in' => $page_id])->orderBy('sort ASC'),
'pagination' => [
'pageSize' => 1,
'route' => "/".Yii::$app->getRequest()->getQueryParam('page')
]
]);
return $this->render('index', [
'categoriesProvider' => $categoriesProvider
]);
and in the view:
<?php Pjax::begin() ?>
<div class="content-area col-md-8 col-sm-6 col-xs-12 no-padding">
<?php if(!empty($categoriesProvider)){
echo ListView::widget([
'dataProvider' => $categoriesProvider,
'layout' => "{summary}\n{items}
\n<nav class='post-pagination col-md-12 col-sm-12 col-xs-12'>
{pager}
</nav>",
'itemView' => function($model, $key, $index, $widget){
return $this->render('_category', [
'model' => $model,
]);
},
'pager' => [
'nextPageLabel' => ">>",
'prevPageLabel' => "<<",
'maxButtonCount' => 5,
'options' => [
'tag' => 'ul',
'class' => 'pagination',
]
]
]);
}?>
</div><!-- Content Area /- -->
<?php Pjax::end(); ?>
URL configuration:
<?php
namespace frontend\controllers;
use backend\models\News;
use backend\models\Page;
use backend\models\Product;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
class SplitterController extends Controller
{
public function actionManageRequest()
{
$param_page = \Yii::$app->getRequest()->getQueryParam('page');
$param_category = \Yii::$app->getRequest()->getQueryParam('category');
$param_product = \Yii::$app->getRequest()->getQueryParam('product');
$page = $this->getModel($param_page, new Page());
//If page is existing page model go forward
if(!empty($page)){
$controller = $this->getController($page->view);
if($this->checkId($param_page) === 'news'){
$model = new News();
}else{
$model = new Page();
}
$category = $this->getModel($param_category, $model);
if(!empty($category)){
$product = $this->getModel($param_product, new Product());
//If product is existing product model - go forward to single view
if(!empty($product)){
$this->registerTags($product);
try{
return \Yii::$app->runAction("$controller/view");
}
catch (\Throwable $e){
throw new NotFoundHttpException('Page not found',404);
}
}
//If product is not empty and product don't - throw exception
if(!empty($param_product) && $product === null){
throw new NotFoundHttpException('Page out found', 404);
}
$this->registerTags($category);
//If page model is news page - render news single view
if($this->checkId($param_page) === 'news'){
return \Yii::$app->runAction("$controller/multi-view");
}
try{
return \Yii::$app->runAction("$controller/multi-view");
}
catch (\Throwable $e){
throw new NotFoundHttpException('Page not found',404);
}
}
$this->registerTags($page);
//If category is not empty but no such page found - throw exception
if(!empty($param_category) && $category === null){
throw new NotFoundHttpException('Page not found', 404);
}
return \Yii::$app->runAction($page->view);
}
//If page is not empty but no such page found - throw exception
if(!empty($param_page) && $page === null){
throw new NotFoundHttpException('Page not found', 404);
}
$page = Page::findOne(13);
$this->registerTags($page);
return \Yii::$app->runAction($page->view);
}
private function getModel($param, $model)
{
$chunks = explode('-', $param);
$chunk_id = end($chunks);
return $model::findOne($chunk_id);
}
private function registerMetaTags($name, $content)
{
\Yii::$app->view->registerMetaTag([
'name' => $name,
'content' => $content
]);
}
private function registerTitle($title)
{
\Yii::$app->view->title = $title;
}
private function checkId($param)
{
$id = explode('-', $param);
$id = end($id);
switch ($id) {
case 14:
return 'news';
break;
default:
return 'page';
break;
}
}
private function getController($path)
{
$controller = explode('/', $path);
return $controller[0];
}
private function registerTags($model)
{
$this->registerMetaTags('description', $model->meta_title);
$this->registerTitle($model->meta_title);
}
}
Url manager rules :
'rules' => [
'<page>/<category>/<product>' => 'splitter/manage-request',
'<page>/<category>' => 'splitter/manage-request',
'<page>' => 'splitter/manage-request',
'' => 'splitter/manage-request'
],
It looks like Pagination param conflict with your URL rules. Pagination uses page GET param to store current page number in URL. But your rules also uses page param and overrides param used by Pagination. You should use different param in your pagination config, to avoid conflicts:
'pagination' => [
'pageSize' => 1,
'route' => "/".Yii::$app->getRequest()->getQueryParam('page'),
'pageParam' => 'paginationPage',
]
See https://www.yiiframework.com/doc/api/2.0/yii-data-pagination#$pageParam-detail
Or you can rename params in your rules to avoid such problem also in other places:
'rules' => [
'<r_page>/<r_category>/<r_product>' => 'splitter/manage-request',
'<r_page>/<r_category>' => 'splitter/manage-request',
'<r_page>' => 'splitter/manage-request',
'' => 'splitter/manage-request'
],

CakePHP 2.0: Class 'String' not found at the end of my Model?

Im using CakePHP 2.0
I have a Model for my Users which is very simple:
<?php
App::uses('Model', 'Model');
class User extends AppModel {
public $name = 'User';
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
)
);
public function beforeSave(array $options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}
?>
However I keep getting the following error:
Fatal Error: Class 'String' not found in /home/xxx/app/Model/User.php on line 27.
The error disappears if I comment the beforeSave function.
What am I missing?
Try changing:
public function beforeSave(array $options = array()) {
to
public function beforeSave($options = array()) {

Resources