12

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 into my site, I need to generate a new token_id and token_key set for that user. How can I generate a random token for both the token_id and the token_key while keeping the two values unique?

For example, if:

  • token_id is dfbs98641aretwsg,
  • token_key is sdf389dxbf1sdz51fga65dfg74asdf

Meaning:

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

There can be no other row in the table with that combination of tokens. How can I do this?

6 Answers 6

25

In terms of generating the tokens, you could use one of Laravel's Helper Functions; str_random().

This will generate a random string of a specified length, e.g str_random(16) will generate a random string of 16 characters (upper case, lower case, and numbers).

Depending on how you are using the tokens, do they really need to be completely unique? Given that they will match to a user, or I assume you may be using the token_id and then verifying this against the token_key does it really matter if there is a double up of one of them? - although the chances of this are extremely small!

However, if you do need them to be truly unique you can always use a validator with the unique constraint. Using this package you could also test that the two of them are unique too with unique_with. And then if the validator fails then it generates a new token as needed.

Based off your examples, you would be using str_random(16) for token_id and str_random(30) for the token_key.

20

I'd avoid including an extra package for a case like this one. Something like:

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

...should do. Replace model name with yours, if different from 'User', and use your or suggested functions for creating random strings.

8
  • 6
    do-while loop will keep "doing" as long as the statement in "while" evaluates as true (and it will run at least once, unlike while-do). In this specific example, it will generate token id/key pair, then it will try to find a user in database that has that specific token and key pair. instanceof checks if the result is instance of the User class, meaning that it's checking if such user is found. If it is, do will execute again and make another pair, and so on until it finds no user having the generated pair of token id/key. Oct 26, 2015 at 10:39
  • 13
    This is a very bad solution! You should never wish to loop through every record in you database table each time you want to add a new record. You should better use a time based unique string.
    – Marten
    Apr 6, 2016 at 9:42
  • 7
    It is not looping through every record in the table each time a new record is added. Please try understanding the do-while loop. Apr 6, 2016 at 9:54
  • 3
    I agree with @Marten. Not a good solution. There are two things wrong with it: First you hit the database every time you create a new token at least once - if the token exists in the db, you hit it again. Second, there is no guarantee of uniqueness. The same key can be inserted into the db by another thread right after you check for its existence and before you insert it on the current thread. Why not use UUID's, which have a high degree of safety when it comes to uniqueness?
    – impeto
    May 22, 2016 at 14:31
  • 8
    One possible improvement would be to just try to insert the new tokens instead of SELECTing them. If they're not unique request will fail (assuming the DB is correctly set with unique indices), and you go back into the loop and create a new pair and try again until the operation succeeds. This would guarantee the atomicity of the operation.
    – ivanhoe
    Jul 19, 2016 at 18:34
1

You can use a dependency to do this. Dirape laravel-token

Run the command

composer require dirape/token

In your controller use

use Dirape\Token\Token;

You can use it like this:

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

Following @ivanhoe suggestion... this is what I came up with:-

    $token = new Token;

    //in case there are duplicate
    for ($x = 0; $x < 10; $x ++) {
        $token->access_token = str_random(16);;
        try {
            if ($token->save()) {
                break;
            }
        }catch (QueryException $e) {

        }
    }
0

I think this is better:

do {
    $this->slug = strtolower(str()->random(5));
} while (User::where("slug", $this->slug)->exists());
-1

For other users seeing this post. Best solution I found was using another string or intiger to make a token. for example what is doing laravel when creating a new user.

base64_encode($data['email']); // here using the email as base

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.