zfcUser getState in another module - module

how could i getState from zfcUser
in view/index.phtml i get it from $this->zfcUserIdentity()->getState();
but now i need to get this value ( state for this user who is logged in ), in other module /controller (this is my costum module controller)
so i need to get State from:
zfcUser/Entity/User
to
myModule/Controller
i watch this https://github.com/ZF-Commons/ZfcUser/wiki/How-to-check-if-the-user-is-logged-in but this solutons is not helpful

and this helps too, for me:
$sm = $this->getServiceLocator();
$auth = $sm->get('zfcuserauthservice');
if ($auth->hasIdentity()) {
$user_edit = $auth->getIdentity()->getPrem();
}

The state is a property from the user itself. So if you get the user throught the identification service, you can grab the state from there.
public function myFooAction()
{
if ($this->zfcUserAuthentication()->hasIdentity()) {
$user = $this->zfcUserAuthentication()->getIdentity();
$state = $user->getState();
}
}
Mind that when the user is not logged in, the if condition is false. Also the state can be null or any arbitrary value, so do not expect that every user returns a valid state (in other words, check the returned value!)

follow this code, I had same problem then I have manage how to use identity of logged in user via zfcUser
in other modules controller at topside,
use Zend\EventManager\EventManagerInterface;
then create this two function in the sameclass,
public function setEventManager(EventManagerInterface $events)
{
parent::setEventManager($events);
$controller = $this;
$events->attach('dispatch', function ($e) use ($controller) {
if (is_callable(array($controller, 'checkUserIdentity')))
{
call_user_func(array($controller, 'checkUserIdentity'));
}
}, 100);
}
public function checkUserIdentity()
{
if ($this->zfcUserAuthentication()->hasIdentity()) {
echo "<pre>"; print_r($this->zfcUserAuthentication()->getIdentity());die;
}
}
it will give this kind of output
Admin\Entity\User Object
(
[id:protected] => 2
[username:protected] =>
[email:protected] => rajat.modi#softwebsolutions.com
[displayName:protected] =>
[password:protected] => $2y$14$2WxYLE0DV0mH7txIRm7GkeVJB3mhD4FmnHmxmrkOXtUFL7S9PqWy6
[state:protected] =>
)
That's it you will automatically get Identity whether user is logged in if not then it will redirect to login page.
Hope this will helps

Related

the auth_key of yii2 is'nt interference in cookie base

