Skip to content

Commit

Permalink
[FIX] Check if user exists before registering
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelomagina committed Jun 6, 2019
1 parent 277682d commit b1316fa
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 16 deletions.
42 changes: 28 additions & 14 deletions owasp-top10-2017-apps/a5/ecommerce-api/app/db/queries.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package db

import (
"errors"

"github.com/globocom/secDevLabs/owasp-top10-2017-apps/a5/ecommerce-api/app/pass"
"github.com/globocom/secDevLabs/owasp-top10-2017-apps/a5/ecommerce-api/app/types"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)

Expand All @@ -24,23 +27,34 @@ func GetUserData(mapParams map[string]interface{}) (types.UserData, error) {

// RegisterUser regisiter into MongoDB a new user and returns an error.
func RegisterUser(userData types.UserData) error {
session, err := Connect()
if err != nil {
return err
}

userData.HashedPassword, err = pass.BcrpytPassword(userData.RawPassword)
userDataQuery := map[string]interface{}{"username": userData.Username}
_, err := GetUserData(userDataQuery)
if err != nil {
return err
}
if err == mgo.ErrNotFound {
// could not find this user in MongoDB (or MongoDB err connection)
session, err := Connect()
if err != nil {
return err
}

userData.HashedPassword, err = pass.BcrpytPassword(userData.RawPassword)
if err != nil {
return err
}

newUserData := bson.M{
"username": userData.Username,
"hashedPassword": userData.HashedPassword,
"userID": userData.UserID,
"ticket": userData.Ticket,
newUserData := bson.M{
"username": userData.Username,
"hashedPassword": userData.HashedPassword,
"userID": userData.UserID,
"ticket": userData.Ticket,
}
err = session.Insert(newUserData, UserCollection)
return err

}
return err
}
err = session.Insert(newUserData, UserCollection)
return err
return errors.New("User already registered.")

}
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,10 @@ func RegisterUser(c echo.Context) error {
err = db.RegisterUser(userData)
if err != nil {
// could not register this user into MongoDB (or MongoDB err connection)
return c.JSON(http.StatusBadRequest, map[string]string{"result": "error", "details": "Error user data2."})
errorString := fmt.Sprintf("%s", err)
return c.JSON(http.StatusBadRequest, map[string]string{"result": "error", "details": errorString})

}

return c.String(http.StatusOK, "Register: success!\n")
return c.String(http.StatusCreated, "Register: success!\n")
}

0 comments on commit b1316fa

Please sign in to comment.