Skip to content

Commit

Permalink
Merge pull request #745 from factly/kavach-policies
Browse files Browse the repository at this point in the history
latest kavach changes
  • Loading branch information
shreeharsha-factly authored Sep 7, 2022
2 parents 05c7c99 + c3d7069 commit cc3467e
Show file tree
Hide file tree
Showing 163 changed files with 4,304 additions and 1,179 deletions.
2 changes: 1 addition & 1 deletion api/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.18
require (
github.com/99designs/gqlgen v0.17.12
github.com/DATA-DOG/go-sqlmock v1.5.0
github.com/factly/x v0.0.77
github.com/factly/x v0.0.84
github.com/gavv/httpexpect/v2 v2.2.0
github.com/go-chi/chi v4.1.2+incompatible
github.com/go-chi/cors v1.1.1
Expand Down
4 changes: 4 additions & 0 deletions api/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@ github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7
github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0=
github.com/factly/x v0.0.77 h1:HQXTOLTpPWZhNhCC3TwLQk9nfKlJqzSYjjrCQ20p57o=
github.com/factly/x v0.0.77/go.mod h1:ZB3evopCd4ev4uZNCxldkh0AgYsxvEabiefrM8RJHBc=
github.com/factly/x v0.0.83 h1:p+/p/QhxWN2DYRuxeRYk5KV27dH+JFjXwKXQAPGIedk=
github.com/factly/x v0.0.83/go.mod h1:ZB3evopCd4ev4uZNCxldkh0AgYsxvEabiefrM8RJHBc=
github.com/factly/x v0.0.84 h1:tMVbLGAoF6gqZqFNiPY5zAybp7N2XwOolaukFBEYgxg=
github.com/factly/x v0.0.84/go.mod h1:ZB3evopCd4ev4uZNCxldkh0AgYsxvEabiefrM8RJHBc=
github.com/fasthttp/websocket v1.4.2 h1:AU/zSiIIAuJjBMf5o+vO0syGOnEfvZRu40xIhW/3RuM=
github.com/fasthttp/websocket v1.4.2/go.mod h1:smsv/h4PBEBaU0XDTY5UwJTpZv69fQ0FfcLJr21mA6Y=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
Expand Down
3 changes: 2 additions & 1 deletion api/graph/loaders/dataloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/factly/dega-api/graph/models"
"github.com/factly/dega-api/graph/validator"
"github.com/factly/dega-api/util"
httpx "github.com/factly/dega-api/util/httpx"
"github.com/spf13/viper"
)

