github.com/greenpau/go-authcrunch@v1.1.4/pkg/authn/handle_http_whoami.go (about)

     1  // Copyright 2022 Paul Greenberg greenpau@outlook.com
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package authn
    16  
    17  import (
    18  	"context"
    19  	"encoding/json"
    20  	"github.com/greenpau/go-authcrunch/pkg/requests"
    21  	"github.com/greenpau/go-authcrunch/pkg/user"
    22  	"net/http"
    23  	"time"
    24  )
    25  
    26  func (p *Portal) handleHTTPWhoami(ctx context.Context, w http.ResponseWriter, r *http.Request, rr *requests.Request, usr *user.User) error {
    27  	p.disableClientCache(w)
    28  	p.injectRedirectURL(ctx, w, r, rr)
    29  	if usr == nil {
    30  		if rr.Response.RedirectURL == "" {
    31  			return p.handleHTTPRedirect(ctx, w, r, rr, "/login?redirect_url="+r.RequestURI)
    32  		}
    33  		return p.handleHTTPRedirect(ctx, w, r, rr, "/login")
    34  	}
    35  	resp := p.ui.GetArgs()
    36  	resp.PageTitle = "User Identity"
    37  	resp.BaseURL(rr.Upstream.BasePath)
    38  	tokenMap := make(map[string]interface{})
    39  	for k, v := range usr.AsMap() {
    40  		tokenMap[k] = v
    41  	}
    42  	tokenMap["authenticated"] = true
    43  	if usr.Claims.ExpiresAt > 0 {
    44  		tokenMap["expires_at_utc"] = time.Unix(usr.Claims.ExpiresAt, 0).Format(time.UnixDate)
    45  	}
    46  	if usr.Claims.IssuedAt > 0 {
    47  		tokenMap["issued_at_utc"] = time.Unix(usr.Claims.IssuedAt, 0).Format(time.UnixDate)
    48  	}
    49  	if usr.Claims.NotBefore > 0 {
    50  		tokenMap["not_before_utc"] = time.Unix(usr.Claims.NotBefore, 0).Format(time.UnixDate)
    51  	}
    52  	prettyTokenMap, err := json.MarshalIndent(tokenMap, "", "  ")
    53  	if err != nil {
    54  		return p.handleHTTPRenderError(ctx, w, r, rr, err)
    55  	}
    56  	resp.Data["token"] = string(prettyTokenMap)
    57  
    58  	content, err := p.ui.Render("whoami", resp)
    59  	if err != nil {
    60  		return p.handleHTTPRenderError(ctx, w, r, rr, err)
    61  	}
    62  	return p.handleHTTPRenderHTML(ctx, w, http.StatusOK, content.Bytes())
    63  }