Skip to content

Commit

Permalink
added bcrypt but need improvement
Browse files Browse the repository at this point in the history
Signed-off-by: PratikforCoding <kotalpratik@gmail.com>
  • Loading branch information
PratikforCoding committed Sep 20, 2023
1 parent aa8754f commit bfad037
Show file tree
Hide file tree
Showing 9 changed files with 173 additions and 19 deletions.
18 changes: 18 additions & 0 deletions auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package auth

import (

"golang.org/x/crypto/bcrypt"
)

func HashedPassword(password string) (string, error) {
dat, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(dat), nil
}

func CheckPasswordHash(password, hash string) error {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
}
74 changes: 66 additions & 8 deletions controllers/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,19 @@ import (
"fmt"
"log"

"github.com/PratikforCoding/BusoFact.git/auth"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)

type APIConfig struct {
Collection *mongo.Collection
BusCollection *mongo.Collection
UserCollection *mongo.Collection
}

func NewAPIConfig(col *mongo.Collection) *APIConfig {
return &APIConfig{Collection: col}
func NewAPIConfig(busCol, usrCol *mongo.Collection) *APIConfig {
return &APIConfig{BusCollection: busCol, UserCollection: usrCol}
}

func (apiCfg *APIConfig)getBuses(source string, destination string) []primitive.M {
Expand All @@ -39,7 +41,7 @@ func (apiCfg *APIConfig)getBuses(source string, destination string) []primitive.
},
}

cursor, err := apiCfg.Collection.Find(context.Background(), filter)
cursor, err := apiCfg.BusCollection.Find(context.Background(), filter)
if err != nil {
log.Fatal(err)
}
Expand All @@ -66,7 +68,7 @@ func (apiCfg *APIConfig)addBuses(name, stopageName string) (bson.M, error) {
{"stopageNumber": 1, "stopage": stopageName},
},
}
inserted, err := apiCfg.Collection.InsertOne(context.Background(), bus)
inserted, err := apiCfg.BusCollection.InsertOne(context.Background(), bus)

if err != nil {
log.Fatal(err)
Expand All @@ -75,7 +77,7 @@ func (apiCfg *APIConfig)addBuses(name, stopageName string) (bson.M, error) {
updatedBus, err := apiCfg.getBusByName(name)
if err != nil {
log.Println(err)
return bus, err
return nil, err
}
return updatedBus, nil
}
Expand All @@ -96,7 +98,7 @@ func (apiCfg *APIConfig)addBuses(name, stopageName string) (bson.M, error) {
update := bson.M{
"$push": bson.M{"stopages": newStopage},
}
result, err := apiCfg.Collection.UpdateOne(context.TODO(), filter, update)
result, err := apiCfg.BusCollection.UpdateOne(context.TODO(), filter, update)
if err != nil {
log.Fatal(err)
}
Expand All @@ -116,7 +118,7 @@ func (apiCfg *APIConfig)addBuses(name, stopageName string) (bson.M, error) {
func (apiCfg *APIConfig)getBusByName(name string) (bson.M, error) {
filter := bson.M{"name": name}
var bus bson.M
err := apiCfg.Collection.FindOne(context.TODO(), filter).Decode(&bus)
err := apiCfg.BusCollection.FindOne(context.TODO(), filter).Decode(&bus)
if err != nil {
if err == mongo.ErrNoDocuments {
fmt.Println("Bus not found")
Expand All @@ -129,3 +131,59 @@ func (apiCfg *APIConfig)getBusByName(name string) (bson.M, error) {
return bus, nil
}

func (apiCfg *APIConfig)createUser(email, password string) (bson.M, error) {
foundUser, err := apiCfg.getUser(email)
if err != nil {
hash, err := auth.HashedPassword(password)
if err != nil {
return nil, err
}
user := bson.M{
"email": email,
"password": hash,
}

inserted, err := apiCfg.UserCollection.InsertOne(context.Background(), user)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted user id:", inserted.InsertedID)
createdUser, err := apiCfg.getUser(email)
if err != nil {
log.Println(err)
return nil, err
}
return createdUser, nil
}
return foundUser, errors.New("user already exists")
}

func (apiCfg *APIConfig)userLogin(email, password string) (bson.M, error) {
user, err := apiCfg.getUser(email)
if err != nil {
return nil, errors.New("user doesn't exist")
}
userHash := user["password"].(string)
err = auth.CheckPasswordHash(password, userHash)
if err != nil {
return nil, errors.New("wrong password")
}
return user, nil
}

func (apiCfg *APIConfig)getUser(email string) (bson.M, error) {
filter := bson.M{"email":email}
var user bson.M
err := apiCfg.UserCollection.FindOne(context.TODO(), filter).Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
fmt.Println("User not found")
return nil , errors.New("user not found")
} else {
log.Fatal(err)
}
}

return user, nil
}

65 changes: 64 additions & 1 deletion controllers/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"strings"

reply "github.com/PratikforCoding/BusoFact.git/json"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)

func (apiCfg *APIConfig)HandlerGetBuses(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -67,4 +69,65 @@ func (apiCfg *APIConfig)HandlerGetBusByName(w http.ResponseWriter, r *http.Reque
return
}
reply.RespondWithJson(w, http.StatusFound, foundBus)
}
}

func (apiCfg *APIConfig)HandlerCreateAccount(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Email string `json:"email"`
Password string `json:"password"`
}

decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(&params)
if err != nil {
reply.RespondWtihError(w, http.StatusInternalServerError, "Couldn,t decode parameters")
return
}

user, err := apiCfg.createUser(params.Email, params.Password)
if err != nil {
reply.RespondWtihError(w, http.StatusConflict, "User already exists")
return
}
idStr := user["_id"].(primitive.ObjectID).Hex()
retUser := bson.M {
"email": user["email"].(string),
"id": idStr,
}
reply.RespondWithJson(w, http.StatusCreated, retUser)
}

func (apiCfg *APIConfig)HandlerLogin(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Email string `json:"email"`
Password string `json:"password"`
}

decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(&params)
if err != nil {
reply.RespondWtihError(w, http.StatusInternalServerError, "Couldn't decode parameters")
return
}

user, err := apiCfg.userLogin(params.Email, params.Password)
if err != nil {
errorMsg := "User authentication failed"
if err.Error() == "user doesn't exist" {
errorMsg = "User doesn't exist"
} else if err.Error() == "wrong password" {
errorMsg = "Wrong password"
}
reply.RespondWtihError(w, http.StatusNotFound, errorMsg)
return
}
idStr := user["_id"].(primitive.ObjectID).Hex()
retUser := bson.M {
"email": user["email"].(string),
"id": idStr,
}
reply.RespondWithJson(w, http.StatusOK, retUser)
}

