-
Notifications
You must be signed in to change notification settings - Fork 0
/
authuser.go
61 lines (47 loc) · 1.67 KB
/
authuser.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
package middleware
import (
"github.com/gorilla/sessions"
"github.com/junhsieh/iojson"
"log"
"net/http"
)
// AuthUserHandler ...
func AuthUserHandler(store *sessions.FilesystemStore, sessionName string) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("DEBUG_AuthUser: Inside")
o := r.Context().Value(iojson.CKey).(*iojson.IOJSON)
// Get a session. Get() always returns a session, even if empty.
session, err := store.Get(r, sessionName)
if err != nil {
//http.Error(w, err.Error(), http.StatusInternalServerError)
//w.WriteHeader(http.StatusInternalServerError)
o.AddError(err.Error())
return
}
// TODO: how to determine whether a session is expired?
// TODO: add a logic to continue only when session.IsNew is false (can be true too when the session is expired)
log.Printf("DEBUG_AuthUser: IsNew Session: %v", session.IsNew)
// TODO: need a way to check if session exists.
if _, ok := session.Values["Username"]; !ok {
//w.WriteHeader(http.StatusForbidden)
o.AddError("You do not have the permission")
return
}
o.AddData("welcome", "Welcom, "+session.Values["Username"].(string))
h.ServeHTTP(w, r)
// TODO: Add a logic to support both session/cookie and Header/Authorization
/*
Authorization := r.Header.Get("Authorization")
log.Printf("Authorization: %v", Authorization)
switch Authorization {
case "user2":
w.WriteHeader(http.StatusForbidden)
o.AddError("You do not have the permission")
case "user3":
o.AddError("You do not have the permission")
}
*/
})
}
}