Laravel: generate random unique token

I have a table in my database called keys that has this structure:

 id | user_id | token_id | token_key 

Every time a user logs in to my site, I need to create a new token_id and token_key for this user. How can I generate a random token for token_id and token_key while keeping the two values ​​unique?

For example, if:

  • token_id dfbs98641aretwsg ,
  • token_key sdf389dxbf1sdz51fga65dfg74asdf

Value:

 id | user_id | token_id | token_key 1 | 1 | dfbs98641aretwsg | sdf389dxbf1sdz51fga65dfg74asdf 

There cannot be another row in the table with this combination of tokens. How can i do this?

+5
source share
3 answers

I would not include an additional package for such a case. Sort of:

 do { $token_id = makeRandomToken(); $token_key = makeRandomTokenKey(); } while (User::where("token_id", "=", $token_id)->where("token_key", "=", $token_key)->first() instanceof User); 

... must do. Replace the model name with yours if it differs from "User", and use your or proposed functions to create random strings.

+10
source

In terms of token generation, you can use one of the Larvel Helper Functions ; str_random() .

This will create a random string of a certain length, for example, str_random(16) will create a random string of 16 characters (uppercase, lowercase and numbers).

Depending on how you use the tokens, should they really be completely unique? Given that they will match the user, or I assume you can use token_id and then check this for token_key , does it really matter if there is one of them? - although the chances of it are extremely small!

However, if you really need to be unique, you can always use a validator with a unique constraint. Using this package , you can also verify that both of them are unique also with unique_with . And then, if the validator fails, it generates a new token as necessary.

Based on your examples, you use str_random(16) for token_id and str_random(30) for token_key .

+17
source

You can use a dependency for this. Dirape laravel token

Run the command

 composer require dirape/token 

In your controller use

 use Dirape\Token\Token; 

You can use it as follows:

 User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), 'token_key' => (new Token())->Unique('users', 'api_token', 60), 'active' => 1 ]) 
0
source

Source: https://habr.com/ru/post/1234490/


All Articles