Issue With Laravel 8 Auth Email Verification - laravel-8

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(){});

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.

Auth::attempt return False

My problem with Auth::attempt return False
I'm moving from codeignter to laravel 8
I start with new laravel project and connected with my DB
Ihis is my controller (change password to to save hash password in DB)
public function loginCheck(Request $request)
{
dd(Auth::attempt(['email'=>$request->email,'password'=>$request->password])); // return false
$credentials = $request->only('email', 'password');
if (Auth::attempt(['email'=>$request->email,'password'=>$request->password])) {
$request->session()->regenerate();
return redirect()->intended('dashboard');
}
return back()->withErrors(['email' => 'The provided credentials do not match our records.']);
}
public function changePasswordAction(Request $request){
$user=User::where('u_username',$request->username)->orWhere('email',$request->email)->first();
// dd($user);
//new pass
$user->password = Hash::make('123456');
$user->save();
}
this my user model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
class User extends Authenticatable
{
use HasFactory, Notifiable;
protected $table = 'user';
protected $primaryKey = 'u_id';
public $timestamps = true;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'u_fullname',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
// 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = Hash::make($password);
}
}
Email filed in DB:
email varchar(255) utf8_general_ci
Password filed in DB:
password varchar(255) utf8_general_ci
i have find solution i just remove this funcation from user model
public function setPasswordAttribute($password)
{
$this->attributes['password'] = Hash::make($password);
}
its was made a duplication in Hash code

Auth changes are not reflected laravel 5.3

I am new to laravel and want to make few changes like validation for proper email in login and sending user to login page after logout.
I have made these change in AuthenticatesUsers trait but they do not seems working.
I have changed these functions:
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|email', 'password' => 'required',
]);
}
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/login');
}
Any help will be appreciated. Thanks.
You should not change AuthenticatesUsers trait . what you can do is override the method in LoginController, so copy paste it into your LoginController
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/login');
}
This should work fine.

upload image to content in Yii

I have 2 tables, postimage and post. Postimage has fields post_id, id and image. I need to create upload form of the image and show it when content created. This image should be lincked to the content(though post_id field). Uploading form appears but images don't uploading. I tried such a way:
class PostImageController extends Controller
{
public $layout='//layouts/column2';
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new PostImage;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['PostImage']))
{
$model->attributes=$_POST['PostImage'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
$path=Yii::getPathOfAlias('webroot').'/images/'.$model->image->getName();
$model->image->saveAs($path);
//$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['PostImage']))
{
$model->attributes=$_POST['PostImage'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('PostImage');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new PostImage('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['PostImage']))
$model->attributes=$_GET['PostImage'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer $id the ID of the model to be loaded
* #return PostImage the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=PostImage::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param PostImage $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='post-image-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
PostImage model:
<?php
/**
* This is the model class for table "PostImage".
*
* The followings are the available columns in table 'PostImage':
* #property integer $id
* #property string $image
* #property integer $post_id
*
* The followings are the available model relations:
* #property Post $post
*/
class PostImage extends CActiveRecord
{
/**
* #return string the associated database table name
*/
public $image;
public function tableName()
{
return 'PostImage';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
//array('image', 'required'),
array('post_id', 'numerical', 'integerOnly'=>true),
array('image', 'length', 'max'=>255),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, image, post_id', 'safe', 'on'=>'search'),
array('image', 'file', 'types'=>'jpg, gif, png'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'post' => array(self::BELONGS_TO, 'Post', 'post_id'),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'image' => 'Image',
'post_id' => 'Post',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* #return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('image',$this->image,true);
$criteria->compare('post_id',$this->post_id);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* #param string $className active record class name.
* #return PostImage the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
And this is view of the form:
<?php
echo CHtml::form('','post',array('enctype'=>'multipart/form-data'));
echo CHtml::activeFileField($model, 'image');
echo CHtml::endForm();
?>

Laravel "auth controller not found" exception

I am making admin panel in LARAVEL4.2.*. I make the controller in "admin" folder and also a view in views "admin" folder. My controller code is
namespace admin;
class AuthController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
and my routes coding is:
Route::get('admin/login', array('as' => 'admin.login', 'uses' => 'App\Controllers\Admin\AuthController#getLogin'));
I have also tried "composer update" and "composer dump-autoload" above 50 times. My url is localhost/laraveltest/public/admin/login.
You defined your namespace as admin, therefore you have to use this also in your routes:
Route::get('admin/login', array('uses' => '\admin\AuthController#getLogin'));