Can't authenticate with different table - authentication

I've changed the auth.php file in order to authenticate my users according to authors table. But I keep getting No account for you when I'm running test route.
auth.php
<?php
return array(
'driver' => 'eloquent',
'model' => 'Author',
'table' => 'authors',
'reminder' => array(
'email' => 'emails.auth.reminder', 'table' => 'password_reminders',
),
);
routes.php
Route::get('test', function() {
$credentials = array('username' => 'giannis',
'password' => Hash::make('giannis'));
if (Auth::attempt($credentials)) {
return "You are a user.";
}
return "No account for you";
});
AuthorsTableSeeder.php
<?php
class AuthorsTableSeeder extends Seeder {
public function run()
{
// Uncomment the below to wipe the table clean before populating
DB::table('authors')->delete();
$authors = array(
[
'username' => 'giannis',
'password' => Hash::make('giannis'),
'name' => 'giannis',
'lastname' => 'christofakis'],
[
'username' => 'antonis',
'password' => Hash::make('antonis'),
'name' => 'antonis',
'lastname' => 'antonopoulos']
);
// Uncomment the below to run the seeder
DB::table('authors')->insert($authors);
}
}
Addendum
I saw in another post that you have to implement the UserInterface RemindableInterface interfaces. But the result was the same.
Author.php
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Author extends Eloquent implements UserInterface, RemindableInterface {
protected $guarded = array();
public static $rules = array();
public function posts() {
return $this->hasMany('Post');
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return "giannis#hotmail.com";
}
}

You don't need to Hash your password when you are using Auth::attempt(); so remove Hash::make from routes
Route::get('test', function() {
$credentials = array('username' => 'giannis',
'password' => 'giannis');
if (Auth::attempt($credentials)) {
return "You are a user.";
}
return "No account for you";
});
and it will work like a charm!

Related

Object of class Faker\UniqueGenerator could not be converted to string

I am using laravel 9. I am trying to generate some fake users to boost my db using factoreis and seeders.
When i try to seed my db i get this error
Object of class Faker\UniqueGenerator could not be converted to string
at D:\PROJECTS\LARAVEL\todo-list\vendor\laravel\framework\src\Illuminate\Database\Connection.php:665
661▕ $value,
662▕ match (true) {
663▕ is_int($value) => PDO::PARAM_INT,
664▕ is_resource($value) => PDO::PARAM_LOB,
➜ 665▕ default => PDO::PARAM_STR
666▕ },
667▕ );
668▕ }
669▕ }
1 D:\PROJECTS\LARAVEL\todo-list\vendor\laravel\framework\src\Illuminate\Database\Connection.php:665
PDOStatement::bindValue(Object(Faker\UniqueGenerator))
2 D:\PROJECTS\LARAVEL\todo-list\vendor\laravel\framework\src\Illuminate\Database\Connection.php:540
Illuminate\Database\Connection::bindValues(Object(PDOStatement))
this my UserFactory
class UserFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'name' => fake()->name(),
'username' => fake()->unique(),
'company' => fake()->sentence(),
'position' => fake()->sentence(),
'bio' => fake()->realText($maxNbChars = 100),
'picture' => fake()->imageUrl(90, 90),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => Hash::make('password'), // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* #return static
*/
public function unverified()
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
After looking arround for a while I found that fake()->unique() does not return a string. So I tried to convert it to string but It also gives me a error saying Unknown format "toString" in Faker\Generator.php:731
[Problem solved]
I just had to edit my UserFactory username to this
'username' => fake()->unique()->text(16),

Authentication using username instead of email laravel 5.2

