otfe/controllers/user.go

92 lines
2.1 KiB
Go
Raw Normal View History

2022-02-23 12:07:09 +00:00
package controllers
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"
)
type userData struct {
Title string
Users []models.User
User models.User
}
//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")
}
//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")
}
//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)
}
//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) {
}
//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)
}