...

/

User Model and User Registration

User Model and User Registration

Learn to create a user model and user registration flow in a Beego application.

In this lesson, we will create a new model User using a migration. Then, we will implement the /signup route using the HTTP POST method that registers a new user. While implementing this route, we will understand how password hashing is used.

Creating a user model

Creating a new model involves the following steps:

  1. Creating a migration

  2. Running the migration

  3. Creating and registering the model

Creating a migration file

We create a new migration with the following command:

bee generate migration create_users_table
Creating a migration

This command creates a migration file, database/migrations/20230921_134238_create_users_table.go.

In this file, we define the schema for the users table. The code should resemble the following:

Press + to interact
package main
import (
"github.com/beego/beego/v2/client/orm/migration"
)
type CreateUsersTable_20230921_134238 struct {
migration.Migration
}
func init() {
m := &CreateUsersTable_20230921_134238{}
m.Created = "20230921_134238"
migration.Register("CreateUsersTable_20230921_134238", m)
}
func (m *CreateUsersTable_20230921_134238) Up() {
// Define the schema for the 'users' table
m.SQL("CREATE TABLE users (\
id bigint unsigned NOT NULL AUTO_INCREMENT, \
username varchar(64) DEFAULT NULL, \
password varchar(255) DEFAULT NULL, \
created_at datetime(3) DEFAULT NULL, \
updated_at datetime(3) DEFAULT NULL, \
PRIMARY KEY (id)
)")
}
func (m *CreateUsersTable_20230921_134238) Down() {
// Define the reverse migration to drop the 'users' table if needed
m.SQL("DROP TABLE users")
}

In the file, we mainly specify two queries:

  • Lines 20–27: Query to create users table is specified.

  • Line 32: Query to drop users table is specified.

Runing the migration

To execute the migration, we run the following command:

bee migrate -driver=mysql -conn="beego_notes:tmp_pwd@tcp(127.0.0.1:3306)/beego_notes?charset=utf8"
Execute the migration

This command runs the Up() method of the migration and creates the users table.

Creating and registering the model

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

Press + to interact
package models
import (
"time"
"github.com/beego/beego/v2/client/orm"
)
type User struct {
Id uint64 `gorm:"primaryKey"`
Username string `gorm:"size:64"`
Password string `gorm:"size:255"`
CreatedAt time.Time
UpdatedAt time.Time
}
func (u *User) TableName() string {
return "users"
}

Let’s understand the above code:

  • Lines 9–15: This block defines a Go struct named User, which represents a user entity in the application’s data model. The Id field serves as the primary key for the user table, and the Username and Password fields are used for user authentication and security. Additionally, the CreatedAt ...