add state validation to oauth flow #8
1 changed files with 18 additions and 11 deletions
|
@ -34,8 +34,8 @@ import (
|
|||
"stereo.cat/backend/internal/types"
|
||||
)
|
||||
|
||||
var oauthStates = make(map[string]struct{})
|
||||
var oauthStatesMu sync.Mutex
|
||||
var states []string
|
||||
var statesMutex sync.Mutex
|
||||
|
||||
func generateState(length int) (string, error) {
|
||||
b := make([]byte, length)
|
||||
|
@ -54,9 +54,9 @@ func RegisterAuthRoutes(cfg *types.StereoConfig, api *gin.RouterGroup) {
|
|||
return
|
||||
}
|
||||
|
||||
oauthStatesMu.Lock()
|
||||
oauthStates[state] = struct{}{}
|
||||
oauthStatesMu.Unlock()
|
||||
statesMutex.Lock()
|
||||
states = append(states, state)
|
||||
statesMutex.Unlock()
|
||||
|
||||
discordURL := fmt.Sprintf(
|
||||
"https://discord.com/oauth2/authorize?client_id=%s&response_type=code&redirect_uri=%s&scope=identify%%20email&state=%s",
|
||||
|
@ -77,13 +77,20 @@ func RegisterAuthRoutes(cfg *types.StereoConfig, api *gin.RouterGroup) {
|
|||
code := c.Query("code")
|
||||
state := c.Query("state")
|
||||
|
||||
oauthStatesMu.Lock()
|
||||
_, ok := oauthStates[state]
|
||||
if ok {
|
||||
delete(oauthStates, state)
|
||||
statesMutex.Lock()
|
||||
|
||||
found := false
|
||||
for i, s := range states {
|
||||
if s == state {
|
||||
states = append(states[:i], states[i+1:]...)
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
oauthStatesMu.Unlock()
|
||||
if !ok {
|
||||
|
||||
statesMutex.Unlock()
|
||||
|
||||
if !found {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid state"})
|
||||
return
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue