Skip to content

Commit

Permalink
added space validation for tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
vsumit89 committed Sep 6, 2022
1 parent d11fa79 commit 797e06d
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
61 changes: 61 additions & 0 deletions server/action/organisation/application/space/token/validate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package token

import (
"encoding/json"
"errors"
"net/http"
"strconv"

"github.com/factly/kavach-server/model"
"github.com/factly/x/errorx"
"github.com/factly/x/loggerx"
"github.com/factly/x/renderx"
"github.com/factly/x/validationx"
"github.com/go-chi/chi"
)

type ValidationBody struct {
Token string `json:"token" validate:"required"`
}

func Validate(w http.ResponseWriter, r *http.Request) {
sID := chi.URLParam(r, "space_id")
spaceID, err := strconv.Atoi(sID)
if err != nil {
loggerx.Error(err)
errorx.Render(w, errorx.Parser(errorx.InvalidID()))
return
}

tokenBody := ValidationBody{}
err = json.NewDecoder(r.Body).Decode(&tokenBody)
if err != nil {
loggerx.Error(err)
errorx.Render(w, errorx.Parser(errorx.DecodeError()))
return
}

validationError := validationx.Check(tokenBody)
if validationError != nil {
loggerx.Error(errors.New("validation error"))
errorx.Render(w, validationError)
return
}

spaceToken := model.SpaceToken{}
err = model.DB.Model(&model.SpaceToken{}).Where(&model.SpaceToken{
Token: tokenBody.Token,
}).Find(&spaceToken).Error
if err != nil {
loggerx.Error(err)
errorx.Render(w, errorx.Parser(errorx.Unauthorized()))
return
}

if spaceToken.SpaceID != uint(spaceID) {
renderx.JSON(w, http.StatusUnauthorized, map[string]interface{}{"valid": false})
return
}

renderx.JSON(w, http.StatusOK, map[string]interface{}{"valid": true})
}
4 changes: 2 additions & 2 deletions server/action/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (

"github.com/factly/kavach-server/action/medium"
"github.com/factly/kavach-server/action/organisation"
"github.com/factly/kavach-server/action/organisation/application/token"
"github.com/factly/kavach-server/action/organisation/application/space/token"
"github.com/factly/kavach-server/action/profile"
"github.com/factly/kavach-server/action/user"
"github.com/factly/kavach-server/action/util"
Expand Down Expand Up @@ -43,7 +43,7 @@ func RegisterRoutes() http.Handler {
r.Mount("/profile", profile.Router())
r.Mount("/media", medium.Router())
r.Mount("/util", util.Router())
r.Post("/applications/{application_slug}/validateToken", token.Validate)
r.Post("/spaces/{space_id}/validateToken", token.Validate)

sqlDB, _ := model.DB.DB()

Expand Down

0 comments on commit 797e06d

Please sign in to comment.