-
-
Notifications
You must be signed in to change notification settings - Fork 684
/
flash.go
95 lines (86 loc) · 2.28 KB
/
flash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright (C) 2019 Nicola Murino
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package httpd
import (
"encoding/base64"
"encoding/json"
"net/http"
"time"
"github.com/drakkan/sftpgo/v2/internal/util"
)
const (
flashCookieName = "message"
)
func newFlashMessage(errorStrig, i18nMessage string) flashMessage {
return flashMessage{
ErrorString: errorStrig,
I18nMessage: i18nMessage,
}
}
type flashMessage struct {
ErrorString string `json:"error"`
I18nMessage string `json:"message"`
}
func (m *flashMessage) getI18nError() *util.I18nError {
if m.ErrorString == "" && m.I18nMessage == "" {
return nil
}
return util.NewI18nError(
util.NewGenericError(m.ErrorString),
m.I18nMessage,
)
}
func setFlashMessage(w http.ResponseWriter, r *http.Request, message flashMessage) {
value, err := json.Marshal(message)
if err != nil {
return
}
http.SetCookie(w, &http.Cookie{
Name: flashCookieName,
Value: base64.URLEncoding.EncodeToString(value),
Path: "/",
Expires: time.Now().Add(60 * time.Second),
MaxAge: 60,
HttpOnly: true,
Secure: isTLS(r),
SameSite: http.SameSiteLaxMode,
})
w.Header().Add("Cache-Control", `no-cache="Set-Cookie"`)
}
func getFlashMessage(w http.ResponseWriter, r *http.Request) flashMessage {
var msg flashMessage
cookie, err := r.Cookie(flashCookieName)
if err != nil {
return msg
}
http.SetCookie(w, &http.Cookie{
Name: flashCookieName,
Value: "",
Path: "/",
Expires: time.Unix(0, 0),
MaxAge: -1,
HttpOnly: true,
Secure: isTLS(r),
SameSite: http.SameSiteLaxMode,
})
value, err := base64.URLEncoding.DecodeString(cookie.Value)
if err != nil {
return msg
}
err = json.Unmarshal(value, &msg)
if err != nil {
return flashMessage{}
}
return msg
}