2022-12-11 02:05:03 +03:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"git.nefrace.ru/nefrace/nashboard/storage"
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
|
|
|
Host string
|
|
|
|
Mux *mux.Router
|
2022-12-11 16:22:24 +03:00
|
|
|
Db storage.MongodbStorage
|
2022-12-11 02:05:03 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
var ErrUnauthorized ApiError = ApiError{Status: http.StatusUnauthorized, Err: "Unauthorized"}
|
|
|
|
var ErrBadRequest ApiError = ApiError{Status: http.StatusBadRequest, Err: "bad request"}
|
|
|
|
|
|
|
|
var anon storage.User = storage.User{
|
|
|
|
Id: primitive.ObjectID{},
|
|
|
|
Username: "Anonymous",
|
|
|
|
IsAdmin: false,
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s Server) InitHandlers() {
|
|
|
|
r := s.Mux
|
|
|
|
r.Use(s.Logger)
|
|
|
|
r.Use(s.UserInContext)
|
|
|
|
apiRouter := r.PathPrefix("/api").Subrouter()
|
|
|
|
authRouter := apiRouter.PathPrefix("/auth").Subrouter()
|
|
|
|
authRouter.Path("/reg").Methods("POST").HandlerFunc(MakeHTTPHandler(s.handleRegister))
|
|
|
|
authRouter.Path("/login").Methods("POST").HandlerFunc(MakeHTTPHandler(s.handleLogin))
|
|
|
|
authRouter.Path("/logout").Methods("POST").HandlerFunc(MakeHTTPHandler(s.handleLogout))
|
|
|
|
|
|
|
|
userRouter := apiRouter.PathPrefix("/user").Subrouter()
|
|
|
|
userRouter.Use(s.AuthorizedOnly)
|
2022-12-11 15:28:10 +03:00
|
|
|
// userRouter.Use(s.AuthorizedOnly)
|
2022-12-11 02:05:03 +03:00
|
|
|
userRouter.Path("/me").HandlerFunc(MakeHTTPHandler(s.handleGetMe))
|
|
|
|
userRouter.Path("/all").HandlerFunc(MakeHTTPHandler(s.handleAllUsers))
|
2022-12-11 15:28:10 +03:00
|
|
|
bookmarkRouter := apiRouter.PathPrefix("/bookmark").Subrouter()
|
|
|
|
bookmarkRouter.Use(s.AuthorizedOnly)
|
|
|
|
bookmarkRouter.Path("").Methods("GET").HandlerFunc(MakeHTTPHandler(s.handleGetBookmarks))
|
|
|
|
bookmarkRouter.Path("").Methods("POST").HandlerFunc(MakeHTTPHandler(s.handleNewBookmark))
|
2022-12-11 16:22:24 +03:00
|
|
|
bookmarkRouter.Path("/random").HandlerFunc(MakeHTTPHandler(s.handleGetRandomBookmarks))
|
|
|
|
bookmarkRouter.Path("/random/{count}").HandlerFunc(MakeHTTPHandler(s.handleGetRandomBookmarks))
|
2022-12-11 02:05:03 +03:00
|
|
|
|
|
|
|
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))
|
|
|
|
}
|