18 changes: 12 additions & 6 deletions database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,33 @@ import (
)

const dbName = "businfo"
const colName = "buses"
const busColName = "buses"
const usrColName = "users"

var busCollection *mongo.Collection
var usrCollection *mongo.Collection

var collection *mongo.Collection

var client *mongo.Client

func CreateDB(mongoUri string) (*mongo.Collection, error) {
func CreateDB(mongoUri string) (*mongo.Collection, *mongo.Collection, error) {
clientOption := options.Client().ApplyURI(mongoUri)
var err error
client, err = mongo.Connect(context.TODO(), clientOption)
if err != nil {
log.Fatal(err)
return nil, err
return nil, nil, err
}
fmt.Println("MongoDB connection success")
collection = client.Database(dbName).Collection(colName)
busCollection = client.Database(dbName).Collection(busColName)
usrCollection = client.Database(dbName).Collection(usrColName)
fmt.Println("Collection instance is ready")

return collection, nil
return busCollection, usrCollection, nil
}



func CloseDB() {
if client != nil {
err := client.Disconnect(context.TODO())
Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ require (
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
go.mongodb.org/mongo-driver v1.12.1 // indirect
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
golang.org/x/crypto v0.13.0 // indirect
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect
golang.org/x/text v0.7.0 // indirect
golang.org/x/text v0.13.0 // indirect
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d h1:sK3txAijHtOK88l68nt020reeT1ZdKLIYetKl95FzVY=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
Expand All @@ -48,6 +50,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
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.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
Expand Down
4 changes: 2 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ func main() {

mongouri := os.Getenv("connectlink")

col, err := database.CreateDB(mongouri)
busCol, usrCol, err := database.CreateDB(mongouri)
if err != nil {
log.Fatal("Didn't create connection to mongodb")
}
defer database.CloseDB()

apicfg := controller.NewAPIConfig(col)
apicfg := controller.NewAPIConfig(busCol, usrCol)

fmt.Println("MongoDB API")
r := router.Router(apicfg)
Expand Down
Binary file modified out
Binary file not shown.
5 changes: 5 additions & 0 deletions router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,17 @@ import (
)
func Router(apiCfg *controller.APIConfig) *chi.Mux {
router := chi.NewRouter()
userRouter := chi.NewRouter()

router.Get("/getbuses", apiCfg.HandlerGetBuses)
router.Get("/getbusbyname", apiCfg.HandlerGetBusByName)
router.Post("/addbus", apiCfg.HandlerAddBuses)

userRouter.Post("/createaccount", apiCfg.HandlerCreateAccount)
userRouter.Post("/login", apiCfg.HandlerLogin)

router.Mount("/api", router)
router.Mount("/usr", userRouter)

return router
}

0 comments on commit bfad037

Please sign in to comment.