Mercurial > gemma
comparison pkg/middleware/dbconn.go @ 2690:ef59a4255670
Added http middlewares to connect to db and parse input as JSON. This complements the JSONHandler which is for JSON in to JSON out. The new middlewares are for JSON in to abitrary out.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Fri, 15 Mar 2019 16:45:34 +0100 |
parents | |
children | 6f9d00c8cc38 |
comparison
equal
deleted
inserted
replaced
2689:8f919fe629f9 | 2690:ef59a4255670 |
---|---|
1 // This is Free Software under GNU Affero General Public License v >= 3.0 | |
2 // without warranty, see README.md and license for details. | |
3 // | |
4 // SPDX-License-Identifier: AGPL-3.0-or-later | |
5 // License-Filename: LICENSES/AGPL-3.0.txt | |
6 // | |
7 // Copyright (C) 2019 by via donau | |
8 // – Österreichische Wasserstraßen-Gesellschaft mbH | |
9 // Software engineering by Intevation GmbH | |
10 // | |
11 // Author(s): | |
12 // * Sascha L. Teichmann <sascha.teichmann@intevation.de> | |
13 | |
14 package middleware | |
15 | |
16 import ( | |
17 "context" | |
18 "database/sql" | |
19 "fmt" | |
20 "log" | |
21 "net/http" | |
22 | |
23 "gemma.intevation.de/gemma/pkg/auth" | |
24 ) | |
25 | |
26 type wrapDBKeyType int | |
27 | |
28 const wrapDBKey wrapDBKeyType = 0 | |
29 | |
30 func GetDBConn(req *http.Request) *sql.Conn { | |
31 if conn, ok := req.Context().Value(wrapDBKey).(*sql.Conn); ok { | |
32 return conn | |
33 } | |
34 return nil | |
35 } | |
36 | |
37 func DBConn(next http.Handler) http.Handler { | |
38 | |
39 return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { | |
40 token, ok := auth.GetToken(req) | |
41 if !ok { | |
42 http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) | |
43 return | |
44 } | |
45 session := auth.Sessions.Session(token) | |
46 if session == nil { | |
47 http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) | |
48 return | |
49 } | |
50 parent := req.Context() | |
51 if err := auth.RunAs(parent, session.User, func(conn *sql.Conn) error { | |
52 ctx := context.WithValue(parent, wrapDBKey, conn) | |
53 req = req.WithContext(ctx) | |
54 next.ServeHTTP(rw, req) | |
55 return nil | |
56 }); err != nil { | |
57 log.Printf("error: %v\n", err) | |
58 http.Error(rw, fmt.Sprintf("error: %v", err), http.StatusInternalServerError) | |
59 } | |
60 }) | |
61 } |