I use setState in Yii but i also get Property "CWebUser.depId" is not defined - yii

i want to return the value dep_id from table user to use it so setState is supposed to return it like (Yii::app()->user->depId) but when i use it i get -- "CWebUser.depId" is not defined. i searched and i dont know what to do and i need a quick answer this is my
example:
private $_id;
//private $_dep_id;
public function authenticate()
{
$user=User::model()->find('LOWER(username)=?',array(strtolower($this->username)));
if($user===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if(!$user->validatePassword($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$user->id;
$this->setState('depId',$user->dep_id);
$this->username=$user->username;
$this->setState('lastLogin', date("m/d/y g:i A", strtotime($user->last_login_time)));
$user->saveAttributes(array('last_login_time'=>date("Y-m-d H:i:s", time())));
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode==self::ERROR_NONE;
}
public function getId()
{
return $this->_id;
}
and then i get this
Property "CWebUser.depId" is not defined.
what is the problem here ?!

You have to be authenticated user to use that variable on above scenario because it is restricted for authenticated users.

Related

Laravel: How to see if user is logged in in Base Controller?

I want to be able to change a field called "last_accessed" in the users table on each and every request the user makes.
I have a controller called "ContentController" which extends "Controller". So I figured just adding code in the constructor of "Controller":
public function __construct()
{
$user = \Auth::user();
if (Auth::check()) {
print 'Good';
}
else print "Bad";
}
No matter what I do, I can't it to see that I'm authorized.
Can someone please tell me:
Why is AUTH not working in the base controller?
How can I update the last_accessed field upon each view if this controller idea of mine isn't possible?
Because that doesn't work in __construct(). There is a workaround. It works but I'm not sure if some other Laravel users will accept my answer. What you should do is create a middleware and work from there. You can use an anonymous function, which in this case, mimics a middleware:
public function __construct(Request $request)
{
$this->middleware(function ($request, $next) {
$user = $request->user();
if ($user) {
print 'Good';
}
else print "Bad";
return $next($request);
});
}
If no user is logged in, $user will be null.

Recursive relationship with scope

A user has a sponsor:
public function sponsor()
{
return $this->belongsTo(User::class, 'sponsor_id');
}
A user has referrals:
public function referrals()
{
return $this->hasMany(User::class, 'sponsor_id');
}
A user is considered capped when they have 2 or more referrals:
public function activeReferrals()
{
return $this->referrals()->whereActive(true);
}
public function isCapped()
{
return $this->activeReferrals()->count() >= 2;
}
A user can give points. By default, the sponsor will receive them, but if the sponsor is capped, I want the points to go to a sponsor's referral that is NOT capped. If all the referrals are capped, then it does the same thing with the level below (the referral's referrals).
If I go user by user making database calls for each one, it's gonna take a long time. How can I write a scope that makes recursive calls until it finds the first active referral in the tree that's not capped?
This is what I'm trying to do:
Please give this a try... I believe this will work for you :)
public function scopeNotCappedActiveReferrals($query, $count) {
return $query->withCount(['referrals' => function($q) {
$q->where('active', true);
}])->where('referrals_count', '<', $count);
}
For the second part...
// Finally you can call it with
public function allReferrals() {
$users = User::notCappedActiveReferrals(2)->get();
$allUsers = $this->findNotCappedActiveReferralsRecurrsively($users);
}
// Do not place this function in the model,
// place it in your Controller or Service or Repo or blahblah...
// Also, not tested... but should work :)
protected function findNotCappedActiveReferralsRecurrsively($users) {
if(!count($user)) {
return $users;
}
foreach($users as $user) {
$moreUsers = $user->notCappedActiveReferrals(2)->get();
return $users->merge($this->findNotCappedActiveReferralsRecurrsively($moreUsers));
}
}
Hope this is what you need :)

Get All Property's From A User in Flash CS2

