Skip to content
Snippets Groups Projects
models.go 2.29 KiB
Newer Older
  • Learn to ignore specific revisions
  • Alexis Poyen's avatar
    Alexis Poyen committed
    package models
    
    import (
    	"net/http"
    	"strings"
    
    	"github.com/jinzhu/gorm"
    
    	// Needed for sqlite
    	_ "github.com/jinzhu/gorm/dialects/sqlite"
    )
    
    // DataHandler init a gorm DB an presents API handlers
    type DataHandler struct {
    	db *gorm.DB
    }
    
    // ErrorIDDoesNotExist = "id does not exist"
    const ErrorIDDoesNotExist = "id does not exist"
    
    // ErrorIDIsMissing = "id is missing"
    const ErrorIDIsMissing = "id is missing"
    
    // ErrorCannotAccessRessource = "You can not access this ressource"
    const ErrorCannotAccessRessource = "You can not access this ressource"
    
    // ErrorRoleOfLoggedUser = "Could not get role of logged user"
    const ErrorRoleOfLoggedUser = "Could not get role of logged user"
    
    // ErrorNotAuthorizeMethodOnRessource = "You're not authorize to execute this method on this ressource."
    const ErrorNotAuthorizeMethodOnRessource = "You're not authorize to execute this method on this ressource."
    
    // NewDataHandler init a DataHandler and returns a pointer to it
    func NewDataHandler() *DataHandler {
    	db, err := gorm.Open("sqlite3", "./data/test.db")
    	if err != nil {
    		panic("failed to connect database")
    	}
    	db.LogMode(true)
    
    	// Add FK with SQLite doesn't work
    	// db.Model(&Operation{}).AddForeignKey("creditor", "bank_account(id)", "Set Null", "Set Null")
    
    	// Migrate the schema
    	return &DataHandler{db: db}
    }
    
    // ProcessAPI redirect API call to DataHandler to each correct API func
    func (d *DataHandler) ProcessAPI(w http.ResponseWriter, r *http.Request) {
    	api := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/"), "/")[0]
    	switch api {
    	}
    
    }
    
    func (d *DataHandler) getLoggedUser(w http.ResponseWriter, r *http.Request) interface{} {
    	// user := auth.GetLoggedUserTechnical(w, r)
    	// if user.Role != "" && (user.Role == "BANKER") {
    	// 	var o UserBanker
    	// 	if err := d.db.Where(reqUserID, user.ID).First(&o).Error; err != nil {
    	// 		o := UserBanker{UserID: user.ID, Name: user.Login}
    	// 		d.db.Create(&o)
    	// 		d.db.Where(reqUserID, user.ID).First(&o)
    	// 		return o
    	// 	}
    	// 	return o
    	// } else if user.Role != "" && (user.Role == "CLIENT") {
    	// 	var o UserClient
    	// 	if err := d.db.Where(reqUserID, user.ID).First(&o).Error; err != nil {
    	// 		o := UserClient{UserID: user.ID, Name: user.Login}
    	// 		d.db.Create(&o)
    	// 		d.db.Where(reqUserID, user.ID).First(&o)
    	// 		return o
    	// 	}
    
    	// 	return o
    	// }
    
    	return nil
    }