laravel 5.2 auth Conditions for email verify - laravel

i want to edit auth and add Additional Conditions
for check user for active or ...
where can edit authcontroller code?

First you need a status column in users table to mark the user as active or inactive.
To check the user status during login you need to modify this file:
project_folder\vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
You can change validateLogin() method. I assume, for active user the status code is 1 and 0 for inactive user. Your code should look like this:
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required', 'status' => 1,
]);
}

In Auth\AuthController.php, add this function ( I assume the column name for user status is "is_active" ):
public function authenticated($request, $user) {
if ($user->is_active != 'Y') {
Auth::logout();
return redirect('login')->withErrors([
$this->loginUsername() => 'Your '.$this->loginUsername().' is not active. Please contact Administrators'
]);
}else {
return redirect()->intended($this->redirectPath());
}
}

Related

Laravel only ignore field if user id is present

If an user is logged in I need to ignore if the email field already exists in the users table. But if the user is not logged in the rule should be applied.
Naturally I only have the user id if the user is logged in. So what is your alternative to this?
public function rules(): array
{
return [
'email' => ['required', 'email:filter', Rule::unique('users')->ignore(Auth::user()->id)],
];
}
You can define the rules as a variable, and append the Rule if the Auth::user() is present:
public function rules(): array {
$rules = [
'email' => [
'required',
'email:filter'
]
];
if (Auth::user()) {
$rules['email'][] = Rule::unique('users')->ignore(Auth::user()->id);
}
return $rules;
}
However, I would expect that you still want emails to be unique within the users table of your Database, regardless if a User is logged in or not, in which case you can use a ternary:
public function rules(): array {
return [
'email' => [
'required',
'email:filter',
Auth::user() ? Rule::unique('users')->ignore(Auth::user()->id) : Rule::unique('users')
]
];
Use whatever approach works best for your scenario.

How to create an invitation system in Laravel PHP

Im new in laravel and I'm watching a youtube playlist to build my 1st project....
now I'm trying to implement an inv only system
so the register form looks like
username:
inv code:
password:
I've already created a migration which has
user_id - this is user id of the user who created the invite
code - the code which will get validated at time of registration and then deleted
{timestamps}
so the issue im having is:
how do I verify that the invite entered by user exists in the table "inv_codes" and matches the column "code" and then delete it after registration is complete
here is a minimal reproducible example
lass RegisterController extends Controller
{
public function __construct()
{
$this->middleware(['guest']);
}
public function index()
{
return view('auth.register');
}
public function submit(Request $request)
{
$this->validate($request, [
'username' => 'required|max:6',
'password' => 'required',
]);
User::create([
'username' => $request->username,
'password' => Hash::make($request->password),
]);
auth()->attempt($request->only('username', 'password'));
return redirect()->route('dashboard');
}
}
Suppose that you have code column in both users and inv_codes tables. Now during registration, you can use validation. Something like this:
$request->validate([
'code' => 'required|exists:inv_codes,code',
// ... rest of registration fields
]);
Then you can delete that row in inv_codes table by something like this:
You can read more at: https://laravel.com/docs/8.x/validation#quick-writing-the-validation-logic
DB::table('inv_codes')->where('code', $request->code)->delete();
You can read more at: https://laravel.com/docs/8.x/queries#delete-statements
Ideally you would create a table to hold the invitations and an accompanying Eloquent model. On register, you can check if the invitation code the user entered is valid by using a couple of ways.
Manually
Invitation::where('code', request()->inv_code)->firstOrFail();
Validation
request()->validate([
'inv_code' => ['exists:inv_codes,code'],
]);
In either case, you need to fetch the invitation and then delete it after registering the user.
$invitation->delete();

Pass Session Data From Controller to View in Laravel 6

I want to create edit user account feature in my Laravel project, so i want to pass current session data from controller to view but i got an error Trying to get property 'name' of non-object. Before passing data, i create login feature to get session, here is my LoginController to get session:
public function loginprocess(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
return redirect()->route('index.user');
}
return back()->withInput($request->only('email', 'remember'));
}
Then in another controller i create this function:
public function account()
{
$data=[
'account' => Session::get('user'),
'titleweddinc' => "Account - User Dashboard"
];
return view('user.account',$data);
}
And in the view i use this code:
{{ $account->name }}
In database user i sure I make sure in the user table there is a name field. I try to get {{ $titleweddinc }} and it can appeat. Does anyone know what my mistake is?
use like this
public function account()
{
$data=[
'account' => Session::get('user'),
'titleweddinc' => "Account - User Dashboard"
];
return view('user.account',compact('data'));
}
If Object then print like
{{ $data->account->name}}
Check if Array then print like
{{ $data['account']['name']}}

Find data before validate form request laravel

