sum7/warehost
sum7
/
warehost
Archived
1
0
Fork 0

fix context

This commit is contained in:
Martin Geno 2016-12-19 12:24:18 +01:00
parent d8815c8316
commit 48cab176df
28 changed files with 706 additions and 681 deletions

View File

@ -13,7 +13,7 @@ type Config struct {
Path string `yaml:"path"` Path string `yaml:"path"`
} `yaml:"log"` } `yaml:"log"`
DatabaseDebug bool `yaml:"databasedebug"` DatabaseDebug bool `yaml:"databasedebug"`
FTPPath string `yaml:"data"` Own string `yaml:"own"`
Host string `yaml:"host"` Host string `yaml:"host"`
Web string `yaml:"web"` Web string `yaml:"web"`
Port int `yaml:"port"` Port int `yaml:"port"`

View File

@ -4,6 +4,6 @@ log:
path: test.log path: test.log
databasedebug: false databasedebug: false
port: 2222 port: 2222
data: /tmp/ftp/%d/ own: /tmp/ftp/%d/
host: /tmp/ftp-domain/%s/ host: /tmp/ftp-domain/%s/
web: /tmp/ftp-web/%d/ web: /tmp/ftp-web/%d/

View File

@ -13,11 +13,21 @@ import (
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres" _ "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" system "dev.sum7.eu/sum7/warehost/system"
) )
const (
DriverOwner = "warehost"
DriverGroup = "http"
DriverFolderOwn = "home"
DriverFolderDomain = "domain"
DriverFolderWeb = "web"
)
type FileDriver struct { type FileDriver struct {
RootPath string config Config
db *gorm.DB db *gorm.DB
Perm ftpd.Perm Perm ftpd.Perm
login system.Login login system.Login
@ -41,7 +51,7 @@ func (f *FackFileInfo) Name() string {
return f.name return f.name
} }
func (f *FackFileInfo) Owner() string { func (f *FackFileInfo) Owner() string {
return "warehost" return DriverOwner
} }
func (f *FackFileInfo) Size() int64 { func (f *FackFileInfo) Size() int64 {
return 0 return 0
@ -51,7 +61,7 @@ func (f *FackFileInfo) ModTime() time.Time {
} }
func (f *FackFileInfo) Group() string { func (f *FackFileInfo) Group() string {
return "http" return DriverGroup
} }
type FileInfo struct { type FileInfo struct {
@ -87,10 +97,22 @@ func (driver *FileDriver) realPath(path string) (string, bool) {
real := false real := false
if len(paths) > 1 && driver.login.ID > 0 { if len(paths) > 1 && driver.login.ID > 0 {
switch paths[1] { switch paths[1] {
case "data": case DriverFolderOwn:
root = fmt.Sprintf(driver.RootPath, driver.login.ID) root = fmt.Sprintf(driver.Own, driver.login.ID)
paths = append([]string{paths[0]}, paths[2:]...) paths = append([]string{paths[0]}, paths[2:]...)
real = true 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 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 return nil
} else { } else {
if path == "/" { switch path {
for _, i := range []string{"data", "web", "host"} { case "/":
for _, i := range []string{DriverFolderOwn, DriverFolderDomain, DriverFolderWeb} {
err := callback(&FackFileInfo{name: i}) err := callback(&FackFileInfo{name: i})
if err != nil { if err != nil {
return err return err
} }
} }
return nil 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") return errors.New("No path")
} }
@ -323,11 +370,11 @@ func (driver *FileDriver) PutFile(destPath string, data io.Reader, appendData bo
} }
type FileDriverFactory struct { type FileDriverFactory struct {
RootPath string config Config
db *gorm.DB db *gorm.DB
Perm ftpd.Perm Perm ftpd.Perm
} }
func (factory *FileDriverFactory) NewDriver() (ftpd.Driver, error) { 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
} }

View File

@ -46,7 +46,7 @@ func main() {
opt := &ftpd.ServerOpts{ opt := &ftpd.ServerOpts{
Name: "", 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, Port: config.Port,
Auth: WarehostAuth{db: dbconnection}, Auth: WarehostAuth{db: dbconnection},
} }

View File

@ -1,19 +1,17 @@
package api package api
import ( import (
"context"
"encoding/json" "encoding/json"
"io"
"net/http" "net/http"
log "github.com/Sirupsen/logrus" // TODO-Bad log "github.com/Sirupsen/logrus" // TODO-Bad
"goji.io"
"golang.org/x/net/context"
libsession "dev.sum7.eu/sum7/warehost/lib/session" libsession "dev.sum7.eu/sum7/warehost/lib/session"
) )
// Handle with response // 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 // ErrorResult struct for api error answer
type ErrorResult struct { type ErrorResult struct {
@ -31,8 +29,20 @@ type JSONResult struct {
} `json:"session,omitempty"` } `json:"session,omitempty"`
} }
// JSONOutput generate default json answer // SessionHandler Handler to manage session of api request
func JSONOutput(ctx context.Context, w http.ResponseWriter, r *http.Request, data interface{}, errorresult *ErrorResult) { 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) sess := ctx.Value("session").(libsession.Session)
result := JSONResult{Data: data, Error: errorresult} result := JSONResult{Data: data, Error: errorresult}
result.Session.Login = sess.Get("login") 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) 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 //JSONDecoder handle complete request of JSON
func JSONDecoder(r io.Reader, data interface{}, w http.ResponseWriter, logger *log.Entry) (returnerr *ErrorResult) { func JSONDecoder(w http.ResponseWriter, r *http.Request, logger *log.Entry, data interface{}) (returnerr *ErrorResult) {
err := json.NewDecoder(r).Decode(data) 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 { if err != nil {
logger.Error("fetch request") logger.Error("fetch request")
returnerr = &ErrorResult{ returnerr = &ErrorResult{

View File

@ -7,7 +7,6 @@ import (
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"goji.io" "goji.io"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
liblog "dev.sum7.eu/sum7/warehost/lib/log" liblog "dev.sum7.eu/sum7/warehost/lib/log"
@ -25,88 +24,96 @@ func BindAPI(db *gorm.DB, router *goji.Mux, prefix string) {
dbconnection = db dbconnection = db
log = liblog.NewModulLog(MODULNAME) log = liblog.NewModulLog(MODULNAME)
router.HandleFuncC(pat.Post(prefix+"/signup"), libapi.SessionHandler(system.LoginHandler(signup))) router.HandleFunc(pat.Post(prefix+"/signup"), libapi.SessionHandler(system.LoginHandler(signup)))
router.HandleFuncC(pat.Get(prefix+"/signup"), libapi.SessionHandler(system.LoginHandler(checkSignup))) router.HandleFunc(pat.Get(prefix+"/signup"), libapi.SessionHandler(system.LoginHandler(checkSignup)))
router.HandleFuncC(pat.Delete(prefix+"/delete"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(delete)))) router.HandleFunc(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.Get(prefix+"/profil"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(profil))))
router.HandleFuncC(pat.Get(prefix+"/domain"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainList)))) router.HandleFunc(pat.Get(prefix+"/domain"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainList))))
router.HandleFuncC(pat.Get(prefix+"/domain/:domainid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainShow)))) router.HandleFunc(pat.Get(prefix+"/domain/:domainid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainShow))))
router.HandleFuncC(pat.Post(prefix+"/domain"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainAdd)))) router.HandleFunc(pat.Post(prefix+"/domain"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainAdd))))
router.HandleFuncC(pat.Patch(prefix+"/domain/:domainid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(domainEdit)))) router.HandleFunc(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.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.HandleFunc(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.HandleFunc(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.HandleFunc(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.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.HandleFunc(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.HandleFunc(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.HandleFunc(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.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.HandleFunc(pat.Get(prefix+"/database"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseList))))
router.HandleFuncC(pat.Post(prefix+"/database"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseAdd)))) router.HandleFunc(pat.Post(prefix+"/database"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseAdd))))
router.HandleFuncC(pat.Patch(prefix+"/database/:databaseid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseEdit)))) router.HandleFunc(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.Delete(prefix+"/database/:databaseid"), libapi.SessionHandler(system.LoginHandler(ProfilHandler(databaseDelete))))
// ADMIN APIS // ADMIN APIS
router.HandleFuncC(pat.Get(prefix+"/profils"), libapi.SessionHandler(system.LoginHandler(profilList))) router.HandleFunc(pat.Get(prefix+"/profils"), libapi.SessionHandler(system.LoginHandler(profilList)))
router.HandleFuncC(pat.Patch(prefix+"/profil/:id"), libapi.SessionHandler(system.LoginHandler(toggleReseller))) 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) { func checkSignupAllow(login *system.Login) bool {
login := ctx.Value("login").(*system.Login)
returndata = false
logger := log.GetLog(r, "checksignup")
run := login.Superadmin run := login.Superadmin
if !run { if !run {
var profil Profil var profil Profil
dbconnection.Joins("LEFT JOIN invite invite ON invite.login=host_profil.login").Where("invite.invited=?", login.ID).Find(&profil) dbconnection.Joins("LEFT JOIN invite invite ON invite.login=host_profil.login").Where("invite.invited=?", login.ID).Find(&profil)
run = profil.Reseller run = profil.Reseller
} }
returndata = run return run
if run {
logger.Info("done")
return
}
w.WriteHeader(http.StatusUnauthorized)
logger.Info("not allowed")
return
} }
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) login := ctx.Value("login").(*system.Login)
logger := log.GetLog(r, "signup") logger := log.GetLog(r, "signup")
returndata, returnerr = checkSignup(ctx, w, r) if checkSignupAllow(login) {
if returndata.(bool) {
profil := &Profil{LoginID: login.ID} profil := &Profil{LoginID: login.ID}
if err := dbconnection.Create(profil).Error; err != nil { if err := dbconnection.Create(profil).Error; err != nil {
w.WriteHeader(http.StatusInternalServerError)
if strings.Contains(err.Error(), "duplicate key") { if strings.Contains(err.Error(), "duplicate key") {
returndata = false
logger.Warning("exists already") logger.Warning("exists already")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "already signup"})
return return
} }
logger.Error("database: during create host profil: ", err) logger.Error("database: during create host profil: ", err)
returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"})
w.WriteHeader(http.StatusInternalServerError)
return return
} }
returndata = true
logger.Info("done") logger.Info("done")
libapi.JSONWrite(w, r, true, nil)
return 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) profil := ctx.Value("profil").(*Profil)
returndata = true
dbconnection.Unscoped().Delete(profil) 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) profil := ctx.Value("profil").(*Profil)
returndata = profil logger.Info("done")
return libapi.JSONWrite(w, r, profil, nil)
} }

