Accessing auth session data (Lithium + MongoDB) - lithium

Okay, so hopefully I am asking this question correctly:
I set up my user model & controller, as well as my session model and controller... but I want to render some of the session info onto a page.
for example
If I were to login to a page, it would read "Brian" (or whatever my username is that I used for my login)
I hope I am not asking a repeated question -- I have searched this question pretty extensively and haven't found a solution yet. Thanks a lot!

If your session (set in a config/bootstrap file) is called "default" then just run check ...
$user = Auth::check('default');
Then $user will have an array of the user data in the session, so if you have a first_name field in your database/session you could do:
echo $user["first_name"];
I created a helper to clean this up a little, I called it: extensions/helper/Login.php
<?php
namespace app\extensions\helper;
use lithium\security\Auth;
class Login extends \lithium\template\Helper {
public function user() {
$user = Auth::check('default');
return $user;
}
public function fullName() {
$user = self::user();
return $user["first_name"] . " " . $user["last_name"];
}
}
?>
Then in my Views I used it like ...
<?=$this->login->fullName(); ?>

Related

Showing Wrong User Data CakePHP

I'm simply want to show the user that is currently logged in. My code for the Auth section came from 2.x cookbook.
The issue is the following:
I have 2 users currently in the system. User A and User B. User B was created second. Instead of showing the current user, it just shows User B. I assume it is because User B was the last to be created, because if I create User C, it will show user C instead.
Here is my action:
public function index($id = null) {
$this->set('strains', $this->Strain->find('all'));
$this->loadModel('User');
$users = $this->User->find('all');
$this->set('users', $users);
$this->set('userDataName', $this->Auth->user('id'));
if($this->Auth->user()) {
$this->User->id = $id;
$user = $this->Session->write('user', $this->User->findById($id));
$this->set('user', $user);
}
}
Here is the line in my view that should show the current user:
<?php echo $user['User']['username']; ?>
I've read several stack questions, but none seem to go over this specific scenario. I'm open to completely re-writing code if necessary. Thanks
the simplest way to display the username of the current session user is to use the auth component:
in controller
$user = $this->Auth->user(); // returns array with user data or null
$this->set('user', $user);
in view
echo $user['username'];
It's a logic error
Here is the line in my view that should show the current user:
<?php echo $user['User']['username']; ?>
In the template the username is taken from the $user variable.
public function index($id = null) {
...
$this->User->id = $id;
$user = $this->Session->write('user', $this->User->findById($id));
$this->set('user', $user);
}
}
The user variable depends on the $id parameter, not directly the currently logged-in user.
How to access the logged in user data
The simplest way to access the logged in user data is to use AuthComponent::user i.e. in a template:
<?php echo AuthComponent::user('username'); ?>

Getting the authenticated user details Laravel 5.2

After authenticating a user and return to an appropriate view I want to get hold of the id of the user so I can get some info from the table (users).
How do I do this please?
You can use Auth Facade in your controller to get the ID of authenticated user.
for eg.-
SomeController -
<?php
namespace App\Http\Controllers;
//don't forget to include this one
use Illuminate\Support\Facades\Auth;
class SomeController extends Controller
{
public function getDetails(){
//get authenticated user's Id
$user = Auth::user();
$user_id = $user->id;
//other details
$user_name = $user->name;
$user_email = $user->email;
}
}
You can use
Auth::user()->id or auth()->user()->id
If you have multiple authentication and you are using guard then you can use
Auth::guard('your_guard_name')->user()->id or auth()->guard('your_guard_name')->user()->id
N.B: if you use Auth then you must include it like use Auth
Hope it will help. :) :)

LARAVEL 5: Need to keep query string after auth redirects

I have a link I am sending via email. For example, www.swings.com/worker?id=3382&tok=jfli3uf
In this case I want the person to click the link, get sent to the login page(which it does) and then be directed to a controller method WITH the $id and $tok variables. I can't get that part to work. Any ideas? I am only using the RedirectIfAuthenticated class and this is what it looks like:
public function handle($request, Closure $next)
{
$user = $request->user();
if ($this->auth->check()) {
if($user && $user->hasRole('worker'))
{
return redirect('worker');
}
return redirect('home');
}
return $next($request);
}
hasRole is a method I created in the User model that checks the role of the logged in user
You can flash data to the session when redirecting by chaining the with() method:
// in your handle() method:
return redirect('home')->with($request->only('id', 'tok'));
// then in home controller method:
$id = session('id');
$tok = session('tok');
AFTER SOME HOURS I WAS ABLE TO HAVE A SOLUTION:
ReturnIfAuthenticated wasn't changed. I just added the following within my controller that this link should go to:
for instance, the route would be:
Route::get('worker', 'WorkerController#methodINeed');
Within this method:
public function methodINeed() {
$id = Input::get('id');
$tok = Input::get('tok');
// Do what I need this variables to do
}
What I didn't understand and what could not be properly understood is that the auth controller in Laravel 5 is triggered when a user is a guest it will still redirect to the actual method with all its original data once auth is successful. Hope this is helpful.

Laravel 5 with entrust - hasRole not working

