From f2a6633a62298b19d84cd415aa2f0364f04356c6 Mon Sep 17 00:00:00 2001 From: Kegan Dougal Date: Mon, 20 Feb 2017 16:18:09 +0000 Subject: [PATCH] Add auth package - Extract the access token from the HTTP request --- .../dendrite/clientapi/auth/auth.go | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/github.com/matrix-org/dendrite/clientapi/auth/auth.go diff --git a/src/github.com/matrix-org/dendrite/clientapi/auth/auth.go b/src/github.com/matrix-org/dendrite/clientapi/auth/auth.go new file mode 100644 index 000000000..4d2c9b094 --- /dev/null +++ b/src/github.com/matrix-org/dendrite/clientapi/auth/auth.go @@ -0,0 +1,43 @@ +package auth + +import ( + "fmt" + "net/http" + "strings" +) + +// VerifyAccessToken verifies that an access token was supplied in the given HTTP request +// and returns the user ID it corresponds to. Returns an error if there is no access token +// or the token is invalid. +func VerifyAccessToken(req *http.Request) (userID string, err error) { + _, tokenErr := extractAccessToken(req) + if tokenErr != nil { + // err = MatrixError(MatrixError.M_MISSING_TOKEN, tokenErr.Error()) + return + } + // TODO: Do something with the token + return +} + +// extractAccessToken from a request, or return an error detailing what went wrong. +func extractAccessToken(req *http.Request) (string, error) { + authBearer := req.Header.Get("Authorization") + queryToken := req.URL.Query().Get("access_token") + if authBearer != "" && queryToken != "" { + return "", fmt.Errorf("mixing Authorization headers and access_token query parameters") + } + + if queryToken != "" { + return queryToken, nil + } + + if authBearer != "" { + parts := strings.SplitN(authBearer, " ", 2) + if len(parts) != 2 || parts[0] != "Bearer" { + return "", fmt.Errorf("invalid Authorization header") + } + return parts[1], nil + } + + return "", fmt.Errorf("missing access token") +}