Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SAC-4 Create User POST #42

Merged
merged 7 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ require (
gorm.io/gorm v1.25.5
)

require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/mcnijman/go-emailaddress v1.1.1 // indirect
)

require github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect

require (
Expand Down
29 changes: 28 additions & 1 deletion backend/src/controllers/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package controllers

import (
"github.com/GenerateNU/sac/backend/src/services"

"github.com/GenerateNU/sac/backend/src/models"
"github.com/gofiber/fiber/v2"
)

Expand Down Expand Up @@ -33,3 +33,30 @@ func (u *UserController) GetAllUsers(c *fiber.Ctx) error {

return c.Status(fiber.StatusOK).JSON(users)
}

// Create User godoc
//
// @Summary Creates a User
// @Description Creates a user
// @ID create-user
// @Tags user
// @Accept json
// @Produce json
// @Success 201 {object} models.User
// @Failure 400 {string} string "failed to create user"
// @Failure 500 {string} string "internal server error"
// @Router /api/v1/users/ [post]
func (u *UserController) CreateUser(c *fiber.Ctx) error {
var userBody models.CreateUserRequestBody

if err := c.BodyParser(&userBody); err != nil {
return fiber.NewError(fiber.StatusBadRequest, "failed to process the request")
}

user, err := u.userService.CreateUser(userBody)
if err != nil {
return err
}

return c.Status(fiber.StatusCreated).JSON(user)
}
11 changes: 11 additions & 0 deletions backend/src/models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,14 @@ type User struct {
RSVP []Event `gorm:"many2many:user_event_rsvps;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-" validate:"-"`
Waitlist []Event `gorm:"many2many:user_event_waitlists;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"-" validate:"-"`
}

// TODO: Should we change error message for missing required fields?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error messages given by the validators seemed kinda wordy and unreadable. For example if a required field like College is missing, the error message is "Key: 'CreateUserRequestBody.College' Error:Field validation for 'College' failed on the 'required' tag" and we feel like this can be better written. Thoughts?

type CreateUserRequestBody struct {
NUID string `json:"nuid" validate:"required,number,len=9"`
FirstName string `json:"first_name" validate:"required,max=255"`
LastName string `json:"last_name" validate:"required,max=255"`
Email string `json:"email" validate:"required,neu_email"`
Password string `json:"password" validate:"required,password"`
College string `json:"college" validate:"required,oneof=CAMD DMSB KCCS CE BCHS SL CPS CS CSSH"`
Year uint `json:"year" validate:"required,min=1,max=6"`
}
1 change: 1 addition & 0 deletions backend/src/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func userRoutes(router fiber.Router, userService services.UserServiceInterface)
users := router.Group("/users")

users.Get("/", userController.GetAllUsers)
users.Post("/", userController.CreateUser)
}

func categoryRoutes(router fiber.Router, categoryService services.CategoryServiceInterface) {
Expand Down
38 changes: 37 additions & 1 deletion backend/src/services/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@ package services
import (
"github.com/GenerateNU/sac/backend/src/models"
"github.com/GenerateNU/sac/backend/src/transactions"

"github.com/GenerateNU/sac/backend/src/utilities"
"github.com/go-playground/validator/v10"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)

type UserServiceInterface interface {
GetAllUsers() ([]models.User, error)
CreateUser(userBody models.CreateUserRequestBody) (*models.User, error)
}

type UserService struct {
Expand All @@ -19,3 +22,36 @@ type UserService struct {
func (u *UserService) GetAllUsers() ([]models.User, error) {
return transactions.GetAllUsers(u.DB)
}

// temporary
func createUserFromRequestBody(userBody models.CreateUserRequestBody) (models.User, error) {
// TL DAVID -- some validation still needs to be done but depends on design

validate := validator.New()
validate.RegisterValidation("neu_email", utilities.ValidateEmail)
validate.RegisterValidation("password", utilities.ValidatePassword)
if err := validate.Struct(userBody); err != nil {
return models.User{}, fiber.NewError(fiber.StatusBadRequest, err.Error())
}

var user models.User
user.NUID = userBody.NUID
user.FirstName = userBody.FirstName
user.LastName = userBody.LastName
user.Email = userBody.Email
// TODO: hash
user.PasswordHash = userBody.Password
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use auth.ComputePasswordHash(userBody.Password) here

user.College = models.College(userBody.College)
user.Year = models.Year(userBody.Year)

return user, nil
}

func (u *UserService) CreateUser(userBody models.CreateUserRequestBody) (*models.User, error) {
user, err := createUserFromRequestBody(userBody)
if err != nil {
return nil, err
}

return transactions.CreateUser(u.DB, &user)
}
42 changes: 41 additions & 1 deletion backend/src/transactions/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package transactions

import (
"github.com/GenerateNU/sac/backend/src/models"

"errors"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
)
Expand All @@ -16,3 +16,43 @@ func GetAllUsers(db *gorm.DB) ([]models.User, error) {

return users, nil
}

func GetUser(db *gorm.DB, id uint) (*models.User, error) {
var user models.User
if err := db.First(&user, id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusNotFound, err.Error())
}

return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}

return &user, nil
}

func CreateUser(db *gorm.DB, user *models.User) (*models.User, error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need these separate queries or can we allow the DB unique constraints to handle this for us?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just didn't want to throw 500 errors for things related to uniqueness, imo that's a 400


var existing models.User

if err := db.Where("email = ?", user.Email).First(&existing).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusInternalServerError, "failed to create user")
}
} else {
return nil, fiber.NewError(fiber.StatusBadRequest, "user with that email already exists")
}

if err := db.Where("nuid = ?", user.NUID).First(&existing).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fiber.NewError(fiber.StatusInternalServerError, "failed to create user")
}
} else {
return nil, fiber.NewError(fiber.StatusBadRequest, "user with that nuid already exists")
}

if err := db.Create(user).Error; err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, "failed to create user")
}

return user, nil
}
19 changes: 19 additions & 0 deletions backend/src/utilities/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,27 @@ package utilities

import (
"github.com/go-playground/validator/v10"
"github.com/mcnijman/go-emailaddress"
)

func ValidateEmail(fl validator.FieldLevel) bool {
email, err := emailaddress.Parse(fl.Field().String())
if err != nil {
return false
}

if email.Domain != "northeastern.edu" {
return false
}

return true
}

func ValidatePassword(fl validator.FieldLevel) bool {
// TODO: we need to think of validation rules
return len(fl.Field().String()) >= 6
}

// Validate the data sent to the server if the data is invalid, return an error otherwise, return nil
func ValidateData(model interface{}) error {
validate := validator.New(validator.WithRequiredStructEnabled())
Expand Down
Loading
Loading