61 lines
1.9 KiB
Go
61 lines
1.9 KiB
Go
package initialize
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"git.schreifuchs.ch/schreifuchs/ng-blog/internal/auth"
|
|
"git.schreifuchs.ch/schreifuchs/ng-blog/internal/config"
|
|
"git.schreifuchs.ch/schreifuchs/ng-blog/internal/model"
|
|
"git.schreifuchs.ch/schreifuchs/ng-blog/internal/posts"
|
|
"git.schreifuchs.ch/schreifuchs/ng-blog/pkg/cors"
|
|
"git.schreifuchs.ch/schreifuchs/ng-blog/pkg/middlewares"
|
|
"git.schreifuchs.ch/schreifuchs/ng-blog/web"
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
// CreateMux creates and configures a mux router with authentication and post-related routes.
|
|
func CreateMux(cfg *config.Config) (r *mux.Router) {
|
|
r = mux.NewRouter()
|
|
r.Use(cors.HandlerForOrigin("*"))
|
|
|
|
app(r.PathPrefix("/api").Subrouter(), cfg)
|
|
frontend(r.PathPrefix("/"))
|
|
|
|
r.Methods("OPTIONS").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// The CORS middleware should set up the headers for you
|
|
w.WriteHeader(http.StatusNoContent)
|
|
})
|
|
|
|
return
|
|
}
|
|
|
|
func frontend(r *mux.Route) {
|
|
frontend := web.Frontend
|
|
r.Handler(
|
|
middlewares.AddPrefix("/dist/frontend/browser",
|
|
middlewares.FallbackFile(
|
|
frontend,
|
|
"/dist/frontend/browser/index.html",
|
|
http.FileServerFS(frontend),
|
|
),
|
|
))
|
|
}
|
|
|
|
func app(r *mux.Router, cfg *config.Config) {
|
|
db := model.Init()
|
|
blg := posts.New(db)
|
|
auth := auth.New(&cfg.Auth, db)
|
|
|
|
// auth
|
|
r.HandleFunc("/auth/login", auth.Login).Methods("POST")
|
|
r.HandleFunc("/auth/signup", auth.Signup).Methods("POST")
|
|
r.Handle("/auth/password", auth.Authenticated(auth.ChangePassword)).Methods("PUT")
|
|
r.Handle("/auth/logout", auth.Authenticated(auth.Logout)).Methods("DELETE")
|
|
|
|
// Posts
|
|
r.Handle("/posts", auth.Authenticated(blg.SavePost, model.RoleUser, model.RoleAdmin)).Methods("POST")
|
|
r.Handle("/posts", auth.Authenticated(blg.SavePost, model.RoleUser, model.RoleAdmin)).Methods("PUT")
|
|
r.Handle("/posts/{postID}", auth.Authenticated(blg.DeletePost, model.RoleUser, model.RoleAdmin)).Methods("DELETE")
|
|
r.Handle("/posts", http.HandlerFunc(blg.GetAllPosts)).Methods("GET")
|
|
}
|