Skip to content

Commit

Permalink
Merge branch 'main' into minor-fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
alderwhiteford authored Mar 5, 2024
2 parents 689b7cf + 3f4a802 commit 4b7c74e
Show file tree
Hide file tree
Showing 24 changed files with 450 additions and 446 deletions.
6 changes: 3 additions & 3 deletions backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ go 1.22.0

require (
github.com/garrettladley/mattress v0.3.2
github.com/go-playground/validator/v10 v10.18.0
github.com/go-playground/validator/v10 v10.19.0
github.com/goccy/go-json v0.10.2
github.com/gofiber/fiber/v2 v2.52.1
github.com/gofiber/fiber/v2 v2.52.2
github.com/gofiber/swagger v1.0.0
github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/google/uuid v1.6.0
Expand All @@ -16,7 +16,7 @@ require (
github.com/mitchellh/mapstructure v1.5.0
github.com/spf13/viper v1.18.2
github.com/swaggo/swag v1.16.3
golang.org/x/crypto v0.19.0
golang.org/x/crypto v0.20.0
golang.org/x/text v0.14.0
gorm.io/driver/postgres v1.5.6
gorm.io/gorm v1.25.7
Expand Down
12 changes: 6 additions & 6 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.18.0 h1:BvolUXjp4zuvkZ5YN5t7ebzbhlUtPsPm2S9NAZ5nl9U=
github.com/go-playground/validator/v10 v10.18.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/go-playground/validator/v10 v10.19.0 h1:ol+5Fu+cSq9JD7SoSqe04GMI92cbn0+wvQ3bZ8b/AU4=
github.com/go-playground/validator/v10 v10.19.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/gofiber/fiber/v2 v2.52.1 h1:1RoU2NS+b98o1L77sdl5mboGPiW+0Ypsi5oLmcYlgHI=
github.com/gofiber/fiber/v2 v2.52.1/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
github.com/gofiber/fiber/v2 v2.52.2 h1:b0rYH6b06Df+4NyrbdptQL8ifuxw/Tf2DgfkZkDaxEo=
github.com/gofiber/fiber/v2 v2.52.2/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
github.com/gofiber/swagger v1.0.0 h1:BzUzDS9ZT6fDUa692kxmfOjc1DZiloLiPK/W5z1H1tc=
github.com/gofiber/swagger v1.0.0/go.mod h1:QrYNF1Yrc7ggGK6ATsJ6yfH/8Zi5bu9lA7wB8TmCecg=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
Expand Down Expand Up @@ -148,8 +148,8 @@ go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.20.0 h1:jmAMJJZXr5KiCw05dfYK9QnqaqKLYXijU23lsEdcQqg=
golang.org/x/crypto v0.20.0/go.mod h1:Xwo95rrVNIoSMx9wa1JroENMToLWn3RNVrTBpLHgZPQ=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
Expand Down
4 changes: 4 additions & 0 deletions backend/src/errors/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ package errors
import "github.com/gofiber/fiber/v2"

var (
FailedToValidateAtLeastOneField = Error{
StatusCode: fiber.StatusBadRequest,
Message: "failed to validate at least one field",
}
FailedToParseRequestBody = Error{
StatusCode: fiber.StatusBadRequest,
Message: "failed to parse request body",
Expand Down
37 changes: 26 additions & 11 deletions backend/src/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package main
import (
"flag"
"fmt"
"net"
"os"
"path/filepath"

"github.com/GenerateNU/sac/backend/src/config"
Expand All @@ -11,13 +13,21 @@ import (
"github.com/GenerateNU/sac/backend/src/server"
)

// @title SAC API
// @version 1.0
// @description Backend Server for SAC App
// @contact.name David Oduneye and Garrett Ladley
// @contact.email [email protected]
// @host 127.0.0.1:8080
// @BasePath /api/v1
func CheckServerRunning(host string, port uint16) error {
address := fmt.Sprintf("%s:%d", host, port)
conn, err := net.Dial("tcp", address)
if err != nil {
return err
}
defer conn.Close()
return nil
}

func Exit(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format, a...)
os.Exit(0)
}

func main() {
onlyMigrate := flag.Bool("only-migrate", false, "Specify if you want to only perform the database migration")
configPath := flag.String("config", filepath.Join("..", "..", "config"), "Specify the path to the config directory")
Expand All @@ -27,12 +37,17 @@ func main() {

config, err := config.GetConfiguration(*configPath, *useDevDotEnv)
if err != nil {
panic(fmt.Sprintf("Error getting configuration: %s", err.Error()))
Exit("Error getting configuration: %s", err.Error())
}

err = CheckServerRunning(config.Application.Host, config.Application.Port)
if err == nil {
Exit("A server is already running on %s:%d.\n", config.Application.Host, config.Application.Port)
}

db, err := database.ConfigureDB(*config)
if err != nil {
panic(fmt.Sprintf("Error configuring database: %s", err.Error()))
Exit("Error migrating database: %s", err.Error())
}

if *onlyMigrate {
Expand All @@ -41,13 +56,13 @@ func main() {

err = database.ConnPooling(db)
if err != nil {
panic(fmt.Sprintf("Error connecting to database: %s", err.Error()))
Exit("Error with connection pooling: %s", err.Error())
}

app := server.Init(db, *config)

err = app.Listen(fmt.Sprintf("%s:%d", config.Application.Host, config.Application.Port))
if err != nil {
panic(fmt.Sprintf("Error starting server: %s", err.Error()))
Exit("Error starting server: %s", err.Error())
}
}
2 changes: 0 additions & 2 deletions backend/src/models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,8 @@ type CreateUserRequestBody struct {
}

type UpdateUserRequestBody struct {
NUID string `json:"nuid" validate:"omitempty,numeric,len=9"`
FirstName string `json:"first_name" validate:"omitempty,max=255"`
LastName string `json:"last_name" validate:"omitempty,max=255"`
Email string `json:"email" validate:"omitempty,email,neu_email,max=255"`
College College `json:"college" validate:"omitempty,oneof=CAMD DMSB KCCS CE BCHS SL CPS CS CSSH"`
Year Year `json:"year" validate:"omitempty,min=1,max=6"`
}
Expand Down
1 change: 0 additions & 1 deletion backend/src/services/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ func (a *AuthService) UpdatePassword(id string, passwordBody models.UpdatePasswo
return idErr
}

// TODO: Validate password
if err := a.Validate.Struct(passwordBody); err != nil {
return &errors.FailedToValidateUpdatePasswordBody
}
Expand Down
4 changes: 4 additions & 0 deletions backend/src/services/club.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ func (c *ClubService) UpdateClub(id string, clubBody models.UpdateClubRequestBod
return nil, idErr
}

if utilities.AtLeastOne(clubBody, models.UpdateClubRequestBody{}) {
return nil, &errors.FailedToValidateClub
}

if err := c.Validate.Struct(clubBody); err != nil {
return nil, &errors.FailedToValidateClub
}
Expand Down
4 changes: 4 additions & 0 deletions backend/src/services/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ func (e *EventService) UpdateEvent(id string, eventBody models.UpdateEventReques
return nil, idErr
}

if utilities.AtLeastOne(eventBody, models.UpdateEventRequestBody{}) {
return nil, &errors.FailedToValidateTag
}

if err := e.Validate.Struct(eventBody); err != nil {
return nil, &errors.FailedToValidateEvent
}
Expand Down
4 changes: 4 additions & 0 deletions backend/src/services/tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ func (t *TagService) UpdateTag(tagID string, tagBody models.UpdateTagRequestBody
return nil, idErr
}

if utilities.AtLeastOne(tagBody, models.UpdateTagRequestBody{}) {
return nil, &errors.FailedToValidateTag
}

if err := t.Validate.Struct(tagBody); err != nil {
return nil, &errors.FailedToValidateTag
}
Expand Down
4 changes: 4 additions & 0 deletions backend/src/services/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,10 @@ func (u *UserService) UpdateUser(id string, userBody models.UpdateUserRequestBod
return nil, idErr
}

if utilities.AtLeastOne(userBody, models.UpdateUserRequestBody{}) {
return nil, &errors.FailedToValidateUser
}

if err := u.Validate.Struct(userBody); err != nil {
return nil, &errors.FailedToValidateUser
}
Expand Down
5 changes: 5 additions & 0 deletions backend/src/utilities/validator.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package utilities

import (
"reflect"
"regexp"
"strconv"

Expand Down Expand Up @@ -41,6 +42,10 @@ func RegisterCustomValidators() (*validator.Validate, error) {
return validate, nil
}

func AtLeastOne[Model any](body Model, model Model) bool {
return reflect.DeepEqual(body, model)
}

func validateEmail(fl validator.FieldLevel) bool {
email, err := emailaddress.Parse(fl.Field().String())
if err != nil {
Expand Down
47 changes: 47 additions & 0 deletions cli/commands/backend.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package commands

import (
"fmt"
"os"
"os/exec"

_ "github.com/lib/pq"
"github.com/urfave/cli/v2"
)

func BackendCommand() *cli.Command {
command := &cli.Command{
Name: "backend",
Usage: "Starts the backend server",
Aliases: []string{"be"},
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "use-dev-dot-env",
Usage: "Use the .env file in the backend directory",
Aliases: []string{"d"},
},
},
Action: func(c *cli.Context) error {
err := RunBackend()
if err != nil {
return cli.Exit(err.Error(), 1)
}

return nil
},
}

return command
}

func RunBackend() error {
cmd := exec.Command("go", "run", "main.go")
cmd.Dir = BACKEND_DIR
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
return fmt.Errorf("error starting backend: %w", err)
}
return nil
}
66 changes: 0 additions & 66 deletions cli/commands/be.go

This file was deleted.

20 changes: 14 additions & 6 deletions cli/commands/clean_tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,16 @@ func CleanTestDBs() error {
return fmt.Errorf("failed to get current user: %w", err)
}

rows, err := db.Query("SELECT datname FROM pg_database WHERE datistemplate = false AND datname != 'postgres' AND datname != $1 AND datname != $2 AND datname LIKE 'sac_test_%';", currentUser.Username, CONFIG.Database.DatabaseName)
query := "SELECT datname FROM pg_database WHERE datistemplate = false AND datname != 'postgres' AND datname != $1 AND datname != $2 AND datname LIKE 'sac_test_%';"
rows, err := db.Query(query, currentUser.Username, CONFIG.Database.DatabaseName)
if err != nil {
return err
}

defer rows.Close()

var wg sync.WaitGroup
var dropped, failed int

for rows.Next() {
var dbName string
Expand All @@ -71,17 +73,23 @@ func CleanTestDBs() error {

fmt.Printf("Dropping database %s\n", dbName)

if _, err := db.Exec(fmt.Sprintf("DROP DATABASE %s", dbName)); err != nil {
_, err := db.Exec(fmt.Sprintf("DROP DATABASE %s", dbName))
if err != nil {
fmt.Printf("Failed to drop database %s: %v\n", dbName, err)
failed++
} else {
dropped++
}
}(dbName)
}

if err := rows.Err(); err != nil {
return err
}

wg.Wait()

fmt.Printf("\nSummary:\n - Databases dropped: %d\n - Databases failed to drop: %d\n", dropped, failed)

if failed > 0 {
return fmt.Errorf("failed to drop %d database(s)", failed)
}

return nil
}
2 changes: 1 addition & 1 deletion cli/commands/fe.go → cli/commands/frontend.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/urfave/cli/v2"
)

func RunFrontendCommand() *cli.Command {
func FrontendCommand() *cli.Command {
command := cli.Command{
Name: "fe",
Usage: "Run the frontend",
Expand Down
2 changes: 1 addition & 1 deletion cli/commands/lint.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func LintFrontend(target string, fix bool) error {
func LintBackend() error {
fmt.Println("Linting backend")

cmd := exec.Command("golangci-lint", "run", "--fix")
cmd := exec.Command("go", "vet", "./...")
cmd.Dir = BACKEND_DIR

err := cmd.Run()
Expand Down
Loading

0 comments on commit 4b7c74e

Please sign in to comment.