fix: harden authentication flows
This commit is contained in:
@@ -65,6 +65,9 @@ func (e *aesEncryption) Decrypt(dec string) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
nonceSize := gcm.NonceSize()
|
nonceSize := gcm.NonceSize()
|
||||||
|
if len(ciphertext) < nonceSize+gcm.Overhead() {
|
||||||
|
return "", fmt.Errorf("ciphertext is too short")
|
||||||
|
}
|
||||||
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
|
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
|
||||||
|
|
||||||
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
|
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/fossyy/filekeeper/app"
|
"github.com/fossyy/filekeeper/app"
|
||||||
|
googleOauthHandler "github.com/fossyy/filekeeper/handler/auth/google"
|
||||||
googleOauthSetupHandler "github.com/fossyy/filekeeper/handler/auth/google/setup"
|
googleOauthSetupHandler "github.com/fossyy/filekeeper/handler/auth/google/setup"
|
||||||
"github.com/fossyy/filekeeper/session"
|
"github.com/fossyy/filekeeper/session"
|
||||||
"github.com/fossyy/filekeeper/types"
|
"github.com/fossyy/filekeeper/types"
|
||||||
@@ -13,6 +14,7 @@ import (
|
|||||||
"github.com/redis/go-redis/v9"
|
"github.com/redis/go-redis/v9"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -45,9 +47,16 @@ type OauthUser struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GET(w http.ResponseWriter, r *http.Request) {
|
func GET(w http.ResponseWriter, r *http.Request) {
|
||||||
_, err := app.Server.Cache.GetCache(r.Context(), "CsrfTokens:"+r.URL.Query().Get("state"))
|
state := r.URL.Query().Get("state")
|
||||||
|
if state == "" {
|
||||||
|
http.Redirect(w, r, "/auth/signin?error=csrf_token_error", http.StatusFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
secureStateCookie := session.IsHTTPS(r)
|
||||||
|
stateJSON, err := app.Server.Cache.GetCache(r.Context(), "CsrfTokens:"+state)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, redis.Nil) {
|
if errors.Is(err, redis.Nil) {
|
||||||
|
http.SetCookie(w, &http.Cookie{Name: "oauth_state", Value: "", Path: "/auth/google/callback", MaxAge: -1, HttpOnly: true, Secure: r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https"), SameSite: http.SameSiteLaxMode})
|
||||||
http.Redirect(w, r, fmt.Sprintf("/auth/signin?error=%s", "csrf_token_error"), http.StatusFound)
|
http.Redirect(w, r, fmt.Sprintf("/auth/signin?error=%s", "csrf_token_error"), http.StatusFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -55,14 +64,28 @@ func GET(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
var csrf googleOauthHandler.CsrfToken
|
||||||
|
if err := json.Unmarshal([]byte(stateJSON), &csrf); err != nil {
|
||||||
|
http.Redirect(w, r, "/auth/signin?error=csrf_token_error", http.StatusFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if cookie, cookieErr := r.Cookie("oauth_state"); cookieErr != nil || cookie.Value != state {
|
||||||
|
http.Redirect(w, r, "/auth/signin?error=csrf_token_error", http.StatusFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if csrf.Token != state {
|
||||||
|
http.Redirect(w, r, "/auth/signin?error=csrf_token_error", http.StatusFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
err = app.Server.Cache.DeleteCache(r.Context(), "CsrfTokens:"+r.URL.Query().Get("state"))
|
err = app.Server.Cache.DeleteCache(r.Context(), "CsrfTokens:"+state)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Redirect(w, r, fmt.Sprintf("/auth/signin?error=%s", "csrf_token_error"), http.StatusFound)
|
http.Redirect(w, r, fmt.Sprintf("/auth/signin?error=%s", "csrf_token_error"), http.StatusFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := r.URL.Query().Get("error"); err != "" {
|
if err := r.URL.Query().Get("error"); err != "" {
|
||||||
|
http.SetCookie(w, &http.Cookie{Name: "oauth_state", Value: "", Path: "/auth/google/callback", MaxAge: -1, HttpOnly: true, Secure: secureStateCookie, SameSite: http.SameSiteLaxMode})
|
||||||
http.Redirect(w, r, fmt.Sprintf("/auth/signin?error=%s", err), http.StatusFound)
|
http.Redirect(w, r, fmt.Sprintf("/auth/signin?error=%s", err), http.StatusFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -75,10 +98,18 @@ func GET(w http.ResponseWriter, r *http.Request) {
|
|||||||
"redirect_uri": {utils.Getenv("GOOGLE_CALLBACK")},
|
"redirect_uri": {utils.Getenv("GOOGLE_CALLBACK")},
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := http.Post("https://oauth2.googleapis.com/token", "application/x-www-form-urlencoded", bytes.NewBufferString(formData.Encode()))
|
tokenRequest, err := http.NewRequestWithContext(r.Context(), http.MethodPost, "https://oauth2.googleapis.com/token", bytes.NewBufferString(formData.Encode()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
app.Server.Logger.Error("Error:", err)
|
app.Server.Logger.Error("Error creating token request:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tokenRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
client := &http.Client{Timeout: 10 * time.Second}
|
||||||
|
resp, err := client.Do(tokenRequest)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
app.Server.Logger.Error("Error requesting token:", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
@@ -95,8 +126,10 @@ func GET(w http.ResponseWriter, r *http.Request) {
|
|||||||
app.Server.Logger.Error("Error reading token response body:", err)
|
app.Server.Logger.Error("Error reading token response body:", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if oauthData.AccessToken == "" {
|
||||||
client := &http.Client{}
|
http.Error(w, "Invalid token response", http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(r.Context(), "GET", "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", nil)
|
req, err := http.NewRequestWithContext(r.Context(), "GET", "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -119,7 +152,6 @@ func GET(w http.ResponseWriter, r *http.Request) {
|
|||||||
app.Server.Logger.Error("Error user info endpoint returned status: ", userInfoResp.Status)
|
app.Server.Logger.Error("Error user info endpoint returned status: ", userInfoResp.Status)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var oauthUser OauthUser
|
var oauthUser OauthUser
|
||||||
if err := json.NewDecoder(userInfoResp.Body).Decode(&oauthUser); err != nil {
|
if err := json.NewDecoder(userInfoResp.Body).Decode(&oauthUser); err != nil {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
@@ -167,9 +199,10 @@ func GET(w http.ResponseWriter, r *http.Request) {
|
|||||||
Authenticated: true,
|
Authenticated: true,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
http.Redirect(w, r, fmt.Sprintf("/auth/signin?error=%s", "csrf_token_error"), http.StatusFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
http.SetCookie(w, &http.Cookie{Name: "oauth_state", Value: "", Path: "/auth/google/callback", MaxAge: -1, HttpOnly: true, Secure: r.TLS != nil, SameSite: http.SameSiteLaxMode})
|
||||||
|
|
||||||
userAgent := r.Header.Get("User-Agent")
|
userAgent := r.Header.Get("User-Agent")
|
||||||
browserInfo, osInfo := utils.ParseUserAgent(userAgent)
|
browserInfo, osInfo := utils.ParseUserAgent(userAgent)
|
||||||
@@ -193,16 +226,24 @@ func GET(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cookie, err := r.Cookie("redirect")
|
cookie, err := r.Cookie("redirect")
|
||||||
if errors.Is(err, http.ErrNoCookie) {
|
if err != nil || !validRedirect(cookie.Value) {
|
||||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
http.SetCookie(w, &http.Cookie{
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: "redirect",
|
Name: "redirect",
|
||||||
MaxAge: -1,
|
MaxAge: -1,
|
||||||
|
Path: "/",
|
||||||
|
HttpOnly: true,
|
||||||
|
Secure: session.IsHTTPS(r),
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
})
|
})
|
||||||
|
|
||||||
http.Redirect(w, r, cookie.Value, http.StatusSeeOther)
|
http.Redirect(w, r, cookie.Value, http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validRedirect(value string) bool {
|
||||||
|
return strings.HasPrefix(value, "/") && !strings.HasPrefix(value, "//") && !strings.Contains(value, `\`)
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,10 +2,11 @@ package googleOauthHandler
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
|
||||||
"github.com/fossyy/filekeeper/app"
|
"github.com/fossyy/filekeeper/app"
|
||||||
|
"github.com/fossyy/filekeeper/session"
|
||||||
"github.com/fossyy/filekeeper/utils"
|
"github.com/fossyy/filekeeper/utils"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -16,6 +17,10 @@ type CsrfToken struct {
|
|||||||
|
|
||||||
func GET(w http.ResponseWriter, r *http.Request) {
|
func GET(w http.ResponseWriter, r *http.Request) {
|
||||||
token, err := utils.GenerateCSRFToken()
|
token, err := utils.GenerateCSRFToken()
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Unable to start Google sign-in", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
csrfToken := CsrfToken{
|
csrfToken := CsrfToken{
|
||||||
Token: token,
|
Token: token,
|
||||||
CreateTime: time.Now(),
|
CreateTime: time.Now(),
|
||||||
@@ -25,12 +30,29 @@ func GET(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
app.Server.Cache.SetCache(r.Context(), "CsrfTokens:"+token, newCsrfToken, time.Minute*15)
|
err = app.Server.Cache.SetCache(r.Context(), "CsrfTokens:"+token, newCsrfToken, time.Minute*15)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
app.Server.Logger.Error(err.Error())
|
app.Server.Logger.Error(err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
http.Redirect(w, r, fmt.Sprintf("https://accounts.google.com/o/oauth2/auth?scope=email profile&response_type=code&access_type=offline&state=%s&redirect_uri=%s&client_id=%s", token, utils.Getenv("GOOGLE_CALLBACK"), utils.Getenv("GOOGLE_CLIENT_ID")), http.StatusFound)
|
http.SetCookie(w, &http.Cookie{
|
||||||
|
Name: "oauth_state", Value: token, Path: "/auth/google/callback", MaxAge: 900,
|
||||||
|
HttpOnly: true, Secure: session.IsHTTPS(r), SameSite: http.SameSiteLaxMode,
|
||||||
|
})
|
||||||
|
oauthURL, err := url.Parse("https://accounts.google.com/o/oauth2/auth")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Unable to start Google sign-in", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
oauthURL.RawQuery = url.Values{
|
||||||
|
"scope": {"email profile"},
|
||||||
|
"response_type": {"code"},
|
||||||
|
"access_type": {"offline"},
|
||||||
|
"state": {token},
|
||||||
|
"redirect_uri": {utils.Getenv("GOOGLE_CALLBACK")},
|
||||||
|
"client_id": {utils.Getenv("GOOGLE_CLIENT_ID")},
|
||||||
|
}.Encode()
|
||||||
|
http.Redirect(w, r, oauthURL.String(), http.StatusFound)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -55,6 +55,11 @@ func POST(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Error(w, "Unauthorized Action", http.StatusUnauthorized)
|
http.Error(w, "Unauthorized Action", http.StatusUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Unable to load setup", http.StatusInternalServerError)
|
||||||
|
app.Server.Logger.Error(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var unregisteredUser UnregisteredUser
|
var unregisteredUser UnregisteredUser
|
||||||
err = json.Unmarshal([]byte(cache), &unregisteredUser)
|
err = json.Unmarshal([]byte(cache), &unregisteredUser)
|
||||||
@@ -63,6 +68,10 @@ func POST(w http.ResponseWriter, r *http.Request) {
|
|||||||
app.Server.Logger.Error(err.Error())
|
app.Server.Logger.Error(err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if unregisteredUser.Email == "" || unregisteredUser.Code != code {
|
||||||
|
http.Error(w, "Unauthorized Action", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
err = r.ParseForm()
|
err = r.ParseForm()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -89,6 +98,11 @@ func POST(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
hashedPassword, err := utils.HashPassword(password)
|
hashedPassword, err := utils.HashPassword(password)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Unable to create account", http.StatusInternalServerError)
|
||||||
|
app.Server.Logger.Error(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
userID := uuid.New()
|
userID := uuid.New()
|
||||||
newUser := models.User{
|
newUser := models.User{
|
||||||
UserID: userID,
|
UserID: userID,
|
||||||
@@ -112,6 +126,11 @@ func POST(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if err := app.Server.Cache.DeleteCache(r.Context(), "GoogleSetup:"+code); err != nil {
|
||||||
|
http.Error(w, "Unable to complete setup", http.StatusInternalServerError)
|
||||||
|
app.Server.Logger.Error(err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
storeSession, err := session.Create(types.User{
|
storeSession, err := session.Create(types.User{
|
||||||
UserID: userID,
|
UserID: userID,
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package signinHandler
|
package signinHandler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"github.com/a-h/templ"
|
"github.com/a-h/templ"
|
||||||
"github.com/fossyy/filekeeper/app"
|
"github.com/fossyy/filekeeper/app"
|
||||||
"github.com/fossyy/filekeeper/session"
|
"github.com/fossyy/filekeeper/session"
|
||||||
@@ -9,6 +8,7 @@ import (
|
|||||||
"github.com/fossyy/filekeeper/utils"
|
"github.com/fossyy/filekeeper/utils"
|
||||||
"github.com/fossyy/filekeeper/view/client/auth/signin"
|
"github.com/fossyy/filekeeper/view/client/auth/signin"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
var errorMessages = make(map[string]string)
|
var errorMessages = make(map[string]string)
|
||||||
@@ -141,13 +141,17 @@ func POST(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cookie, err := r.Cookie("redirect")
|
cookie, err := r.Cookie("redirect")
|
||||||
if errors.Is(err, http.ErrNoCookie) {
|
if err != nil || !validRedirect(cookie.Value) {
|
||||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
http.SetCookie(w, &http.Cookie{
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: "redirect",
|
Name: "redirect",
|
||||||
MaxAge: -1,
|
MaxAge: -1,
|
||||||
|
Path: "/",
|
||||||
|
HttpOnly: true,
|
||||||
|
Secure: session.IsHTTPS(r),
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
})
|
})
|
||||||
http.Redirect(w, r, cookie.Value, http.StatusSeeOther)
|
http.Redirect(w, r, cookie.Value, http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
@@ -164,3 +168,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validRedirect(value string) bool {
|
||||||
|
return strings.HasPrefix(value, "/") && !strings.HasPrefix(value, "//") && !strings.Contains(value, `\`)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
package totpHandler
|
package totpHandler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"crypto/subtle"
|
||||||
"github.com/fossyy/filekeeper/app"
|
"github.com/fossyy/filekeeper/app"
|
||||||
"github.com/fossyy/filekeeper/session"
|
"github.com/fossyy/filekeeper/session"
|
||||||
"github.com/fossyy/filekeeper/types"
|
"github.com/fossyy/filekeeper/types"
|
||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/fossyy/filekeeper/view/client/totp"
|
"github.com/fossyy/filekeeper/view/client/totp"
|
||||||
"github.com/xlzd/gotp"
|
"github.com/xlzd/gotp"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -38,15 +39,30 @@ func POST(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
code := r.Form.Get("code")
|
code := r.Form.Get("code")
|
||||||
|
if len(code) != 6 || !isNumericCode(code) {
|
||||||
|
http.Error(w, "Invalid code", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
_, user, key := session.GetSession(r)
|
_, user, key := session.GetSession(r)
|
||||||
|
if key == "" || user.Totp == "" {
|
||||||
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
decryptedSecret, err := app.Server.Encryption.Decrypt(user.Totp)
|
decryptedSecret, err := app.Server.Encryption.Decrypt(user.Totp)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
http.Error(w, "Unable to verify code", http.StatusInternalServerError)
|
||||||
app.Server.Logger.Error(err.Error())
|
app.Server.Logger.Error(err.Error())
|
||||||
|
return
|
||||||
}
|
}
|
||||||
totp := gotp.NewDefaultTOTP(decryptedSecret)
|
totp := gotp.NewDefaultTOTP(decryptedSecret)
|
||||||
|
|
||||||
if totp.Verify(code, time.Now().Unix()) {
|
validCode := false
|
||||||
|
for _, timestamp := range []int64{time.Now().Unix() - 30, time.Now().Unix(), time.Now().Unix() + 30} {
|
||||||
|
if subtle.ConstantTimeCompare([]byte(totp.At(timestamp)), []byte(code)) == 1 {
|
||||||
|
validCode = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if validCode {
|
||||||
storeSession := session.Get(key)
|
storeSession := session.Get(key)
|
||||||
err := storeSession.Change(types.User{
|
err := storeSession.Change(types.User{
|
||||||
UserID: user.UserID,
|
UserID: user.UserID,
|
||||||
@@ -82,13 +98,17 @@ func POST(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cookie, err := r.Cookie("redirect")
|
cookie, err := r.Cookie("redirect")
|
||||||
if errors.Is(err, http.ErrNoCookie) {
|
if err != nil || !validRedirect(cookie.Value) {
|
||||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
http.SetCookie(w, &http.Cookie{
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: "redirect",
|
Name: "redirect",
|
||||||
MaxAge: -1,
|
MaxAge: -1,
|
||||||
|
Path: "/",
|
||||||
|
HttpOnly: true,
|
||||||
|
Secure: session.IsHTTPS(r),
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
})
|
})
|
||||||
http.Redirect(w, r, cookie.Value, http.StatusSeeOther)
|
http.Redirect(w, r, cookie.Value, http.StatusSeeOther)
|
||||||
return
|
return
|
||||||
@@ -105,3 +125,16 @@ func POST(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validRedirect(value string) bool {
|
||||||
|
return strings.HasPrefix(value, "/") && !strings.HasPrefix(value, "//") && !strings.Contains(value, `\`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isNumericCode(value string) bool {
|
||||||
|
for _, digit := range value {
|
||||||
|
if digit < '0' || digit > '9' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
|
|
||||||
func GET(w http.ResponseWriter, r *http.Request) {
|
func GET(w http.ResponseWriter, r *http.Request) {
|
||||||
userSession := r.Context().Value("user").(types.User)
|
userSession := r.Context().Value("user").(types.User)
|
||||||
cookie, err := r.Cookie("Session")
|
cookie, err := r.Cookie(utils.Getenv("SESSION_NAME"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
app.Server.Logger.Error(err.Error())
|
app.Server.Logger.Error(err.Error())
|
||||||
|
|||||||
@@ -12,6 +12,15 @@ func DELETE(w http.ResponseWriter, r *http.Request) {
|
|||||||
id := r.PathValue("id")
|
id := r.PathValue("id")
|
||||||
mySession := r.Context().Value("user").(types.User)
|
mySession := r.Context().Value("user").(types.User)
|
||||||
mySessionID := r.Context().Value("sessionID").(string)
|
mySessionID := r.Context().Value("sessionID").(string)
|
||||||
|
otherSessionInfo, err := session.GetSessionInfo(mySession.Email, id)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if otherSessionInfo.SessionID != id {
|
||||||
|
http.Error(w, "Session not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if id == mySessionID {
|
if id == mySessionID {
|
||||||
w.Header().Set("HX-Redirect", "/logout")
|
w.Header().Set("HX-Redirect", "/logout")
|
||||||
@@ -20,7 +29,7 @@ func DELETE(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
otherSession := session.Get(id)
|
otherSession := session.Get(id)
|
||||||
err := session.RemoveSessionInfo(mySession.Email, otherSession.ID)
|
err = session.RemoveSessionInfo(mySession.Email, otherSession.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, session.ErrorSessionNotFound) {
|
if errors.Is(err, session.ErrorSessionNotFound) {
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
|||||||
+10
-11
@@ -82,7 +82,10 @@ func (s *Session) Delete() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Session) Save(r *http.Request, w http.ResponseWriter) {
|
func (s *Session) Save(r *http.Request, w http.ResponseWriter) {
|
||||||
maxAge, _ := strconv.Atoi(utils.Getenv("SESSION_MAX_AGE"))
|
maxAge, err := strconv.Atoi(utils.Getenv("SESSION_MAX_AGE"))
|
||||||
|
if err != nil {
|
||||||
|
maxAge = 0
|
||||||
|
}
|
||||||
http.SetCookie(w, &http.Cookie{
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: utils.Getenv("SESSION_NAME"),
|
Name: utils.Getenv("SESSION_NAME"),
|
||||||
Value: s.ID,
|
Value: s.ID,
|
||||||
@@ -137,21 +140,16 @@ func RemoveSessionInfo(email string, id string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func RemoveAllSessions(email string) error {
|
func RemoveAllSessions(email string) error {
|
||||||
pattern := "UserSessionInfo:" + email + ":*"
|
sessions, err := GetSessions(email)
|
||||||
keys, err := app.Server.Cache.GetKeys(context.Background(), pattern)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
for _, sessionInfo := range sessions {
|
||||||
for _, key := range keys {
|
err = app.Server.Cache.DeleteCache(context.Background(), "Session:"+sessionInfo.SessionID)
|
||||||
parts := strings.Split(key, ":")
|
|
||||||
sessionID := parts[2]
|
|
||||||
|
|
||||||
err = app.Server.Cache.DeleteCache(context.Background(), "Session:"+sessionID)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
err = app.Server.Cache.DeleteCache(context.Background(), key)
|
err = app.Server.Cache.DeleteCache(context.Background(), "UserSessionInfo:"+email+":"+sessionInfo.SessionID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -181,7 +179,8 @@ func GetSessionInfo(email string, id string) (*SessionInfo, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GetSession(r *http.Request) (UserStatus, types.User, string) {
|
func GetSession(r *http.Request) (UserStatus, types.User, string) {
|
||||||
cookie, err := r.Cookie("Session")
|
cookieName := utils.Getenv("SESSION_NAME")
|
||||||
|
cookie, err := r.Cookie(cookieName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Unauthorized, types.User{}, ""
|
return Unauthorized, types.User{}, ""
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user