From ac7aa8c6e95023def1eba7615d8a42ad52271500 Mon Sep 17 00:00:00 2001 From: Vidhu Kant Sharma Date: Sun, 29 Jan 2023 20:11:09 +0530 Subject: checking password before editing/deleting user --- auth/auth.go | 64 ------------------- auth/jwt.go | 95 --------------------------- auth/password_middleware.go | 73 --------------------- auth/refresh_middleware.go | 47 -------------- auth/router.go | 60 +++++++++++++++++ brand/controller.go | 93 +++++++++++++++++++++++++++ brand/db_actions.go | 69 -------------------- brand/router.go | 80 ++--------------------- brand/service.go | 69 ++++++++++++++++++++ client/controller.go | 93 +++++++++++++++++++++++++++ client/db_actions.go | 62 ------------------ client/router.go | 79 ++--------------------- client/service.go | 62 ++++++++++++++++++ invoice/controller.go | 95 +++++++++++++++++++++++++++ invoice/db_actions.go | 131 -------------------------------------- invoice/invoice.go | 101 +++++++++++------------------ invoice/router.go | 152 ++------------------------------------------ invoice/service.go | 68 ++++++++++++++++++++ item/controller.go | 91 ++++++++++++++++++++++++++ item/db_actions.go | 82 ------------------------ item/router.go | 79 ++--------------------- item/service.go | 82 ++++++++++++++++++++++++ main.go | 6 +- transport/controller.go | 57 +++++++++++++++++ transport/router.go | 31 +++++++++ transport/service.go | 52 +++++++++++++++ transport/transport.go | 36 +++++++++++ transporter/controller.go | 57 +++++++++++++++++ transporter/router.go | 31 +++++++++ transporter/service.go | 52 +++++++++++++++ transporter/transporter.go | 39 ++++++++++++ user/controller.go | 105 ++++++++++++++++++++++++++++++ user/db_actions.go | 60 ----------------- user/password.go | 70 ++++++++++++++++++++ user/refresh.go | 117 ++++++++++++++++++++++++++++++++++ user/router.go | 87 ++----------------------- user/service.go | 60 +++++++++++++++++ util/authorize.go | 68 ++++++++++++++++++++ util/jwt_middleware.go | 51 --------------- 39 files changed, 1555 insertions(+), 1251 deletions(-) delete mode 100644 auth/auth.go delete mode 100644 auth/jwt.go delete mode 100644 auth/password_middleware.go delete mode 100644 auth/refresh_middleware.go create mode 100644 auth/router.go create mode 100644 brand/controller.go delete mode 100644 brand/db_actions.go create mode 100644 brand/service.go create mode 100644 client/controller.go delete mode 100644 client/db_actions.go create mode 100644 client/service.go create mode 100644 invoice/controller.go delete mode 100644 invoice/db_actions.go create mode 100644 invoice/service.go create mode 100644 item/controller.go delete mode 100644 item/db_actions.go create mode 100644 item/service.go create mode 100644 transport/controller.go create mode 100644 transport/router.go create mode 100644 transport/service.go create mode 100644 transport/transport.go create mode 100644 transporter/controller.go create mode 100644 transporter/router.go create mode 100644 transporter/service.go create mode 100644 transporter/transporter.go create mode 100644 user/controller.go delete mode 100644 user/db_actions.go create mode 100644 user/password.go create mode 100644 user/refresh.go create mode 100644 user/service.go create mode 100644 util/authorize.go delete mode 100644 util/jwt_middleware.go diff --git a/auth/auth.go b/auth/auth.go deleted file mode 100644 index 1048f82..0000000 --- a/auth/auth.go +++ /dev/null @@ -1,64 +0,0 @@ -/* OpenBills-server - Server for libre billing software OpenBills-web - * Copyright (C) 2022 Vidhu Kant Sharma - - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package auth - -import ( - "github.com/gin-gonic/gin" - "go.mongodb.org/mongo-driver/mongo" - "github.com/MikunoNaka/OpenBills-server/database" - "github.com/MikunoNaka/OpenBills-server/user" - "net/http" - "log" -) - -var db *mongo.Collection = database.DB.Collection("Users") - -func Routes(route *gin.Engine) { - r := route.Group("/auth") - { - r.POST("/login", checkPassword(), func(ctx *gin.Context) { - user := ctx.MustGet("user").(user.User) - - accessToken, err := newAccessToken(user.Id.Hex()) - if err != nil { - log.Printf("Error while generating new access token: %v", err) - ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Internal Server Error (cannot login)"}) - } - - refreshToken, expiresAt, err := newRefreshToken(user.Id.Hex()) - if err != nil { - log.Printf("Error while generating new refresh token: %v", err) - ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Internal Server Error (cannot login)"}) - } - - ctx.SetCookie("refreshToken", refreshToken, int(expiresAt), "", "", true, true) - ctx.JSON(http.StatusOK, gin.H{"accessToken": accessToken}) - }) - - r.POST("/refresh", verifyRefreshToken(), func (ctx *gin.Context) { - u := ctx.MustGet("user").(user.User) - accessToken, err := newAccessToken(u.Id.Hex()) - if err != nil { - log.Printf("Error while generating new access token: %v", err) - ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Internal Server Error (cannot refresh session)"}) - } else { - ctx.JSON(http.StatusOK, gin.H{"accessToken": accessToken}) - } - }) - } -} diff --git a/auth/jwt.go b/auth/jwt.go deleted file mode 100644 index 66a4f12..0000000 --- a/auth/jwt.go +++ /dev/null @@ -1,95 +0,0 @@ -/* OpenBills-server - Server for libre billing software OpenBills-web - * Copyright (C) 2022 Vidhu Kant Sharma - - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package auth - -import ( - "github.com/MikunoNaka/OpenBills-server/user" - "github.com/MikunoNaka/OpenBills-server/util" - "github.com/golang-jwt/jwt/v4" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - - "context" - "errors" - "time" -) - -var ( - errUserNotFound error = errors.New("user does not exist") -) - -var accessSecret []byte -var refreshSecret []byte -func init() { - conf := util.GetConfig().Crypto - accessSecret = []byte(conf.AccessTokenSecret) - refreshSecret = []byte(conf.RefreshTokenSecret) -} - -func newAccessToken(userId string) (string, error) { - claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims { - Issuer: userId, - ExpiresAt: time.Now().Add(time.Second * 15).Unix(), - }) - - token, err := claims.SignedString(accessSecret) - if err != nil { - return "", err - } - - return token, nil -} - -/* - * the refresh token has a long lifespan and is stored in - * the database in case it needs to be revoked. - * - * this can be stored as an HTTP only cookie and will be used - * when creating a new access token - * - * I'm using a different secret key for refresh tokens - * for enhanced security - */ -func newRefreshToken(userId string) (string, int64, error) { - // convert id from string to ObjectID - id, _ := primitive.ObjectIDFromHex(userId) - - // check if user exists - var u user.User - if err := db.FindOne(context.TODO(), bson.M{"_id": id}).Decode(&u); err != nil { - return "", 0, errUserNotFound - } - - // generate refresh token - expiresAt := time.Now().Add(time.Hour * 12).Unix() - claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims { - Issuer: userId, - ExpiresAt: expiresAt, - }) - token, err := claims.SignedString(refreshSecret) - if err != nil { - return "", expiresAt, err - } - - // store refresh token in db with unique session name for ease in identification - sessionName := time.Now().Format("01-02-2006.15:04:05") + "-" + u.UserName - u.Sessions = append(u.Sessions, user.Session{Name: sessionName, Token: token}) - db.UpdateOne(context.TODO(), bson.M{"_id": id}, bson.D{{"$set", u}}) - - return token, expiresAt, nil -} diff --git a/auth/password_middleware.go b/auth/password_middleware.go deleted file mode 100644 index 3fda389..0000000 --- a/auth/password_middleware.go +++ /dev/null @@ -1,73 +0,0 @@ -/* OpenBills-server - Server for libre billing software OpenBills-web - * Copyright (C) 2022 Vidhu Kant Sharma - - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package auth - -import ( - "github.com/gin-gonic/gin" - "net/http" - "log" - "context" - "golang.org/x/crypto/bcrypt" - "github.com/MikunoNaka/OpenBills-server/user" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/mongo" -) - -func checkPassword() gin.HandlerFunc { - return func(ctx *gin.Context) { - var u user.User - ctx.BindJSON(&u) - - filter := bson.M{ - "$or": []bson.M{ - // u.UserName in this case can be either username or email - {"Email": u.UserName}, - {"UserName": u.UserName}, - }, - } - - // check if the user exists in DB - var user user.User - err := db.FindOne(context.TODO(), filter).Decode(&user) - if err != nil { - if err == mongo.ErrNoDocuments { - ctx.JSON(http.StatusNotFound, gin.H{"error": "user does not exist"}) - } else { - log.Printf("Error while reading user from DB to check password: %v", err.Error()) - ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal server error"}) - } - ctx.Abort() - } else { - // compare hash and password - err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(u.Password)) - if err != nil { - if err == bcrypt.ErrMismatchedHashAndPassword { - ctx.JSON(http.StatusUnauthorized, gin.H{"error": "incorrect password"}) - } else { - log.Printf("Error while checking password: %v", err.Error()) - ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal server error"}) - } - ctx.Abort() - } - } - - // everything's fine! - ctx.Set("user", user) - ctx.Next() - } -} diff --git a/auth/refresh_middleware.go b/auth/refresh_middleware.go deleted file mode 100644 index 00f73bf..0000000 --- a/auth/refresh_middleware.go +++ /dev/null @@ -1,47 +0,0 @@ -package auth - -import ( - "github.com/golang-jwt/jwt/v4" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/bson" - "github.com/MikunoNaka/OpenBills-server/user" - "github.com/gin-gonic/gin" - "context" - "net/http" -) - -func verifyRefreshToken() gin.HandlerFunc { - return func(ctx *gin.Context) { - refreshToken, err := ctx.Cookie("refreshToken") - if err == nil { - token, err := jwt.ParseWithClaims(refreshToken, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) { - return []byte(refreshSecret), nil - }) - if err != nil { // invalid token - ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "refresh token expired"}) - } else { // valid token - // convert id from string to ObjectID - id, _ := primitive.ObjectIDFromHex(token.Claims.(*jwt.StandardClaims).Issuer) - - // check if user exists - var u user.User - if err := db.FindOne(context.TODO(), bson.M{"_id": id}).Decode(&u); err != nil { - ctx.AbortWithStatusJSON(http.StatusNotFound, gin.H{"message": "user not found"}) - } else { - // check if this refreshToken is in DB - for _, i := range u.Sessions { - if i.Token == refreshToken { - ctx.Set("user", u) - ctx.Next() - } else { - ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "refresh token expired"}) - } - } - } - } - } else { - // invalid Authorization header - ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "not logged in"}) - } - } -} diff --git a/auth/router.go b/auth/router.go new file mode 100644 index 0000000..9fa03b7 --- /dev/null +++ b/auth/router.go @@ -0,0 +1,60 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package auth + +import ( + "github.com/MikunoNaka/OpenBills-server/user" + "github.com/gin-gonic/gin" + "log" + "net/http" +) + +func Routes(route *gin.Engine) { + r := route.Group("/auth") + { + r.POST("/login", user.checkPassword(), func(ctx *gin.Context) { + user := ctx.MustGet("user").(user.User) + + accessToken, err := user.newAccessToken(user.Id.Hex()) + if err != nil { + log.Printf("Error while generating new access token: %v", err) + ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Internal Server Error (cannot login)"}) + } + + refreshToken, expiresAt, err := user.newRefreshToken(user.Id.Hex()) + if err != nil { + log.Printf("Error while generating new refresh token: %v", err) + ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Internal Server Error (cannot login)"}) + } + + ctx.SetCookie("refreshToken", refreshToken, int(expiresAt), "", "", true, true) + ctx.JSON(http.StatusOK, gin.H{"accessToken": accessToken}) + }) + + r.POST("/refresh", user.verifyRefreshToken(), func(ctx *gin.Context) { + u := ctx.MustGet("user").(user.User) + accessToken, err := util.newAccessToken(u.Id.Hex()) + if err != nil { + log.Printf("Error while generating new access token: %v", err) + ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": "Internal Server Error (cannot refresh session)"}) + } else { + ctx.JSON(http.StatusOK, gin.H{"accessToken": accessToken}) + } + }) + } +} diff --git a/brand/controller.go b/brand/controller.go new file mode 100644 index 0000000..f69f466 --- /dev/null +++ b/brand/controller.go @@ -0,0 +1,93 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package brand + +import ( + "github.com/gin-gonic/gin" + "go.mongodb.org/mongo-driver/bson/primitive" + "log" + "net/http" +) + +func getAll(ctx *gin.Context) { + // TODO: add functionality to filter results + brands, err := getBrands(nil) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to read brands from DB: %v\n", err.Error()) + return + } + + ctx.JSON(http.StatusOK, brands) +} + +func save(ctx *gin.Context) { + var b Brand + ctx.BindJSON(&b) + _, err := saveBrand(b) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to add new brand %v to DB: %v\n", b, err.Error()) + return + } + + log.Printf("Successfully saved new brand to DB: %v", b) + ctx.JSON(http.StatusOK, nil) +} + +func modify(ctx *gin.Context) { + id := ctx.Param("brandId") + objectId, err := primitive.ObjectIDFromHex(id) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to modify brand, Error parsing ID: %v\n", err.Error()) + return + } + + var b Brand + ctx.BindJSON(&b) + err = modifyBrand(objectId, b) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to modify brand %v: %v\n", objectId, err.Error()) + return + } + + log.Printf("Modified brand %v to %v.\n", objectId, b) + ctx.JSON(http.StatusOK, nil) +} + +func remove(ctx *gin.Context) { + id := ctx.Param("brandId") + objectId, err := primitive.ObjectIDFromHex(id) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete brand, Error parsing ID: %v\n", err.Error()) + return + } + + err = deleteBrand(objectId) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete brand %v: %v\n", objectId, err.Error()) + return + } + + log.Printf("Deleted brand %v from database.\n", objectId) + ctx.JSON(http.StatusOK, nil) +} diff --git a/brand/db_actions.go b/brand/db_actions.go deleted file mode 100644 index eb5961c..0000000 --- a/brand/db_actions.go +++ /dev/null @@ -1,69 +0,0 @@ -/* OpenBills-server - Server for libre billing software OpenBills-web - * Copyright (C) 2022 Vidhu Kant Sharma - - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package brand - -import ( - "context" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/mongo" - "github.com/MikunoNaka/OpenBills-server/database" -) - -var items *mongo.Collection = database.DB.Collection("Items") - -// Add brand to db -func saveBrand(b Brand) (primitive.ObjectID, error) { - res, err := db.InsertOne(context.TODO(), b) - return res.InsertedID.(primitive.ObjectID), err -} - -// Delete brand from DB -func deleteBrand(id primitive.ObjectID) error { - // delete brand - _, err := db.DeleteOne(context.TODO(), bson.M{"_id": id}) - if err != nil { - return err - } - - // delete items associated with this brand - _, err = items.DeleteMany(context.TODO(), bson.M{"Brand._id": id}) - return err -} - -// modify brand in DB -func modifyBrand(id primitive.ObjectID, nb Brand) error { - _, err := db.UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", nb}}) - return err -} - -/* GetBrands queries the database and - * returns brands based on the given filter - * if filter is nil every brand is returned - */ -func getBrands(filter bson.M) ([]Brand, error) { - var brands []Brand - - cursor, err := db.Find(context.TODO(), filter) - if err != nil { - return brands, err - } - - err = cursor.All(context.TODO(), &brands) - return brands, err -} diff --git a/brand/router.go b/brand/router.go index 5c9c7af..6593291 100644 --- a/brand/router.go +++ b/brand/router.go @@ -18,84 +18,16 @@ package brand import ( - "github.com/MikunoNaka/OpenBills-server/util" + "github.com/MikunoNaka/OpenBills-server/util" "github.com/gin-gonic/gin" - "go.mongodb.org/mongo-driver/bson/primitive" - "log" - "net/http" ) - func Routes(route *gin.Engine) { - b := route.Group("/brand") - b.Use(util.Authorize()) + b := route.Group("/brand", util.Authorize()) { - b.GET("/all", func(ctx *gin.Context) { - // TODO: add functionality to filter results - brands, err := getBrands(nil) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to read brands from DB: %v\n", err.Error()) - return - } - - ctx.JSON(http.StatusOK, brands) - }) - - b.POST("/new", func(ctx *gin.Context) { - var b Brand - ctx.BindJSON(&b) - _, err := saveBrand(b) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to add new brand %v to DB: %v\n", b, err.Error()) - return - } - - log.Printf("Successfully saved new brand to DB: %v", b) - ctx.JSON(http.StatusOK, nil) - }) - - b.PUT("/:brandId", func(ctx *gin.Context) { - id := ctx.Param("brandId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to modify brand, Error parsing ID: %v\n", err.Error()) - return - } - - var b Brand - ctx.BindJSON(&b) - err = modifyBrand(objectId, b) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to modify brand %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Modified brand %v to %v.\n", objectId, b) - ctx.JSON(http.StatusOK, nil) - }) - - b.DELETE("/:brandId", func(ctx *gin.Context) { - id := ctx.Param("brandId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete brand, Error parsing ID: %v\n", err.Error()) - return - } - - err = deleteBrand(objectId) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete brand %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Deleted brand %v from database.\n", objectId ) - ctx.JSON(http.StatusOK, nil) - }) + b.GET("/all", getAll) + b.POST("/new", save) + b.PUT("/:brandId", modify) + b.DELETE("/:brandId", remove) } } diff --git a/brand/service.go b/brand/service.go new file mode 100644 index 0000000..eb5961c --- /dev/null +++ b/brand/service.go @@ -0,0 +1,69 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package brand + +import ( + "context" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "github.com/MikunoNaka/OpenBills-server/database" +) + +var items *mongo.Collection = database.DB.Collection("Items") + +// Add brand to db +func saveBrand(b Brand) (primitive.ObjectID, error) { + res, err := db.InsertOne(context.TODO(), b) + return res.InsertedID.(primitive.ObjectID), err +} + +// Delete brand from DB +func deleteBrand(id primitive.ObjectID) error { + // delete brand + _, err := db.DeleteOne(context.TODO(), bson.M{"_id": id}) + if err != nil { + return err + } + + // delete items associated with this brand + _, err = items.DeleteMany(context.TODO(), bson.M{"Brand._id": id}) + return err +} + +// modify brand in DB +func modifyBrand(id primitive.ObjectID, nb Brand) error { + _, err := db.UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", nb}}) + return err +} + +/* GetBrands queries the database and + * returns brands based on the given filter + * if filter is nil every brand is returned + */ +func getBrands(filter bson.M) ([]Brand, error) { + var brands []Brand + + cursor, err := db.Find(context.TODO(), filter) + if err != nil { + return brands, err + } + + err = cursor.All(context.TODO(), &brands) + return brands, err +} diff --git a/client/controller.go b/client/controller.go new file mode 100644 index 0000000..b9a9abe --- /dev/null +++ b/client/controller.go @@ -0,0 +1,93 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package client + +import ( + "github.com/gin-gonic/gin" + "go.mongodb.org/mongo-driver/bson/primitive" + "log" + "net/http" +) + +func getAll(ctx *gin.Context) { + // TODO: add functionality to filter results + clients, err := getClients(nil) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to read clients from DB: %v\n", err.Error()) + return + } + + ctx.JSON(http.StatusOK, clients) +} + +func save(ctx *gin.Context) { + var c Client + ctx.BindJSON(&c) + _, err := saveClient(c) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to add new client %v to DB: %v\n", c, err.Error()) + return + } + + log.Printf("Successfully saved new client to DB: %v", c) + ctx.JSON(http.StatusOK, nil) +} + +func modify(ctx *gin.Context) { + id := ctx.Param("clientId") + objectId, err := primitive.ObjectIDFromHex(id) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to modify client, Error parsing ID: %v\n", err.Error()) + return + } + + var c Client + ctx.BindJSON(&c) + err = modifyClient(objectId, c) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to modify client %v: %v\n", objectId, err.Error()) + return + } + + log.Printf("Modified client %v to %v.\n", objectId, c) + ctx.JSON(http.StatusOK, nil) +} + +func remove(ctx *gin.Context) { + id := ctx.Param("clientId") + objectId, err := primitive.ObjectIDFromHex(id) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete client, Error parsing ID: %v\n", err.Error()) + return + } + + err = deleteClient(objectId) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete client %v: %v\n", objectId, err.Error()) + return + } + + log.Printf("Deleted client %v from database.\n", objectId) + ctx.JSON(http.StatusOK, nil) +} diff --git a/client/db_actions.go b/client/db_actions.go deleted file mode 100644 index bf32d97..0000000 --- a/client/db_actions.go +++ /dev/null @@ -1,62 +0,0 @@ -/* OpenBills-server - Server for libre billing software OpenBills-web - * Copyright (C) 2022 Vidhu Kant Sharma - - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package client - -import ( - "context" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" -) - -/* TODO: Handle errors properly - * Send an API error response instead of log.Fatal - */ - -// Add client to db -func saveClient(c Client) (primitive.ObjectID, error) { - res, err := db.InsertOne(context.TODO(), c) - return res.InsertedID.(primitive.ObjectID), err -} - -// Delete client from DB -func deleteClient(id primitive.ObjectID) error { - _, err := db.DeleteOne(context.TODO(), bson.M{"_id": id}) - return err -} - -// modify client in DB -func modifyClient(id primitive.ObjectID, nc Client) error { - _, err := db.UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", nc}}) - return err -} - -/* GetClients queries the database and - * returns clients based on the given filter - * if filter is nil every client is returned - */ -func getClients(filter bson.M) ([]Client, error) { - var clients []Client - - cursor, err := db.Find(context.TODO(), filter) - if err != nil { - return clients, err - } - - err = cursor.All(context.TODO(), &clients) - return clients, err -} diff --git a/client/router.go b/client/router.go index 232ad83..6bf1ba9 100644 --- a/client/router.go +++ b/client/router.go @@ -18,83 +18,16 @@ package client import ( - "github.com/MikunoNaka/OpenBills-server/util" + "github.com/MikunoNaka/OpenBills-server/util" "github.com/gin-gonic/gin" - "log" - "net/http" - "go.mongodb.org/mongo-driver/bson/primitive" ) func Routes(route *gin.Engine) { - c := route.Group("/client") - c.Use(util.Authorize()) + c := route.Group("/client", util.Authorize()) { - c.GET("/all", func(ctx *gin.Context) { - // TODO: add functionality to filter results - clients, err := getClients(nil) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to read clients from DB: %v\n", err.Error()) - return - } - - ctx.JSON(http.StatusOK, clients) - }) - - c.POST("/new", func(ctx *gin.Context) { - var c Client - ctx.BindJSON(&c) - _, err := saveClient(c) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to add new client %v to DB: %v\n", c, err.Error()) - return - } - - log.Printf("Successfully saved new client to DB: %v", c) - ctx.JSON(http.StatusOK, nil) - }) - - c.PUT("/:clientId", func(ctx *gin.Context) { - id := ctx.Param("clientId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to modify client, Error parsing ID: %v\n", err.Error()) - return - } - - var c Client - ctx.BindJSON(&c) - err = modifyClient(objectId, c) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to modify client %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Modified client %v to %v.\n", objectId, c) - ctx.JSON(http.StatusOK, nil) - }) - - c.DELETE("/:clientId", func(ctx *gin.Context) { - id := ctx.Param("clientId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete client, Error parsing ID: %v\n", err.Error()) - return - } - - err = deleteClient(objectId) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete client %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Deleted client %v from database.\n", objectId ) - ctx.JSON(http.StatusOK, nil) - }) + c.GET("/all", getAll) + c.POST("/new", save) + c.PUT("/:brandId", modify) + c.DELETE("/:brandId", remove) } } diff --git a/client/service.go b/client/service.go new file mode 100644 index 0000000..bf32d97 --- /dev/null +++ b/client/service.go @@ -0,0 +1,62 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package client + +import ( + "context" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +/* TODO: Handle errors properly + * Send an API error response instead of log.Fatal + */ + +// Add client to db +func saveClient(c Client) (primitive.ObjectID, error) { + res, err := db.InsertOne(context.TODO(), c) + return res.InsertedID.(primitive.ObjectID), err +} + +// Delete client from DB +func deleteClient(id primitive.ObjectID) error { + _, err := db.DeleteOne(context.TODO(), bson.M{"_id": id}) + return err +} + +// modify client in DB +func modifyClient(id primitive.ObjectID, nc Client) error { + _, err := db.UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", nc}}) + return err +} + +/* GetClients queries the database and + * returns clients based on the given filter + * if filter is nil every client is returned + */ +func getClients(filter bson.M) ([]Client, error) { + var clients []Client + + cursor, err := db.Find(context.TODO(), filter) + if err != nil { + return clients, err + } + + err = cursor.All(context.TODO(), &clients) + return clients, err +} diff --git a/invoice/controller.go b/invoice/controller.go new file mode 100644 index 0000000..e328dc4 --- /dev/null +++ b/invoice/controller.go @@ -0,0 +1,95 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package invoice + +import ( + "errors" + "github.com/gin-gonic/gin" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "log" + "net/http" +) + +func getAll(ctx *gin.Context) { + // TODO: add functionality to filter results + invoices, err := getInvoices(nil) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to read invoices from DB: %v\n", err.Error()) + return + } + + ctx.JSON(http.StatusOK, invoices) +} + +func get(ctx *gin.Context) { + id, err := primitive.ObjectIDFromHex(ctx.Param("invoiceId")) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to get invoice with ID, Error parsing ID: %v\n", err.Error()) + return + } + + invoice, err := getInvoiceById(id) + if err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) + } else { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } + log.Printf("ERROR: Failed to read invoice %v from DB: %v\n", id, err.Error()) + return + } + + ctx.JSON(http.StatusOK, invoice) +} + +func save(ctx *gin.Context) { + var i Invoice + ctx.BindJSON(&i) + _, err := saveInvoice(i) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to add new invoice %v to DB: %v\n", i, err.Error()) + return + } + + log.Printf("Successfully created new Invoice: %v", i) + ctx.JSON(http.StatusOK, nil) +} + +func remove(ctx *gin.Context) { + id := ctx.Param("invoiceId") + objectId, err := primitive.ObjectIDFromHex(id) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete invoice, Error parsing ID: %v\n", err.Error()) + return + } + + err = deleteInvoice(objectId) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete invoice %v: %v\n", objectId, err.Error()) + return + } + + log.Printf("Deleted invoice %v from database.\n", objectId) + ctx.JSON(http.StatusOK, nil) +} diff --git a/invoice/db_actions.go b/invoice/db_actions.go deleted file mode 100644 index 0cbeec1..0000000 --- a/invoice/db_actions.go +++ /dev/null @@ -1,131 +0,0 @@ -/* OpenBills-server - Server for libre billing software OpenBills-web - * Copyright (C) 2022 Vidhu Kant Sharma - - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package invoice - -import ( - "context" - - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" -) - -// add invoice to db -func saveInvoice(i Invoice) (primitive.ObjectID, error) { - res, err := db.Collection("Invoices").InsertOne(context.TODO(), i) - return res.InsertedID.(primitive.ObjectID), err -} - -// add transporter to db -func saveTransporter(t Transporter) (primitive.ObjectID, error) { - res, err := db.Collection("Transporters").InsertOne(context.TODO(), t) - return res.InsertedID.(primitive.ObjectID), err -} - -// add transport vehicle to db -func saveTransport(t *Transport) (primitive.ObjectID, error) { - res, err := db.Collection("Transports").InsertOne(context.TODO(), t) - return res.InsertedID.(primitive.ObjectID), err -} - -// Delete invoice from DB -func deleteInvoice(id primitive.ObjectID) error { - _, err := db.Collection("Invoices").DeleteOne(context.TODO(), bson.M{"_id": id}) - return err -} - -// Delete transporter from DB -func deleteTransporter(id primitive.ObjectID) error { - _, err := db.Collection("Transporters").DeleteOne(context.TODO(), bson.M{"_id": id}) - return err -} - -// Delete transport vehicle from DB -func deleteTransport(id primitive.ObjectID) error { - _, err := db.Collection("Transports").DeleteOne(context.TODO(), bson.M{"_id": id}) - return err -} - -// modify invoice in DB -func modifyInvoice(id primitive.ObjectID, ni Invoice) error { - _, err := db.Collection("Invoices").UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", ni}}) - return err -} - -// modify transporter in DB -func modifyTransporter(id primitive.ObjectID, nt Transporter) error { - _, err := db.Collection("Transporters").UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", nt}}) - return err -} - -// modify transport in DB -func modifyTransport(id primitive.ObjectID, nt Transport) error { - _, err := db.Collection("Transports").UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", nt}}) - return err -} - -/* GetInvoices queries the database and - * returns invoices based on the given filter - * if filter is nil every invoice is returned - */ -func getInvoices(filter bson.M) ([]Invoice, error) { - var invoices []Invoice - - cursor, err := db.Collection("Invoices").Find(context.TODO(), filter) - if err != nil { - return invoices, err - } - - err = cursor.All(context.TODO(), &invoices) - return invoices, err -} - -func getTransporters(filter bson.M) ([]Transporter, error) { - var transporters []Transporter - - cursor, err := db.Collection("Transporters").Find(context.TODO(), filter) - if err != nil { - return transporters, err - } - - err = cursor.All(context.TODO(), &transporters) - return transporters, err -} - -func getTransports(filter bson.M) ([]Transport, error) { - var transports []Transport - - cursor, err := db.Collection("Transports").Find(context.TODO(), filter) - if err != nil { - return transports, err - } - - err = cursor.All(context.TODO(), &transports) - return transports, err -} - -func getInvoiceByNumber(invoiceNumber int) (Invoice, error) { - var invoice Invoice - err := db.Collection("Invoices").FindOne(context.TODO(), bson.M{"InvoiceNumber": invoiceNumber}).Decode(&invoice) - return invoice, err -} - -func getInvoiceById(invoiceId primitive.ObjectID) (Invoice, error) { - var invoice Invoice - err := db.Collection("Invoices").FindOne(context.TODO(), bson.M{"_id": invoiceId}).Decode(&invoice) - return invoice, err -} diff --git a/invoice/invoice.go b/invoice/invoice.go index 91b881c..f7b638a 100644 --- a/invoice/invoice.go +++ b/invoice/invoice.go @@ -18,45 +18,18 @@ package invoice import ( - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/mongo" "github.com/MikunoNaka/OpenBills-server/client" - "github.com/MikunoNaka/OpenBills-server/item" "github.com/MikunoNaka/OpenBills-server/database" + "github.com/MikunoNaka/OpenBills-server/item" + t "github.com/MikunoNaka/OpenBills-server/transport" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" "time" ) // initialise a database connection for this package // not sure if I should do this but I am... -var db *mongo.Database = database.DB - -/* you should be able to: - * - add, modify, delete an invoice - * - add client to invoice - * - add items to invoice - */ - -/* Transporter details can be stored in - * the DB. That is decided by the frontend. - * You can optionally store Transporter - * and Transport details which are often used - */ -type Transporter struct { - Id primitive.ObjectID `bson:"_id,omitempty" json:"Id"` - Name string `bson:"Name" json:"Name"` - GSTIN string `bson:"GSTIN" json:"GSTIN"` - // Issued ID for the transporter if any - TransporterId string `bson:"TransporterId,omitempty" json:"TransporterId"` -} - -// transport vehicle details -type Transport struct { - Id primitive.ObjectID `bson:"_id,omitempty" json:"Id"` - Transporter Transporter `bson:"Transporter,omitempty" json:"Transporter"` - VehicleNum string `bson:"VehicleNum" json:"VehicleNum"` - Note string `bson:"Note" json:"Note"` - TransportMethod string `bson:"TransportMethod" json:"TransportMethod"` -} +var db *mongo.Collection = database.DB.Collection("Invoice") /* The *legendary* Invoice struct * Each Recipient, Item in invoice, Address @@ -80,37 +53,37 @@ type Transport struct { */ // TODO: add place of supply type Invoice struct { - Id primitive.ObjectID `bson:"_id,omitempty" json:"Id"` // not the same as invoice number - InvoiceNumber int `bson:"InvoiceNumber" json:"InvoiceNumber"` - CreatedAt time.Time `bson:"CreatedAt" json:"CreatedAt"` - LastUpdated time.Time `bson:"LastUpdated,omitempty" json:"LastUpdated"` - Recipient client.Client `bson:"Recipient" json:"Recipient"` - Paid bool `bson:"Paid" json:"Paid"` - TransactionId string `bson:"TransactionId" json:"TransactionId"` - Transport Transport `bson:"Transport" json:"Transport"` - // user can apply a discount on the whole invoice - // TODO: float64 isn't the best for this - DiscountPercentage float64 `bson:"DiscountPercentage" json:"DiscountPercentage"` - // helps to filter amount by amount - TotalAmount float64 `bson:"TotalAmount" json:"TotalAmount"` - /* client may have multiple shipping - * addresses but invoice only has one. - * Empty ShippingAddress means shipping - * address same as billing address - */ - BillingAddress client.Address `bson:"BillingAddress" json:"BillingAddress"` - ShippingAddress client.Address `bson:"ShippingAddress,omitempty" json:"ShippingAddress"` - Items []item.InvoiceItem `bson:"Items" json:"Items"` - // user can attach notes to the invoice - // frontend decides if recipient sees this or not - Note string `bson:"Note" json:"Note"` + Id primitive.ObjectID `bson:"_id,omitempty" json:"Id"` // not the same as invoice number + InvoiceNumber int `bson:"InvoiceNumber" json:"InvoiceNumber"` + CreatedAt time.Time `bson:"CreatedAt" json:"CreatedAt"` + LastUpdated time.Time `bson:"LastUpdated,omitempty" json:"LastUpdated"` + Recipient client.Client `bson:"Recipient" json:"Recipient"` + Paid bool `bson:"Paid" json:"Paid"` + TransactionId string `bson:"TransactionId" json:"TransactionId"` + Transport t.Transport `bson:"Transport" json:"Transport"` + // user can apply a discount on the whole invoice + // TODO: float64 isn't the best for this + DiscountPercentage float64 `bson:"DiscountPercentage" json:"DiscountPercentage"` + // helps to filter amount by amount + TotalAmount float64 `bson:"TotalAmount" json:"TotalAmount"` + /* client may have multiple shipping + * addresses but invoice only has one. + * Empty ShippingAddress means shipping + * address same as billing address + */ + BillingAddress client.Address `bson:"BillingAddress" json:"BillingAddress"` + ShippingAddress client.Address `bson:"ShippingAddress,omitempty" json:"ShippingAddress"` + Items []item.InvoiceItem `bson:"Items" json:"Items"` + // user can attach notes to the invoice + // frontend decides if recipient sees this or not + Note string `bson:"Note" json:"Note"` - /* Invoices can be drafts - * I personally like this functionality - * because we can constantly save the - * invoice to the DB as a draft - * and if OpenBills crashes or is disconnected - * we still have the progress - */ - Draft bool `bson:"Draft" json:"Draft"` + /* Invoices can be drafts + * I personally like this functionality + * because we can constantly save the + * invoice to the DB as a draft + * and if OpenBills crashes or is disconnected + * we still have the progress + */ + Draft bool `bson:"Draft" json:"Draft"` } diff --git a/invoice/router.go b/invoice/router.go index c89d667..4a3a3b0 100644 --- a/invoice/router.go +++ b/invoice/router.go @@ -18,156 +18,16 @@ package invoice import ( - "github.com/MikunoNaka/OpenBills-server/util" + "github.com/MikunoNaka/OpenBills-server/util" "github.com/gin-gonic/gin" - "log" - "errors" - "net/http" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/mongo" ) func Routes(route *gin.Engine) { - i := route.Group("/invoice") - i.Use(util.Authorize()) + i := route.Group("/invoice", util.Authorize()) { - i.GET("/all", func(ctx *gin.Context) { - // TODO: add functionality to filter results - invoices, err := getInvoices(nil) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to read invoices from DB: %v\n", err.Error()) - return - } - - ctx.JSON(http.StatusOK, invoices) - }) - - // send invoice as JSON, filtering by ID - i.GET("/:invoiceId", func(ctx *gin.Context) { - id, err := primitive.ObjectIDFromHex(ctx.Param("invoiceId")) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to get invoice with ID, Error parsing ID: %v\n", err.Error()) - return - } - - invoice, err := getInvoiceById(id) - if err != nil { - if errors.Is(err, mongo.ErrNoDocuments) { - ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) - } else { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } - log.Printf("ERROR: Failed to read invoice %v from DB: %v\n", id, err.Error()) - return - } - - ctx.JSON(http.StatusOK, invoice) - }) - - i.POST("/new", func(ctx *gin.Context) { - var i Invoice - ctx.BindJSON(&i) - _, err := saveInvoice(i) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to add new invoice %v to DB: %v\n", i, err.Error()) - return - } - - log.Printf("Successfully created new Invoice: %v", i) - ctx.JSON(http.StatusOK, nil) - }) - - i.DELETE("/:invoiceId", func(ctx *gin.Context) { - id := ctx.Param("invoiceId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete invoice, Error parsing ID: %v\n", err.Error()) - return - } - - err = deleteInvoice(objectId) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete invoice %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Deleted invoice %v from database.\n", objectId ) - ctx.JSON(http.StatusOK, nil) - }) - } - - transport := route.Group("/transport") - { - transport.GET("/all", func(ctx *gin.Context) { - // TODO: add functionality to filter results - transports, err := getTransports(nil) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to read transport vehicles from DB: %v\n", err.Error()) - return - } - - ctx.JSON(http.StatusOK, transports) - }) - - transport.DELETE("/:transportId", func(ctx *gin.Context) { - id := ctx.Param("transportId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete transport vehicle, Error parsing ID: %v\n", err.Error()) - return - } - - err = deleteTransport(objectId) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete transport vehicle %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Deleted transport vehicle %v from database.\n", objectId ) - ctx.JSON(http.StatusOK, nil) - }) - } - - transporter := route.Group("/transporter") - { - transporter.GET("/all", func(ctx *gin.Context) { - // TODO: add functionality to filter results - transporters, err := getTransporters(nil) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to read transporters from DB: %v\n", err.Error()) - return - } - - ctx.JSON(http.StatusOK, transporters) - }) - - transporter.DELETE("/:transporterId", func(ctx *gin.Context) { - id := ctx.Param("transporterId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete transporter, Error parsing ID: %v\n", err.Error()) - return - } - - err = deleteTransporter(objectId) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete transporter %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Deleted transporter %v from database.\n", objectId ) - ctx.JSON(http.StatusOK, nil) - }) + i.GET("/all", getAll) + i.GET("/:invoiceId", get) // send invoice as JSON, filtering by ID + i.POST("/new", save) + i.DELETE("/:invoiceId", remove) } } diff --git a/invoice/service.go b/invoice/service.go new file mode 100644 index 0000000..ab37d8a --- /dev/null +++ b/invoice/service.go @@ -0,0 +1,68 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package invoice + +import ( + "context" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +func saveInvoice(i Invoice) (primitive.ObjectID, error) { + res, err := db.InsertOne(context.TODO(), i) + return res.InsertedID.(primitive.ObjectID), err +} + +func deleteInvoice(id primitive.ObjectID) error { + _, err := db.DeleteOne(context.TODO(), bson.M{"_id": id}) + return err +} + +func modifyInvoice(id primitive.ObjectID, ni Invoice) error { + _, err := db.UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", ni}}) + return err +} + +/* GetInvoices queries the database and + * returns invoices based on the given filter + * if filter is nil every invoice is returned + */ +func getInvoices(filter bson.M) ([]Invoice, error) { + var invoices []Invoice + + cursor, err := db.Find(context.TODO(), filter) + if err != nil { + return invoices, err + } + + err = cursor.All(context.TODO(), &invoices) + return invoices, err +} + +func getInvoiceByNumber(invoiceNumber int) (Invoice, error) { + var invoice Invoice + err := db.FindOne(context.TODO(), bson.M{"InvoiceNumber": invoiceNumber}).Decode(&invoice) + return invoice, err +} + +func getInvoiceById(invoiceId primitive.ObjectID) (Invoice, error) { + var invoice Invoice + err := db.FindOne(context.TODO(), bson.M{"_id": invoiceId}).Decode(&invoice) + return invoice, err +} diff --git a/item/controller.go b/item/controller.go new file mode 100644 index 0000000..f8fe58e --- /dev/null +++ b/item/controller.go @@ -0,0 +1,91 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package item + +import ( + "github.com/gin-gonic/gin" + "go.mongodb.org/mongo-driver/bson/primitive" + "log" + "net/http" +) + +func getAll(ctx *gin.Context) { + items, err := getItems(nil) + if err != nil { + log.Printf("ERROR: Failed to read items from DB: %v\n", err.Error()) + ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } + + ctx.JSON(http.StatusOK, items) +} + +func save(ctx *gin.Context) { + var i Item + ctx.BindJSON(&i) + _, err := saveItem(i) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to add new item %v to DB: %v\n", i, err.Error()) + return + } + + log.Printf("Successfully saved new item to DB: %v", i) + ctx.JSON(http.StatusOK, nil) +} + +func modify(ctx *gin.Context) { + id := ctx.Param("itemId") + objectId, err := primitive.ObjectIDFromHex(id) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to modify item, Error parsing ID: %v\n", err.Error()) + return + } + + var i Item + ctx.BindJSON(&i) + err = modifyItem(objectId, i) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to modify item %v: %v\n", objectId, err.Error()) + return + } + + log.Printf("Modified item %v to %v.\n", objectId, i) + ctx.JSON(http.StatusOK, nil) +} + +func remove(ctx *gin.Context) { + id := ctx.Param("itemId") + objectId, err := primitive.ObjectIDFromHex(id) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete item, Error parsing ID: %v\n", err.Error()) + return + } + + err = deleteItem(objectId) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete item %v: %v\n", objectId, err.Error()) + return + } + + log.Printf("Deleted item %v from database.\n", objectId) + ctx.JSON(http.StatusOK, nil) +} diff --git a/item/db_actions.go b/item/db_actions.go deleted file mode 100644 index 36f8364..0000000 --- a/item/db_actions.go +++ /dev/null @@ -1,82 +0,0 @@ -/* OpenBills-server - Server for libre billing software OpenBills-web - * Copyright (C) 2022 Vidhu Kant Sharma - - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package item - -import ( - "context" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" - "github.com/MikunoNaka/OpenBills-server/database" - "github.com/MikunoNaka/OpenBills-server/brand" - "go.mongodb.org/mongo-driver/mongo" -) - -var brands *mongo.Collection = database.DB.Collection("Brands") - -// Add item to db -func saveItem(i Item) (primitive.ObjectID, error) { - res, err := db.InsertOne(context.TODO(), i) - return res.InsertedID.(primitive.ObjectID), err -} - -// Delete item from DB -func deleteItem(id primitive.ObjectID) error { - _, err := db.DeleteOne(context.TODO(), bson.M{"_id": id}) - return err -} - -// modify item in DB -func modifyItem(id primitive.ObjectID, ni Item) error { - _, err := db.UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", ni}}) - return err -} - -/* GetItems queries the database and - * returns items based on the given filter - * if filter is nil every item is returned - */ -func getItems(filter bson.M) ([]Item, error) { - var items []Item - - cursor, err := db.Find(context.TODO(), filter) - if err != nil { - return items, err - } - - err = cursor.All(context.TODO(), &items) - if err != nil { - return items, err - } - - for id, i := range items { - // continue if item doesn't have a brand - if (i.Brand.Id == primitive.ObjectID{}) { - continue - } - - var b brand.Brand - - err := brands.FindOne(context.TODO(), bson.M{"_id": i.Brand.Id}).Decode(&b) - if err != nil { - return items, err - } - items[id].Brand = b - } - - return items, err -} diff --git a/item/router.go b/item/router.go index c65af8f..614e7f2 100644 --- a/item/router.go +++ b/item/router.go @@ -18,84 +18,17 @@ package item import ( + //"github.com/MikunoNaka/OpenBills-server/util" "github.com/gin-gonic/gin" - "github.com/MikunoNaka/OpenBills-server/util" - "go.mongodb.org/mongo-driver/bson/primitive" - "log" - "net/http" ) func Routes(route *gin.Engine) { i := route.Group("/item") - i.Use(util.Authorize()) + //i.Use(util.Authorize()) { - // TODO: add functionality to filter results - // /all returns all the saved items - i.GET("/all", func(ctx *gin.Context) { - items, err := getItems(nil) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to read items from DB: %v\n", err.Error()) - return - } - - ctx.JSON(http.StatusOK, items) - }) - - i.POST("/new", func(ctx *gin.Context) { - var i Item - ctx.BindJSON(&i) - _, err := saveItem(i) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to add new item %v to DB: %v\n", i, err.Error()) - return - } - - log.Printf("Successfully saved new item to DB: %v", i) - ctx.JSON(http.StatusOK, nil) - }) - - i.PUT("/:itemId", func(ctx *gin.Context) { - id := ctx.Param("itemId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to modify item, Error parsing ID: %v\n", err.Error()) - return - } - - var i Item - ctx.BindJSON(&i) - err = modifyItem(objectId, i) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to modify item %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Modified item %v to %v.\n", objectId, i) - ctx.JSON(http.StatusOK, nil) - }) - - i.DELETE("/:itemId", func(ctx *gin.Context) { - id := ctx.Param("itemId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete item, Error parsing ID: %v\n", err.Error()) - return - } - - err = deleteItem(objectId) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete item %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Deleted item %v from database.\n", objectId ) - ctx.JSON(http.StatusOK, nil) - }) + i.GET("/all", getAll) // TODO: add functionality to filter results + i.POST("/new", save) + i.PUT("/:itemId", modify) + i.DELETE("/:itemId", remove) } } diff --git a/item/service.go b/item/service.go new file mode 100644 index 0000000..36f8364 --- /dev/null +++ b/item/service.go @@ -0,0 +1,82 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package item + +import ( + "context" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "github.com/MikunoNaka/OpenBills-server/database" + "github.com/MikunoNaka/OpenBills-server/brand" + "go.mongodb.org/mongo-driver/mongo" +) + +var brands *mongo.Collection = database.DB.Collection("Brands") + +// Add item to db +func saveItem(i Item) (primitive.ObjectID, error) { + res, err := db.InsertOne(context.TODO(), i) + return res.InsertedID.(primitive.ObjectID), err +} + +// Delete item from DB +func deleteItem(id primitive.ObjectID) error { + _, err := db.DeleteOne(context.TODO(), bson.M{"_id": id}) + return err +} + +// modify item in DB +func modifyItem(id primitive.ObjectID, ni Item) error { + _, err := db.UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", ni}}) + return err +} + +/* GetItems queries the database and + * returns items based on the given filter + * if filter is nil every item is returned + */ +func getItems(filter bson.M) ([]Item, error) { + var items []Item + + cursor, err := db.Find(context.TODO(), filter) + if err != nil { + return items, err + } + + err = cursor.All(context.TODO(), &items) + if err != nil { + return items, err + } + + for id, i := range items { + // continue if item doesn't have a brand + if (i.Brand.Id == primitive.ObjectID{}) { + continue + } + + var b brand.Brand + + err := brands.FindOne(context.TODO(), bson.M{"_id": i.Brand.Id}).Decode(&b) + if err != nil { + return items, err + } + items[id].Brand = b + } + + return items, err +} diff --git a/main.go b/main.go index a477e30..d309be4 100644 --- a/main.go +++ b/main.go @@ -18,14 +18,13 @@ package main import ( - "github.com/MikunoNaka/OpenBills-server/util" "github.com/MikunoNaka/OpenBills-server/brand" "github.com/MikunoNaka/OpenBills-server/client" "github.com/MikunoNaka/OpenBills-server/database" "github.com/MikunoNaka/OpenBills-server/invoice" "github.com/MikunoNaka/OpenBills-server/item" "github.com/MikunoNaka/OpenBills-server/user" - "github.com/MikunoNaka/OpenBills-server/auth" + "github.com/MikunoNaka/OpenBills-server/util" "github.com/gin-gonic/gin" ) @@ -39,10 +38,9 @@ func main() { client.Routes(r) invoice.Routes(r) user.Routes(r) - auth.Routes(r) // ping server and check if logged in - r.POST("/ping", util.Authorize(), func (ctx *gin.Context) { + r.POST("/ping", util.Authorize(), func(ctx *gin.Context) { ctx.Status(200) }) diff --git a/transport/controller.go b/transport/controller.go new file mode 100644 index 0000000..43b07ff --- /dev/null +++ b/transport/controller.go @@ -0,0 +1,57 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package transport + +import ( + "github.com/gin-gonic/gin" + "go.mongodb.org/mongo-driver/bson/primitive" + "log" + "net/http" +) + +func getAll(ctx *gin.Context) { + // TODO: add functionality to filter results + transports, err := getTransports(nil) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to read transport vehicles from DB: %v\n", err.Error()) + return + } + + ctx.JSON(http.StatusOK, transports) +} + +func remove(ctx *gin.Context) { + id := ctx.Param("transportId") + objectId, err := primitive.ObjectIDFromHex(id) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete transport vehicle, Error parsing ID: %v\n", err.Error()) + return + } + + err = deleteTransport(objectId) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete transport vehicle %v: %v\n", objectId, err.Error()) + return + } + + log.Printf("Deleted transport vehicle %v from database.\n", objectId) + ctx.JSON(http.StatusOK, nil) +} diff --git a/transport/router.go b/transport/router.go new file mode 100644 index 0000000..e515a8d --- /dev/null +++ b/transport/router.go @@ -0,0 +1,31 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package transport + +import ( + "github.com/MikunoNaka/OpenBills-server/util" + "github.com/gin-gonic/gin" +) + +func Routes(route *gin.Engine) { + t := route.Group("/transport", util.Authorize()) + { + t.GET("/all", getAll) + t.DELETE("/:transportId", remove) + } +} diff --git a/transport/service.go b/transport/service.go new file mode 100644 index 0000000..acd953e --- /dev/null +++ b/transport/service.go @@ -0,0 +1,52 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package transport + +import ( + "context" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +func saveTransport(t *Transport) (primitive.ObjectID, error) { + res, err := db.InsertOne(context.TODO(), t) + return res.InsertedID.(primitive.ObjectID), err +} + +func deleteTransport(id primitive.ObjectID) error { + _, err := db.DeleteOne(context.TODO(), bson.M{"_id": id}) + return err +} + +func modifyTransport(id primitive.ObjectID, nt Transport) error { + _, err := db.UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", nt}}) + return err +} + +func getTransports(filter bson.M) ([]Transport, error) { + var transports []Transport + + cursor, err := db.Find(context.TODO(), filter) + if err != nil { + return transports, err + } + + err = cursor.All(context.TODO(), &transports) + return transports, err +} diff --git a/transport/transport.go b/transport/transport.go new file mode 100644 index 0000000..2b281f5 --- /dev/null +++ b/transport/transport.go @@ -0,0 +1,36 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package transport + +import ( + "github.com/MikunoNaka/OpenBills-server/database" + t "github.com/MikunoNaka/OpenBills-server/transporter" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" +) + +var db *mongo.Collection = database.DB.Collection("Transport") + +// transport vehicle details +type Transport struct { + Id primitive.ObjectID `bson:"_id,omitempty" json:"Id"` + Transporter t.Transporter `bson:"Transporter,omitempty" json:"Transporter"` + VehicleNum string `bson:"VehicleNum" json:"VehicleNum"` + Note string `bson:"Note" json:"Note"` + TransportMethod string `bson:"TransportMethod" json:"TransportMethod"` +} diff --git a/transporter/controller.go b/transporter/controller.go new file mode 100644 index 0000000..0ba29a6 --- /dev/null +++ b/transporter/controller.go @@ -0,0 +1,57 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package transporter + +import ( + "github.com/gin-gonic/gin" + "go.mongodb.org/mongo-driver/bson/primitive" + "log" + "net/http" +) + +func getAll(ctx *gin.Context) { + // TODO: add functionality to filter results + transporters, err := getTransporters(nil) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to read transporters from DB: %v\n", err.Error()) + return + } + + ctx.JSON(http.StatusOK, transporters) +} + +func remove(ctx *gin.Context) { + id := ctx.Param("transporterId") + objectId, err := primitive.ObjectIDFromHex(id) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete transporter, Error parsing ID: %v\n", err.Error()) + return + } + + err = deleteTransporter(objectId) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete transporter %v: %v\n", objectId, err.Error()) + return + } + + log.Printf("Deleted transporter %v from database.\n", objectId) + ctx.JSON(http.StatusOK, nil) +} diff --git a/transporter/router.go b/transporter/router.go new file mode 100644 index 0000000..769d7fa --- /dev/null +++ b/transporter/router.go @@ -0,0 +1,31 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package transporter + +import ( + "github.com/MikunoNaka/OpenBills-server/util" + "github.com/gin-gonic/gin" +) + +func Routes(route *gin.Engine) { + t := route.Group("/transport", util.Authorize()) + { + t.GET("/all", getAll) + t.DELETE("/:transportId", remove) + } +} diff --git a/transporter/service.go b/transporter/service.go new file mode 100644 index 0000000..b5b4454 --- /dev/null +++ b/transporter/service.go @@ -0,0 +1,52 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package transporter + +import ( + "context" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +func saveTransporter(t Transporter) (primitive.ObjectID, error) { + res, err := db.InsertOne(context.TODO(), t) + return res.InsertedID.(primitive.ObjectID), err +} + +func deleteTransporter(id primitive.ObjectID) error { + _, err := db.DeleteOne(context.TODO(), bson.M{"_id": id}) + return err +} + +func modifyTransporter(id primitive.ObjectID, nt Transporter) error { + _, err := db.UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", nt}}) + return err +} + +func getTransporters(filter bson.M) ([]Transporter, error) { + var transporters []Transporter + + cursor, err := db.Find(context.TODO(), filter) + if err != nil { + return transporters, err + } + + err = cursor.All(context.TODO(), &transporters) + return transporters, err +} diff --git a/transporter/transporter.go b/transporter/transporter.go new file mode 100644 index 0000000..c8fffee --- /dev/null +++ b/transporter/transporter.go @@ -0,0 +1,39 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package transporter + +import ( + "github.com/MikunoNaka/OpenBills-server/database" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" +) + +var db *mongo.Collection = database.DB.Collection("Transporter") + +/* Transporter details can be stored in + * the DB. That is decided by the frontend. + * You can optionally store Transporter + * and Transport details which are often used + */ +type Transporter struct { + Id primitive.ObjectID `bson:"_id,omitempty" json:"Id"` + Name string `bson:"Name" json:"Name"` + GSTIN string `bson:"GSTIN" json:"GSTIN"` + // Issued ID for the transporter if any + TransporterId string `bson:"TransporterId,omitempty" json:"TransporterId"` +} diff --git a/user/controller.go b/user/controller.go new file mode 100644 index 0000000..df13a06 --- /dev/null +++ b/user/controller.go @@ -0,0 +1,105 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package user + +import ( + "errors" + "github.com/gin-gonic/gin" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "log" + "net/http" +) + +func getSelf(ctx *gin.Context) { + hex := ctx.MustGet("userId").(string) + id, err := primitive.ObjectIDFromHex(hex) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to modify user, Error parsing ID: %v\n", err.Error()) + return + } + + user, err := getUser(id) + if err != nil { + log.Printf("ERROR: Failed to read user %d info from DB: %v\n", id, err.Error()) + if errors.Is(err, mongo.ErrNoDocuments) { + ctx.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": err.Error()}) + } else { + ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + } + } + + ctx.JSON(http.StatusOK, user) +} + +func save(ctx *gin.Context) { + u := ctx.MustGet("user").(User) + // TODO: maybe add an invite code for some instances + + _, err := saveUser(u) + if err != nil { + log.Printf("ERROR: Failed to add new user %v to DB: %v\n", u, err.Error()) + ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "could not login"}) + } + + log.Printf("Successfully saved new user to DB: %s", u.UserName) + ctx.JSON(http.StatusOK, nil) +} + +func modify(ctx *gin.Context) { + id := ctx.Param("userId") + objectId, err := primitive.ObjectIDFromHex(id) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to modify user, Error parsing ID: %v\n", err.Error()) + return + } + + var u User + ctx.BindJSON(&u) + err = modifyUser(objectId, u) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to modify user %v: %v\n", objectId, err.Error()) + return + } + + log.Printf("Modified user %v to %v.\n", objectId, u) + ctx.JSON(http.StatusOK, nil) +} + +func remove(ctx *gin.Context) { + id := ctx.Param("userId") + objectId, err := primitive.ObjectIDFromHex(id) + if err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete user, Error parsing ID: %v\n", err.Error()) + return + } + + err = deleteUser(objectId) + if err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + log.Printf("ERROR: Failed to delete user %v: %v\n", objectId, err.Error()) + return + } + + log.Printf("Deleted user %v from database.\n", objectId) + ctx.JSON(http.StatusOK, nil) +} diff --git a/user/db_actions.go b/user/db_actions.go deleted file mode 100644 index 51490e7..0000000 --- a/user/db_actions.go +++ /dev/null @@ -1,60 +0,0 @@ -/* OpenBills-server - Server for libre billing software OpenBills-web - * Copyright (C) 2022 Vidhu Kant Sharma - - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package user - -import ( - "context" - "fmt" - "go.mongodb.org/mongo-driver/bson" - "go.mongodb.org/mongo-driver/bson/primitive" -) - -// Add user to db -func saveUser(u User) (primitive.ObjectID, error) { - err := u.hashPassword() - if err != nil { - return *new(primitive.ObjectID), err - } - res, err := db.InsertOne(context.TODO(), u) - return res.InsertedID.(primitive.ObjectID), err -} - -// Delete user from DB -func deleteUser(id primitive.ObjectID) error { - _, err := db.DeleteOne(context.TODO(), bson.M{"_id": id}) - return err -} - -// modify user in DB -func modifyUser(id primitive.ObjectID, nu User) error { - fmt.Println(nu.Password) - _, err := db.UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", nu}}) - return err -} - -// gets user info -func getUser(userId primitive.ObjectID) (User, error) { - var user User - err := db.FindOne(context.TODO(), bson.D{{"_id", userId}}).Decode(&user) - - // remove sensitive data - user.Password = "" - user.Sessions = []Session{} - - return user, err -} diff --git a/user/password.go b/user/password.go new file mode 100644 index 0000000..d667ebc --- /dev/null +++ b/user/password.go @@ -0,0 +1,70 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package user + +import ( + "github.com/gin-gonic/gin" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "golang.org/x/crypto/bcrypt" + "log" + "net/http" +) + +func checkPassword() gin.HandlerFunc { + return func(ctx *gin.Context) { + var u User + ctx.BindJSON(&u) + + filter := bson.M{ + "$or": []bson.M{ + // u.UserName in this case can be either username or email + {"Email": u.UserName}, + {"UserName": u.UserName}, + }, + } + + // check if the user exists in DB + var user User + err := db.FindOne(ctx, filter).Decode(&user) + if err != nil { + if err == mongo.ErrNoDocuments { + ctx.JSON(http.StatusNotFound, gin.H{"error": "user does not exist"}) + } else { + log.Printf("Error while reading user from DB to check password: %v", err.Error()) + ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal server error"}) + } + ctx.Abort() + } else { + // compare hash and password + err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(u.Password)) + if err != nil { + if err == bcrypt.ErrMismatchedHashAndPassword { + ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "incorrect password"}) + } else { + log.Printf("Error while checking password: %v", err.Error()) + ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "internal server error"}) + } + } + } + + // everything's fine! + ctx.Set("user", user) + ctx.Next() + } +} diff --git a/user/refresh.go b/user/refresh.go new file mode 100644 index 0000000..72a7655 --- /dev/null +++ b/user/refresh.go @@ -0,0 +1,117 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package user + +import ( + "context" + "errors" + "fmt" + "github.com/MikunoNaka/OpenBills-server/util" + "github.com/gin-gonic/gin" + "github.com/golang-jwt/jwt/v4" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "net/http" + "time" +) + +var ( + errUserNotFound error = errors.New("user does not exist") + refreshSecret []byte +) + +func init() { + conf := util.GetConfig().Crypto + refreshSecret = []byte(conf.RefreshTokenSecret) +} + +// middleware to check refresh token +func verifyRefreshToken() gin.HandlerFunc { + return func(ctx *gin.Context) { + refreshToken, err := ctx.Cookie("refreshToken") + fmt.Println(refreshToken) + if err == nil { + token, err := jwt.ParseWithClaims(refreshToken, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) { + return []byte(refreshSecret), nil + }) + if err != nil { // invalid token + ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "invalid token"}) + } else { // valid token + // convert id from string to ObjectID + id, _ := primitive.ObjectIDFromHex(token.Claims.(*jwt.StandardClaims).Issuer) + + // check if user exists + var u User + if err := db.FindOne(context.TODO(), bson.M{"_id": id}).Decode(&u); err != nil { + ctx.AbortWithStatusJSON(http.StatusNotFound, gin.H{"message": "user not found"}) + } else { + // check if this refreshToken is in DB + for _, i := range u.Sessions { + if i.Token == refreshToken { + ctx.Set("user", u) + ctx.Next() + } + } + ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "refresh token expired"}) + } + } + } else { + // invalid Authorization header + ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "not logged in"}) + } + } +} + +/* + * the refresh token has a long lifespan and is stored in + * the database in case it needs to be revoked. + * + * this can be stored as an HTTP only cookie and will be used + * when creating a new access token + * + * I'm using a different secret key for refresh tokens + * for enhanced security + */ +func newRefreshToken(userId string) (string, int64, error) { + // convert id from string to ObjectID + id, _ := primitive.ObjectIDFromHex(userId) + + // check if user exists + var u User + if err := db.FindOne(context.TODO(), bson.M{"_id": id}).Decode(&u); err != nil { + return "", 0, errUserNotFound + } + + // generate refresh token + expiresAt := time.Now().Add(time.Hour * 12).Unix() + claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{ + Issuer: userId, + ExpiresAt: expiresAt, + }) + token, err := claims.SignedString(refreshSecret) + if err != nil { + return "", expiresAt, err + } + + // store refresh token in db with unique session name for ease in identification + sessionName := time.Now().Format("01-02-2006.15:04:05") + "-" + u.UserName + u.Sessions = append(u.Sessions, Session{Name: sessionName, Token: token}) + db.UpdateOne(context.TODO(), bson.M{"_id": id}, bson.D{{"$set", u}}) + + return token, expiresAt, nil +} diff --git a/user/router.go b/user/router.go index 6e84185..ad9b4df 100644 --- a/user/router.go +++ b/user/router.go @@ -19,94 +19,15 @@ package user import ( "github.com/MikunoNaka/OpenBills-server/util" - "errors" "github.com/gin-gonic/gin" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/mongo" - "log" - "net/http" ) - func Routes(route *gin.Engine) { u := route.Group("/user") { - u.GET("/", util.Authorize(), func(ctx *gin.Context) { - hex := ctx.MustGet("userId").(string) - id, err := primitive.ObjectIDFromHex(hex) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to modify user, Error parsing ID: %v\n", err.Error()) - return - } - - user, err := getUser(id) - if err != nil { - log.Printf("ERROR: Failed to read user %d info from DB: %v\n", id, err.Error()) - if errors.Is(err, mongo.ErrNoDocuments) { - ctx.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": err.Error()}) - } else { - ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - } - } - - ctx.JSON(http.StatusOK, user) - }) - - u.POST("/new", validateMiddleware(), func(ctx *gin.Context) { - u := ctx.MustGet("user").(User) - // TODO: maybe add an invite code for some instances - - _, err := saveUser(u) - if err != nil { - log.Printf("ERROR: Failed to add new user %v to DB: %v\n", u, err.Error()) - ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "could not login"}) - } - - log.Printf("Successfully saved new user to DB: %s", u.UserName) - ctx.JSON(http.StatusOK, nil) - }) - - u.PUT("/:userId", func(ctx *gin.Context) { - id := ctx.Param("userId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to modify user, Error parsing ID: %v\n", err.Error()) - return - } - - var u User - ctx.BindJSON(&u) - err = modifyUser(objectId, u) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to modify user %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Modified user %v to %v.\n", objectId, u) - ctx.JSON(http.StatusOK, nil) - }) - - u.DELETE("/:userId", func(ctx *gin.Context) { - id := ctx.Param("userId") - objectId, err := primitive.ObjectIDFromHex(id) - if err != nil { - ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete user, Error parsing ID: %v\n", err.Error()) - return - } - - err = deleteUser(objectId) - if err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - log.Printf("ERROR: Failed to delete user %v: %v\n", objectId, err.Error()) - return - } - - log.Printf("Deleted user %v from database.\n", objectId ) - ctx.JSON(http.StatusOK, nil) - }) + u.GET("/", util.Authorize(), getSelf) + u.POST("/new", validateMiddleware(), save) + u.PUT("/:userId", checkPassword(), modify) + u.DELETE("/:userId", checkPassword(), remove) } } diff --git a/user/service.go b/user/service.go new file mode 100644 index 0000000..51490e7 --- /dev/null +++ b/user/service.go @@ -0,0 +1,60 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package user + +import ( + "context" + "fmt" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +// Add user to db +func saveUser(u User) (primitive.ObjectID, error) { + err := u.hashPassword() + if err != nil { + return *new(primitive.ObjectID), err + } + res, err := db.InsertOne(context.TODO(), u) + return res.InsertedID.(primitive.ObjectID), err +} + +// Delete user from DB +func deleteUser(id primitive.ObjectID) error { + _, err := db.DeleteOne(context.TODO(), bson.M{"_id": id}) + return err +} + +// modify user in DB +func modifyUser(id primitive.ObjectID, nu User) error { + fmt.Println(nu.Password) + _, err := db.UpdateOne(context.TODO(), bson.D{{"_id", id}}, bson.D{{"$set", nu}}) + return err +} + +// gets user info +func getUser(userId primitive.ObjectID) (User, error) { + var user User + err := db.FindOne(context.TODO(), bson.D{{"_id", userId}}).Decode(&user) + + // remove sensitive data + user.Password = "" + user.Sessions = []Session{} + + return user, err +} diff --git a/util/authorize.go b/util/authorize.go new file mode 100644 index 0000000..ca6660e --- /dev/null +++ b/util/authorize.go @@ -0,0 +1,68 @@ +/* OpenBills-server - Server for libre billing software OpenBills-web + * Copyright (C) 2022 Vidhu Kant Sharma + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package util + +import ( + "github.com/gin-gonic/gin" + "github.com/golang-jwt/jwt/v4" + "net/http" + "time" +) + +var accessSecret []byte + +func init() { + conf := GetConfig().Crypto + accessSecret = []byte(conf.AccessTokenSecret) +} + +func Authorize() gin.HandlerFunc { + return func(ctx *gin.Context) { + tokenHeader := ctx.Request.Header["Authorization"] + if tokenHeader != nil { + token, err := jwt.ParseWithClaims(tokenHeader[0], &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) { + return []byte(accessSecret), nil + }) + if err != nil { + ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "access token expired"}) + } else { + ctx.Set("userId", token.Claims.(*jwt.StandardClaims).Issuer) + ctx.Next() + } + } else { + // invalid Authorization header + ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "not logged in"}) + } + + } +} + +// generate new access token +func newAccessToken(userId string) (string, error) { + claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{ + Issuer: userId, + ExpiresAt: time.Now().Add(time.Second * 15).Unix(), + }) + + token, err := claims.SignedString(accessSecret) + if err != nil { + return "", err + } + + return token, nil +} diff --git a/util/jwt_middleware.go b/util/jwt_middleware.go deleted file mode 100644 index ce8c20a..0000000 --- a/util/jwt_middleware.go +++ /dev/null @@ -1,51 +0,0 @@ -/* OpenBills-server - Server for libre billing software OpenBills-web - * Copyright (C) 2022 Vidhu Kant Sharma - - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package util - -import ( - "github.com/golang-jwt/jwt/v4" - "github.com/gin-gonic/gin" - "net/http" -) - -var accessSecret []byte -func init() { - conf := GetConfig().Crypto - accessSecret = []byte(conf.AccessTokenSecret) -} - -func Authorize() gin.HandlerFunc { - return func(ctx *gin.Context) { - tokenHeader := ctx.Request.Header["Authorization"] - if tokenHeader != nil { - token, err := jwt.ParseWithClaims(tokenHeader[0], &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) { - return []byte(accessSecret), nil - }) - if err != nil { - ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "access token expired"}) - } else { - ctx.Set("userId", token.Claims.(*jwt.StandardClaims).Issuer) - ctx.Next() - } - } else { - // invalid Authorization header - ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "not logged in"}) - } - - } -} -- cgit v1.2.3