...

Source file src/edge-infra.dev/pkg/edge/auth-proxy/handlers/default.go

Documentation: edge-infra.dev/pkg/edge/auth-proxy/handlers

     1  package handlers
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"time"
     7  
     8  	"github.com/gin-contrib/sessions"
     9  	"github.com/gin-gonic/gin"
    10  
    11  	"edge-infra.dev/pkg/edge/api/middleware"
    12  )
    13  
    14  func (h ProxyHandler) Default(req *http.Request, body []byte) (*http.Request, []byte, error) {
    15  	expiresAt := h.session.Get("expires_on")
    16  	if expiresAt != nil {
    17  		expirationTime := expiresAt.(time.Time)
    18  		if expirationTime.Before(time.Now().UTC()) {
    19  			h.log.Info("session has expired, deleting session", "sessionID", h.session.ID(), "expirationTime", expirationTime.String())
    20  			h.session.Clear()
    21  			h.session.Options(sessions.Options{MaxAge: -1})
    22  			if err := h.session.Save(); err != nil {
    23  				return req, body, err
    24  			}
    25  			h.c.JSON(http.StatusNotFound, gin.H{"error": "unauthorized"})
    26  			h.c.Abort()
    27  		}
    28  	}
    29  	return req, body, nil
    30  }
    31  
    32  func (h ProxyHandler) SessionDefault(req *http.Request, body []byte) (*http.Request, []byte, error) {
    33  	if h.session.Get("id") == nil {
    34  		return req, body, nil
    35  	}
    36  	username := ""
    37  	email := ""
    38  	roles := make([]string, 0)
    39  	token := ""
    40  	organization := ""
    41  	refreshToken := ""
    42  	usernameSessionVal := h.session.Get("username")
    43  	if usernameSessionVal != nil {
    44  		username = usernameSessionVal.(string)
    45  	}
    46  	emailSessionVal := h.session.Get("email")
    47  	if emailSessionVal != nil {
    48  		email = emailSessionVal.(string)
    49  	}
    50  	rolesSessionVal := h.session.Get("roles")
    51  	if rolesSessionVal != nil {
    52  		roles = rolesSessionVal.([]string)
    53  	}
    54  	tokenSessionVal := h.session.Get("token")
    55  	if tokenSessionVal != nil {
    56  		token = tokenSessionVal.(string)
    57  	}
    58  	refreshTokenSessionVal := h.session.Get("refresh_token")
    59  	if refreshTokenSessionVal != nil {
    60  		refreshToken = refreshTokenSessionVal.(string)
    61  	}
    62  	organizationSessionVal := h.session.Get("organization")
    63  	if organizationSessionVal != nil {
    64  		organization = organizationSessionVal.(string)
    65  	}
    66  
    67  	authProvider := h.session.Get("auth_type").(string)
    68  
    69  	edgeToken, err := middleware.CreateToken(username, email, organization, h.tokenSecret, roles, token, authProvider, refreshToken)
    70  	if err != nil {
    71  		h.log.Error(err, "unable to create edge token")
    72  		return req, body, err
    73  	}
    74  	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", edgeToken))
    75  	return req, body, nil
    76  }
    77  

View as plain text