harveyslash
harveyslash

Reputation: 6012

Database Design for oauth2

I have a users table that looks like so:

enter image description here

Currently my email is set to unique. And when user tries to login, I check the email and password, and if it matches, I send a token . But now I want to enable login using oauth providers(G+, Facebook, github etc). To achieve this, I decided to use Laravel's socialite plugin. In the docs, it says:

Retrieving User Details

Once you have a user instance, you can grab a few more details about the user:

$user = Socialite::driver('github')->user();

// OAuth Two Providers
$token = $user->token;

// OAuth One Providers
$token = $user->token;
$tokenSecret = $user->tokenSecret;

// All Providers
$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();

My question is, once the oauth is successful, how do I save the details in the database. What changes should I make in the table.

Upvotes: 5

Views: 4453

Answers (2)

Denis Mysenko
Denis Mysenko

Reputation: 6534

If you don't plan to make any requests on behalf of user, you actually don't even need to save OAuth access tokens – you could simple log users in once social authentication is passed. A typical flow:

  1. See if user exists already, eg. $user = User::whereEmail($user->getEmail());

  2. If user doesn't exist, create one using User::create([]), take as much data as possible from social network. If user exists, you may want to update his avatar/name with values from the social network.

  3. Log user in using Auth::login($user);

If you do however plan to do some extra requests on behalf of user, you would need to store access token somewhere (in a separate database table, for example). Most social networks would require you to save one long string – access token, and Twitter needs two – access token and a secret. So at the very least your table will contain: user ID from your users table, social provider ID and access token.

If you save access tokens, you can do API requests on behalf of users – check their timelines, post, etc.

Upvotes: 2

Mihkel Allorg
Mihkel Allorg

Reputation: 989

You could perhaps check this repository:

https://github.com/lucadegasperi/oauth2-server-laravel

If you don't want to use the package, you can just check out the database migration files and controllers to see how the logins and registrations are handled.

Upvotes: 0

Related Questions