Laravel Auth::attempt always return false? - laravel

Here is myscreen shot of database and my login input
public function action(Request $request){
$username = $request->username;
$pass = bcrypt($request->password);
$credentials = [
'id' => $username,
'password' => $pass
];
dd(Auth::attempt($credentials));
if (Auth::attempt(['id' => $username, 'password' => $pass])) {
echo 'Ok';
}else{
echo 'Not ok';
}
I'm trying to make a login action using laravel auth::attemptbut it always return false.

$pass = bcrypt($request->password);
should be
$pass = $request->password;
The attempt method will automatically handle the encryption and comparison. You are in effect bcrypting it twice, so a match isn't found

Related

Laravel Auth::attempt ans Hash::check not working

I try make rest API with Laravel 8 + Sanctum. And my database is MySql Maria DB.
I create LoginController and make function call login. When i try my API, it's always return Unauthorized. I pretty sure my USERNAME and PASSWORD is correct.
This is my LoginController
public function store(Request $request) {
$user = User::create(
[
"USERNAME" => $request->username,
"PASSWORD" => Hash::make($request->password),
"ADM_MST_SITE_ID" => 0,
]
);
$token = $user->createToken('apiToken')->plainTextToken;
$res = [
'user' => $user,
'token' => $token
];
return response($res, 201);
}
public function login(Request $request)
{
$data = $request->validate([
'username' => 'required|string',
'password' => 'required|string'
]);
$user = User::where('username', $data['username'])->first();
$credentials = request(['username', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$token = $user->createToken('apiToken')->plainTextToken;
$res = [
'user' => $user,
'token' => $token
];
return response($res, 201);
}
Model
////
protected $table = 'adm_mst_user';
protected $guarded = ['ID'];
public function getAuthPassword()
{
return $this->PASSWORD;
}
////
The store function is work well, the new data are inserted to my database. But, when i login with username and password, it's not working.
I try 2 different auth check, using Auth::attempt and Hash::check.
I don't know where the error coming from. It's always return Unauthorized.
$user = User::where('username', $data['username'])->first();
$this->guard()->login($user);
and make a guard function in same controller
protected function guard()
{
return Auth::guard();
}
import use Illuminate\Support\Facades\Auth; in top
include
use Illuminate\Support\Facades\Hash;
You need to make it with email not with username
$credentials = request(['email', 'password']);
OR, modify your attempt code
if(!Auth::attempt(['username' => $credentials['username'], 'password' => $credentials['password']))
this code worked with sanctum
use App\Models\User;
use Illuminate\Support\Facades\Hash;
function login($candidate)
{
$user = User::where('username', $candidate['username'])->first();
if (!$user || !Hash::check($candidate['password'], $user->password)) {
return [
'message' => 'These credentials do not match our records.'
];
}
$token = $user->createToken('my-token')->plainTextToken;
return [
'user' => $user,
'token' => $token
];
}

how to use session check properly

I have made session check, I am using:
if ($data!==false) {
$this->load->view("a");
}
But the both code is still running (true and false), and that session also run, so i got my screen was a half code false a half code true :")
Controller
public function aksi_login()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$where = array(
'username' => $username,
'password' => $password
);
$cek = $this->product_model->cek_login("admin",$where)->num_rows();
if($cek > 0){
$data_session = array(
'nama' => $username,
'status' => "login"
);
$this->session->set_userdata($data_session);
redirect(base_url("admin"));
}else{
echo "Username dan password salah !";
}
}
View
<?php if($this->session->userdata("data_session") !== false)
{$this->load->view("login");} ?>
False and true statement is running together so my screen is splited become 2 side.

How to generate access_token without username and password

I am trying to make an API with Passport. If a user tries to login or signs up with Socialite, find user than generate access_token then redirect to the frontend with access_token in URL parameters.
I tried to register and login than generate access_token with user email and the default password, which is not suitable for security.
try {
$serviceUser = Socialite::driver($service)->stateless()->user();
} catch (\Exception $e) {
return redirect(config('app.client_url').'/auth/social-callback?error=Unable to login using '.$service.'. Please try again'.'&origin=login');
}
$email = $serviceUser->getEmail();
$name = $serviceUser->getName();
$user = $this->getExistingUser($serviceUser, $email, $service);
$newUser = false;
if (!$user) {
$newUser = true;
$user = new User;
$user->name = $name;
$user->email = $email;
$user->username = Str::random(10);
if ($service === 'facebook') {
$user->image = $serviceUser->avatar;
}
$user->verify = true;
$user->save();
}
if ($this->needsToCreateSocial($user, $service)) {
Social::create([
'user_id' => $user->id,
'social_id' => $serviceUser->getId(),
'service' => $service
]);
}
$http = new Client;
$response = $http->post(config('app.url').'/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => '2',
'client_secret' => 'oBKWxgF2fDvrxwA05ciapwy4JYKaHxzhGzr6D24X',
'username' => $email,
'password' => 'gebdandi',
'scope' => '',
],
]);
$body = json_decode((string) $response->getBody(), true);
$accessToken = $body['access_token'];
return redirect(config('app.client_url').'/social-callback?token='.$accessToken.'&origin='.($newUser ? 'register' : 'login'));
I can't find any solution in the documentation.
after reading all documentation i found solution in this documentation
i did like this
edit authserviceprovider like this
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::personalAccessClientId(1);
Passport::tokensExpireIn(now()->addDays(15));
Passport::refreshTokensExpireIn(now()->addDays(30));
}
added code in controller like this
$accessToken = $user->createToken('access_token')->accessToken;
thanks for laravel Team for provide good documentation

