Skip to content

Commit

Permalink
[Backend] Refactor main.go
Browse files Browse the repository at this point in the history
- Organize everything better
  • Loading branch information
Alfex4936 committed Apr 15, 2024
1 parent bad6694 commit 223ff7b
Show file tree
Hide file tree
Showing 19 changed files with 637 additions and 436 deletions.
7 changes: 3 additions & 4 deletions backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ require (
github.com/gofiber/utils v1.1.0 // indirect
github.com/gorilla/websocket v1.5.1 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/klauspost/compress v1.17.7 // indirect
github.com/klauspost/compress v1.17.8 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
Expand All @@ -95,12 +95,11 @@ require (
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.52.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
go.mongodb.org/mongo-driver v1.14.0 // indirect
go.mongodb.org/mongo-driver v1.15.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0 // indirect
golang.org/x/exp v0.0.0-20240409090435-93d18d7e34b8 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/tools v0.20.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
8 changes: 6 additions & 2 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+o
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg=
github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU=
github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
Expand Down Expand Up @@ -236,6 +238,8 @@ github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaD
go.mongodb.org/mongo-driver v1.11.4/go.mod h1:PTSz5yu21bkT/wXpkS7WR5f0ddqw5quethTUn9WM+2g=
go.mongodb.org/mongo-driver v1.14.0 h1:P98w8egYRjYe3XDjxhYJagTokP/H6HzlsnojRgZRd80=
go.mongodb.org/mongo-driver v1.14.0/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c=
go.mongodb.org/mongo-driver v1.15.0 h1:rJCKC8eEliewXjZGf0ddURtl7tTVy1TK3bfl0gkUSLc=
go.mongodb.org/mongo-driver v1.15.0/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c=
go.uber.org/goleak v1.2.1/go.mod h1:qlT2yGI9QafXHhZZLxlSuNsMw3FFLxBr+tBRlmO1xH4=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
Expand All @@ -251,6 +255,8 @@ golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0 h1:985EYyeCOxTpcgOTJpflJUwOeEz0CQOdPt73OzpE9F8=
golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI=
golang.org/x/exp v0.0.0-20240409090435-93d18d7e34b8 h1:ESSUROHIBHg7USnszlcdmjBEwdMj9VUvU+OPk4yl2mc=
golang.org/x/exp v0.0.0-20240409090435-93d18d7e34b8/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI=
golang.org/x/image v0.15.0 h1:kOELfmgrmJlw4Cdb7g/QGuB3CvDrXbqEIww/pNtNBm8=
golang.org/x/image v0.15.0/go.mod h1:HUYqC05R2ZcZ3ejNQsIHQDQiwWM4JBqmm6MKANTp4LE=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
Expand Down Expand Up @@ -288,8 +294,6 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
Expand Down
61 changes: 60 additions & 1 deletion backend/handlers/admin_api.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
package handlers

import (
"chulbong-kr/middlewares"
"chulbong-kr/services"
"time"

"github.com/gofiber/fiber/v2"
)

func ListUnreferencedS3ObjectsHandler(c *fiber.Ctx) error {
// RegisterAdminRoutes sets up the routes for admin handling within the application.
func RegisterAdminRoutes(api fiber.Router) {
api.Post("/chat/ban/:markerID/:userID", middlewares.AdminOnly, banUserHandler)

adminGroup := api.Group("/admin")
{
adminGroup.Use(middlewares.AdminOnly)
adminGroup.Get("/dead", listUnreferencedS3ObjectsHandler)
}
}

func listUnreferencedS3ObjectsHandler(c *fiber.Ctx) error {
killSwitch := c.Query("kill", "n")

dbURLs, err := services.FetchAllPhotoURLsFromDB()
Expand All @@ -29,3 +42,49 @@ func ListUnreferencedS3ObjectsHandler(c *fiber.Ctx) error {

return c.JSON(unreferenced)
}

func banUserHandler(c *fiber.Ctx) error {
// Extract markerID and userID from the path parameters
markerID := c.Params("markerID")
userID := c.Params("userID")

// assert duration is sent in the request body as JSON
var requestBody struct {
DurationInMinutes int `json:"duration"`
}
if err := c.BodyParser(&requestBody); err != nil {
requestBody = struct {
DurationInMinutes int `json:"duration"`
}{
DurationInMinutes: 5, // default 5 minutes banned
}
// return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
// "error": "Invalid request format",
// })
}

if requestBody.DurationInMinutes < 1 {
requestBody.DurationInMinutes = 5
} else if requestBody.DurationInMinutes > 15 {
requestBody.DurationInMinutes = 10 // max 10 minutes
}

// Convert duration to time.Duration
duration := time.Duration(requestBody.DurationInMinutes) * time.Minute

// Call the BanUser method on the manager instance
err := services.WsRoomManager.BanUser(markerID, userID, duration)
if err != nil {
// Log the error or handle it as needed
// log.Printf("Error banning user %s from room %s: %v", userID, markerID, err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "Failed to ban user",
})
}

// Return success response
return c.JSON(fiber.Map{
"message": "User successfully banned",
"time": duration,
})
}
49 changes: 42 additions & 7 deletions backend/handlers/auth_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,40 @@ package handlers

import (
"chulbong-kr/dto"
"chulbong-kr/middlewares"
"chulbong-kr/services"
"chulbong-kr/utils"
"database/sql"
"fmt"
"log"
"os"
"strings"

"github.com/gofiber/fiber/v2"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)

// RegisterAuthRoutes sets up the routes for auth handling within the application.
func RegisterAuthRoutes(api fiber.Router) {
oauth2 := generateOAuthConfig()

api.Get("/google", getGoogleAuthHandler(oauth2))
authGroup := api.Group("/auth")
{
authGroup.Post("/signup", signUpHandler)
authGroup.Post("/login", loginHandler)
authGroup.Post("/logout", middlewares.AuthMiddleware, logoutHandler)
authGroup.Get("/google/callback", getGoogleCallbackHandler(oauth2))
authGroup.Post("/verify-email/send", sendVerificationEmailHandler)
authGroup.Post("/verify-email/confirm", validateTokenHandler)

// Finding password
authGroup.Post("/request-password-reset", requestResetPasswordHandler)
authGroup.Post("/reset-password", resetPasswordHandler)
}
}

// SignUp User godoc
//
// @Summary Sign up a new user [normal]
Expand All @@ -31,7 +55,7 @@ import (
// @Failure 409 {object} map[string]interface{} "Email already registered"
// @Failure 500 {object} map[string]interface{} "An error occurred while creating the user"
// @Router /auth/signup [post]
func SignUpHandler(c *fiber.Ctx) error {
func signUpHandler(c *fiber.Ctx) error {
var signUpReq dto.SignUpRequest
if err := c.BodyParser(&signUpReq); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Cannot parse JSON, wrong sign up form."})
Expand Down Expand Up @@ -80,7 +104,7 @@ func SignUpHandler(c *fiber.Ctx) error {
// @Failure 401 {object} map[string]interface{} "Invalid email or password"
// @Failure 500 {object} map[string]interface{} "Failed to generate token"
// @Router /auth/login [post]
func LoginHandler(c *fiber.Ctx) error {
func loginHandler(c *fiber.Ctx) error {
var request dto.LoginRequest
if err := c.BodyParser(&request); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
Expand Down Expand Up @@ -109,7 +133,7 @@ func LoginHandler(c *fiber.Ctx) error {
return c.JSON(response)
}

func LogoutHandler(c *fiber.Ctx) error {
func logoutHandler(c *fiber.Ctx) error {
// Retrieve user ID from context or session
userID, ok := c.Locals("userID").(int)
if !ok {
Expand Down Expand Up @@ -150,7 +174,7 @@ func LogoutHandler(c *fiber.Ctx) error {
// @Failure 409 {object} map[string]interface{} "Email already registered"
// @Failure 500 {object} map[string]interface{} "An unexpected error occurred"
// @Router /auth/send-verification-email [post]
func SendVerificationEmailHandler(c *fiber.Ctx) error {
func sendVerificationEmailHandler(c *fiber.Ctx) error {
userEmail := c.FormValue("email")
_, err := services.GetUserByEmail(userEmail)
if err == nil {
Expand Down Expand Up @@ -212,7 +236,7 @@ func SendVerificationEmailHandler(c *fiber.Ctx) error {
// @Failure 400 {object} map[string]interface{} "Invalid or expired token"
// @Failure 500 {object} map[string]interface{} "Error validating token"
// @Router /auth/validate-token [post]
func ValidateTokenHandler(c *fiber.Ctx) error {
func validateTokenHandler(c *fiber.Ctx) error {
token := c.FormValue("token")
email := c.FormValue("email")

Expand Down Expand Up @@ -245,7 +269,7 @@ func ValidateTokenHandler(c *fiber.Ctx) error {
// @Success 200 "Password reset request initiated successfully"
// @Failure 500 {object} map[string]interface{} "Failed to request reset password"
// @Router /auth/request-reset-password [post]
func RequestResetPasswordHandler(c *fiber.Ctx) error {
func requestResetPasswordHandler(c *fiber.Ctx) error {
email := c.FormValue("email")

// Generate the password reset token
Expand Down Expand Up @@ -286,7 +310,7 @@ func RequestResetPasswordHandler(c *fiber.Ctx) error {
// @Success 200 "Password reset successfully"
// @Failure 500 {object} map[string]interface{} "Failed to reset password"
// @Router /auth/reset-password [post]
func ResetPasswordHandler(c *fiber.Ctx) error {
func resetPasswordHandler(c *fiber.Ctx) error {
token := c.FormValue("token")
newPassword := c.FormValue("password")

Expand All @@ -297,3 +321,14 @@ func ResetPasswordHandler(c *fiber.Ctx) error {

return c.SendStatus(fiber.StatusOK)
}

func generateOAuthConfig() *oauth2.Config {
// OAuth2 Configuration
return &oauth2.Config{
ClientID: os.Getenv("G_CLIENT_ID"),
ClientSecret: os.Getenv("G_CLIENT_SECRET"),
RedirectURL: os.Getenv("G_REDIRECT"),
Scopes: []string{"https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"},
Endpoint: google.Endpoint,
}
}
46 changes: 0 additions & 46 deletions backend/handlers/chat_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,49 +123,3 @@ func GetRoomUsersHandler(c *fiber.Ctx) error {

return c.JSON(fiber.Map{"connections": connections, "total_users": len(connections)})
}

func BanUserHandler(c *fiber.Ctx) error {
// Extract markerID and userID from the path parameters
markerID := c.Params("markerID")
userID := c.Params("userID")

// assert duration is sent in the request body as JSON
var requestBody struct {
DurationInMinutes int `json:"duration"`
}
if err := c.BodyParser(&requestBody); err != nil {
requestBody = struct {
DurationInMinutes int `json:"duration"`
}{
DurationInMinutes: 5, // default 5 minutes banned
}
// return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
// "error": "Invalid request format",
// })
}

if requestBody.DurationInMinutes < 1 {
requestBody.DurationInMinutes = 5
} else if requestBody.DurationInMinutes > 15 {
requestBody.DurationInMinutes = 10 // max 10 minutes
}

// Convert duration to time.Duration
duration := time.Duration(requestBody.DurationInMinutes) * time.Minute

// Call the BanUser method on the manager instance
err := services.WsRoomManager.BanUser(markerID, userID, duration)
if err != nil {
// Log the error or handle it as needed
// log.Printf("Error banning user %s from room %s: %v", userID, markerID, err)
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "Failed to ban user",
})
}

// Return success response
return c.JSON(fiber.Map{
"message": "User successfully banned",
"time": duration,
})
}
30 changes: 22 additions & 8 deletions backend/handlers/comment_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,29 @@ package handlers

import (
"chulbong-kr/dto"
"chulbong-kr/middlewares"
"chulbong-kr/services"
"chulbong-kr/utils"
"strconv"

"github.com/gofiber/fiber/v2"
)

// PostCommentHandler creates a new comment
func PostCommentHandler(c *fiber.Ctx) error {
// RegisterCommentRoutes sets up the routes for comments handling within the application.
func RegisterCommentRoutes(api fiber.Router) {
api.Get("/comments/:markerId/comments", loadCommentsHandler)

commentGroup := api.Group("/comments")
{
commentGroup.Use(middlewares.AuthMiddleware)
commentGroup.Post("", postCommentHandler)
commentGroup.Patch("/:commentId", updateCommentHandler)
commentGroup.Delete("/:commentId", removeCommentHandler)
}
}

// postCommentHandler creates a new comment
func postCommentHandler(c *fiber.Ctx) error {
userID := c.Locals("userID").(int)
var req dto.CommentRequest
if err := c.BodyParser(&req); err != nil {
Expand All @@ -19,7 +33,7 @@ func PostCommentHandler(c *fiber.Ctx) error {

containsBadWord, _ := utils.CheckForBadWords(req.CommentText)
if containsBadWord {
return c.Status(fiber.StatusBadRequest).SendString("Comment contains inappropriate content.")
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Comment contains inappropriate content."})
}

comment, err := services.CreateComment(req.MarkerID, userID, req.CommentText)
Expand All @@ -29,7 +43,7 @@ func PostCommentHandler(c *fiber.Ctx) error {
return c.Status(fiber.StatusOK).JSON(comment)
}

func UpdateCommentHandler(c *fiber.Ctx) error {
func updateCommentHandler(c *fiber.Ctx) error {
commentID, err := strconv.Atoi(c.Params("commentId"))
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid comment ID"})
Expand All @@ -47,16 +61,16 @@ func UpdateCommentHandler(c *fiber.Ctx) error {
// Call the service function to update the comment
if err := services.UpdateComment(commentID, userID, request.CommentText); err != nil {
if err.Error() == "comment not found or not owned by user" {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "Failed to update the comment"})
}
// Handle other potential errors
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to update comment"})
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to update the comment"})
}

return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Comment updated successfully"})
}

func RemoveCommentHandler(c *fiber.Ctx) error {
func removeCommentHandler(c *fiber.Ctx) error {
commentID, err := strconv.Atoi(c.Params("commentId"))
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid comment ID"})
Expand All @@ -75,7 +89,7 @@ func RemoveCommentHandler(c *fiber.Ctx) error {
return c.Status(fiber.StatusOK).JSON(fiber.Map{"message": "Comment removed successfully"})
}

func LoadCommentsHandler(c *fiber.Ctx) error {
func loadCommentsHandler(c *fiber.Ctx) error {
var params dto.CommentLoadParams
if err := c.QueryParser(&params); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid query parameters"})
Expand Down
Loading

0 comments on commit 223ff7b

Please sign in to comment.