Laravel API having trouble logging in - php

I have the following 2 methods to create and login a user in my API. I cannot login the user. These files are in the api.php within the routes folder. If I leave off the bcrypt($password) within the User::Create() method it still seems to hash the password somehow does the User::Create() method automatically hash the password. I am wondering if it is getting double hashed somehow.
Route::post('/register', function( Request $request){
$rules = [
'name' => 'required|max:255|alpha_dash|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
];
$input = $request->only(
'name',
'email',
'password',
'password_confirmation'
);
$validator = Validator::make($input, $rules);
if($validator->fails()) {
$error = $validator->messages();
return response()->json(['success'=> false, 'error'=> $error]);
}
$name = $request->name;
$email = $request->email;
$password = $request->password;
$user = User::create(['name' => $name, 'email' => $email, 'password' => bcrypt($password), 'api_token' => md5($email)]);
return response()->json(['success'=> true, 'data'=> $user]);
});
Route::post("/login", function (Request $request){
$rules = [
'email' => 'required|email',
'password' => 'required',
];
$input = $request->only('email', 'password');
$validator = Validator::make($input, $rules);
if($validator->fails()) {
$error = $validator->messages();
return response()->json(['success'=> false, 'error'=> $error]);
}
$email = $request->email;
$password = bcrypt($request->password);
if(\Auth::Attempt(['email' => $email, 'password' => $password])){
///How to get USER to return with Response
return response()->json(['success' => true]);
}else{
return response()->json(['success' => false, 'error' => 'Invalid Credentials', 'password' => $password, 'email' => $email]);
}
});

You bcrypt($request->password) but if you Auth::Attempt(['email' => $email, 'password' => $password]), laravel automatically hash the value.
So try in your login route just $password = $request->password;
From the docs:
The attempt method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column. If the user is found, the hashed password stored in the database will be compared with the password value passed to the method via the array. You should not hash the password specified as the password value, since the framework will automatically hash the value before comparing it to the hashed password in the database. If the two hashed passwords match an authenticated session will be started for the user.

So this is what i came up with to "log the user in".
Route::post("/login", function (Request $request){
$rules = [
'email' => 'required|email',
'password' => 'required',
];
$input = $request->only('email', 'password');
$validator = Validator::make($input, $rules);
if($validator->fails()) {
$error = $validator->messages();
return response()->json(['success'=> false, 'error'=> $error]);
}
$email = $request['email'];
$password = $request['password'];
$user = User::where('email', $email)->first();
if($user){
if(\Hash::check($password, $user->password)){
return response()->json(['success' => true, 'user' => $user]);
}else{
return response()->json(['success' => false, 'error' => 'Invalid Credentials']);
}
}else{
return response()->json(['success' => false, 'error' => 'Invalid Credentials']);
}
});

Related

How to generate custom random secret key for users when they register in Laravel 8x?

I do not know how i can generate custom secret key for each user when they register. I do not want to use passport, i just want to generate custom .
Here is my code
public function register(Request $request)
{
// $validated = $request->validate([
// 'username' => 'required',
// 'phonenumber' => 'required|digits:10|unique:users',
// 'password' => 'required|string',
// 'device_serial_number' => 'required'
// ]);
$user = User::create([
'username' => $request->username,
'phonenumber' => $request->phonenumber,
'device_serial_number' => $request->device_serial_number,
'password' => bcrypt($request->password)
]);
if($user)
{
// $token = $user->createToken('Laravel Password Grant Client')->accessToken;
$user_secret_key = Str::random(60);
$user->user_secret_key = hash('sha256', $user_secret_key);
return response()->json(['token' => $token], 200);
} else{
return response('error');
}
$user = User::create([
'username' => $request->username,
'phonenumber' => $request->phonenumber,
'device_serial_number' => $request->device_serial_number,
'password' => bcrypt($request->password),
'user_secret_key' => Str::random(60);
]);
if($user){
$token = $user->user_secret_key;
return response()->json(['token' => $token], 200);
} else{
return response('error');
}

Laravel passport: Lcobucci\JWT\Token\InvalidTokenStructure Value is not in the allowed date format

I created a laravel passport to authenticate apps via an api. The setup works local on my machine very well, but when I move the project to the server, I always get the following error:
"Lcobucci\JWT\Token\InvalidTokenStructure
Value is not in the allowed date format: 1616443683.7318161"
The user gets created and the registration throws an error 500 in the following line:
$success['token'] = $user->createToken('appToken')->accessToken;
Registration function
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'firstname' => 'required',
'lastname' => 'required',
'phone' => 'digits_between:4,30|numeric',
'email' => 'required|email|unique:users',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'message' => $validator->errors(),
], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('appToken')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
}
Downgrade Lcobucci\JWT from latest to v3.4

Laravel 5.3 Auth::attempt() always returns false

When a new user get registered then it automatically logins, Which is working fine. I am hashing the password like this :
'$newUser->password = bcrypt($request->get('password'));'
It successfully hashes the password, My users table have password column which is varchar 255. And i have remember_token field too in users table. 'dd($request->all())' returns:
array:3 [
"email" => "info#hotmail.com"
"_token" => "QIwnHacApWg3SotAXtoCCMFNK3FYFoFBAv2LSx4c"
"password" => "adminadmin"
]
And, The email and password is 100% correct against the users table record.
The request is Ajax so i have the following code of JS:
$('.post-btn').click(function(){
$.ajax({
url: '/sign-in',
type: "post",
data: {'email':$('input[name=email]').val(), '_token': $('input[name=_token]').val(),'password': $('input[name=password]').val()},
success: function(data){
console.log(data);
window.location = '/';
}
});
});
The authenticate method :
public function authenticate(Request $request) {
$validator = Validator::make($request->all(),
[
'email' => "required",
'password' => 'required'
]
);
$user = array('email' => $request->get('email'),'password' => $request->get('password'));
if (Auth::attempt($user)) {
$response = array(
'status' => 'success',
'msg' => 'Successfully Logins.',
);
$user = new \App\User;
if(Auth::check()) {
}
return \Response::json($response);
} else {
$response = array(
'status' => 'failed',
'msg' => 'Invalid Credentials!',
);
return \Response::json($response);
}
}
The input field names are correct.
What else I am missing ?
This work for me:
public function authenticate(Request $request)
{
$validator = Validator::make($request->all(),
[
'email' => "required",
'password' => 'required'
]
);
$email = $request->input('email');
$password = $request->input('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return \Response::json([
'status' => 'success',
'msg' => 'Successfully Logins.',
]);
}
else {
return \Response::json([
'status' => 'failed',
'msg' => 'Invalid Credentials!',
]);
}
}
Hope this will help you..
$user = array('email' => $request->email,'password' => $request->password);

Login fail in laravel 4.2

I'm Laravel Beginner
I make some web application using laravel 4.2 then I make login page but when I try to login it's go to login fail condition every time
anyone tell why
here is my code
public function doLogIn(){
$rules = array(
'username' => 'required|min:3',
'password' => 'required|min:3'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return 'Wrong Require';
}
else{
$user = array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'))
);
$password = Hash::make('password');
if (Auth::attempt($user))
{
return View::make('home.home');
}
else
{
return 'Wrong Password';
}
}
}
$user = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
You must remove Hash::make() in Auth::attempt(), because Laravel makes hashing automatically (I suppose that you register user with Hash::make(Input::get('password'))).

Username/password Authentication Rules in Laravel

Currently, when a user logs into my Laravel app I use the following rules...
// Validation rules
$rules = array(
'email' => 'required|email|exists:users,email',
'password' => 'required'
);
What I'm looking for is a validation rule for checking the password against the user.
From docs:
if (Auth::attempt(array('email' => $email, 'password' => $password))) {
return Redirect::intended('dashboard');
}
Example:
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
$rules = array(
'email' => 'required|email|exists:users,email',
'password' => 'required'
);
// Validate the inputs.
$validator = Validator::make($userdata, $rules);
// Check if the form validates with success.
if ($validator->passes()) {
// Try to log the user in.
if (Auth::attempt($userdata)) {
// Redirect to homepage
return Redirect::to('')->with('success', 'You have logged in successfully');
} else {
// Redirect to the login page.
return Redirect::to('login')->withErrors(array('password' => 'Password invalid'))->withInput(Input::except('password'));
}
}

Categories