88292

set custom sql for Authorization in Laravel 5

Question:

I am new on Laravel and use Authorization. I am looking for the way to change default sql for Auth. Actually, Laravel does it using this simple sql command at below:

SELECT * FROM users WHERE login="something" AND password = "something" LIMIT 1

I am trying to change default sql like this:

SELECT u.id, u.name, c.company FROM users u, companies c WHERE u.login="something" AND u.password = "something" AND u.companyId = c.id LIMIT 1

I understood that I should create custom Authorization system: crate new user Provider and Auth Provider.

Firstly, I created Auth folder inside App and added there CustomUserProvider.php

<strong>CustomUserProvider.php</strong>

<?php namespace App\Auth; use Illuminate\Contracts\Auth\Authenticatable as UserContract; use Illuminate\Contracts\Auth\UserProvider as UserProviderInterface; use App\Models\User; class CustomUserProvider implements UserProviderInterface { protected $model; public function __construct(UserContract $model) { $this->model = $model; } public function retrieveById($identifier) { } public function retrieveByToken($identifier, $token) { } public function updateRememberToken(UserContract $user, $token) { } public function retrieveByCredentials(array $credentials) { } public function validateCredentials(UserContract $user, array $credentials) { } }

My <strong>customAuthProvider.php</strong> file, in App/Providers:

<?php namespace App\Providers; use App\Models\User; use Illuminate\Support\Facades\Auth; use App\Auth\CustomUserProvider; use Illuminate\Support\ServiceProvider; class CustomAuthProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $this->app['auth']->extend('custom',function() { return new CustomUserProvider(new User); }); } /** * Register the application services. * * @return void */ public function register() { // } }

At the end I set driver to custom in config/Auth.php

'driver' => 'custom'

I am looking for the way using this custom classes how can I use custom sql command for Authorization (Login)? Or maybe this way is wrong?

Answer1:

If all you need are additional constraints on the query that fetches user from the database during authentication, there is much simpler way to do that.

First of all, Laravel offers an AuthenticatesUsers trait that you can use in your controller to handle authentication requests. The default implementation fetches user from the database using username field and then, if matching user is found, it validates their password.

The list of attributes that is used to fetch user from the database can be customized by overriding getCredentials method in your controller. In your case the following should be enough to load user using their username and company id:

protected function getCredentials(Request $request) { return $request->only($this->loginUsername(), 'password', 'companyId); }

Once you add that, user should provide their username, companyId and password in the login form and they will be authenticated only if there exists a user with given username that belongs to given company and the password provided is valid.

<strong>UPDATE:</strong> If you decide not to use the trait, but want to authenticate users manually, you can do so in a really similar manner. When calling Auth::attempt() you just need to pass all the criteria that should be used to authenticate the user, e.g.:

Auth::attempt([ 'username' => Input::get('username'), 'companyId' => Input::get('companyId'), 'password' => Input::get('password') ]);

Answer2:

I tried this package and it helped me:

<a href="https://github.com/ollieread/multiauth/" rel="nofollow">https://github.com/ollieread/multiauth/</a>

Recommend

  • Global PHP class in functions?
  • Swiftmailer email message returns error when attaching file
  • form_validation class does not load (codeigniter)
  • Get variable height for a UIButton for iPhones 5/6/6+
  • Cannot invoke my method on the array type int[]
  • Single django queryset to get n adjacent items
  • Are there any side effects from calling SQLAlchemy flush() within code?
  • Django return user model id with L
  • Django model for a Postgres view
  • Doctrine2 bulk import try to work with another entity
  • Regarding starting the threads on a condition
  • Combining two different ActiveRecord collections into one
  • Laravel: Getting Session ID oddly truncates when using foreach
  • Bypass multiple inheritance in Java
  • The plugin 'org.apache.maven.plugins:maven-jboss-as-plugin' does not exist or no valid ver
  • Recording logins for password protected directories
  • How to access EntityManager inside Entity class in EJB3
  • how to do an event when i swipe from fragment to the other
  • Sails.js/waterline: Executing waterline queries in toJSON function of a model?
  • Opengl-es onTouchEvents problem or a draw problem? [closed]
  • Cannot Parse HTML Data Using Android / JSOUP
  • KeystoneJS: Relationships in Admin UI not updating
  • JTable with a ScrollPane misbehaving
  • Java static initializers and reflection
  • Authorize attributes not working in MVC 4
  • unknown Exception android
  • MATLAB: Piecewise function in curve fitting toolbox using fittype
  • Busy indicator not showing up in wpf window [duplicate]
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Reading document lines to the user (python)
  • Binding checkboxes to object values in AngularJs
  • Observable and ngFor in Angular 2
  • How can I use `wmic` in a Windows PE script?
  • failed to connect to specific WiFi in android programmatically
  • Unable to use reactive element in my shiny app
  • Python/Django TangoWithDjango Models and Databases
  • Net Present Value in Excel for Grouped Recurring CF
  • How can I use threading to 'tick' a timer to be accessed by other threads?
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?