Error with Laravel authentication - authentication

I'm new to Laravel and I am trying to implement authentication in my application, when I post the login form this error is returned in my browser:
I have no idea what this error means, where it occurs, or how to fix it.
This is my signin function in my authentication controller that handles all logins:
public function signin()
{
// validate the info, create rules for the inputs
$rules = array(
'email' => 'required|email', // make sure the email is an actual email
'password' => 'required|min:6' // password can only be alphanumeric and has to be greater than 3 characters
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('/authentication')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {
// create our user data for the authentication
$user = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($user)) {
// validation successful!
// redirect them to the secure section or whatever
// return Redirect::to('secure');
// for now we'll just echo success (even though echoing in a controller is bad)
return Redirect::to('dashboard.index');
} else {
// validation not successful, send back to form
return Redirect::to('/authentication')
->with('failed', 'Incorrect email / password!');
}
}
}
This is my User model:
<?php
class User extends Eloquent{
// MASS ASSIGNMENT -------------------------------------------------------
// define which attributes are mass assignable (for security)
protected $fillable = array('email','school_id','role_id','activation_key','reset_key','login_status','account_status');
// LINK THIS MODEL TO OUR DATABASE TABLE ---------------------------------
protected $table = 'users';
// DEFINE RELATIONSHIPS --------------------------------------------------
public function roles() {
return $this->belongsTo('Role');
}
public function schools() {
return $this->belongsTo('Institution');
}
public function lectures() {
return $this->hasOne('Lecturer');
}
public function students() {
return $this->hasOne('Student');
}
public function getId()
{
return $this->id;
}
}

Let's take a look at Laravel's default User model:
class User extends Eloquent ...
so far so good
... implements UserInterface, RemindableInterface {
Oooops looks like you're missing something ;)
Also the two traits are not unimportant.
Here's how it should look like:
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
// MASS ASSIGNMENT -------------------------------------------------------
// define which attributes are mass assignable (for security)
protected $fillable = array('email','school_id','role_id','activation_key','reset_key','login_status','account_status');
// [the rest of your model]

Related

Laravel Default validation message wouldn't appear

I am developing a Laravel backend API. I am trying to build an API that will accept two fields which are name and email with validation.
Here is my controller file:
public function register(RegisterUserRequest $request)
{
// retrieved validated user
$validated = $request->validated();
}
Here is my RegisterUserRequest file:
class RegisterUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email:rfc,dns',
];
}
}
I am trying to pass the invalid email format to the backend but the error message not appearing:
I had already set my header to Accept:application/json in my postman.
Is anyone know how to resolve the problem? Really appreciated!
Thanks.

Issue With Laravel 8 Auth Email Verification

