Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wip #4658

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

wip #4658

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 38 additions & 44 deletions api/server/authn/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"

"github.com/gorilla/sessions"
"github.com/porter-dev/porter/api/server/shared/apierrors"
Expand Down Expand Up @@ -70,63 +70,57 @@
}

// if the bearer token is not found, look for a request cookie
session, err := authn.config.Store.Get(r, authn.config.ServerConf.CookieName)
if err != nil {
session.Values["authenticated"] = false

// we attempt to save the session, but do not catch the error since we send the
// forbidden error regardless
session.Save(r, w)
// first look for new ory cookie
// set the cookies on the ory client
var cookies string

// this example passes all request.Cookies
// to `ToSession` function
//
// However, you can pass only the value of
// ory_session_projectid cookie to the endpoint
cookies = r.Header.Get("Cookie")

fmt.Println("Cookies: ", cookies)

// check if we have a session
orySession, _, err := authn.config.Ory.FrontendAPI.ToSession(r.Context()).Cookie(cookies).Execute()
if err != nil {
authn.sendForbiddenError(err, w, r)
return
}

cancelTokens := func(lastIssueTime time.Time, cancelEmail string, authn *AuthN, session *sessions.Session) bool {
if email, ok := session.Values["email"]; ok {
if email.(string) == cancelEmail {
timeAsUTC := lastIssueTime.UTC()
sess, _ := authn.config.Repo.Session().SelectSession(&models.Session{Key: session.ID})
if sess.CreatedAt.UTC().Before(timeAsUTC) {
_, _ = authn.config.Repo.Session().DeleteSession(sess)
return true
}
}
}
return false
if orySession == nil {
err = errors.New("ory session is nil")
authn.sendForbiddenError(err, w, r)
return
}

est, err := time.LoadLocation("EST")
// if err == nil {
// authn.handleForbiddenForSession(w, r, fmt.Errorf("error, contact admin"), session)
// return
// }
// TODO: handle error from time.LoadLocation
if err == nil {
if cancelTokens(time.Date(2024, 0o1, 16, 18, 35, 0, 0, est), "[email protected]", authn, session) {
authn.handleForbiddenForSession(w, r, fmt.Errorf("error, contact admin"), session)
return
}
if cancelTokens(time.Date(2024, 0o1, 16, 18, 35, 0, 0, est), "[email protected]", authn, session) {
authn.handleForbiddenForSession(w, r, fmt.Errorf("error, contact admin"), session)
return
}
if !*orySession.Active {
err = errors.New("ory session is not active")
authn.sendForbiddenError(err, w, r)
return
}

if auth, ok := session.Values["authenticated"].(bool); !auth || !ok {
authn.handleForbiddenForSession(w, r, fmt.Errorf("stored cookie was not authenticated"), session)
if orySession.Identity == nil {
err = errors.New("ory session identity is nil")
authn.sendForbiddenError(err, w, r)
return
}

// read the user id in the token
userID, ok := session.Values["user_id"].(uint)

if !ok {
authn.handleForbiddenForSession(w, r, fmt.Errorf("could not cast user_id to uint"), session)
fmt.Println("now in here")
// get user id from Ory
externalId := orySession.Identity.Id
user, err := authn.config.Repo.User().ReadUserByAuthProvider("ory", externalId)
if err != nil || user == nil {
err := fmt.Errorf("ory user not found in database", externalId)

Check failure on line 115 in api/server/authn/handler.go

View workflow job for this annotation

GitHub Actions / Running Go Tests (ubuntu-latest, api)

fmt.Errorf call has arguments but no formatting directives
authn.sendForbiddenError(err, w, r)
return
}

authn.nextWithUserID(w, r, userID)
fmt.Println("going next")

authn.nextWithUserID(w, r, user.ID)
return
}

func (authn *AuthN) handleForbiddenForSession(
Expand Down
136 changes: 136 additions & 0 deletions api/server/handlers/invite/create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package invite

import (
"net/http"
"time"

"github.com/porter-dev/porter/internal/telemetry"

"github.com/porter-dev/porter/api/server/handlers"
"github.com/porter-dev/porter/api/server/shared"
"github.com/porter-dev/porter/api/server/shared/apierrors"
"github.com/porter-dev/porter/api/server/shared/config"
"github.com/porter-dev/porter/api/types"
"github.com/porter-dev/porter/internal/models"
"github.com/porter-dev/porter/internal/oauth"
)

type InviteCreateHandler struct {
handlers.PorterHandlerReadWriter
}

func NewInviteCreateHandler(
config *config.Config,
decoderValidator shared.RequestDecoderValidator,
writer shared.ResultWriter,
) http.Handler {
return &InviteCreateHandler{
PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
}
}

func (c *InviteCreateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx, span := telemetry.NewSpan(r.Context(), "serve-invite-create")
defer span.End()

user, _ := ctx.Value(types.UserScope).(*models.User)
project, _ := ctx.Value(types.ProjectScope).(*models.Project)

request := &types.CreateInviteRequest{}

if ok := c.DecodeAndValidate(w, r, request); !ok {
telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "message", Value: "failed to decode and validate request"})
return
}

//identities, _, err := c.Config().Ory.IdentityAPI.ListIdentities(context.WithValue(ctx, ory.ContextAccessToken, c.Config().OryApiKey)).CredentialsIdentifier(request.Email).Execute()
//if err != nil {
// fmt.Println("dgt ory", err.Error())
// return
//} else {
// fmt.Println("dgt ory", identities)
// return
//}
//
//basicIdentityBody := ory.CreateIdentityBody{
// SchemaId: "preset://email",
// Traits: map[string]interface{}{"email": request.Email},
//}
//
//fmt.Println("dgt ory", c.Config().OryApiKey)
//
//identity, _, err := c.Config().Ory.IdentityAPI.CreateIdentity(context.WithValue(ctx, ory.ContextAccessToken, c.Config().OryApiKey)).CreateIdentityBody(basicIdentityBody).Execute()
//if err != nil {
// err = telemetry.Error(ctx, span, err, "error creating identity")
// c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
// return
//}
//
//sevenDays := "7d"
//createRecoveryBody := ory.CreateRecoveryLinkForIdentityBody{
// ExpiresIn: &sevenDays,
// IdentityId: identity.Id,
//}
//
//recoveryLink, _, err := c.Config().Ory.IdentityAPI.CreateRecoveryLinkForIdentity(context.WithValue(ctx, ory.ContextAccessToken, c.Config().OryApiKey)).CreateRecoveryLinkForIdentityBody(createRecoveryBody).Execute()
//if err != nil || recoveryLink == nil {
// err = telemetry.Error(ctx, span, err, "error creating recovery link")
// c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
// return
//
//}

// create invite model
invite, err := CreateInviteWithProject(request, project.ID)
if err != nil {
c.HandleAPIError(w, r, apierrors.NewErrInternal(telemetry.Error(ctx, span, err, "error creating invite with project")))
return
}

invite.InvitingUserID = user.ID

telemetry.WithAttributes(span,
telemetry.AttributeKV{Key: "project-id", Value: invite.ProjectID},
telemetry.AttributeKV{Key: "user-id", Value: invite.UserID},
telemetry.AttributeKV{Key: "kind", Value: invite.Kind},
)

// write to database
invite, err = c.Repo().Invite().CreateInvite(invite)
if err != nil {
c.HandleAPIError(w, r, apierrors.NewErrInternal(telemetry.Error(ctx, span, err, "error creating invite in repo")))
return
}

//if err := c.Config().UserNotifier.SendProjectInviteEmail(
// &notifier.SendProjectInviteEmailOpts{
// InviteeEmail: request.Email,
// URL: recoveryLink.RecoveryLink,
// Project: project.Name,
// ProjectOwnerEmail: user.Email,
// },
//); err != nil {
// c.HandleAPIError(w, r, apierrors.NewErrInternal(telemetry.Error(ctx, span, err, "error sending project invite email")))
// return
//}

res := types.CreateInviteResponse{
Invite: invite.ToInviteType(),
}

c.WriteResult(w, r, res)
}

func CreateInviteWithProject(invite *types.CreateInviteRequest, projectID uint) (*models.Invite, error) {
// generate a token and an expiry time
expiry := time.Now().Add(7 * 24 * time.Hour)

return &models.Invite{
Token: oauth.CreateRandomState(),
Expiry: &expiry,
Email: invite.Email,
Kind: invite.Kind,
ProjectID: projectID,
Status: models.InvitePending,
}, nil
}
36 changes: 36 additions & 0 deletions api/server/handlers/invite/delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package invite

import (
"net/http"

"github.com/porter-dev/porter/api/server/authz"
"github.com/porter-dev/porter/api/server/handlers"
"github.com/porter-dev/porter/api/server/shared/apierrors"
"github.com/porter-dev/porter/api/server/shared/config"
"github.com/porter-dev/porter/api/types"
"github.com/porter-dev/porter/internal/models"
)

type InviteDeleteHandler struct {
handlers.PorterHandler
authz.KubernetesAgentGetter
}

func NewInviteDeleteHandler(
config *config.Config,
) http.Handler {
return &InviteDeleteHandler{
PorterHandler: handlers.NewDefaultPorterHandler(config, nil, nil),
KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
}
}

func (c *InviteDeleteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
invite, _ := r.Context().Value(types.InviteScope).(*models.Invite)

if err := c.Repo().Invite().DeleteInvite(invite); err != nil {
c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
}

w.WriteHeader(http.StatusOK)
}
69 changes: 0 additions & 69 deletions api/server/handlers/invite/invite_ce.go

This file was deleted.

Loading
Loading