Laravel - Can't upload the user in multiauth system - laravel

I am using multi auth login system. I made register, login and mail system. But i don't know how to make update function. Every member needs to update own profile. My problem is i can't get the related users details. id, name, etc...
In my auth.php customer guards was created:
'customer' => [
'driver' => 'session',
'provider' => 'customers',
]
Also this is the CustomerLoginController:
class CustomerLoginController extends Controller{
public function __construct()
{
$this->middleware('guest:customer')->except('logout', 'userLogout');
}
public function showLoginForm(){
return redirect()->route('homepage');
}
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
if (Auth::guard('customer')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
return redirect()->intended(route('homepage'));
}
return redirect('/')->with('error_login', 'Login Fail');
}
public function logout(Request $request) {
Auth::guard('customer')->logout();
return redirect('/');
}
I added the function show($id) and function update(Request $request)
But as i told. Can't get the related user.
My last try is:
$user = Customer::find($id);
this is the right way to doing this i think. But i can't connect them.
ps: i am not using --resources (crud). I must do that manually.

Related

Unauthenticated error when using Sanctum Token to get API Request with domain URL

I am working on a project (web and api) and using Laravel sanctum in my project, I am trying to make an api get request on postman to see user information after logged in but I keep getting this "message": "Unauthenticated." error but I notice that when I was using the get to access user information from my api on localhost (http://127.0.0.1:8000/) it was showing the details and working fine, but when I test it with my domain url (http://sotun.com/mark/live) show Unauthenticated.
My Controller
class AuthApiController extends Controller
{
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
'device_name' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
$token = $user->createToken($request->device_name)->plainTextToken;
$response = [
'user' => $user,
'token' => $token,
];
return response ($response, 201);
}
public function user(Request $request)
{
return $request->user();
}
}
api.php
use App\Http\Controllers\AuthApiController;
Route::group(['middleware' => ['auth:sanctum']], function() {
Route::get('/user', [AuthApiController::class, 'user']);
Route::post('/logout', [AuthApiController::class, 'logout']);
});
User Model
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable implements MustVerifyEmail
{
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
'user_id',
'user_type',
'user_job',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
In the .env I added the below
.env
SANCTUM_STATEFUL_DOMAIN=http://sotun.com/mark/live
SESSION_DOMAIN=http://sotun.com/mark/live
postman output
But the same result, please I will help to solve this Thanks
Modify your .env file configurations to:
SANCTUM_STATEFUL_DOMAINS="sotun.com,127.0.0.1:8000"
SESSION_DOMAIN=sotun.com
Notice the pluralization of the environmental variable SANCTUM_STATEFUL_DOMAINS.

Laravel: how change rules of validation in reset password

If a user enters a wrong email when trying to reset a password, he receives an error message "passwords.user". I'm trying to override the methods of rules and messages of trait Auth/ResetsPasswords.php but my user gets all the same message
This is my controller
class ResetPasswordController extends Controller
{
use ResetsPasswords;
public function __construct()
{
$this->middleware('guest');
}
protected function rules()
{
return [
'email' => 'exists:users.email',
];
}
protected function validationErrorMessages()
{
return [
'email.exists' => 'The email is not registered',
];
}
}
trait method does not contain key 'passwords.user'
protected function rules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:6',
];
}
but it is in the folder config/auth
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
How can I add my own rules and error messages when resetting password?
Edit: I have corrected the previous answer, because I was pointing to the wrong file
The file you are looking for, to translate your message is in resources/lang/en/passwords.php and there you can customize che 'user' entry.
Of course if en is not your current locale, change that directory to your language

Laravel create new records error

