I'm trying to return the user logged in but I'm getting null
when I dd(Auth::guard('admin')->user() in the login Controller it works but when I try to use it in NiveauController it returns null.
LoginController:
public function VerifierLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('enseignant')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
Auth::guard('enseignant')->user();
return redirect()->intended(route('EnseignantDashboard'));
}
if (Auth::guard('superadmin')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
Auth::guard('superadmin')->user();
return redirect()->intended('/superadmin');
}
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
Auth::guard('admin')->user();
return redirect()->intended('/admin');
}
return back()->withInput($request->only('email', 'remember'))->with('error');
}
NiveauController:
public function showListNiveaux()
{
$admin=Auth::guard('admin')->user();
dd( $admin);
$niveaux = DB::table('niveaux')->where('id_etablissement',$admin->id_etablissement);
return view('Niveau:index',compact($niveaux));
}
This usually happens if you forget to put the auth middleware on your route/controller
Try putting this in your controller
public function __construct()
{
$this->middleware('auth');
//OR
// $this->middleware('web');
}
and see if this solves your issue.
Related
When I register a new user and I want to sign him in by using auth attempt it doesn't work while the user is saved to database
static function register()
{
if(self::$validate['message'])
{
$user = User::create([
'name' => self::$values['name'],
'email' => self::$values['email'],
'password' => Hash::make(self::$values['password'])
]);
Auth::attempt($user,true);
Auth::attempt($user->only(['email','password']));
return result::repsonse(true);
} else
return self::$validate;
}
You can use Auth::login() method
static function register()
{
if(self::$validate['message'])
{
$user = User::create([
'name' => self::$values['name'],
'email' => self::$values['email'],
'password' => Hash::make(self::$values['password'])
]);
Auth::login($user);
return result::repsonse(true);
} else
return self::$validate;
}
When I register a member at Laravel, I send a confirmation email. But when I click on the verification link, the column in the database does not fill.
Sample codes:
protected function create(array $data)
{
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'phone' => $data['phone'],
'password' => Hash::make($data['password']),
]);
$user->sendEmailVerificationNotification();
return $user;
}
public function register(Request $request) {
$validation = $this->validator($request->all());
if($request->input('type') == "customer" || $request->input('type') == "company") {
if ($validation->fails()) {
return response()->json([$validation->errors()->toArray()], 400);
}else {
$this->create($request->all());
}
}else {
return response()->json([
0 => ['Üyelik sırasında bir hata oluştu. Lütfen tekrar deneyiniz.']
], 404);
}
}
1) Have you migrated the tables after running the auth boilerplate?
2) Have you checked your logs for any additional errors that might be showing?
I want when I finished register it redirects me to the dashboard page (Auto login after the register).
this is the user register code :
public function store(Request $request)
{
$this->validator($request->all())->validate();
$apprenant = Apprenant::create([
'nom' => $request['nom'],
'prenom' => $request['prenom'],
'email' => $request['email'],
'niveau' => $request['niveau'],
'password' => Hash::make($request['password']),
]);
return redirect('/apprenant/dashboard');
}
But when I finished registring it redirects me to the login page
Hi if you are create a guard then run this code for after register login
Auth::guard(guard_name)->loginUsingId($id);
// example
public function register(Request $req)
{
$user = new User; // define here your model
$user->name = $req->name;
$user->email = $req->email;
$user->password = Hash::make($req->password);
if($user->save()){
Auth::guard(guard_name)->loginUsingId($user->id);
}
}
// logout overite
public function logout()
{
Auth::guard('guard_name')->logout();
return redirect("login_path");
}
When creating a new user, create() method, should return a new model object.
Use Auth::loginUsingId($apprenant->id); before redirecting to dashboard:
public function store(Request $request)
{
$this->validator($request->all())->validate();
$apprenant = Apprenant::create([
'nom' => $request['nom'],
'prenom' => $request['prenom'],
'email' => $request['email'],
'niveau' => $request['niveau'],
'password' => Hash::make($request['password']),
]);
Auth::loginUsingId($apprenant->id);
return redirect('/apprenant/dashboard');
}
source
https://laravel.com/docs/5.7/authentication#other-authentication-methods
Write this line before redirecting to the dashboard:
\Auth::login($apprenant);
or just,
auth()->login($apprenant);
That means, you code will look like:
public function store(Request $request)
{
$this->validator($request->all())->validate();
$apprenant = Apprenant::create([
'nom' => $request['nom'],
'prenom' => $request['prenom'],
'email' => $request['email'],
'niveau' => $request['niveau'],
'password' => Hash::make($request['password']),
]);
//login the user
\Auth::login($apprenant);
return redirect('/apprenant/dashboard');
}
When I am trying to register a user from mobile, that data is inserting in the users table but not in oauth_clients. It should upload at the same time.
When I try to login, it shows oauth/token 401 error
Here are my routes:
Route::post('/register' , 'ProviderAuth\TokenController#register');
Route::post('/oauth/token' , 'ProviderAuth\TokenController#authenticate');
This is my register function, which is in TokenConrtoller:
public function register(Request $request)
{
$this->validate($request, [
'device_id' => 'required',
'device_type' => 'required|in:android,ios',
'device_token' => 'required',
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:providers',
'mobile' => 'required',
'password' => 'required|min:6|confirmed',
]);
try{
$Provider = $request->all();
$Provider['password'] = bcrypt($request->password);
$Provider['status'] = 'approved';
$Provider = Provider::create($Provider);
ProviderDevice::create([
'provider_id' => $Provider->id,
'udid' => $request->device_id,
'token' => $request->device_token,
'type' => $request->device_type,
]);
return $Provider;
} catch (QueryException $e) {
if ($request->ajax() || $request->wantsJson()) {
return response()->json(['error' => 'Something went wrong, Please try again later!'], 500);
}
return abort(500);
}
}
This is my authenticate method:
public function authenticate(Request $request)
{
$this->validate($request, [
'device_id' => 'required',
'device_type' => 'required|in:android,ios',
'device_token' => 'required',
'email' => 'required|email',
'password' => 'required|min:6',
]);
Config::set('auth.providers.users.model', 'App\Provider');
$credentials = $request->only('email', 'password');
try {
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'The email address or password you entered is incorrect.'], 401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'Something went wrong, Please try again later!'], 500);
}
$User = Provider::with('service', 'device')->find(Auth::user()->id);
$User->access_token = $token;
$User->currency = Setting::get('currency', '$');
if($User->device) {
if($User->device->token != $request->token) {
$User->device->update([
'udid' => $request->device_id,
'token' => $request->device_token,
'type' => $request->device_type,
]);
}
} else {
ProviderDevice::create([
'provider_id' => $User->id,
'udid' => $request->device_id,
'token' => $request->device_token,
'type' => $request->device_type,
]);
}
return response()->json($User);
}
I think you should register in JWT auth Like
$token = JWTAuth::fromUser($user);
after Register User
Check this Link for more information
https://blog.pusher.com/laravel-jwt/
I'm using laravel with JWT Auth to connect my laravel project to mobile, this is my api controller at laravel
public function login(Request $request) {
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
$user = Sentry::authenticate($credentials, false);
return response()->json([
'code' => '200',
'message' => 'success',
'last_updated' => $user->updated_at->format("Y-m-d\TH:i:s\Z"),
'data' => [
'id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'username' => $user->username,
'token' => $token
]
]);
}
but how to set the credentials using email or username with this JWT?
If you are using "tymon/jwt-auth" package, then you can just pass the user object to the JWTAuth class and bam!, you can get the JWT token in return which you can use to make user go through the app.
$user = User::where('email', $email)
->orWhere('username', $username)
->first();
$token = null;
if (!$token = JWTAuth::fromUser($get_info)) {
return $this->respondInternalError( 'Can\'t generate the JWT token right now, try again later!', 'object', 400);
}
return response()->json([
'code' => '200',
'message' => 'success',
'last_updated' => $user->updated_at->format("Y-m-d\TH:i:s\Z"),
'data' => [
'id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'username' => $user->username,
'token' => $token
]
]);
You can login using email or using the following format
public function login(Request $request)
{
//validate incoming request
$this->validate($request, [
'email_phone' => 'required|string',
'password' => 'required|string',
]);
try {
$login_type = filter_var( $request->email_phone, FILTER_VALIDATE_EMAIL ) ? 'email' : 'phone';
// return $login_type;
$credentials = [$login_type => $request->email_phone, 'password'=>$request->password];
if (! $token = Auth::attempt($credentials)) {
return response()->json($this->customResponse("failed", "Unauthorized"), 401);
}
return $this->respondWithToken($token);
} catch(JWTException $e) {
return response()->json($this->customResponse("failed", "An error occured, please contact support.", $user), 500);
}
}