summaryrefslogtreecommitdiff
path: root/user/router.go
diff options
context:
space:
mode:
authorVidhu Kant Sharma <vidhukant@vidhukant.xyz>2023-01-28 23:32:41 +0530
committerVidhu Kant Sharma <vidhukant@vidhukant.xyz>2023-01-28 23:32:41 +0530
commit0607478f1e4c86619a606af7876a6625e859ee1a (patch)
tree308c7a03e911994452a903d029c8cacd9a824d32 /user/router.go
parent31e9605652faf350291634f5a2d642573f320e66 (diff)
created endpoint to get logged in user's info
Diffstat (limited to 'user/router.go')
-rw-r--r--user/router.go28
1 files changed, 26 insertions, 2 deletions
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)