...

/

Storing the User and OAuth Data in the Database

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:

Press + to interact
Model creation process
Model creation process

Creating and registering the model

In our project, we create a new Go file called models/oauth_user.go. The code looks like this:

Press + to interact
package models
import (
"time"
"github.com/beego/beego/v2/client/orm"
)
type OauthUser struct {
Id uint64
UserId uint64
Provider string // Like Facebook, Google, Twitter etc.
Uuid string
Name string
Email string
AccessToken string
ExpiresAt time.Time
TokenType string
RefreshToken string
ProfilePic string
CreatedAt time.Time
UpdatedAt 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. The Id field is a unique identifier for the records in OauthUser table. The UserId attribute links OAuth information to a user by establishing a relationship between OauthUser and User. The Provider, Uuid, Name, Email, ProfilePic attributes store user details fetched from the OAuth provider. The Provider field indicates the OAuth provider used. Uuid is the provider’s unique identifier of the user. AccessToken, ExpiresAt, TokenType, and RefreshToken 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. ...