I have a logged in user and the code here works:
#if( Auth::check() )
Logged in as: {{ Auth::user()->firstname }} {{ Auth::user()->lastname }}
#endif
I'm using zizaco/entrust and it's all working. I've created roles and permissions and given my user the admin role which has administrative permission.
So why doesn't this work:
$user = Auth::user();
print_r($user->hasRole('admin'));
If I print_r the $user I can see that the Auth user is loaded, but hasRole is not working. I was just testing this within the blade template at the moment but tried it in the Controller with the same result. My error is:
BadMethodCallException in Builder.php line 1992:
Call to undefined method Illuminate\Database\Query\Builder::hasRole()
My user model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Model {
use EntrustUserTrait;
protected $table = 'users';
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
}
UPDATE
I realized hasRole works for me when I look up the user this way (returns App\Models\User Object):
$user = \App\Models\User::find( \Auth::user()->id );
but NOT when I find the user this way (returns App\User Object ):
$user = \Auth::user();
I rather would have thought it would work the other way, when I pull up the App\User I'd have access to hasRole but not necessarily when I search for a user. I thought hasRole would work right from the Auth::user() without having to lookup the user with the user model...???
Found the issue..
in config/auth.php I had
'model' => 'App\User',
My namespace requires
'model' => 'App\Models\User',
Thanks for you update, it was a problem for me as well. And I used your advice and I put in my HomeController
public function index()
{
$user = User::find( \Auth::user()->id );
return view('home', compact('user'));
}
and then in my Home View
#if ($user->hasRole('Admin'))
<li>Create User</li>
#endif
<li>User List</li>
<li>Create Client</li>
<li>Create Payment</li>
and everything works perfect...

Yii form and model for key-value table

I have a table which has only two column key-value. I want to create a form which allow user insert 3 pair of key-value settings.
Do I need pass 3 different models to the view? Or is there any possible way to do this?
Check out this link:
http://www.yiiframework.com/doc/guide/1.1/en/form.table
This is considered best form in Yii for updating for creating multiple models.
In essence, for creation you can create a for loop generate as many inputs a you wish to have visible, and in your controller loop over the inputs to create new models.
View File:
for ( $settings as $i=>$setting ) //Settings would be an array of Models (new or otherwise)
{
echo CHtml::activeLabelEx($setting, "[$i]key");
echo CHtml::activeLabelEx($setting, "[$i]key");
echo CHtml::error($setting, "[$i]key");
echo CHtml::activeTextField($setting, "[$i]value");
echo CHtml::activeTextField($setting, "[$i]value");
echo CHtml::error($setting, "[$i]value");
}
Controller actionCreate:
$settings = array(new Setting, new Setting, new Setting);
if ( isset( $_POST['Settings'] ) )
foreach ( $settings as $i=>$setting )
if ( isset( $_POST['Setttings'][$i] ) )
{
$setting->attributes = $_POST['Settings'][$i];
$setting->save();
}
//Render View
To update existing models you can use the same method but instead of creating new models you can load models based on the keys in the $_POST['Settings'] array.
To answer your question about passing 3 models to the view, it can be done without passing them, but to validate data and have the correct error messages sent to the view you should pass the three models placed in the array to the view in the array.
Note: The example above should work as is, but does not provide any verification that the models are valid or that they saved correctly
I'm going to give you a heads up and let you know you could potentially make your life very complicated with this.
I'm currently using an EAV patterned table similar to this key-value and here's a list of things you may find difficult or impossible:
use CDbCriteria mergeWith() to filter related elements on "value"s in the event of a search() (or other)
Filtering CGridView or CListView
If this is just very straight forward key-value with no related entity aspect ( which I'm guessing it is since it looks like settings) then one way of doing it would be:
create a normal "Setting" CActiveRecord for your settings table (you will use this to save entries to your settings table)
create a Form model by extending CFormModel and use this as the $model in your form.
Add a save() method to your Form model that would individually insert key-value pairs using the "Setting" model. Preferably using a transaction incase a key-value pair doesn't pass Settings->validate() (if applicable)
optionally you may want to override the Form model's getAttributes() to return db data in the event of a user wanting to edit an entry.
I hope that was clear enough.
Let me give you some basic code setup. Please note that I have not tested this. It should give you a rough idea though.:
Setting Model:
class Setting extends CActiveRecord
{
public function tableName()
{
return 'settings';
}
}
SettingsForm Model:
class SettingsForm extends CFormModel
{
/**
* Load attributes from DB
*/
public function loadAttributes()
{
$settings = Setting::model()->findAll();
$this->setAttributes(CHtml::listData($settings,'key','value'));
}
/*
* Save to database
*/
public function save()
{
foreach($this->attributes as $key => $value)
{
$setting = Setting::model()->find(array('condition'=>'key = :key',
'params'=>array(':key'=>$key)));
if($setting==null)
{
$setting = new Setting;
$setting->key = $key;
}
$setting->value = $value;
if(!$setting->save(false))
return false;
}
return true;
}
}
Controller:
public function actionSettingsForm()
{
$model = new Setting;
$model->loadAttributes();
if(isset($_POST['SettingsForm']))
{
$model->attributes = $_POST['SettingsForm'];
if($model->validate() && $model->save())
{
//success code here, with redirect etc..
}
}
$this->render('form',array('model'=>$model));
}
form view :
$form=$this->beginWidget('CActiveForm', array(
'id'=>'SettingsForm'));
//all your form element here + submit
//(you could loop on model attributes but lets set it up static for now)
//ex:
echo $form->textField($model,'fieldName'); //fieldName = db key
$this->endWidget($form);
If you want further clarification on a point (code etc.) let me know.
PS: for posterity, if other people are wondering about this and EAV they can check the EAV behavior extention or choose a more appropriate DB system such as MongoDb (there are a few extentions out there) or HyperDex