hi i am building a social network with Laravel but even though i log in it always says that the password is wrong but it is correct i think the problem is in the following part of code,
please show me the error?
public function getsignin()
{
return view('auth.signin');
}
public function postsignin(Request $request)
{
$this->validate($request, [
'email'=>'required',
'password'=>'required'
]);
if( !Auth::attempt($request->only(['email','password']), $request->has('remember'))) {
return redirect()->back()->with('info','Whoops! Try again please...');
}
return redirect()->route('home')->with('info','Welcome!');
}
Try to name your parameters like this:
if( !Auth::attempt(['email' => $request->email, 'password' => $request->password], $request->has('remember'))) {
...
}
if(!Auth::attempt(['email' => $request->email, 'password' => $request->password, $request->has('remember'))]) {
...
}
When attempting, your parameter must be one array, with key=>value pairs of attributes you want to be accepted
Related
I'm trying using Laravel login authentication using different guards but I found that there is some repetition within the store method in the Login Controller (the only difference is the guard used, all other logic are the same). I just can't find a way to shorten them into some other logic such as method(function) which can be reusable. So if there is possible way, Please help me out.
public function store(Request $request)
{
$request->validate([
'username' => 'required',
'password' => 'required'
]);
if (Auth::guard('instructor')->attempt(['email' => $request->username, 'password' => $request->password])) {
if (auth('instructor')->user()->status === Instructor::HAS_DEACTIVATED) {
$request->session()->flush();
Auth::guard('instructor')->logout();
return redirect('login')->with(
'error',
'Your Account has being deactivated . Please Contact your Administrator!');
}
return redirect(route('instructor.dashboard'));
}
if (Auth::guard('student')->attempt(['email' => $request->username, 'password' => $request->password])) {
if (auth('student')->user()->status === Student::HAS_DEACTIVATED) {
$request->session()->flush();
Auth::guard('student')->logout();
return redirect('login')->with(
'error',
'Your Account has being deactivated . Please Contact your Administrator!');
}
return redirect(route('student.dashboard'));
}
return back()->with('error', 'Credentials provided do not match any record.');
}
You can create a separate function and then call that function.
public static function deleteSession($gaurd)
{
$request->session()->flush();
Auth::guard($gaurd)->logout();
return redirect('login')->with(
'error',
'Your Account has being deactivated . Please Contact your Administrator!');
}
Then in your store function call deleteSession statically.
if (auth('instructor')->user()->status === Instructor::HAS_DEACTIVATED)
{
self::deleteSession('instructor'); //change gaurd according to your need
}
This is probably not the best way to go about this, I'm sure there is a better solution, and #Aqib Javaed's seems to be it, but here's one way to shorten the code a bit that I could manage. It's not perfect but does the job done.
public function store(Request $request)
{
$request->validate([
'username' => 'required',
'password' => 'required'
]);
if (Auth::guard('instructor')->attempt(['email' => $request->username, 'password' => $request->password])) {
$userType = 'instructor';
} elseif (Auth::guard('student')->attempt(['email' => $request->username, 'password' => $request->password])) {
$userType = 'student';
} else {
return back()->with('error', 'Credentials provided do not match any record.');
}
$modelName = ucwords($userType); //turn the user type to its corresponding model name
if (auth('$userType')->user()->status === $modelName::HAS_DEACTIVATED) {
$request->session()->flush();
Auth::guard('$userType')->logout();
return redirect('login')->with(
'error',
'Your Account has being deactivated . Please Contact your Administrator!');
}
return redirect(route("$userType.dashboard"));
}
In my Register controller - I have the following method to check if a record exists in another table before creating a user:
public function getCompanyDetails($id)
{
$details = Company::where('company_id', $id)->first();
return $details;
}
protected function create(array $data)
{
$company_id = $data['com_id'];
$company_details = $this->getCompanyDetails($company_id);
if ($company_details == null) {
return redirect()
->back()
->with('warning', 'We could not find the company');
} else {
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
However when the company record is not found. I'm getting the following error message:
Cannot use object of type Illuminate\Http\RedirectResponse as an array
I believe it's expecting a return of type user. But how can I redirect back to the registration page if the company is not found?
Thanks in Advance
Try the method withErrors():
Redirect::back()->withErrors(['warning', 'We could not find the company']);
I however recommend you to use the validation rule Exists instead of having more queries and manually return a message. You can do it like so:
$request->validate([
'company_id' => 'required|integer|exists:App\Company,id',
]);
Then you won't need the extra logic and the other method.
Source: https://laravel.com/docs/7.x/validation#rule-exists
I am working in Laravel.
I have a URL like as below:
http://localhost/udonls/public/mastercandidate/candidate/reset-password/11/das#sdadas.com
Now has a function which is like
public function sendCanResLink(Request $request, $id, $email)
{
// So in this function how should i validate "$email" using laravel validation ?
}
Here is the route:
Route::get('/candidate/reset-password/{id}/{email}', [
'as' => 'candidate.reset.password',
'uses' => 'CandidateSmdnContoller#sendCanResLink'
]);
Overall !! I want to validate my email address which I get in the GET request in larvae with Laravel validation.
I know regex technique but I want to use the Laravel validation technique.
Maybe something like this:
public function sendCanResLink(Request $request, $id, $email)
{
try {
$validator = Validator::make($email, [
"email" => "required|email:rfc,dns,filter,spoof",
]);
} catch(ValidationException $validation) {
return redirect()->back();
}
}
Why spend resources on validation in this case, if you can check one on one for the user?
Route::get('/candidate/reset-password/{user}/{email}', [
'as' => 'candidate.reset.password',
'uses' => 'CandidateSmdnContoller#sendCanResLink'
]);
public function sendCanResLink(Request $request, User $user, $email)
{
if($user->email !== $email) return 'some error';
// reset code here
return 'ok';
}
2) With validator
public function sendCanResLink(Request $request, $id, $email)
{
Validator::make(compact('email'), [
'email' => ['required', 'string', 'regex:/[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/', 'max:255', 'unique:YOUR_TABLE']
])->validate();
// auto redirect back if error and use
// #error('email') {{ $message }} #enderror in blade
}
I am new to Laravel and have been fairly successful in implementing user authentication. Now to move on to the next step I must allow only users whose status in active to login. For that I have added a
status TINYINT
column in my mysql users table.
I found this in the Laravel Documentation:
Specifying Additional Conditions
If you wish, you may also add extra conditions to the authentication
query in addition to the user's e-mail and password. For example, we
may verify that user is marked as "active":
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// The user is active, not suspended, and exists.
}
Can someone please point out where I need to put this chunk. Am thoroughly confused and need some pointers.
Thanks
Have this on your LoginController:
protected function credentials(Request $request)
{
return ['username' => $request->{$this->username()}, 'password' => $request->password, 'status' => 1];
}
You just take user status and check user status is true or false. You can take status using Auth::User()->status from auth session. Try this.
if(Auth::attempt(['email'=>$request->email,'password'=>$request->password])){
$userStatus = Auth::User()->status;
if($userStatus=='1') {
return redirect()->intended(url('/dashboard'));
}else{
Auth::logout();
Session::flush();
return redirect(url('login'))->withInput()->with('errorMsg','You are temporary blocked. please contact to admin');
}
}
else {
return redirect(url('login'))->withInput()->with('errorMsg','Incorrect username or password. Please try again.');
}
Just simply put this code in your App\Auth\LoginController or elsewhere where you have your LoginController located.
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
with this code you are overriding default authenticate function
Add this to your LoginController:
protected function credentials(Request $request)
{
return [$this->username() => $request->{$this->username()}, 'password' => $request->password, 'active' => 1];
}
Add below method in
app\Http\Controllers\Auth\LoginController.php
and it would extend
AuthenticatesUsers trait
validateLogin method. So basically, it would check for your active clause as well.
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => [
'required',
Rule::exists('users')->where(function ($query) {
$query->where('active', 1);
}),
],
'password' => 'required'
]);
}
OR
Place your required code in app\Http\Controllers\Auth\LoginController.php
public function authenticate(Request $request)
{
if (Auth::attempt(['email' => $request->email, 'password' => $request->password, 'active' => 1])) {
// The user is active, not suspended, and exists.
}
}
You can override authenticated() method in your App\Http\Controllers\Auth\LoginController.php like so:
protected function authenticated(Request $request, $user)
{
if(!$user->active) {
Auth::logout();
abort(403);
};
}
Do note it's quick but not very "Laravely" solution. Sloppy.
I am using laravel multi-auth. I have a table column called status. At the time of login in, I want compare user whether it is active or in active. If active only login and if not give a message 'inactive account, please contacct to administrator'.
Here is my login controller.
<?php
namespace Modules\University\Http\Controllers;
class LoginController extends Controller
{
protected $redirectTo = '/university';
public function __construct()
{
$this->middleware('guest:university', ['except' => ['universityLogout']]);
}
public function showLoginForm()
{
return view('university::login');
}
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
//attempt to log the user in
if(Auth::guard('university')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
/****Here I want check whether university status is active or not and give message if not else login*****/
return redirect()->intended(route('university.dashboard'));
}
Session::flash('failed', 'Login credential incorrect!');
return redirect()
->back()
->withInput($request->only('email', 'remember'));
}
public function universityLogout(Request $request)
{
Auth::guard('university')->logout();
return redirect(route('university.login'));
}
}
Thanks in advance.
if(Auth::guard('university')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
if( Auth::guard('university')->user()->status == 'inactive')
{
return redirect()->route('university.dashboard-inactive');
}
return redirect()->intended(route('university.dashboard'));
}
If you want to check before login is attempted you may just query the DB by the email address to check its status and then procceed with login attempt if the status is active. If you want to login anyhow regardless of the status and redirect only if inactive, something like above would work.