Laravel auth, disable password - php

I am trying to disable the password verification system from my laravel website. I want to login my users using only their first name and last name. Form wise and register wise and database wise, password field has been removed completely. But in login controller, i am having some issues, it does not seem to work. Here is my code:
public function login(Request $request)
{
$first_name = $request->first_name;
$last_name = $request->last_name;
$user = User::where(['first_name' => $first_name, 'last_name' => $last_name])->first();
if (!$user) {
return redirect()->back()->withInput($request->only('first_name', 'last_name'))->withErrors([
'first_name' => 'We could not find you in our database, if you think this is a mistake kindly contact the site administrators',
]);
}
Auth::login($user);
return redirecte('/');
}
in the above code, i am getting the error message
We could not find you in our database, if you think this is a mistake kindly contact the site administrators
regardless of what info (true of false) i insert in my form.

Yes thank you #laravel levaral for answering, but i found out the problem.
I am going to quote a user from laracasts
If you're going to group multiple where clauses into a single where(), each needs to be it's own array, within an array. You're sending a single array. You're also using =>, which isn't correct. The parameters for each where statement are separated by commas.
so for whoever wants to see the new working code:
public function login(Request $request)
{
$first_name = $request->first_name;
$last_name = $request->last_name;
$user = User::where('first_name', $first_name)
->where('last_name', $last_name)
->first();
if (!$user) {
return redirect()->back()->withInput($request->only('first_name', 'last_name'))->withErrors([
'first_name' => 'We could not find you in our database, if you think this is a mistake kindly contact the site administrators',
]);
}
Auth::login($user);
return redirect('/');
}

First of all, you have to check either the first_nameand last_name matches the database.
$user = User::where(['first_name' => $first_name, 'last_name' => $last_name])->first()
You have a problem in above lines.
public function login(Request $request)
{
$first_name = $request->first_name;
$last_name = $request->last_name;
$user = User::where(['first_name' => $first_name, 'last_name' => $last_name])->first();
if (!$user) {
return redirect()->back()->withInput($request->only('first_name', 'last_name'))->withErrors([
'first_name' => 'We could not find you in our database, if you think this is a mistake kindly contact the site administrators',
]);
}
Auth::loginUsingId($user->id);
return redirecte('/');
}

Related

How to Generate unique usernames using Laravel

I am trying to generate unique usernames for users upon registration using laravel. I want to include both the first name and the last name. If I use only the first or last name it works, but if I try both, it enters a blank value to the database. Please Help.
Here is my code:
Auth Controller
`
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'firstname'=>'required|max:191',
'lastname'=>'required|max:191',
'phone'=>'required',
'email'=>'required|email|max:191|unique:users,email',
'password'=>'required|min:6',
]);
if($validator->fails())
{
return response()->json([
'validation_errors'=>$validator->messages(),
]);
}
else
{
$userObject = New User;
$userName = $userObject->generateUserName($request['firstname'.'lastname']);
$user = User::create([
'firstname'=>$request->firstname,
'lastname'=>$request->lastname,
'phone'=>$request->phone,
'email'=>$request->email,
'password'=>Hash::make($request->password),
'username'=>$userName,
]);
$token = $user->createToken($user->phone.'_Token')->plainTextToken;
return response()->json([
'status'=>200,
'username'=>$user->firstname,
'token'=>$token,
'message'=>'Registered Successfully',
]);
}
}
`
The User Model
`
public function generateUserName($firstname){
$username = Str::lower(Str::slug($firstname));
if(User::where('username', '=', $username)->exists()){
$uniqueUserName = $username.'-'.Str::lower(Str::random(5));
$username = $this->generateUserName($uniqueUserName);
}
return $username;
}
`
your issue generate from $request['firstname'.'lastname'], you are actually Concating keys of a request array though you want to Concat the value of 2 separate keys which means to use it like this $request['firstname'] and $request['lastname']. please change the below line
$userName = $userObject->generateUserName($request['firstname'.'lastname']);
with this
$userName = $userObject->generateUserName($request['firstname'].$request['lastname']);

user vaidation / unique email using cartylyst sentinel

I want to validate user using sentinel and i want to check that unique user email_address my post request looks like:
public function postRegister(Request $request)
{
$user = Sentinel::register($request->all());
$activation = Activation::create($user);
$this->sendEmail($user, $activation->code);
return redirect()->back()->with([
'sucess' => 'user registered successfully'
]);
}
Here i am adding first_name , last_name , email_address and password but i want to validate these fields and with unique email_address?
How i can do that?
Your help will be highly appreciated!
For example, you can use this https://laravel.com/docs/5.6/validation
$validatedData = $request->validate([
'email' => 'required|email|unique:users|max:255',
]);
After this, put $validateData to register
$user = Sentinel::register($validatedData);
But, for first step, i recommended use Custom request class, and put validation in rules() method. https://laravel.com/docs/5.6/validation#creating-form-requests

Not able to authenticate in laravel

I have this error in Laravel latest for authentication
Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must
be an instance of Illuminate\Contracts\Auth\UserProvider, null given,
called in
G:\xampp\htdocs\newrestaurantcrm\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php
can anyone give me an idea about this error why this error is occurring?
I am using below code for authentication in my Auth\AuthController.php file
protected function login(Request $request) {
$email = $request->email;
$password = bcrypt($request->password);
if (Auth::login(['email' => $email, 'password' => $password])) {
return redirect()->intended('/admin/dashboard');
}
}
Change your code to
public function login(Request $request) {
$email = $request->get('email');
$password = $request->get('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('/admin/dashboard');
}
}
I changed the protected to public, Auth::login() to Auth::attempt(). If you use login, you will actually have to pass the User object you like to login as. You do not need to encrypt the password to pass to attempt and. To make this simpler you can write
public function login(Request $request) {
if (Auth::attempt($request->only('email', 'password'))) {
return redirect()->intended('/admin/dashboard');
}
}
This of course assumes that your form has correct name for fields, email and password and also has same field email and password in users table as well.
When you are authenticate user against email and password then use Auth::attempt or Auth::once (For single request). When we have user instance and we want to login with that user instance then we use Auth::login. For your case use Auth::attempt like this
public function login(Request $request) {
$email = $request->email;
$password = bcrypt($request->password);
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('/admin/dashboard');
}
}
Details: https://laravel.com/docs/5.6/authentication#included-authenticating

Laravel 5 custom login with username OR email using the Attempt method

In my laravel app, at the start I had decided to create my own custom login controller, rather than use the base one.
public function postSignin(Request $request, AppMailer $mailer) {
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect()->back()->with('info', 'Could not sign you in with those details.');
}
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'), 'verified' => 0]))
{
$mailer->sendEmailConfirmationTo(Auth::user());
Auth::logout();
return redirect()->back()->with('info', 'Email verification required.');
}
Auth::user()->last_login = new DateTime();
Auth::user()->save();
return redirect()->back()->with('info', 'You are now signed in.');
}
And now I want to edit this so that users can also login with their usernames and not just their emails, using the same field. However, the attempt method is confusing. It seems to expect an email even after I switch the values around.
The Auth documentation isn't very helpful in this case either. It asks me to add this:
public function username()
{
return 'username';
}
in the login controller, but obviously this is for a default setup.
You can use the 'FILTER_VALIDATE_EMAIL' checker.
$username = $request->get('username');
$password = $request->get('password');
$remember_me = $request->get('remember_me','1');
$field = filter_var($username,FILTER_VALIDATE_EMAIL)? 'email': 'username';
if(Auth::attempt([$field => $username,'password' => $password],$remember_me)){
//Auth successful here
}
Meaning FILTER_VALIDATE_EMAIL do check the string whether it is in email format or not.
I hope this sample code helps you.
-ken

Laravel 5.1 bcrypt and login

When I'm registering a new user in the Laravel framework, I'm currently doing it like this,
// Creating a new user
$user = new User;
$user->firstname = $data['firstname'];
$user->lastname = $data['lastname'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->save();
This works great, and I am able to login to the application. However, I want the user to have an option to change their passwords in their settings page. Doing this, i used the same technique, using
$newPass = bcrypt($response->new_password);
and updating the user field. However, after doing this, I'm not able to login? I'm using the built in authentication service in laravel for the registration/login.
What am I doing wrong here? and should i do it another way?
I also tried to bcrypt my current password, and i got an completely different hash than the one stored in the database.
This so confusing..
Updated with controller code,
// Validation
$this->validate($request, [
'email' => 'email',
'password' => 'min:8|confirmed',
'current_password' => 'required',
]);
// Getting the user ID
$userId = Auth::id();
// Dummy hack check, change later.
if(!Auth::attempt(['id' => $userId, 'password' => $request->current_password]))
{
return redirect('settings')->with('alert','current password is wrong.');
}
// Everything is validated and ok to proceed
if($request->email)
{
$data['email'] = $request->email;
}
if($request->password)
{
$data['password'] = bcrypt("helloworld");
}
$user = User::where('id',$userId)->update($data);
dd($data);
Dump data for the inputs,
+request: ParameterBag {#40 ▼
#parameters: array:5 [▼
"_token" => "JQIIuCjiKQmbK0X5zCM6czYD1vIoh4PGjLO4qrFm"
"email" => "testing#gmail.com"
"password" => "thisisnewpass"
"password_confirmation" => "thisisnewpass"
"current_password" => "helloworld"
]
}
This code is closer to how Laravel handles resetting a user's password internally. Give it a try.
// Getting the User
$user = Auth::user(); // Gets the currently logged in User
$credentials = [
'id' => $user->id,
'password' => $request->input('current_password')
];
// Make sure current password is correct
if (!Auth::validate($credentials)) { // Checks the User's credentials
return redirect('settings')->with('alert','current password is wrong.');
}
// Change the password
if ($request->has('password')) {
$user->password = bcrypt($request->input('password'));
}
// Save any changes
$user->save();
It looks like you're using the same form to update the User's email address too, so update the code to fit your needs.
Storing the password in an new variable seems to fix the issue (not sure why?) however, this is the code that made everything work,
// Validation
$this->validate($request, [
'email' => 'email',
'password' => 'min:8|confirmed',
'current_password' => 'required',
]);
// Getting the user ID
$userId = Auth::id();
$newPassword = $request->password;
// Dummy hack check, change later.
if(!Auth::attempt(['id' => $userId, 'password' => $request->current_password]))
{
return redirect('settings')->with('alert','Wrong password.');
}
// Everything is validated and ok to proceed
if($request->email)
{
$data['email'] = $request->email;
}
if($request->password)
{
$data['password'] = bcrypt($newPassword);
}
// Getting, and checking if the current password is corrent.
$user = User::where('id',$userId)->update($data);
echo $newPassword . "<br><br>";
dd($data);
If there is any explanations that i don't see, please let me know why. However, it's working now.
For Laravel in year 2017, this is how we roll:
//create a setter method in your controller
public function setPasswordAttribute( $password ) {
if ( $password !== null ) {
if ( is_null(request()->bcrypt) ) {
$this->attributes['password'] = bcrypt($password);
} else {
$this->attributes['password'] = $password;
}
}
}
Check this link they all are talking about placing it in model but it works inside my own controller.

Categories