MCPcopy Create free account
hub / github.com/TomDoesTech/GOTTH / AddUserToContext

Method AddUserToContext

internal/middleware/middleware.go:119–160  ·  view source on GitHub ↗
(next http.Handler)

Source from the content-addressed store, hash-verified

117var UserKey UserContextKey = "user"
118
119func (m *AuthMiddleware) AddUserToContext(next http.Handler) http.Handler {
120 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
121
122 sessionCookie, err := r.Cookie(m.sessionCookieName)
123
124 if err != nil {
125 next.ServeHTTP(w, r)
126 return
127 }
128
129 decodedValue, err := b64.StdEncoding.DecodeString(sessionCookie.Value)
130
131 if err != nil {
132 next.ServeHTTP(w, r)
133 return
134 }
135
136 splitValue := strings.Split(string(decodedValue), ":")
137
138 if len(splitValue) != 2 {
139 next.ServeHTTP(w, r)
140 return
141 }
142
143 sessionID := splitValue[0]
144 userID := splitValue[1]
145
146 fmt.Println("sessionID", sessionID)
147 fmt.Println("userID", userID)
148
149 user, err := m.sessionStore.GetUserFromSession(sessionID, userID)
150
151 if err != nil {
152 next.ServeHTTP(w, r)
153 return
154 }
155
156 ctx := context.WithValue(r.Context(), UserKey, user)
157
158 next.ServeHTTP(w, r.WithContext(ctx))
159 })
160}
161
162func GetUser(ctx context.Context) *store.User {
163 user := ctx.Value(UserKey)

Callers

nothing calls this directly

Calls 2

GetUserFromSessionMethod · 0.65
ServeHTTPMethod · 0.45

Tested by

no test coverage detected