Files
AstralCalendar/auth/auth.go
T
2026-08-06 10:08:07 -04:00

73 lines
1.7 KiB
Go

package auth
import (
"crypto/rand"
"encoding/base64"
"fmt"
"net/http"
"astraltech.xyz/calendar/v2/webserver"
"golang.org/x/oauth2"
)
func generateState() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
func HandlePasswordAuth(authData webserver.PasswordAuthData) bool {
fmt.Printf("%s, %s\n", authData.Username, authData.Password)
return false
}
func HandleOAuth(authData webserver.OAuthAuthData) bool {
state, err := generateState()
if err != nil {
http.Error(*authData.ResponseWriter, "Failed to generate state", http.StatusInternalServerError)
return false
}
verifier := oauth2.GenerateVerifier()
http.SetCookie(*authData.ResponseWriter, &http.Cookie{
Name: "oauth_state",
Value: state,
Path: "/",
MaxAge: 300,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
http.SetCookie(*authData.ResponseWriter, &http.Cookie{
Name: "pkce_verifier",
Value: verifier,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
url := OAuthConfigs[0].AuthCodeURL(
state,
oauth2.S256ChallengeOption(verifier),
)
http.Redirect(*authData.ResponseWriter, authData.Request, url, http.StatusFound)
return false
}
func HandleAuthRequest(authType webserver.AuthStyle, authData webserver.AuthData) bool {
if authType == webserver.AuthStylePassword {
passwordAuthData, _ := authData.(webserver.PasswordAuthData)
return HandlePasswordAuth(passwordAuthData)
}
if authType == webserver.AuthStyleOAuth {
passwordAuthData, _ := authData.(webserver.OAuthAuthData)
return HandleOAuth(passwordAuthData)
}
return false
}