Laravel authentication Not Working for a specific user - php

i have a code that works perfectly for login for every mobile users,until a user tries to login but he cant here is the login code,
Note, this happens to only this user
public function MobileLogin(Request $request)
{
error_log($request);
$n = $request->get('username');
$p = $request->get('password');
error_log($p);
error_log($n);
error_log('i got the values');
if (Auth::attempt( array(
'UserName' => $request->get('username'),
'password' => $request->get('password')
) )) {
$user = Auth::user();
$id = Auth::id();
error_log($id); // i am able to see this value on the log which means user is authenticated
$n = 'ok';
return Response::json($user); // but i couldn't get this instead
} else {
$n ='Invalid Username or Password Please Try Again'; // i get this
return Response::json($n);
}
}

Related

Problem with authenticating user using laravel socialite

I'm trying to make login with google using laravel socialite and I have a problem.
Route that initiates login:
Route::get('/auth/login/google', 'AuthController#google');
Method in controller that initiates login:
public function google()
{
return Socialite::driver('google')->redirect();
}
Callback route:
Route::get('/auth/login/google/redirect', 'AuthController#googleRedirect');
Callback method in controller:
public function googleRedirect()
{
$googleUser = Socialite::driver('google')->user();
$email = $googleUser->getEmail();
$user = new User();
$user = $user->firstOrCreate(['email' => $email], ['email' => $email, 'password' =>
bcrypt(str_shuffle('abcdefgh45678')), 'email_verified' => 1]);
Auth::login($user, true);
}
And I'm getting ERR_EMPTY_RESPONSE every time I'm trying to redirect user after login.
Funny thing is that I can dump data with dd(Auth::user()->id) and I'm getting user's ID, but when I try to redirect user to the home page using return redirect('/') I'm getting empty response error and if I manually go to home page my user is not authenticated.
#Matej Petric blow code is working for me.
public function handleProviderCallback($provider) {
$user = Socialite::driver('google')->stateless()->user();
$authUser = $this->findOrCreateUser($user);
if ($authUser) {
Auth::login($authUser, true);
return redirect('/');
} else {
return redirect('/login')->withErrors(['msg', 'The Message']);
}
}
public function findOrCreateUser($user) {
$authUser = User::where('email', $user->email)->first();
if ($authUser) {
return $authUser;
}
$userN = User::create([
'name' => $user->name,
'email' => $user->email,
'password' => bcrypt(generateRandom()),
]);
return $userN;
}

Logout user from all browser when password is reset in laravel 5.6

When the user changes their password, they get Logged Out from the browser. However, if they are logged into another browser at the same time they stay logged in on the other browser.
I want to log out the user from all browsers they are logged into when they reset their password.
Here login controller.
function checklogin(Request $request)
{
$this->validate($request, ['email' => 'required|email', 'password' => 'required|string|min:3']);
$user_data = array(
'email' => $request->get('email') ,
'password' => $request->get('password')
);
$remember_me = $request->has('remember') ? true : false;
if (Auth::attempt($user_data, $remember_me))
{
return redirect()->intended('dashboard');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}
send mail function as below
function sendEmail(Request $request)
{
$this->validate($request, ['email' => 'required|exists:users']);
$email = $request->email;
$name = User::where('email', $email)->first();
$name = $name->name;
$token = Password::getRepository()->createNewToken();
$link = url("password/reset?email=$email&token=$token");
$value = Password_resets::where('email', $email)->first();
if (isset($value))
{
Password_resets::where('email', $email)->update(['email' => $email, 'token' => $token]);
}
else
{
Password_resets::insert(['email' => $email, 'token' => $token]);
}
Mail::to($email)->send(new \App\Mail\ResetPassword($link, $name));
return redirect()->back()->with('success', 'Please check your Email for Password Reset');
}
password reset function as below
function resetpasswordchange(Request $request)
{
$passwordtoken = $request->input('passwordtoken');
$email = $request->input('email');
$user_password = $request->input('user_password');
$users['user'] = Password_resets::where('token', $passwordtoken)->where('email', $email)->get();
if (empty($users['user'][0]))
{
$settoken = '0';
}
else
{
$settoken = $users['user'][0]->token;
}
if (($settoken) == $passwordtoken)
{
$update = array(
'password' => bcrypt($user_password) ,
);
User::where('email', $email)->update($update);
/* Auth::logout();
auth()->logoutOtherDevices(bcrypt($user_password),'password');*/
return redirect()->route('login')->with('success', 'Password has been Updated.');
}
else
{
return redirect()->back()->with('error', 'Token & Email Not Match!.');
}
}
How I can logout the user from all browsers who they are logged already ?
Open App\Http\Kernel and inside the protected $middlewareGroups property uncomment the \Illuminate\Session\Middleware\AuthenticateSession::class middleware. This compares the password hash of the user to see if the session is valid or not.

How to request for login with email and plain text password in cakephp3

I am new in php and working on REST API in cakephp3 for my android application.
after setting up php and composer and routing I created login function..
public function login() {
$this->request->allowMethod('post');
$this->loadModel('Users');
$entity = $this->Users->newEntity($this->request->data, ['validate' => 'LoginApi']);
if ($entity->errors()) {
$this->httpStatusCode = 400;
$this->apiResponse['message'] = 'Validation failed.';
foreach ($entity->errors() as $field => $validationMessage) {
$this->apiResponse['error'][$field] = $validationMessage[key($validationMessage)];
}
} else {
$hasher = new DefaultPasswordHasher();
$password = $hasher->hash($entity->password);
$user = $this->Users->find()
->where([
'email' => $entity->email,
'password' => $password
])
->first();
if (empty($user)) {
$this->httpStatusCode = 403;
$this->apiResponse['error'] = 'Invalid email or password.';
return;
}
$payload = ['email' => $user->email, 'name' => $user->name];
$this->apiResponse['token'] = JwtToken::generateToken($payload);
$this->apiResponse['message'] = 'Logged in successfully.';
isset($user);
isset($payload);
}
}
I use 123456 for password and this hasher returns random string every time, but the password which is already saved in database for 123456 is
$2y$10$f7K02jamD7ZeGHLcTkP6Weh6VsthMWHiwqHJmcqbsxuLCKGCQCGCu this.
that is why it gives Invalid password in response.
My question is how to match the exact same string or hashing for request.
thanks in advance.
With reference to this answer
Use this line
password_verify($entity->password, $user->password)
instead of this
$hasher = new DefaultPasswordHasher();
$password = $hasher->hash($entity->password);
you can try this function
public function login()
{
$this->request->allowMethod('post');
$this->loadModel('Users');
$entity = $this->Users->newEntity($this->request->data, ['validate' => 'LoginApi']);
if ($entity->errors()) {
$this->httpStatusCode = 400;
$this->apiResponse['message'] = 'Validation failed.';
foreach ($entity->errors() as $field => $validationMessage) {
$this->apiResponse['error'][$field] = $validationMessage[key($validationMessage)];
}
} else {
$user = $this->Users->find()->where(['email' => $entity->email])->first();
if (count($user)) {
if (password_verify($entity->password, $user->password)) {
$payload = ['email' => $user->email, 'password' => $user->password];
$this->apiResponse['token'] = JwtToken::generateToken($payload);
unset($user->password);
$this->apiResponse['response'] = array($user);
unset($user);
unset($payload);
} else {
$this->httpStatusCode = 403;
$this->apiResponse['error'] = 'Incorrect password';
return;
}
} else {
$this->httpStatusCode = 403;
$this->apiResponse['error'] = 'Email not found';
return;
}
}
}
The general idea would be to hash according to a key you specify.
An advice would be to keep changing the key periodically. You will then need to dehash your save into the clear again using the old key then rehash on new.
I'm not sure if the option is available to you, so you might want to take it with a grain of salt.
Cheers
First of all, CakePHP ships with authentication functionality out of the box, and I'd strongly suggest that you make use of that instead of running your own, given that it sounds as if you're looking for deterministic algorithms, this can very easily backfire.
If you are using CakePHP 3.5+, look into the authentication middleware plugin (currently in RC phase), for earlier CakePHP versions, use the authentication component.
For the sake of completeness, if you were to do this manually, you'd first query the user by its unique identifier (in your case the email address), and then compare the password at PHP level, using the password hashers AbstractPasswordHasher::check() implementation:
$user = $this->Users
->find()
->where([
'email' => $this->request->data('email')
])
->first();
if (!$user ||
$hasher->check($this->request->data('password'), $user->password) !== true
) {
// authentication failed
} else {
// authentication succeeded
}

Codeigniter ignoring a function?

I'm new to CodeIgniter and have only started learning ajax. I'm trying to make a web-based management system using codeigniter, a distant relative gave me a sample of his system using codeigniter for reference before he left to work abroad. but I'm having problem with the login page of his system it keeps on refreshing the login page.
here is the login page.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CM_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->generate_login_page('backbone/login', [
'title'=>'CCC case management system - Login',
'js'=>['modules/home/login.js']
]);
}
public function authenticate_login() {
//$this->output->set_content_type('json');
//$this->form_validation->set_rules('username', '<strong>Username</strong>', 'required');
//$this->form_validation->set_rules('password', '<strong>Password</strong>', 'required');
//if($this->form_validation->run()){
$input = elements(['username','password'], $this->input->post());
$input['username'] = ucwords($input['username']);
$input['password'] = sha1($input['password']);
$result = $this->login_model->check_user_exist($input['username']);
//echo $input['username'];
//echo $result;
if($input['username'] !== ''){
if($result)
{
$result_match = $this->login_model->check_user_password_match($input['username'],$input['password'] );
//echo ''.;
if($result_match)
{
$result_user = $this->login_model->retrieve_user_information($input['username']);
$user_type_id = 0;
$user_id = 0;
if($result_user->num_rows() > 0){
foreach ($result_user->result() as $row) {
$user_type_id = $row->user_type_id;
$user_id = $row->user_id;
$username = $row->username;
}
}
//echo json_encode($result_user);
$session_data = array(
'username' => $username,
'session_id' => $this->session->userdata('session_id'),
'user_id' => $user_id,
'user_type_id' =>$user_type_id,
'is_logged_in' => 1
);
$this->session->set_userdata($session_data);
$this->session->set_userdata('login_state', TRUE);
redirect('/');
}
else
{
$this->session->set_flashdata('msg', 'Incorrect Password or Username!');
redirect('login/');
//
//echo 'Username or Password is incorrect';
//$this->output->set_output($this->set_json_output(FALSE, 'Username or Password is incorrect'));
}
}
else
{
$this->session->set_flashdata('msg', 'Invalid Username or doesnt exist !');
redirect('login/');
//
//$this->output->set_output($this->set_json_output(FALSE, 'User not Exist'));
//echo 'User not registered';
}
}else{
$this->session->set_flashdata('msg', 'Please input username !');
redirect('login/');
}
/*}else{
$error_messages = array_values($this->form_validation->error_array());
$this->output->set_output($this->set_json_output(FALSE, $error_messages));
}*/
}
}
if username and password match from database is should redirect to another page. if not a message should pop out for incorrect user / pass.
im not getting any errors but the problem is it does not redirect to another page it only keeps on refreshing the page and also if i leave user and pass empty / give an incorrect user & pass input the same thing happens. it seems like the function authenticate_login is not being executed? can anyone tell me what exactly is wrong here. Tnx.

