Laravel Auth Login Solution - laravel

I create postSignIn Method and want to verified :
email, password, verifiedFlag
First there was no problem for create postSignIn Method, like :
public function postSignIn(){
if(Auth::attempt(array('email' => Input::get('email'),'password' => Input::get('password'),'verifiedFlag'=>1))){
return Redirect::route('home-view');
}
else{
return "Email/Password wrong or Your Account not verified by Admin";
}
}
But now I try to make it more user friendly by Separate Alert for
Account not Verified, and
Email/Password Wrong
and now I try to make it like this:
if(Auth::attempt(array('nim' => Input::get('nim'),'password' => Input::get('password')))){
Auth::logout();
if(Auth::attempt(array('nim' => Input::get('nim'),'password' => Input::get('password'),'verified' => 1))){
return Redirect::route('home-view');
}
else{
return "Your Account not verfied. Please wait until admin verified your account or contact your admin";
}
}
else{
return "NIM/Password wrong";
}
there was no problem, but I think I need other solution so Auth don't need to Login(Attempt) Twice

You can use the validate method. This would work:
public function postSignIn(){
if(Auth::attempt(array('email' => Input::get('email'),'password' => Input::get('password'),'verifiedFlag'=>1))){
return Redirect::route('home-view');
}
elseif(Auth::validate(array('email' => Input::get('email'),'password' => Input::get('password')))){
return "Your Account not verified by Admin";
}
else
{
return "Email/Password wrong";
}
}

Filters are the way to go. It's easy and clean to solve this problem, see my example below.
if user is inactive at any point it will logout user,
you can redirect user with Session flash message, your login code works as it is.
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
else
{
// If the user is not active any more, immidiately log out.
if(Auth::check() && !Auth::user()->verifiedFlag)
{
Auth::logout();
Session::flash('message','Your account is not active, please contact your administrator to active your account');
// redirect to login page
return Redirect::to('/');
}
}
});

Related

Catching org_internal 403 error via Google's OAUTH?

I have google OATH setup via socialite (only for within our organisation) and everything is working fine.
One thing I'd like to try and do is catch this "error" and get redirected back to our login page with a custom message telling the user that they do not belong to our organisation.
In principle this works fine, they can just hit the back button... but for fluidity and design, I'd like to catch this and redirect back to our home page.
Is this even possible? If so, how would you recommend I go about it?
public function show()
{
return view('auth.login');
}
public function redirectToProvider($driver)
{
if( ! $this->isProviderAllowed($driver) ) {
return $this->sendFailedResponse("{$driver} is not currently supported");
}
try {
return Socialite::driver($driver)->redirect();
} catch (Exception $e) {
return $this->sendFailedResponse($e->getMessage());
}
}
public function handleProviderCallback( $driver )
{
try {
$user = Socialite::driver($driver)->user();
} catch (Exception $e) {
return $this->sendFailedResponse($e->getMessage());
}
// check for email in returned user
return empty( $user->email )
? redirect()->intended('/login?failed=1')
: $this->loginOrCreateAccount($user, $driver);
}
protected function sendSuccessResponse()
{
return redirect()->intended('/');
}
protected function sendFailedResponse($msg = null)
{
return redirect()->intended('/login?failedResponse='.$msg);
}
protected function loginOrCreateAccount($providerUser, $driver)
{
// check for already has account
$user = User::where('email', $providerUser->getEmail())->first();
// if user
if( $user ) {
// update the avatar and provider that might have changed
$user->update([
'avatar' => $providerUser->avatar,
'provider' => $driver,
'provider_id' => $providerUser->id,
'access_token' => $providerUser->token
]);
} else {
return redirect()->intended('/login?noUser=1');
}
// login the user
Auth::login($user, true);
return $this->sendSuccessResponse();
}
private function isProviderAllowed($driver)
{
return in_array($driver, $this->providers) && config()->has("services.{$driver}");
}

Multiple pages to open based on single route laravel

