/
response.go
192 lines (162 loc) · 5.81 KB
/
response.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// Itero - Online iterative vote application
// Copyright (C) 2020 Joseph Boudou
//
// 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, either version 3 of the
// License, or (at your option) any later version.
//
// 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 server
import (
"context"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/JBoudou/Itero/pkg/b64buff"
"github.com/JBoudou/Itero/pkg/slog"
gs "github.com/gorilla/sessions"
)
// Response is used to construct the response to a HTTP request.
type Response interface {
// SendJSON sends a JSON as response.
// On success statuc code is http.StatusOK.
SendJSON(ctx context.Context, data interface{})
// SendError sends an error as response.
// If the error is an HttpError, its code and msg are used in the HTPP response.
// Also log the error.
SendError(context.Context, error)
// SendRedirect sends a permanent redirection.
SendRedirect(ctx context.Context, req *Request, url string)
// SendLoginAccepted create new credential for the user and send it as response.
SendLoginAccepted(ctx context.Context, usr User, req *Request, profileInfo interface{})
// SendUnloggedId adds a cookie for unlogged users.
SendUnloggedId(ctx context.Context, user User, req *Request) error
}
type response struct {
writer http.ResponseWriter
}
func (self response) SendJSON(ctx context.Context, data interface{}) {
if err := ctx.Err(); err != nil {
self.SendError(ctx, err)
return
}
buff, err := json.Marshal(data)
if err != nil {
self.SendError(ctx, err)
return
}
self.writer.Header().Add("content-type", "application/JSON")
if _, err = self.writer.Write(buff); err != nil {
slog.CtxLogf(ctx, "Write error: %v", err)
}
}
func (self response) SendError(ctx context.Context, err error) {
send := func(statusCode int, msg string) {
http.Error(self.writer, msg, statusCode)
slog.CtxLogf(ctx, "%d %s: %s", statusCode, msg, err)
}
var pError HttpError
if errors.As(err, &pError) {
send(pError.Code, pError.Msg)
} else if errors.Is(err, context.Canceled) {
send(http.StatusInternalServerError, "Canceled")
} else if errors.Is(err, context.DeadlineExceeded) {
send(http.StatusGatewayTimeout, "Timed out")
} else {
send(http.StatusInternalServerError, "Internal error")
}
}
func (self response) SendRedirect(ctx context.Context, req *Request, url string) {
if err := ctx.Err(); err != nil {
self.SendError(ctx, err)
return
}
http.Redirect(self.writer, req.original, url, http.StatusPermanentRedirect)
}
// SessionAnswer is the type of the value sent by request creating a new session.
// It is a part of the API between the server and the frontend.
//
// Profile is not defined in this package. It must contains information about the user corresponding
// to the session. For security reason, Profile must not contain the user name, id, hash or
// password.
type SessionAnswer struct {
SessionId string
Expires time.Time
Profile interface{}
}
func (self response) SendLoginAccepted(ctx context.Context, user User, req *Request, profile interface{}) {
if err := ctx.Err(); err != nil {
self.SendError(ctx, err)
return
}
if !user.Logged {
self.SendError(ctx, NewHttpError(http.StatusInternalServerError, "Unlogged user",
"wrong user argument"))
return
}
sessionId, err := MakeSessionId()
if err != nil {
self.SendError(ctx, err)
return
}
answer := SessionAnswer{SessionId: sessionId, Profile: profile}
session := NewSession(sessionStore, sessionStore.Options, &answer, user)
if err = session.Save(req.original, self.writer); err != nil {
slog.CtxLogf(ctx, "Error saving session: %v", err)
}
self.SendJSON(ctx, answer)
}
func (self response) SendUnloggedId(ctx context.Context, user User, req *Request) error {
if err := ctx.Err(); err != nil {
return err
}
if user.Logged {
return errors.New("Wrong argument to SendUnloggedId")
}
session := NewUnloggedUser(unloggedStore, unloggedStore.Options, user)
if err := session.Save(req.original, self.writer); err != nil {
slog.CtxLogf(ctx, "Error saving session: %v", err)
}
return nil
}
// MakeSessionId create a new session id.
//
// This is a low level function, made available for tests.
func MakeSessionId() (string, error) {
return b64buff.RandomString(4)
}
// NewSession creates a new session for the given user.
//
// This is a low level function, made available for tests. Use SendLoginAccepted instead.
func NewSession(st gs.Store, opts *gs.Options, answer *SessionAnswer, user User) (session *gs.Session) {
session = gs.NewSession(st, SessionName)
sessionOptions := *opts
session.Options = &sessionOptions
session.IsNew = true
answer.Expires = time.Now().Add(sessionMaxAge * time.Second)
session.Values[sessionKeySessionId] = answer.SessionId
session.Values[sessionKeyUserName] = user.Name
session.Values[sessionKeyUserId] = user.Id
session.Values[sessionKeyDeadline] = answer.Expires.Unix() + sessionGraceTime
return
}
// NewUnloggedUser creates a new unlogged session for the given anonymous user.
//
// This is a low level function, made available for tests. Use SendUnloggedId instead.
func NewUnloggedUser(st gs.Store, opts *gs.Options, user User) (session *gs.Session) {
session = gs.NewSession(st, SessionUnlogged)
sessionOptions := *opts
session.Options = &sessionOptions
session.IsNew = true
session.Values[sessionKeyUserId] = user.Id
session.Values[sessionKeyHash] = user.Hash
return
}