Laravel email confirm login

Ok so what i'm trying todo, do not let login if user has not confirmed his account by email. My login code looks like that:
public function postLogin()
{
$credentials = [
'confirmed' => 0,
'email' => Input::get('email'),
'password' => Input::get('password')
];
$user = Sentinel::authenticate($credentials, false); // Login the user (if possible)
if ($user and $user->banned) {
Sentinel::logout();
$user = null;
}
if ($user) {
return $this->afterLoginActions();
} else {
$this->alertFlash(trans('app.access_denied'));
return Redirect::to('auth/login');
}
}
But i can still login without any errors. Any help? Thanks guys!
Edited: working, but now i dont get flash message if my details are incorect.
Code:
public function postLogin()
{
$credentials = [
'email' => Input::get('email'),
'password' => Input::get('password'),
'confirmed' => 1
];
$user = Sentinel::authenticate($credentials, false); // Login the user (if possible)
if ($user and $user->banned) {
Sentinel::logout();
$this->alertFlash(trans('app.banned'));
$user = null;
}
if ($user->confirmed==1) {
return $this->afterLoginActions();
}
else if ($user->confirmed==0) {
Sentinel::logout();
$this->alertFlash(trans('app.not_active'));
return Redirect::to('auth/login');
} else {
$this->alertFlash(trans('app.access_denied'));
return Redirect::to('auth/login');
}
}
Do you have a column in your table storing the information if this user passed the email confirmation? If you have one, this is what I do it with typical Laravel postLogin method.
public function postLogin(Request $request)
{
$credentialas = (your credential here);
// only check credentials
if ($this->guard()->once($credentials)) {
$currentStatus = $this->guard()->user()->status;
if (intval($currentStatus) === (NOT_CONFIRMED)) {
$this->guard()->logout();
return $this->sendSuspendedResponse($request);
} else {
$this->guard()->login($this->guard()->user());
return $this->sendLoginResponse($request);
}
}
}

Categories