User Model and User Registration
Understand how to design and migrate a user model, implement password hashing for secure storage, and build a signup route with validations to register users in a Beego web 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:
In the file, we mainly specify two queries:
Lines 20–27: Query to create
userstable is specified.Line 32: Query to drop
userstable 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:
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. TheIdfield serves as the primary key for the user table, and theUsernameandPasswordfields are used for user authentication and security. Additionally, the ...