token-validator: use cookies instead of localStorage to store auth token
This commit is contained in:
parent
72a4015288
commit
a4a7b48a4f
6 changed files with 98 additions and 92 deletions
|
@ -11,7 +11,6 @@ import (
|
|||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
|
@ -51,13 +50,16 @@ func rawHandler(f func(http.ResponseWriter, *http.Request, httprouter.Params, []
|
|||
|
||||
// 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 {
|
||||
if cookie, err := r.Cookie("auth"); err == nil {
|
||||
if sessionid, err := base64.StdEncoding.DecodeString(cookie.Value); err != nil {
|
||||
http.Error(w, fmt.Sprintf(`{"errmsg": %q}`, err), http.StatusNotAcceptable)
|
||||
return
|
||||
} 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 {
|
||||
} else if session.IdStudent == nil {
|
||||
student = nil
|
||||
} else if std, err := getStudent(int(*session.IdStudent)); err != nil {
|
||||
http.Error(w, fmt.Sprintf(`{"errmsg": %q}`, err), http.StatusUnauthorized)
|
||||
return
|
||||
} else {
|
||||
|
@ -156,13 +158,15 @@ func apiHandler(f DispatchFunction, access ...func(*Student, *http.Request) erro
|
|||
|
||||
func apiAuthHandler(f func(Student, httprouter.Params, []byte) (interface{}, error), access ...func(*Student, *http.Request) error) func(http.ResponseWriter, *http.Request, httprouter.Params) {
|
||||
return rawHandler(responseHandler(func (r *http.Request, ps httprouter.Params, b []byte) (interface{}, error) {
|
||||
if flds := strings.Fields(r.Header.Get("Authorization")); len(flds) != 2 || flds[0] != "Bearer" {
|
||||
if cookie, err := r.Cookie("auth"); err != nil {
|
||||
return nil, errors.New("Authorization required")
|
||||
} else if sessionid, err := base64.StdEncoding.DecodeString(flds[1]); err != nil {
|
||||
} else if sessionid, err := base64.StdEncoding.DecodeString(cookie.Value); err != nil {
|
||||
return nil, err
|
||||
} else if session, err := getSession(sessionid); err != nil {
|
||||
return nil, err
|
||||
} else if std, err := getStudent(int(session.IdStudent)); err != nil {
|
||||
} else if session.IdStudent == nil {
|
||||
return nil, errors.New("Authorization required")
|
||||
} else if std, err := getStudent(int(*session.IdStudent)); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return f(std, ps, b)
|
||||
|
|
Reference in a new issue