Skip to content

Commit

Permalink
Merge pull request #89 from Klaven/dashboard-api
Browse files Browse the repository at this point in the history
Dashboard api
  • Loading branch information
Klaven authored Mar 12, 2024
2 parents 0b93d7b + 14c465d commit a0e1782
Show file tree
Hide file tree
Showing 8 changed files with 83 additions and 41 deletions.
4 changes: 0 additions & 4 deletions .github/workflows/update-dev-manifets.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,6 @@ jobs:
working-directory: ./deployments/null-cloud/base/null-operator/dev/
run: |
kustomize edit set image nullchannel/eddington-null-operator:${{ github.sha }}
- name: update image tag for ui
working-directory: ./deployments/null-cloud/base/ui/dev/
run: |
kustomize edit set image eddington-ui:${{ github.sha }}
- name: Update image tag for container builder service
working-directory: ./deployments/null-cloud/base/container-runner/dev/
run: |
Expand Down
Empty file removed api/:q
Empty file.
54 changes: 49 additions & 5 deletions api/app/controllers/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package controllers
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
Expand Down Expand Up @@ -77,7 +78,7 @@ func NewApplicationController(kube dynamic.Interface, istio *versionedclient.Cli

func (a *ApplicationController) RegisterRoutes(router *mux.Router) {
router.HandleFunc("", a.AppPOST).Methods("POST")
router.HandleFunc("/{id}", a.AppGET).Methods("GET")
router.HandleFunc("/{}", a.AppGET).Methods("GET")
}

type Application struct {
Expand Down Expand Up @@ -315,15 +316,58 @@ func getIstioNetowrkGVR(resource string) schema.GroupVersionResource {

// AppGET godoc
//
// @Summary Get all applications created by the user
// @Summary Get all applications in the org
// @Schemes
// @Description Get all applications created by the user
// @Description Get all applications in the org
// @Tags example
// @Accept json
// @Produce json
// @Success 200 {string} Helloworld
// @Router /apps/ [get]
func (a ApplicationController) AppGET(w http.ResponseWriter, r *http.Request) {
// TODO: implement
w.WriteHeader(http.StatusNotImplemented)
userId, err := strconv.ParseInt(r.Context().Value("user-id").(string), 10, 64)

if err != nil {
a.logs.Errorf("Failed to parse user id",
"user-id:", r.Context().Value("user-id"))
}
// get user org
org, err := a.userController.GetUserContext(r.Context(), userId)
if err != nil {
a.logs.Errorw("Failed to get user org for the user controller",
"user-id", userId,
"error", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}

nullApplications, err := a.GetApplications(r.Context(), org.ID)
if err != nil {
a.logs.Errorw("Failed to get applications for the user",
"user-id", userId,
"error", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(nullApplications)
}

func (a ApplicationController) GetApplication(ctx context.Context, id int64) (*appmodels.NullApplication, error) {
nullApplication := &appmodels.NullApplication{}
err := a.database.NewSelect().Model(nullApplication).Where("id = ?", id).Scan(ctx)
if err != nil {
return nil, err
}
return nullApplication, nil
}

func (a ApplicationController) GetApplications(ctx context.Context, orgId int64) ([]*appmodels.NullApplication, error) {
nullApplications := []*appmodels.NullApplication{}
err := a.database.NewSelect().Model(&nullApplications).Where("org_id = ?", orgId).Scan(ctx)
if err != nil {
return nil, err
}
return nullApplications, nil
}
2 changes: 1 addition & 1 deletion api/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ go 1.20

require (
github.com/evanphx/json-patch v5.6.0+incompatible
github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/gorilla/handlers v1.5.1
github.com/null-channel/eddington/proto v0.0.0-20231009003536-a2b6e90d2dcd
github.com/ory/client-go v1.1.41
Expand Down
4 changes: 2 additions & 2 deletions api/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
Expand Down
4 changes: 3 additions & 1 deletion api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ func main() {
istioClient := versionedclient.NewForConfigOrDie(clusterConfig)
appController := app.NewApplicationController(config, istioClient, kubeClient, userController, client, logger)
middlwares := []mux.MiddlewareFunc{
middleware.AddJwtHeaders,
authzMiddleware.CheckAuthz,
userMiddleware.NewUserMiddlewareCheck,
}
Expand All @@ -120,7 +121,8 @@ func main() {
// Users
users := v1.PathPrefix("/users").Subrouter()
{
addMiddleware(users, middlwares...)
users.Use(middleware.AddJwtHeaders)
users.Use(authzMiddleware.CheckAuthz)
userController.AddAllControllers(users)
}
// Marketing
Expand Down
54 changes: 27 additions & 27 deletions api/middleware/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,24 @@ import (
"fmt"
"log"
"net/http"
"strings"

"github.com/golang-jwt/jwt"
ory "github.com/ory/client-go"
"github.com/golang-jwt/jwt/v4"
)

type OryApp struct {
Ory *ory.APIClient
}

// save the cookies for any upstream calls to the Ory apis
func withCookies(ctx context.Context, v string) context.Context {
return context.WithValue(ctx, "req.cookies", v)
}
func withUser(ctx context.Context, v string) context.Context {
return context.WithValue(ctx, "user-id", v)
}

func getCookies(ctx context.Context) string {
return ctx.Value("req.cookies").(string)
}

// save the session to display it on the dashboard
func withSession(ctx context.Context, v *ory.Session) context.Context {
return context.WithValue(ctx, "req.session", v)
}

func getSession(ctx context.Context) *ory.Session {
return ctx.Value("req.session").(*ory.Session)
}

func withUser(ctx context.Context, v *ory.Session) context.Context {
return context.WithValue(ctx, "user-id", v.GetIdentity().Id)
}

func (app *OryApp) SessionMiddleware(next http.Handler) http.Handler {
func AddJwtHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {

//TODO: Parse JWT token and get user id
Expand All @@ -54,19 +40,33 @@ func (app *OryApp) SessionMiddleware(next http.Handler) http.Handler {
// ory_session_projectid cookie to the endpoint
cookies = request.Header.Get("Cookie")
tokenString := request.Header.Get("Authorization")
user_id, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
fmt.Println(token)
return token.Claims.(jwt.MapClaims)["user-id"], nil
// remove the Bearer prefix
// and parse the token
parser := &jwt.Parser{
ValidMethods: []string{"none"},
UseJSONNumber: true,
SkipClaimsValidation: true,
}
tokenString = strings.Replace(tokenString, "Bearer ", "", 1)
userId, err := parser.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
//fmt.Println("claims: " + token.Claims.(jwt.MapClaims)["sub"])
claims := token.Claims.(jwt.MapClaims)
// You can now extract any data from the token's payload
return claims["sub"], nil
})
user_id := fmt.Sprintf("%v", userId)
if err != nil {
fmt.Println(err)
return
fmt.Println("Error parsing token! but that is ok")
// can fail if the token is invalid but we don't want to validate it here for now
//return
}
//TODO: Delete this line
fmt.Println(user_id)
fmt.Println("request userId: %s" + user_id)
fmt.Println("next line")
ctx = withUser(ctx, user_id)

//ctx = withSession(ctx, session)
//ctx = withUser(ctx, session)
request.Header.Set("user-id", fmt.Sprintf("%v", user_id))

// continue to the requested page (in our case the Dashboard)
next.ServeHTTP(writer, request.WithContext(ctx))
Expand Down
2 changes: 1 addition & 1 deletion api/middleware/newuser.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func NewUserMiddleware(db *bun.DB) *UserMiddleware {
func (k *UserMiddleware) NewUserMiddlewareCheck(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userId := r.Context().Value("user-id").(int64)
fmt.Println("Checking if user is new...")
fmt.Println("Checking if user is new... %i", userId)
// Check database for user
_, err := user.GetUserForId(userId, k.db)

Expand Down

0 comments on commit a0e1782

Please sign in to comment.