I have problem with auth_key , I have login form and it's work correctly without remember me and with remember me , but I read yii document , in that document wrote about remember me work with id and auth_key for create cookie to stay user in long time , i check the framework code and in there have three parameters (id, auth_key, expire_time()) i save auth_key in user table and it's code here
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
public function getAuthKey()
{
return $this->auth_key;
}
but i have problem , it's if a user login in site and i go to the user table and change the auth_key field , and now if user refresh the page it must be throw out the site because it's auth key is changed , but the user stay login in site , where is problem ?
The main use of auth_key is to authenticate the user by cookie (user don't have to put login data again). When you choose to be remembered at Login, this is how you are remembered. The system has to identify and login you somehow. It won't log out user if u change it.
You can try to change the key yourself in the "ValidateAutney" method, but this will be a bad practice, it is better to set the session time.
'session' => [
'class' => 'yii\mongodb\Session',
'writeCallback' => function($session)
{
return [
'user_id' => Yii::$app->user->id,
'agent' => Yii::$app->request->getUserAgent(),
'ip' => Yii::$app->request->getUserIP(),
'auth_key' => Yii::$app->security->generateRandomString(),
];
}
],
public function getAuthKey()
{
Yii::$app->session->open();
$query = new Query();
$query->select(['auth_key'])
->from('cache')
->where(['id'=> Yii::$app->session->id ]);
$row = $query->one();
return $row['auth_key'];
}

Redirect user after login in laravel 5.1

I am trying to implement a feature where, after logging in, a user gets redirected to a URL depending on their role. I have the roles part set up, but I'm having trouble testing the user's properties immediately after login.
I followed the instructions here to create a user login page. I have an AuthController that looks like this:
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;
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/test';
...
}
My __construct() function validates the user, but I don't know how to access the user object only immediately after login. This is what I presently have:
public function __construct() {
$this->middleware('guest', ['except' => 'getLogout']);
if ( \Auth::check() ) {
$user = \Auth::user();
if ( $user->admin() ) {
// an admin
$this->redirectTo = '/admin';
} else {
// it's a client
$this->redirectTo = '/client/dashboard';
}
}
$user = \Auth::user();
if ( is_object($user) ) {
} else {
$this->redirectTo = '/auth-not-object';
}
}
When I first attempt to log in with an administrator account, I get to the path /auth-not-object, because there isn't any authenticated user object at that point.
After having attempted to log in, but getting a bad redirect, when I revisit the /login url, I get redirected to /home, which I believe is the default $redirectTo in the traits this class uses. So that means we've passed the AuthController __construct() method without having changed the $redirectTo, even though there is an authenticated user.
I've found other questions, such as How to add extra logic on login condition in Laravel 5.2 and laravel redirect to url after login, but I don't understand how to apply those answers. For instance, the accepted answer to the second question shows new methods, getCredentials() and login(), which don't exist in the poster's original class. I am not sure in what class to add them, or where to call them from, in my codebase.
Other similar answers show a radically different way of authenticating users, such as this. It seems that, to use that solution, I would need to re-write my code, and forgo the use of the traits, which include bonus features like login throttling and so on.
Is there a way I can redirect users based on role after login, while still using these built-in traits?
Im not sure if the 5.1 auth is the same as the 5.2 auth, but if it is, remove all that from the construct and add this method:
protected function handleUserWasAuthenticated( Request $request, $throttles, $guard )
{
if ($throttles) {
$this->clearLoginAttempts( $request );
}
if ( method_exists( $this, 'authenticated' ) ) {
return $this->authenticated( $request, Auth::guard( $guard )->user() );
}
return redirect()->intended( $this->redirectTo );
}
this is the method that will determine the redirect and you have access to the user object.
EDIT
I take the above back, just add the following to your controller;
protected function authenticated( $request, $user ) {
return redirect()->intended( $user->admin() ? '/admin' : '/client/dashboard' );
}
That should work nicely

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.

Yii Rights :: Error 403 You Are Not Authorized To Perform This Action