I want to update the data using the request form validation with a unique email role, everything works normally.
Assume I have 3 data from id 1-3 with url:
127.0.0.1:8000/api/user/update/3
Controller:
use App\Http\Requests\Simak\User\Update;
...
public function update(Update $request, $id)
{
try {
// UPDATE DATA
return resp(200, trans('general.message.200'), true);
} catch (\Exception $e) {
// Ambil error
return $e;
}
}
FormRequest "Update":
public function rules()
{
return [
'user_akses_id' => 'required|numeric',
'nama' => 'required|max:50',
'email' => 'required|email|unique:users,email,' . $this->id,
'password' => 'required',
'foto' => 'nullable|image|max:1024|mimes:jpg,png,jpeg',
'ip' => 'nullable|ip',
'status' => 'required|boolean'
];
}
but if the updated id is not found eg:
127.0.0.1:8000/api/user/update/4
The response gets The email has already been taken.
What is the solution so that the return of the data is not found instead of validation first?
The code looks like it should work fine, sharing a few things below that may help.
Solution 1: Check if $this->id contains the id you are updating for.
Solution 2: Try using the following changes, try to get the id from the URL segment.
public function rules()
{
return [
'user_akses_id' => 'required|numeric',
'nama' => 'required|max:50',
'email' => 'required|email|unique:users,email,' . $this->segment(4),
'password' => 'required',
'foto' => 'nullable|image|max:1024|mimes:jpg,png,jpeg',
'ip' => 'nullable|ip',
'status' => 'required|boolean'
];
}
Sharing one more thing that may help you.
Some person uses Request keyword at the end of the request name. The Update sounds generic and the same as the method name you are using the request for. You can use UpdateRequest for more code readability.
What I understand from your question is, you need a way to check if the record really exists or not in the form request. If that's the case create a custom rule that will check if the record exists or not and use that rule inside your request.
CheckRecordRule
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class CheckRecordRule implements Rule
{
protected $recordId;
public function __construct($id)
{
$this->recordId = $id;
}
public function passes($attribute, $value)
{
// this will check and return true/false
return User::where('id', $this->recordId)->exists();
}
public function message()
{
return 'Record not found.';
}
}
Update form request
public function rules()
{
return [
'email' => 'required|email|unique:users,email,' . $this->id.'|'. new CheckRecordRule($this->id),
];
}
So when checking for duplicate it will also check if the record really exists or not and then redirect back with the proper message.

Laravel auth attempt not working or returning false always?

I've been looking all over the place (I checked all the other duplicate questions and answers ), no luck. I don't understand what am I doing wrong, all the values are coming from post, but Auth:attempt keeps on failing/returning false, if I try to implement login manually it won't authenticate as I am expecting, Also do I have to make or use separate methods like for validation, credentials, username ..etc ?
Here is my login Controller > login method
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'usermail' => 'required|max:255',
'password' => 'required_with:usermail',
],[
'password.required_with' => "The password field is empty."
]);
if ($validator->fails()) {
return redirect()
->route('admin.login')
->withErrors($validator)
->withInput();
}
$usermail = $request->get('usermail');
$password = $request->get('password');
$remember = $request->get('rememberMe');
if(filter_var($usermail, FILTER_VALIDATE_EMAIL)) {
$isEmailExist = User::where('user_email',$usermail)->first();
if($isEmailExist != null){
if(Auth::attempt([
'user_email' => $usermail,
'user_pass' => $password
])){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the email address <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid email address.'
]);
}
}else{
$isUsernameExist = User::where('user_login',$usermail)->first();
if($isUsernameExist != null){
if(Auth::attempt([
'user_login' => $usermail,
'user_pass' => $password
],$remember)){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the username <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid username. Lost your password?'
]);
}
}
}
And this is my user migration schema,
Schema::create('vw_users', function (Blueprint $table) {
$table->bigIncrements('ID');
$table->string('user_login','60')->unique()->default('');
$table->string('user_pass');
$table->string('user_email','100')->unique()->default('');
$table->rememberToken();
});
Here is how i seed user,
User::create([
'user_login' => 'admin',
'user_pass' => Hash::make("123456"),
'user_email' => 'admin#gmail.com',
]);
OK OK OK,
I made it work, I think in laravel framework we can only create the column name for the password is "password" field in database authentication table.
I updated the following changes:-
I renamed the password field name from migration schema the "user_pass" to "password". (Also updated in login controller and user model).
Added following code into user model:-
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
...
}
I checked twice to confirm so I revert back it didn't work.
If i make any sense to anyone please let me know and help me understand.
I've looked into very similar posts like this Laravel: How can i change the default Auth Password field name
can I please have a reference book or blog for all the laravel predefined libraries and functions? I know the vendor folder is full of surprises but still, I need more references.
Thank you so much for your time.

Resources