Skip to content

Commit

Permalink
check username
Browse files Browse the repository at this point in the history
  • Loading branch information
bkawk committed Feb 4, 2023
1 parent da3fdd7 commit e35e8f8
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
8 changes: 4 additions & 4 deletions api/email/welcome.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ func WelcomeEmail(u *models.User) error {
password := os.Getenv("SMTP_PASSWORD")
to := u.Email
message := `Subject: Welcome to Our System
<p>Dear ` + u.Username + `,</p>
<p>Welcome to our system!</p>
<p>Best regards,</p>
<p>Support Team</p>`

<p>Dear ` + u.Username + `,</p>
<p>Welcome to our system!</p>
<p>Best regards,</p>
<p>Support Team</p>`
smtpServer := os.Getenv("SMTP_SERVER")
auth := smtp.PlainAuth("", from, password, smtpServer)
err := smtp.SendMail(smtpServer, auth, from, []string{to}, []byte(message))
Expand Down
35 changes: 35 additions & 0 deletions api/handlers/checkUsername.go
Original file line number Diff line number Diff line change
@@ -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"})
}
1 change: 1 addition & 0 deletions api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit e35e8f8

Please sign in to comment.