Below is my code for AuthController
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
//use App\Http\Requests\Request;
use Request;
use View;
use Hash;
use DB;
use Auth;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/home';
protected $redirectAfterLogout = '/login';
protected $username = 'user_name';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
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',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function showLogin()
{
if (Auth::check())
{
return redirect('/home');
}
else
{
return View::make('index');
}
}
public function doLogin()
{
//echo 'test';
$input = Request::all();
$pass = Hash::make($input['password']);
//print_r($input);exit;
//echo $input['username'];exit;
/*DB::table('admin_user')->insert(
['user_name' => $input['username'], 'password' => $pass]
);*/
if (Auth::attempt(['user_name' => $input['username'], 'password' => $input['password']])) {
return redirect('/home');
//return View::make('home');
}
else
{
return redirect('/');
}
}
public function doLogout()
{
Auth::logout();
return redirect('/');
}
}
Below is my Route Code
Route::get('/',array('uses'=>'Auth\AuthController#showLogin') );
Route::post('/login',array('uses'=>'Auth\AuthController#doLogin'));
//Route::get('/login',array('uses'=>'Login#showLogin') );
Route::group(['middleware' => ['web', 'auth.basic']], function(){
Route::get('/home',['uses'=>'Home#getHome']);
Route::get('/logout',array('uses'=>'Auth\AuthController#doLogout') );
});
i am using user name instead of email id for Auth but below error is shown
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'email' in
'where clause' (SQL: select * from admin_user where email = admin
limit 1)
below is my kernal.php code
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
please help me how can i do login with username .
Thanks in advance.
Update:
Add the auth middleware to specific route
Route::group(['middleware' => ['web']], function(){
Route::get('/',array('uses'=>'Auth\AuthController#showLogin') );
Route::post('/login',array('uses'=>'Auth\AuthController#doLogin'));
Route::get('/home',['uses'=>'Home#getHome'])->middleware('auth');//update
Route::get('/logout',array('uses'=>'Auth\AuthController#doLogout') );
});
To redirect to intended page after login replace your doLogin() function with following:
public function doLogin()
{
$input = Request::all();
$pass = Hash::make($input['password']);
if (Auth::attempt(['user_name' => $input['username'], 'password' => $input['password']])) {
return redirect()->intended('/home');//This line is changed
}
else
{
return redirect('/');
}
}
Explaination:
intended() method redirects the user to the previous page, from where the user is redirected to login page. It expects a default route as a parameter, where user will be sent if he has came here directly.
Update 2:
add doLogout in your AuthController's constructor:
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'doLogout']);
}
You can simply override $username in AuthController by writing protected $username = 'username'.

Laravel Auth::attempt() fails. I use SQLite btw

What i'm doing wrong?
<?php
public function login() {
$user_name = time();
User::create(array(
'name' => $user_name,
'email' => $user_name.'#test.com',
'password' => Hash::make('123123'),
));
$user = array(
'email' => $user_name.'#test.com',
'password' => '123123',
);
$m = User::where('email' , '=', $user_name.'#test.com')->first();
dd([
'Auth::attempt($user)',
Auth::attempt($user),
'Auth::check()',
Auth::check(),
'Hash::check($m->password, \'123123\')',
Hash::check($m->password, '123123')
]);
}
Result:
array(6) {
[0]=>
string(20) "Auth::attempt($user)"
[1]=>
bool(false)
[2]=>
string(13) "Auth::check()"
[3]=>
bool(false)
[4]=>
string(38) "Hash::check($user->password, '123123')"
[5]=>
bool(false)
}
Not sure what information should I add.
app/config/auth.php
'driver' => 'eloquent',
'model' => 'User',
'table' => 'users',
app/config/app.php
'key' => 'DMmiPAxSYz4O2jG44S92OcdPZN7ZsGGs',
'cipher' => MCRYPT_RIJNDAEL_256,
models/User.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* Validation rules
*/
public static $rules = array(
'name' => 'required',
'email' => 'email|required|unique',
'password' => 'min:6',
);
/**
* Validation rules
*/
public static $messages = array(
'name.required' => 'The name field is required',
'email.email' => 'The email field must contain properly formatted email.',
'email.required' => 'The email field is required',
'password.required' => 'The password field is required',
'password.min:6' => 'The password must be minimum 6 characters long',
);
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
protected $guarded = array('id');
public function setPasswordAttribute($value) {
if ($value) {
$this->attributes['password'] = Hash::make($value);
}
}
}
Well here's some checks that you can do
Have you setup config/auth.php with driver, model and table?
Have you filled the fillable array of the User's model?
Have you change the key inside config/app.php ?
Also try to dd($m) in order to see what you got from that query.
I found what is wrong.
This part of code hash password for first time:
User::create(array(
'name' => $user_name,
'email' => $user_name.'#test.com',
'password' => Hash::make('123123'), // <---- first time
));
And this mutator in User model does hashing for second time before put password to database:
public function setPasswordAttribute($value) {
if ($value) {
$this->attributes['password'] = Hash::make($value); // <---- second time
}
}
So I just changed first block to this:
User::create(array(
'name' => $user_name,
'email' => $user_name.'#test.com',
'password' => '123123', // <---- no hashing here
));

Basic Auth Laravel4 How to use it?