Expand Down Expand Up @@ -323,7 +324,7 @@ func DataloaderMiddleware(next http.Handler) http.Handler {
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-User", fmt.Sprint(keys[0]))
client := &http.Client{}
client := httpx.CustomHttpClient()
resp, err := client.Do(req)

if err != nil {
Expand Down
3 changes: 2 additions & 1 deletion api/graph/resolvers/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,12 @@ func (r *queryResolver) Posts(ctx context.Context, spaces []int, formats *models
if err != nil {
return nil, err
}

oID, err := validator.GetOrganisation(ctx)
if err != nil {
return nil, err
}

columns := []string{"created_at", "updated_at", "name", "slug"}
pageSortBy := "created_at"
pageSortOrder := "desc"
Expand Down
2 changes: 1 addition & 1 deletion api/graph/resolvers/sitemap.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ func (r *sitemapResolver) PublishedDate(ctx context.Context, obj *models.Sitemap

func (r *Resolver) Sitemap() generated.SitemapResolver { return &sitemapResolver{r} }

type sitemapResolver struct{ *Resolver }
type sitemapResolver struct{ *Resolver }
3 changes: 2 additions & 1 deletion api/graph/resolvers/sitemaps.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/factly/dega-api/graph/generated"
"github.com/factly/dega-api/graph/models"
"github.com/factly/dega-api/graph/validator"
"github.com/factly/dega-api/util/httpx"
"github.com/spf13/viper"
)

Expand Down Expand Up @@ -104,7 +105,7 @@ func (r *sitemapsResolver) Users(ctx context.Context, obj *models.Sitemaps) ([]*

req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-User", fmt.Sprint(postAuthor.AuthorID))
client := &http.Client{}
client := httpx.CustomHttpClient()
resp, err := client.Do(req)

if err != nil {
Expand Down
47 changes: 40 additions & 7 deletions api/graph/validator/organisation.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ package validator

import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"

"github.com/factly/dega-api/config"
"github.com/factly/dega-api/graph/models"
"github.com/factly/dega-api/util/httpx"
"github.com/factly/x/errorx"
"github.com/factly/x/loggerx"
"github.com/spf13/viper"
)

type ctxKeyOrganisationID int
Expand All @@ -25,16 +29,20 @@ func CheckOrganisation() func(http.Handler) http.Handler {
return
}

space := &models.Space{}
space.ID = spaceID

err = config.DB.First(&space).Error
token, err := GetSpaceToken(ctx)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}

ctx = context.WithValue(ctx, OrgIDKey, space.OrganisationID)
organisationID, err := GetOrganisationIDfromSpaceID(uint(spaceID), token)
if err != nil {
loggerx.Error(err)
errorx.Render(w, errorx.Parser(errorx.InternalServerError()))
return
}

ctx = context.WithValue(ctx, OrgIDKey, organisationID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
Expand All @@ -51,3 +59,28 @@ func GetOrganisation(ctx context.Context) (int, error) {
}
return 0, errors.New("something went wrong")
}

func GetOrganisationIDfromSpaceID(spaceID uint, token string) (int, error) {
req, err := http.NewRequest(http.MethodGet, viper.GetString("kavach_url")+fmt.Sprintf("/util/space/%d/getOrganisationUsingToken", spaceID), nil)
if err != nil {
return 0, err
}
req.Header.Set("X-Space-Token", token)
client := httpx.CustomHttpClient()
response, err := client.Do(req)
if err != nil {
return 0, err
}
defer response.Body.Close()
responseBody := map[string]interface{}{}
err = json.NewDecoder(response.Body).Decode(&responseBody)
if err != nil {
return 0, err
}

if response.StatusCode != 200 {
return 0, errors.New("internal server error on kavach while getting organisation id from space id")
}
organisationID := int(responseBody["organisation_id"].(float64))
return organisationID, nil
}
47 changes: 43 additions & 4 deletions api/graph/validator/space.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,25 @@ package validator
import (
"context"
"errors"
"fmt"

"net/http"
"strconv"

"github.com/factly/x/requestx"
"github.com/spf13/viper"
)

type ctxKeySpaceID int
type ctxKeyToken string

// SpaceIDKey is the key that holds the unique space ID in a request context.
const SpaceIDKey ctxKeySpaceID = 0
const TokenIDKey ctxKeyToken = "spaceToken"

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

// CheckSpace - to check Space in header
func CheckSpace() func(http.Handler) http.Handler {
Expand All @@ -22,14 +33,31 @@ func CheckSpace() func(http.Handler) http.Handler {
return
}

sid, err := strconv.Atoi(space)
if err != nil || sid == 0 {
sID, err := strconv.Atoi(space)
if err != nil || sID == 0 {
w.WriteHeader(http.StatusUnauthorized)
return
}
ctx := r.Context()

ctx = context.WithValue(ctx, SpaceIDKey, sid)
authHeader := r.Header.Get("X-Dega-API-Key")
if authHeader == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}

tokenBody := ValidationBody{
Token: authHeader,
}

res, err := requestx.Request("POST", viper.GetString("kavach_url")+"/spaces/"+fmt.Sprintf("%d", sID)+"/validateToken", tokenBody, nil)
if err != nil || res.StatusCode != http.StatusOK {
w.WriteHeader(http.StatusUnauthorized)
return
}

ctx := r.Context()
ctx = context.WithValue(ctx, SpaceIDKey, sID)
ctx = context.WithValue(ctx, TokenIDKey, authHeader)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
Expand All @@ -46,3 +74,14 @@ func GetSpace(ctx context.Context) (uint, error) {
}
return 0, errors.New("something went wrong")
}

func GetSpaceToken(ctx context.Context) (string, error) {
if ctx == nil {
return "", errors.New("context not found")
}
token := ctx.Value(TokenIDKey)
if token != nil {
return token.(string), nil
}
return "", errors.New("something went wrong")
}
3 changes: 1 addition & 2 deletions api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"github.com/factly/x/healthx"
"github.com/factly/x/loggerx"
"github.com/factly/x/meilisearchx"
"github.com/factly/x/middlewarex"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/viper"

Expand Down Expand Up @@ -79,7 +78,7 @@ func main() {

srv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &resolvers.Resolver{}}))

r := router.With(validator.CheckSpace(), validator.CheckOrganisation(), middlewarex.ValidateAPIToken("X-Dega-API-Key", "dega", validator.GetOrganisation))
r := router.With(validator.CheckSpace(), validator.CheckOrganisation())

if cache.IsEnabled() {
r = r.With(cache.CachingMiddleware(), cache.RespMiddleware)
Expand Down
12 changes: 12 additions & 0 deletions api/util/httpx/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package httpx

import (
"net/http"
"time"
)

const httpTimeout = 10

func CustomHttpClient() *http.Client {
return &http.Client{Timeout: time.Minute * time.Duration(httpTimeout)}
}
50 changes: 50 additions & 0 deletions config.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
MODE=development

# dependencies services
KAVACH_URL=http://kavach-server:8000
IMAGEPROXY_URL=http://127.0.0.1:7001
KETO_URL=http://keto:4466
NATS_URL=http://nats:4222
KRATOS_PUBLIC_URL=http://kratos:4433
IFRAMELY_URL=http://iframely:8061
OATHKEEPER_HOST=oathkeeper:4455

GOOGLE_KEY=GOOGLE_KEY # for google fact checks search

# database params
DATABASE_HOST=postgres
DATABASE_USER=postgres
DATABASE_PASSWORD=postgres
DATABASE_NAME=dega
DATABASE_PORT=5432
DATABASE_SSL_MODE=disable

# set this to true if want to use sqlite db
USE_SQLITE=false
SQLITE_DB_PATH=dega.db

TEMPLATES_PATH=web/templates/*

DEFAULT_NUMBER_OF_MEDIA=10
DEFAULT_NUMBER_OF_SPACES=2
DEFAULT_NUMBER_OF_POSTS=10

CREATE_SUPER_ORGANISATION=true # give SUPER_ORGANISATION_TITLE, DEFAULT_USER_EMAIL & DEFAULT_USER_PASSWORD
SUPER_ORGANISATION_TITLE='Dega Administration'
DEFAULT_USER_EMAIL=admin@dega.in
DEFAULT_USER_PASSWORD=2ssad32sadADSd@!@4

ENABLE_HUKZ=true # include hukz in docker-compose and give HUKZ_URL, NATS_URL, NATS_USER_NAME & NATS_USER_PASSWORD
ENABLE_FEEDS=true
ENABLE_SEARCH_INDEXING=true # include meilisearch in docker-compost and give MEILI_KEY & MEILI_URL

MEILI_URL=http://meilisearch:7700
MEILI_KEY=password

NATS_URL=nats://nats:4222
NATS_USER_NAME=natsuser
NATS_USER_PASSWORD=natspassword
HUKZ_URL=http://hukz:8000

DEGA_APPLICATION_ID=1
ORGANISATION_PERMISSION_ENABLED=false
Loading

0 comments on commit cc3467e

Please sign in to comment.