#17 add dockerfile for api
This commit is contained in:
34
api/src/middleware/auth.go
Normal file
34
api/src/middleware/auth.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"api/src/utils"
|
||||
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type ContextKey string
|
||||
|
||||
const TOKEN_KEY ContextKey = "token"
|
||||
|
||||
func EnsureAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
tokenStr := r.Header.Get("Authorization")
|
||||
if (tokenStr == "") || (len(tokenStr) < len("Bearer ")) {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
tokenStr = tokenStr[len("Bearer "):]
|
||||
|
||||
token, err := utils.VerifyToken(tokenStr)
|
||||
if err != nil {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var newContext = context.WithValue(r.Context(), TOKEN_KEY, token)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(newContext))
|
||||
})
|
||||
}
|
||||
28
api/src/middleware/cors.go
Normal file
28
api/src/middleware/cors.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
)
|
||||
|
||||
func EnableCors(next http.Handler) http.Handler {
|
||||
var frontent_url = os.Getenv("FRONTEND_URL")
|
||||
if frontent_url == "" {
|
||||
log.Fatal("FRONTEND_URL is not set")
|
||||
}
|
||||
log.Println("FRONTEND_URL is", frontent_url)
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", frontent_url)
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization")
|
||||
|
||||
if r.Method == "OPTIONS" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
30
api/src/middleware/logger.go
Normal file
30
api/src/middleware/logger.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type WrappedWriter struct {
|
||||
http.ResponseWriter
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
func (w *WrappedWriter) WriteHeader(code int) {
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
w.StatusCode = code
|
||||
}
|
||||
|
||||
func Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
wrapped := &WrappedWriter{
|
||||
ResponseWriter: w,
|
||||
StatusCode: http.StatusOK,
|
||||
}
|
||||
next.ServeHTTP(wrapped, r)
|
||||
log.Println(wrapped.StatusCode, r.Method, r.URL.Path, time.Since(start))
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user