From e35e8f8c3a8738eb1a3b4c3b6b0462c38638781d Mon Sep 17 00:00:00 2001 From: bkawk Date: Sat, 4 Feb 2023 21:40:37 +0000 Subject: [PATCH] check username --- api/email/welcome.go | 8 ++++---- api/handlers/checkUsername.go | 35 +++++++++++++++++++++++++++++++++++ api/main.go | 1 + 3 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 api/handlers/checkUsername.go diff --git a/api/email/welcome.go b/api/email/welcome.go index 9e36a1b..ccc7bb2 100644 --- a/api/email/welcome.go +++ b/api/email/welcome.go @@ -13,11 +13,11 @@ func WelcomeEmail(u *models.User) error { password := os.Getenv("SMTP_PASSWORD") to := u.Email message := `Subject: Welcome to Our System +

Dear ` + u.Username + `,

+

Welcome to our system!

+

Best regards,

+

Support Team

` -

Dear ` + u.Username + `,

-

Welcome to our system!

-

Best regards,

-

Support Team

` smtpServer := os.Getenv("SMTP_SERVER") auth := smtp.PlainAuth("", from, password, smtpServer) err := smtp.SendMail(smtpServer, auth, from, []string{to}, []byte(message)) diff --git a/api/handlers/checkUsername.go b/api/handlers/checkUsername.go new file mode 100644 index 0000000..c3c4eb7 --- /dev/null +++ b/api/handlers/checkUsername.go @@ -0,0 +1,35 @@ +package handlers + +import ( + "bkawk/go-echo/api/models" + "context" + "net/http" + "time" + + "github.com/labstack/echo/v4" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" +) + +func CheckUsernameGet(c echo.Context) error { + + // Get the username from the query parameter + username := c.QueryParam("username") + + // Get database connection from context + db := c.Get("db").(*mongo.Database) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + // Check if username exists in the database + var existingUser models.User + collection := db.Collection("users") + err := collection.FindOne(ctx, bson.M{ + "username": username, + }).Decode(&existingUser) + if err == nil { + return c.JSON(http.StatusOK, echo.Map{"message": "Username not available"}) + } + + return c.JSON(http.StatusOK, echo.Map{"message": "Username available"}) +} diff --git a/api/main.go b/api/main.go index 773e8b3..6b49d18 100644 --- a/api/main.go +++ b/api/main.go @@ -107,6 +107,7 @@ func main() { // Routes e.GET("/health", handlers.HealthGet) // Health Check e.POST("/register", handlers.RegisterPost) // Register a new user + e.GET("/check-username", handlers.CheckUsernameGet) // Check if a username is available e.POST("/login", handlers.LoginPost) // Login with a username and password e.POST("/refresh", handlers.RefreshPost) // Refresh the access token using a refresh token e.DELETE("/refresh", handlers.RefreshDelete) // Invalidate the current refresh token, effectively logging the user out