Error when creating token with laravel Santum - api

I am having problems when generating tokens with laravel sanctum.
The error claims that the value is out of range for the column 'tokenable_id'.
Here textual: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'c247a941-4954-4bf3-91eb-ddf37a8e2611' for column 'tokenable_id'.
This is the error message (image)
In my user model, I have implemented the uuid as the primary key, so the id corresponds to this code: c247a941-4954-4bf3-91eb-ddf37a8e2611, which claims the error.
This is the function where I am creating the token
LoginController.php
class LoginController extends Controller
{
public function __invoke(Request $request)
{
$user = User::whereEmail($request->email)->first();
/* Token generation */
$plainTextToken = $user->createToken($request->device_name)->plainTextToken;
return response()->json([[
'plain-text-token' => $plainTextToken
]);
}
}
To my understanding, this uuid, is the one that is generating me the error, then , my question goes to what action should I implement to resoolver with uuid with primary key.
Should I modify the personal tokens table, so that it accepts this string that is now the user id?
I remain attentive to any suggestion.

Remember to update your personal_access_tokens table migration. Change morphs('tokenable') to uuidMorphs('tokenable'), since morphs() is used when your related model (users in this case) uses auto increment. Since you are using uuids, you have to make this change to support those values.

Related

Customize the primary key data type for Identity in asp.net core 2 creates problems in UserStore

I need the primary key for my user class in Identity to be long instead of the default string. Following this MS tutorial. So i do all that (just replace GUID in the tutorial with long) and everything was looking good until I was working on created a seed class
var userStore = new UserStore<ApplicationUser>(context);
gives me the squiggles on ApplicationUser with the message:
Error CS0311 The type 'WSCPA_AC.Models.ApplicationUser' cannot be used as type parameter 'TUser' in the generic type or method 'UserStore'. There is no implicit reference conversion from 'WSCPA_AC.Models.ApplicationUser' to 'Microsoft.AspNetCore.Identity.IdentityUser'.
Now I see mention of this sort of problem in the comments at the bottom of the tutorial. Do I have to somehow override the UserStore class, and if so, how?
I think you will need to use the base class of UserStore which has a signature of UserStore<TUser, TRole, TContext, TKey> as follows:
var userStore = new UserStore<ApplicationUser, IdentityRole<long>, TContext, long>(context);
Where TContext is the type of your database context.

Phalcon working with MySQL routines

I have a MySQL database which has GUID's stored as binary(16) for the primary keys. I'm using a MySQL user defined routine when inserting and selecting to convert the id's to and from GUID's (GUIDToBinary() and BinaryToGUID()).
In order to use my routines in Phalcon, I am setting the 'columns' parameter for the find() and findFirst() model functions which now means i'm working with incomplete objects as the functions return an instance of Phalcon\Mvc\Model\Row.
The docs state when using the columns parameter the following occurs;
Return specific columns instead of the full columns in the model. When
using this option an incomplete object is returned
UserController.php
// Returns Phalcon\Mvc\Model\Row
$incompleteUser = User::find(['columns' => 'BinaryToGUID(id) as id, status, username, password, .....']);
// Create a new user object to update
$user = new User();
// Populate with existing data
$user->assign($incompleteUser->toArray());
// Assign new changes requested by the user
$user->assign($this->request->getPost());
// Update
$user->updateUser();
User.php
public function updateUser()
{
$manager = $this->getModelsManager();
return $manager->executeQuery("UPDATE User SET ..... WHERE id = GUIDToBinary(".$this->getDI()->get('db')->escapeString($this->id).")");
}
Irrespective of the fact that I've explicitly defined an update, an insert is performed due to the Model being in a transient state.
One solution I thought of was to move the binary to GUID conversion into Phalcon by using Model events however I can't find a suitable method for performing the conversion when selecting. Updating/Inserting is possible by using the beforeSave() and beforeUpdate() events. Perhaps I could just have different properties getId() and getIdGuid() within the model but I would prefer to avoid this if possible.
Is there a way to use MySQL user defined routines in Phalcon and hydrate my model so that it remains in a persistent state? Or do i need to go down the raw SQL route for my updates and avoid PHQL?
Thanks in advance for your time.

Problems understanding Redis ServiceStack Example

I am trying to get a grip on the ServiceStack Redis example and Redis itself and now have some questions.
Question 1:
I see some static indexes defined, eg:
static class TagIndex
{
public static string Questions(string tag) { return "urn:tags>q:" + tag.ToLower(); }
public static string All { get { return "urn:tags"; } }
}
What does that '>' (greater than) sign do? Is this some kind of convention?
Question 2:
public User GetOrCreateUser(User user)
{
var userIdAliasKey = "id:User:DisplayName:" + user.DisplayName.ToLower();
using (var redis = RedisManager.GetClient())
{
var redisUsers = redis.As<User>();
var userKey = redis.GetValue(userIdAliasKey);
if (userKey != null) return redisUsers.GetValue(userKey);
if (user.Id == default(long)) user.Id = redisUsers.GetNextSequence();
redisUsers.Store(user);
redis.SetEntry(userIdAliasKey, user.CreateUrn());
return redisUsers.GetById(user.Id);
}
}
As far as I can understand, first a user is stored with a unique id. Is this necessary when using the client (I know this is not for Redis necessary)? I have for my model a meaningful string id (like an email address) which I like to use. I also see a SetEntry is done. What does SetEntry do exactly? I think it is an extra key just to set a relation between the id and a searchable key. I guess this is not necessary when storing the object itself with a meaningful key, so user.id = "urn:someusername". And how is SetEntry stored as a Redis Set or just an extra key?
Question 3:
This is more Redis related but I am trying to figure out how everything is stored in Redis in order to get a grip on the example so I did:
Started redis-cli.exe in a console
Typed 'keys *' this shows all keys
Typed 'get id:User:DisplayName:joseph' this showed 'urn:user:1'
Typed 'get urn:user:1' this shows the user
Now I also see keys like 'urn:user>q:1' or 'urn:tags' if I do a 'get urn:tags' I get the error 'ERR Operation against a key holding the wrong kind of value'. And tried other Redis commands like smembers but I cannot find the right query commands.
Question 1: return "urn:tags>q:" + tag.ToLower(); gives you the key (a string) for a given tag; the ">" has no meaning for Redis, it's a convention of the developer of the example, and could have been any other character.
Question 3: use the TYPE command to determine the type of the key, then you'll find the right command in redis documentation to get the values.

Adding more info to Laravel's auth user

I am new to Laravel and I am trying to add some more information to the user variable I am getting back from Auth::user()
To be more detailed, I have a Many-to-Many relationship to a "Privileges" table. As the name suggests, that table holds specific privileges a user can have. In the pivot table, I just hold the the user_id and privilege_id. I have the necessary models set up and everything works fine if I do this in my before filter:
$user = Auth::user();
$user->priviledges()->get();
Now, I would really like to avoid querying every single time I want to find the privileges and would like to have Laravel's Auth class include the privilege information, so that when I do
$user = Auth::user();
I can do a
$user->privileges;
to get an array of all privileges the user has.
Any suggestions for the best approach?
The link to the answer above is not working. However, I found another solution here which worked for me as follows:
First I created a model called EmailPref.php in my own case;
app/model/EmailPref.php
class EmailPref extends Eloquent {
protected $table = 'email_pref';
public function user()
{
return $this->belongsTo('User');
}
}
and then I created a relationship (in my own case) in the User model like so;
app/model/User.php
public function emailPref()
{
return $this->hasOne('EmailPref');
}
I subsequently referenced it anywhere required within my application like so:
Auth::user()->emailPref;
Hence, I was able to add more information to the Auth user.
I'm no Laravel pro, but i think this will solve your problem: http://forums.laravel.io/viewtopic.php?id=1652

Yii CActiveRecord: find related data, but not using the primary key

I have this code in my model for "Application", I'm trying to get all the related "Campaign" objects
public function relations()
{
return array(
'campaigns' => array(self::HAS_MANY, 'Campaign', 'appKey'),
);
}
My problem is, the 'appKey' field in the campaigns table is not the primary key of the applications table and this is what Yii is using to try and find the campaigns.
The primary key of my applications table is 'id' but I would like it to use 'appKey'. How can I update my relations method to do this without making it the primary key?
Thanks.
You could set up a named scope in the Campaign model, like so:
public function byApplication($appKey)
{
$this->getDbCriteria()->mergeWith(array(
'condition'=>'appKey = :appkey',
'params'=>array('appKey'=>$appKey),
));
return $this;
}
And call it like this:
$campaigns = Campaign::model()->byApplication($appKey);
Or, as Irobb said, just set up a query function in your Application model instead of using an actual Relation, like so:
public function getCampaigns() {
return Campaign::model()->findallbyAttributes(array('appKey'=>$this->appKey));
}
And call it like a regular relation on your Application $model:
$campaigns = $model->campaigns; // remember with Yii you can call getters w/o the 'get'
A couple of things... AR is primarily useful for modeling a single table to a class, with a well-defined primary key... Anything else I would use the query builder.
Note: AR is not meant to solve all database-related tasks. It is best
used for modeling database tables in PHP constructs and performing
queries that do not involve complex SQLs. Yii DAO should be used for
those complex scenarios.
http://www.yiiframework.com/doc/guide/1.1/en/database.ar
AR relies on well defined primary keys of tables. If a table does not
have a primary key, it is required that the corresponding AR class
specify which column(s) should be the primary key by overriding the
primaryKey() method as follows,
public function primaryKey() {
return 'id';
// For composite primary key, return an array like the following
// return array('pk1', 'pk2'); }