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

Revert "feat: add fetch customers list" #77

Merged
merged 1 commit into from
Jul 21, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,3 @@ _ignore/
app.env
tmp/
.idea/

app.env
20 changes: 9 additions & 11 deletions internal/models/seed/seed.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,10 @@ func SeedDatabase(db *gorm.DB) {

Userid1 := utility.GenerateUUID()
user1 := models.User{
ID: Userid1,
Name: "John Doe",
Email: "[email protected]",
ID: Userid1,
Name: "John Doe",
Email: "[email protected]",
Password: utility.RandomString(20),
Role: "customer",
Profile: models.Profile{
ID: utility.GenerateUUID(),
FirstName: "John",
Expand All @@ -35,11 +34,10 @@ func SeedDatabase(db *gorm.DB) {

Userid2 := utility.GenerateUUID()
user2 := models.User{
ID: Userid2,
Name: "Jane Doe",
ID: Userid2,
Name: "Jane Doe",
Password: utility.RandomString(20),
Email: "[email protected]",
Role: "customer",
Email: "[email protected]",
Profile: models.Profile{
ID: utility.GenerateUUID(),
FirstName: "Jane",
Expand All @@ -54,9 +52,9 @@ func SeedDatabase(db *gorm.DB) {
}

organisations := []models.Organisation{
{ID: utility.GenerateUUID(), Name: "Org1", Email: fmt.Sprintf(utility.RandomString(4) + "@email.com"), Description: "Description1", OwnerID: Userid1},
{ID: utility.GenerateUUID(), Name: "Org2", Email: fmt.Sprintf(utility.RandomString(4) + "@email.com"), Description: "Description2", OwnerID: Userid1},
{ID: utility.GenerateUUID(), Name: "Org3", Email: fmt.Sprintf(utility.RandomString(4) + "@email.com"), Description: "Description3", OwnerID: Userid2},
{ID: utility.GenerateUUID(), Name: "Org1", Email: fmt.Sprintf(utility.RandomString(4)+"@email.com"),Description: "Description1", OwnerID: Userid1},
{ID: utility.GenerateUUID(), Name: "Org2", Email: fmt.Sprintf(utility.RandomString(4)+"@email.com"),Description: "Description2", OwnerID: Userid1},
{ID: utility.GenerateUUID(), Name: "Org3", Email: fmt.Sprintf(utility.RandomString(4)+"@email.com"),Description: "Description3", OwnerID: Userid2},
}

var existingUser models.User
Expand Down
12 changes: 0 additions & 12 deletions internal/models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ type User struct {
Name string `gorm:"column:name; type:varchar(255)" json:"name"`
Email string `gorm:"column:email; type:varchar(255)" json:"email"`
Password string `gorm:"column:password; type:text; not null" json:"-"`
Role string `gorm:"column:role; type:varchar(255)" json:"role"`
IsActive bool `gorm:"column:is_active; type:boolean" json:"is_active"`
Profile Profile `gorm:"foreignKey:Userid;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;" json:"profile"`
Organisations []Organisation `gorm:"many2many:user_organisations;;constraint:OnUpdate:CASCADE,OnDelete:SET NULL;" json:"organisations" ` // many to many relationship
Products []Product `gorm:"foreignKey:OwnerID" json:"products"`
Expand All @@ -29,7 +27,6 @@ type CreateUserRequestModel struct {
LastName string `json:"last_name" validate:"required"`
UserName string `json:"username" validate:"required"`
PhoneNumber string `json:"phone_number"`
Role string `json:"role"`
}

type LoginRequestModel struct {
Expand Down Expand Up @@ -68,12 +65,3 @@ func (u *User) CreateUser(db *gorm.DB) error {

return nil
}

func (u *User) GetAllCustomers(db *gorm.DB) ([]User, error) {
var users []User
if err := db.Preload("Profile").Preload("Products").Preload("Organisations").Where("role = ?", "customer").Find(&users).Error; err != nil {
return users, err
}

return users, nil
}
14 changes: 0 additions & 14 deletions pkg/controller/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,17 +92,3 @@ func (base *Controller) LoginUser(c *gin.Context) {
rd := utility.BuildSuccessResponse(http.StatusOK, "user login successfully", respData)
c.JSON(http.StatusOK, rd)
}

func (base *Controller) GetAllCustomers(c *gin.Context) {
respData, err := user.GetAllCustomers(base.Db.Postgresql)
if err != nil {
rd := utility.BuildErrorResponse(400, "error", err.Error(), err, nil)
c.JSON(http.StatusBadRequest, rd)
return
}

base.Logger.Info("All Customers fetched successfully")

rd := utility.BuildSuccessResponse(http.StatusOK, "All Customers fetched successfully", respData)
c.JSON(http.StatusOK, rd)
}
23 changes: 1 addition & 22 deletions pkg/middleware/authorize.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/hngprojects/hng_boilerplate_golang_web/utility"
)

func Authorize(requiredRoles ...string) gin.HandlerFunc {
func Authorize() gin.HandlerFunc {
return func(c *gin.Context) {
var tokenStr string
bearerToken := c.GetHeader("Authorization")
Expand Down Expand Up @@ -49,27 +49,6 @@ func Authorize(requiredRoles ...string) gin.HandlerFunc {
return
}

// Check user role
userRole, ok := claims["user_role"].(string)
if !ok {
c.AbortWithStatusJSON(http.StatusForbidden, utility.BuildErrorResponse(http.StatusForbidden, "error", "Forbidden", "Unauthorized", nil))
return
}

// Check if user role is in the list of required roles
roleAuthorized := false
for _, role := range requiredRoles {
if userRole == role {
roleAuthorized = true
break
}
}

if !roleAuthorized {
c.AbortWithStatusJSON(http.StatusForbidden, utility.BuildErrorResponse(http.StatusForbidden, "error", "Forbidden", "Unauthorized", nil))
return
}

// store user claims in Context
// for accesiblity in controller

Expand Down
2 changes: 0 additions & 2 deletions pkg/middleware/jwttoken.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,10 @@ func CreateToken(user models.User) (string, time.Time, error) {

//create token
userid := user.ID
userRole := user.Role
userClaims := jwt.MapClaims{}

// specify user claims
userClaims["user_id"] = userid
userClaims["user_role"] = userRole
userClaims["exp"] = UnixExp
userClaims["authorised"] = true

Expand Down
2 changes: 1 addition & 1 deletion pkg/repository/storage/postgresql/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func connectToDb(host, user, password, dbname, port, sslmode, timezone string, l
port = detectedPort
}

dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v sslmode=%v TimeZone=%v prefer_simple_protocol=true", host, user, password, dbname, port, sslmode, timezone)
dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v sslmode=%v TimeZone=%v", host, user, password, dbname, port, sslmode, timezone)

newLogger := lg.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
Expand Down
2 changes: 1 addition & 1 deletion pkg/router/organisation.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func Organisation(r *gin.Engine, ApiVersion string, validator *validator.Validat
extReq := request.ExternalRequest{Logger: logger, Test: false}
organisation := organisation.Controller{Db: db, Validator: validator, Logger: logger, ExtReq: extReq}

organisationUrl := r.Group(fmt.Sprintf("%v", ApiVersion), middleware.Authorize("customer", "admin"))
organisationUrl := r.Group(fmt.Sprintf("%v", ApiVersion), middleware.Authorize())
{
organisationUrl.POST("/organisations", organisation.CreateOrganisation)

Expand Down
2 changes: 0 additions & 2 deletions pkg/router/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (

"github.com/hngprojects/hng_boilerplate_golang_web/external/request"
"github.com/hngprojects/hng_boilerplate_golang_web/pkg/controller/user"
"github.com/hngprojects/hng_boilerplate_golang_web/pkg/middleware"
"github.com/hngprojects/hng_boilerplate_golang_web/pkg/repository/storage"
"github.com/hngprojects/hng_boilerplate_golang_web/utility"
)
Expand All @@ -21,7 +20,6 @@ func User(r *gin.Engine, ApiVersion string, validator *validator.Validate, db *s
{
userUrl.POST("/users/signup", user.CreateUser)
userUrl.POST("/users/login", user.LoginUser)
userUrl.GET("/customers", middleware.Authorize("admin"), user.GetAllCustomers)
}
return r
}
19 changes: 0 additions & 19 deletions services/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ func CreateUser(req models.CreateUserRequestModel, db *gorm.DB) (gin.H, int, err
username = strings.ToLower(req.UserName)
phoneNumber = req.PhoneNumber
password = req.Password
role = req.Role
responseData gin.H
)

Expand All @@ -80,16 +79,11 @@ func CreateUser(req models.CreateUserRequestModel, db *gorm.DB) (gin.H, int, err
return nil, http.StatusInternalServerError, err
}

if role == "" {
role = "customer"
}

user := models.User{
ID: utility.GenerateUUID(),
Name: username,
Email: email,
Password: password,
Role: role,
Profile: models.Profile{
ID: utility.GenerateUUID(),
FirstName: firstName,
Expand All @@ -114,7 +108,6 @@ func CreateUser(req models.CreateUserRequestModel, db *gorm.DB) (gin.H, int, err
"first_name": user.Profile.FirstName,
"last_name": user.Profile.LastName,
"phone": user.Profile.Phone,
"role": user.Role,
"expires_in": expiry,
"access_token": token,
}
Expand Down Expand Up @@ -156,21 +149,9 @@ func LoginUser(req models.LoginRequestModel, db *gorm.DB) (gin.H, int, error) {
"first_name": userData.Profile.FirstName,
"last_name": userData.Profile.LastName,
"phone": userData.Profile.Phone,
"role": userData.Role,
"expires_in": expiry,
"access_token": token,
}

return responseData, http.StatusCreated, nil
}

func GetAllCustomers(db *gorm.DB) ([]models.User, error) {
var users models.User

userResp, err := users.GetAllCustomers(db)
if err != nil {
return userResp, err
}

return userResp, err
}
Loading