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.
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
OauthUser
struct represents a user’s OAuth credentials and related information obtained after authenticating via an external OAuth 2.0 provider like Facebook, Google, or Twitter. TheId
field is a unique identifier for the records inOauthUser
table. TheUserId
attribute links OAuth information to a user by establishing a relationship betweenOauthUser
andUser
. TheProvider
,Uuid
,Name
,Email
,ProfilePic
attributes store user details fetched from the OAuth provider. TheProvider
field indicates the OAuth provider used.Uuid
is the provider’s unique identifier of the user.AccessToken
,ExpiresAt
,TokenType
, andRefreshToken
are part of the OAuth protocol. These fields are used to handle the authentication and authorization processes. To access the provider’s APIs,AccessToken
is used as an authentication token.ExpiresAt
denotes the token’s expiration time.TokenType
specifies the type of the token. ...