Storing the User and OAuth Data in the Database
Learn to implement a model/table to enable integration of user data from OAuth 2.0 providers.
We'll cover the following...
Creating the OauthUser model
We will create a new model OauthUser using a migration. This model will be used to store information gathered from the OAuth 2.0 provider.
Creating a new model involves the following steps:
Creating and registering the model
In our project, we create a new Go file called models/oauth_user.go. The code looks like this:
package modelsimport ("time""github.com/beego/beego/v2/client/orm")type OauthUser struct {Id uint64UserId uint64Provider string // Like Facebook, Google, Twitter etc.Uuid stringName stringEmail stringAccessToken stringExpiresAt time.TimeTokenType stringRefreshToken stringProfilePic stringCreatedAt time.TimeUpdatedAt time.Time}func (u *OauthUser) TableName() string {return "oauth_users"}
Let’s understand the above code:
Lines 9–23: The
OauthUserstruct represents a user’s OAuth credentials and related information obtained after authenticating via an external OAuth 2.0 provider like Facebook, Google, or Twitter. TheIdfield is a unique identifier for the records inOauthUsertable. TheUserIdattribute links OAuth information to a user by establishing a relationship betweenOauthUserandUser. TheProvider,Uuid,Name,Email,ProfilePicattributes store user details fetched from the OAuth provider. TheProviderfield indicates the OAuth provider used.Uuidis the provider’s unique identifier of the user.AccessToken,ExpiresAt,TokenType, andRefreshTokenare part of the OAuth protocol. These fields are used to handle the authentication and authorization processes. To access the provider’s APIs,AccessTokenis used as an authentication token.ExpiresAtdenotes the token’s expiration time.TokenTypespecifies the type of the token.RefreshTokenis used to fetch a new access token when the current token expires. Lastly, ...