2021-01-26 10:36:53 -05:00
|
|
|
// Copyright 2020 The Macaron Authors
|
2021-01-05 08:05:40 -05:00
|
|
|
// Copyright 2020 The Gitea Authors. All rights reserved.
|
2022-11-27 13:20:29 -05:00
|
|
|
// SPDX-License-Identifier: MIT
|
2021-01-05 08:05:40 -05:00
|
|
|
|
2021-01-30 03:55:53 -05:00
|
|
|
package middleware
|
2021-01-05 08:05:40 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2023-04-13 15:45:33 -04:00
|
|
|
"strings"
|
2021-01-05 08:05:40 -05:00
|
|
|
|
|
|
|
"code.gitea.io/gitea/modules/setting"
|
|
|
|
)
|
|
|
|
|
2021-03-07 03:12:43 -05:00
|
|
|
// SetRedirectToCookie convenience function to set the RedirectTo cookie consistently
|
|
|
|
func SetRedirectToCookie(resp http.ResponseWriter, value string) {
|
2023-04-13 15:45:33 -04:00
|
|
|
SetSiteCookie(resp, "redirect_to", value, 0)
|
2021-03-07 03:12:43 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// DeleteRedirectToCookie convenience function to delete most cookies consistently
|
|
|
|
func DeleteRedirectToCookie(resp http.ResponseWriter) {
|
2023-04-13 15:45:33 -04:00
|
|
|
SetSiteCookie(resp, "redirect_to", "", -1)
|
2021-03-07 03:12:43 -05:00
|
|
|
}
|
|
|
|
|
2023-04-13 15:45:33 -04:00
|
|
|
// GetSiteCookie returns given cookie value from request header.
|
|
|
|
func GetSiteCookie(req *http.Request, name string) string {
|
2021-01-26 10:36:53 -05:00
|
|
|
cookie, err := req.Cookie(name)
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
val, _ := url.QueryUnescape(cookie.Value)
|
|
|
|
return val
|
|
|
|
}
|
2023-04-13 15:45:33 -04:00
|
|
|
|
|
|
|
// SetSiteCookie returns given cookie value from request header.
|
|
|
|
func SetSiteCookie(resp http.ResponseWriter, name, value string, maxAge int) {
|
|
|
|
cookie := &http.Cookie{
|
|
|
|
Name: name,
|
|
|
|
Value: url.QueryEscape(value),
|
|
|
|
MaxAge: maxAge,
|
|
|
|
Path: setting.SessionConfig.CookiePath,
|
|
|
|
Domain: setting.SessionConfig.Domain,
|
|
|
|
Secure: setting.SessionConfig.Secure,
|
|
|
|
HttpOnly: true,
|
|
|
|
SameSite: setting.SessionConfig.SameSite,
|
|
|
|
}
|
|
|
|
resp.Header().Add("Set-Cookie", cookie.String())
|
|
|
|
if maxAge < 0 {
|
|
|
|
// There was a bug in "setting.SessionConfig.CookiePath" code, the old default value of it was empty "".
|
|
|
|
// So we have to delete the cookie on path="" again, because some old code leaves cookies on path="".
|
|
|
|
cookie.Path = strings.TrimSuffix(setting.SessionConfig.CookiePath, "/")
|
|
|
|
resp.Header().Add("Set-Cookie", cookie.String())
|
|
|
|
}
|
|
|
|
}
|