Skip to content

Commit

Permalink
fix: first name, last name, notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
abinba committed May 17, 2024
1 parent b7c6294 commit 4a71c2e
Show file tree
Hide file tree
Showing 10 changed files with 61 additions and 17 deletions.
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Expand Down
1 change: 1 addition & 0 deletions handler/code_snippet_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func GetSingleCodeSnippet(c *fiber.Ctx) error {
Preload("User").
Preload("CodeSnippetVersions.ProgramLanguage").
Preload("CodeSnippetVersions.ReviewComments").
Preload("CodeSnippetVersions.ReviewComments.User").
Preload("CodeSnippetVersions.CodeSnippetRatings").Where("code_snippet_id = ?", id).First(&code_snippet)

if code_snippet.CodeSnippetID == uuid.Nil {
Expand Down
2 changes: 1 addition & 1 deletion handler/notification_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func GetNotificationsByUserID(c *fiber.Ctx) error {
}

var notifications []model.Notification
db.Where("user_id = ?", userUUID).Preload("User").Find(&notifications)
db.Where("user_id = ?", userUUID).Preload("User").Order("created_at desc").Find(&notifications)

if len(notifications) == 0 {
return c.Status(404).JSON(fiber.Map{
Expand Down
9 changes: 6 additions & 3 deletions handler/review_comment_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/google/uuid"
)


// GetAllReviewComments godoc
// @Summary Get all review comments
// @Description Get all review comments
Expand Down Expand Up @@ -69,14 +68,18 @@ func CreateReviewComment(c *fiber.Ctx) error {
})
}

var codeSnippetVersion model.CodeSnippetVersion
db.Model(&model.CodeSnippetVersion{}).Where("code_snippet_version_id = ?", review_comment.CodeSnippetVersionID).First(&codeSnippetVersion)

var codeSnippet model.CodeSnippet
db.Model(&model.CodeSnippet{}).Preload("CodeSnippetVersions", "code_snippet_version_id = ?", review_comment.CodeSnippetVersionID).First(&codeSnippet)
db.Model(&model.CodeSnippet{}).Where("code_snippet_id = ?", codeSnippetVersion.CodeSnippetID).First(&codeSnippet)

// TODO: use message queue and worker in the future for non-blocking.
if codeSnippet.UserID != nil && *codeSnippet.UserID != uuid.Nil {
notification := model.Notification{
UserID: *codeSnippet.UserID,
NotificationType: "CodeReview",
Text: "Your code has been reviewed! Check it out at My snippets",
Text: "<a href='/code_snippet/" + codeSnippet.CodeSnippetID.String() + "'>Your code has been reviewed! Check it out!</a>",
}
if notifResult := db.Create(&notification); notifResult.Error != nil {
fmt.Println("Error creating notification")
Expand Down
41 changes: 33 additions & 8 deletions handler/user_handler.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package handler

import (
"fmt"

"github.com/abinba/codereview/database"
"github.com/abinba/codereview/middleware"
"github.com/abinba/codereview/model"
Expand All @@ -9,9 +11,18 @@ import (
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)

type User struct {
type UserLogin struct {
Username string `json:"username" example:"johndoe" description:"The username of the user"`
Password string `json:"password" description:"The password of the user"`
}


type UserSignup struct {
FirstName string `json:"first_name" example:"john"`
LastName string `json:"last_name" example:"doe"`
Username string `json:"username" example:"johndoe" description:"The username of the user"`
Password string `json:"password" description:"The password of the user"`
}
Expand Down Expand Up @@ -49,7 +60,11 @@ func validateUser(username, password string) (bool, string) {
// @Router /api/v1/register/ [post]
func CreateUser(c *fiber.Ctx) error {
db := database.DB.Db
credentials := new(User)
if db == nil {
return c.Status(500).JSON(fiber.Map{"status": "error", "message": "Database connection not initialized"})
}

credentials := new(UserSignup)

err := c.BodyParser(credentials)
if err != nil {
Expand All @@ -62,10 +77,15 @@ func CreateUser(c *fiber.Ctx) error {
}

user := new(model.User)

err = db.Where("username = ?", credentials.Username).First(&user).Error
if err == nil {
return c.Status(400).JSON(fiber.Map{"status": "error", "message": "User already exists"})
}

if err != gorm.ErrRecordNotFound {
return c.Status(500).JSON(fiber.Map{"status": "error", "message": "Database query error", "data": err})
}

hashedPassword, err := bcrypt.GenerateFromPassword([]byte(credentials.Password), bcrypt.DefaultCost)
if err != nil {
Expand All @@ -74,9 +94,12 @@ func CreateUser(c *fiber.Ctx) error {

credentials.Password = string(hashedPassword)

err = repo.NewUserRepository(db).CreateUser(
credentials.Username, credentials.Password,
)
userRepo := repo.NewUserRepository(db)
if userRepo == nil {
return c.Status(500).JSON(fiber.Map{"status": "error", "message": "Failed to initialize user repository"})
}

err = userRepo.CreateUser(credentials.Username, credentials.Password, credentials.FirstName, credentials.LastName)
if err != nil {
return c.Status(500).JSON(fiber.Map{"status": "error", "message": "Could not create user", "data": err})
}
Expand All @@ -96,7 +119,7 @@ func CreateUser(c *fiber.Ctx) error {
// @Router /api/v1/login [post]
func Login(c *fiber.Ctx) error {
db := database.DB.Db
credentials := new(User)
credentials := new(UserLogin)

if err := c.BodyParser(credentials); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"status": "error", "message": "Invalid input", "data": err})
Expand Down Expand Up @@ -162,7 +185,8 @@ func GetSingleUser(c *fiber.Ctx) error {
// @Router /api/v1/user/{id} [put]
func UpdateUser(c *fiber.Ctx) error {
type updateUser struct {
Username string `json:"username"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}

db := database.DB.Db
Expand All @@ -182,7 +206,8 @@ func UpdateUser(c *fiber.Ctx) error {
return c.Status(500).JSON(fiber.Map{"status": "error", "message": "Something's wrong with your input", "data": err})
}

user.Username = updateUserData.Username
user.FirstName = updateUserData.FirstName
user.LastName = updateUserData.LastName
db.Save(&user)

return c.Status(200).JSON(fiber.Map{"status": "success", "message": "users Found", "data": user})
Expand Down
11 changes: 8 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,13 @@ func main() {
app := fiber.New()

app.Use(logger.New())
app.Use(cors.New())

app.Use(cors.New(cors.Config{
AllowOrigins: "http://localhost:8080", // your Vue.js frontend URL
AllowHeaders: "Origin, Content-Type, Accept, Authorization",
AllowMethods: "GET, POST, PUT, DELETE, OPTIONS",
AllowCredentials: true,
}))

router.SetupRoutes(app)

app.Get("/swagger/*", swagger.HandlerDefault) // default
Expand All @@ -32,5 +37,5 @@ func main() {
return c.SendStatus(404)
})

app.Listen(":8080")
app.Listen(":3000")
}
2 changes: 2 additions & 0 deletions migrations/20240517122442.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- Modify "users" table
ALTER TABLE "public"."users" DROP CONSTRAINT "users_username_key", ADD COLUMN "first_name" text NULL, ADD COLUMN "last_name" text NULL, ADD COLUMN "phone_number" text NULL;
3 changes: 2 additions & 1 deletion migrations/atlas.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
h1:XYIxcthCR23F/vyIpKtlhAEX4uBJdIGpnmE0TEfeW10=
h1:hN0o2GlS1JB626yOSIi4NvmfmOvwjdM9V3OLKlZ/zG8=
20240425202222.sql h1:soPLhrNf3kjJ7/VIwi0H07nUoFLrQUnDP0aQqyKL2P8=
20240425235457.sql h1:32ELkiV5mx7Idl0lRKtEZyZX/WGvICz3NkzjveL7rp0=
20240517122442.sql h1:5qyGzLuc7HWIvjfDwZzfUdDb05aCyUsokTvwanpz9T0=
3 changes: 3 additions & 0 deletions model/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ type User struct {
UserID uuid.UUID `gorm:"primaryKey;type:uuid;default:gen_random_uuid()" description:"UUID"`
Username string `gorm:"unqiue;not null" json:"username" example:"johndoe" description:"The username of the user"`
Password string `gorm:"not null;" json:"password" description:"The password of the user"`
FirstName string `gorm:"null;" json:"first_name" description:"First name of the user"`
LastName string `gorm:"null;" json:"last_name" description:"Last name of the user"`
PhoneNumber string `gorm:"null;" json:"phone_number" description: "Phone number of the user"`
IsActive bool `gorm:"default:true" description:"Is the user active"`
CreatedAt time.Time `gorm:"autoCreateTime"`
UpdatedAt time.Time `gorm:"autoUpdateTime"`
Expand Down
4 changes: 3 additions & 1 deletion repo/user_repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ func NewUserRepository(db *gorm.DB) *UserRepository {
return &UserRepository{db: db}
}

func (repo *UserRepository) CreateUser(username, password string) error {
func (repo *UserRepository) CreateUser(username, password, first_name, last_name string) error {
user := model.User{
Username: username,
Password: password,
FirstName: first_name,
LastName: last_name,
}
return repo.db.Create(&user).Error
}

0 comments on commit 4a71c2e

Please sign in to comment.