Different name fields user table? - authentication

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(){
}

Related

passing value from request in function to other function in same controller

I would like in My ContactController.php (which manages my US contact) replace the recipient's email address with a value get from the database in a table called Student ..
'''
<?php
namespace App\Http\Controllers;
use Mail;
use App\Models\Student;
use App\Models\ContactUs;
use Illuminate\Http\Request;
class ContactController extends Controller
{
public function showForm(Request $request)
{
return view('welcome');
}
public function Infos(Request $request)
{
$info = Student::find(1)->value('monemail');
//// do something
}
public function storeForm(Request $request)
{
///get value of $info
$this->validate($request, [
'name' => 'required|max:100',
'email' => 'required|email',
'phone' => 'required|numeric',
'subject' => 'required|max:100',
'message' => 'required|max:400'
]);
ContactUs::create($request->all());
\Mail::send('email', array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'phone' => $request->get('phone'),
'subject' => $request->get('subject'),
'form_message' => $request->get('message'),
), function ($message) use ($request) {
$message->from($request->email);
//change test#test.fr by value of $info in Infos method
$message->to('test#test.fr', 'Message de Transport Parisien')->subject($request->get('subject'));
});
return back()->with('success', 'Thank.');
}
}
'''
I do not remember how to pass the value of a result to another method in the same controller
Thank for any help or suggestion.
I found that as a solution. It's working. If someone has another solution can be more elegant.
'''
function ($message) use ($request) {
$info = Student::find(1)->value('monemail');
$message->from($request->email);
$message->to($info, 'Message from me')->subject($request->get('subject'));
'''
Have a good day.

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
));

Saving a Doctrine 2 Entity that contains an ObjectSelect element using Zend Form

I was following along with the Doctrine Hydrator tutorial, but I am having issues saving when my fieldset contains an ObjectSelect. I'm using ORM mapping on my entities. Basically I have a Role entity with id and name. I also have a User entity with id, name and role (ManyToOne). I also have my getters and setters. My setRole() method passes the Role entity as a parameter.
/** #param Role $role */
public function setRole(\Application\Entity\Role $role) {
$this->role = $role;
}
I setup a UserFieldset with a Doctrine Hydrator.
$this->setHydrator(new DoctrineHydrator($objectManager, 'Application\Entity\User'))
->setObject(new User());
The object select for the Role
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'role',
'options' => array(
'label' => 'Role',
'object_manager' => $objectManager,
'target_class' => 'Application\Entity\Role',
'property' => 'name'
)
));
I then setup a UserForm that sets the DoctrineHydrator and adds the UserFieldset.
My controller action
public function addUserAction() {
$objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$form = new UserForm($objectManager);
$user = new User();
$form->bind($user);
if ($this->request->isPost()) {
$form->setData($this->request->getPost());
if ($form->isValid()) {
$objectManager->persist($user);
$objectManager->flush();
}
}
return array('form' => $form);
}
What seems to be happening is that the ID of the role is passed to setRole rather than an object. As a workaround I've modified my action to:
if ($form->isValid()) {
$objectManager->persist($user);
$data = $this->request->getPost();
$role = $objectManager->find('Application\Entity\Role', $data->user['role']);
$user->setRole($role);
$objectManager->flush();
}
It seems as if this additional step should not be required, but I am not sure if I need to modify my setRole or if I also need to bind a Role entity to the form. This is obviously a simplified example, but my actual forms have many associations that will be tedious to have to code in the controller like this.
UPDATE:
Debug information about post and form.
var_dump($form->getData());
var_dump($this->request->getPost());
Output
object(Application\Entity\User)[395]
protected 'id' => int 6
protected 'name' => string 'Jane Doe' (length=8)
protected 'role' => null
object(Zend\Stdlib\Parameters)[146]
public 'user' =>
array (size=3)
'id' => string '' (length=0)
'name' => string 'Jane Doe' (length=8)
'role' => string '3' (length=1)
public 'submit' => string 'Add User' (length=8)
At long last I got it working. The issue was that I needed to add the role to my input filter on the fieldset
public function getInputFilterSpecification() {
return array(
'name' => array('required' => true),
'role' => array('required' => true)
)
}
... and my validation group on my form.
$this->setValidationGroup(array(
'User' => array(
'name',
'role'
)
));
Now to save the user in my action it is simply
if ($form->isValid()) {
$objectManager->persist($user);
$objectManager->flush();
}

Can't authenticate with different table

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!

yii. can't logout from module

I have admin module and different CWebUser(adminuser) for that module. It works good for login. So I can login in main app and in module by different users. But when I call logout method in module
Yii::app()->getModule('admin')->adminuser->logout();
it log me out from module and from main app as well.
how can I fix it?
thanks beforehand.
I think the key is stateKeyPrefix which can be used to tell different modules to use different session keys.
I will put main config file user section.
'user' => [
'allowAutoLogin' => true,
**'stateKeyPrefix' => 'YOUR-DEFAULT_',**
'loginUrl' => array('/login'),
'class' => 'application.wsi.auth.WSIWebUser',
'authTimeout' => 3600 * 24 // 1 hour
],
I have Admin module and I will put my AdminModule.php for you.
class AdminModule extends \CWebModule
{
public $defaultController = 'index';
public function init()
{
$this->setImport(array(
'admin.components.*',
));
$this->layout = 'main';
\Yii::app()->setComponents(array(
'authManager' => array(
'class' => 'CPhpAuthManager',
'authFile' => \Yii::getPathOfAlias('admin.data.auth') .'php',
'showErrors' => true,
),
'user' => array(
'stateKeyPrefix' => 'admin_',
'loginUrl' => \Yii::app()->createUrl('/admin/index/login'),
'class' => 'AdminWebUser',
'authTimeout' => 3600 * 24 // 1 day
),
), false);
}
}
I have components folder in admin module with AdminWebUser class in it as well.
class AdminWebUser extends \CWebUser {
public function getId() {
return Yii::app ()->user->getState ( 'id' );
}
public function getName() {
return Yii::app ()->user->getState ( 'name' );
}
public function getRole() {
return Yii::app ()->user->getState ( 'role' );
}
public function getEmail() {
return Yii::app ()->user->getState ( 'email' );
}
}
The rest of login and logout controller codes are same.
Hope it helps. If not please let me know.