diff options
author | Vidhu Kant Sharma <vidhukant@vidhukant.xyz> | 2023-01-28 23:32:41 +0530 |
---|---|---|
committer | Vidhu Kant Sharma <vidhukant@vidhukant.xyz> | 2023-01-28 23:32:41 +0530 |
commit | 0607478f1e4c86619a606af7876a6625e859ee1a (patch) | |
tree | 308c7a03e911994452a903d029c8cacd9a824d32 | |
parent | 31e9605652faf350291634f5a2d642573f320e66 (diff) |
created endpoint to get logged in user's info
-rwxr-xr-x | OpenBills-server | bin | 0 -> 21606675 bytes | |||
-rw-r--r-- | auth/refresh_middleware.go (renamed from auth/jwt_middleware.go) | 44 | ||||
-rw-r--r-- | brand/router.go | 4 | ||||
-rw-r--r-- | client/router.go | 4 | ||||
-rw-r--r-- | invoice/router.go | 4 | ||||
-rw-r--r-- | item/router.go | 4 | ||||
-rw-r--r-- | main.go | 4 | ||||
-rw-r--r-- | user/db_actions.go | 12 | ||||
-rw-r--r-- | user/router.go | 28 | ||||
-rw-r--r-- | user/user.go | 2 | ||||
-rw-r--r-- | util/jwt_middleware.go | 51 |
11 files changed, 104 insertions, 53 deletions
diff --git a/OpenBills-server b/OpenBills-server Binary files differnew file mode 100755 index 0000000..88d150e --- /dev/null +++ b/OpenBills-server diff --git a/auth/jwt_middleware.go b/auth/refresh_middleware.go index 8dd77b8..00f73bf 100644 --- a/auth/jwt_middleware.go +++ b/auth/refresh_middleware.go @@ -1,53 +1,15 @@ -/* 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 auth import ( - "github.com/MikunoNaka/OpenBills-server/user" + "github.com/golang-jwt/jwt/v4" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/bson" - "github.com/golang-jwt/jwt/v4" + "github.com/MikunoNaka/OpenBills-server/user" "github.com/gin-gonic/gin" - "net/http" "context" + "net/http" ) -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"}) - } - - } -} - func verifyRefreshToken() gin.HandlerFunc { return func(ctx *gin.Context) { refreshToken, err := ctx.Cookie("refreshToken") diff --git a/brand/router.go b/brand/router.go index b5522dc..5c9c7af 100644 --- a/brand/router.go +++ b/brand/router.go @@ -18,7 +18,7 @@ package brand import ( - "github.com/MikunoNaka/OpenBills-server/auth" + "github.com/MikunoNaka/OpenBills-server/util" "github.com/gin-gonic/gin" "go.mongodb.org/mongo-driver/bson/primitive" "log" @@ -28,7 +28,7 @@ import ( func Routes(route *gin.Engine) { b := route.Group("/brand") - b.Use(auth.Authorize()) + b.Use(util.Authorize()) { b.GET("/all", func(ctx *gin.Context) { // TODO: add functionality to filter results diff --git a/client/router.go b/client/router.go index 0e5663b..232ad83 100644 --- a/client/router.go +++ b/client/router.go @@ -18,7 +18,7 @@ package client import ( - "github.com/MikunoNaka/OpenBills-server/auth" + "github.com/MikunoNaka/OpenBills-server/util" "github.com/gin-gonic/gin" "log" "net/http" @@ -27,7 +27,7 @@ import ( func Routes(route *gin.Engine) { c := route.Group("/client") - c.Use(auth.Authorize()) + c.Use(util.Authorize()) { c.GET("/all", func(ctx *gin.Context) { // TODO: add functionality to filter results diff --git a/invoice/router.go b/invoice/router.go index ffa8ed3..c89d667 100644 --- a/invoice/router.go +++ b/invoice/router.go @@ -18,7 +18,7 @@ package invoice import ( - "github.com/MikunoNaka/OpenBills-server/auth" + "github.com/MikunoNaka/OpenBills-server/util" "github.com/gin-gonic/gin" "log" "errors" @@ -29,7 +29,7 @@ import ( func Routes(route *gin.Engine) { i := route.Group("/invoice") - i.Use(auth.Authorize()) + i.Use(util.Authorize()) { i.GET("/all", func(ctx *gin.Context) { // TODO: add functionality to filter results diff --git a/item/router.go b/item/router.go index 4cdd633..c65af8f 100644 --- a/item/router.go +++ b/item/router.go @@ -19,7 +19,7 @@ package item import ( "github.com/gin-gonic/gin" - "github.com/MikunoNaka/OpenBills-server/auth" + "github.com/MikunoNaka/OpenBills-server/util" "go.mongodb.org/mongo-driver/bson/primitive" "log" "net/http" @@ -27,7 +27,7 @@ import ( func Routes(route *gin.Engine) { i := route.Group("/item") - i.Use(auth.Authorize()) + i.Use(util.Authorize()) { // TODO: add functionality to filter results // /all returns all the saved items @@ -18,7 +18,7 @@ package main import ( - _ "github.com/MikunoNaka/OpenBills-server/util" + "github.com/MikunoNaka/OpenBills-server/util" "github.com/MikunoNaka/OpenBills-server/brand" "github.com/MikunoNaka/OpenBills-server/client" "github.com/MikunoNaka/OpenBills-server/database" @@ -42,7 +42,7 @@ func main() { auth.Routes(r) // ping server and check if logged in - r.POST("/ping", auth.Authorize(), func (ctx *gin.Context) { + r.POST("/ping", util.Authorize(), func (ctx *gin.Context) { ctx.Status(200) }) diff --git a/user/db_actions.go b/user/db_actions.go index 2d89b7e..51490e7 100644 --- a/user/db_actions.go +++ b/user/db_actions.go @@ -46,3 +46,15 @@ func modifyUser(id primitive.ObjectID, nu User) error { _, 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/router.go b/user/router.go index 15d6efb..6e84185 100644 --- a/user/router.go +++ b/user/router.go @@ -18,8 +18,11 @@ 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" ) @@ -28,15 +31,36 @@ import ( 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 { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": "could not login"}) log.Printf("ERROR: Failed to add new user %v to DB: %v\n", u, err.Error()) - return + ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "could not login"}) } log.Printf("Successfully saved new user to DB: %s", u.UserName) diff --git a/user/user.go b/user/user.go index 4c41f24..30ae333 100644 --- a/user/user.go +++ b/user/user.go @@ -28,6 +28,8 @@ var db *mongo.Collection = database.DB.Collection("Users") // per-user config can be shared to DB type Config struct { + // just CSS variable overrides for the frontend + Styling string `bson:"Styling" json:"Styling"` } type Session struct { diff --git a/util/jwt_middleware.go b/util/jwt_middleware.go new file mode 100644 index 0000000..ce8c20a --- /dev/null +++ b/util/jwt_middleware.go @@ -0,0 +1,51 @@ +/* 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 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"}) + } + + } +} |