basic redirect test

This commit is contained in:
Milo Schwartz 2024-10-06 18:10:17 -04:00
parent f92225f24e
commit 387ce901b9
No known key found for this signature in database
2 changed files with 31 additions and 36 deletions

View file

@ -6,5 +6,5 @@ import: github.com/fosrl/badger
summary: Middleware auth bouncer for Fossorial
testData:
apiAddress: http://pangolin:3001
validToken: abc123
apiBaseUrl: http://localhost:3001/api/v1
appBaseUrl: http://localhost:3000

63
main.go
View file

@ -2,13 +2,16 @@ package badger
import (
"context"
"fmt"
"net/http"
"time"
"net/url"
)
const SessionCookieName = "session"
type Config struct {
APIAddress string `json:"apiAddress"`
ValidToken string `json:"validToken"`
AppBaseUrl string `json:"appBaseUrl"`
APIBaseUrl string `json:"apiBaseUrl"`
}
func CreateConfig() *Config {
@ -18,52 +21,44 @@ func CreateConfig() *Config {
type Badger struct {
next http.Handler
name string
apiAdress string
validToken string
appBaseUrl string
apiBaseUrl string
}
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
return &Badger{
next: next,
name: name,
apiAdress: config.APIAddress,
validToken: config.ValidToken,
appBaseUrl: config.AppBaseUrl,
apiBaseUrl: config.APIBaseUrl,
}, nil
}
// THIS IS AN EAXMPLE FOR TESTING
var usedTokens = make(map[string]bool)
const cookieName = "access_token"
const cookieDuration = 1 * time.Minute
func (p *Badger) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if _, err := req.Cookie(cookieName); err == nil {
p.next.ServeHTTP(rw, req)
// Check if the session cookie exists
cookie, err := req.Cookie(SessionCookieName)
if err != nil {
// No session cookie, redirect to login
originalRequestURL := url.QueryEscape(req.URL.String())
http.Redirect(rw, req, fmt.Sprintf("%s/auth/login?redirect=%s", p.appBaseUrl, originalRequestURL), http.StatusFound)
return
}
queryToken := req.URL.Query().Get("token")
if queryToken == "" {
http.Error(rw, "Missing token", http.StatusUnauthorized)
// Verify the user with the session ID
sessionID := cookie.Value
verifyURL := fmt.Sprintf("%s/badger/verify-user?sessionId=%s", p.apiBaseUrl, sessionID)
resp, err := http.Get(verifyURL)
if err != nil || resp.StatusCode != http.StatusOK {
// If unauthorized (401), redirect to the homepage
if resp != nil && resp.StatusCode == http.StatusUnauthorized {
http.Redirect(rw, req, p.appBaseUrl, http.StatusFound)
} else {
// Handle other errors, possibly log them (you can adjust the error handling here)
http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
}
return
}
if queryToken != p.validToken || usedTokens[queryToken] {
http.Error(rw, "Invalid or already used token", http.StatusUnauthorized)
return
}
usedTokens[queryToken] = true
expiration := time.Now().Add(cookieDuration)
http.SetCookie(rw, &http.Cookie{
Name: cookieName,
Value: "temporary-access",
Expires: expiration,
Path: "/",
})
p.next.ServeHTTP(rw, req)
}