Using Kohana 3, I have my User table with a field that references a field from another table in the database, however, I can't find where the user data is requested so I can add a ->with to it so I can use it throughout the site.
I'm still digging around and these are the pieces I've found so far:
in: modules/orm/classes/Kohana/Auth/ORM.php
public function get_user($default = NULL)
it calls parent::get_user($default);
so when I look up it’s parent: modules/auth/classes/Kohana/Auth.php:74, it's running this:
return $this->_session->get($this->_config['session_key'], $default);
$this->_session is created using:
Session::instance($this->_config['session_type']);
which I tracked down to: system/classes/Kohana/Session.php.
I think I reached a dead-end there.
I also tried doing a search for ORM::factory('User'), however, it's only used on login as far as I can tell.
get_user() returns an object of Model_User, but I'm not quite sure how to work with that to help me out.
In modules/auth/classes/model/auth/user.php (phew) there's on line 86 in my possibly outdated Kohana 3 install:
// Attempt to load the user
$this->where($fieldname, '=', $array['username'])->find();
Given that Model_Auth_User extends ORM this seems to be where it queries the db for the user, and hopefully where you can add your requirements.
Maybe use _load_with and always load the other table together with the user?
class Model_User extends Model_Auth_User
{
protected $_table_columns = array(
'id' => '',
'username' => '',
'email' => '',
'password' => '',
'logins' => '',
'last_login' => '',
'some_id' => '',
);
protected $_belongs_to = array(
'some_model' => array('foreign_key' => 'some_id'),
);
protected $_load_with = array(
'some_model',
);
The problem was coming from the fact that when you login, the data is cached and not pulled again until you re-login.
So the tables needed to be joined on the login methods.
Related
I am trying to export/import Excel files from/to the database. For that, I have viewed few tutorials. All show the same way for it. Here are the links.
https://www.laravelcode.com/post/laravel-8-excel-and-csv-import-export-to-database-using-maatwebsite-excel-with-example
https://www.itsolutionstuff.com/post/laravel-8-import-export-excel-and-csv-file-tutorialexample.html
And some other.
Exporting excel from the database is working fine. I am getting errors only while importing.
In both tutorials, they showed same way of importing code as shown below
public function model(array $row) {
return new product([
'vendor_id' => $row[0],
'product_name' => $row[1],
'product_price' => $row[2],
'product_model' => $row[3],
'created_at' => $row[4],
'updated_at' => $row[5],
]);
}
It is giving me this error while I am trying to import excel.
Add [vendor_id] to fillable property to allow mass assignment on [App\Models\product].
I try to search about fillable and found some solutions. I tried to apply on it but the error isn't getting resolved. Any idea where I went wrong?
UPDATE
Product Model file code
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class product extends Model {
use HasFactory;
}
You will need to specify either a fillable or guarded property on your model class. These properties are required because all Eloquent models are protected against mass assignment vulnerabilities by default.
A mass assignment vulnerability occurs when a user passes an unexpected HTTP request field and that field changes a column in your database that you did not expect. For example, a malicious user might send an is_admin parameter through an HTTP request, which is then passed to your model's create method, allowing the user to escalate themselves to an administrator.
If you are not specifying $guarded property then all fields need to be mentioned in $fillable property.
protected $fillable = ['vendor_id',
'product_name',
'product_price',
'product_model',
];
or
protected $guarded=['id']
Ref:https://laravel.com/docs/8.x/eloquent#mass-assignment
Good evening.
I added a boolean field "privacy_ok" to my user model and migration.
migration file
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name',100)->nullable();
$table->string('last_name',100)->nullable();
$table->string('email');
$table->string('password');
$table->boolean('privacy_ok')->default(0);
$table->text('permissions')->nullable();
$table->timestamp('last_login')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('email');
});
App\User.php
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'first_name','last_name','email', 'password', 'privacy_ok'
];
....
When I try to register my user, the new field is skipped.
$user = Sentinel::register($request->all());
I noticed that, if I cause an error (a duplicate email address... for example), the INSERT query does show the "privacy_ok" field.
Is there a way to solve that?
Do I have to user User::create and than "convert" it into a Cartalyst Sentinel object to go on with all the other operations (such as activation, for example) ?
Thanks
EDIT
I found some info here
Laravel Cartalyst Sentinel - Adding a username column to users table (What is the right way)
Now I have a new file App\Models\Cartalyst\User.php, but when I add it to the cartalyst config file ( config/cartalyst.sentinel.php ), I receive an error.
'users' => [
// 'model' => 'Cartalyst\Sentinel\Users\EloquentUser',
'model' => 'App\Models\Cartalyst\User',
],
Cannot declare class User, because the name is already in use
Of course the user is there even if I change User to Lorem. It's not a naming issue.
SOLVED
I forgot to declare the namespace in the header of the new class! :(
run.py:
class HMACAuth(HMACAuth):
def check_auth(self, userid, hmac_hash, headers, data, allowed_roles, resource, method):
accounts = app.data.driver.db['accounts']
user = accounts.find_one({'username': userid})
if user and '_id' in user:
secret_key = user['secret_key']
self.set_request_auth_value(user['_id'])
# in this implementation we only hash request data, ignoring the headers.
hm = hmac.new(bytes(secret_key, encoding='utf-8'), data, sha1).digest()
return user and base64.b64encode(hm).decode() == hmac_hash
settings.py:
vms = {
'additional_lookup': {
'url': 'regex("[\w]+")',
'field': 'name',
},
'cache_control': '',
'cache_expires': 0,
'public_methods': [],
'public_item_methods': [],
'resource_methods': ['GET', 'POST'],
'item_methods': ['GET','PATCH','DELETE'],
'auth_field': 'user_id',
'schema': vm_schema,
}
my problem is that every user is receiving all the VMs info when he/she send a GET request to localhost:5000/vms.
With the TokenAuth authentication this didn't happen.What am I missing??
PS: Eve 0.5-dev on Python 3.3.5
Since everything was working fine with token based authentication, and since there's nothing really different between the two methods expect the custom class itself, I would investigate around its behavior.
I would start by checking if documents are actually being stored with the proper user_id value, maybe by using the mongo shell. If not, make sure that the documents that you are inspecting have been saved with your custom HMAC class active. Add a breakpoint and track your code, simple stuff like that. Hope this helps
In a Model_Page class, extending the Kohana ORM class, I have this rules definition :
public function rules() {
return array(
'url' => array(
array('Model_Page::unique_url', array($this)),
),
);
}
To simplify here, I will just return false from this function, so it should never validate when I try to save/update a page :
public static function unique_url($page) {
return false;
}
This works as expected, if the value for url is not NULL or not an empty string.
But if I already have a page with an empty url, and that I try to add a new page with an empty url, the unique_url function is ignored, even when forcing a return false.
This could be a bug, but maybe I missed something...? In the Kohana docs, for the unique example, they use a username as an example, but the username also has a not_empty rule, which does not apply here.
Any help/suggestion appreciated!
I believe the rule is applied once you set the value, not when you're saving it.
I had a similar issue - the filter wasn't working if I didn't assign any value to the field. I've written my own save method:
public function save(Validation $validation = NULL)
{
if (!$this->loaded())
{
$this->ordering = 0;
}
return parent::save($validation);
}
this way the ordering would always be assigned for newly created objects and my filter would work.
And that's how I built another model. It's a company model that has a unique company name. Rules for the field are defined like this:
'name' => array(
array('not_empty'),
array('max_length', array(':value', 255)),
array(array($this, 'unique_name'))
)
And I have a method:
public function unique_name($value)
{
$exists = (bool) DB::select(array(DB::expr('COUNT(*)'), 'total_count'))
->from($this->_table_name)
->where('name', '=', $value)
->where($this->_primary_key, '!=', $this->pk())
->execute($this->_db)
->get('total_count');
return !$exists;
}
It basically checks if there are any other companies with the same name as the current one. Maybe this will give you the idea of what could be wrong with your solution.
I have been working with soft delete and now i want to load the navigation properties of my entity that are not "deleted". I have found a way, my problem this way is not to clear for me, there is another way to do this.
Context.CreateSet().Include("Salary").Select(u => new {User= u, Salary = u.Salarys.Where(s => !s.Deleted)}).AsQueryable().Select(a => a.User).AsQueryable();
Eager loading doesn't support filtering. Your code can be simplified to:
var users = Context.CreateSet<User>()
.Select(u => new {
User = u,
Salary = u.Salaries.Where(s => !s.Deleted)
})
.AsEnumerable()
.Select(a => a.User);
Include is not needed because you are replacing it with your own query and AsQueryable is not needed because the query is IQueryable all the time till called AsEnumerable which will sqitch to Linq-to-Objects when selecting users and selected salaries. EF will take care of correctly fixing navigation properties for you.