Login auth for existing user not working correct for existing and non existing user in laravel

I am working on login panel with custom login after successfull user registeration with in table while trying to login after validating email and password in correct format it unabling to check auth condition as i have used auth library.While registering user i am entering md5 format password then how i can check email and md5 password exist with in database.Right now only else part is executing for corret credentials.
Controller Code:
public function login_student(Request $request){
$rules = array(
'email' => 'required|email',
'password' => 'required'
);
$validator = Validator::make(Input::all() , $rules);
if ($validator->fails()) {
return Redirect::to('log')->withErrors($validator)->withInput(Input::except('password'));
}else{
$email = Input::get('email');
$pass = md5($request->input['password']);
if (Auth::attempt(['email' => $request->input('email'),'password' => $pass])) {
echo "Welcome User";
exit;
}
else {
echo "Please enter correct details to login";
exit;
}
}
}
Since you used an Auth library, the Auth service will handle the encryption of passwords.
Therefore you must replace the following line:
$pass = md5($request->input['password']);
To:
$pass = $request->input('password');
Did you try using Auth:: guard()?
if (Auth::guard()->attempt(['email' => $request->email, 'password' => $request->password])) {
/////////////////
}
try with this
$user = \App\Models\User::where([
'email' => $request->email,
'password' => md5($request->password)
])->first();
if ($user) {
echo "Welcome User";
exit;
}
else{
echo "Please enter correct details to login";
exit;
}

laravel 5.2 custom login

I try to create custom login page but I got an error
Undefined index: password
my controller code
$this->validate($Request, [
'Email' => 'required',
'password' => 'required',
]);
$email = $Request['Email'];
$password = md5($Request['password']);
$login = new login();
$login = login::where('Email', $email);
if(empty($password))
{
return('404');
}
if(Auth::attempt(['Email' => $Request->input('Email'), 'Password' =>$password]))
{
return ('ok');
}
return ('no');
any one help my to create custom login
this is my new code
but again i gor undefined::passsword
public function logincheck(Request $request)
{
$this->validate($request, [
'Email' => 'required',
'password' => 'required',
]);
$email = $request->Email;
$password = md5($request->get('password'));
if(Auth::attempt(['Email' => $request->get('Email'), 'Password' =>md5($request->get('password'))]))
{
return ('ok');
}
return ('no');
}
Your error comes from
$Request['password']
You are treating Request as an array. It's an object. You do
public funciton login(Request $request)
{
$password = $request->password;
//or use the global helper
$password = request('password');
//Attempt login
if(Auth::attempt(['Email' => $request->get('Email'), 'Password' =>$password]))
{
return ('ok');
}
}
Also if you follow Laravel tutorial properly, you don't need md5 to hash password. Auth::attemp() will hash it for you

Resources