summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorVidhu Kant Sharma <vidhukant@vidhukant.xyz>2023-01-29 20:11:09 +0530
committerVidhu Kant Sharma <vidhukant@vidhukant.xyz>2023-01-29 20:11:09 +0530
commitac7aa8c6e95023def1eba7615d8a42ad52271500 (patch)
treeb3477a9d3ae39244a759b19fe42e7d3bccbda38d
parent0607478f1e4c86619a606af7876a6625e859ee1a (diff)
checking password before editing/deleting user
-rw-r--r--auth/refresh_middleware.go47
-rw-r--r--auth/router.go (renamed from auth/auth.go)18
-rw-r--r--brand/controller.go93
-rw-r--r--brand/router.go80
-rw-r--r--brand/service.go (renamed from brand/db_actions.go)0
-rw-r--r--client/controller.go93
-rw-r--r--client/router.go79
-rw-r--r--client/service.go (renamed from client/db_actions.go)0
-rw-r--r--invoice/controller.go95
-rw-r--r--invoice/db_actions.go131
-rw-r--r--invoice/invoice.go101
-rw-r--r--invoice/router.go152
-rw-r--r--invoice/service.go68
-rw-r--r--item/controller.go91
-rw-r--r--item/router.go79
-rw-r--r--item/service.go (renamed from item/db_actions.go)0
-rw-r--r--main.go6
-rw-r--r--transport/controller.go57
-rw-r--r--transport/router.go31
-rw-r--r--transport/service.go52
-rw-r--r--transport/transport.go36
-rw-r--r--transporter/controller.go57
-rw-r--r--transporter/router.go31
-rw-r--r--transporter/service.go52
-rw-r--r--transporter/transporter.go39
-rw-r--r--user/controller.go105
-rw-r--r--user/password.go (renamed from auth/password_middleware.go)41
-rw-r--r--user/refresh.go (renamed from auth/jwt.go)70
-rw-r--r--user/router.go87
-rw-r--r--user/service.go (renamed from user/db_actions.go)0
-rw-r--r--util/authorize.go (renamed from util/jwt_middleware.go)27
31 files changed, 1061 insertions, 757 deletions
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/auth.go b/auth/router.go
index 1048f82..9fa03b7 100644
--- a/auth/auth.go
+++ b/auth/router.go
@@ -18,29 +18,25 @@
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"
+ "github.com/gin-gonic/gin"
"log"
+ "net/http"
)
-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) {
+ r.POST("/login", user.checkPassword(), func(ctx *gin.Context) {
user := ctx.MustGet("user").(user.User)
- accessToken, err := newAccessToken(user.Id.Hex())
+ 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 := newRefreshToken(user.Id.Hex())
+ 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)"})
@@ -50,9 +46,9 @@ func Routes(route *gin.Engine) {
ctx.JSON(http.StatusOK, gin.H{"accessToken": accessToken})
})
- r.POST("/refresh", verifyRefreshToken(), func (ctx *gin.Context) {
+ r.POST("/refresh", user.verifyRefreshToken(), func(ctx *gin.Context) {
u := ctx.MustGet("user").(user.User)
- accessToken, err := newAccessToken(u.Id.Hex())
+ 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)"})
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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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/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/db_actions.go b/brand/service.go
index eb5961c..eb5961c 100644
--- a/brand/db_actions.go
+++ b/brand/service.go
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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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/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/db_actions.go b/client/service.go
index bf32d97..bf32d97 100644
--- a/client/db_actions.go
+++ b/client/service.go
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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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 <vidhukant@vidhukant.xyz>
-
- * 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 <https://www.gnu.org/licenses/>.
- */
-
-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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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/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/db_actions.go b/item/service.go
index 36f8364..36f8364 100644
--- a/item/db_actions.go
+++ b/item/service.go
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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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 <vidhukant@vidhukant.xyz>
+
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+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/auth/password_middleware.go b/user/password.go
index 3fda389..d667ebc 100644
--- a/auth/password_middleware.go
+++ b/user/password.go
@@ -15,35 +15,33 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
-package auth
+package user
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"
+ "golang.org/x/crypto/bcrypt"
+ "log"
+ "net/http"
)
func checkPassword() gin.HandlerFunc {
return func(ctx *gin.Context) {
- var u user.User
- ctx.BindJSON(&u)
+ var u User
+ ctx.BindJSON(&u)
filter := bson.M{
"$or": []bson.M{
- // u.UserName in this case can be either username or email
+ // 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)
+ 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"})
@@ -53,17 +51,16 @@ func checkPassword() gin.HandlerFunc {
}
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()
- }
+ // 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!
diff --git a/auth/jwt.go b/user/refresh.go
index 66a4f12..72a7655 100644
--- a/auth/jwt.go
+++ b/user/refresh.go
@@ -15,44 +15,66 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
-package auth
+package user
import (
- "github.com/MikunoNaka/OpenBills-server/user"
+ "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"
-
- "context"
- "errors"
+ "net/http"
"time"
)
var (
- errUserNotFound error = errors.New("user does not exist")
+ errUserNotFound error = errors.New("user does not exist")
+ refreshSecret []byte
)
-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
+// 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"})
+ }
}
-
- return token, nil
}
/*
@@ -70,15 +92,15 @@ func newRefreshToken(userId string) (string, int64, error) {
id, _ := primitive.ObjectIDFromHex(userId)
// check if user exists
- var u user.User
+ 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,
+ claims := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{
+ Issuer: userId,
ExpiresAt: expiresAt,
})
token, err := claims.SignedString(refreshSecret)
@@ -88,7 +110,7 @@ func newRefreshToken(userId string) (string, int64, error) {
// 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})
+ 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/db_actions.go b/user/service.go
index 51490e7..51490e7 100644
--- a/user/db_actions.go
+++ b/user/service.go
diff --git a/util/jwt_middleware.go b/util/authorize.go
index ce8c20a..ca6660e 100644
--- a/util/jwt_middleware.go
+++ b/util/authorize.go
@@ -18,12 +18,14 @@
package util
import (
- "github.com/golang-jwt/jwt/v4"
"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)
@@ -39,13 +41,28 @@ func Authorize() gin.HandlerFunc {
if err != nil {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "access token expired"})
} else {
- ctx.Set("userId", token.Claims.(*jwt.StandardClaims).Issuer)
- ctx.Next()
+ ctx.Set("userId", token.Claims.(*jwt.StandardClaims).Issuer)
+ ctx.Next()
}
} else {
- // invalid Authorization header
- ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "not logged in"})
+ // 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
+}