token-handler: handle authorization through Epita CRI LDAP
This commit is contained in:
parent
58e541d6ad
commit
38902bee8d
6 changed files with 194 additions and 12 deletions
|
@ -10,6 +10,7 @@ import (
|
|||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
|
@ -38,6 +39,20 @@ func remoteValidatorHandler(f func(http.ResponseWriter, *http.Request, httproute
|
|||
}
|
||||
}
|
||||
|
||||
func authHandler(f func(http.ResponseWriter, *http.Request, httprouter.Params)) func(http.ResponseWriter, *http.Request, httprouter.Params) {
|
||||
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
||||
if flds := strings.Fields(r.Header.Get("Authorization")); len(flds) != 2 || flds[0] != "Bearer" {
|
||||
http.Error(w, `{"errmsg": "Authorization required"}`, http.StatusUnauthorized)
|
||||
} else if sessionid, err := base64.StdEncoding.DecodeString(flds[1]); err != nil {
|
||||
http.Error(w, fmt.Sprintf(`{"errmsg": %q}`, err), http.StatusNotAcceptable)
|
||||
} else if _, err := getSession(sessionid); err != nil {
|
||||
http.Error(w, fmt.Sprintf(`{"errmsg": %q}`, err), http.StatusUnauthorized)
|
||||
} else {
|
||||
f(w, r, ps)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func rawHandler(f func(*http.Request, httprouter.Params, []byte) (interface{}, error), access ...func(*Student, *http.Request) error) func(http.ResponseWriter, *http.Request, httprouter.Params) {
|
||||
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
|
||||
if addr := r.Header.Get("X-Forwarded-For"); addr != "" {
|
||||
|
@ -50,10 +65,26 @@ func rawHandler(f func(*http.Request, httprouter.Params, []byte) (interface{}, e
|
|||
var ret interface{}
|
||||
var err error = nil
|
||||
|
||||
// Read Authorization header
|
||||
var student *Student = nil
|
||||
if flds := strings.Fields(r.Header.Get("Authorization")); len(flds) == 2 && flds[0] == "Bearer" {
|
||||
if sessionid, err := base64.StdEncoding.DecodeString(flds[1]); err != nil {
|
||||
http.Error(w, fmt.Sprintf(`{"errmsg": %q}`, err), http.StatusNotAcceptable)
|
||||
} else if session, err := getSession(sessionid); err != nil {
|
||||
http.Error(w, fmt.Sprintf(`{"errmsg": %q}`, err), http.StatusUnauthorized)
|
||||
return
|
||||
} else if std, err := getStudent(int(session.IdStudent)); err != nil {
|
||||
http.Error(w, fmt.Sprintf(`{"errmsg": %q}`, err), http.StatusUnauthorized)
|
||||
return
|
||||
} else {
|
||||
student = &std
|
||||
}
|
||||
}
|
||||
|
||||
// Check access limitation
|
||||
for _, a := range access {
|
||||
if err := a(nil, r); err != nil {
|
||||
http.Error(w, fmt.Sprintf("{errmsg:\"You're not allowed to access this page this way!\"}", err), http.StatusForbidden)
|
||||
if err := a(student, r); err != nil {
|
||||
http.Error(w, fmt.Sprintf(`{"errmsg":%q}`, err), http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
|
Reference in a new issue