prepare user system

This commit is contained in:
SowinskiBraeden committed 2023-09-28 21:42:58 -07:00
1 parent ecf4fabd86
commit 5bc4adceea
13 files changed
+470 -18

No files matched your search

+44 -2
View File
@@ -1,14 +1,20 @@
package handlers
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/SowinskiBraeden/DeviceBookingAPI/api"
"github.com/SowinskiBraeden/DeviceBookingAPI/models"
"github.com/SowinskiBraeden/DeviceBookingAPI/util"
"github.com/go-playground/validator/v10"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/bson"
"go.uber.org/zap"
"github.com/SowinskiBraeden/DeviceBookingAPI/config"
@@ -27,9 +33,14 @@ type App struct {
// New creates a new mux router and all the routes
func (a *App) New() *mux.Router {
// Detect if system is new and needs default admin
a.newSystem()
r := mux.NewRouter()
cow := Cow{DB: databases.NewCowDatabase(a.dbHelper)}
device := Device{DB: databases.NewDeviceDatabase(a.dbHelper)}
// user := User{DB: databases.NewUserDatabase(a.dbHelper)}
// healthcheck
r.HandleFunc("/health", healthCheckHandler)
@@ -37,7 +48,7 @@ func (a *App) New() *mux.Router {
apiCreate := r.PathPrefix("/api/v1").Subrouter()
// Data handlers, create, delete, update etc.
apiCreate.Handle("/cow/{cow_id}", api.Middleware(http.HandlerFunc(cow.CowByIDHandler))).Methods("GET") // By Object ID not Cow Name
apiCreate.Handle("/cow/{cow_id}", api.Middleware(http.HandlerFunc(cow.CowByObjectIDHandler))).Methods("GET") // By Object ID not Cow Name
apiCreate.Handle("/cows", api.Middleware(http.HandlerFunc(cow.CowHandler))).Methods("GET") // Returns all cows
apiCreate.Handle("/cows", api.Middleware(http.HandlerFunc(cow.CowHandlerQuery))).Methods("POST") // Returns list of cows based of name query
apiCreate.Handle("/cows/new", api.Middleware(http.HandlerFunc(cow.NewCowHandler))).Methods("POST") // Create new cow
@@ -46,7 +57,7 @@ func (a *App) New() *mux.Router {
apiCreate.Handle("/cows/get_devices/{cow_id}", api.Middleware(http.HandlerFunc(device.GetChildDevices))).Methods("POST") // Returns a list of devices from a given Cow obj
apiCreate.Handle("cows/bookings/{cow_id}", api.Middleware(http.HandlerFunc(cow.GetBookingsHandler))).Methods("GET") // Returns all bookings for a given cow
apiCreate.Handle("/device/{device_id}", api.Middleware(http.HandlerFunc(device.DeviceByIDHandler))).Methods("GET") // By Object ID not Device Name
apiCreate.Handle("/device/{device_id}", api.Middleware(http.HandlerFunc(device.DeviceByObjectIDHandler))).Methods("GET") // By Object ID not Device Name
apiCreate.Handle("/devices", api.Middleware(http.HandlerFunc(device.DeviceHandler))).Methods("GET") // Returns all devices
apiCreate.Handle("/devices", api.Middleware(http.HandlerFunc(device.DeviceHandlerQuery))).Methods("POST") // Returns list of devices based of name query
apiCreate.Handle("/devices/new", api.Middleware(http.HandlerFunc(device.NewDeviceHandler))).Methods("POST") // create new device
@@ -93,3 +104,34 @@ func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
})
_, _ = io.WriteString(w, string(b))
}
func (a *App) newSystem() {
var DB databases.UserDatabase = databases.NewUserDatabase(a.dbHelper)
dbResp, err := DB.Find(context.TODO(), bson.M{})
if err != nil {
zap.S().With(err).Error("Unable to detect new system: failed to get users")
}
if len(dbResp) == 0 {
fmt.Println("Admin account setup...")
for {
defaultAdmin := util.CreateDefaultAdmin(DB)
if util.Confirm("Are the above credentials correct?") {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, err := DB.InsertOne(ctx, defaultAdmin)
if err != nil {
log.Printf("Failed to create an admin\n")
break
}
log.Printf("Successfully created default admin")
log.Printf("Your default admin ID is %s", defaultAdmin.Details.UID)
break
}
}
}
}
+1 -1
View File
@@ -77,7 +77,7 @@ func (c Cow) CowHandlerQuery(w http.ResponseWriter, r *http.Request) {
}
// CowByIDHandler returns a cow by ID
func (c Cow) CowByIDHandler(w http.ResponseWriter, r *http.Request) {
func (c Cow) CowByObjectIDHandler(w http.ResponseWriter, r *http.Request) {
cowID := mux.Vars(r)["cow_id"]
cID, err := primitive.ObjectIDFromHex(cowID)
+4 -4
View File
@@ -79,12 +79,12 @@ func (d Device) DeviceHandlerQuery(w http.ResponseWriter, r *http.Request) {
}
// DeviceByIDHandler returns a cow by ID
func (d Device) DeviceByIDHandler(w http.ResponseWriter, r *http.Request) {
deviceID := mux.Vars(r)["cow_id"]
func (d Device) DeviceByObjectIDHandler(w http.ResponseWriter, r *http.Request) {
deviceID := mux.Vars(r)["device_id"]
dbResp, err := d.DB.FindOne(context.Background(), bson.M{"_id": deviceID})
if err != nil {
config.ErrorStatus("failed to get device by ID", http.StatusNotFound, w, err)
config.ErrorStatus("failed to get device by ObjectID", http.StatusNotFound, w, err)
return
}
@@ -100,7 +100,7 @@ func (d Device) DeviceByIDHandler(w http.ResponseWriter, r *http.Request) {
// NewDeviceHandler inserts a new cow into the collection and returns a result and error
func (d Device) NewDeviceHandler(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
var deviceDetails models.DeviceDetails // Json data will represent the cow details model
var deviceDetails models.DeviceDetails // Json data will represent the device details model
defer cancel()
// validate the request body
+84
View File
@@ -0,0 +1,84 @@
package handlers
import (
"context"
"encoding/json"
"net/http"
"time"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"github.com/SowinskiBraeden/DeviceBookingAPI/config"
"github.com/SowinskiBraeden/DeviceBookingAPI/databases"
"github.com/SowinskiBraeden/DeviceBookingAPI/models"
)
type User struct {
DB databases.UserDatabase
}
// CowByIDHandler returns a cow by ID
func (u User) UserByObjectIDHandler(w http.ResponseWriter, r *http.Request) {
userID := mux.Vars(r)["user_object_id"]
cID, err := primitive.ObjectIDFromHex(userID)
if err != nil {
config.ErrorStatus("failed to get objectID from Hex", http.StatusBadRequest, w, err)
return
}
dbResp, err := u.DB.FindOne(context.Background(), bson.M{"_id": cID})
if err != nil {
config.ErrorStatus("failed to get cow by ID", http.StatusNotFound, w, err)
return
}
b, err := json.Marshal(models.UserResponse{Status: http.StatusOK, Message: "success", Data: map[string]interface{}{"result": dbResp}})
if err != nil {
config.ErrorStatus("failed to marshal response", http.StatusInternalServerError, w, err)
return
}
w.WriteHeader(http.StatusOK)
w.Write(b)
}
// TODO: Handle User.Details.UserType properly i.e only SuperUser
// NewUserHandler inserts a new cow into the collection and returns a result and error
func (u User) NewUserHandler(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
var userDetails models.UserDetails // Json data will represent the user details model
defer cancel()
// validate the request body
if err := json.NewDecoder(r.Body).Decode(&userDetails); err != nil {
config.ErrorStatus("failed to unpack request body", http.StatusInternalServerError, w, err)
return
}
// use the validator library to validate required fields
if validationErr := validate.Struct(&userDetails); validationErr != nil {
config.ErrorStatus("invalid request body", http.StatusBadRequest, w, validationErr)
return
}
newUser := models.User{
ID: primitive.NewObjectID().Hex(),
Details: userDetails,
}
result, err := u.DB.InsertOne(ctx, newUser)
if err != nil {
config.ErrorStatus("failed to insert user", http.StatusBadRequest, w, err)
return
}
b, err := json.Marshal(models.UserResponse{Status: http.StatusCreated, Message: "success", Data: map[string]interface{}{"result": result}})
if err != nil {
config.ErrorStatus("failed to marshal response", http.StatusInternalServerError, w, err)
return
}
w.WriteHeader(http.StatusCreated)
w.Write(b)
}