I'm very new to Laravel and have a scenario where if a user tries to apply for a job but is not logged in then the user is redirected to an Auth0 login, at this point I want to return the user to a dashboard but also open the job application in a new tab. Is it possible to return two views like this?
I tried to return an array with both redirects in;
public function callback(): RedirectResponse
{
$redirect_to = session('auth_return_to_url', '/');
if (str_contains($redirect_to, '/job/view/')) {
$redirect = [Redirect::intended($redirect_to), Redirect::intended(route('dashboard.dashboard'))];
} else {
$redirect = Redirect::intended(route('dashboard.dashboard'));
}
try {
$this->doLogin();
} catch (Exception $exception) {
Log::error('Auth0 initialization error', [
'message' => $exception->getMessage()
]);
return $redirect;
}
return $redirect;
}
but this understandably fails with the following message.
Return value of App\Http\Controllers\Auth\Auth0CallbackController::callback() must be an instance of Illuminate\Http\RedirectResponse, array returned
why you not add a param to login url. Example
login?redirect=%2Fjob%2Fview
And after logged in, you can redirect user to url you want.

How to make the profile user forbid to anyone except the own user?

I have route:
Route::get('#{username}', 'HomePageController#username')->name('user.profile');
that route to allow for everyone to see the profile ( contains his info and his cv .. etc ), and in the beginning of register any user user must wait to active his account by the admin
I need to see if account of user still under process show above route just for him. and when the account is active open above route for everyone can see his profile.
I tried to create middleware but don't know how can I forbid the guest user
My wrong shut:
public function username($username)
{
$user = User::where('username' , '=' , $username)->firstOrFail();
if($user->active){
return view('frontend.user_profile',compact('user','projects_last','first_project','whole_projects'));
}else{
return redirect('/');
}
}
What the best scenario to do something like that?
thanks.
if ($user->active) {
// Everyone can see
} else {
if (Auth::user() && Auth::user()->username == $username) {
// only auth and himself can see
} else {
// redirect to home page
}
}
if($user->active || $username == Auth::user()->username){
return view('frontend.user_profile',compact('user','projects_last','first_project','whole_projects'));
}else{
return redirect('/');
}
You can try this
public function username($username)
{
$user = User::where(['username' => $username,'status' => 'active'])->firstOrFail();
if($user && auth()->user()->username == $username){
return view('frontend.user_profile',compact('user','projects_last','first_project','whole_projects'));
}else{
return abort(403, 'Unauthorized action.');
}
}
}
You can also use it like this
if( $username == Auth::user()->username){
return view('frontend.user_profile',compact('user','projects_last','firs. t_project','whole_projects'));
}else{
return abort(403, 'Unauthorized action.');
}

CakePHP Refresh specific user session after updating details

I want to refresh the session of an user I am editing so he doesn't need to log-out to have the new details, such as a role for example.
My edit function is:
public function edit($id = null)
{
if (!$id) {
$this->Flash->error(__('User not found.'));
}
$user = $this->Users->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('User has been updated.'));
return $this->redirect(['action' => 'edit/' . $id]);
}
$this->Flash->error(__('Unable to update User details.'));
}
$this->set(compact('user'));
}
How can I accomplish this? Thanks.
You can try something like this:
public function edit($id = null)
{
if (!$id) {
$this->Flash->error(__('User not found.'));
}
$user = $this->Users->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('User has been updated.'));
$this->request->session()->write([Auth.YourUserVariable => $user]);
return $this->redirect(['action' => 'edit/' . $id]);
}
$this->Flash->error(__('Unable to update User details.'));
}
$this->set(compact('user'));
}
Then when your user uptade his/her profile if it save the user it will overide session, are you using Auth ok? To see details from user you can try this:
debug($this->request->session()->read('Auth'));exit;
Or something like this ;)

How to redirect index page if user not logged in laravel

Hello i create website in laravel but i facing one problem. The problem is that when user is not log in and user type www.test.com/notifications that time showing error like this
ErrorException (E_UNKNOWN)
Undefined variable: messages (View: /home/test/app/views/message-page.blade.php)
But i want to when user is not log in and enter www.test.com/notifications so user automatic redirect to index page. Please help me i very confuse.
I using the some code in base controller is as follows:
public function checkLoggedIn(){
if(Auth::user()->check()){
return;
}
else {
return Redirect::to("/");
}
}
You should do it this way:
public function checkLoggedIn(){
if (!Auth::check()) {
return Redirect::to("/");
}
return true;
}
However I assume you want to use this function in another controller so then you should do it this way:
$result = $this->checkLoggedIn();
if ($result !== true) {
return $result;
}
to make redirection.
But Laravel have filters so you can easily check if user is logged.
You can just use in your routes.php:
Route::group(
['before' => 'auth'],
function () {
// here you put all paths that requires user authentication
}
);
And you can adjust your filter in app/filters for example:
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::to('/');
}
}
});

Resources