diff --git a/cmd/warehost-ftp/config.go b/cmd/warehost-ftp/config.go index 8fca2e3..2e56104 100644 --- a/cmd/warehost-ftp/config.go +++ b/cmd/warehost-ftp/config.go @@ -13,7 +13,7 @@ type Config struct { Path string `yaml:"path"` } `yaml:"log"` DatabaseDebug bool `yaml:"databasedebug"` - FTPPath string `yaml:"data"` + Own string `yaml:"own"` Host string `yaml:"host"` Web string `yaml:"web"` Port int `yaml:"port"` diff --git a/cmd/warehost-ftp/config.yml.example b/cmd/warehost-ftp/config.yml.example index 88c10d5..ea1191c 100644 --- a/cmd/warehost-ftp/config.yml.example +++ b/cmd/warehost-ftp/config.yml.example @@ -4,6 +4,6 @@ log: path: test.log databasedebug: false port: 2222 -data: /tmp/ftp/%d/ +own: /tmp/ftp/%d/ host: /tmp/ftp-domain/%s/ web: /tmp/ftp-web/%d/ diff --git a/cmd/warehost-ftp/driver.go b/cmd/warehost-ftp/driver.go index cdaa53e..fe6b7d6 100644 --- a/cmd/warehost-ftp/driver.go +++ b/cmd/warehost-ftp/driver.go @@ -13,15 +13,25 @@ import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" + host "dev.sum7.eu/sum7/warehost/modul/host" + web "dev.sum7.eu/sum7/warehost/modul/web" system "dev.sum7.eu/sum7/warehost/system" ) +const ( + DriverOwner = "warehost" + DriverGroup = "http" + DriverFolderOwn = "home" + DriverFolderDomain = "domain" + DriverFolderWeb = "web" +) + type FileDriver struct { - RootPath string - db *gorm.DB - Perm ftpd.Perm - login system.Login - conn *ftpd.Conn + config Config + db *gorm.DB + Perm ftpd.Perm + login system.Login + conn *ftpd.Conn } type FackFileInfo struct { @@ -41,7 +51,7 @@ func (f *FackFileInfo) Name() string { return f.name } func (f *FackFileInfo) Owner() string { - return "warehost" + return DriverOwner } func (f *FackFileInfo) Size() int64 { return 0 @@ -51,7 +61,7 @@ func (f *FackFileInfo) ModTime() time.Time { } func (f *FackFileInfo) Group() string { - return "http" + return DriverGroup } type FileInfo struct { @@ -87,10 +97,22 @@ func (driver *FileDriver) realPath(path string) (string, bool) { real := false if len(paths) > 1 && driver.login.ID > 0 { switch paths[1] { - case "data": - root = fmt.Sprintf(driver.RootPath, driver.login.ID) + case DriverFolderOwn: + root = fmt.Sprintf(driver.Own, driver.login.ID) paths = append([]string{paths[0]}, paths[2:]...) real = true + case DriverFolderDomain: + if len(paths) > 2 { + root = fmt.Sprintf(driver.Host, driver.login.ID) + paths = append([]string{paths[0]}, paths[3:]...) + real = true + } + case DriverFolderWeb: + if len(paths) > 2 { + root = fmt.Sprintf(driver.Web, driver.login.ID) + paths = append([]string{paths[0]}, paths[3:]...) + real = true + } } } return filepath.Join(append([]string{root}, paths...)...), real @@ -179,14 +201,39 @@ func (driver *FileDriver) ListDir(path string, callback func(ftpd.FileInfo) erro }) return nil } else { - if path == "/" { - for _, i := range []string{"data", "web", "host"} { + switch path { + case "/": + for _, i := range []string{DriverFolderOwn, DriverFolderDomain, DriverFolderWeb} { err := callback(&FackFileInfo{name: i}) if err != nil { return err } } return nil + case fmt.Sprintf("/%s", DriverFolderDomain): + var list []*host.Web + driver.db.Preload("Domain.Profil.Login").Order("length(subdomain) asc").Find(&list) + for _, i := range list { + domain := i.Domain.FQDN + if len(item.Subdomain) > 0 { + domain = fmt.Sprintf("%s.%s", i.Subdomain, domain) + } + err := callback(&FackFileInfo{name: domain}) + if err != nil { + return err + } + } + return nil + case fmt.Sprintf("/%s", DriverFolderWeb): + var list []*web.Website + driver.db.Find(&list) + for _, i := range list { + err := callback(&FackFileInfo{name: strconv.Itoa(i.ID)}) + if err != nil { + return err + } + } + return nil } return errors.New("No path") } @@ -323,11 +370,11 @@ func (driver *FileDriver) PutFile(destPath string, data io.Reader, appendData bo } type FileDriverFactory struct { - RootPath string - db *gorm.DB - Perm ftpd.Perm + config Config + db *gorm.DB + Perm ftpd.Perm } func (factory *FileDriverFactory) NewDriver() (ftpd.Driver, error) { - return &FileDriver{RootPath: factory.RootPath, db: factory.db, Perm: factory.Perm}, nil + return &FileDriver{config: factory.config, db: factory.db, Perm: factory.Perm}, nil } diff --git a/cmd/warehost-ftp/main.go b/cmd/warehost-ftp/main.go index 63d9f48..3096678 100644 --- a/cmd/warehost-ftp/main.go +++ b/cmd/warehost-ftp/main.go @@ -46,7 +46,7 @@ func main() { opt := &ftpd.ServerOpts{ Name: "", - Factory: &FileDriverFactory{RootPath: config.FTPPath, db: dbconnection, Perm: ftpd.NewSimplePerm("warehost", "http")}, + Factory: &FileDriverFactory{Config: config, db: dbconnection, Perm: ftpd.NewSimplePerm("warehost", "http")}, Port: config.Port, Auth: WarehostAuth{db: dbconnection}, } diff --git a/lib/api/main.go b/lib/api/main.go index e312c61..fbf9b60 100644 --- a/lib/api/main.go +++ b/lib/api/main.go @@ -1,19 +1,17 @@ package api import ( + "context" "encoding/json" - "io" "net/http" log "github.com/Sirupsen/logrus" // TODO-Bad - "goji.io" - "golang.org/x/net/context" libsession "dev.sum7.eu/sum7/warehost/lib/session" ) // Handle with response -type Handle func(ctx context.Context, w http.ResponseWriter, r *http.Request) (interface{}, *ErrorResult) +type Handle func(w http.ResponseWriter, r *http.Request) // ErrorResult struct for api error answer type ErrorResult struct { @@ -31,8 +29,20 @@ type JSONResult struct { } `json:"session,omitempty"` } -// JSONOutput generate default json answer -func JSONOutput(ctx context.Context, w http.ResponseWriter, r *http.Request, data interface{}, errorresult *ErrorResult) { +// SessionHandler Handler to manage session of api request +func SessionHandler(h Handle) Handle { + return func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + sess := libsession.SessionStart(w, r) + ctx = context.WithValue(ctx, "session", sess) + r = r.WithContext(ctx) + h(w, r) + } +} + +// JSONWrite generate default json answer +func JSONWrite(w http.ResponseWriter, r *http.Request, data interface{}, errorresult *ErrorResult) { + ctx := r.Context() sess := ctx.Value("session").(libsession.Session) result := JSONResult{Data: data, Error: errorresult} result.Session.Login = sess.Get("login") @@ -52,19 +62,17 @@ func JSONOutput(ctx context.Context, w http.ResponseWriter, r *http.Request, dat w.Write(js) } -// SessionHandler Handler to manage session of api request -func SessionHandler(h Handle) goji.HandlerFunc { - return func(ctx context.Context, w http.ResponseWriter, r *http.Request) { - sess := libsession.SessionStart(w, r) - ctx = context.WithValue(ctx, "session", sess) - data, err := h(ctx, w, r) - JSONOutput(ctx, w, r, data, err) - } -} - //JSONDecoder handle complete request of JSON -func JSONDecoder(r io.Reader, data interface{}, w http.ResponseWriter, logger *log.Entry) (returnerr *ErrorResult) { - err := json.NewDecoder(r).Decode(data) +func JSONDecoder(w http.ResponseWriter, r *http.Request, logger *log.Entry, data interface{}) (returnerr *ErrorResult) { + if r.Header.Get("Content-Type") != "application/json" { + logger.Error("fetch wrong request type") + returnerr = &ErrorResult{ + Message: "Internal Request Error", + } + w.WriteHeader(http.StatusBadRequest) + return + } + err := json.NewDecoder(r.Body).Decode(data) if err != nil { logger.Error("fetch request") returnerr = &ErrorResult{ diff --git a/modul/host/api.go b/modul/host/api.go index ee6cbea..184f69b 100644 --- a/modul/host/api.go +++ b/modul/host/api.go @@ -7,7 +7,6 @@ import ( "github.com/jinzhu/gorm" "goji.io" "goji.io/pat" - "golang.org/x/net/context" libapi "dev.sum7.eu/sum7/warehost/lib/api" liblog "dev.sum7.eu/sum7/warehost/lib/log" @@ -25,88 +24,96 @@ func BindAPI(db *gorm.DB, router *goji.Mux, prefix string) { dbconnection = db log = liblog.NewModulLog(MODULNAME) - router.HandleFuncC(pat.Post(prefix+"/signup"), libapi.SessionHandler(system.LoginHandler(signup))) - router.HandleFuncC(pat.Get(prefix+"/signup"), libapi.SessionHandler(system.LoginHandler(checkSignup))) - router.HandleFuncC(pat.Delete(prefix+"/delete"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(delete)))) - router.HandleFuncC(pat.Get(prefix+"/profil"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(profil)))) + router.HandleFunc(pat.Post(prefix+"/signup"), libapi.SessionHandler(system.LoginHandler(signup))) + router.HandleFunc(pat.Get(prefix+"/signup"), libapi.SessionHandler(system.LoginHandler(checkSignup))) + router.HandleFunc(pat.Delete(prefix+"/delete"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(delete)))) + router.HandleFunc(pat.Get(prefix+"/profil"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(profil)))) - router.HandleFuncC(pat.Get(prefix+"/domain"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainList)))) - router.HandleFuncC(pat.Get(prefix+"/domain/:domainid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainShow)))) - router.HandleFuncC(pat.Post(prefix+"/domain"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainAdd)))) - router.HandleFuncC(pat.Patch(prefix+"/domain/:domainid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainEdit)))) - router.HandleFuncC(pat.Delete(prefix+"/domain/:domainid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainDelete)))) + router.HandleFunc(pat.Get(prefix+"/domain"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainList)))) + router.HandleFunc(pat.Get(prefix+"/domain/:domainid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainShow)))) + router.HandleFunc(pat.Post(prefix+"/domain"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainAdd)))) + router.HandleFunc(pat.Patch(prefix+"/domain/:domainid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainEdit)))) + router.HandleFunc(pat.Delete(prefix+"/domain/:domainid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainDelete)))) - router.HandleFuncC(pat.Get(prefix+"/domain/:domainid/web"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(webList)))) - router.HandleFuncC(pat.Post(prefix+"/domain/:domainid/web"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(webAdd)))) - router.HandleFuncC(pat.Patch(prefix+"/domain/:domainid/web/:webid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(webEdit)))) - router.HandleFuncC(pat.Delete(prefix+"/domain/:domainid/web/:webid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(webDelete)))) + router.HandleFunc(pat.Get(prefix+"/domain/:domainid/web"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(webList)))) + router.HandleFunc(pat.Post(prefix+"/domain/:domainid/web"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(webAdd)))) + router.HandleFunc(pat.Patch(prefix+"/domain/:domainid/web/:webid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(webEdit)))) + router.HandleFunc(pat.Delete(prefix+"/domain/:domainid/web/:webid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(webDelete)))) - router.HandleFuncC(pat.Get(prefix+"/domain/:domainid/mail"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(mailList)))) - router.HandleFuncC(pat.Post(prefix+"/domain/:domainid/mail"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(mailAdd)))) - router.HandleFuncC(pat.Patch(prefix+"/domain/:domainid/mail/:mailid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(mailEdit)))) - router.HandleFuncC(pat.Delete(prefix+"/domain/:domainid/mail/:mailid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(mailDelete)))) + router.HandleFunc(pat.Get(prefix+"/domain/:domainid/mail"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(mailList)))) + router.HandleFunc(pat.Post(prefix+"/domain/:domainid/mail"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(mailAdd)))) + router.HandleFunc(pat.Patch(prefix+"/domain/:domainid/mail/:mailid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(mailEdit)))) + router.HandleFunc(pat.Delete(prefix+"/domain/:domainid/mail/:mailid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(mailDelete)))) - router.HandleFuncC(pat.Get(prefix+"/database"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseList)))) - router.HandleFuncC(pat.Post(prefix+"/database"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseAdd)))) - router.HandleFuncC(pat.Patch(prefix+"/database/:databaseid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseEdit)))) - router.HandleFuncC(pat.Delete(prefix+"/database/:databaseid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseDelete)))) + router.HandleFunc(pat.Get(prefix+"/database"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseList)))) + router.HandleFunc(pat.Post(prefix+"/database"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseAdd)))) + router.HandleFunc(pat.Patch(prefix+"/database/:databaseid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseEdit)))) + router.HandleFunc(pat.Delete(prefix+"/database/:databaseid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseDelete)))) // ADMIN APIS - router.HandleFuncC(pat.Get(prefix+"/profils"), libapi.SessionHandler(system.LoginHandler(profilList))) - router.HandleFuncC(pat.Patch(prefix+"/profil/:id"), libapi.SessionHandler(system.LoginHandler(toggleReseller))) + router.HandleFunc(pat.Get(prefix+"/profils"), libapi.SessionHandler(system.LoginHandler(profilList))) + router.HandleFunc(pat.Patch(prefix+"/profil/:id"), libapi.SessionHandler(system.LoginHandler(toggleReseller))) } -func checkSignup(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - login := ctx.Value("login").(*system.Login) - returndata = false - logger := log.GetLog(r, "checksignup") +func checkSignupAllow(login *system.Login) bool { run := login.Superadmin if !run { var profil Profil dbconnection.Joins("LEFT JOIN invite invite ON invite.login=host_profil.login").Where("invite.invited=?", login.ID).Find(&profil) run = profil.Reseller } - returndata = run - if run { - logger.Info("done") - return - } - w.WriteHeader(http.StatusUnauthorized) - logger.Info("not allowed") - return + return run } -func signup(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func checkSignup(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + login := ctx.Value("login").(*system.Login) + returndata := checkSignupAllow(login) + logger := log.GetLog(r, "checksignup") + if returndata { + logger.Info("done") + } else { + logger.Info("not allowed") + } + libapi.JSONWrite(w, r, returndata, nil) +} + +func signup(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*system.Login) logger := log.GetLog(r, "signup") - returndata, returnerr = checkSignup(ctx, w, r) - if returndata.(bool) { + if checkSignupAllow(login) { profil := &Profil{LoginID: login.ID} if err := dbconnection.Create(profil).Error; err != nil { + w.WriteHeader(http.StatusInternalServerError) if strings.Contains(err.Error(), "duplicate key") { - returndata = false logger.Warning("exists already") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "already signup"}) return } logger.Error("database: during create host profil: ", err) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} - w.WriteHeader(http.StatusInternalServerError) + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") + libapi.JSONWrite(w, r, true, nil) return } - return + w.WriteHeader(http.StatusUnauthorized) + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "You are not allowed to signup"}) } -func delete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func delete(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + logger := log.GetLog(r, "delete") profil := ctx.Value("profil").(*Profil) - returndata = true dbconnection.Unscoped().Delete(profil) - return + logger.Info("done") + libapi.JSONWrite(w, r, true, nil) } -func profil(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func profil(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + logger := log.GetLog(r, "profil") profil := ctx.Value("profil").(*Profil) - returndata = profil - return + logger.Info("done") + libapi.JSONWrite(w, r, profil, nil) } diff --git a/modul/host/api_test.go b/modul/host/api_test.go index 4edabed..3d768a0 100644 --- a/modul/host/api_test.go +++ b/modul/host/api_test.go @@ -12,8 +12,8 @@ import ( func loginTest(session *test.Request, assertion *assert.Assertions) { result, w := session.JSONRequest("POST", "/login", system.RequestLogin{Username: "root", Password: "root"}) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) } func TestAPI(t *testing.T) { @@ -35,71 +35,71 @@ func TestAPI(t *testing.T) { * TEST signup */ result, w := session.JSONRequest("POST", "/host/signup", nil) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("POST", "/host/signup", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("POST", "/host/signup", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusInternalServerError, w.StatusCode) + assertion.Equal(false, result.Data) /* * TEST checksignup */ session.Clean() result, w = session.JSONRequest("GET", "/host/signup", nil) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("GET", "/host/signup", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) /* * TEST delete */ session.Clean() result, w = session.JSONRequest("DELETE", "/host/delete", nil) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("DELETE", "/host/delete", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("DELETE", "/host/delete", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(false, result.Data) /* * TEST profil */ session.Clean() result, w = session.JSONRequest("GET", "/host/profil", nil) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("GET", "/host/profil", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(false, result.Data) // Need a Profile for Next tests result, w = session.JSONRequest("POST", "/host/signup", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("GET", "/host/profil", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.NotEqual(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.NotEqual(false, result.Data) } diff --git a/modul/host/apidatabase.go b/modul/host/apidatabase.go index a7c7f30..93413cb 100644 --- a/modul/host/apidatabase.go +++ b/modul/host/apidatabase.go @@ -5,16 +5,16 @@ import ( "strconv" "goji.io/pat" - "golang.org/x/net/context" libapi "dev.sum7.eu/sum7/warehost/lib/api" system "dev.sum7.eu/sum7/warehost/system" ) -func getDatabase(ctx context.Context, w http.ResponseWriter) (database Database, returnerr *libapi.ErrorResult) { +func getDatabase(w http.ResponseWriter, r *http.Request) (database Database, returnerr *libapi.ErrorResult) { + ctx := r.Context() login := ctx.Value("login").(*system.Login) profil := ctx.Value("profil").(*Profil) - id, err := strconv.ParseInt(pat.Param(ctx, "databaseid"), 10, 64) + id, err := strconv.ParseInt(pat.Param(r, "databaseid"), 10, 64) if err != nil { returnerr = &libapi.ErrorResult{ Message: "Internal Request Error", @@ -22,12 +22,12 @@ func getDatabase(ctx context.Context, w http.ResponseWriter) (database Database, w.WriteHeader(http.StatusBadRequest) return } - database = Database{ID: id} + database = Database{} if login.Superadmin { - dbconnection.Find(&database) + dbconnection.Where("ID = ?", id).Find(&database) } else { - dbconnection.Where(map[string]int64{"profil": profil.ID}).Find(&database) + dbconnection.Where(map[string]int64{"ID": id, "profil": profil.ID}).Find(&database) } if database.ID <= 0 { @@ -37,10 +37,10 @@ func getDatabase(ctx context.Context, w http.ResponseWriter) (database Database, return } -func databaseList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func databaseList(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*system.Login) profil := ctx.Value("profil").(*Profil) - returndata = false logger := log.GetLog(r, "databaselist") var database []*Database if login.Superadmin && r.URL.Query().Get("filter") == "all" { @@ -49,18 +49,18 @@ func databaseList(ctx context.Context, w http.ResponseWriter, r *http.Request) ( dbconnection.Where("profil = ?", profil.ID).Preload("Profil").Find(&database) } logger.Info("done") - returndata = database - return + libapi.JSONWrite(w, r, database, nil) } -func databaseAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func databaseAdd(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() profil := ctx.Value("profil").(*Profil) - returndata = false logger := log.GetLog(r, "databaseadd") var databaseRequest Database - returnerr = libapi.JSONDecoder(r.Body, &databaseRequest, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &databaseRequest) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } @@ -73,29 +73,28 @@ func databaseAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (r if err := dbconnection.Create(database).Error; err != nil { logger.Error("database: during create host database: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } -func databaseEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func databaseEdit(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "databaseedit") - database, returnerr := getDatabase(ctx, w) + database, returnerr := getDatabase(w, r) if returnerr != nil { logger.Info("not found") + libapi.JSONWrite(w, r, false, returnerr) return } logger = logger.WithField("dbID", database.ID) var databaseRequest Database - returnerr = libapi.JSONDecoder(r.Body, &databaseRequest, w, logger) + returnerr = libapi.JSONDecoder(w, r, logger, &databaseRequest) if returnerr != nil { - return + libapi.JSONWrite(w, r, false, returnerr) } database.Password = databaseRequest.Password @@ -104,21 +103,20 @@ func databaseEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) ( if err := dbconnection.Save(database).Error; err != nil { logger.Error("database: during modify host database: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } -func databaseDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func databaseDelete(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "databasedelete") - database, returnerr := getDatabase(ctx, w) + database, returnerr := getDatabase(w, r) if returnerr != nil { logger.Info("not found") + libapi.JSONWrite(w, r, false, returnerr) return } logger = logger.WithField("dbID", database.ID) @@ -126,10 +124,9 @@ func databaseDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) if err := dbconnection.Unscoped().Delete(database).Error; err != nil { logger.Error("database: during create host database: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } diff --git a/modul/host/apidatabase_test.go b/modul/host/apidatabase_test.go index 90730e0..8ef8418 100644 --- a/modul/host/apidatabase_test.go +++ b/modul/host/apidatabase_test.go @@ -27,30 +27,30 @@ func TestAPIDatabase(t *testing.T) { loginTest(session, assertion) result, w := session.JSONRequest("DELETE", "/host/delete", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) // Need a Profile for Next tests result, w = session.JSONRequest("POST", "/host/signup", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) /* * TEST databaseList */ session.Clean() result, w = session.JSONRequest("GET", "/host/database", nil) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("GET", "/host/database", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.NotEqual(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.NotEqual(false, result.Data) result, w = session.JSONRequest("GET", "/host/database?filter=all", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.NotEqual(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.NotEqual(false, result.Data) /* * TEST databaseAdd @@ -59,15 +59,15 @@ func TestAPIDatabase(t *testing.T) { Password: "example.de", Comment: "test", }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.NotEqual(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.NotEqual(false, result.Data) /* * TEST databaseEdit */ result, w = session.JSONRequest("GET", "/host/database", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.NotEqual(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.NotEqual(false, result.Data) var database int for _, obj := range result.Data.([]interface{}) { item := obj.(map[string]interface{}) @@ -81,26 +81,26 @@ func TestAPIDatabase(t *testing.T) { result, w = session.JSONRequest("PATCH", "/host/database/"+strconv.Itoa(database), Database{ Comment: "test-bug", }) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("PATCH", "/host/database/"+strconv.Itoa(database), Database{ Comment: "test2", }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("PATCH", "/host/database/"+strconv.Itoa(-1), Database{ Comment: "test-bug", }) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("PATCH", "/host/database/"+strconv.Itoa(database), []byte{2, 3}) - assertion.Equal(w.StatusCode, http.StatusBadRequest) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusBadRequest, w.StatusCode) + assertion.Equal(false, result.Data) /* * TEST databaseDelete @@ -108,17 +108,17 @@ func TestAPIDatabase(t *testing.T) { session.Clean() result, w = session.JSONRequest("DELETE", "/host/database/"+strconv.Itoa(database), nil) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("DELETE", "/host/database/"+strconv.Itoa(database), nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("DELETE", "/host/database/"+strconv.Itoa(database), nil) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) } diff --git a/modul/host/apidomain.go b/modul/host/apidomain.go index 20eb1d0..a23b913 100644 --- a/modul/host/apidomain.go +++ b/modul/host/apidomain.go @@ -6,16 +6,16 @@ import ( "strings" "goji.io/pat" - "golang.org/x/net/context" libapi "dev.sum7.eu/sum7/warehost/lib/api" system "dev.sum7.eu/sum7/warehost/system" ) -func getDomain(ctx context.Context, w http.ResponseWriter) (domain Domain, returnerr *libapi.ErrorResult) { +func getDomain(w http.ResponseWriter, r *http.Request) (domain Domain, returnerr *libapi.ErrorResult) { + ctx := r.Context() login := ctx.Value("login").(*system.Login) profil := ctx.Value("profil").(*Profil) - id, err := strconv.ParseInt(pat.Param(ctx, "domainid"), 10, 64) + id, err := strconv.ParseInt(pat.Param(r, "domainid"), 10, 64) if err != nil { returnerr = &libapi.ErrorResult{ Message: "Internal Request Error", @@ -23,12 +23,12 @@ func getDomain(ctx context.Context, w http.ResponseWriter) (domain Domain, retur w.WriteHeader(http.StatusBadRequest) return } - domain = Domain{ID: id} + domain = Domain{} if login.Superadmin { - dbconnection.Find(&domain) + dbconnection.Where("ID = ?", id).Find(&domain) } else { - dbconnection.Where(map[string]int64{"profil": profil.ID}).Find(&domain) + dbconnection.Where(map[string]int64{"ID": id, "profil": profil.ID}).Find(&domain) } if domain.ID <= 0 { @@ -38,10 +38,10 @@ func getDomain(ctx context.Context, w http.ResponseWriter) (domain Domain, retur return } -func domainList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func domainList(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*system.Login) profil := ctx.Value("profil").(*Profil) - returndata = false logger := log.GetLog(r, "domainlist") var domain []*Domain if login.Superadmin && r.URL.Query().Get("filter") == "all" { @@ -50,32 +50,30 @@ func domainList(ctx context.Context, w http.ResponseWriter, r *http.Request) (re dbconnection.Where("profil = ?", profil.ID).Find(&domain) } logger.Info("done") - returndata = domain - return + libapi.JSONWrite(w, r, domain, nil) } -func domainShow(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func domainShow(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "domainshow") - domain, returnerr := getDomain(ctx, w) + domain, returnerr := getDomain(w, r) if returnerr != nil { logger.Info("not found") return } logger = logger.WithField("dID", domain.ID) logger.Info("done") - returndata = domain - return + libapi.JSONWrite(w, r, domain, nil) } -func domainAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func domainAdd(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() profil := ctx.Value("profil").(*Profil) - returndata = false logger := log.GetLog(r, "domainadd") var domainRequest Domain - returnerr = libapi.JSONDecoder(r.Body, &domainRequest, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &domainRequest) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } @@ -87,26 +85,26 @@ func domainAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (ret } if err := dbconnection.Create(domain).Error; err != nil { - if strings.Contains(err.Error(), "duplicate key") { + w.WriteHeader(http.StatusInternalServerError) + if strings.Contains(err.Error(), "licate key") { logger.Warning("exists already") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "already signup"}) return } logger.Error("database: during create host domain: ", err) - w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } -func domainEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func domainEdit(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*system.Login) - returndata = false logger := log.GetLog(r, "domainedit") - domain, returnerr := getDomain(ctx, w) + domain, returnerr := getDomain(w, r) if returnerr != nil { logger.Info("not found") return @@ -114,8 +112,9 @@ func domainEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (re logger = logger.WithField("dID", domain.ID) var domainRequest Domain - returnerr = libapi.JSONDecoder(r.Body, &domainRequest, w, logger) + returnerr = libapi.JSONDecoder(w, r, logger, &domainRequest) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } @@ -130,19 +129,17 @@ func domainEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (re if err := dbconnection.Save(domain).Error; err != nil { logger.Error("database: during modify host domain: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } -func domainDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func domainDelete(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "domaindelete") - domain, returnerr := getDomain(ctx, w) + domain, returnerr := getDomain(w, r) if returnerr != nil { logger.Info("not found") return @@ -152,10 +149,9 @@ func domainDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) ( if err := dbconnection.Unscoped().Delete(domain).Error; err != nil { logger.Error("database: during create host domain: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } diff --git a/modul/host/apidomain_test.go b/modul/host/apidomain_test.go index 8792755..abdc57f 100644 --- a/modul/host/apidomain_test.go +++ b/modul/host/apidomain_test.go @@ -27,30 +27,31 @@ func TestAPIDomain(t *testing.T) { loginTest(session, assertion) result, w := session.JSONRequest("DELETE", "/host/delete", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) // Need a Profile for Next tests result, w = session.JSONRequest("POST", "/host/signup", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) /* * TEST domainList */ session.Clean() result, w = session.JSONRequest("GET", "/host/domain", nil) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("GET", "/host/domain", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.NotEqual(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.NotEqual(false, result.Data) result, w = session.JSONRequest("GET", "/host/domain?filter=all", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.NotEqual(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.NotEqual(false, result.Data) /* * TEST domainAdd @@ -59,33 +60,33 @@ func TestAPIDomain(t *testing.T) { result, w = session.JSONRequest("POST", "/host/domain", Domain{ FQDN: "example.de", }) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("POST", "/host/domain", []byte{2, 3}) - assertion.Equal(w.StatusCode, http.StatusBadRequest) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusBadRequest, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("POST", "/host/domain", Domain{ FQDN: "example.de", }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.NotEqual(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.NotEqual(false, result.Data) result, w = session.JSONRequest("POST", "/host/domain", Domain{ FQDN: "example.de", }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(false, result.Data) /* * TEST domainEdit */ result, w = session.JSONRequest("GET", "/host/domain", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.NotEqual(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.NotEqual(false, result.Data) var domain int for _, obj := range result.Data.([]interface{}) { item := obj.(map[string]interface{}) @@ -99,26 +100,26 @@ func TestAPIDomain(t *testing.T) { result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain), Domain{ Mail: true, }) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain), Domain{ Mail: true, }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(-1), Domain{ Mail: true, }) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain), []byte{2, 3}) - assertion.Equal(w.StatusCode, http.StatusBadRequest) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusBadRequest, w.StatusCode) + assertion.Equal(false, result.Data) /* * TEST domainShow @@ -126,18 +127,18 @@ func TestAPIDomain(t *testing.T) { session.Clean() result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain), nil) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(-1), nil) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain), nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.NotEqual(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.NotEqual(false, result.Data) /* * TEST domainDelete @@ -145,22 +146,22 @@ func TestAPIDomain(t *testing.T) { session.Clean() result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain), nil) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(-1), nil) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain), nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain), nil) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) // CLEANUP diff --git a/modul/host/apimail.go b/modul/host/apimail.go index f61dde4..06ac43c 100644 --- a/modul/host/apimail.go +++ b/modul/host/apimail.go @@ -6,16 +6,16 @@ import ( "strings" "goji.io/pat" - "golang.org/x/net/context" libapi "dev.sum7.eu/sum7/warehost/lib/api" system "dev.sum7.eu/sum7/warehost/system" ) -func getMail(ctx context.Context, w http.ResponseWriter) (mail Mail, returnerr *libapi.ErrorResult) { +func getMail(w http.ResponseWriter, r *http.Request) (mail Mail, returnerr *libapi.ErrorResult) { + ctx := r.Context() login := ctx.Value("login").(*system.Login) profil := ctx.Value("profil").(*Profil) - id, err := strconv.ParseInt(pat.Param(ctx, "mailid"), 10, 64) + id, err := strconv.ParseInt(pat.Param(r, "mailid"), 10, 64) if err != nil { returnerr = &libapi.ErrorResult{ Message: "Internal Request Error", @@ -37,11 +37,10 @@ func getMail(ctx context.Context, w http.ResponseWriter) (mail Mail, returnerr * return } -func mailList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func mailList(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "maillist") var mail []*Mail - domain, returnerr := getDomain(ctx, w) + domain, returnerr := getDomain(w, r) if returnerr != nil { logger.Info("not found") return @@ -49,23 +48,24 @@ func mailList(ctx context.Context, w http.ResponseWriter, r *http.Request) (retu logger = logger.WithField("dID", domain.ID) dbconnection.Where("domain = ?", domain.ID).Preload("Domain").Preload("Forwards").Find(&mail) logger.Info("done") - returndata = mail + libapi.JSONWrite(w, r, mail, nil) return } -func mailAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func mailAdd(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "mailadd") var mailRequest Mail - returnerr = libapi.JSONDecoder(r.Body, &mailRequest, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &mailRequest) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } - domain, returnerr := getDomain(ctx, w) + domain, returnerr := getDomain(w, r) if returnerr != nil { logger.Info("not found") + libapi.JSONWrite(w, r, false, returnerr) return } logger = logger.WithField("dID", domain.ID) @@ -78,25 +78,24 @@ func mailAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (retur } if err := dbconnection.Create(mail).Error; err != nil { + w.WriteHeader(http.StatusInternalServerError) if strings.Contains(err.Error(), "duplicate key") { logger.Warning("exists already") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "already signup"}) return } logger.Error("database: during create host mail: ", err) - w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } -func mailEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func mailEdit(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "mailedit") - mail, returnerr := getMail(ctx, w) + mail, returnerr := getMail(w, r) if returnerr != nil { logger.Info("not found") return @@ -104,8 +103,9 @@ func mailEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (retu logger = logger.WithField("mID", mail.ID) var mailRequest Mail - returnerr = libapi.JSONDecoder(r.Body, &mailRequest, w, logger) + returnerr = libapi.JSONDecoder(w, r, logger, &mailRequest) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } @@ -133,27 +133,26 @@ func mailEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (retu if err := dbconnection.Unscoped().Delete(MailForward{}, "id in (?)", idsDel).Error; err != nil { logger.Error("database: during delete host mail forwards: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } if err := dbconnection.Save(mail).Error; err != nil { logger.Error("database: during modify host mail: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } -func mailDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func mailDelete(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "maildelete") - mail, returnerr := getMail(ctx, w) + mail, returnerr := getMail(w, r) if returnerr != nil { logger.Info("not found") + libapi.JSONWrite(w, r, false, returnerr) return } logger = logger.WithField("mID", mail.ID) @@ -161,10 +160,9 @@ func mailDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (re if err := dbconnection.Unscoped().Delete(mail).Error; err != nil { logger.Error("database: during create host mail: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } diff --git a/modul/host/apimail_test.go b/modul/host/apimail_test.go index e6431e1..aeeb89a 100644 --- a/modul/host/apimail_test.go +++ b/modul/host/apimail_test.go @@ -27,23 +27,23 @@ func TestAPIMail(t *testing.T) { loginTest(session, assertion) result, w := session.JSONRequest("DELETE", "/host/delete", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) // Need a Profile for Next tests result, w = session.JSONRequest("POST", "/host/signup", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) // Need a Domain for next tests result, w = session.JSONRequest("POST", "/host/domain", Domain{ FQDN: "example.de", }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) // Get id von domain result, w = session.JSONRequest("GET", "/host/domain", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) assertion.NotEqual(result.Data, false) var domain int for _, obj := range result.Data.([]interface{}) { @@ -60,16 +60,16 @@ func TestAPIMail(t *testing.T) { result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain)+"/mail", nil) assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(-1)+"/mail", nil) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain)+"/mail", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) assertion.NotEqual(result.Data, false) /* @@ -81,37 +81,37 @@ func TestAPIMail(t *testing.T) { Name: "test-bug", }) assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/mail", []byte{2, 3}) assertion.Equal(w.StatusCode, http.StatusBadRequest) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(-1)+"/mail", Mail{ Name: "test-bug", }) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/mail", Mail{ Name: "test", }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/mail", Mail{ Name: "test", }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(false, result.Data) /* * TEST mailEdit */ result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain)+"/mail", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) assertion.NotEqual(result.Data, false) var mail int for _, obj := range result.Data.([]interface{}) { @@ -127,25 +127,25 @@ func TestAPIMail(t *testing.T) { Name: "test-bug-auth", }) assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), []byte{2, 3}) assertion.Equal(w.StatusCode, http.StatusBadRequest) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(-1), Mail{ Name: "test-bug", }) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), Mail{ Name: "test", }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) /* * TEST domainDelete @@ -154,20 +154,20 @@ func TestAPIMail(t *testing.T) { result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), nil) assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(-1), nil) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), nil) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) } diff --git a/modul/host/apiprofil.go b/modul/host/apiprofil.go index b067e62..87dc471 100644 --- a/modul/host/apiprofil.go +++ b/modul/host/apiprofil.go @@ -5,42 +5,40 @@ import ( "strconv" "goji.io/pat" - "golang.org/x/net/context" libapi "dev.sum7.eu/sum7/warehost/lib/api" system "dev.sum7.eu/sum7/warehost/system" ) -func profilList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func profilList(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*system.Login) - returndata = false logger := log.GetLog(r, "toggleReseller") if !login.Superadmin { - returnerr = &libapi.ErrorResult{Fields: []string{"session"}, Message: "not a superadmin"} - w.WriteHeader(http.StatusUnauthorized) logger.Warn("not a superadmin") + w.WriteHeader(http.StatusUnauthorized) + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"session"}, Message: "not a superadmin"}) return } var profils []*Profil dbconnection.Preload("Login").Find(&profils) - returndata = profils - return + libapi.JSONWrite(w, r, profils, nil) } -func toggleReseller(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func toggleReseller(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*system.Login) - returndata = false logger := log.GetLog(r, "toggleReseller") if !login.Superadmin { - returnerr = &libapi.ErrorResult{Fields: []string{"session"}, Message: "not a superadmin"} - w.WriteHeader(http.StatusUnauthorized) logger.Warn("not a superadmin") + w.WriteHeader(http.StatusUnauthorized) + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"session"}, Message: "not a superadmin"}) return } - id, err := strconv.ParseInt(pat.Param(ctx, "id"), 10, 64) + id, err := strconv.ParseInt(pat.Param(r, "id"), 10, 64) if err != nil { - returnerr = &libapi.ErrorResult{Message: "Error invalid input"} logger.Warn("invalid userinput, no integer") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error invalid input"}) return } logger = logger.WithField("id", id) @@ -50,9 +48,8 @@ func toggleReseller(ctx context.Context, w http.ResponseWriter, r *http.Request) if err := dbconnection.Save(profil).Error; err != nil { logger.Error("database: during modify host profil: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true - return + libapi.JSONWrite(w, r, true, nil) } diff --git a/modul/host/apiprofil_test.go b/modul/host/apiprofil_test.go index 7392803..caeb9aa 100644 --- a/modul/host/apiprofil_test.go +++ b/modul/host/apiprofil_test.go @@ -27,12 +27,12 @@ func TestAPIProfil(t *testing.T) { loginTest(session, assertion) result, w := session.JSONRequest("DELETE", "/host/delete", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) // Need a Profile for Next tests result, w = session.JSONRequest("POST", "/host/signup", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) /* * TEST profilList @@ -40,19 +40,19 @@ func TestAPIProfil(t *testing.T) { session.Clean() result, w = session.JSONRequest("GET", "/host/profils", nil) assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("GET", "/host/profils", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) assertion.NotEqual(result.Data, false) /* * TEST toggleReseller */ result, w = session.JSONRequest("GET", "/host/profils", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) assertion.NotEqual(result.Data, false) var id int for _, obj := range result.Data.([]interface{}) { @@ -64,15 +64,15 @@ func TestAPIProfil(t *testing.T) { result, w = session.JSONRequest("PATCH", "/host/profil/"+strconv.Itoa(id), nil) assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("PATCH", "/host/profil/"+strconv.Itoa(id), nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("PATCH", "/host/profil/"+strconv.Itoa(id), nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) } diff --git a/modul/host/apiweb.go b/modul/host/apiweb.go index 34d5d8f..34ca4f6 100644 --- a/modul/host/apiweb.go +++ b/modul/host/apiweb.go @@ -6,7 +6,6 @@ import ( "strings" "goji.io/pat" - "golang.org/x/net/context" libapi "dev.sum7.eu/sum7/warehost/lib/api" system "dev.sum7.eu/sum7/warehost/system" @@ -25,10 +24,11 @@ func cleanLoginHTTPAccess(access []*HTTPAccess) { } } -func getWeb(ctx context.Context, w http.ResponseWriter) (web Web, returnerr *libapi.ErrorResult) { +func getWeb(w http.ResponseWriter, r *http.Request) (web Web, returnerr *libapi.ErrorResult) { + ctx := r.Context() login := ctx.Value("login").(*system.Login) profil := ctx.Value("profil").(*Profil) - id, err := strconv.ParseInt(pat.Param(ctx, "webid"), 10, 64) + id, err := strconv.ParseInt(pat.Param(r, "webid"), 10, 64) if err != nil { returnerr = &libapi.ErrorResult{ Message: "Internal Request Error", @@ -49,11 +49,10 @@ func getWeb(ctx context.Context, w http.ResponseWriter) (web Web, returnerr *lib return } -func webList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func webList(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "weblist") var web []*Web - domain, returnerr := getDomain(ctx, w) + domain, returnerr := getDomain(w, r) if returnerr != nil { logger.Info("not found") return @@ -62,23 +61,23 @@ func webList(ctx context.Context, w http.ResponseWriter, r *http.Request) (retur dbconnection.Where("domain = ?", domain.ID).Preload("Domain").Preload("HTTPAccess.Login").Preload("FTPAccess.Login").Find(&web) logger.Info("done") - returndata = web - return + libapi.JSONWrite(w, r, web, nil) } -func webAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func webAdd(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "webadd") var webRequest Web - returnerr = libapi.JSONDecoder(r.Body, &webRequest, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &webRequest) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } - domain, returnerr := getDomain(ctx, w) + domain, returnerr := getDomain(w, r) if returnerr != nil { logger.Info("not found") + libapi.JSONWrite(w, r, false, returnerr) return } logger = logger.WithField("dID", domain.ID) @@ -99,34 +98,35 @@ func webAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (return } if err := dbconnection.Create(web).Error; err != nil { + w.WriteHeader(http.StatusInternalServerError) if strings.Contains(err.Error(), "duplicate key") { logger.Warning("exists already") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "already signup"}) return } logger.Error("database: during create host web: ", err) - w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } -func webEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func webEdit(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "webedit") - web, returnerr := getWeb(ctx, w) + web, returnerr := getWeb(w, r) if returnerr != nil { logger.Info("not found") + libapi.JSONWrite(w, r, false, returnerr) return } logger = logger.WithField("wID", web.ID) var webRequest Web - returnerr = libapi.JSONDecoder(r.Body, &webRequest, w, logger) + returnerr = libapi.JSONDecoder(w, r, logger, &webRequest) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } @@ -161,7 +161,7 @@ func webEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (retur if err := dbconnection.Unscoped().Where("web = ?", web.ID).Delete(HTTPAccess{}, "login in (?)", idsDel).Error; err != nil { logger.Error("database: during delete host web httpaccess: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } @@ -189,7 +189,7 @@ func webEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (retur if err := dbconnection.Unscoped().Where("web = ?", web.ID).Delete(FTPAccess{}, "login in (?)", idsDel).Error; err != nil { logger.Error("database: during delete host web ftpaccess: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } cleanLoginFTPAccess(web.FTPAccess) @@ -198,19 +198,17 @@ func webEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (retur if err := dbconnection.Save(web).Error; err != nil { logger.Error("database: during modify host web: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } -func webDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func webDelete(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "webdelete") - web, returnerr := getWeb(ctx, w) + web, returnerr := getWeb(w, r) if returnerr != nil { logger.Info("not found") return @@ -220,10 +218,9 @@ func webDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (ret if err := dbconnection.Unscoped().Delete(web).Error; err != nil { logger.Error("database: during create host web: ", err) w.WriteHeader(http.StatusInternalServerError) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } diff --git a/modul/host/apiweb_test.go b/modul/host/apiweb_test.go index 68d1062..a4ea780 100644 --- a/modul/host/apiweb_test.go +++ b/modul/host/apiweb_test.go @@ -27,23 +27,23 @@ func TestAPIWeb(t *testing.T) { loginTest(session, assertion) result, w := session.JSONRequest("DELETE", "/host/delete", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) // Need a Profile for Next tests result, w = session.JSONRequest("POST", "/host/signup", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) // Need a Domain for next tests result, w = session.JSONRequest("POST", "/host/domain", Domain{ FQDN: "example.de", }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) // Get id von domain result, w = session.JSONRequest("GET", "/host/domain", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) assertion.NotEqual(result.Data, false) var domain int for _, obj := range result.Data.([]interface{}) { @@ -60,16 +60,16 @@ func TestAPIWeb(t *testing.T) { result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain)+"/web", nil) assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(-1)+"/web", nil) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain)+"/web", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) assertion.NotEqual(result.Data, false) /* @@ -81,37 +81,37 @@ func TestAPIWeb(t *testing.T) { Subdomain: "", }) assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/web", []byte{2, 3}) assertion.Equal(w.StatusCode, http.StatusBadRequest) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(-1)+"/web", Web{ Subdomain: "", }) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/web", Web{ Subdomain: "", }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/web", Web{ Subdomain: "", }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(false, result.Data) /* * TEST webEdit */ result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain)+"/web", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) assertion.NotEqual(result.Data, false) var web int for _, obj := range result.Data.([]interface{}) { @@ -127,25 +127,25 @@ func TestAPIWeb(t *testing.T) { Subdomain: "test-bug-auth", }) assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), []byte{2, 3}) assertion.Equal(w.StatusCode, http.StatusBadRequest) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(-1), Web{ Subdomain: "test-bug", }) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), Web{ Subdomain: "test", }) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) /* * TEST domainDelete @@ -154,20 +154,20 @@ func TestAPIWeb(t *testing.T) { result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), nil) assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(false, result.Data) loginTest(session, assertion) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(-1), nil) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), nil) - assertion.Equal(w.StatusCode, http.StatusNotFound) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusNotFound, w.StatusCode) + assertion.Equal(false, result.Data) } diff --git a/modul/host/lib.go b/modul/host/lib.go index e907bc6..b2fb92f 100644 --- a/modul/host/lib.go +++ b/modul/host/lib.go @@ -3,7 +3,7 @@ package host import ( "net/http" - "golang.org/x/net/context" + "context" libapi "dev.sum7.eu/sum7/warehost/lib/api" liblog "dev.sum7.eu/sum7/warehost/lib/log" @@ -12,19 +12,19 @@ import ( //ProfilHandler for api function to get host.Profil func ProfilHandler(h libapi.Handle) libapi.Handle { - return func(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { + return func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*libsystem.Login) - returnerr = &libapi.ErrorResult{Fields: []string{"session"}, Message: "no profil found"} - returndata = false profil := &Profil{LoginID: login.ID} dbconnection.Where("login = ?", login.ID).Find(profil) if profil.ID > 0 { ctx = context.WithValue(ctx, "profil", profil) - returndata, returnerr = h(ctx, w, r) + r = r.WithContext(ctx) + h(w, r) return } liblog.Log.Warn("no profil found") - return + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"session"}, Message: "no profil found"}) } } diff --git a/modul/web/api.go b/modul/web/api.go index edd5164..eaf8538 100644 --- a/modul/web/api.go +++ b/modul/web/api.go @@ -6,7 +6,6 @@ import ( "github.com/jinzhu/gorm" "goji.io" "goji.io/pat" - "golang.org/x/net/context" //libconfig "dev.sum7.eu/sum7/warehost/config" libapi "dev.sum7.eu/sum7/warehost/lib/api" @@ -25,106 +24,104 @@ func BindAPI(db *gorm.DB, router *goji.Mux, prefix string) { dbconnection = db log = liblog.NewModulLog(MODULNAME) - router.HandleFuncC(pat.Get(prefix+"/involve"), libapi.SessionHandler(libsystem.LoginHandler(involve))) - router.HandleFuncC(pat.Post(prefix+"/website"), libapi.SessionHandler(libsystem.LoginHandler(websiteAdd))) - router.HandleFuncC(pat.Patch(prefix+"/website/:websiteid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(websiteEdit)))) - router.HandleFuncC(pat.Delete(prefix+"/website/:websiteid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(websiteDelete)))) - router.HandleFuncC(pat.Get(prefix+"/website/:websiteid/permission"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(permissionList)))) - router.HandleFuncC(pat.Post(prefix+"/website/:websiteid/permission/:loginid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(permissionAdd)))) - router.HandleFuncC(pat.Delete(prefix+"/website/:websiteid/permission/:loginid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(permissionDelete)))) - router.HandleFuncC(pat.Get(prefix+"/website/:websiteid/domain"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(domainList)))) - router.HandleFuncC(pat.Post(prefix+"/website/:websiteid/domain/:domain"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(domainAdd)))) - router.HandleFuncC(pat.Delete(prefix+"/website/:websiteid/domain/:domain"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(domainDelete)))) - router.HandleFuncC(pat.Get(prefix+"/website/:websiteid/menu"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(menuTree)))) - router.HandleFuncC(pat.Get(prefix+"/website/:websiteid/menu/list"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(menuList)))) - router.HandleFuncC(pat.Post(prefix+"/website/:websiteid/menu"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(menuAdd)))) - router.HandleFuncC(pat.Patch(prefix+"/website/:websiteid/menu/:menuid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(menuEdit)))) - router.HandleFuncC(pat.Delete(prefix+"/website/:websiteid/menu/:menuid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(menuDelete)))) - router.HandleFuncC(pat.Get(prefix+"/website/:websiteid/page"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(pageList)))) - router.HandleFuncC(pat.Post(prefix+"/website/:websiteid/page"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(pageAdd)))) - router.HandleFuncC(pat.Patch(prefix+"/website/:websiteid/page/:pageid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(pageEdit)))) - router.HandleFuncC(pat.Delete(prefix+"/website/:websiteid/page/:pageid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(pageDelete)))) + router.HandleFunc(pat.Get(prefix+"/involve"), libapi.SessionHandler(libsystem.LoginHandler(involve))) + router.HandleFunc(pat.Post(prefix+"/website"), libapi.SessionHandler(libsystem.LoginHandler(websiteAdd))) + router.HandleFunc(pat.Patch(prefix+"/website/:websiteid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(websiteEdit)))) + router.HandleFunc(pat.Delete(prefix+"/website/:websiteid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(websiteDelete)))) + router.HandleFunc(pat.Get(prefix+"/website/:websiteid/permission"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(permissionList)))) + router.HandleFunc(pat.Post(prefix+"/website/:websiteid/permission/:loginid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(permissionAdd)))) + router.HandleFunc(pat.Delete(prefix+"/website/:websiteid/permission/:loginid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(permissionDelete)))) + router.HandleFunc(pat.Get(prefix+"/website/:websiteid/domain"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(domainList)))) + router.HandleFunc(pat.Post(prefix+"/website/:websiteid/domain/:domain"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(domainAdd)))) + router.HandleFunc(pat.Delete(prefix+"/website/:websiteid/domain/:domain"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(domainDelete)))) + router.HandleFunc(pat.Get(prefix+"/website/:websiteid/menu"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(menuTree)))) + router.HandleFunc(pat.Get(prefix+"/website/:websiteid/menu/list"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(menuList)))) + router.HandleFunc(pat.Post(prefix+"/website/:websiteid/menu"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(menuAdd)))) + router.HandleFunc(pat.Patch(prefix+"/website/:websiteid/menu/:menuid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(menuEdit)))) + router.HandleFunc(pat.Delete(prefix+"/website/:websiteid/menu/:menuid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(menuDelete)))) + router.HandleFunc(pat.Get(prefix+"/website/:websiteid/page"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(pageList)))) + router.HandleFunc(pat.Post(prefix+"/website/:websiteid/page"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(pageAdd)))) + router.HandleFunc(pat.Patch(prefix+"/website/:websiteid/page/:pageid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(pageEdit)))) + router.HandleFunc(pat.Delete(prefix+"/website/:websiteid/page/:pageid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(pageDelete)))) } // Involve to get Website where loggend in user has privilegs -func involve(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func involve(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*libsystem.Login) - returndata = false logger := log.GetLog(r, "involve") var involved []*Manager dbconnection.Where("login = ?", login.ID).Preload("Website").Find(&involved) logger.Info("done") - returndata = involved - return + libapi.JSONWrite(w, r, involved, nil) } // WebsiteAdd to add a new website -func websiteAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func websiteAdd(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*libsystem.Login) - returndata = false logger := log.GetLog(r, "websiteadd") tx := dbconnection.Begin() var websiteRequest Website - returnerr = libapi.JSONDecoder(r.Body, &websiteRequest, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &websiteRequest) if returnerr != nil { tx.Rollback() + libapi.JSONWrite(w, r, false, returnerr) return } website := &Website{Name: websiteRequest.Name} if err := tx.Create(website).Error; err != nil { tx.Rollback() logger.Error("error during Website") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } if err := tx.Create(&Manager{LoginID: login.ID, WebsiteID: website.ID}).Error; err != nil { tx.Rollback() logger.Error("error during Manager") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } tx.Commit() - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } // WebsiteEdit to edit website -func websiteEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func websiteEdit(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "websiteedit") var websiteRequest Website - returnerr = libapi.JSONDecoder(r.Body, &websiteRequest, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &websiteRequest) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } websiteRequest.ID = ctx.Value("websiteid").(int64) if err := dbconnection.Save(websiteRequest).Error; err != nil { logger.Error("Database: during edit Website") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } // WebsiteDelete to delete website -func websiteDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func websiteDelete(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "websitedelete") website := &Website{ ID: ctx.Value("websiteid").(int64), } if err := dbconnection.Unscoped().Delete(website).Error; err != nil { logger.Error("database: during delete website") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } diff --git a/modul/web/apidomain.go b/modul/web/apidomain.go index bd1ba83..5be1c8b 100644 --- a/modul/web/apidomain.go +++ b/modul/web/apidomain.go @@ -4,54 +4,50 @@ import ( "net/http" "goji.io/pat" - "golang.org/x/net/context" libapi "dev.sum7.eu/sum7/warehost/lib/api" ) // DomainList to list domains -func domainList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func domainList(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "domainlist") var domain []*Domain dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Preload("Domains").Find(&domain) logger.Info("done") - returndata = domain - return + libapi.JSONWrite(w, r, domain, nil) } // DomainAdd to add domain -func domainAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func domainAdd(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "domainadd") domain := &Domain{ WebsiteID: ctx.Value("websiteid").(int64), - Name: pat.Param(ctx, "domain"), + Name: pat.Param(r, "domain"), } if err := dbconnection.Create(domain).Error; err != nil { logger.Error("database: during create website domain: ", err) - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } // DomainDelete to delete domain -func domainDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func domainDelete(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "domaindelete") domain := &Domain{ WebsiteID: ctx.Value("websiteid").(int64), - Name: pat.Param(ctx, "domain"), + Name: pat.Param(r, "domain"), } if err := dbconnection.Unscoped().Delete(domain).Error; err != nil { logger.Error("database: during delete website Domain") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } diff --git a/modul/web/apimenu.go b/modul/web/apimenu.go index 6afeb64..e611eaa 100644 --- a/modul/web/apimenu.go +++ b/modul/web/apimenu.go @@ -5,40 +5,38 @@ import ( "strconv" "goji.io/pat" - "golang.org/x/net/context" libapi "dev.sum7.eu/sum7/warehost/lib/api" ) // MenuTree to give the tree of a menu back -func menuTree(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func menuTree(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "menutree") var menus []*Menu dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Order("position").Find(&menus) - returndata = BuildMenuTree(menus) logger.Info("done") - return + libapi.JSONWrite(w, r, BuildMenuTree(menus), nil) } // MenuList give all menu entries of a website -func menuList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func menuList(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "menulist") var menus []*Menu dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Order("position").Find(&menus) - returndata = menus logger.Info("done") - return + libapi.JSONWrite(w, r, menus, nil) } // MenuAdd to add a new menu entry -func menuAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func menuAdd(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "menuadd") var menuEntry Menu - returnerr = libapi.JSONDecoder(r.Body, &menuEntry, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &menuEntry) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } @@ -46,28 +44,28 @@ func menuAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (retur if err := dbconnection.Create(&menuEntry).Error; err != nil { logger.Error("database: during create menu") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } // MenuEdit to edit menu -func menuEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func menuEdit(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "menuedit") var menuEntry Menu - menuid, err := strconv.ParseInt(pat.Param(ctx, "menuid"), 10, 64) + menuid, err := strconv.ParseInt(pat.Param(r, "menuid"), 10, 64) if err != nil { - returnerr = &libapi.ErrorResult{Fields: []string{"menuid"}, Message: "Not a valid menuid"} logger.Warn("invalid loginid, no integer") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"menuid"}, Message: "Not a valid menuid"}) return } logger = logger.WithField("id", menuid) - returnerr = libapi.JSONDecoder(r.Body, &menuEntry, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &menuEntry) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } menuEntry.WebsiteID = ctx.Value("websiteid").(int64) @@ -75,22 +73,21 @@ func menuEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (retu if err := dbconnection.Save(menuEntry).Error; err != nil { logger.Error("database: during edit website menu entry") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } // MenuDelete to delete menu entry -func menuDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func menuDelete(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "menudelete") - menuid, err := strconv.ParseInt(pat.Param(ctx, "menuid"), 10, 64) + menuid, err := strconv.ParseInt(pat.Param(r, "menuid"), 10, 64) if err != nil { - returnerr = &libapi.ErrorResult{Fields: []string{"menuid"}, Message: "Not a valid menuid"} logger.Warn("invalid menuid, no integer") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"menuid"}, Message: "Not a valid menuid"}) return } logger = logger.WithField("id", menuid) @@ -100,10 +97,9 @@ func menuDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (re } if err := dbconnection.Unscoped().Delete(menu).Error; err != nil { logger.Error("database: during delete website menu entry") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } diff --git a/modul/web/apipage.go b/modul/web/apipage.go index 98ee090..071a095 100644 --- a/modul/web/apipage.go +++ b/modul/web/apipage.go @@ -5,29 +5,28 @@ import ( "strconv" "goji.io/pat" - "golang.org/x/net/context" libapi "dev.sum7.eu/sum7/warehost/lib/api" ) // PageList give all pages of a website -func pageList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func pageList(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "pagelist") var pages []*Page dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Preload("Menu").Find(&pages) - returndata = pages logger.Info("done") - return + libapi.JSONWrite(w, r, pages, nil) } // PageAdd to add a new page -func pageAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func pageAdd(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "pageadd") var page Page - returnerr = libapi.JSONDecoder(r.Body, &page, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &page) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } @@ -39,28 +38,28 @@ func pageAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (retur if err := dbconnection.Create(&page).Error; err != nil { logger.Error("database: during create page") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } // PageEdit to edit page -func pageEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func pageEdit(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "pageedit") var page Page - pageid, err := strconv.ParseInt(pat.Param(ctx, "pageid"), 10, 64) + pageid, err := strconv.ParseInt(pat.Param(r, "pageid"), 10, 64) if err != nil { - returnerr = &libapi.ErrorResult{Fields: []string{"pageid"}, Message: "Not a valid pageid"} logger.Warn("invalid pageid, no integer") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"pageid"}, Message: "Not a valid pageid"}) return } logger = logger.WithField("id", pageid) - returnerr = libapi.JSONDecoder(r.Body, &page, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &page) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } page.WebsiteID = ctx.Value("websiteid").(int64) @@ -72,22 +71,21 @@ func pageEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (retu if err := dbconnection.Save(page).Error; err != nil { logger.Error("database: during delete website page") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } // PageDelete to delete page -func pageDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func pageDelete(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "pagedelete") - pageid, err := strconv.ParseInt(pat.Param(ctx, "pageid"), 10, 64) + pageid, err := strconv.ParseInt(pat.Param(r, "pageid"), 10, 64) if err != nil { - returnerr = &libapi.ErrorResult{Fields: []string{"pageid"}, Message: "Not a valid pageid"} logger.Warn("invalid pageid, no integer") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"pageid"}, Message: "Not a valid pageid"}) return } logger = logger.WithField("id", pageid) @@ -97,10 +95,9 @@ func pageDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (re } if err := dbconnection.Unscoped().Delete(page).Error; err != nil { logger.Error("database: during delete website page") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } diff --git a/modul/web/apipermission.go b/modul/web/apipermission.go index f5b2f11..ef081ac 100644 --- a/modul/web/apipermission.go +++ b/modul/web/apipermission.go @@ -5,30 +5,28 @@ import ( "strconv" "goji.io/pat" - "golang.org/x/net/context" libapi "dev.sum7.eu/sum7/warehost/lib/api" ) // PermissionList to add permissions -func permissionList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func permissionList(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "permissionlist") var involved []*Manager dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Preload("Login").Find(&involved) logger.Info("done") - returndata = involved - return + libapi.JSONWrite(w, r, involved, nil) } // PermissionAdd to add permissions -func permissionAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func permissionAdd(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "permissionadd") - loginid, err := strconv.ParseInt(pat.Param(ctx, "loginid"), 10, 64) + loginid, err := strconv.ParseInt(pat.Param(r, "loginid"), 10, 64) if err != nil { - returnerr = &libapi.ErrorResult{Fields: []string{"loginid"}, Message: "Not a valid loginid"} logger.Warn("invalid loginid, no integer") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"loginid"}, Message: "Not a valid loginid"}) return } manager := &Manager{ @@ -37,22 +35,21 @@ func permissionAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) } if err := dbconnection.Create(manager).Error; err != nil { logger.Error("database: during create website permission") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } // PermissionDelete to delete permissions -func permissionDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func permissionDelete(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() logger := log.GetLog(r, "permissiondelete") - loginid, err := strconv.ParseInt(pat.Param(ctx, "loginid"), 10, 64) + loginid, err := strconv.ParseInt(pat.Param(r, "loginid"), 10, 64) if err != nil { - returnerr = &libapi.ErrorResult{Fields: []string{"loginid"}, Message: "Not a valid loginid"} logger.Warn("invalid loginid, no integer") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"loginid"}, Message: "Not a valid loginid"}) return } manager := &Manager{ @@ -61,10 +58,9 @@ func permissionDelete(ctx context.Context, w http.ResponseWriter, r *http.Reques } if err := dbconnection.Unscoped().Delete(manager).Error; err != nil { logger.Error("database: during delete website permission") - returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"}) return } - returndata = true logger.Info("done") - return + libapi.JSONWrite(w, r, true, nil) } diff --git a/modul/web/lib.go b/modul/web/lib.go index b928c76..53fbcdc 100644 --- a/modul/web/lib.go +++ b/modul/web/lib.go @@ -4,8 +4,8 @@ import ( "net/http" "strconv" + "context" "goji.io/pat" - "golang.org/x/net/context" libapi "dev.sum7.eu/sum7/warehost/lib/api" liblog "dev.sum7.eu/sum7/warehost/lib/log" @@ -14,24 +14,24 @@ import ( //InvolveWebsiteHandler for api function to Verifie User ist loggedin func InvolveWebsiteHandler(h libapi.Handle) libapi.Handle { - return func(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { + return func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*libsystem.Login) - returnerr = &libapi.ErrorResult{Fields: []string{"session"}, Message: "Not logged in"} - returndata = false - id, err := strconv.ParseInt(pat.Param(ctx, "websiteid"), 10, 64) + id, err := strconv.ParseInt(pat.Param(r, "websiteid"), 10, 64) if err == nil { res := dbconnection.Where(map[string]int64{"website": id, "login": login.ID}).Find(&Manager{}) if !res.RecordNotFound() { ctx = context.WithValue(ctx, "websiteid", id) - returndata, returnerr = h(ctx, w, r) + r = r.WithContext(ctx) + h(w, r) return } - returnerr = &libapi.ErrorResult{Fields: []string{"permission"}, Message: "No permission"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"permission"}, Message: "No permission"}) liblog.Log.Info("no Permissions") return } - returnerr = &libapi.ErrorResult{Fields: []string{"websiteid"}, Message: "Not a valid websiteid"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"websiteid"}, Message: "Not a valid websiteid"}) liblog.Log.Warn("invalid websiteid, no integer") return } diff --git a/system/api.go b/system/api.go index 4daea6f..cfd2187 100644 --- a/system/api.go +++ b/system/api.go @@ -9,7 +9,6 @@ import ( "github.com/jinzhu/gorm" "goji.io" "goji.io/pat" - "golang.org/x/net/context" libapi "dev.sum7.eu/sum7/warehost/lib/api" liblog "dev.sum7.eu/sum7/warehost/lib/log" @@ -28,36 +27,37 @@ func BindAPI(db *gorm.DB, router *goji.Mux, prefix string) { dbconnection = db log = liblog.NewModulLog(MODULNAME) - router.HandleFuncC(pat.Get(prefix+"/status"), libapi.SessionHandler(status)) - router.HandleFuncC(pat.Post(prefix+"/login"), libapi.SessionHandler(login)) - router.HandleFuncC(pat.Get(prefix+"/logout"), libapi.SessionHandler(LoginHandler(logout))) - router.HandleFuncC(pat.Post(prefix+"/password"), libapi.SessionHandler(LoginHandler(password))) - router.HandleFuncC(pat.Get(prefix+"/delete"), libapi.SessionHandler(LoginHandler(delete))) - router.HandleFuncC(pat.Get(prefix+"/invite"), libapi.SessionHandler(LoginHandler(inviteList))) - router.HandleFuncC(pat.Post(prefix+"/invite"), libapi.SessionHandler(LoginHandler(inviteAdd))) - router.HandleFuncC(pat.Get(prefix+"/user"), libapi.SessionHandler(LoginHandler(loginList))) - router.HandleFuncC(pat.Post(prefix+"/user"), libapi.SessionHandler(LoginHandler(loginAdd))) - router.HandleFuncC(pat.Patch(prefix+"/user/:id"), libapi.SessionHandler(LoginHandler(loginEdit))) - router.HandleFuncC(pat.Delete(prefix+"/user/:id"), libapi.SessionHandler(LoginHandler(loginDelete))) - router.HandleFuncC(pat.Get(prefix+"/invitor"), libapi.SessionHandler(LoginHandler(invitor))) - router.HandleFuncC(pat.Patch(prefix+"/invitor"), libapi.SessionHandler(LoginHandler(invitorAdminToggle))) + router.HandleFunc(pat.Get(prefix+"/status"), libapi.SessionHandler(status)) + router.HandleFunc(pat.Post(prefix+"/login"), libapi.SessionHandler(login)) + router.HandleFunc(pat.Get(prefix+"/logout"), libapi.SessionHandler(LoginHandler(logout))) + router.HandleFunc(pat.Post(prefix+"/password"), libapi.SessionHandler(LoginHandler(password))) + router.HandleFunc(pat.Get(prefix+"/delete"), libapi.SessionHandler(LoginHandler(delete))) + router.HandleFunc(pat.Get(prefix+"/invite"), libapi.SessionHandler(LoginHandler(inviteList))) + router.HandleFunc(pat.Post(prefix+"/invite"), libapi.SessionHandler(LoginHandler(inviteAdd))) + router.HandleFunc(pat.Get(prefix+"/user"), libapi.SessionHandler(LoginHandler(loginList))) + router.HandleFunc(pat.Post(prefix+"/user"), libapi.SessionHandler(LoginHandler(loginAdd))) + router.HandleFunc(pat.Patch(prefix+"/user/:id"), libapi.SessionHandler(LoginHandler(loginEdit))) + router.HandleFunc(pat.Delete(prefix+"/user/:id"), libapi.SessionHandler(LoginHandler(loginDelete))) + router.HandleFunc(pat.Get(prefix+"/invitor"), libapi.SessionHandler(LoginHandler(invitor))) + router.HandleFunc(pat.Patch(prefix+"/invitor"), libapi.SessionHandler(LoginHandler(invitorAdminToggle))) } // Status to get Login and Server status -func status(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { - returndata = false +func status(w http.ResponseWriter, r *http.Request) { logger := log.GetLog(r, "status") var result int64 dbconnection.Model(&Login{}).Count(&result) if result > 0 { - returndata = true + libapi.JSONWrite(w, r, true, nil) + return } logger.Info("done") - return + libapi.JSONWrite(w, r, false, nil) } // Logout current user -func logout(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func logout(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() sess := ctx.Value("session").(libsession.Session) libsession.SessionDestroy(w, r) logger := log.GetLog(r, "logout") @@ -67,19 +67,18 @@ func logout(ctx context.Context, w http.ResponseWriter, r *http.Request) (return sess.Delete("login") sess.Delete("profil") logger.Info("done") - returndata = true - - return + libapi.JSONWrite(w, r, true, nil) } // Login of system -func login(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func login(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() sess := ctx.Value("session").(libsession.Session) - returndata = false logger := log.GetLog(r, "login") var requestlogin RequestLogin - returnerr = libapi.JSONDecoder(r.Body, &requestlogin, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &requestlogin) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } @@ -88,104 +87,103 @@ func login(ctx context.Context, w http.ResponseWriter, r *http.Request) (returnd dbconnection.Where("mail = ?", requestlogin.Username).First(&login) if login.ID <= 0 { logger.Warn("user not found") - returnerr = &libapi.ErrorResult{Fields: []string{"username"}, Message: "User not Found"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"username"}, Message: "User not Found"}) return } if login.Active { output, _ := libpassword.Validate(login.Password, requestlogin.Password) if output { - returndata = true dbconnection.Model(&login).Update("LastLoginAt", time.Now()) sess.Set("login", &login) logger.Info("done") - } else { - logger.Warn("wrong password") - returnerr = &libapi.ErrorResult{Fields: []string{"password"}, Message: "Wrong Password"} + libapi.JSONWrite(w, r, true, nil) + return } - } else { - logger.Warn("not active") - returnerr = &libapi.ErrorResult{Fields: []string{"active"}, Message: "Not a active User"} + logger.Warn("wrong password") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"password"}, Message: "Wrong Password"}) + return } + logger.Warn("not active") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"active"}, Message: "Not a active User"}) return } //Password to change the password -func password(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func password(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() sess := ctx.Value("session").(libsession.Session) login := ctx.Value("login").(*Login) - returndata = false logger := log.GetLog(r, "password") var changePasswordRequest ChangePasswordRequest - returnerr = libapi.JSONDecoder(r.Body, &changePasswordRequest, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &changePasswordRequest) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } output, _ := libpassword.Validate(login.Password, changePasswordRequest.CurrentPassword) if !output { logger.Warn("wrong current password") - returnerr = &libapi.ErrorResult{Fields: []string{"currentpassword"}, Message: "Wrong CurrentPassword"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"currentpassword"}, Message: "Wrong CurrentPassword"}) return } if len(changePasswordRequest.NewPassword) < MINPASSWORDLENTH { logger.Warn("wrong new password") - returnerr = &libapi.ErrorResult{Fields: []string{"newpassword"}, Message: "Wrong NewPassword"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"newpassword"}, Message: "Wrong NewPassword"}) return } login.Password = libpassword.NewHash(changePasswordRequest.NewPassword) if err := dbconnection.Save(login).Error; err != nil { logger.Warn("error save new password to database") - returnerr = &libapi.ErrorResult{Message: "Error save new password"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error save new password"}) return } sess.Set("login", login) logger.Info("done") - returndata = true - return + libapi.JSONWrite(w, r, true, nil) } //Delete of login on warehost -func delete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func delete(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() sess := ctx.Value("session").(libsession.Session) login := ctx.Value("login").(*Login) - returndata = false logger := log.GetLog(r, "delete") sess.Delete("login") if err := dbconnection.Unscoped().Delete(login).Error; err != nil { logger.Warn("error detete login") - returnerr = &libapi.ErrorResult{Message: "Error delete login"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error delete login"}) return } logger.Warn("done") - returndata = true - return + libapi.JSONWrite(w, r, true, nil) } // InviteList list all of your invites -func inviteList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func inviteList(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*Login) - returndata = false logger := log.GetLog(r, "invitelist") if err := dbconnection.Model(login).Preload("Invites.Invited").First(login).Error; err != nil { logger.Warn("error load own invites") - returnerr = &libapi.ErrorResult{Message: "Could not load invites!"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Could not load invites!"}) return } logger.Info("done") - returndata = login.Invites - return + libapi.JSONWrite(w, r, login.Invites, nil) } // InviteAdd invite a new user to warehost -func inviteAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func inviteAdd(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*Login) - returndata = false logger := log.GetLog(r, "inviteadd") var newLogin RequestLogin - returnerr = libapi.JSONDecoder(r.Body, &newLogin, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &newLogin) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } @@ -199,18 +197,17 @@ func inviteAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (ret } if err := dbconnection.Create(invite).Error; err != nil { logger.Warn("error create invite") - returnerr = &libapi.ErrorResult{Message: "Username exists already"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Username exists already"}) return } logger.Info("done") - returndata = true - return + libapi.JSONWrite(w, r, true, nil) } // LoginList list all users in system -func loginList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func loginList(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*Login) - returndata = false logger := log.GetLog(r, "loginlist") var logins []Login selectfield := "ID, mail" @@ -219,27 +216,27 @@ func loginList(ctx context.Context, w http.ResponseWriter, r *http.Request) (ret } if err := dbconnection.Select(selectfield).Find(&logins).Error; err != nil { logger.Warn("sql list login") - returnerr = &libapi.ErrorResult{Message: "Error during list login"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error during list login"}) return } logger.Info("done") - returndata = logins - return + libapi.JSONWrite(w, r, logins, nil) } // LoginAdd add a new Login -func loginAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func loginAdd(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*Login) - returndata = false logger := log.GetLog(r, "loginadd") if !login.Superadmin { logger.Error("no superadmin") - returnerr = &libapi.ErrorResult{Message: "Error no permission to edit this invite"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error no permission to edit this invite"}) return } var newLogin RequestLogin - returnerr = libapi.JSONDecoder(r.Body, &newLogin, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &newLogin) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } @@ -251,30 +248,30 @@ func loginAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (retu if err := dbconnection.Create(loginObj).Error; err != nil { logger.Warn("error create login") - returnerr = &libapi.ErrorResult{Message: "Username exists already"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Username exists already"}) return } logger.Info("done") - returndata = true - return + libapi.JSONWrite(w, r, true, nil) } // LoginEdit edit a login by invite or superadmin -func loginEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func loginEdit(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*Login) - returndata = false logger := log.GetLog(r, "loginedit") - id, err := strconv.ParseInt(pat.Param(ctx, "id"), 10, 64) + id, err := strconv.ParseInt(pat.Param(r, "id"), 10, 64) if err != nil { - returnerr = &libapi.ErrorResult{Message: "Error invalid input"} logger.Warn("invalid userinput, no integer") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error invalid input"}) return } logger = logger.WithField("id", id) var invitedLogin = Login{ID: id} var changeLogin RequestLogin - returnerr = libapi.JSONDecoder(r.Body, &changeLogin, w, logger) + returnerr := libapi.JSONDecoder(w, r, logger, &changeLogin) if returnerr != nil { + libapi.JSONWrite(w, r, false, returnerr) return } @@ -282,7 +279,7 @@ func loginEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (ret invite := invitedLogin.GetInvitedby(dbconnection) if !login.Superadmin && !invite.Admin && invitedLogin.CreateAt.Before(invitedLogin.LastLoginAt) { logger.Warn("no permission") - returnerr = &libapi.ErrorResult{Message: "Error no permission to edit this login"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error no permission to edit this login"}) return } if len(changeLogin.Password) > 0 { @@ -295,23 +292,22 @@ func loginEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (ret } if err := dbconnection.Save(invitedLogin).Error; err != nil { logger.Warn("sql edit login") - returnerr = &libapi.ErrorResult{Message: "Error during edit login"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error during edit login"}) return } logger.Info("done") - returndata = true - return + libapi.JSONWrite(w, r, true, nil) } // LoginDelete delete a login by invite or superadmin -func loginDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func loginDelete(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*Login) - returndata = false logger := log.GetLog(r, "logindelete") - id, err := strconv.ParseInt(pat.Param(ctx, "id"), 10, 64) + id, err := strconv.ParseInt(pat.Param(r, "id"), 10, 64) if err != nil { - returnerr = &libapi.ErrorResult{Message: "Error invalid input"} logger.Warn("invalid userinput, no integer") + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error invalid input"}) return } logger = logger.WithField("id", id) @@ -320,39 +316,36 @@ func loginDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (r invite := invitedLogin.GetInvitedby(dbconnection) if !login.Superadmin && !invite.Admin && invitedLogin.CreateAt.Before(invitedLogin.LastLoginAt) { logger.Warn("no permission") - returnerr = &libapi.ErrorResult{Message: "Error no permission to delete this login"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error no permission to delete this login"}) return } if err := dbconnection.Unscoped().Delete(invitedLogin).Error; err != nil { logger.Warn("sql detete login") - returnerr = &libapi.ErrorResult{Message: "Error during delete login"} + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error during delete login"}) return } logger.Info("done") - returndata = true - return + libapi.JSONWrite(w, r, true, nil) } // Invitor get Invite of current login -func invitor(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func invitor(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*Login) - returndata = false logger := log.GetLog(r, "invitor") invite := login.GetInvitedby(dbconnection) logger.Info("done") - returndata = invite - return + libapi.JSONWrite(w, r, invite, nil) } // InvitorAdminToggle toggle admin of current login -func invitorAdminToggle(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { +func invitorAdminToggle(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() login := ctx.Value("login").(*Login) - returndata = false logger := log.GetLog(r, "invitoradmintoggle") invite := login.GetInvitedby(dbconnection) invite.Admin = !invite.Admin dbconnection.Model(invite).Save(&invite) logger.Info("done") - returndata = true - return + libapi.JSONWrite(w, r, true, nil) } diff --git a/system/api_test.go b/system/api_test.go index a737ed5..0a3c58a 100644 --- a/system/api_test.go +++ b/system/api_test.go @@ -11,8 +11,8 @@ import ( func loginTest(session *test.Request, assertion *assert.Assertions) { result, w := session.JSONRequest("POST", "/login", RequestLogin{Username: "root", Password: "root"}) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) } func TestAPI(t *testing.T) { @@ -31,25 +31,25 @@ func TestAPI(t *testing.T) { * TEST status */ result, w := session.JSONRequest("GET", "/status", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) assertion.Nil(result.Error) - assertion.Equal(result.Data, true) + assertion.Equal(true, result.Data) /* * TEST login */ result, w = session.JSONRequest("POST", "/login", RequestLogin{Username: "root", Password: "root2"}) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, false) - assertion.Equal(result.Error.Fields[0], "password") + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(false, result.Data) + assertion.Equal("password", result.Error.Fields[0]) result, w = session.JSONRequest("POST", "/login", RequestLogin{Username: "root2", Password: "root"}) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, false) - assertion.Equal(result.Error.Fields[0], "username") + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(false, result.Data) + assertion.Equal("username", result.Error.Fields[0]) result, w = session.JSONRequest("POST", "/login", []byte{2, 3}) - assertion.Equal(w.StatusCode, http.StatusBadRequest) + assertion.Equal(http.StatusBadRequest, w.StatusCode) //login before loginTest(session, assertion) @@ -58,71 +58,71 @@ func TestAPI(t *testing.T) { * TEST logout */ result, w = session.JSONRequest("GET", "/logout", nil) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) // Test if crash on if not login in result, w = session.JSONRequest("GET", "/logout", nil) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) /* * TEST password */ session.Clean() result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root", NewPassword: "root-bug"}) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) //login before loginTest(session, assertion) result, w = session.JSONRequest("POST", "/password", []byte{2, 3}) - assertion.Equal(w.StatusCode, http.StatusBadRequest) + assertion.Equal(http.StatusBadRequest, w.StatusCode) result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root-wrong", NewPassword: "root-bug"}) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, false) - assertion.Equal(result.Error.Fields[0], "currentpassword") + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(false, result.Data) + assertion.Equal("currentpassword", result.Error.Fields[0]) result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root", NewPassword: ""}) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, false) - assertion.Equal(result.Error.Fields[0], "newpassword") + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(false, result.Data) + assertion.Equal("newpassword", result.Error.Fields[0]) result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root", NewPassword: "root-tmp"}) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root-tmp", NewPassword: "root"}) - assertion.Equal(w.StatusCode, http.StatusOK) - assertion.Equal(result.Data, true) + assertion.Equal(http.StatusOK, w.StatusCode) + assertion.Equal(true, result.Data) /* * TEST inviteList */ session.Clean() result, w = session.JSONRequest("GET", "/invite", nil) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) //login before loginTest(session, assertion) result, w = session.JSONRequest("GET", "/invite", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) /* * TEST loginList */ session.Clean() result, w = session.JSONRequest("GET", "/user", nil) - assertion.Equal(w.StatusCode, http.StatusUnauthorized) - assertion.Equal(result.Data, false) + assertion.Equal(http.StatusUnauthorized, w.StatusCode) + assertion.Equal(false, result.Data) //login before loginTest(session, assertion) result, w = session.JSONRequest("GET", "/user", nil) - assertion.Equal(w.StatusCode, http.StatusOK) + assertion.Equal(http.StatusOK, w.StatusCode) } diff --git a/system/lib.go b/system/lib.go index 2609e39..c389dc5 100644 --- a/system/lib.go +++ b/system/lib.go @@ -12,24 +12,25 @@ import ( //LoginHandler for api function to Verifie User ist loggedin func LoginHandler(h libapi.Handle) libapi.Handle { - return func(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { + return func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() sess := ctx.Value("session").(libsession.Session) - returndata = false if login := sess.Get("login"); login != nil { if loginObj := login.(*Login); loginObj.Active { ctx = context.WithValue(ctx, "login", loginObj) - returndata, returnerr = h(ctx, w, r) + r = r.WithContext(ctx) + h(w, r) return } - returnerr = &libapi.ErrorResult{Fields: []string{"session"}, Message: "Not active user"} - w.WriteHeader(http.StatusUnauthorized) liblog.Log.Warn("user not active") + w.WriteHeader(http.StatusUnauthorized) + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"session"}, Message: "Not active user"}) return } - w.WriteHeader(http.StatusUnauthorized) - returnerr = &libapi.ErrorResult{Fields: []string{"session"}, Message: "Not logged in"} liblog.Log.Warn("not loggedin") + w.WriteHeader(http.StatusUnauthorized) + libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"session"}, Message: "Not logged in"}) return } } diff --git a/test/main.go b/test/main.go index a6b8c79..4907b6f 100644 --- a/test/main.go +++ b/test/main.go @@ -58,6 +58,7 @@ func NewSession(router *goji.Mux) *Request { func (r *Request) JSONRequest(method string, url string, body interface{}) (jsonResult libapi.JSONResult, res *http.Response) { jsonObj, _ := json.Marshal(body) req, _ := http.NewRequest(method, url, bytes.NewReader(jsonObj)) + req.Header.Set("Content-Type", "application/json") for _, c := range r.cookies { req.AddCookie(c) } @@ -73,7 +74,7 @@ func (r *Request) JSONRequest(method string, url string, body interface{}) (json return } -// CleanSession to clean the current session +// Clean to clean the current session func (r *Request) Clean() { r.cookies = nil }