I'm Using Laravel 8.x And i'm trying to make login/register With Email verification
I followed Some Tutorials,Blogs but didn't get desired output
I want:-
Whenever User Register themselve An Verification Email must send to there email
(Email Is Sent but not able to verify by that url so i follow some laracast blog by that i'm able to verify by that verification url)
but the issue is if i didn't verified my self i'm still able to login into my application
Here Is Codes
HomeController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(['auth','verified']);
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
','--------------------------------------------------------------------------
',' Register Controller
','--------------------------------------------------------------------------
','
',' This controller handles the registration of new users as well as their
',' validation and creation. By default this controller uses a trait to
',' provide this functionality without requiring any additional code.
','
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'contact' => ['required','min:10'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required','string','min:8','confirmed','regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{6,}$/'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'contact' => $data['contact'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
Veification Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;
use Illuminate\Auth\Access\AuthorizationException;
use App\Models\User;
class VerificationController extends Controller
{
/*
|--------------------------------------------------------------------------
| Email Verification Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling email verification for any
| user that recently registered with the application. Emails may also
| be re-sent if the user didn't receive the original email message.
|
*/
use VerifiesEmails;
/**
* Where to redirect users after verification.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
// $this->middleware('auth');
$this->middleware('signed')->only('verify');
$this->middleware('throttle:6,1')->only('verify', 'resend');
}
public function verify(Request $request)
{
// if ($request->route('id') != $request->user()->getKey()) {
// throw new AuthorizationException;
// }
$user = User::find($request->route('id'));
auth()->login($user);
if ($request->user()->hasVerifiedEmail()) {
return redirect($this->redirectPath());
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect($this->redirectPath())->with('verified', true);
}
}
Route
Auth::routes(['verify' => true]);
Route::group(['prefix'=>'user', 'middleware' => 'auth'],function(){});

notification system in Laravel 8

I am working on a laravel app where i have a user(organizer) who post an event ,and other users can comment on this event .
I am trying to make notifications system in laravel 8 between the organizer and the users when commenting on these event !
but i get this error (Call to a member function notify() on null).
This is my class :
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class NewCommentPosted extends Notification
{
use Queueable;
protected $user;
protected $event;
public function __construct($user, $event)
{
$this->user = $user;
$this->event = $event;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
'user' => $this->user->name,
'eventTitle' => $this->event->title,
'eventId' => $this->event->id
];
}
This is storefunction() in my controller :
namespace App\Http\Controllers;
use App\Models\Event;
use App\Models\Comment;
use App\Notifications\NewCommentPosted;
use Illuminate\Http\Request;
class CommentController extends Controller
{
public function store(Event $event)
{
request()->validate([
'content' => 'required|min:5'
]);
$comment = new Comment();
$comment->content = request('content');
$comment->user_id = auth()->user()->id;
$event->comments()->save($comment);
$event->user->notify(new NewCommentPosted(auth()->user(), $event));
return redirect()->route('events.show', [$event->id, $event->title]);
}
Any help please !!?

Successful Pages after registration in yii controller

I want to redirect to another pages after successful registration. How I can I restrict this pages to be visited directly from url. only display after registration.
public function actionRegistration()
{
.......
if($model->save())
{
$this->redirect(Yii::app()->request->baseUrl.'/site/success_registration');
}
............
}
public function actionSuccess_registration()
{
$this->render('success_registration');
}
You could probably add some rules and filters, or you could check the referrer in the actionSuccess_registration but the simplest way to make the view non-accessible from anywhere else would be to render the success_registration view from inside actionRegistration. actionSuccess_registration is therefore redundant if all it does is render the view.
public function actionRegistration()
{
.......
if($model->save())
{
$this->render('success_registration');
return;
}
............
}
check this out for authentication in yii.
so u could do like this:
class YourController extends CController
{
......
public function filters()
{
return array(
'accessControl',
);
}
public function accessRules()
{
return array(
array('deny',
'actions'=>array('registration'),
'users'=>array('?'),
),
array('allow',
'actions'=>array('success_registration'),
'users'=>array('#'),
),
array('deny',
'actions'=>array('delete'),
'users'=>array('*'),
),
);
}
}
in your method
public function actionRegistration()
{
.......
if($model->save())
{
$this->redirect($this->createUrl('site/success_registration'));
}
............
}
It would be easier if you used flash messages instead. That's what they are there for.
public function actionRegister()
{
if(Yii::app()->user->hasFlash('registered')) {
$this->render('success_login');
} else {
// Process POST registration data here.
// If registration was successul you do:
Yii::app()->user->setFlash('registered',true);
$this->refresh();
// Otherwhise you render the registration form here
}
}
you should go to the project file and go to the protected folder ->controller folder and then open the SiteController.php
please find the "public action actionLogin()" in the SiteController.php.
after that find this line:
$this->redirect(Yii::app()->user->returnUrl);
in the actionLogin() function.
for example i want it is redirect to the user controller.i add .'?r=user' at the end of code.
$this->redirect(Yii::app()->user->returnUrl.'?r=user');

Yii: handling login without a login page

I'm working with a server-based authentication, so I'm attempting to implement a custom login system in Yii. To learn the system, I tried to create a dummy authentication class that would automatically log in a user. I included the class in the config, but I can't figure out how to log users in.
Is there a way to automatically log in on the first use of the application (eg as a session is created?) Or is there some better way of achieving this?
The base of this is a custom authentication class:
class MyAuthentication
extends CApplicationComponent
implements IUserIdentity {
private $_username = '';
private $_authenticated = False;
...
public function authenticate()
{
$this->_username = 'exampleUser';
$this->_authenticated = True;
return True;
}
public function getIsAuthenticated()
{
return $this->_authenticated;
}
seems like you're close. something like this should work re your example:
class UserIdentity extends CUserIdentity
{
private $_username = '';
private $_authenticated = FALSE;
public function authenticate()
{
$this->_username = 'exampleUser';
$this->_authenticated = TRUE;
return $this->_authenticated;
}
public function getIsAuthenticated()
{
return $this->_authenticated;
}
}
Create a filter for Controller and check the user was authenticated or not. If not, authenticate a user.
Since my authentication was based on a server-side variable, I was able to use the expression feature of the accessRules array to check if that variable was true. I wrote a custom class to help:
class User
{
public function is_authenticated()
{
return True;
}
}
And updated my rules to use an expression check instead of a user check, as described by the documentation:
public function accessRules()
{
return array(
array('allow',
'actions'=>array('index','view', 'new'),
'expression'=>'User::is_authenticated()',
...