You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.5 KiB

package Api
import (
"log"
"net/http"
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Api/Auth"
"github.com/gorilla/mux"
)
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf(
"%s %s %s, Content Length: %d",
r.RemoteAddr,
r.Method,
r.RequestURI,
r.ContentLength,
)
next.ServeHTTP(w, r)
})
}
func authenticationMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
userSession Auth.Session
err error
)
userSession, err = Auth.CheckCookie(r)
if err != nil {
http.Error(w, "Forbidden", http.StatusUnauthorized)
return
}
log.Printf(
"Authenticated user: %s (%s)",
userSession.Email,
userSession.UserID,
)
next.ServeHTTP(w, r)
})
}
func InitApiEndpoints(router *mux.Router) {
var (
api *mux.Router
adminApi *mux.Router
)
log.Println("Initializing API routes...")
api = router.PathPrefix("/api/v1/").Subrouter()
api.Use(loggingMiddleware)
api.HandleFunc("/posts/front-page", getFrontPagePosts).Methods("GET")
api.HandleFunc("/post", getPostsPublic).Methods("GET")
api.HandleFunc("/post/{postID}", getPostPublic).Methods("GET")
// Define routes for authentication
api.HandleFunc("/admin/login", Auth.Login).Methods("POST")
api.HandleFunc("/admin/logout", Auth.Logout).Methods("GET")
api.HandleFunc("/admin/me", Auth.Me).Methods("GET")
adminApi = api.PathPrefix("/admin/").Subrouter()
adminApi.Use(authenticationMiddleware)
// Define routes for posts api
adminApi.HandleFunc("/post", getPosts).Methods("GET")
adminApi.HandleFunc("/post/{postID}", getPost).Methods("GET")
adminApi.HandleFunc("/post", createPost).Methods("POST")
adminApi.HandleFunc("/post/{postID}", updatePost).Methods("PUT")
adminApi.HandleFunc("/post/{postID}", deletePost).Methods("DELETE")
adminApi.HandleFunc("/post/{postID}/publish", publishPost).Methods("GET")
adminApi.HandleFunc("/post/{postID}/image", createPostImage).Methods("POST")
adminApi.HandleFunc("/post/{postID}/image/{imageID}", deletePostImage).Methods("DELETE")
// Define routes for users api
adminApi.HandleFunc("/user", getUsers).Methods("GET")
adminApi.HandleFunc("/user", createUser).Methods("POST")
adminApi.HandleFunc("/user/{userID}", getUser).Methods("GET")
adminApi.HandleFunc("/user/{userID}", updateUser).Methods("PUT")
adminApi.HandleFunc("/user/{userID}", deletePost).Methods("DELETE")
adminApi.HandleFunc("/user/{userID}/update-password", Auth.UpdatePassword).Methods("PUT")
}