I am newb in yii. I installed yii-rights in protected/modules/rights as per documentation. But can't use properly. There are something missing that I couldn't find out. localhost/index.php/right page is working well. But when I press on "permissions", "roles", "tasks", "operations". It shows
"Error 403
You are not authorized to perform this action."
Here is my main config::
'import'=>array(
'application.modules.right.*',
'application.modules.right.models*',
'application.modules.rights.components.*',
),
'rights'=>array(
'superuserName'=>'Admin', // Name of the role with super user privileges.
'authenticatedName'=>'Authenticated', // Name of the authenticated user role.
'userIdColumn'=>'id', // Name of the user id column in the database.
'userNameColumn'=>'username', // Name of the user name column in the database.
'enableBizRule'=>true, // Whether to enable authorization item business rules.
'enableBizRuleData'=>false, // Whether to enable data for business rules.
'displayDescription'=>true, // Whether to use item description instead of name.
'flashSuccessKey'=>'RightsSuccess', // Key to use for setting success flash messages.
'flashErrorKey'=>'RightsError', // Key to use for setting error flash messages.
'baseUrl'=>'/rights', // Base URL for Rights. Change if module is nested.
'layout'=>'rights.views.layouts.main', // Layout to use for displaying Rights.
'appLayout'=>'application.views.layouts.main', // Application layout.
'cssFile'=>'rights.css', // Style sheet file to use for Rights.
'install'=>false, // Whether to enable installer.
'debug'=>false,
),
'components'=>array(
'user'=>array(
'class'=>'RWebUser',
// enable cookie-based authentication
'allowAutoLogin'=>true,
'loginUrl'=>array('/user/login'),
),
AssignementController
public function accessRules()
{
return array(
array('allow', // Allow superusers to access Rights
'actions'=>array(
'view',
'user',
'revoke',
),
'users'=>$this->_authorizer->getSuperusers(),
),
array('deny', // Deny all users
'users'=>array('*'),
),
);
}
I need your help. PLEASE
Note that:: I am using yii-user also. yii-user is working well.
In your controller, you are required to name your action to perform function.
public function accessRules(){
.......
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update','districts','center'),
'users'=>array('#'),
......
}
For example in the above code, district and center are actions.
Hopefully, you will get the idea.
I know it's an older question but have you add
public function filters()
{
return array(
'accessControl',
);
}
to the AssignementController? Yii needs it to regard function accessRules() for access controlling.
Set your "Yii::app()->user->name";
Try this
<?php
class UserIdentity extends CUserIdentity
{
protected $_id;
const USER_INACTIVE = 3;
public function authenticate()
{
$p= Person::model()->findByUsername($this->username);
if (empty($p))
$this->errorCode = self::ERROR_USERNAME_INVALID;
elseif (!CPasswordHelper::verifyPassword($this->password, $p->password))
$this->errorCode = self::ERROR_PASSWORD_INVALID;
else
{
$this->_id = $p->id;
$this->username = $p->username;
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId() {
return $this->_id;
}
}
the line "$this->username = $p->username;";
Hope this help.

Saving data with cakephp won't work

I'm trying to load, edit and save a record with CakePHP 2.0 but I get a generic error during the save method that don't help me to understand where is the problem.
if I try with debug($this->User->invalidFields()); I get an empty array, but I get false from $this->User->save() condition.
Here is the controller action where I get the error:
public function activate ($code = false) {
if (!empty ($code)) {
// if I printr $user I get the right user
$user = $this->User->find('first', array('activation_key' => $code));
if (!empty($user)) {
$this->User->set(array (
'activation_key' => null,
'active' => 1
));
if ($this->User->save()) {
$this->render('activation_successful');
} else {
// I get this error
$this->set('status', 'Save error message');
$this->set('user_data', $user);
$this->render('activation_fail');
}
debug($this->User->invalidFields());
} else {
$this->set('status', 'Account not found for this key');
$this->render('activation_fail');
}
} else {
$this->set('status', 'Empty key');
$this->render('activation_fail');
}
}
When I try the action test.com/users/activate/hashedkey I get the activation_fail template page with Save error message message.
If I printr the $user var I get the right user from cake's find method.
Where I'm wrong?
I think the problem may be in the way you're querying for the User record. When you do this:
$user = $this->User->find('first', array('activation_key' => $code));
The variable $user is populated with the User record as an array. You check to ensure it's not empty, then proceed; but the problem is that $this->User hasn't been populated. I think if you tried debug($this->User->id) it would be empty. The read() method works the way you're thinking.
You could try using the ID from that $user array to set the Model ID first, like so:
if (!empty($user)) {
$this->User->id = $user['User']['id']; // ensure the Model has the ID to use
$this->User->set(array (
'activation_key' => null,
'active' => 1
));
if ($this->User->save()) {
...
Edit: Well another possible approach is to use the $user array instead of modifying the current model. You said that you get back a valid user if you debug($user), so if that's true you can do something like this:
if (!empty($user)) {
$user['User']['activation_key'] = null;
$user['User']['active'] = 1;
if ($this->User->save($user)) {
...
This method works in the same way as receiving form data from $this->request->data, and is described on the Saving Your Data part of the book.
I'm curious though if there's another part of your setup that's getting in the way. Can other parts of your app write to the database properly? You should also check to make sure you aren't having validation errors, like their example:
<?php
if ($this->Recipe->save($this->request->data)) {
// handle the success.
}
debug($this->Recipe->validationErrors);