forked from u5surf/auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
75 lines (62 loc) · 1.87 KB
/
auth.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
// Copyright 2018 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.
package main
import (
"errors"
"fmt"
"net/http"
"github.com/go-kit/kit/log"
"github.com/gorilla/mux"
)
var (
errNoCookie = fmt.Errorf("no %s cookie provided", cookieName)
errUserNotFound = errors.New("user not found")
)
// extractUserId tries to find the Moov userId associated to the cookie data.
// This function will never return a blank userId with a nil error.
func extractUserId(auth authable, r *http.Request) (string, error) {
cookie := extractCookie(r)
if cookie == nil {
return "", errNoCookie
}
userId, err := auth.findUserId(cookie.Value)
if err != nil {
return "", errUserNotFound
}
if userId == "" {
return "", errUserNotFound
}
return userId, nil
}
func addAuthRoutes(router *mux.Router, logger log.Logger, auth authable, o *oauth, repo userRepository) {
router.Methods("GET").Path("/auth/check").HandlerFunc(checkAuth(logger, auth, o, repo))
}
func checkAuth(logger log.Logger, auth authable, o *oauth, repo userRepository) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w = wrapResponseWriter(w, r, "checkAuth")
if allowForOptions(w, r) {
return // was a CORS pre-flight request
}
user, _ := getUserFromCookie(auth, repo, r)
token, err := o.requestHasValidOAuthToken(r)
if user == nil && err != nil { // no user from cookie and no oauth credentials
w.WriteHeader(http.StatusForbidden)
return
}
var userId string
if user != nil && user.ID != "" {
userId = user.ID
}
if token != nil && userId == "" {
userId = token.GetUserID()
}
if userId == "" {
w.WriteHeader(http.StatusForbidden)
return
}
w.Header().Set("X-User-Id", userId)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
}
}