-
Notifications
You must be signed in to change notification settings - Fork 3
/
session.go
271 lines (238 loc) · 8.53 KB
/
session.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package user
import (
"errors"
"fmt"
"net/http"
"github.com/budden/semdict/pkg/privilegecode"
"github.com/budden/semdict/pkg/sddb"
"github.com/budden/semdict/pkg/apperror"
"github.com/budden/semdict/pkg/shared"
"github.com/gin-gonic/gin"
)
// EnsureLoggedIn causes a request to be aborted with an error
// if the user is not logged in. Can only be used downstream from SetUserStatusMiddleware
// middleware
func EnsureLoggedIn(c *gin.Context) {
if !IsLoggedIn(c) {
apperror.Panic500If(apperror.ErrDummy, "Please log in to view this page")
}
}
// EnsureNotLoggedIn ensures that a request will be aborted with an error
// if the user is already logged in. Can only be used downstream from SetUserStatusMiddleware
// middleware
func EnsureNotLoggedIn(c *gin.Context) {
if IsLoggedIn(c) {
// FIXME - invent "Panic401" or do whatever else meaningful here,
// but don't return 500.
apperror.Panic500If(apperror.ErrDummy, "Please log OUT to view this page")
}
}
// IsLoggedIn is true if the user is logged in with valid credentials.
// Can only be used downstream from SetUserStatusMiddleware middleware
func IsLoggedIn(c *gin.Context) bool {
loggedInInterface, exists := c.Get("is_logged_in")
loggedIn := loggedInInterface.(bool)
if !exists {
apperror.GracefullyExitAppIf(apperror.ErrDummy, "Only call this one after SetUserStatusMiddleware")
}
return loggedIn
}
// GetSDUserIdOrZero returns sduserid for a logged in user, or 0 for a not logged
// Use downstream from SetUserStatusMiddleware middleware
func GetSDUserIdOrZero(c *gin.Context) int32 {
if !IsLoggedIn(c) {
return 0
}
sduserid, mustExist := c.Get("sduserid")
if !mustExist {
apperror.GracefullyExitAppIf(apperror.ErrDummy, "sduser must be set if a user is logged in")
}
if sduserIdint32, ok := sduserid.(int32); ok {
return sduserIdint32
}
apperror.GracefullyExitAppIf(apperror.ErrDummy, "sduser must be int32 in a gin context")
return -1 // this must never happen
}
// SetUserStatusMiddleware sets a flag indicating whether the request was from an authenticated user or not
func SetUserStatusMiddleware() gin.HandlerFunc {
return setUserStatusFn
}
func setUserStatusFn(c *gin.Context) {
tokenPresent, tokenValid, sduserid := getAndValidateToken(c)
isLoggedIn := false
if !tokenPresent {
// ok, it will be false
} else if !tokenValid {
// session expired, or, worse, it is an attack
apperror.LogAttack(c, errors.New("setUserStatusFn: invalid token"))
endSessionIfThereIsOne(c)
} else {
// hence token is present and valid
isLoggedIn = true
}
c.Set("is_logged_in", isLoggedIn)
if isLoggedIn {
c.Set("sduserid", int32(sduserid))
} else {
c.Set("sduserid", nil)
}
}
func getAndValidateToken(c *gin.Context) (tokenPresent, tokenValid bool, sduserid int) {
if shared.SecretConfigData.UserAlwaysLoggedIn != 0 {
// special case for debugging
tokenPresent = true
tokenValid = true
sduserid = shared.SecretConfigData.UserAlwaysLoggedIn
} else {
var token string
token, tokenPresent = getSessionToken(c)
if !tokenPresent {
return
}
params := map[string]interface{}{"token": token}
res, err := sddb.NamedReadQuery(`select sduserid from session
where eid=:token and expireat > current_timestamp limit 1`,
params)
apperror.Panic500AndErrorIf(err, "Failed to check validity of your session, sorry. Please logout and retry")
defer sddb.CloseRows(res)()
for res.Next() {
err1 := res.Scan(&sduserid)
apperror.GracefullyExitAppIf(err1, "Failed to check if session is present, error is «%#v»", err1)
}
tokenValid = (sduserid != 0)
}
return
}
// LoginSubmitPostHandler handles login route
func LoginSubmitPostHandler(c *gin.Context) {
// We could check that user is not yet logged in, but we won't do
// Obtain the POSTed username and password values
nickname := c.PostForm("nickname")
password := c.PostForm("password")
// just in case, if there is an old session, we close it.
endSessionIfThereIsOne(c)
// Check if the username/password combination is valid
sduserid := isUserValid(nickname, password)
if sduserid != 0 {
// check if the use have the login privilege
if !isUserHavePrivilege(sduserid, privilegecode.Login) {
c.HTML(http.StatusBadRequest, "general.t.html",
shared.GeneralTemplateParams{Message: fmt.Sprintf("Sorry, %s, but you have no login privilege", nickname)})
return
}
// If the username/password is valid set the token in a cookie
token := generateSessionToken()
recordSessionTokenIntoDb(nickname, token)
c.SetCookie("token", token, 3600, "", "", false, true)
c.HTML(http.StatusOK, "general.t.html",
shared.GeneralTemplateParams{Message: fmt.Sprintf("Welcome, %s!", nickname)})
} else {
c.HTML(http.StatusBadRequest, "general.t.html",
shared.GeneralTemplateParams{Message: "Go away, stranger!"})
}
}
// isUserValid checks that the user is valid, in this case non-zero sduserid is returned
func isUserValid(nickname, password string) (sduserid int32) {
if !isNicknameInValidFormat(nickname) {
apperror.Panic500If(apperror.ErrDummy, "Nickname has an illegal format (e.g. invalid characters)")
}
if validatePassword(password) != nil {
apperror.Panic500If(apperror.ErrDummy, "Password has an illegal format (e.g. invalid characters)")
}
var sud SDUserData
getSDUserDataFromDb(nickname, &sud)
if CheckPasswordAgainstSaltAndHash(password, sud.Salt, sud.Hash) {
sduserid = sud.ID
} else {
sduserid = 0
}
return
}
// function could be general, but it's error messages are login process specific. FIXME
func getSDUserDataFromDb(nickname string, sud *SDUserData) {
// have <= 1 record only due to unique index
params := map[string]interface{}{"nickname": nickname}
res, err := sddb.NamedReadQuery("select * from sduser where nickname = :nickname limit 1", params)
apperror.Panic500If(err, "Unable to login, sorry")
defer sddb.CloseRows(res)()
dataFound := false
for res.Next() {
err1 := res.StructScan(sud)
apperror.GracefullyExitAppIf(err1, "Failed to read sduser's record: «%s»", err1)
dataFound = true
}
if !dataFound {
apperror.Panic500AndErrorIf(err, "Attempt to log on as a non-existing user «%s»", nickname)
}
return
}
func isUserHavePrivilege(sduserid int32, privilegekind privilegecode.Enum) (granted bool) {
params := map[string]interface{}{"sduserid": sduserid, "privilegekind": privilegekind}
res, err := sddb.NamedReadQuery("select isuserhaveprivilege(:sduserid, :privilegekind)", params)
apperror.GracefullyExitAppIf(err, "Error obtaining user privilege: «%s»", err)
defer sddb.CloseRows(res)()
dataFound := false
for res.Next() {
err1 := res.Scan(&granted)
apperror.GracefullyExitAppIf(err1, "Failed to read sduser's record: «%s»", err1)
dataFound = true
}
if !dataFound {
apperror.GracefullyExitAppIf(apperror.ErrDummy, "got no data from isuserhaveprivilege")
}
return granted
}
func generateSessionToken() string {
return GenNonce(32)
}
func recordSessionTokenIntoDb(nickname, token string) {
err := sddb.WithTransaction(func(trans *sddb.TransactionType) (err1 error) {
res, err1 := trans.Tx.Queryx("select begin_session($1,$2)", nickname, token)
// FIXME process exception with too_many_sessions mentioned
apperror.GracefullyExitAppIf(err1, "Failed to begin session, error is «%#v»", err1)
for res.Next() {
// it returns an id, but we don't need it
}
return
})
apperror.GracefullyExitAppIf(err, "Failed to begin session 2, error is «%#v»", err)
}
func getSessionToken(c *gin.Context) (token string, found bool) {
token, err := c.Cookie("token")
if err == http.ErrNoCookie {
return
}
apperror.GracefullyExitAppIf(err, "Unknown error getting session token: «%s»", err)
found = true
return
}
// Logout performs a logout
func Logout(c *gin.Context) {
endSessionIfThereIsOne(c)
// Redirect to the home page
c.Redirect(http.StatusTemporaryRedirect, "/")
}
// clear the cookie and delete the session from db
func endSessionIfThereIsOne(c *gin.Context) {
token, tokenFound := getSessionToken(c)
if !tokenFound {
return
}
c.SetCookie("token", "", -1, "", "", false, true)
err := sddb.WithTransaction(func(trans *sddb.TransactionType) (err1 error) {
res, err1 := trans.Tx.Queryx("select end_session($1)", token)
apperror.GracefullyExitAppIf(err1, "Failed to end session, error is «%#v»", err1)
for res.Next() {
// don't need the result
}
return
})
apperror.GracefullyExitAppIf(err, "Failed to end session 2, error is «%#v»", err)
}
// LoginFormPageHandler renders a /loginform page
func LoginFormPageHandler(c *gin.Context) {
EnsureNotLoggedIn(c)
c.HTML(http.StatusOK,
"loginform.t.html",
shared.LoginFormParams{ /*CaptchaID: "100500"*/ })
}