I have a few Form on create different records with different validation rules.
My route (web.php) file:
Route::group(['middleware' => ['auth']], function () {
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/home/info/create/{id}', 'InfoController#create');
Route::post('/home', 'InfoController#store')->name('home');
Route::get('/home/info/delete/{id}', 'InfoController#delete');
Route::get('/home/odbor/create/{id}', 'OdborController#create');
Route::post('/home', 'OdborController#store')->name('home');
Route::get('/home/odbor/delete/{id}', 'OdborController#delete');
Route::get('/home/zamestnanec/create/{id}', 'ZamestnanecController#create');
Route::post('/home', 'ZamestnanecController#store')->name('home');
Route::get('/home/zamestnanec/delete/{id}', 'ZamestnanecController#delete');
Route::get('/home/program/create/{id}', 'ProgramController#create');
Route::post('/home', 'ProgramController#store')->name('home');
Route::get('/home/program/delete/{id}', 'ProgramController#delete');
});
Creat, store, delete function :
(function is simillar in all controller)
public function create(Fakulta $id)
{
return view('create.info', compact('id'));
}
public function store(CreateInfoRequest $request)
{
Info::create($request->all());
return redirect('home');
}
public function delete($id)
{
Info::where('id',$id)->delete();
return redirect('home');
}
And problem is, when I want create new e.g. Info (/home/info/create) after touch submite button I get validation errors. On validation is using file specified in last Controller from middleware group (ProgramController#store) and I don't know why. But when I move Route::post('/home', 'InfoController#store')->name('home'); on last line of group or create new program (/home/program/create) everything is OK.
Easier:
After touch submit button is dont use this file
CreateInfoRequest.php file:
public function rules()
{
return [
'title' => 'required',
'description' => 'required',
'event_date' => 'required|date|after:today'
];
}
but this one :
CreateProgramRequest.php
public function rules()
{
return [
'title' => 'required',
'titul' => 'required',
'length' => 'required',
'forma' => 'required',
'typ'=> 'required',
'description' => 'required',
'fakulta_id' => 'required',
];
}
You should try with below changes:
Put route as:
Route::post('/home/info/store', 'InfoController#store')->name('infoStore');
Instead of
Route::post('/home', 'InfoController#store')->name('home');
Because you create same post route for all so just change route and try its may be solve your problem.

Laravel 5.3: How to authenticate only active users

I want to laravel 5.3 loged in users table status='Active' but status='Inactive' can't loged in.
Please help me with that. Thanks a lot guys!
Go to \vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
then change credentials functions.
And see this link https://laracasts.com/discuss/channels/laravel/allowing-only-active-users-to-login.
example function link
protected function credentials(Request $request)
{
$crendentials = $request->only($this->username(), 'password');
$crendentials['status']='Active';
return $crendentials;
}
Add this function in Auth/LoginController.php
use Illuminate\Http\Request;
protected function credentials(Request $request)
{
return [
$this->username() => $request->get($this->username()),
'password' => $request->get('password'),
'active' => 1
];
}
By doing this, you actually override it. This function is in the AuthenticatesUsers trait.
Another way for getting the same result is to override the validateLogin() function by adding
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => [
'required',
Rule::exists('users')->where(function ($query) {
$query->where('active', 1);
}),
],
'password' => 'required',
]);
}
to the LoginController.php
You can try like this:
if (Auth::attempt(['email' => $email, 'password' => $password, 'status' => 'Active'])) {
// The user is active, not suspended, and exists.
}

How to add extra logic on login condition in Laravel 5.2

I just wanted to say if the user is not active, don't allow to login. I have made the controller as below, I am not sure what I am missing or what else I have to do here to make this work!
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Auth\Authenticatable;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
}
My thinking was authenticate() method should do the trick!
The below code worked for my case:
protected function getCredentials(Request $request)
{
return [
'email' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
for Laravel 5.3 need to add following code to LoginController
protected function credentials(Request $request)
{
return [
'email' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
i think you should create method to check if user passed your credentials, here's my suggestion :
protected function getCredentials(Request $request)
{
return [
'username' => $request->input('email'),
'password' => $request->input('password'),
'active' => true
];
}
and your login method:
public function login(Request $request) {
$this->validate($request,['email' => 'required|email','password' => 'required']);
if (Auth::guard()->attempt($this->getCredentials($request))){
//authentication passed
}
return redirect()->back();
}
hope you get basic idea.
In LoginController.php file write this function
protected function credentials(Request $request) {
$extraFields = [
'user_type'=> 'customer',
'user_entry_status' => 1
];
return array_merge($request->only($this->username(), 'password'), $extraFields);
}
Go to this path :
your-project-folder/vendor/laravel/framework/src/illuminate/Foundation/Auth/AuthenticatesUsers.php
$credentials=$request->only($this->loginUsername(), 'password');
$credentials['status'] = '1';
return $credentials;
Change getCredantials works fine, but it is good practice to let user know, that the account was suspended (credentials are OK, but the account status is not). You can easily override login method in Auth/LoginController.php to your own copy, add your own logic to login process and raise own exception.
in Auth/LoginController.php create login and sendAccountBlocked function
/*load additional classes to LoginController.php*/
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Auth;
public function login(Request $request){
//
$this->validateLogin($request);
//
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if (method_exists($this, 'hasTooManyLoginAttempts') && $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
//check user status
if (Auth::user()->user_status == 'A') return $this->sendLoginResponse($request);
// if user_status != 'A' raise exception
else {
$this->guard()->logout();
return $this->sendAccountBlocked($request);
}
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
//
}//
protected function sendAccountBlocked(Request $request){
throw ValidationException::withMessages([
$this->username() => ['Your account was suspended.'],
]);
}

Resources