From dc8de8b4b9296faae85120263a088973574f07a6 Mon Sep 17 00:00:00 2001 From: Jimmy Date: Sun, 13 Mar 2022 07:06:39 +1300 Subject: [PATCH] Debugging --- app.go | 73 ++++++------- app/seed_test.go | 4 +- controllers/controller.go | 54 +++++----- controllers/post.go | 104 +++++++++---------- controllers/session.go | 122 +++++++++++----------- controllers/session_test.go | 164 ++++++++++++++--------------- controllers/static.go | 44 ++++---- controllers/user.go | 150 +++++++++++++-------------- go.mod | 3 + misc/auth/auth.go | 98 +++++++++--------- misc/auth/auth_test.go | 194 +++++++++++++++++------------------ misc/b64/b64.go | 18 ++-- misc/config/config.go | 96 ++++++++--------- misc/config/config_test.go | 10 +- misc/cookie/cookie.go | 31 ------ misc/cookie/cookie_test.go | 39 ------- misc/helpers/helpers.go | 92 ++++++++--------- misc/helpers/helpers_test.go | 56 +++++----- misc/helpers/test.go | 64 ++++++------ misc/rand/rand.go | 32 +++--- misc/test/seed.go | 72 ++++++------- models/group.go | 82 +++++++-------- models/group_test.go | 40 ++++---- models/model.go | 22 ++-- models/model_test.go | 31 +++--- models/post.go | 54 +++++----- models/session.go | 2 +- models/session_test.go | 90 ++++++++-------- models/user.go | 136 ++++++++++++------------ runner.conf | 14 --- tmp/build-errors.log | 1 + 31 files changed, 952 insertions(+), 1040 deletions(-) create mode 100644 go.mod delete mode 100644 misc/cookie/cookie.go delete mode 100644 misc/cookie/cookie_test.go delete mode 100644 runner.conf create mode 100644 tmp/build-errors.log diff --git a/app.go b/app.go index 00c0055..f5abddd 100644 --- a/app.go +++ b/app.go @@ -2,56 +2,49 @@ package main import ( "fmt" - "log" - "net/http" - - c "git.1248.nz/1248/Otfe/controllers" - a "git.1248.nz/1248/Otfe/misc/auth" - "git.1248.nz/1248/Otfe/misc/helpers" - "github.com/husobee/vestigo" ) func main() { fmt.Println("Starting") - log.Fatal(http.ListenAndServe(":8080", router())) + //log.Fatal(http.ListenAndServe(":8080", router())) } -func router() *vestigo.Router { - router := vestigo.NewRouter() +// func router() *vestigo.Router { +// router := vestigo.NewRouter() - var static c.Static - router.Get("/", a.User(static.Home)) +// var static c.Static +// router.Get("/", a.User(static.Home)) - router.Get("/public/*", http.FileServer( - http.Dir(helpers.GetAssets())).ServeHTTP) +// router.Get("/public/*", http.FileServer( +// http.Dir(helpers.GetAssets())).ServeHTTP) - //User routes - var user c.User - router.Get("/user", c.User{}.Index) - router.Get("/user/:username", a.Perm(user.Show, user.ShowSelf, - "user.show")) - router.Get("/user/new", user.New) - router.Post("/user/new", user.Create) - router.Get("/user/:username/edit", user.Edit) - router.Post("/user/:username/edit", user.Update) - router.Post("/user/:username/delete", user.Delete) - router.Get("/register", user.New) +// //User routes +// var user c.User +// router.Get("/user", c.User{}.Index) +// router.Get("/user/:username", a.Perm(user.Show, user.ShowSelf, +// "user.show")) +// router.Get("/user/new", user.New) +// router.Post("/user/new", user.Create) +// router.Get("/user/:username/edit", user.Edit) +// router.Post("/user/:username/edit", user.Update) +// router.Post("/user/:username/delete", user.Delete) +// router.Get("/register", user.New) - //Session routes - var session c.Session - router.Get("/login", session.New) - router.Post("/login", session.Create) - router.Post("/logout", session.Delete) +// //Session routes +// var session c.Session +// router.Get("/login", session.New) +// router.Post("/login", session.Create) +// router.Post("/logout", session.Delete) - //Post routes - router.Get("/post", c.Post{}.Index) - router.Get("/user/:id", c.Post{}.Show) - router.Get("/post/new", c.Post{}.New) - router.Post("/post/new", c.Post{}.Create) - router.Get("/post/:id/edit", c.Post{}.Edit) - router.Post("/post/:id/edit", c.Post{}.Update) - router.Post("/post/:id/delete", c.Post{}.Delete) +// //Post routes +// router.Get("/post", c.Post{}.Index) +// router.Get("/user/:id", c.Post{}.Show) +// router.Get("/post/new", c.Post{}.New) +// router.Post("/post/new", c.Post{}.Create) +// router.Get("/post/:id/edit", c.Post{}.Edit) +// router.Post("/post/:id/edit", c.Post{}.Update) +// router.Post("/post/:id/delete", c.Post{}.Delete) - return router -} +// return router +// } diff --git a/app/seed_test.go b/app/seed_test.go index 9a11154..3e32d89 100644 --- a/app/seed_test.go +++ b/app/seed_test.go @@ -3,8 +3,8 @@ package main import ( "testing" - "git.1248.nz/1248/Otfe/misc/helpers" - "git.1248.nz/1248/Otfe/models" + "git.technical.kiwi/go/otfe/misc/helpers" + "git.technical.kiwi/go/otfe/models" "github.com/globalsign/mgo/bson" ) diff --git a/controllers/controller.go b/controllers/controller.go index b273c2f..82ccd7b 100644 --- a/controllers/controller.go +++ b/controllers/controller.go @@ -1,33 +1,33 @@ -package controllers +// package controllers -import ( - "html/template" - "net/http" +// import ( +// "html/template" +// "net/http" - "git.1248.nz/1248/Otfe/misc/helpers" - "github.com/globalsign/mgo/bson" -) +// "git.technical.kiwi/go/otfe/misc/helpers" +// "github.com/globalsign/mgo/bson" +// ) -/*type Controller interface { - Index(w http.ResponseWriter, r *http.Request) - Show(w http.ResponseWriter, r *http.Request) - New(w http.ResponseWriter, r *http.Request) - Create(w http.ResponseWriter, r *http.Request) - Edit(w http.ResponseWriter, r *http.Request) - Update(w http.ResponseWriter, r *http.Request) - Delete(w http.ResponseWriter, r *http.Request) -}*/ +// /*type Controller interface { +// Index(w http.ResponseWriter, r *http.Request) +// Show(w http.ResponseWriter, r *http.Request) +// New(w http.ResponseWriter, r *http.Request) +// Create(w http.ResponseWriter, r *http.Request) +// Edit(w http.ResponseWriter, r *http.Request) +// Update(w http.ResponseWriter, r *http.Request) +// Delete(w http.ResponseWriter, r *http.Request) +// }*/ -var funcMap = template.FuncMap{ - "getId": func(id bson.ObjectId) string { - return "1" - }, -} +// var funcMap = template.FuncMap{ +// "getId": func(id bson.ObjectId) string { +// return "1" +// }, +// } -func t(w http.ResponseWriter, data interface{}, layout string) { - views := helpers.GetRootDir() + "/views/" - tmpl := template.Must(template.New("layout").Funcs(funcMap). - ParseFiles(views+"/layouts/layout.gtpl", views+"/layouts/header.gtpl", views+"/layouts/footer.gtpl", views+"/layouts/nav.gtpl", views+layout)) - tmpl.ExecuteTemplate(w, "layout", data) +// func t(w http.ResponseWriter, data interface{}, layout string) { +// views := helpers.GetRootDir() + "/views/" +// tmpl := template.Must(template.New("layout").Funcs(funcMap). +// ParseFiles(views+"/layouts/layout.gtpl", views+"/layouts/header.gtpl", views+"/layouts/footer.gtpl", views+"/layouts/nav.gtpl", views+layout)) +// tmpl.ExecuteTemplate(w, "layout", data) -} +// } diff --git a/controllers/post.go b/controllers/post.go index 695b943..2d61c59 100644 --- a/controllers/post.go +++ b/controllers/post.go @@ -1,66 +1,66 @@ -package controllers +// package controllers -import ( - "fmt" - "net/http" +// import ( +// "fmt" +// "net/http" - "git.1248.nz/1248/Otfe/misc/helpers" - "git.1248.nz/1248/Otfe/models" - "github.com/husobee/vestigo" -) +// "git.technical.kiwi/go/otfe/misc/helpers" +// "git.technical.kiwi/go/otfe/models" +// "github.com/husobee/vestigo" +// ) -//User handlers -type Post struct { - Title string -} +// //User handlers +// type Post struct { +// Title string +// } -//Index of posts -func (p Post) Index(w http.ResponseWriter, r *http.Request) { - p.Title = "Posts" - t(w, p, "/post/posts.gtpl") -} +// //Index of posts +// func (p Post) Index(w http.ResponseWriter, r *http.Request) { +// p.Title = "Posts" +// t(w, p, "/post/posts.gtpl") +// } -//Show given user -func (p Post) Show(w http.ResponseWriter, r *http.Request) { - t(w, p, "/post/post.gtpl") -} +// //Show given user +// func (p Post) Show(w http.ResponseWriter, r *http.Request) { +// t(w, p, "/post/post.gtpl") +// } -//New user form -func (p Post) New(w http.ResponseWriter, r *http.Request) { - t(w, p, "/post/new.gtpl") -} +// //New user form +// func (p Post) New(w http.ResponseWriter, r *http.Request) { +// t(w, p, "/post/new.gtpl") +// } -//Create new a user -func (p Post) Create(w http.ResponseWriter, r *http.Request) { - r.ParseForm() - var user models.User - var err error - user.Username = r.Form.Get("username") - user.Email = r.Form.Get("email") - user.Password, err = helpers.HashPassword(r.Form.Get("password")) - helpers.CheckError(err) - user.Create() - http.Redirect(w, r, "/user/"+user.Username, http.StatusFound) +// //Create new a user +// func (p Post) Create(w http.ResponseWriter, r *http.Request) { +// r.ParseForm() +// var user models.User +// var err error +// user.Username = r.Form.Get("username") +// user.Email = r.Form.Get("email") +// user.Password, err = helpers.HashPassword(r.Form.Get("password")) +// helpers.CheckError(err) +// user.Create() +// http.Redirect(w, r, "/user/"+user.Username, http.StatusFound) -} +// } -//Edit form -func (p Post) Edit(w http.ResponseWriter, r *http.Request) { - var data userData - data.User.Read("username", vestigo.Param(r, "username")) +// //Edit form +// func (p Post) Edit(w http.ResponseWriter, r *http.Request) { +// var data userData +// data.User.Read("username", vestigo.Param(r, "username")) -} +// } -//Update user -func (p Post) Update(w http.ResponseWriter, r *http.Request) { +// //Update user +// func (p Post) Update(w http.ResponseWriter, r *http.Request) { -} +// } -//Delete user -func (p Post) Delete(w http.ResponseWriter, r *http.Request) { - fmt.Println("Deleting " + vestigo.Param(r, "username")) - var user models.User - user.Delete("username", vestigo.Param(r, "username")) - http.Redirect(w, r, "/user", http.StatusFound) +// //Delete user +// func (p Post) Delete(w http.ResponseWriter, r *http.Request) { +// fmt.Println("Deleting " + vestigo.Param(r, "username")) +// var user models.User +// user.Delete("username", vestigo.Param(r, "username")) +// http.Redirect(w, r, "/user", http.StatusFound) -} +// } diff --git a/controllers/session.go b/controllers/session.go index 88f1c5f..58bdae3 100644 --- a/controllers/session.go +++ b/controllers/session.go @@ -1,72 +1,72 @@ -package controllers +// package controllers -import ( - "errors" - "net/http" +// import ( +// "errors" +// "net/http" - "git.1248.nz/1248/Otfe/misc/cookie" - "git.1248.nz/1248/Otfe/misc/helpers" - "git.1248.nz/1248/Otfe/misc/rand" - "git.1248.nz/1248/Otfe/models" -) +// "git.technical.kiwi/go/otfe/misc/cookie" +// "git.technical.kiwi/go/otfe/misc/helpers" +// "git.technical.kiwi/go/otfe/misc/rand" +// "git.technical.kiwi/go/otfe/models" +// ) -//Session controllers -type Session struct{} +// //Session controllers +// type Session struct{} -type pageData struct { - Title string - Err string - User models.User -} +// type pageData struct { +// Title string +// Err string +// User models.User +// } -//New login form -func (s *Session) New(w http.ResponseWriter, r *http.Request) { - var err error - data := pageData{Title: "Login"} - data.Err, err = cookie.Read(r, "error") - if err == nil { - cookie.Delete(w, "error") - } - t(w, data, "/static/login.gtpl") -} +// //New login form +// func (s *Session) New(w http.ResponseWriter, r *http.Request) { +// var err error +// data := pageData{Title: "Login"} +// data.Err, err = cookie.Read(r, "error") +// if err == nil { +// cookie.Delete(w, "error") +// } +// t(w, data, "/static/login.gtpl") +// } -//Create a new session -func (s *Session) Create(w http.ResponseWriter, r *http.Request) { - r.ParseForm() - //Get email and password and check they are not empty - email := r.Form.Get("email") - password := r.Form.Get("password") +// //Create a new session +// func (s *Session) Create(w http.ResponseWriter, r *http.Request) { +// r.ParseForm() +// //Get email and password and check they are not empty +// email := r.Form.Get("email") +// password := r.Form.Get("password") - //Check if user exists - var user models.User +// //Check if user exists +// var user models.User - //Check password is correct - if user.Read("email", email) == nil && - helpers.CheckPasswordHash(password, user.Password) == nil { - id, _ := rand.B64String(32) - sess := models.Session{ID: id, UserID: user.ID} - sess.Create() - cookie.Create(w, "session", sess.ID) - http.Redirect(w, r, "/", http.StatusFound) - } else { - loginFail(w, r, errors.New("Email or password incorrect")) - } -} +// //Check password is correct +// if user.Read("email", email) == nil && +// helpers.CheckPasswordHash(password, user.Password) == nil { +// id, _ := rand.B64String(32) +// sess := models.Session{ID: id, UserID: user.ID} +// sess.Create() +// cookie.Create(w, "session", sess.ID) +// http.Redirect(w, r, "/", http.StatusFound) +// } else { +// loginFail(w, r, errors.New("Email or password incorrect")) +// } +// } -//Delete session -func (s *Session) Delete(w http.ResponseWriter, r *http.Request) { - id, err := cookie.Read(r, "session") - //Check user is logged in - if err == nil { - cookie.Delete(w, "session") - var session models.Session - session.Delete(id) - http.Redirect(w, r, "/", http.StatusFound) - } +// //Delete session +// func (s *Session) Delete(w http.ResponseWriter, r *http.Request) { +// id, err := cookie.Read(r, "session") +// //Check user is logged in +// if err == nil { +// cookie.Delete(w, "session") +// var session models.Session +// session.Delete(id) +// http.Redirect(w, r, "/", http.StatusFound) +// } -} +// } -func loginFail(w http.ResponseWriter, r *http.Request, err error) { - cookie.Create(w, "error", err.Error()) - http.Redirect(w, r, "/login", http.StatusFound) -} +// func loginFail(w http.ResponseWriter, r *http.Request, err error) { +// cookie.Create(w, "error", err.Error()) +// http.Redirect(w, r, "/login", http.StatusFound) +// } diff --git a/controllers/session_test.go b/controllers/session_test.go index 913a61a..95da5a6 100644 --- a/controllers/session_test.go +++ b/controllers/session_test.go @@ -1,102 +1,102 @@ -package controllers_test +// package controllers_test -import ( - "net/http" - "net/http/httptest" - "net/url" - "strings" - "testing" +// import ( +// "net/http" +// "net/http/httptest" +// "net/url" +// "strings" +// "testing" - "git.1248.nz/1248/Otfe/controllers" - "git.1248.nz/1248/Otfe/misc/b64" - "git.1248.nz/1248/Otfe/misc/helpers" - "git.1248.nz/1248/Otfe/models" -) +// "git.technical.kiwi/go/otfe/controllers" +// "git.technical.kiwi/go/otfe/misc/b64" +// "git.technical.kiwi/go/otfe/misc/helpers" +// "git.technical.kiwi/go/otfe/models" +// ) -func TestSessionNew(t *testing.T) { - var s controllers.Session - handler := http.HandlerFunc(s.New) - req, err := http.NewRequest("GET", "/login", nil) - w := httptest.NewRecorder() - if err != nil { - t.Fatal(err) - } - handler(w, req) - body := w.Body.String() - if !strings.Contains(body, "Login") { - t.Fail() - } -} +// func TestSessionNew(t *testing.T) { +// var s controllers.Session +// handler := http.HandlerFunc(s.New) +// req, err := http.NewRequest("GET", "/login", nil) +// w := httptest.NewRecorder() +// if err != nil { +// t.Fatal(err) +// } +// handler(w, req) +// body := w.Body.String() +// if !strings.Contains(body, "Login") { +// t.Fail() +// } +// } -func TestSessionCreate(t *testing.T) { - //Create test user +// func TestSessionCreate(t *testing.T) { +// //Create test user - var s controllers.Session - handler := http.HandlerFunc(s.Create) - req, w := setup(t, "POST", "/login") +// var s controllers.Session +// handler := http.HandlerFunc(s.Create) +// req, w := setup(t, "POST", "/login") - addTofForm(req, "email=test", "password=test") - handler(w, req) +// addTofForm(req, "email=test", "password=test") +// handler(w, req) - errorMessage := getCookie("error", w.Header()["Set-Cookie"]) - t.Log(errorMessage) - t.Log(b64.Decode(errorMessage)) +// errorMessage := getCookie("error", w.Header()["Set-Cookie"]) +// t.Log(errorMessage) +// t.Log(b64.Decode(errorMessage)) - header := w.Header() - sessionid := getCookie("session", header["Set-Cookie"]) - var session models.Session - if session.Read(sessionid) != nil { - t.Fatal("Could not find session") - } +// header := w.Header() +// sessionid := getCookie("session", header["Set-Cookie"]) +// var session models.Session +// if session.Read(sessionid) != nil { +// t.Fatal("Could not find session") +// } -} +// } -/*func testloginFail(t *testing.T) { +// /*func testloginFail(t *testing.T) { -}*/ +// }*/ -func setup(t *testing.T, method string, url string) (*http.Request, *httptest.ResponseRecorder) { - req, err := http.NewRequest("POST", "/login", nil) - w := httptest.NewRecorder() - if err != nil { - t.Fatal(err) - } - return req, w +// func setup(t *testing.T, method string, url string) (*http.Request, *httptest.ResponseRecorder) { +// req, err := http.NewRequest("POST", "/login", nil) +// w := httptest.NewRecorder() +// if err != nil { +// t.Fatal(err) +// } +// return req, w -} +// } -func createUser(t *testing.T, email string, password string) models.User { +// func createUser(t *testing.T, email string, password string) models.User { - password, err := helpers.HashPassword(password) - if err != nil { - t.Fatal("Failed to create password") - } - user := models.User{Email: email, Password: password} - if user.Create() != nil { - t.Fatal("failed to create user") - } +// password, err := helpers.HashPassword(password) +// if err != nil { +// t.Fatal("Failed to create password") +// } +// user := models.User{Email: email, Password: password} +// if user.Create() != nil { +// t.Fatal("failed to create user") +// } - return user -} +// return user +// } -func getCookie(name string, cookies []string) string { - for _, cookie := range cookies { - a := strings.Split(cookie, "=") - if a[0] == name { - return a[1] +// func getCookie(name string, cookies []string) string { +// for _, cookie := range cookies { +// a := strings.Split(cookie, "=") +// if a[0] == name { +// return a[1] - } +// } - } - return "Cookie not found" -} +// } +// return "Cookie not found" +// } -func addTofForm(r *http.Request, values ...string) { - form, _ := url.ParseQuery(r.URL.RawQuery) - for _, value := range values { - v := strings.Split(value, "=") - form.Add(v[0], v[1]) - } - r.URL.RawQuery = form.Encode() - r.Form.Encode() -} +// func addTofForm(r *http.Request, values ...string) { +// form, _ := url.ParseQuery(r.URL.RawQuery) +// for _, value := range values { +// v := strings.Split(value, "=") +// form.Add(v[0], v[1]) +// } +// r.URL.RawQuery = form.Encode() +// r.Form.Encode() +// } diff --git a/controllers/static.go b/controllers/static.go index a15e998..ad37842 100644 --- a/controllers/static.go +++ b/controllers/static.go @@ -1,29 +1,29 @@ -package controllers +// package controllers -import ( - "net/http" +// import ( +// "net/http" - "git.1248.nz/1248/Otfe/models" -) +// "git.technical.kiwi/go/otfe/models" +// ) -//Static pages -type Static struct{} +// //Static pages +// type Static struct{} -type staticData struct { - Title string - User models.User -} +// type staticData struct { +// Title string +// User models.User +// } -type contextKey string +// type contextKey string -func (c contextKey) String() string { - return string(c) -} +// func (c contextKey) String() string { +// return string(c) +// } -//Home page -func (s *Static) Home(w http.ResponseWriter, r *http.Request, u models.User) { - data := staticData{Title: "Otfe"} - data.User = u - //fmt.Fprintln(w, data.User) - t(w, data, "/static/home.gtpl") -} +// //Home page +// func (s *Static) Home(w http.ResponseWriter, r *http.Request, u models.User) { +// data := staticData{Title: "Otfe"} +// data.User = u +// //fmt.Fprintln(w, data.User) +// t(w, data, "/static/home.gtpl") +// } diff --git a/controllers/user.go b/controllers/user.go index 4edcc49..5680cac 100644 --- a/controllers/user.go +++ b/controllers/user.go @@ -1,91 +1,91 @@ -package controllers +// package controllers -import ( - "fmt" - "net/http" +// import ( +// "fmt" +// "net/http" - "git.1248.nz/1248/Otfe/misc/auth" - "git.1248.nz/1248/Otfe/misc/helpers" - "git.1248.nz/1248/Otfe/models" - "github.com/husobee/vestigo" -) +// "git.technical.kiwi/go/otfe/misc/auth" +// "git.technical.kiwi/go/otfe/misc/helpers" +// "git.technical.kiwi/go/otfe/models" +// "github.com/husobee/vestigo" +// ) -type userData struct { - Title string - Users []models.User - User models.User -} +// type userData struct { +// Title string +// Users []models.User +// User models.User +// } -//User handlers -type User struct{} +// //User handlers +// type User struct{} -//Index list all users -func (u User) Index(w http.ResponseWriter, r *http.Request) { - var err error - data := userData{Title: "Users"} - data.Users, err = data.User.ReadAll() - helpers.CheckError(err) - t(w, data, "/user/users.gtpl") -} +// //Index list all users +// func (u User) Index(w http.ResponseWriter, r *http.Request) { +// var err error +// data := userData{Title: "Users"} +// data.Users, err = data.User.ReadAll() +// helpers.CheckError(err) +// t(w, data, "/user/users.gtpl") +// } -//Show given user -func (u *User) Show(w http.ResponseWriter, r *http.Request, user models.User) { - var data userData - data.User.Read("username", vestigo.Param(r, "username")) - //matchUser(data.User, w, r) - data.Title = data.User.Username - t(w, data, "/user/user.gtpl") -} +// //Show given user +// func (u *User) Show(w http.ResponseWriter, r *http.Request, user models.User) { +// var data userData +// data.User.Read("username", vestigo.Param(r, "username")) +// //matchUser(data.User, w, r) +// data.Title = data.User.Username +// t(w, data, "/user/user.gtpl") +// } -//ShowSelf show given user if they are the same as the authenticated one -func (u *User) ShowSelf(w http.ResponseWriter, r *http.Request, user models.User) { - if user.Username != vestigo.Param(r, "username") { - auth.UnAuth(w) - return - } - var data userData - data.User = user - data.Title = data.User.Username - t(w, data, "/user/user.gtpl") -} +// //ShowSelf show given user if they are the same as the authenticated one +// func (u *User) ShowSelf(w http.ResponseWriter, r *http.Request, user models.User) { +// if user.Username != vestigo.Param(r, "username") { +// auth.UnAuth(w) +// return +// } +// var data userData +// data.User = user +// data.Title = data.User.Username +// t(w, data, "/user/user.gtpl") +// } -//New user form -func (u *User) New(w http.ResponseWriter, r *http.Request) { - data := userData{Title: "New User"} - t(w, data, "/user/new.gtpl") -} +// //New user form +// func (u *User) New(w http.ResponseWriter, r *http.Request) { +// data := userData{Title: "New User"} +// t(w, data, "/user/new.gtpl") +// } -//Create new a user -func (u *User) Create(w http.ResponseWriter, r *http.Request) { - r.ParseForm() - var user models.User - var err error - user.Username = r.Form.Get("username") - user.Email = r.Form.Get("email") - user.Password, err = helpers.HashPassword(r.Form.Get("password")) - helpers.CheckError(err) - user.Create() - http.Redirect(w, r, "/user/"+user.Username, http.StatusFound) +// //Create new a user +// func (u *User) Create(w http.ResponseWriter, r *http.Request) { +// r.ParseForm() +// var user models.User +// var err error +// user.Username = r.Form.Get("username") +// user.Email = r.Form.Get("email") +// user.Password, err = helpers.HashPassword(r.Form.Get("password")) +// helpers.CheckError(err) +// user.Create() +// http.Redirect(w, r, "/user/"+user.Username, http.StatusFound) -} +// } -//Edit form -func (u *User) Edit(w http.ResponseWriter, r *http.Request) { - var data userData - data.User.Read("username", vestigo.Param(r, "username")) +// //Edit form +// func (u *User) Edit(w http.ResponseWriter, r *http.Request) { +// var data userData +// data.User.Read("username", vestigo.Param(r, "username")) -} +// } -//Update user -func (u *User) Update(w http.ResponseWriter, r *http.Request) { +// //Update user +// func (u *User) Update(w http.ResponseWriter, r *http.Request) { -} +// } -//Delete user -func (u *User) Delete(w http.ResponseWriter, r *http.Request) { - fmt.Println("Deleting " + vestigo.Param(r, "username")) - var user models.User - user.Delete("username", vestigo.Param(r, "username")) - http.Redirect(w, r, "/user", http.StatusFound) +// //Delete user +// func (u *User) Delete(w http.ResponseWriter, r *http.Request) { +// fmt.Println("Deleting " + vestigo.Param(r, "username")) +// var user models.User +// user.Delete("username", vestigo.Param(r, "username")) +// http.Redirect(w, r, "/user", http.StatusFound) -} +// } diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..766a980 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.technical.kiwi/go/otfe + +go 1.17 diff --git a/misc/auth/auth.go b/misc/auth/auth.go index e4a23c0..9a074bb 100644 --- a/misc/auth/auth.go +++ b/misc/auth/auth.go @@ -1,59 +1,59 @@ -package auth +// package auth -import ( - "errors" - "net/http" +// import ( +// "errors" +// "net/http" - "git.1248.nz/1248/Otfe/models" -) +// "git.technical.kiwi/go/otfe/models" +// ) -type auth func(http.ResponseWriter, *http.Request, models.User) +// type auth func(http.ResponseWriter, *http.Request, models.User) -func User(h auth) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - user, _ := getUserSession(r) - h(w, r, user) - } -} +// func User(h auth) http.HandlerFunc { +// return func(w http.ResponseWriter, r *http.Request) { +// user, _ := getUserSession(r) +// h(w, r, user) +// } +// } -func Perm(handler auth, fallback auth, perm string) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - user, err := getUserSession(r) - if err != nil { - http.Redirect(w, r, "/login", http.StatusFound) - return - } - if user.HasPermission(perm) { - handler(w, r, user) - } else { - if fallback == nil { - UnAuth(w) - } else { - fallback(w, r, user) - } - } +// func Perm(handler auth, fallback auth, perm string) http.HandlerFunc { +// return func(w http.ResponseWriter, r *http.Request) { +// user, err := getUserSession(r) +// if err != nil { +// http.Redirect(w, r, "/login", http.StatusFound) +// return +// } +// if user.HasPermission(perm) { +// handler(w, r, user) +// } else { +// if fallback == nil { +// UnAuth(w) +// } else { +// fallback(w, r, user) +// } +// } - } +// } -} +// } -func getUserSession(r *http.Request) (models.User, error) { - var session models.Session - var user models.User - //Check for session in db - err := session.Get(r) - if err == nil { - //Get user associated with the session - err = user.Read("_id", session.UserID) - if err == nil { - return user, nil +// func getUserSession(r *http.Request) (models.User, error) { +// var session models.Session +// var user models.User +// //Check for session in db +// err := session.Get(r) +// if err == nil { +// //Get user associated with the session +// err = user.Read("_id", session.UserID) +// if err == nil { +// return user, nil - } - } - return user, errors.New("User not logged in") -} +// } +// } +// return user, errors.New("User not logged in") +// } -func UnAuth(w http.ResponseWriter) { - http.Error(w, "You are not authorized to view this page", - http.StatusForbidden) -} +// func UnAuth(w http.ResponseWriter) { +// http.Error(w, "You are not authorized to view this page", +// http.StatusForbidden) +// } diff --git a/misc/auth/auth_test.go b/misc/auth/auth_test.go index e6d6389..45484af 100644 --- a/misc/auth/auth_test.go +++ b/misc/auth/auth_test.go @@ -1,113 +1,113 @@ -package auth +// package auth -import ( - "fmt" - "net/http" - "net/http/httptest" - "strings" - "testing" +// import ( +// "fmt" +// "net/http" +// "net/http/httptest" +// "strings" +// "testing" - "git.1248.nz/1248/Otfe/misc/helpers" - "git.1248.nz/1248/Otfe/misc/helpers/cookie" - "git.1248.nz/1248/Otfe/models" - "github.com/globalsign/mgo/bson" -) +// "git.technical.kiwi/go/otfe/misc/helpers" +// "git.technical.kiwi/go/otfe/misc/helpers/cookie" +// "git.technical.kiwi/go/otfe/models" +// "github.com/globalsign/mgo/bson" +// ) -func TestUser(t *testing.T) { - //Setup user with session - recorder := httptest.NewRecorder() - user, session := userSession(t) - request := request(t, session) - u := User(handler) - //Run - u(recorder, request) - //Check - body := recorder.Body.String() - if !strings.Contains(body, user.ID.Hex()) { - t.Fail() - } - //Setup without session - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/", nil) - //Run - u(recorder, request) - //Check - helpers.Equals(t, recorder.Body.String(), - "{ObjectIdHex(\"\") ObjectIdHex(\"\") []}") +// func TestUser(t *testing.T) { +// //Setup user with session +// recorder := httptest.NewRecorder() +// user, session := userSession(t) +// request := request(t, session) +// u := User(handler) +// //Run +// u(recorder, request) +// //Check +// body := recorder.Body.String() +// if !strings.Contains(body, user.ID.Hex()) { +// t.Fail() +// } +// //Setup without session +// recorder = httptest.NewRecorder() +// request, _ = http.NewRequest("GET", "/", nil) +// //Run +// u(recorder, request) +// //Check +// helpers.Equals(t, recorder.Body.String(), +// "{ObjectIdHex(\"\") ObjectIdHex(\"\") []}") -} +// } -func TestPerm(t *testing.T) { - p := Perm(handler, UnAuth, "perm") - recorder := httptest.NewRecorder() - user, session := userSession(t) - request := request(t, session) - p(recorder, request) - if !strings.Contains(recorder.Body.String(), - "You are not authorized to view this page") { - t.Log("Authorization fail") - t.Fail() - } +// func TestPerm(t *testing.T) { +// p := Perm(handler, UnAuth, "perm") +// recorder := httptest.NewRecorder() +// user, session := userSession(t) +// request := request(t, session) +// p(recorder, request) +// if !strings.Contains(recorder.Body.String(), +// "You are not authorized to view this page") { +// t.Log("Authorization fail") +// t.Fail() +// } - p = Perm(handler, UnAuth, "test") - recorder = httptest.NewRecorder() - p(recorder, request) - if !strings.Contains(recorder.Body.String(), user.ID.Hex()) { - t.Log("Has permission fail") - t.Fail() - } +// p = Perm(handler, UnAuth, "test") +// recorder = httptest.NewRecorder() +// p(recorder, request) +// if !strings.Contains(recorder.Body.String(), user.ID.Hex()) { +// t.Log("Has permission fail") +// t.Fail() +// } - recorder = httptest.NewRecorder() - request, err := http.NewRequest("GET", "/", nil) - helpers.Ok(t, err) - p(recorder, request) - if !strings.Contains(recorder.Body.String(), "login") { - t.Log("Login fail") - t.Fail() - } +// recorder = httptest.NewRecorder() +// request, err := http.NewRequest("GET", "/", nil) +// helpers.Ok(t, err) +// p(recorder, request) +// if !strings.Contains(recorder.Body.String(), "login") { +// t.Log("Login fail") +// t.Fail() +// } -} +// } -func TestGetUserSession(t *testing.T) { - user, session := userSession(t) - request := request(t, session) - //Test - user2, err := getUserSession(request) - helpers.Ok(t, err) - helpers.Equals(t, user, user2) +// func TestGetUserSession(t *testing.T) { +// user, session := userSession(t) +// request := request(t, session) +// //Test +// user2, err := getUserSession(request) +// helpers.Ok(t, err) +// helpers.Equals(t, user, user2) -} +// } -func userSession(t *testing.T) (models.User, models.Session) { - models.DBWipeCollection("user", "session", "group") +// func userSession(t *testing.T) (models.User, models.Session) { +// models.DBWipeCollection("user", "session", "group") - group := models.NewGroup("test") - group.ID = bson.NewObjectId() - group.Permissions["test"] = true - //group.Admin = true - helpers.Ok(t, group.Create()) +// group := models.NewGroup("test") +// group.ID = bson.NewObjectId() +// group.Permissions["test"] = true +// //group.Admin = true +// helpers.Ok(t, group.Create()) - user := models.User{Name: "test", - Email: "test"} - user.ID = bson.NewObjectId() - user.PrimaryGroup = group.ID - helpers.Ok(t, user.Create()) +// user := models.User{Name: "test", +// Email: "test"} +// user.ID = bson.NewObjectId() +// user.PrimaryGroup = group.ID +// helpers.Ok(t, user.Create()) - session := models.Session{UserID: user.ID} - session.ID = bson.NewObjectId() - helpers.Ok(t, session.Create()) - return user, session -} +// session := models.Session{UserID: user.ID} +// session.ID = bson.NewObjectId() +// helpers.Ok(t, session.Create()) +// return user, session +// } -func request(t *testing.T, s models.Session) *http.Request { - cookie := &http.Cookie{Name: "session", - Value: cookie.Encode(s.ID.Hex())} - request, err := http.NewRequest("GET", "/", nil) - helpers.Ok(t, err) - request.AddCookie(cookie) - return request -} +// func request(t *testing.T, s models.Session) *http.Request { +// cookie := &http.Cookie{Name: "session", +// Value: cookie.Encode(s.ID.Hex())} +// request, err := http.NewRequest("GET", "/", nil) +// helpers.Ok(t, err) +// request.AddCookie(cookie) +// return request +// } -func handler(w http.ResponseWriter, r *http.Request, u models.User) { - fmt.Fprint(w, u) -} +// func handler(w http.ResponseWriter, r *http.Request, u models.User) { +// fmt.Fprint(w, u) +// } diff --git a/misc/b64/b64.go b/misc/b64/b64.go index cd543f5..59dcd3a 100644 --- a/misc/b64/b64.go +++ b/misc/b64/b64.go @@ -1,12 +1,12 @@ -package b64 +// package b64 -import "encoding/base64" +// import "encoding/base64" -func Encode(src string) string { - return base64.URLEncoding.EncodeToString([]byte(src)) -} +// func Encode(src string) string { +// return base64.URLEncoding.EncodeToString([]byte(src)) +// } -func Decode(src string) (string, error) { - value, err := base64.URLEncoding.DecodeString(src) - return string(value), err -} +// func Decode(src string) (string, error) { +// value, err := base64.URLEncoding.DecodeString(src) +// return string(value), err +// } diff --git a/misc/config/config.go b/misc/config/config.go index 411ba56..705df43 100644 --- a/misc/config/config.go +++ b/misc/config/config.go @@ -1,60 +1,60 @@ -package config +// package config -import ( - "encoding/hex" - "path/filepath" +// import ( +// "encoding/hex" +// "path/filepath" - "git.1248.nz/1248/Otfe/misc/helpers" +// "git.technical.kiwi/go/otfe/misc/helpers" - "github.com/BurntSushi/toml" -) +// "github.com/BurntSushi/toml" +// ) -//Configuration struct -type Configuration struct { - DB database `toml:"database"` - Session session -} +// //Configuration struct +// type Configuration struct { +// DB database `toml:"database"` +// Session session +// } -// Database stuct -type database struct { - Host string - Name string - User string - Password string -} +// // Database stuct +// type database struct { +// Host string +// Name string +// User string +// Password string +// } -type session struct { - SecretKey string - Sessionkey string - Timeout int -} +// type session struct { +// SecretKey string +// Sessionkey string +// Timeout int +// } -var config *Configuration +// var config *Configuration -func init() { - Get() -} +// func init() { +// Get() +// } -// Get config info from toml config file -func Get() *Configuration { - if config == nil { - _, err := toml.DecodeFile(getConfigFile(), &config) - helpers.CheckError(err) - } - return config -} +// // Get config info from toml config file +// func Get() *Configuration { +// if config == nil { +// _, err := toml.DecodeFile(getConfigFile(), &config) +// helpers.CheckError(err) +// } +// return config +// } -func getConfigFile() string { - return filepath.Join(helpers.GetRootDir(), "config.toml") -} +// func getConfigFile() string { +// return filepath.Join(helpers.GetRootDir(), "config.toml") +// } -func GetSecretKey() []byte { - config := Get() - key, err := hex.DecodeString(config.Session.SecretKey) - helpers.CheckError(err) - return key -} +// func GetSecretKey() []byte { +// config := Get() +// key, err := hex.DecodeString(config.Session.SecretKey) +// helpers.CheckError(err) +// return key +// } -func GetSessionKey() string { - return Get().Session.Sessionkey -} +// func GetSessionKey() string { +// return Get().Session.Sessionkey +// } diff --git a/misc/config/config_test.go b/misc/config/config_test.go index b9c7582..b8d122c 100644 --- a/misc/config/config_test.go +++ b/misc/config/config_test.go @@ -1,7 +1,7 @@ -package config +// package config -import "testing" +// import "testing" -func TestGetConfigFile(t *testing.T) { - t.Log(Get()) -} +// func TestGetConfigFile(t *testing.T) { +// t.Log(Get()) +// } diff --git a/misc/cookie/cookie.go b/misc/cookie/cookie.go deleted file mode 100644 index 5be2d1c..0000000 --- a/misc/cookie/cookie.go +++ /dev/null @@ -1,31 +0,0 @@ -package cookie - -import ( - "errors" - "net/http" - "time" - - "git.1248.nz/1248/Otfe/misc/b64" -) - -func Create(w http.ResponseWriter, name string, value string) { - c := &http.Cookie{Name: name, Value: b64.Encode(value)} - http.SetCookie(w, c) -} - -func Read(r *http.Request, name string) (string, error) { - c, err := r.Cookie(name) - if err != nil { - return "", errors.New("Cookie not found") - } - value, err := b64.Decode(c.Value) - if err != nil { - return "", errors.New("Failed to decode cookie") - } - return value, nil -} - -func Delete(w http.ResponseWriter, name string) { - http.SetCookie(w, &http.Cookie{Name: name, MaxAge: -1, Expires: time.Unix(1, 0)}) - -} diff --git a/misc/cookie/cookie_test.go b/misc/cookie/cookie_test.go deleted file mode 100644 index 649246b..0000000 --- a/misc/cookie/cookie_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package cookie - -import ( - "net/http" - "net/http/httptest" - "testing" - - "git.1248.nz/1248/Otfe/misc/b64" - "git.1248.nz/1248/Otfe/misc/helpers" -) - -func TestCreate(t *testing.T) { - recorder := httptest.NewRecorder() - Create(recorder, "test", "test") - request := &http.Request{Header: http.Header{ - "Cookie": recorder.HeaderMap["Set-Cookie"]}} - cookie, err := request.Cookie("test") - if err != nil { - t.Fail() - return - } - value, err := b64.Decode(cookie.Value) - if err != nil || value != "test" { - t.Fail() - } -} - -func TestRead(t *testing.T) { - cookie := &http.Cookie{Name: "test", Value: b64.Encode("test")} - - request, err := http.NewRequest("GET", "", nil) - if err != nil { - t.Fail() - return - } - request.AddCookie(cookie) - value, err := Read(request, "test") - helpers.Equals(t, value, "test") -} diff --git a/misc/helpers/helpers.go b/misc/helpers/helpers.go index 571ce93..993b61b 100644 --- a/misc/helpers/helpers.go +++ b/misc/helpers/helpers.go @@ -1,55 +1,55 @@ -package helpers +// package helpers -import ( - "crypto/rand" - "encoding/hex" - "log" - "path/filepath" - "runtime" +// import ( +// "crypto/rand" +// "encoding/hex" +// "log" +// "path/filepath" +// "runtime" - "golang.org/x/crypto/bcrypt" -) +// "golang.org/x/crypto/bcrypt" +// ) -//CheckError checks for errors and logs them and stops the program -func CheckError(err error) bool { - if err != nil { - log.Fatal(err) - return false - } - return true -} +// //CheckError checks for errors and logs them and stops the program +// func CheckError(err error) bool { +// if err != nil { +// log.Fatal(err) +// return false +// } +// return true +// } -func GetRootDir() string { - _, b, _, _ := runtime.Caller(0) - dir := filepath.Dir(b) - return filepath.Dir(filepath.Dir(dir)) -} +// func GetRootDir() string { +// _, b, _, _ := runtime.Caller(0) +// dir := filepath.Dir(b) +// return filepath.Dir(filepath.Dir(dir)) +// } -func GetAssets() string { - return GetRootDir() -} +// func GetAssets() string { +// return GetRootDir() +// } -func HashPassword(password string) (string, error) { - hash, err := bcrypt.GenerateFromPassword([]byte(password), 14) - return string(hash), err -} +// func HashPassword(password string) (string, error) { +// hash, err := bcrypt.GenerateFromPassword([]byte(password), 14) +// return string(hash), err +// } -func CheckPasswordHash(password, hash string) error { - err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) - return err -} +// func CheckPasswordHash(password, hash string) error { +// err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) +// return err +// } -func RandHex() string { - bytes := make([]byte, 12) - rand.Read(bytes) - return hex.EncodeToString(bytes) -} +// func RandHex() string { +// bytes := make([]byte, 12) +// rand.Read(bytes) +// return hex.EncodeToString(bytes) +// } -func Bytes(n int) ([]byte, error) { - b := make([]byte, n) - _, err := rand.Read(b) - if err != nil { - return nil, err - } - return b, nil -} +// func Bytes(n int) ([]byte, error) { +// b := make([]byte, n) +// _, err := rand.Read(b) +// if err != nil { +// return nil, err +// } +// return b, nil +// } diff --git a/misc/helpers/helpers_test.go b/misc/helpers/helpers_test.go index de8e8bd..e72729d 100644 --- a/misc/helpers/helpers_test.go +++ b/misc/helpers/helpers_test.go @@ -1,35 +1,35 @@ -package helpers_test +// package helpers_test -import ( - "testing" +// import ( +// "testing" - "git.1248.nz/1248/Otfe/misc/helpers" - "git.1248.nz/1248/Otfe/models" -) +// "git.technical.kiwi/go/otfe/misc/helpers" +// "git.technical.kiwi/go/otfe/models" +// ) -func TestGetRootDir(t *testing.T) { - t.Log("Root path:", helpers.GetRootDir()) -} +// func TestGetRootDir(t *testing.T) { +// t.Log("Root path:", helpers.GetRootDir()) +// } -func TestHashPassword(t *testing.T) { - user := models.User{Email: "a@a.com", Username: "a"} - user.Delete("username", "a") - var err error - password := "43539jgifdkvnm4935078uJKJR**$ufjqd98438uiAHFJean89q34JKDFJ" - user.Password, err = helpers.HashPassword(password) - if err != nil { - t.Fail() - } - user.Create() - var user2 models.User - user2.Read("username", "a") +// func TestHashPassword(t *testing.T) { +// user := models.User{Email: "a@a.com", Username: "a"} +// user.Delete("username", "a") +// var err error +// password := "43539jgifdkvnm4935078uJKJR**$ufjqd98438uiAHFJean89q34JKDFJ" +// user.Password, err = helpers.HashPassword(password) +// if err != nil { +// t.Fail() +// } +// user.Create() +// var user2 models.User +// user2.Read("username", "a") - t.Log(helpers.CheckPasswordHash(password, user2.Password)) +// t.Log(helpers.CheckPasswordHash(password, user2.Password)) -} +// } -func TestRandHex(t *testing.T) { - for i := 0; i < 20; i++ { - t.Log(helpers.RandHex()) - } -} +// func TestRandHex(t *testing.T) { +// for i := 0; i < 20; i++ { +// t.Log(helpers.RandHex()) +// } +// } diff --git a/misc/helpers/test.go b/misc/helpers/test.go index 2e04b46..278b7a7 100644 --- a/misc/helpers/test.go +++ b/misc/helpers/test.go @@ -1,36 +1,36 @@ -package helpers +// package helpers -import ( - "fmt" - "path/filepath" - "reflect" - "runtime" - "testing" -) +// import ( +// "fmt" +// "path/filepath" +// "reflect" +// "runtime" +// "testing" +// ) -// assert fails the test if the condition is false. -func Assert(tb testing.TB, condition bool, msg string, v ...interface{}) { - if !condition { - _, file, line, _ := runtime.Caller(1) - fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...) - tb.FailNow() - } -} +// // assert fails the test if the condition is false. +// func Assert(tb testing.TB, condition bool, msg string, v ...interface{}) { +// if !condition { +// _, file, line, _ := runtime.Caller(1) +// fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...) +// tb.FailNow() +// } +// } -// ok fails the test if an err is not nil. -func Ok(tb testing.TB, err error) { - if err != nil { - _, file, line, _ := runtime.Caller(1) - fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error()) - tb.FailNow() - } -} +// // ok fails the test if an err is not nil. +// func Ok(tb testing.TB, err error) { +// if err != nil { +// _, file, line, _ := runtime.Caller(1) +// fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error()) +// tb.FailNow() +// } +// } -// equals fails the test if exp is not equal to act. -func Equals(tb testing.TB, exp, act interface{}) { - if !reflect.DeepEqual(exp, act) { - _, file, line, _ := runtime.Caller(1) - fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act) - tb.FailNow() - } -} +// // equals fails the test if exp is not equal to act. +// func Equals(tb testing.TB, exp, act interface{}) { +// if !reflect.DeepEqual(exp, act) { +// _, file, line, _ := runtime.Caller(1) +// fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act) +// tb.FailNow() +// } +// } diff --git a/misc/rand/rand.go b/misc/rand/rand.go index 7391016..e43e17e 100644 --- a/misc/rand/rand.go +++ b/misc/rand/rand.go @@ -1,20 +1,20 @@ -package rand +// package rand -import ( - "crypto/rand" +// import ( +// "crypto/rand" - "git.1248.nz/1248/Otfe/misc/b64" -) +// "git.technical.kiwi/go/otfe/misc/b64" +// ) -//Bytes generates an random set of bytes n long -func Bytes(n int) ([]byte, error) { - b := make([]byte, n) - _, err := rand.Read(b) - return b, err -} +// //Bytes generates an random set of bytes n long +// func Bytes(n int) ([]byte, error) { +// b := make([]byte, n) +// _, err := rand.Read(b) +// return b, err +// } -//B64String generates a base 64 string n bytess long -func B64String(n int) (string, error) { - b, err := Bytes(n) - return b64.Encode(string(b)), err -} +// //B64String generates a base 64 string n bytess long +// func B64String(n int) (string, error) { +// b, err := Bytes(n) +// return b64.Encode(string(b)), err +// } diff --git a/misc/test/seed.go b/misc/test/seed.go index e9225b4..f77e95c 100644 --- a/misc/test/seed.go +++ b/misc/test/seed.go @@ -1,41 +1,41 @@ -package main +// package main -import ( - "git.1248.nz/1248/Otfe/misc/helpers" - "git.1248.nz/1248/Otfe/models" - "github.com/globalsign/mgo/bson" -) +// import ( +// "git.technical.kiwi/go/otfe/misc/helpers" +// "git.technical.kiwi/go/otfe/models" +// "github.com/globalsign/mgo/bson" +// ) -func main() { - models.DBWipeCollection("group", "user", "session") - //admin user and group - adminGroup := models.NewGroup("admin") - adminGroup.Admin = true - adminGroup.ID = bson.NewObjectId() - adminGroup.Permissions["user.show"] = true +// func main() { +// models.DBWipeCollection("group", "user", "session") +// //admin user and group +// adminGroup := models.NewGroup("admin") +// adminGroup.Admin = true +// adminGroup.ID = bson.NewObjectId() +// adminGroup.Permissions["user.show"] = true - admin := models.User{} - admin.Username = "admin" - admin.Email = "admin" - admin.ID = bson.NewObjectId() - admin.Password, _ = helpers.HashPassword("admin") - admin.PrimaryGroup = adminGroup.ID - adminGroup.Users = append(adminGroup.Users, admin.ID) - adminGroup.Create() - admin.Create() +// admin := models.User{} +// admin.Username = "admin" +// admin.Email = "admin" +// admin.ID = bson.NewObjectId() +// admin.Password, _ = helpers.HashPassword("admin") +// admin.PrimaryGroup = adminGroup.ID +// adminGroup.Users = append(adminGroup.Users, admin.ID) +// adminGroup.Create() +// admin.Create() - //user and user group - userGroup := models.NewGroup("user") - userGroup.ID = bson.NewObjectId() - userGroup.Admin = false - user := models.User{} - user.ID = bson.NewObjectId() - user.Username = "user" - user.Email = "u" - user.Password, _ = helpers.HashPassword("user") - user.PrimaryGroup = userGroup.ID - userGroup.Users = append(userGroup.Users, user.ID) - user.Create() - userGroup.Create() +// //user and user group +// userGroup := models.NewGroup("user") +// userGroup.ID = bson.NewObjectId() +// userGroup.Admin = false +// user := models.User{} +// user.ID = bson.NewObjectId() +// user.Username = "user" +// user.Email = "u" +// user.Password, _ = helpers.HashPassword("user") +// user.PrimaryGroup = userGroup.ID +// userGroup.Users = append(userGroup.Users, user.ID) +// user.Create() +// userGroup.Create() -} +// } diff --git a/models/group.go b/models/group.go index a7c77b6..a39a051 100644 --- a/models/group.go +++ b/models/group.go @@ -1,50 +1,50 @@ -package models +// package models -import ( - "github.com/jinzhu/gorm" -) +// import ( +// "github.com/jinzhu/gorm" +// ) -//Group type -type Group struct { - gorm.Model - Name string - Permissions map[string]bool - Admin bool - Users []string -} +// //Group type +// type Group struct { +// gorm.Model +// Name string +// Permissions map[string]bool +// Admin bool +// Users []string +// } -func NewGroup(Name string) Group { - var group Group - group.Permissions = make(map[string]bool) - return group -} +// func NewGroup(Name string) Group { +// var group Group +// group.Permissions = make(map[string]bool) +// return group +// } -//Create group -func (g *Group) Create() error { - return create(&g) -} +// //Create group +// func (g *Group) Create() error { +// return create(&g) +// } -//Read group -func (g *Group) Read() error { - return read(&g) +// //Read group +// func (g *Group) Read() error { +// return read(&g) -} +// } -//ReadAll groups -func (g *Group) ReadAll() ([]Group, error) { - var groups []Group - var err error - err = readAll(&groups) - return groups, err -} +// //ReadAll groups +// func (g *Group) ReadAll() ([]Group, error) { +// var groups []Group +// var err error +// err = readAll(&groups) +// return groups, err +// } -//Update group -func (g *Group) Update() error { - return update(&g) -} +// //Update group +// func (g *Group) Update() error { +// return update(&g) +// } -//Delete group -func (g *Group) Delete() error { - err := delete(&g) - return err -} +// //Delete group +// func (g *Group) Delete() error { +// err := delete(&g) +// return err +// } diff --git a/models/group_test.go b/models/group_test.go index b57938a..6edf2be 100644 --- a/models/group_test.go +++ b/models/group_test.go @@ -1,25 +1,25 @@ -package models +// package models -import ( - "testing" +// import ( +// "testing" - "github.com/globalsign/mgo/bson" -) +// "github.com/globalsign/mgo/bson" +// ) -func TestCreateGroup(t *testing.T) { - group := NewGroup("test") - group.Users = append(group.Users, bson.NewObjectId()) - group.Permissions["test"] = true - t.Log(group.Create()) -} +// func TestCreateGroup(t *testing.T) { +// group := NewGroup("test") +// group.Users = append(group.Users, bson.NewObjectId()) +// group.Permissions["test"] = true +// t.Log(group.Create()) +// } -func TestReadGroup(t *testing.T) { - var group Group - group.Read("name", "test") - t.Log(group) -} +// func TestReadGroup(t *testing.T) { +// var group Group +// group.Read("name", "test") +// t.Log(group) +// } -func TestReadAllGroup(t *testing.T) { - var group Group - t.Log(group.ReadAll()) -} +// func TestReadAllGroup(t *testing.T) { +// var group Group +// t.Log(group.ReadAll()) +// } diff --git a/models/model.go b/models/model.go index 96ce40c..137ced4 100644 --- a/models/model.go +++ b/models/model.go @@ -1,33 +1,27 @@ package models import ( - "fmt" - "github.com/jinzhu/gorm" - _ "github.com/jinzhu/gorm/dialects/postgres" // + _ "github.com/jinzhu/gorm/dialects/postgres" + "gorm.io/driver/sqlite" ) -const ( - host = "localhost" - port = 5432 - user = "test" - password = "test" - dbname = "test" -) +// var ( +// gormdb, err = +// store = gormstore.New(gormdb, []byte("secret")) +// ) var psqlInfo string var db *gorm.DB func init() { - psqlInfo = fmt.Sprintf("host=%s port=%d user=%s "+ - "password=%s dbname=%s sslmode=disable", - host, port, user, password, dbname) DB() } + func DB() (*gorm.DB, error) { if db == nil { - db, err := gorm.Open("postgres", psqlInfo) + db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) db.LogMode(true) return db, err } diff --git a/models/model_test.go b/models/model_test.go index 1f896ba..ebfedcc 100644 --- a/models/model_test.go +++ b/models/model_test.go @@ -1,37 +1,42 @@ -package models +package models_test import ( "testing" + + "git.technical.kiwi/go/otfe/models" ) -func TestGetSession(t *testing.T) { - GetMongoSession() +func TestGetDB(t *testing.T) { + db, err := models.DB() + if !err || !db { + t.Fail() + } } func TestGetCollection(t *testing.T) { - GetCollection("test") + //GetCollection("test") } func TestCreate(t *testing.T) { - create("user", &User{Name: "Ale"}) + //create("user", &User{Name: "Ale"}) } func TestReadAll(t *testing.T) { - var u []User - readAll("user", "", nil, &u) - t.Log(u) + //var u []User + //readAll("user", "", nil, &u) + //t.Log(u) } func TestRead(t *testing.T) { - var u User - read("user", "name", "Ann", &u) - t.Log(u) + //var u User + //read("user", "name", "Ann", &u) + //t.Log(u) } func TestUpdate(t *testing.T) { - update("test", "name", "Ale", &User{Name: "Bob", Email: "z"}) + //update("test", "name", "Ale", &User{Name: "Bob", Email: "z"}) } func TestDelete(t *testing.T) { - t.Log(delete("user", "name", "Ann")) + //t.Log(delete("user", "name", "Ann")) } diff --git a/models/post.go b/models/post.go index 7241cf4..a4f960c 100644 --- a/models/post.go +++ b/models/post.go @@ -1,33 +1,33 @@ -package models +// package models -import ( - "time" +// import ( +// "time" - "github.com/jinzhu/gorm" -) +// "github.com/jinzhu/gorm" +// ) -//Post model -type Post struct { - gorm.Model - Title string - Author string - Published time.Time - LastEdited time.Time - Content []byte -} +// //Post model +// type Post struct { +// gorm.Model +// Title string +// Author string +// Published time.Time +// LastEdited time.Time +// Content []byte +// } -//Create new post -func (p Post) Create() error { - return create(&p) -} +// //Create new post +// func (p Post) Create() error { +// return create(&p) +// } -func (p *Post) Read() (*Post, error) { - err := read(&p) - return p, err -} +// func (p *Post) Read() (*Post, error) { +// err := read(&p) +// return p, err +// } -func (p Post) ReadAll() ([]Post, error) { - var posts []Post - err := readAll(&posts) - return posts, err -} +// func (p Post) ReadAll() ([]Post, error) { +// var posts []Post +// err := readAll(&posts) +// return posts, err +// } diff --git a/models/session.go b/models/session.go index 8e4d787..c6d475a 100644 --- a/models/session.go +++ b/models/session.go @@ -4,7 +4,7 @@ import ( "net/http" "time" - "git.1248.nz/1248/Otfe/misc/cookie" + "git.technical.kiwi/go/otfe/misc/cookie" "github.com/globalsign/mgo/bson" "github.com/jinzhu/gorm" ) diff --git a/models/session_test.go b/models/session_test.go index 015cbb4..e68d423 100644 --- a/models/session_test.go +++ b/models/session_test.go @@ -1,51 +1,51 @@ -package models +// package models -import ( - "net/http" - "testing" +// import ( +// "net/http" +// "testing" - "git.1248.nz/1248/Otfe/misc/b64" - "git.1248.nz/1248/Otfe/misc/helpers" - "git.1248.nz/1248/Otfe/misc/rand" -) +// "git.technical.kiwi/go/otfe/misc/b64" +// "git.technical.kiwi/go/otfe/misc/helpers" +// "git.technical.kiwi/go/otfe/misc/rand" +// ) -func TestSessionCreate(t *testing.T) { - var s1, s2 Session - s1.ID, _ = rand.B64String(32) - if s1.Create() != nil { - t.Fail() - } - read("session", "_id", s1.ID, &s2) +// func TestSessionCreate(t *testing.T) { +// var s1, s2 Session +// s1.ID, _ = rand.B64String(32) +// if s1.Create() != nil { +// t.Fail() +// } +// read("session", "_id", s1.ID, &s2) - if s1.ID != s2.ID { - t.Fail() - } -} +// if s1.ID != s2.ID { +// t.Fail() +// } +// } -func TestSessionRead(t *testing.T) { - var s1, s2 Session - s1.ID, _ = rand.B64String(32) - if create("session", &s1) != nil { - t.Fatal("Failed to create session") - } - if s2.Read(s1.ID) != nil { - t.Fatal("Failed to read session") - } - if s1.ID != s2.ID { - t.Fatal("Ids don't match") - } -} +// func TestSessionRead(t *testing.T) { +// var s1, s2 Session +// s1.ID, _ = rand.B64String(32) +// if create("session", &s1) != nil { +// t.Fatal("Failed to create session") +// } +// if s2.Read(s1.ID) != nil { +// t.Fatal("Failed to read session") +// } +// if s1.ID != s2.ID { +// t.Fatal("Ids don't match") +// } +// } -func TestGet(t *testing.T) { - DBWipeCollection("session") - var s1, s2 Session - s1.ID, _ = rand.B64String(32) - s1.Create() - c := &http.Cookie{Name: "session", - Value: b64.Encode(s1.ID)} - request, err := http.NewRequest("GET", "/", nil) - helpers.Ok(t, err) - request.AddCookie(c) - s2.Get(request) - helpers.Equals(t, s1, s2) -} +// func TestGet(t *testing.T) { +// DBWipeCollection("session") +// var s1, s2 Session +// s1.ID, _ = rand.B64String(32) +// s1.Create() +// c := &http.Cookie{Name: "session", +// Value: b64.Encode(s1.ID)} +// request, err := http.NewRequest("GET", "/", nil) +// helpers.Ok(t, err) +// request.AddCookie(c) +// s2.Get(request) +// helpers.Equals(t, s1, s2) +// } diff --git a/models/user.go b/models/user.go index a2fe529..83c589e 100644 --- a/models/user.go +++ b/models/user.go @@ -1,80 +1,80 @@ -package models +// package models -import ( - "errors" - "fmt" +// import ( +// "errors" +// "fmt" - "github.com/globalsign/mgo/bson" -) +// "github.com/globalsign/mgo/bson" +// ) -//User model -type User struct { - ID bson.ObjectId `bson:"_id,omitempty"` - Email string `bson:"email"` - Name string `bson:"name"` - Username string `bson:"username"` - Password string `bson:"password"` - PrimaryGroup bson.ObjectId `bson:"primarygroup,omitempty"` - Groups []bson.ObjectId `bson:"groups,omitempty"` - Session string -} +// //User model +// type User struct { +// ID bson.ObjectId `bson:"_id,omitempty"` +// Email string `bson:"email"` +// Name string `bson:"name"` +// Username string `bson:"username"` +// Password string `bson:"password"` +// PrimaryGroup bson.ObjectId `bson:"primarygroup,omitempty"` +// Groups []bson.ObjectId `bson:"groups,omitempty"` +// Session string +// } -//Create user -func (u *User) Create() error { - var user User - read("user", "email", u.Email, &user) - if u.Email == user.Email { - return errors.New("Email all ready used") - } - return create("user", &u) +// //Create user +// func (u *User) Create() error { +// var user User +// read("user", "email", u.Email, &user) +// if u.Email == user.Email { +// return errors.New("Email all ready used") +// } +// return create("user", &u) -} +// } -//Read user -func (u *User) Read(key string, value interface{}) error { - err := read("user", key, value, &u) - if err != nil { - return errors.New("User doesn't exist") - } - return nil -} +// //Read user +// func (u *User) Read(key string, value interface{}) error { +// err := read("user", key, value, &u) +// if err != nil { +// return errors.New("User doesn't exist") +// } +// return nil +// } -//ReadAll users -func (u *User) ReadAll() ([]User, error) { - var users []User - var err error - err = readAll("user", "", nil, &users) - return users, err +// //ReadAll users +// func (u *User) ReadAll() ([]User, error) { +// var users []User +// var err error +// err = readAll("user", "", nil, &users) +// return users, err -} +// } -//Update user -func (u *User) Update() error { - return update("user", "_id", u.ID, &u) -} +// //Update user +// func (u *User) Update() error { +// return update("user", "_id", u.ID, &u) +// } -//Delete user -func (u *User) Delete(key string, value string) error { - err := delete("user", key, value) - return err -} +// //Delete user +// func (u *User) Delete(key string, value string) error { +// err := delete("user", key, value) +// return err +// } -//HasPermission check if a given user is admin or has a given permisssion -func (u *User) HasPermission(perm string) bool { - var group Group - //Check primary group - err := group.Read("_id", u.PrimaryGroup) - fmt.Println(group.Admin) - if err == nil && (group.Admin == true || group.Permissions[perm] == true) { +// //HasPermission check if a given user is admin or has a given permisssion +// func (u *User) HasPermission(perm string) bool { +// var group Group +// //Check primary group +// err := group.Read("_id", u.PrimaryGroup) +// fmt.Println(group.Admin) +// if err == nil && (group.Admin == true || group.Permissions[perm] == true) { - return true - } - //Check other groups - for id := range u.Groups { - err = group.Read("_id", id) - if err == nil && (group.Admin || group.Permissions[perm]) { - return true - } - } - return false -} +// return true +// } +// //Check other groups +// for id := range u.Groups { +// err = group.Read("_id", id) +// if err == nil && (group.Admin || group.Permissions[perm]) { +// return true +// } +// } +// return false +// } diff --git a/runner.conf b/runner.conf deleted file mode 100644 index 6d6a183..0000000 --- a/runner.conf +++ /dev/null @@ -1,14 +0,0 @@ -root: ./ -tmp_path: ./tmp -build_name: runner-build -build_log: runner-build-errors.log -valid_ext: .go, .tpl, .tmpl, .html, .ccs, .js, .toml -no_rebuild_ext: .tpl, .tmpl, .html -ignored: assets, tmp -build_delay: 600 -colors: 1 -log_color_main: cyan -log_color_build: yellow -log_color_runner: green -log_color_watcher: magenta -log_color_app: \ No newline at end of file diff --git a/tmp/build-errors.log b/tmp/build-errors.log new file mode 100644 index 0000000..4660a1c --- /dev/null +++ b/tmp/build-errors.log @@ -0,0 +1 @@ +exit status 1exit status 1 \ No newline at end of file