Hello I use laravel 8 and backpack 4.1. I get an error: Property not found in \Illuminate\Contracts\Auth\Authenticatable|null, I have user_id in the table 'tenants'. Has somebody an idea, why the variable $ccu is null.
User.php:
public static function getUser()
{
return Auth::guard('backpack')->user();
}
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class);
}
Tenant.php:
vpublic function ccus(): HasMany
{
return $this->hasMany(Ccu::class);
}
public function users():hasMany
{
return $this->hasMany(User::class, 'user_id');
}
DashboardUserController:
public function index()
{
if (backpack_user()->hasRole('admin')) {
$this->data['title'] = trans('backpack::base.dashboard');
$this->data['breadcrumbs'] = [
trans('backpack::crud.admin') => backpack_url('dashboard'),
trans('backpack::base.dashboard') => false,
];
return view('dashboard', $this->data);
} else {
$user=User::getUser();
$ccu = $user->tenant->ccus()->get();
$ccuDiagram = new CcuDiagram($ccu);
$dataForGauge = CcuDiagram::getData($ccu);
$service = Service::find(1);
return view('ccu', ["dataForGauge" => $dataForGauge, "service" => $service]);
}
}
Ccu.php
public function tenant(): HasOne
{
return $this->hasOne(Tenant::Class);
}
Related
I have the following code :
RuleFor(record => record)
.Must(WholeObject => Mandatory(WholeObject, keyValuePairs))
.WithName( X => X.KeyName).WithMessage("KeyValue is mandatory but some values are missing")
//Here X.KeyValue contains the value.
//I want to pass this value on error
private bool Mandatory(Object recObj, Object keyValuePairs)
{
//return true or false depeneds on the logic
}
How do I pass the X.KeyValue in WithMessage?, If there is an error it returns .WithMessage("KeyValue is mandatory but some values are missing") but how do I pass the actual value ?
X contains X.KeyName and X.KeyValue
Note:
X.KeyValue is not a string.
public class KeyValue
{
public List<string> Val { get; set; }
}
RuleFor(record => record)
.Must(WholeObject => SizeOF(WholeObject, keyValuePairs))
.WithName(X => X.KeyName).WithMessage(x => $"{x.KeyValue.Val[0]} is not in range(min, max) as defined");
unfortunately this prints only the first value. Is it a way to include only the error value?
I used this
.WithName(X => X.KeyName).WithMessage(x => $"
{x.KeyValue.Val.ToList().ForEach(s => s)} is not in range(min, max) as
defined");
but this didnot work.
private bool SizeOF(Entity.EigenData.Record recObj, IDictionary<string, Entity.EigenSchema.AttributeSet> keyValuePairs)
{
string strval = recObj.KeyName;
Entity.EigenSchema.AttributeSet obj = keyValuePairs[recObj.KeyName];
//if the size falls inbetween min and max
return recObj.KeyValue.ISSizeWithinRange(obj);
//string val = obj.KeyValue.ToString();
}
public static bool ISSizeWithinRange(this Validation.Entity.EigenData.KeyValue kv, Validation.Entity.EigenSchema.AttributeSet Obj)
{
try
{
if (kv.Val.Count > 0) //only if List<val> is available go inside the loop
{
foreach (string s in kv.Val)
{
//foreach val check if its empty or null, if its empty or null then return false
bool True = String.IsNullOrEmpty(s);
if (True)
{
return true;
}
else
{
bool False = (Enumerable.Range(Obj.Size.Min, Obj.Size.Max).Contains(s.Length));
// if it contains within range then do nothing, return true at the end
//if it doesnot fall with in range then return false immediately. No need to check the entire set of values
if(!False)
{
return false;
}
}
}
//if it contains some value then return true
return true;
}
else
{
//List<val> count is zero
return false;
}
}
catch
{
return false;
}
}
Change your code like below:
RuleFor(record => record)
.Must(WholeObject => Mandatory(WholeObject,keyValuePairs))
.WithName(X => X.KeyName).WithMessage(x => $"{x.KeyName} is mandatory but some values are missing");
Whole code:
public class Status
{
public string Name { get; set; }
}
public class CustomValidator : AbstractValidator<Status>
{
public CustomValidator ()
{
RuleFor(record => record)
.Must(WholeObject => Mandatory(WholeObject,keyValuePairs))
.WithName(X => X.Name).WithMessage(x => $"{x.Name} is mandatory but some values are missing");
}
private bool Mandatory(Object recObj, Object keyValuePairs)
{
//return true or false depeneds on the logic
return false;
}
}
I want to login using the sql password() function in laravel. This is because the master database of employee table contains password in the format insert into tbl_name(' ') values (' ', password('abc'));
So I need to use this master table for login so can anyone suggest me as to how can this be possible?
public function login(Request $request) {
// dd($request->all());
if(Auth::attempt([
'tgi' => $request->tgi,
'password' => $request->password
]))
{
// $user = \DB::where('tgi', $request->tgi)->first();
$user = MasterLogin::where('tgi', $request->tgi)->first();
if($user->is_admin() == '1') {
return redirect()->route('dashboard');
}
elseif($user->is_admin() == '0'){
return redirect()->route('home');
}
elseif($user->is_admin() == '3'){
return redirect()->route('manager');
}
}
return redirect()->back();
}
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
In validateCredentials i would like to know how can I pass the password here.
As of now I tried this as said:
public function login(Request $request) {
// dd($request->all());
if(Auth::attempt([
'tgi' => $request->tgi,
'password' => sha1($request->password)
]))
{
$user = User::select("SELECT * FROM emp_username_db WHERE tgi = $request->tgi AND password = sha1('$request->password')");
if (Hash::check(sha1($request->password), $user['password'])) {
// The passwords match...
return redirect()->route('dashboard');
}
}
return redirect()->back();
}
My code that I am working on
class LoginController extends Controller
{
public function login(Request $request) {
//$user = User::where('tgi', $request->tgi)->first();
$result = User::where('tgi',$request->tgi)->where('password',\DB::raw('password("$request->password")'))->exists();
if ($result) {
if($result->is_admin() == '1'){
// Authentication passed...
return redirect()->intended('dashboard');
}elseif($result->admin == '0'){
return redirect()->route('home');
}
elseif($result->admin == '3'){
return redirect()->route('manager');
}
return redirect()->back();
}
}
As SQL default password is hashed using SHA1 so we can compare user's password by using laravel raw query like this.
$result = User::where('tgi',$request->tgi)->where('password',\DB::raw('password("$request->password")'))->exists();
if($result){
your code....
}
It's redirecting to dashboard but getting 302 found.
I'm trying to make a use from Steam API data as I like to learn on live examples, and looking at the way various statistics are returned I began to think that OOP approach would suit me best in this case.
What I'm trying to achieve is to loop through all the results, and programatically populate an array with objects of type that corresponds to the actual type of the statistic. I've tried to build myself a basic class, called Statistic, and after instantiating an object determine wheter or not it's class should change (i.e. whether or not to cast an object of type that Statistic is parent to and if so, of what type). How to do that in PHP? My solution gives me no luck, all of the objects are of type Statistic with it's 'type' property being the object I want to store alone in the array. Code:
$data = file_get_contents($url);
$data = json_decode($data);
$data = $data->playerstats;
$data = $data->stats;
$array;
for($i=0;$i<165;$i++)
{
$array[$i] = new Statistic($data[$i]);
echo "<br/>";
}
var_dump($array[10]);
And the classes' code:
<?php
class Statistic
{
public function getProperties()
{
$array["name"] = $this->name;
$array["value"] = $this->value;
$array["type"] = $this->type;
$array["className"] = __CLASS__;
return json_encode($array);
}
public function setType($x)
{
$y = explode("_",$x->name);
if($y[0]=="total")
{
if(!isset($y[2]))
{
$this->type = "General";
}
else
{
if($y[1]=="wins")
{
$this->type = new Map($x);
$this->__deconstruct();
}
if($y[1]=="kills")
{
$this->type = new Weapon($x);
$this->__deconstruct();
}
else $this->type="Other";
}
}
else $this->type = "Other";
}
function __construct($obj)
{
$this->name = $obj->name;
$this->value = $obj->value;
$this->setType($obj);
}
function __deconstruct()
{
echo "deconstructing <br/>";
return $this->type;
}
}
class Weapon extends Statistic
{
public function setType($x)
{
$y = explode("_",$x);
if($y[1]=="kills")
{
$this->type = "kills";
}
else if($y[1]=="shots")
{
$this->type = "shots";
}
else if($y[1]=="hits")
{
$this->type = "hits";
}
}
function __construct($x)
{
$name = explode("_",$x->name);
$this->name = $name[2];
$this->value = $x->value;
$this->setType($x->name);
}
function __deconstruct()
{
}
}
class Map extends Statistic
{
public function setType($x)
{
if($x[1]=="wins")
{
$this->type = "wins";
}
if($x[1]=="rounds")
{
$this->type = "rounds";
}
}
public function setName($name)
{
if(isset($name[3]))
{
if(isset($name[4]))
{
return $name[3] + " " + $name[4];
}
else return $name[3];
}
else return $name[2];
}
function __construct($x)
{
$name = explode("_",$x->name);
$this->name = $this->setName($name);
$this->value = $x->value;
$this->setType($name);
}
function __deconstruct()
{
}
}
Gives the result:
object(Statistic)#223 (3) {
["name"]=> string(18) "total_kills_deagle"
["value"]=> int(33)
["type"]=> object(Weapon)#222 (3) {
["name"]=> string(6) "deagle"
["value"]=> int(33)
["type"]=> string(5) "kills" }
}
Should that determination be driven from the loop itself, the whole advantage of having a set of functions that does everything for me and returns a ready-to-serve data is gone, since I would really have to cast different objects that aren't connected to each other, which is not the case here. How can I achieve returning objects of different type than the object itself is?
For answer your question How can I achieve returning objects of different type than the object itself is?
"Casting to change the object's type is not possible in PHP (without using a nasty extension)"
For more info: Cast the current object ($this) to a descendent class
So you can't change the class type of an instance with type of a derived class. In other world can't change instance of Static with instance of Weapon.
my website application is mostly model around a User Model which has all the key data that needed for most of the times.
Once the user is logged into the website I would like to keep it as a persistent variable across all the controllers. How do i achieve this as i cannot use session to hold a class object of Type Model.
My application is based on phalcon. However any suggestions are welcome.
I suggest you to write a simple class for user authentication & other user data manipulation, i wrote this Component and using in my project :
use Phalcon\Mvc\User\Component;
class Auth extends Component {
public function login($credentials) {
if(!isset($credentials['email'],$credentials['password'])) {
return FALSE;
}
if($this->isAuthorized()) {
return true;
}
$user = Users::findFirstByEmail($credentials['email']);
if($user == false) {
//block user for seconds
return false;
}
if($this->security->checkHash($credentials['password'],$user->password) && $user->status == 1) {
$this->_saveSuccessLogin($user);
$this->_setUserLoginSession($user);
return true;
} else {
return false;
}
}
public function isAuthorized() {
return $this->session->has('auth');
}
public function logout() {
$this->session->remove('auth');
return true;
}
public function user($key = null) {
if(!$this->isAuthorized()) {
return null;
}
if(is_null($key)) {
return $this->session->get('auth');
} else {
$user = $this->session->get('auth');
return array_key_exists($key, $user) ? $user[$key] : null;
}
}
private function _saveSuccessLogin(Users $user){
$userLogin = new UserLogins();
$userLogin->user_id = $user->id;
$userLogin->ip = $this->request->getClientAddress();
$userLogin->user_agent = $this->request->getUserAgent();
$userLogin->dns = gethostbyaddr($userLogin->ip);
if(!$userLogin->save()) {
return false;
}
return true;
}
private function _setUserLoginSession(Users $user) {
if(!$user) {
return false;
}
$this->session->set('auth',array(
'id' => $user->id,
'firstname' => $user->firstname,
'lastname' => $user->lastname,
'email' => $user->email,
'role_id' => $user->role_id
));
return true;
}
}
And in my services.php added into DI with this code :
$di->setShared('auth', function () {
return new Auth();
});
So when i want to get user info i use this :
$this->auth->user('email')
Also you can add more functionality to this component & modify it.
I hope that's useful for You.
You can use memcached and save it as key => value:
userId => serialized User model
I have a really simple class with two methods; One that will be called and the other that it will call. The idea is to call the OuterMockMethod method BUT mock the InnerMockMethod. Right now I can only seem to mock the OuterMockMethod method.
public class MockClass : IMockInterface
{
public virtual MockClass InnerMockMethod()
{
MockClass returnValue;
returnValue = new MockClass();
returnValue.SomeMessage = "Not mocked";
return returnValue;
}
public virtual MockClass OuterMockMethod()
{
MockClass mock;
mock = new MockClass();
return mock.MockedMethod();
}
}
Now this works, but it isn't the method I want to mock:
public void MockTest_Internal()
{
MockClass returnedClass;
MockClass mockProvider;
mockProvider = repository.StrictMock<MockClass>();
mockProvider.Expect(item => item.OuterMockMethod())
.Return(new MockClass { SomeMessage = "Mocked" });
repository.Replay(mockProvider);
returnedClass = mockProvider.OuterMockMethod();
Assert.IsTrue(returnedClass.SomeMessage == "Mocked");
}
As you can see, it calls the OuterMockMethod which it likes but I don't want that. I want to mock the InnerMockMethod so that when it's called by the OuterMockMethod it will return what I want it to.
public void MockTest_Internal()
{
MockClass returnedClass;
MockClass mockProvider;
mockProvider = repository.StrictMock<MockClass>();
mockProvider.Expect(item => item.InnerMockMethod())
.Return(new MockClass { SomeMessage = "Mocked" });
repository.Replay(mockProvider);
returnedClass = mockProvider.OuterMockMethod(); //Boom angry Rhino
Assert.IsTrue(returnedClass.SomeMessage == "Mocked");
}
In this case you need to put the mock on the returned object:
MockClass returnedMock = MockRepository.GenerateMock<MockClass>();
returnedMock.Expect( rm => rm.InnerMockMethod() )
.Return( new MockClass { SomeMessage = "Mocked" } );
mockProvider.Expect( mp => mp.OuterMockMethod() ).Return (returnedMock );
returnedClass = mockProvider.OuterMockMethod();
...
Note that StrictMock has been deprecated. The preferred pattern is now AAA (Arrange, Act, Assert). You can find more info here.