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:
Creating a migration
Running the migration
Creating and registering the model
Creating a migration file
We create a new migration with the following command:
bee generate migration create_users_table
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:
package mainimport ("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' tablem.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 neededm.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"
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:
package modelsimport ("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.TimeUpdatedAt 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. TheId
field serves as the primary key for the user table, and theUsername
andPassword
fields are used for user authentication and security. Additionally, theCreatedAt
...