I have this:
public function saveProfile() {
this.setProperty("picture",factory.getClass("userProfile").getProperty("picture"),"no");
this.setProperty("gender",factory.getClass("userProfile").getProperty("gender"),"no");
this.setProperty("state",factory.getClass("userProfile").getProperty("state"),"no");
this.setProperty("city",factory.getClass("userProfile").getProperty("city"),"no");
this.setProperty("marital",factory.getClass("userProfile").getProperty("marital"),"no");
this.setProperty("about",factory.getClass("userProfile").getProperty("about"),"no");
}
factory.getClass("userProfile") functions:
public function setProperty(property:String, value:String) {
_profile[property] = value;
}
public function getProperty(property:String) {
if (_profile[property] == undefined) {
return "";
}
return _profile[property];
}
what i wanna do is:
this getProperty - setProperty returns the values from a specific user.
I want to get the properties from another user ex:
public function saveProfile(username:String) {
this.setProperty("picture",factory.getClass("userProfile").getProperty("picture"),"no"); ->
from the user username:String i ask to
etc...
}
If anyone can help me to change the getProperty, setProperty functions in the userprofile class to give me the property's from the username i ask.
Thanks a lot!
Regards

How do you add more error codes for user login on YII?

In yii I can use:
self::ERROR_USERNAME_INVALID;
I want another one:
self::ERROR_USER_BANNED;
That must give the error:
Sorry, but you cannot login because you account has been blocked.
How do I set this up?
Add it directly to your protected/components/UserIdentity.php :
class UserIdentity extends CUserIdentity {
const ERROR_USER_BANNED = -1; // say -1 you have to give some int value
public function authenticate() {
// ... code ...
if (/* condition to check for banning */) { // you might want to put this check right after any other username checks, and before password checks
$this->errorCode=self::ERROR_USER_BANNED;
$this->errorMessage='Sorry, but you cannot login because your account has been blocked.'
return $this->errorCode;
}
}
}
The default way with LoginForm.php model :
Add a new validator rule, say to your username field:
public function rules() {
return array(
// ... other rules ...
array('username','isBanned')
);
}
// the isbanned validator
public function isBanned($attribute,$params) {
if($this->_identity===null)
$this->_identity=new UserIdentity($this->username,$this->password);
if($this->_identity->authenticate() === UserIdentity::ERROR_USER_BANNED){
$this->addError($attribute,$this->_identity->errorMessage);
}
Ofcourse you could have declared another function in UserIdentity to check just for banning, and call that function from the isBanned validator, instead of having things in the authenticate function.
add following in UserIdentity.php
const ERROR_USER_BANNED = 12 ; #or whateve int value you prefer
public function getErrorMessageX() #or whatever method name
{
switch ($this->errorCode)
{
case self::ERROR_USER_BANNED:
return 'sorry, your account has been banned'; # custom error msg
case self::ERROR_USERNAME_INVALID:
return 'User does not exists';
case self::ERROR_PASSWORD_INVALID:
return 'Password does not match';
case self::ERROR_ACCOUNT_NOT_CONFIRMED: #this one is mine:)
return 'This Account needs confirmation';
}
}
now in LoginForm.php
public function authenticate( )
{
$this->_identity = new UserIdentity($this->username,$this->password);
if( $this->_identity->authenticate() === FALSE )
$this->addError('username', $this->_identity->errorMessageX); #here
#some more code
return !$this->_identity->errorCode;
}

NHibernate - how to resolve casting problem from nhibernate cache?

What i have is User class and say there are 2 more sub classes vipUser and regularUser.
in the login page i wanna check authentication and i don't know if it is vipUser or regularUser.. if it's vip the redirect is to one location and if it's regular to another location.
the authentication method must be on the User class for some resone - like this:
Function Authenticate(ByVal username As String, ByVal password As String) As User Implements IMindriUserDao.Authenticate
Return MyBase.GetUniqueByCriteria(Restrictions.Where(Of User)(Function(x) x.Username = username AndAlso x.Password = password))
End Function
the issue is that after i get from the nhibernate the authentication with the User now i wanna check if he is vip or regular but the user is already in the cache as a User without a casting option to check what type the User is...
any suggestions?!
Hope i was clear enough..
Thanks!
2 options: polymorphism or any-mapping
Polymorphism (sorry for being c# but im not fluent in VB.NET)
class User
{
public virtual IsVip { get { return false; } }
}
class VipUser
{
public override IsVip { get { return true; } }
}
Any-Mapping: everywhere where you have lazyloaded reference to User
public EntityMap()
{
ReferencesAny(x => x.User)
}
Are you sure? The user object should be the correct concrete type and you should be able to use the is or as operators to check.
var user = Authenticate("userid", "password");
var vipUser = user as vipUser;
if (vipUser != null) { RedirectToChampagneRoom(); }
That said, it's much easier to work with role properties that subclassing, i.e. User.UserType.