View File

@ -12,8 +12,8 @@ import (
func loginTest(session *test.Request, assertion *assert.Assertions) { func loginTest(session *test.Request, assertion *assert.Assertions) {
result, w := session.JSONRequest("POST", "/login", system.RequestLogin{Username: "root", Password: "root"}) result, w := session.JSONRequest("POST", "/login", system.RequestLogin{Username: "root", Password: "root"})
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
} }
func TestAPI(t *testing.T) { func TestAPI(t *testing.T) {
@ -35,71 +35,71 @@ func TestAPI(t *testing.T) {
* TEST signup * TEST signup
*/ */
result, w := session.JSONRequest("POST", "/host/signup", nil) result, w := session.JSONRequest("POST", "/host/signup", nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("POST", "/host/signup", nil) result, w = session.JSONRequest("POST", "/host/signup", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("POST", "/host/signup", nil) result, w = session.JSONRequest("POST", "/host/signup", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusInternalServerError, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
/* /*
* TEST checksignup * TEST checksignup
*/ */
session.Clean() session.Clean()
result, w = session.JSONRequest("GET", "/host/signup", nil) result, w = session.JSONRequest("GET", "/host/signup", nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("GET", "/host/signup", nil) result, w = session.JSONRequest("GET", "/host/signup", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
/* /*
* TEST delete * TEST delete
*/ */
session.Clean() session.Clean()
result, w = session.JSONRequest("DELETE", "/host/delete", nil) result, w = session.JSONRequest("DELETE", "/host/delete", nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("DELETE", "/host/delete", nil) result, w = session.JSONRequest("DELETE", "/host/delete", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("DELETE", "/host/delete", nil) result, w = session.JSONRequest("DELETE", "/host/delete", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
/* /*
* TEST profil * TEST profil
*/ */
session.Clean() session.Clean()
result, w = session.JSONRequest("GET", "/host/profil", nil) result, w = session.JSONRequest("GET", "/host/profil", nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("GET", "/host/profil", nil) result, w = session.JSONRequest("GET", "/host/profil", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
// Need a Profile for Next tests // Need a Profile for Next tests
result, w = session.JSONRequest("POST", "/host/signup", nil) result, w = session.JSONRequest("POST", "/host/signup", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("GET", "/host/profil", nil) result, w = session.JSONRequest("GET", "/host/profil", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.NotEqual(result.Data, false) assertion.NotEqual(false, result.Data)
} }

View File

@ -5,16 +5,16 @@ import (
"strconv" "strconv"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
system "dev.sum7.eu/sum7/warehost/system" 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) login := ctx.Value("login").(*system.Login)
profil := ctx.Value("profil").(*Profil) 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 { if err != nil {
returnerr = &libapi.ErrorResult{ returnerr = &libapi.ErrorResult{
Message: "Internal Request Error", Message: "Internal Request Error",
@ -22,12 +22,12 @@ func getDatabase(ctx context.Context, w http.ResponseWriter) (database Database,
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
return return
} }
database = Database{ID: id} database = Database{}
if login.Superadmin { if login.Superadmin {
dbconnection.Find(&database) dbconnection.Where("ID = ?", id).Find(&database)
} else { } 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 { if database.ID <= 0 {
@ -37,10 +37,10 @@ func getDatabase(ctx context.Context, w http.ResponseWriter) (database Database,
return 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) login := ctx.Value("login").(*system.Login)
profil := ctx.Value("profil").(*Profil) profil := ctx.Value("profil").(*Profil)
returndata = false
logger := log.GetLog(r, "databaselist") logger := log.GetLog(r, "databaselist")
var database []*Database var database []*Database
if login.Superadmin && r.URL.Query().Get("filter") == "all" { 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) dbconnection.Where("profil = ?", profil.ID).Preload("Profil").Find(&database)
} }
logger.Info("done") logger.Info("done")
returndata = database libapi.JSONWrite(w, r, database, nil)
return
} }
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) profil := ctx.Value("profil").(*Profil)
returndata = false
logger := log.GetLog(r, "databaseadd") logger := log.GetLog(r, "databaseadd")
var databaseRequest Database var databaseRequest Database
returnerr = libapi.JSONDecoder(r.Body, &databaseRequest, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &databaseRequest)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return 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 { if err := dbconnection.Create(database).Error; err != nil {
logger.Error("database: during create host database: ", err) logger.Error("database: during create host database: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 return
} }
returndata = true
logger.Info("done") 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) { func databaseEdit(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "databaseedit") logger := log.GetLog(r, "databaseedit")
database, returnerr := getDatabase(ctx, w) database, returnerr := getDatabase(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
logger = logger.WithField("dbID", database.ID) logger = logger.WithField("dbID", database.ID)
var databaseRequest Database var databaseRequest Database
returnerr = libapi.JSONDecoder(r.Body, &databaseRequest, w, logger) returnerr = libapi.JSONDecoder(w, r, logger, &databaseRequest)
if returnerr != nil { if returnerr != nil {
return libapi.JSONWrite(w, r, false, returnerr)
} }
database.Password = databaseRequest.Password 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 { if err := dbconnection.Save(database).Error; err != nil {
logger.Error("database: during modify host database: ", err) logger.Error("database: during modify host database: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 return
} }
returndata = true
logger.Info("done") 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) { func databaseDelete(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "databasedelete") logger := log.GetLog(r, "databasedelete")
database, returnerr := getDatabase(ctx, w) database, returnerr := getDatabase(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
logger = logger.WithField("dbID", database.ID) 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 { if err := dbconnection.Unscoped().Delete(database).Error; err != nil {
logger.Error("database: during create host database: ", err) logger.Error("database: during create host database: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }

View File

@ -27,30 +27,30 @@ func TestAPIDatabase(t *testing.T) {
loginTest(session, assertion) loginTest(session, assertion)
result, w := session.JSONRequest("DELETE", "/host/delete", nil) 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 // Need a Profile for Next tests
result, w = session.JSONRequest("POST", "/host/signup", nil) result, w = session.JSONRequest("POST", "/host/signup", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
/* /*
* TEST databaseList * TEST databaseList
*/ */
session.Clean() session.Clean()
result, w = session.JSONRequest("GET", "/host/database", nil) result, w = session.JSONRequest("GET", "/host/database", nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("GET", "/host/database", nil) result, w = session.JSONRequest("GET", "/host/database", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.NotEqual(result.Data, false) assertion.NotEqual(false, result.Data)
result, w = session.JSONRequest("GET", "/host/database?filter=all", nil) result, w = session.JSONRequest("GET", "/host/database?filter=all", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.NotEqual(result.Data, false) assertion.NotEqual(false, result.Data)
/* /*
* TEST databaseAdd * TEST databaseAdd
@ -59,15 +59,15 @@ func TestAPIDatabase(t *testing.T) {
Password: "example.de", Password: "example.de",
Comment: "test", Comment: "test",
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.NotEqual(result.Data, false) assertion.NotEqual(false, result.Data)
/* /*
* TEST databaseEdit * TEST databaseEdit
*/ */
result, w = session.JSONRequest("GET", "/host/database", nil) result, w = session.JSONRequest("GET", "/host/database", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.NotEqual(result.Data, false) assertion.NotEqual(false, result.Data)
var database int var database int
for _, obj := range result.Data.([]interface{}) { for _, obj := range result.Data.([]interface{}) {
item := obj.(map[string]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{ result, w = session.JSONRequest("PATCH", "/host/database/"+strconv.Itoa(database), Database{
Comment: "test-bug", Comment: "test-bug",
}) })
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("PATCH", "/host/database/"+strconv.Itoa(database), Database{ result, w = session.JSONRequest("PATCH", "/host/database/"+strconv.Itoa(database), Database{
Comment: "test2", Comment: "test2",
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("PATCH", "/host/database/"+strconv.Itoa(-1), Database{ result, w = session.JSONRequest("PATCH", "/host/database/"+strconv.Itoa(-1), Database{
Comment: "test-bug", Comment: "test-bug",
}) })
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("PATCH", "/host/database/"+strconv.Itoa(database), []byte{2, 3}) result, w = session.JSONRequest("PATCH", "/host/database/"+strconv.Itoa(database), []byte{2, 3})
assertion.Equal(w.StatusCode, http.StatusBadRequest) assertion.Equal(http.StatusBadRequest, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
/* /*
* TEST databaseDelete * TEST databaseDelete
@ -108,17 +108,17 @@ func TestAPIDatabase(t *testing.T) {
session.Clean() session.Clean()
result, w = session.JSONRequest("DELETE", "/host/database/"+strconv.Itoa(database), nil) result, w = session.JSONRequest("DELETE", "/host/database/"+strconv.Itoa(database), nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("DELETE", "/host/database/"+strconv.Itoa(database), nil) result, w = session.JSONRequest("DELETE", "/host/database/"+strconv.Itoa(database), nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("DELETE", "/host/database/"+strconv.Itoa(database), nil) result, w = session.JSONRequest("DELETE", "/host/database/"+strconv.Itoa(database), nil)
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
} }

View File

@ -6,16 +6,16 @@ import (
"strings" "strings"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
system "dev.sum7.eu/sum7/warehost/system" 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) login := ctx.Value("login").(*system.Login)
profil := ctx.Value("profil").(*Profil) 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 { if err != nil {
returnerr = &libapi.ErrorResult{ returnerr = &libapi.ErrorResult{
Message: "Internal Request Error", Message: "Internal Request Error",
@ -23,12 +23,12 @@ func getDomain(ctx context.Context, w http.ResponseWriter) (domain Domain, retur
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
return return
} }
domain = Domain{ID: id} domain = Domain{}
if login.Superadmin { if login.Superadmin {
dbconnection.Find(&domain) dbconnection.Where("ID = ?", id).Find(&domain)
} else { } 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 { if domain.ID <= 0 {
@ -38,10 +38,10 @@ func getDomain(ctx context.Context, w http.ResponseWriter) (domain Domain, retur
return 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) login := ctx.Value("login").(*system.Login)
profil := ctx.Value("profil").(*Profil) profil := ctx.Value("profil").(*Profil)
returndata = false
logger := log.GetLog(r, "domainlist") logger := log.GetLog(r, "domainlist")
var domain []*Domain var domain []*Domain
if login.Superadmin && r.URL.Query().Get("filter") == "all" { 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) dbconnection.Where("profil = ?", profil.ID).Find(&domain)
} }
logger.Info("done") logger.Info("done")
returndata = domain libapi.JSONWrite(w, r, domain, nil)
return
} }
func domainShow(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func domainShow(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "domainshow") logger := log.GetLog(r, "domainshow")
domain, returnerr := getDomain(ctx, w) domain, returnerr := getDomain(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
return return
} }
logger = logger.WithField("dID", domain.ID) logger = logger.WithField("dID", domain.ID)
logger.Info("done") logger.Info("done")
returndata = domain libapi.JSONWrite(w, r, domain, nil)
return
} }
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) profil := ctx.Value("profil").(*Profil)
returndata = false
logger := log.GetLog(r, "domainadd") logger := log.GetLog(r, "domainadd")
var domainRequest Domain var domainRequest Domain
returnerr = libapi.JSONDecoder(r.Body, &domainRequest, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &domainRequest)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return 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 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") logger.Warning("exists already")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "already signup"})
return return
} }
logger.Error("database: during create host domain: ", err) logger.Error("database: during create host domain: ", err)
w.WriteHeader(http.StatusInternalServerError) libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"})
returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"}
return return
} }
returndata = true
logger.Info("done") 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) login := ctx.Value("login").(*system.Login)
returndata = false
logger := log.GetLog(r, "domainedit") logger := log.GetLog(r, "domainedit")
domain, returnerr := getDomain(ctx, w) domain, returnerr := getDomain(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
return return
@ -114,8 +112,9 @@ func domainEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (re
logger = logger.WithField("dID", domain.ID) logger = logger.WithField("dID", domain.ID)
var domainRequest Domain var domainRequest Domain
returnerr = libapi.JSONDecoder(r.Body, &domainRequest, w, logger) returnerr = libapi.JSONDecoder(w, r, logger, &domainRequest)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return 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 { if err := dbconnection.Save(domain).Error; err != nil {
logger.Error("database: during modify host domain: ", err) logger.Error("database: during modify host domain: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 return
} }
returndata = true
logger.Info("done") 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) { func domainDelete(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "domaindelete") logger := log.GetLog(r, "domaindelete")
domain, returnerr := getDomain(ctx, w) domain, returnerr := getDomain(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
return 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 { if err := dbconnection.Unscoped().Delete(domain).Error; err != nil {
logger.Error("database: during create host domain: ", err) logger.Error("database: during create host domain: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }

View File

@ -27,30 +27,31 @@ func TestAPIDomain(t *testing.T) {
loginTest(session, assertion) loginTest(session, assertion)
result, w := session.JSONRequest("DELETE", "/host/delete", nil) 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 // Need a Profile for Next tests
result, w = session.JSONRequest("POST", "/host/signup", nil) result, w = session.JSONRequest("POST", "/host/signup", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
/* /*
* TEST domainList * TEST domainList
*/ */
session.Clean() session.Clean()
result, w = session.JSONRequest("GET", "/host/domain", nil) result, w = session.JSONRequest("GET", "/host/domain", nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("GET", "/host/domain", nil) 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) assertion.NotEqual(false, result.Data)
result, w = session.JSONRequest("GET", "/host/domain?filter=all", nil) result, w = session.JSONRequest("GET", "/host/domain?filter=all", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.NotEqual(result.Data, false) assertion.NotEqual(false, result.Data)
/* /*
* TEST domainAdd * TEST domainAdd
@ -59,33 +60,33 @@ func TestAPIDomain(t *testing.T) {
result, w = session.JSONRequest("POST", "/host/domain", Domain{ result, w = session.JSONRequest("POST", "/host/domain", Domain{
FQDN: "example.de", FQDN: "example.de",
}) })
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("POST", "/host/domain", []byte{2, 3}) result, w = session.JSONRequest("POST", "/host/domain", []byte{2, 3})
assertion.Equal(w.StatusCode, http.StatusBadRequest) assertion.Equal(http.StatusBadRequest, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("POST", "/host/domain", Domain{ result, w = session.JSONRequest("POST", "/host/domain", Domain{
FQDN: "example.de", FQDN: "example.de",
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.NotEqual(result.Data, false) assertion.NotEqual(false, result.Data)
result, w = session.JSONRequest("POST", "/host/domain", Domain{ result, w = session.JSONRequest("POST", "/host/domain", Domain{
FQDN: "example.de", FQDN: "example.de",
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
/* /*
* TEST domainEdit * TEST domainEdit
*/ */
result, w = session.JSONRequest("GET", "/host/domain", nil) 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) assertion.NotEqual(false, result.Data)
var domain int var domain int
for _, obj := range result.Data.([]interface{}) { for _, obj := range result.Data.([]interface{}) {
item := obj.(map[string]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{ result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain), Domain{
Mail: true, Mail: true,
}) })
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain), Domain{ result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain), Domain{
Mail: true, Mail: true,
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(-1), Domain{ result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(-1), Domain{
Mail: true, Mail: true,
}) })
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain), []byte{2, 3}) result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain), []byte{2, 3})
assertion.Equal(w.StatusCode, http.StatusBadRequest) assertion.Equal(http.StatusBadRequest, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
/* /*
* TEST domainShow * TEST domainShow
@ -126,18 +127,18 @@ func TestAPIDomain(t *testing.T) {
session.Clean() session.Clean()
result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain), nil) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain), nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(-1), nil) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(-1), nil)
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain), nil) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain), nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.NotEqual(result.Data, false) assertion.NotEqual(false, result.Data)
/* /*
* TEST domainDelete * TEST domainDelete
@ -145,22 +146,22 @@ func TestAPIDomain(t *testing.T) {
session.Clean() session.Clean()
result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain), nil) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain), nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(-1), nil) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(-1), nil)
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain), nil) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain), nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain), nil) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain), nil)
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
// CLEANUP // CLEANUP

View File

@ -6,16 +6,16 @@ import (
"strings" "strings"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
system "dev.sum7.eu/sum7/warehost/system" 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) login := ctx.Value("login").(*system.Login)
profil := ctx.Value("profil").(*Profil) 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 { if err != nil {
returnerr = &libapi.ErrorResult{ returnerr = &libapi.ErrorResult{
Message: "Internal Request Error", Message: "Internal Request Error",
@ -37,11 +37,10 @@ func getMail(ctx context.Context, w http.ResponseWriter) (mail Mail, returnerr *
return return
} }
func mailList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func mailList(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "maillist") logger := log.GetLog(r, "maillist")
var mail []*Mail var mail []*Mail
domain, returnerr := getDomain(ctx, w) domain, returnerr := getDomain(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
return return
@ -49,23 +48,24 @@ func mailList(ctx context.Context, w http.ResponseWriter, r *http.Request) (retu
logger = logger.WithField("dID", domain.ID) logger = logger.WithField("dID", domain.ID)
dbconnection.Where("domain = ?", domain.ID).Preload("Domain").Preload("Forwards").Find(&mail) dbconnection.Where("domain = ?", domain.ID).Preload("Domain").Preload("Forwards").Find(&mail)
logger.Info("done") logger.Info("done")
returndata = mail libapi.JSONWrite(w, r, mail, nil)
return return
} }
func mailAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func mailAdd(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "mailadd") logger := log.GetLog(r, "mailadd")
var mailRequest Mail var mailRequest Mail
returnerr = libapi.JSONDecoder(r.Body, &mailRequest, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &mailRequest)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
domain, returnerr := getDomain(ctx, w) domain, returnerr := getDomain(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
logger = logger.WithField("dID", domain.ID) 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 { if err := dbconnection.Create(mail).Error; err != nil {
w.WriteHeader(http.StatusInternalServerError)
if strings.Contains(err.Error(), "duplicate key") { if strings.Contains(err.Error(), "duplicate key") {
logger.Warning("exists already") logger.Warning("exists already")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "already signup"})
return return
} }
logger.Error("database: during create host mail: ", err) logger.Error("database: during create host mail: ", err)
w.WriteHeader(http.StatusInternalServerError) libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"})
returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"}
return return
} }
returndata = true
logger.Info("done") 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) { func mailEdit(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "mailedit") logger := log.GetLog(r, "mailedit")
mail, returnerr := getMail(ctx, w) mail, returnerr := getMail(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
return return
@ -104,8 +103,9 @@ func mailEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (retu
logger = logger.WithField("mID", mail.ID) logger = logger.WithField("mID", mail.ID)
var mailRequest Mail var mailRequest Mail
returnerr = libapi.JSONDecoder(r.Body, &mailRequest, w, logger) returnerr = libapi.JSONDecoder(w, r, logger, &mailRequest)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return 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 { if err := dbconnection.Unscoped().Delete(MailForward{}, "id in (?)", idsDel).Error; err != nil {
logger.Error("database: during delete host mail forwards: ", err) logger.Error("database: during delete host mail forwards: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 return
} }
if err := dbconnection.Save(mail).Error; err != nil { if err := dbconnection.Save(mail).Error; err != nil {
logger.Error("database: during modify host mail: ", err) logger.Error("database: during modify host mail: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 return
} }
returndata = true
logger.Info("done") 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) { func mailDelete(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "maildelete") logger := log.GetLog(r, "maildelete")
mail, returnerr := getMail(ctx, w) mail, returnerr := getMail(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
logger = logger.WithField("mID", mail.ID) 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 { if err := dbconnection.Unscoped().Delete(mail).Error; err != nil {
logger.Error("database: during create host mail: ", err) logger.Error("database: during create host mail: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }

View File

@ -27,23 +27,23 @@ func TestAPIMail(t *testing.T) {
loginTest(session, assertion) loginTest(session, assertion)
result, w := session.JSONRequest("DELETE", "/host/delete", nil) 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 // Need a Profile for Next tests
result, w = session.JSONRequest("POST", "/host/signup", nil) result, w = session.JSONRequest("POST", "/host/signup", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
// Need a Domain for next tests // Need a Domain for next tests
result, w = session.JSONRequest("POST", "/host/domain", Domain{ result, w = session.JSONRequest("POST", "/host/domain", Domain{
FQDN: "example.de", FQDN: "example.de",
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
// Get id von domain // Get id von domain
result, w = session.JSONRequest("GET", "/host/domain", nil) 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) assertion.NotEqual(result.Data, false)
var domain int var domain int
for _, obj := range result.Data.([]interface{}) { 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) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain)+"/mail", nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(w.StatusCode, http.StatusUnauthorized)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(-1)+"/mail", nil) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(-1)+"/mail", nil)
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain)+"/mail", nil) 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) assertion.NotEqual(result.Data, false)
/* /*
@ -81,37 +81,37 @@ func TestAPIMail(t *testing.T) {
Name: "test-bug", Name: "test-bug",
}) })
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(w.StatusCode, http.StatusUnauthorized)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/mail", []byte{2, 3}) result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/mail", []byte{2, 3})
assertion.Equal(w.StatusCode, http.StatusBadRequest) 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{ result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(-1)+"/mail", Mail{
Name: "test-bug", Name: "test-bug",
}) })
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/mail", Mail{ result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/mail", Mail{
Name: "test", Name: "test",
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/mail", Mail{ result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/mail", Mail{
Name: "test", Name: "test",
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
/* /*
* TEST mailEdit * TEST mailEdit
*/ */
result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain)+"/mail", nil) 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) assertion.NotEqual(result.Data, false)
var mail int var mail int
for _, obj := range result.Data.([]interface{}) { for _, obj := range result.Data.([]interface{}) {
@ -127,25 +127,25 @@ func TestAPIMail(t *testing.T) {
Name: "test-bug-auth", Name: "test-bug-auth",
}) })
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(w.StatusCode, http.StatusUnauthorized)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), []byte{2, 3}) 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(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{ result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(-1), Mail{
Name: "test-bug", Name: "test-bug",
}) })
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), Mail{ result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), Mail{
Name: "test", Name: "test",
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
/* /*
* TEST domainDelete * 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) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(w.StatusCode, http.StatusUnauthorized)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(-1), nil) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(-1), nil)
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), nil) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), nil) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/mail/"+strconv.Itoa(mail), nil)
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
} }

View File

@ -5,42 +5,40 @@ import (
"strconv" "strconv"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
system "dev.sum7.eu/sum7/warehost/system" 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) login := ctx.Value("login").(*system.Login)
returndata = false
logger := log.GetLog(r, "toggleReseller") logger := log.GetLog(r, "toggleReseller")
if !login.Superadmin { if !login.Superadmin {
returnerr = &libapi.ErrorResult{Fields: []string{"session"}, Message: "not a superadmin"}
w.WriteHeader(http.StatusUnauthorized)
logger.Warn("not a superadmin") logger.Warn("not a superadmin")
w.WriteHeader(http.StatusUnauthorized)
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"session"}, Message: "not a superadmin"})
return return
} }
var profils []*Profil var profils []*Profil
dbconnection.Preload("Login").Find(&profils) dbconnection.Preload("Login").Find(&profils)
returndata = profils libapi.JSONWrite(w, r, profils, nil)
return
} }
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) login := ctx.Value("login").(*system.Login)
returndata = false
logger := log.GetLog(r, "toggleReseller") logger := log.GetLog(r, "toggleReseller")
if !login.Superadmin { if !login.Superadmin {
returnerr = &libapi.ErrorResult{Fields: []string{"session"}, Message: "not a superadmin"}
w.WriteHeader(http.StatusUnauthorized)
logger.Warn("not a superadmin") logger.Warn("not a superadmin")
w.WriteHeader(http.StatusUnauthorized)
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"session"}, Message: "not a superadmin"})
return return
} }
id, err := strconv.ParseInt(pat.Param(ctx, "id"), 10, 64) id, err := strconv.ParseInt(pat.Param(r, "id"), 10, 64)
if err != nil { if err != nil {
returnerr = &libapi.ErrorResult{Message: "Error invalid input"}
logger.Warn("invalid userinput, no integer") logger.Warn("invalid userinput, no integer")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error invalid input"})
return return
} }
logger = logger.WithField("id", id) 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 { if err := dbconnection.Save(profil).Error; err != nil {
logger.Error("database: during modify host profil: ", err) logger.Error("database: during modify host profil: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 return
} }
returndata = true libapi.JSONWrite(w, r, true, nil)
return
} }

View File

@ -27,12 +27,12 @@ func TestAPIProfil(t *testing.T) {
loginTest(session, assertion) loginTest(session, assertion)
result, w := session.JSONRequest("DELETE", "/host/delete", nil) 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 // Need a Profile for Next tests
result, w = session.JSONRequest("POST", "/host/signup", nil) result, w = session.JSONRequest("POST", "/host/signup", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
/* /*
* TEST profilList * TEST profilList
@ -40,19 +40,19 @@ func TestAPIProfil(t *testing.T) {
session.Clean() session.Clean()
result, w = session.JSONRequest("GET", "/host/profils", nil) result, w = session.JSONRequest("GET", "/host/profils", nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(w.StatusCode, http.StatusUnauthorized)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("GET", "/host/profils", nil) 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) assertion.NotEqual(result.Data, false)
/* /*
* TEST toggleReseller * TEST toggleReseller
*/ */
result, w = session.JSONRequest("GET", "/host/profils", nil) 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) assertion.NotEqual(result.Data, false)
var id int var id int
for _, obj := range result.Data.([]interface{}) { 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) result, w = session.JSONRequest("PATCH", "/host/profil/"+strconv.Itoa(id), nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(w.StatusCode, http.StatusUnauthorized)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("PATCH", "/host/profil/"+strconv.Itoa(id), nil) result, w = session.JSONRequest("PATCH", "/host/profil/"+strconv.Itoa(id), nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("PATCH", "/host/profil/"+strconv.Itoa(id), nil) result, w = session.JSONRequest("PATCH", "/host/profil/"+strconv.Itoa(id), nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
} }

View File

@ -6,7 +6,6 @@ import (
"strings" "strings"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
system "dev.sum7.eu/sum7/warehost/system" 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) login := ctx.Value("login").(*system.Login)
profil := ctx.Value("profil").(*Profil) 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 { if err != nil {
returnerr = &libapi.ErrorResult{ returnerr = &libapi.ErrorResult{
Message: "Internal Request Error", Message: "Internal Request Error",
@ -49,11 +49,10 @@ func getWeb(ctx context.Context, w http.ResponseWriter) (web Web, returnerr *lib
return return
} }
func webList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func webList(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "weblist") logger := log.GetLog(r, "weblist")
var web []*Web var web []*Web
domain, returnerr := getDomain(ctx, w) domain, returnerr := getDomain(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
return 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) dbconnection.Where("domain = ?", domain.ID).Preload("Domain").Preload("HTTPAccess.Login").Preload("FTPAccess.Login").Find(&web)
logger.Info("done") logger.Info("done")
returndata = web libapi.JSONWrite(w, r, web, nil)
return
} }
func webAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func webAdd(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "webadd") logger := log.GetLog(r, "webadd")
var webRequest Web var webRequest Web
returnerr = libapi.JSONDecoder(r.Body, &webRequest, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &webRequest)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
domain, returnerr := getDomain(ctx, w) domain, returnerr := getDomain(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
logger = logger.WithField("dID", domain.ID) 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 { if err := dbconnection.Create(web).Error; err != nil {
w.WriteHeader(http.StatusInternalServerError)
if strings.Contains(err.Error(), "duplicate key") { if strings.Contains(err.Error(), "duplicate key") {
logger.Warning("exists already") logger.Warning("exists already")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "already signup"})
return return
} }
logger.Error("database: during create host web: ", err) logger.Error("database: during create host web: ", err)
w.WriteHeader(http.StatusInternalServerError) libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error with Database"})
returnerr = &libapi.ErrorResult{Message: "Internal Database Error with Database"}
return return
} }
returndata = true
logger.Info("done") 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) { func webEdit(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "webedit") logger := log.GetLog(r, "webedit")
web, returnerr := getWeb(ctx, w) web, returnerr := getWeb(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
logger = logger.WithField("wID", web.ID) logger = logger.WithField("wID", web.ID)
var webRequest Web var webRequest Web
returnerr = libapi.JSONDecoder(r.Body, &webRequest, w, logger) returnerr = libapi.JSONDecoder(w, r, logger, &webRequest)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return 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 { 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) logger.Error("database: during delete host web httpaccess: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 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 { 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) logger.Error("database: during delete host web ftpaccess: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 return
} }
cleanLoginFTPAccess(web.FTPAccess) 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 { if err := dbconnection.Save(web).Error; err != nil {
logger.Error("database: during modify host web: ", err) logger.Error("database: during modify host web: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 return
} }
returndata = true
logger.Info("done") 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) { func webDelete(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "webdelete") logger := log.GetLog(r, "webdelete")
web, returnerr := getWeb(ctx, w) web, returnerr := getWeb(w, r)
if returnerr != nil { if returnerr != nil {
logger.Info("not found") logger.Info("not found")
return 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 { if err := dbconnection.Unscoped().Delete(web).Error; err != nil {
logger.Error("database: during create host web: ", err) logger.Error("database: during create host web: ", err)
w.WriteHeader(http.StatusInternalServerError) 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }

View File

@ -27,23 +27,23 @@ func TestAPIWeb(t *testing.T) {
loginTest(session, assertion) loginTest(session, assertion)
result, w := session.JSONRequest("DELETE", "/host/delete", nil) 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 // Need a Profile for Next tests
result, w = session.JSONRequest("POST", "/host/signup", nil) result, w = session.JSONRequest("POST", "/host/signup", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
// Need a Domain for next tests // Need a Domain for next tests
result, w = session.JSONRequest("POST", "/host/domain", Domain{ result, w = session.JSONRequest("POST", "/host/domain", Domain{
FQDN: "example.de", FQDN: "example.de",
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
// Get id von domain // Get id von domain
result, w = session.JSONRequest("GET", "/host/domain", nil) 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) assertion.NotEqual(result.Data, false)
var domain int var domain int
for _, obj := range result.Data.([]interface{}) { 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) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain)+"/web", nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(w.StatusCode, http.StatusUnauthorized)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(-1)+"/web", nil) result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(-1)+"/web", nil)
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain)+"/web", nil) 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) assertion.NotEqual(result.Data, false)
/* /*
@ -81,37 +81,37 @@ func TestAPIWeb(t *testing.T) {
Subdomain: "", Subdomain: "",
}) })
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(w.StatusCode, http.StatusUnauthorized)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/web", []byte{2, 3}) result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/web", []byte{2, 3})
assertion.Equal(w.StatusCode, http.StatusBadRequest) 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{ result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(-1)+"/web", Web{
Subdomain: "", Subdomain: "",
}) })
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/web", Web{ result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/web", Web{
Subdomain: "", Subdomain: "",
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/web", Web{ result, w = session.JSONRequest("POST", "/host/domain/"+strconv.Itoa(domain)+"/web", Web{
Subdomain: "", Subdomain: "",
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
/* /*
* TEST webEdit * TEST webEdit
*/ */
result, w = session.JSONRequest("GET", "/host/domain/"+strconv.Itoa(domain)+"/web", nil) 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) assertion.NotEqual(result.Data, false)
var web int var web int
for _, obj := range result.Data.([]interface{}) { for _, obj := range result.Data.([]interface{}) {
@ -127,25 +127,25 @@ func TestAPIWeb(t *testing.T) {
Subdomain: "test-bug-auth", Subdomain: "test-bug-auth",
}) })
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(w.StatusCode, http.StatusUnauthorized)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), []byte{2, 3}) 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(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{ result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(-1), Web{
Subdomain: "test-bug", Subdomain: "test-bug",
}) })
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), Web{ result, w = session.JSONRequest("PATCH", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), Web{
Subdomain: "test", Subdomain: "test",
}) })
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
/* /*
* TEST domainDelete * 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) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(w.StatusCode, http.StatusUnauthorized)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(-1), nil) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(-1), nil)
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), nil) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), nil) result, w = session.JSONRequest("DELETE", "/host/domain/"+strconv.Itoa(domain)+"/web/"+strconv.Itoa(web), nil)
assertion.Equal(w.StatusCode, http.StatusNotFound) assertion.Equal(http.StatusNotFound, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
} }

View File

@ -3,7 +3,7 @@ package host
import ( import (
"net/http" "net/http"
"golang.org/x/net/context" "context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
liblog "dev.sum7.eu/sum7/warehost/lib/log" liblog "dev.sum7.eu/sum7/warehost/lib/log"
@ -12,19 +12,19 @@ import (
//ProfilHandler for api function to get host.Profil //ProfilHandler for api function to get host.Profil
func ProfilHandler(h libapi.Handle) libapi.Handle { 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) login := ctx.Value("login").(*libsystem.Login)
returnerr = &libapi.ErrorResult{Fields: []string{"session"}, Message: "no profil found"}
returndata = false
profil := &Profil{LoginID: login.ID} profil := &Profil{LoginID: login.ID}
dbconnection.Where("login = ?", login.ID).Find(profil) dbconnection.Where("login = ?", login.ID).Find(profil)
if profil.ID > 0 { if profil.ID > 0 {
ctx = context.WithValue(ctx, "profil", profil) ctx = context.WithValue(ctx, "profil", profil)
returndata, returnerr = h(ctx, w, r) r = r.WithContext(ctx)
h(w, r)
return return
} }
liblog.Log.Warn("no profil found") liblog.Log.Warn("no profil found")
return libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"session"}, Message: "no profil found"})
} }
} }

View File

@ -6,7 +6,6 @@ import (
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"goji.io" "goji.io"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
//libconfig "dev.sum7.eu/sum7/warehost/config" //libconfig "dev.sum7.eu/sum7/warehost/config"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
@ -25,106 +24,104 @@ func BindAPI(db *gorm.DB, router *goji.Mux, prefix string) {
dbconnection = db dbconnection = db
log = liblog.NewModulLog(MODULNAME) log = liblog.NewModulLog(MODULNAME)
router.HandleFuncC(pat.Get(prefix+"/involve"), libapi.SessionHandler(libsystem.LoginHandler(involve))) router.HandleFunc(pat.Get(prefix+"/involve"), libapi.SessionHandler(libsystem.LoginHandler(involve)))
router.HandleFuncC(pat.Post(prefix+"/website"), libapi.SessionHandler(libsystem.LoginHandler(websiteAdd))) router.HandleFunc(pat.Post(prefix+"/website"), libapi.SessionHandler(libsystem.LoginHandler(websiteAdd)))
router.HandleFuncC(pat.Patch(prefix+"/website/:websiteid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(websiteEdit)))) router.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.HandleFunc(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.Delete(prefix+"/website/:websiteid/page/:pageid"), libapi.SessionHandler(libsystem.LoginHandler(InvolveWebsiteHandler(pageDelete))))
} }
// Involve to get Website where loggend in user has privilegs // 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) login := ctx.Value("login").(*libsystem.Login)
returndata = false
logger := log.GetLog(r, "involve") logger := log.GetLog(r, "involve")
var involved []*Manager var involved []*Manager
dbconnection.Where("login = ?", login.ID).Preload("Website").Find(&involved) dbconnection.Where("login = ?", login.ID).Preload("Website").Find(&involved)
logger.Info("done") logger.Info("done")
returndata = involved libapi.JSONWrite(w, r, involved, nil)
return
} }
// WebsiteAdd to add a new website // 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) login := ctx.Value("login").(*libsystem.Login)
returndata = false
logger := log.GetLog(r, "websiteadd") logger := log.GetLog(r, "websiteadd")
tx := dbconnection.Begin() tx := dbconnection.Begin()
var websiteRequest Website var websiteRequest Website
returnerr = libapi.JSONDecoder(r.Body, &websiteRequest, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &websiteRequest)
if returnerr != nil { if returnerr != nil {
tx.Rollback() tx.Rollback()
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
website := &Website{Name: websiteRequest.Name} website := &Website{Name: websiteRequest.Name}
if err := tx.Create(website).Error; err != nil { if err := tx.Create(website).Error; err != nil {
tx.Rollback() tx.Rollback()
logger.Error("error during Website") logger.Error("error during Website")
returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"})
return return
} }
if err := tx.Create(&Manager{LoginID: login.ID, WebsiteID: website.ID}).Error; err != nil { if err := tx.Create(&Manager{LoginID: login.ID, WebsiteID: website.ID}).Error; err != nil {
tx.Rollback() tx.Rollback()
logger.Error("error during Manager") logger.Error("error during Manager")
returnerr = &libapi.ErrorResult{Message: "Internal Database Error"} libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Internal Database Error"})
return return
} }
tx.Commit() tx.Commit()
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }
// WebsiteEdit to edit website // WebsiteEdit to edit website
func websiteEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func websiteEdit(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "websiteedit") logger := log.GetLog(r, "websiteedit")
var websiteRequest Website var websiteRequest Website
returnerr = libapi.JSONDecoder(r.Body, &websiteRequest, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &websiteRequest)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
websiteRequest.ID = ctx.Value("websiteid").(int64) websiteRequest.ID = ctx.Value("websiteid").(int64)
if err := dbconnection.Save(websiteRequest).Error; err != nil { if err := dbconnection.Save(websiteRequest).Error; err != nil {
logger.Error("Database: during edit Website") 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }
// WebsiteDelete to delete website // WebsiteDelete to delete website
func websiteDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func websiteDelete(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "websitedelete") logger := log.GetLog(r, "websitedelete")
website := &Website{ website := &Website{
ID: ctx.Value("websiteid").(int64), ID: ctx.Value("websiteid").(int64),
} }
if err := dbconnection.Unscoped().Delete(website).Error; err != nil { if err := dbconnection.Unscoped().Delete(website).Error; err != nil {
logger.Error("database: during delete website") 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }

View File

@ -4,54 +4,50 @@ import (
"net/http" "net/http"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
) )
// DomainList to list domains // DomainList to list domains
func domainList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func domainList(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "domainlist") logger := log.GetLog(r, "domainlist")
var domain []*Domain var domain []*Domain
dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Preload("Domains").Find(&domain) dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Preload("Domains").Find(&domain)
logger.Info("done") logger.Info("done")
returndata = domain libapi.JSONWrite(w, r, domain, nil)
return
} }
// DomainAdd to add domain // DomainAdd to add domain
func domainAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func domainAdd(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "domainadd") logger := log.GetLog(r, "domainadd")
domain := &Domain{ domain := &Domain{
WebsiteID: ctx.Value("websiteid").(int64), WebsiteID: ctx.Value("websiteid").(int64),
Name: pat.Param(ctx, "domain"), Name: pat.Param(r, "domain"),
} }
if err := dbconnection.Create(domain).Error; err != nil { if err := dbconnection.Create(domain).Error; err != nil {
logger.Error("database: during create website domain: ", err) 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }
// DomainDelete to delete domain // DomainDelete to delete domain
func domainDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func domainDelete(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "domaindelete") logger := log.GetLog(r, "domaindelete")
domain := &Domain{ domain := &Domain{
WebsiteID: ctx.Value("websiteid").(int64), WebsiteID: ctx.Value("websiteid").(int64),
Name: pat.Param(ctx, "domain"), Name: pat.Param(r, "domain"),
} }
if err := dbconnection.Unscoped().Delete(domain).Error; err != nil { if err := dbconnection.Unscoped().Delete(domain).Error; err != nil {
logger.Error("database: during delete website Domain") 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }

View File

@ -5,40 +5,38 @@ import (
"strconv" "strconv"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
) )
// MenuTree to give the tree of a menu back // 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) { func menuTree(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "menutree") logger := log.GetLog(r, "menutree")
var menus []*Menu var menus []*Menu
dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Order("position").Find(&menus) dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Order("position").Find(&menus)
returndata = BuildMenuTree(menus)
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, BuildMenuTree(menus), nil)
} }
// MenuList give all menu entries of a website // MenuList give all menu entries of a website
func menuList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func menuList(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "menulist") logger := log.GetLog(r, "menulist")
var menus []*Menu var menus []*Menu
dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Order("position").Find(&menus) dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Order("position").Find(&menus)
returndata = menus
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, menus, nil)
} }
// MenuAdd to add a new menu entry // MenuAdd to add a new menu entry
func menuAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func menuAdd(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "menuadd") logger := log.GetLog(r, "menuadd")
var menuEntry Menu var menuEntry Menu
returnerr = libapi.JSONDecoder(r.Body, &menuEntry, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &menuEntry)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return 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 { if err := dbconnection.Create(&menuEntry).Error; err != nil {
logger.Error("database: during create menu") 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }
// MenuEdit to edit menu // MenuEdit to edit menu
func menuEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func menuEdit(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "menuedit") logger := log.GetLog(r, "menuedit")
var menuEntry Menu 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 { if err != nil {
returnerr = &libapi.ErrorResult{Fields: []string{"menuid"}, Message: "Not a valid menuid"}
logger.Warn("invalid loginid, no integer") logger.Warn("invalid loginid, no integer")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"menuid"}, Message: "Not a valid menuid"})
return return
} }
logger = logger.WithField("id", menuid) logger = logger.WithField("id", menuid)
returnerr = libapi.JSONDecoder(r.Body, &menuEntry, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &menuEntry)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
menuEntry.WebsiteID = ctx.Value("websiteid").(int64) 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 { if err := dbconnection.Save(menuEntry).Error; err != nil {
logger.Error("database: during edit website menu entry") 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }
// MenuDelete to delete menu entry // MenuDelete to delete menu entry
func menuDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func menuDelete(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "menudelete") 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 { if err != nil {
returnerr = &libapi.ErrorResult{Fields: []string{"menuid"}, Message: "Not a valid menuid"}
logger.Warn("invalid menuid, no integer") logger.Warn("invalid menuid, no integer")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"menuid"}, Message: "Not a valid menuid"})
return return
} }
logger = logger.WithField("id", menuid) 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 { if err := dbconnection.Unscoped().Delete(menu).Error; err != nil {
logger.Error("database: during delete website menu entry") 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }

View File

@ -5,29 +5,28 @@ import (
"strconv" "strconv"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
) )
// PageList give all pages of a website // PageList give all pages of a website
func pageList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func pageList(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "pagelist") logger := log.GetLog(r, "pagelist")
var pages []*Page var pages []*Page
dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Preload("Menu").Find(&pages) dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Preload("Menu").Find(&pages)
returndata = pages
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, pages, nil)
} }
// PageAdd to add a new page // PageAdd to add a new page
func pageAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func pageAdd(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "pageadd") logger := log.GetLog(r, "pageadd")
var page Page var page Page
returnerr = libapi.JSONDecoder(r.Body, &page, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &page)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return 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 { if err := dbconnection.Create(&page).Error; err != nil {
logger.Error("database: during create page") 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }
// PageEdit to edit page // PageEdit to edit page
func pageEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func pageEdit(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "pageedit") logger := log.GetLog(r, "pageedit")
var page Page 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 { if err != nil {
returnerr = &libapi.ErrorResult{Fields: []string{"pageid"}, Message: "Not a valid pageid"}
logger.Warn("invalid pageid, no integer") logger.Warn("invalid pageid, no integer")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"pageid"}, Message: "Not a valid pageid"})
return return
} }
logger = logger.WithField("id", pageid) logger = logger.WithField("id", pageid)
returnerr = libapi.JSONDecoder(r.Body, &page, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &page)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
page.WebsiteID = ctx.Value("websiteid").(int64) 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 { if err := dbconnection.Save(page).Error; err != nil {
logger.Error("database: during delete website page") 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }
// PageDelete to delete page // PageDelete to delete page
func pageDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func pageDelete(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "pagedelete") 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 { if err != nil {
returnerr = &libapi.ErrorResult{Fields: []string{"pageid"}, Message: "Not a valid pageid"}
logger.Warn("invalid pageid, no integer") logger.Warn("invalid pageid, no integer")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"pageid"}, Message: "Not a valid pageid"})
return return
} }
logger = logger.WithField("id", pageid) 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 { if err := dbconnection.Unscoped().Delete(page).Error; err != nil {
logger.Error("database: during delete website page") 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }

View File

@ -5,30 +5,28 @@ import (
"strconv" "strconv"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
) )
// PermissionList to add permissions // PermissionList to add permissions
func permissionList(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func permissionList(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "permissionlist") logger := log.GetLog(r, "permissionlist")
var involved []*Manager var involved []*Manager
dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Preload("Login").Find(&involved) dbconnection.Where("website = ?", ctx.Value("websiteid").(int64)).Preload("Login").Find(&involved)
logger.Info("done") logger.Info("done")
returndata = involved libapi.JSONWrite(w, r, involved, nil)
return
} }
// PermissionAdd to add permissions // PermissionAdd to add permissions
func permissionAdd(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func permissionAdd(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "permissionadd") 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 { if err != nil {
returnerr = &libapi.ErrorResult{Fields: []string{"loginid"}, Message: "Not a valid loginid"}
logger.Warn("invalid loginid, no integer") logger.Warn("invalid loginid, no integer")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"loginid"}, Message: "Not a valid loginid"})
return return
} }
manager := &Manager{ 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 { if err := dbconnection.Create(manager).Error; err != nil {
logger.Error("database: during create website permission") 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }
// PermissionDelete to delete permissions // PermissionDelete to delete permissions
func permissionDelete(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func permissionDelete(w http.ResponseWriter, r *http.Request) {
returndata = false ctx := r.Context()
logger := log.GetLog(r, "permissiondelete") 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 { if err != nil {
returnerr = &libapi.ErrorResult{Fields: []string{"loginid"}, Message: "Not a valid loginid"}
logger.Warn("invalid loginid, no integer") logger.Warn("invalid loginid, no integer")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"loginid"}, Message: "Not a valid loginid"})
return return
} }
manager := &Manager{ 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 { if err := dbconnection.Unscoped().Delete(manager).Error; err != nil {
logger.Error("database: during delete website permission") 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 return
} }
returndata = true
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, true, nil)
} }

View File

@ -4,8 +4,8 @@ import (
"net/http" "net/http"
"strconv" "strconv"
"context"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
liblog "dev.sum7.eu/sum7/warehost/lib/log" liblog "dev.sum7.eu/sum7/warehost/lib/log"
@ -14,24 +14,24 @@ import (
//InvolveWebsiteHandler for api function to Verifie User ist loggedin //InvolveWebsiteHandler for api function to Verifie User ist loggedin
func InvolveWebsiteHandler(h libapi.Handle) libapi.Handle { 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) 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 { if err == nil {
res := dbconnection.Where(map[string]int64{"website": id, "login": login.ID}).Find(&Manager{}) res := dbconnection.Where(map[string]int64{"website": id, "login": login.ID}).Find(&Manager{})
if !res.RecordNotFound() { if !res.RecordNotFound() {
ctx = context.WithValue(ctx, "websiteid", id) ctx = context.WithValue(ctx, "websiteid", id)
returndata, returnerr = h(ctx, w, r) r = r.WithContext(ctx)
h(w, r)
return 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") liblog.Log.Info("no Permissions")
return 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") liblog.Log.Warn("invalid websiteid, no integer")
return return
} }

View File

@ -9,7 +9,6 @@ import (
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"goji.io" "goji.io"
"goji.io/pat" "goji.io/pat"
"golang.org/x/net/context"
libapi "dev.sum7.eu/sum7/warehost/lib/api" libapi "dev.sum7.eu/sum7/warehost/lib/api"
liblog "dev.sum7.eu/sum7/warehost/lib/log" liblog "dev.sum7.eu/sum7/warehost/lib/log"
@ -28,36 +27,37 @@ func BindAPI(db *gorm.DB, router *goji.Mux, prefix string) {
dbconnection = db dbconnection = db
log = liblog.NewModulLog(MODULNAME) log = liblog.NewModulLog(MODULNAME)
router.HandleFuncC(pat.Get(prefix+"/status"), libapi.SessionHandler(status)) router.HandleFunc(pat.Get(prefix+"/status"), libapi.SessionHandler(status))
router.HandleFuncC(pat.Post(prefix+"/login"), libapi.SessionHandler(login)) router.HandleFunc(pat.Post(prefix+"/login"), libapi.SessionHandler(login))
router.HandleFuncC(pat.Get(prefix+"/logout"), libapi.SessionHandler(LoginHandler(logout))) router.HandleFunc(pat.Get(prefix+"/logout"), libapi.SessionHandler(LoginHandler(logout)))
router.HandleFuncC(pat.Post(prefix+"/password"), libapi.SessionHandler(LoginHandler(password))) router.HandleFunc(pat.Post(prefix+"/password"), libapi.SessionHandler(LoginHandler(password)))
router.HandleFuncC(pat.Get(prefix+"/delete"), libapi.SessionHandler(LoginHandler(delete))) router.HandleFunc(pat.Get(prefix+"/delete"), libapi.SessionHandler(LoginHandler(delete)))
router.HandleFuncC(pat.Get(prefix+"/invite"), libapi.SessionHandler(LoginHandler(inviteList))) router.HandleFunc(pat.Get(prefix+"/invite"), libapi.SessionHandler(LoginHandler(inviteList)))
router.HandleFuncC(pat.Post(prefix+"/invite"), libapi.SessionHandler(LoginHandler(inviteAdd))) router.HandleFunc(pat.Post(prefix+"/invite"), libapi.SessionHandler(LoginHandler(inviteAdd)))
router.HandleFuncC(pat.Get(prefix+"/user"), libapi.SessionHandler(LoginHandler(loginList))) router.HandleFunc(pat.Get(prefix+"/user"), libapi.SessionHandler(LoginHandler(loginList)))
router.HandleFuncC(pat.Post(prefix+"/user"), libapi.SessionHandler(LoginHandler(loginAdd))) router.HandleFunc(pat.Post(prefix+"/user"), libapi.SessionHandler(LoginHandler(loginAdd)))
router.HandleFuncC(pat.Patch(prefix+"/user/:id"), libapi.SessionHandler(LoginHandler(loginEdit))) router.HandleFunc(pat.Patch(prefix+"/user/:id"), libapi.SessionHandler(LoginHandler(loginEdit)))
router.HandleFuncC(pat.Delete(prefix+"/user/:id"), libapi.SessionHandler(LoginHandler(loginDelete))) router.HandleFunc(pat.Delete(prefix+"/user/:id"), libapi.SessionHandler(LoginHandler(loginDelete)))
router.HandleFuncC(pat.Get(prefix+"/invitor"), libapi.SessionHandler(LoginHandler(invitor))) router.HandleFunc(pat.Get(prefix+"/invitor"), libapi.SessionHandler(LoginHandler(invitor)))
router.HandleFuncC(pat.Patch(prefix+"/invitor"), libapi.SessionHandler(LoginHandler(invitorAdminToggle))) router.HandleFunc(pat.Patch(prefix+"/invitor"), libapi.SessionHandler(LoginHandler(invitorAdminToggle)))
} }
// Status to get Login and Server status // Status to get Login and Server status
func status(ctx context.Context, w http.ResponseWriter, r *http.Request) (returndata interface{}, returnerr *libapi.ErrorResult) { func status(w http.ResponseWriter, r *http.Request) {
returndata = false
logger := log.GetLog(r, "status") logger := log.GetLog(r, "status")
var result int64 var result int64
dbconnection.Model(&Login{}).Count(&result) dbconnection.Model(&Login{}).Count(&result)
if result > 0 { if result > 0 {
returndata = true libapi.JSONWrite(w, r, true, nil)
return
} }
logger.Info("done") logger.Info("done")
return libapi.JSONWrite(w, r, false, nil)
} }
// Logout current user // 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) sess := ctx.Value("session").(libsession.Session)
libsession.SessionDestroy(w, r) libsession.SessionDestroy(w, r)
logger := log.GetLog(r, "logout") 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("login")
sess.Delete("profil") sess.Delete("profil")
logger.Info("done") logger.Info("done")
returndata = true libapi.JSONWrite(w, r, true, nil)
return
} }
// Login of system // 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) sess := ctx.Value("session").(libsession.Session)
returndata = false
logger := log.GetLog(r, "login") logger := log.GetLog(r, "login")
var requestlogin RequestLogin var requestlogin RequestLogin
returnerr = libapi.JSONDecoder(r.Body, &requestlogin, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &requestlogin)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
@ -88,104 +87,103 @@ func login(ctx context.Context, w http.ResponseWriter, r *http.Request) (returnd
dbconnection.Where("mail = ?", requestlogin.Username).First(&login) dbconnection.Where("mail = ?", requestlogin.Username).First(&login)
if login.ID <= 0 { if login.ID <= 0 {
logger.Warn("user not found") 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 return
} }
if login.Active { if login.Active {
output, _ := libpassword.Validate(login.Password, requestlogin.Password) output, _ := libpassword.Validate(login.Password, requestlogin.Password)
if output { if output {
returndata = true
dbconnection.Model(&login).Update("LastLoginAt", time.Now()) dbconnection.Model(&login).Update("LastLoginAt", time.Now())
sess.Set("login", &login) sess.Set("login", &login)
logger.Info("done") logger.Info("done")
} else { libapi.JSONWrite(w, r, true, nil)
return
}
logger.Warn("wrong password") logger.Warn("wrong password")
returnerr = &libapi.ErrorResult{Fields: []string{"password"}, Message: "Wrong Password"} libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"password"}, Message: "Wrong Password"})
return
} }
} else {
logger.Warn("not active") logger.Warn("not active")
returnerr = &libapi.ErrorResult{Fields: []string{"active"}, Message: "Not a active User"} libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"active"}, Message: "Not a active User"})
}
return return
} }
//Password to change the password //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) sess := ctx.Value("session").(libsession.Session)
login := ctx.Value("login").(*Login) login := ctx.Value("login").(*Login)
returndata = false
logger := log.GetLog(r, "password") logger := log.GetLog(r, "password")
var changePasswordRequest ChangePasswordRequest var changePasswordRequest ChangePasswordRequest
returnerr = libapi.JSONDecoder(r.Body, &changePasswordRequest, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &changePasswordRequest)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
output, _ := libpassword.Validate(login.Password, changePasswordRequest.CurrentPassword) output, _ := libpassword.Validate(login.Password, changePasswordRequest.CurrentPassword)
if !output { if !output {
logger.Warn("wrong current password") 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 return
} }
if len(changePasswordRequest.NewPassword) < MINPASSWORDLENTH { if len(changePasswordRequest.NewPassword) < MINPASSWORDLENTH {
logger.Warn("wrong new password") 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 return
} }
login.Password = libpassword.NewHash(changePasswordRequest.NewPassword) login.Password = libpassword.NewHash(changePasswordRequest.NewPassword)
if err := dbconnection.Save(login).Error; err != nil { if err := dbconnection.Save(login).Error; err != nil {
logger.Warn("error save new password to database") 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 return
} }
sess.Set("login", login) sess.Set("login", login)
logger.Info("done") logger.Info("done")
returndata = true libapi.JSONWrite(w, r, true, nil)
return
} }
//Delete of login on warehost //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) sess := ctx.Value("session").(libsession.Session)
login := ctx.Value("login").(*Login) login := ctx.Value("login").(*Login)
returndata = false
logger := log.GetLog(r, "delete") logger := log.GetLog(r, "delete")
sess.Delete("login") sess.Delete("login")
if err := dbconnection.Unscoped().Delete(login).Error; err != nil { if err := dbconnection.Unscoped().Delete(login).Error; err != nil {
logger.Warn("error detete login") logger.Warn("error detete login")
returnerr = &libapi.ErrorResult{Message: "Error delete login"} libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error delete login"})
return return
} }
logger.Warn("done") logger.Warn("done")
returndata = true libapi.JSONWrite(w, r, true, nil)
return
} }
// InviteList list all of your invites // 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) login := ctx.Value("login").(*Login)
returndata = false
logger := log.GetLog(r, "invitelist") logger := log.GetLog(r, "invitelist")
if err := dbconnection.Model(login).Preload("Invites.Invited").First(login).Error; err != nil { if err := dbconnection.Model(login).Preload("Invites.Invited").First(login).Error; err != nil {
logger.Warn("error load own invites") 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 return
} }
logger.Info("done") logger.Info("done")
returndata = login.Invites libapi.JSONWrite(w, r, login.Invites, nil)
return
} }
// InviteAdd invite a new user to warehost // 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) login := ctx.Value("login").(*Login)
returndata = false
logger := log.GetLog(r, "inviteadd") logger := log.GetLog(r, "inviteadd")
var newLogin RequestLogin var newLogin RequestLogin
returnerr = libapi.JSONDecoder(r.Body, &newLogin, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &newLogin)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return 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 { if err := dbconnection.Create(invite).Error; err != nil {
logger.Warn("error create invite") logger.Warn("error create invite")
returnerr = &libapi.ErrorResult{Message: "Username exists already"} libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Username exists already"})
return return
} }
logger.Info("done") logger.Info("done")
returndata = true libapi.JSONWrite(w, r, true, nil)
return
} }
// LoginList list all users in system // 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) login := ctx.Value("login").(*Login)
returndata = false
logger := log.GetLog(r, "loginlist") logger := log.GetLog(r, "loginlist")
var logins []Login var logins []Login
selectfield := "ID, mail" 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 { if err := dbconnection.Select(selectfield).Find(&logins).Error; err != nil {
logger.Warn("sql list login") 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 return
} }
logger.Info("done") logger.Info("done")
returndata = logins libapi.JSONWrite(w, r, logins, nil)
return
} }
// LoginAdd add a new Login // 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) login := ctx.Value("login").(*Login)
returndata = false
logger := log.GetLog(r, "loginadd") logger := log.GetLog(r, "loginadd")
if !login.Superadmin { if !login.Superadmin {
logger.Error("no 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 return
} }
var newLogin RequestLogin var newLogin RequestLogin
returnerr = libapi.JSONDecoder(r.Body, &newLogin, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &newLogin)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return 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 { if err := dbconnection.Create(loginObj).Error; err != nil {
logger.Warn("error create login") logger.Warn("error create login")
returnerr = &libapi.ErrorResult{Message: "Username exists already"} libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Username exists already"})
return return
} }
logger.Info("done") logger.Info("done")
returndata = true libapi.JSONWrite(w, r, true, nil)
return
} }
// LoginEdit edit a login by invite or superadmin // 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) login := ctx.Value("login").(*Login)
returndata = false
logger := log.GetLog(r, "loginedit") 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 { if err != nil {
returnerr = &libapi.ErrorResult{Message: "Error invalid input"}
logger.Warn("invalid userinput, no integer") logger.Warn("invalid userinput, no integer")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error invalid input"})
return return
} }
logger = logger.WithField("id", id) logger = logger.WithField("id", id)
var invitedLogin = Login{ID: id} var invitedLogin = Login{ID: id}
var changeLogin RequestLogin var changeLogin RequestLogin
returnerr = libapi.JSONDecoder(r.Body, &changeLogin, w, logger) returnerr := libapi.JSONDecoder(w, r, logger, &changeLogin)
if returnerr != nil { if returnerr != nil {
libapi.JSONWrite(w, r, false, returnerr)
return return
} }
@ -282,7 +279,7 @@ func loginEdit(ctx context.Context, w http.ResponseWriter, r *http.Request) (ret
invite := invitedLogin.GetInvitedby(dbconnection) invite := invitedLogin.GetInvitedby(dbconnection)
if !login.Superadmin && !invite.Admin && invitedLogin.CreateAt.Before(invitedLogin.LastLoginAt) { if !login.Superadmin && !invite.Admin && invitedLogin.CreateAt.Before(invitedLogin.LastLoginAt) {
logger.Warn("no permission") 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 return
} }
if len(changeLogin.Password) > 0 { 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 { if err := dbconnection.Save(invitedLogin).Error; err != nil {
logger.Warn("sql edit login") 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 return
} }
logger.Info("done") logger.Info("done")
returndata = true libapi.JSONWrite(w, r, true, nil)
return
} }
// LoginDelete delete a login by invite or superadmin // 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) login := ctx.Value("login").(*Login)
returndata = false
logger := log.GetLog(r, "logindelete") 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 { if err != nil {
returnerr = &libapi.ErrorResult{Message: "Error invalid input"}
logger.Warn("invalid userinput, no integer") logger.Warn("invalid userinput, no integer")
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Message: "Error invalid input"})
return return
} }
logger = logger.WithField("id", id) 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) invite := invitedLogin.GetInvitedby(dbconnection)
if !login.Superadmin && !invite.Admin && invitedLogin.CreateAt.Before(invitedLogin.LastLoginAt) { if !login.Superadmin && !invite.Admin && invitedLogin.CreateAt.Before(invitedLogin.LastLoginAt) {
logger.Warn("no permission") 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 return
} }
if err := dbconnection.Unscoped().Delete(invitedLogin).Error; err != nil { if err := dbconnection.Unscoped().Delete(invitedLogin).Error; err != nil {
logger.Warn("sql detete login") 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 return
} }
logger.Info("done") logger.Info("done")
returndata = true libapi.JSONWrite(w, r, true, nil)
return
} }
// Invitor get Invite of current login // 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) login := ctx.Value("login").(*Login)
returndata = false
logger := log.GetLog(r, "invitor") logger := log.GetLog(r, "invitor")
invite := login.GetInvitedby(dbconnection) invite := login.GetInvitedby(dbconnection)
logger.Info("done") logger.Info("done")
returndata = invite libapi.JSONWrite(w, r, invite, nil)
return
} }
// InvitorAdminToggle toggle admin of current login // 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) login := ctx.Value("login").(*Login)
returndata = false
logger := log.GetLog(r, "invitoradmintoggle") logger := log.GetLog(r, "invitoradmintoggle")
invite := login.GetInvitedby(dbconnection) invite := login.GetInvitedby(dbconnection)
invite.Admin = !invite.Admin invite.Admin = !invite.Admin
dbconnection.Model(invite).Save(&invite) dbconnection.Model(invite).Save(&invite)
logger.Info("done") logger.Info("done")
returndata = true libapi.JSONWrite(w, r, true, nil)
return
} }

View File

@ -11,8 +11,8 @@ import (
func loginTest(session *test.Request, assertion *assert.Assertions) { func loginTest(session *test.Request, assertion *assert.Assertions) {
result, w := session.JSONRequest("POST", "/login", RequestLogin{Username: "root", Password: "root"}) result, w := session.JSONRequest("POST", "/login", RequestLogin{Username: "root", Password: "root"})
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
} }
func TestAPI(t *testing.T) { func TestAPI(t *testing.T) {
@ -31,25 +31,25 @@ func TestAPI(t *testing.T) {
* TEST status * TEST status
*/ */
result, w := session.JSONRequest("GET", "/status", nil) result, w := session.JSONRequest("GET", "/status", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Nil(result.Error) assertion.Nil(result.Error)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
/* /*
* TEST login * TEST login
*/ */
result, w = session.JSONRequest("POST", "/login", RequestLogin{Username: "root", Password: "root2"}) result, w = session.JSONRequest("POST", "/login", RequestLogin{Username: "root", Password: "root2"})
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
assertion.Equal(result.Error.Fields[0], "password") assertion.Equal("password", result.Error.Fields[0])
result, w = session.JSONRequest("POST", "/login", RequestLogin{Username: "root2", Password: "root"}) result, w = session.JSONRequest("POST", "/login", RequestLogin{Username: "root2", Password: "root"})
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
assertion.Equal(result.Error.Fields[0], "username") assertion.Equal("username", result.Error.Fields[0])
result, w = session.JSONRequest("POST", "/login", []byte{2, 3}) result, w = session.JSONRequest("POST", "/login", []byte{2, 3})
assertion.Equal(w.StatusCode, http.StatusBadRequest) assertion.Equal(http.StatusBadRequest, w.StatusCode)
//login before //login before
loginTest(session, assertion) loginTest(session, assertion)
@ -58,71 +58,71 @@ func TestAPI(t *testing.T) {
* TEST logout * TEST logout
*/ */
result, w = session.JSONRequest("GET", "/logout", nil) result, w = session.JSONRequest("GET", "/logout", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
// Test if crash on if not login in // Test if crash on if not login in
result, w = session.JSONRequest("GET", "/logout", nil) result, w = session.JSONRequest("GET", "/logout", nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
/* /*
* TEST password * TEST password
*/ */
session.Clean() session.Clean()
result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root", NewPassword: "root-bug"}) result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root", NewPassword: "root-bug"})
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
//login before //login before
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("POST", "/password", []byte{2, 3}) 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"}) result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root-wrong", NewPassword: "root-bug"})
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
assertion.Equal(result.Error.Fields[0], "currentpassword") assertion.Equal("currentpassword", result.Error.Fields[0])
result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root", NewPassword: ""}) result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root", NewPassword: ""})
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
assertion.Equal(result.Error.Fields[0], "newpassword") assertion.Equal("newpassword", result.Error.Fields[0])
result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root", NewPassword: "root-tmp"}) result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root", NewPassword: "root-tmp"})
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root-tmp", NewPassword: "root"}) result, w = session.JSONRequest("POST", "/password", ChangePasswordRequest{CurrentPassword: "root-tmp", NewPassword: "root"})
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
assertion.Equal(result.Data, true) assertion.Equal(true, result.Data)
/* /*
* TEST inviteList * TEST inviteList
*/ */
session.Clean() session.Clean()
result, w = session.JSONRequest("GET", "/invite", nil) result, w = session.JSONRequest("GET", "/invite", nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
//login before //login before
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("GET", "/invite", nil) result, w = session.JSONRequest("GET", "/invite", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
/* /*
* TEST loginList * TEST loginList
*/ */
session.Clean() session.Clean()
result, w = session.JSONRequest("GET", "/user", nil) result, w = session.JSONRequest("GET", "/user", nil)
assertion.Equal(w.StatusCode, http.StatusUnauthorized) assertion.Equal(http.StatusUnauthorized, w.StatusCode)
assertion.Equal(result.Data, false) assertion.Equal(false, result.Data)
//login before //login before
loginTest(session, assertion) loginTest(session, assertion)
result, w = session.JSONRequest("GET", "/user", nil) result, w = session.JSONRequest("GET", "/user", nil)
assertion.Equal(w.StatusCode, http.StatusOK) assertion.Equal(http.StatusOK, w.StatusCode)
} }

View File

@ -12,24 +12,25 @@ import (
//LoginHandler for api function to Verifie User ist loggedin //LoginHandler for api function to Verifie User ist loggedin
func LoginHandler(h libapi.Handle) libapi.Handle { 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) sess := ctx.Value("session").(libsession.Session)
returndata = false
if login := sess.Get("login"); login != nil { if login := sess.Get("login"); login != nil {
if loginObj := login.(*Login); loginObj.Active { if loginObj := login.(*Login); loginObj.Active {
ctx = context.WithValue(ctx, "login", loginObj) ctx = context.WithValue(ctx, "login", loginObj)
returndata, returnerr = h(ctx, w, r) r = r.WithContext(ctx)
h(w, r)
return return
} }
returnerr = &libapi.ErrorResult{Fields: []string{"session"}, Message: "Not active user"}
w.WriteHeader(http.StatusUnauthorized)
liblog.Log.Warn("user not active") 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 return
} }
w.WriteHeader(http.StatusUnauthorized)
returnerr = &libapi.ErrorResult{Fields: []string{"session"}, Message: "Not logged in"}
liblog.Log.Warn("not loggedin") liblog.Log.Warn("not loggedin")
w.WriteHeader(http.StatusUnauthorized)
libapi.JSONWrite(w, r, false, &libapi.ErrorResult{Fields: []string{"session"}, Message: "Not logged in"})
return return
} }
} }

View File

@ -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) { func (r *Request) JSONRequest(method string, url string, body interface{}) (jsonResult libapi.JSONResult, res *http.Response) {
jsonObj, _ := json.Marshal(body) jsonObj, _ := json.Marshal(body)
req, _ := http.NewRequest(method, url, bytes.NewReader(jsonObj)) req, _ := http.NewRequest(method, url, bytes.NewReader(jsonObj))
req.Header.Set("Content-Type", "application/json")
for _, c := range r.cookies { for _, c := range r.cookies {
req.AddCookie(c) req.AddCookie(c)
} }
@ -73,7 +74,7 @@ func (r *Request) JSONRequest(method string, url string, body interface{}) (json
return return
} }
// CleanSession to clean the current session // Clean to clean the current session
func (r *Request) Clean() { func (r *Request) Clean() {
r.cookies = nil r.cookies = nil
} }