Skip to content

Commit

Permalink
fix: return a 401 HTTP Response on auth fail instead of looping OAuth…
Browse files Browse the repository at this point in the history
… forever
  • Loading branch information
VeryStrongFingers committed Jan 25, 2024
1 parent 48ab07e commit 8886d2c
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 12 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/.idea/
/Caddyfile
vendor/
15 changes: 7 additions & 8 deletions module_callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,17 +157,16 @@ func (d DiscordAuthPlugin) ServeHTTP(w http.ResponseWriter, r *http.Request, _ c
}
}

if !allowed {
// User failed realm checks
//http.Error(w, "You do not have access to this", http.StatusForbidden)
http.Redirect(w, r, token.RedirectURI, http.StatusFound)
// Re-validate user through OAuth2 flow every 16 hours when authorised
expiration := time.Now().Add(time.Hour * 16)

return nil
// Otherwise re-validate user every 3 minutes if authorised failed
// in-case of Discord role change, etc.
if !allowed {
expiration = time.Now().Add(time.Minute * 3)
}
// Re-validate user through OAuth2 flow every 16 hours
expiration := time.Now().Add(time.Hour * 16)

authedToken := NewAuthenticatedToken(*identity, realm.Ref, expiration)
authedToken := NewAuthenticatedToken(*identity, realm.Ref, expiration, allowed)
signedToken, err := d.tokenSigner(authedToken)
if err != nil {
// Unable to generate JWT
Expand Down
2 changes: 1 addition & 1 deletion module_entrypoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func (e ProtectorPlugin) Authenticate(w http.ResponseWriter, r *http.Request) (c
"username": claims.Username,
"avatar": claims.Avatar,
},
}, true, nil
}, claims.Authorised, nil
}

// 15 minutes to make it through Discord consent.
Expand Down
8 changes: 5 additions & 3 deletions token.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ type JWTManager struct {
type AuthenticatedClaims struct {
Realm string `json:"realm,omitempty"`

Username string `json:"user,omitempty"`
Avatar string `json:"avatar,omitempty"`
Username string `json:"user,omitempty"`
Avatar string `json:"avatar,omitempty"`
Authorised bool `json:"authorised,omitempty"`
jwt.RegisteredClaims
}

Expand All @@ -40,11 +41,12 @@ func (f FlowTokenParser) GetAudience() string {
return "flow"
}

func NewAuthenticatedToken(identity discord.User, realm string, exp time.Time) *jwt.Token {
func NewAuthenticatedToken(identity discord.User, realm string, exp time.Time, authorised bool) *jwt.Token {
claims := AuthenticatedClaims{
realm,
identity.Username,
identity.Avatar,
authorised,
jwt.RegisteredClaims{
Audience: []string{"auth"},
ExpiresAt: jwt.NewNumericDate(exp),
Expand Down

0 comments on commit 8886d2c

Please sign in to comment.