From 0607478f1e4c86619a606af7876a6625e859ee1a Mon Sep 17 00:00:00 2001 From: Vidhu Kant Sharma Date: Sat, 28 Jan 2023 23:32:41 +0530 Subject: created endpoint to get logged in user's info --- OpenBills-server | Bin 0 -> 21606675 bytes auth/jwt_middleware.go | 85 --------------------------------------------- auth/refresh_middleware.go | 47 +++++++++++++++++++++++++ brand/router.go | 4 +-- client/router.go | 4 +-- invoice/router.go | 4 +-- item/router.go | 4 +-- main.go | 4 +-- user/db_actions.go | 12 +++++++ user/router.go | 28 +++++++++++++-- user/user.go | 2 ++ util/jwt_middleware.go | 51 +++++++++++++++++++++++++++ 12 files changed, 148 insertions(+), 97 deletions(-) create mode 100755 OpenBills-server delete mode 100644 auth/jwt_middleware.go create mode 100644 auth/refresh_middleware.go create mode 100644 util/jwt_middleware.go diff --git a/OpenBills-server b/OpenBills-server new file mode 100755 index 0000000..88d150e Binary files /dev/null and b/OpenBills-server differ diff --git a/auth/jwt_middleware.go b/auth/jwt_middleware.go deleted file mode 100644 index 8dd77b8..0000000 --- a/auth/jwt_middleware.go +++ /dev/null @@ -1,85 +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" - "go.mongodb.org/mongo-driver/bson/primitive" - "go.mongodb.org/mongo-driver/bson" - "github.com/golang-jwt/jwt/v4" - "github.com/gin-gonic/gin" - "net/http" - "context" -) - -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") - 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/refresh_middleware.go b/auth/refresh_middleware.go new file mode 100644 index 0000000..00f73bf --- /dev/null +++ b/auth/refresh_middleware.go @@ -0,0 +1,47 @@ +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/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 diff --git a/main.go b/main.go index 76fb534..a477e30 100644 --- a/main.go +++ b/main.go @@ -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 + + * 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