I try to protect my restAPI with credentials and reading about basic-auth laravel I try to implement a basic authentication sytem
User tabel already exists and populated with data
in filter.php I set
Route::filter('auth.basic', function() {
return Auth::basic(); });
than in api Route
// =============================================
// API ROUTES ==================================
// =============================================
Route::group(array('prefix' => 'api', 'before' => 'auth.basic'), function() {
Route::resource('products', 'ProductController', array('only' => array('index', 'store', 'destroy', 'update', 'show', 'edit')));
Route::get('products/{id}', 'ProductController#get', array('only' => array('show')));
});
the controller is quite simple
<?php
use App\Models\Product;
class ProductController extends \BaseController {
private $model;
function __construct() {
$this->model = new Product();
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index() {
$model = new Product();
$page = Input::get('pageNumber');
$limit = Input::get('pageNumber');
$ram = Input::get('limit');
$cpu = Input::get('cpu');
$price_range = Input::get('price_range');
$keyword = Input::get('keyword');
return Response::json($model->getProducts($page));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store() {
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id) {
}
public function get($id) {
$model = new Product();
return Response::json($model->getProduct($id));
}
public function show($id) {
return Response::json($this->model->getProduct($id));
}
public function update($id) {
return Response::json($this->model->getProduct($id));
}
public function pause($id) {
var_dump('pause');
}
public function create(){
}
public function edit(){
var_dump('test_edit');
}
}
calling domain.com/api/products pop up login window. populating fields and submit datas can't log in
How do I check Users credentials?
For backend I use Sentry and it's working
filter.php
Route::filter('auth.admin', function() {
if (!Sentry::check()) {
return Redirect::route('admin.login');
}
});
Route
Route::get('admin/login', array('as' => 'admin.login', 'uses'
=> 'App\Controllers\Admin\AuthController#getLogin'));
Controller
<?php namespace App\Controllers\Admin;
use Auth, BaseController, Form, Input, Redirect, Sentry, View;
class AuthController extends BaseController {
/**
* Display the login page
* #return View
*/
public function getLogin()
{
return View::make('admin.auth.login');
}
/**
* Login action
* #return Redirect
*/
public function postLogin()
{
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
try
{
$user = Sentry::authenticate($credentials, false);
if ($user)
{
return Redirect::route('admin.pages.index');
}
}
catch(\Exception $e)
{
return Redirect::route('admin.login')->withErrors(array('login' => $e->getMessage()));
}
}
/**
* Logout action
* #return Redirect
*/
public function getLogout()
{
Sentry::logout();
return Redirect::route('admin.login');
}
}
It seems that you don't have a login function defined.
by the way, you should change:
Route::group(array('prefix' => 'api', 'before' => 'auth.basic'), function() {
Route::resource('products', 'ProductController', array('only' => array('index', 'store', 'destroy', 'update', 'show', 'edit')));
Route::get('products/{id}', 'ProductController#get', array('only' => array('show')));
});
to:
Route::group(array('prefix' => 'api', 'before' => 'auth.basic'), function(){
Route::get('products/{id}', 'ProductController#get'));
Route::resource('products', 'ProductController', array('except' => array('show')));
});

Different name fields user table?

I have a form with 2 fields (username, password) and a mysql table with those 2 same fields (username, password), and I authentication system working properly :)
But, I can not make it work if my table fields have different names, for example: (my_user, my_pass).
If you just change the username field on the other also works for me, that gives me problems is the password field.
My config auth.php
'driver' => 'eloquent'
Update
Already found the solution in my controller, the password name can not change.
Before (WRONG):
What I've done in first place was wrong
$userdata = array(
'my_user' => Input::get('my_user'),
'my_pass' => Input::get('my_pass')
);
it should be
$userdata = array(
'my_user' => Input::get('my_user'),
'password' => Input::get('my_pass')
);
You can define you own username and password field in the auth.php inside the config folder.
return array(
'driver' => 'eloquent',
'username' => 'my_user',
'password' => 'my_pass',
'model' => 'User',
'table' => 'users',
);
I hope this can be of some help.
I ran into this same problem. You need to extend your model:
// User.php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable = array('name','passwd','email','status','timezone','language','notify');
protected $hidden = array('passwd');
protected $table = "users_t";
protected $primaryKey = "uid";
public static $rules = array(
'name' => 'required',
'passwd' => 'required',
'email' => 'required'
);
public function getAuthIdentifier() {
return $this->getKey();
}
public function getAuthPassword() {
return $this->passwd;
}
public function getReminderEmail() {
return $this->email;
}
public static function validate($data) {
return Validator::make($data,static::$rules);
}
}
You need to implements this methods too:
public function getRememberToken(){
}
public function setRememberToken($value){
}
public function getRememberTokenName(){
}