refactor validation and add admin system

This commit is contained in:
sentriz
2019-04-17 17:33:47 +01:00
parent 0d1c25a550
commit 9f6cd20f5a
11 changed files with 169 additions and 68 deletions

View File

@@ -197,10 +197,11 @@ func main() {
orm.FirstOrCreate(&db.User{}, db.User{ orm.FirstOrCreate(&db.User{}, db.User{
Name: "admin", Name: "admin",
Password: "admin", Password: "admin",
IsAdmin: true,
}) })
orm.FirstOrCreate(&db.User{}, db.User{ orm.FirstOrCreate(&db.User{}, db.User{
Name: "senan", Name: "stephen",
Password: "password", Password: "stephen",
}) })
startTime := time.Now() startTime := time.Now()
tx = orm.Begin() tx = orm.Begin()

View File

@@ -65,25 +65,32 @@ func setSubsonicRoutes(mux *http.ServeMux) {
func setAdminRoutes(mux *http.ServeMux) { func setAdminRoutes(mux *http.ServeMux) {
cont := handler.Controller{ cont := handler.Controller{
DB: dbCon, DB: dbCon,
SStore: gormstore.New(dbCon, []byte("saynothinboys")), SStore: gormstore.New(dbCon, []byte("saynothinboys")), // TODO: not this
} }
withBaseWare := newChain( withPublicWare := newChain(
cont.WithLogging, cont.WithLogging,
cont.WithSession,
) )
withAuthWare := newChain( withUserWare := newChain(
withBaseWare, withPublicWare,
cont.WithValidSession, cont.WithUserSession,
)
withAdminWare := newChain(
withUserWare,
cont.WithAdminSession,
) )
server := http.FileServer(http.Dir("static")) server := http.FileServer(http.Dir("static"))
mux.Handle("/admin/static/", http.StripPrefix("/admin/static/", server)) mux.Handle("/admin/static/", http.StripPrefix("/admin/static/", server))
mux.HandleFunc("/admin/login", withBaseWare(cont.ServeLogin)) mux.HandleFunc("/admin/login", withPublicWare(cont.ServeLogin))
mux.HandleFunc("/admin/login_do", withBaseWare(cont.ServeLoginDo)) mux.HandleFunc("/admin/login_do", withPublicWare(cont.ServeLoginDo))
mux.HandleFunc("/admin/logout", withAuthWare(cont.ServeLogout)) mux.HandleFunc("/admin/logout", withUserWare(cont.ServeLogout))
mux.HandleFunc("/admin/home", withAuthWare(cont.ServeHome)) mux.HandleFunc("/admin/home", withUserWare(cont.ServeHome))
mux.HandleFunc("/admin/change_password", withAuthWare(cont.ServeChangePassword)) mux.HandleFunc("/admin/change_own_password", withUserWare(cont.ServeChangeOwnPassword))
mux.HandleFunc("/admin/change_password_do", withBaseWare(cont.ServeChangePasswordDo)) mux.HandleFunc("/admin/change_own_password_do", withUserWare(cont.ServeChangeOwnPasswordDo))
mux.HandleFunc("/admin/create_user", withAuthWare(cont.ServeCreateUser)) mux.HandleFunc("/admin/change_password", withAdminWare(cont.ServeChangePassword))
mux.HandleFunc("/admin/create_user_do", withBaseWare(cont.ServeCreateUserDo)) mux.HandleFunc("/admin/change_password_do", withAdminWare(cont.ServeChangePasswordDo))
mux.HandleFunc("/admin/create_user", withAdminWare(cont.ServeCreateUser))
mux.HandleFunc("/admin/create_user_do", withAdminWare(cont.ServeCreateUserDo))
} }
func main() { func main() {

View File

@@ -53,4 +53,5 @@ type User struct {
Base Base
Name string `gorm:"not null;unique_index"` Name string `gorm:"not null;unique_index"`
Password string Password string
IsAdmin bool
} }

View File

@@ -4,17 +4,18 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"github.com/gorilla/sessions"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"github.com/sentriz/gonic/db" "github.com/sentriz/gonic/db"
"github.com/sentriz/gonic/handler/utilities"
) )
func (c *Controller) ServeLogin(w http.ResponseWriter, r *http.Request) { func (c *Controller) ServeLogin(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic") renderTemplate(w, r, "login", nil)
renderTemplate(w, r, session, "login", &templateData{})
} }
func (c *Controller) ServeLoginDo(w http.ResponseWriter, r *http.Request) { func (c *Controller) ServeLoginDo(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic") session := r.Context().Value("session").(*sessions.Session)
username := r.FormValue("username") username := r.FormValue("username")
password := r.FormValue("password") password := r.FormValue("password")
if username == "" || password == "" { if username == "" || password == "" {
@@ -37,24 +38,43 @@ func (c *Controller) ServeLoginDo(w http.ResponseWriter, r *http.Request) {
} }
func (c *Controller) ServeLogout(w http.ResponseWriter, r *http.Request) { func (c *Controller) ServeLogout(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic") session := r.Context().Value("session").(*sessions.Session)
delete(session.Values, "user") delete(session.Values, "user")
session.Save(r, w) session.Save(r, w)
http.Redirect(w, r, "/admin/login", 303) http.Redirect(w, r, "/admin/login", 303)
} }
func (c *Controller) ServeHome(w http.ResponseWriter, r *http.Request) { func (c *Controller) ServeHome(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic")
var data templateData var data templateData
c.DB.Table("album_artists").Count(&data.ArtistCount) c.DB.Table("album_artists").Count(&data.ArtistCount)
c.DB.Table("albums").Count(&data.AlbumCount) c.DB.Table("albums").Count(&data.AlbumCount)
c.DB.Table("tracks").Count(&data.TrackCount) c.DB.Table("tracks").Count(&data.TrackCount)
c.DB.Find(&data.AllUsers) c.DB.Find(&data.AllUsers)
renderTemplate(w, r, session, "home", &data) renderTemplate(w, r, "home", &data)
}
func (c *Controller) ServeChangeOwnPassword(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, r, "change_own_password", nil)
}
func (c *Controller) ServeChangeOwnPasswordDo(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*sessions.Session)
passwordOne := r.FormValue("password_one")
passwordTwo := r.FormValue("password_two")
err := utilities.ValidatePasswords(passwordOne, passwordTwo)
if err != nil {
session.AddFlash(err.Error())
session.Save(r, w)
http.Redirect(w, r, r.Header.Get("Referer"), 302)
return
}
user, _ := session.Values["user"].(*db.User)
user.Password = passwordOne
c.DB.Save(user)
http.Redirect(w, r, "/admin/home", 303)
} }
func (c *Controller) ServeChangePassword(w http.ResponseWriter, r *http.Request) { func (c *Controller) ServeChangePassword(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic")
username := r.URL.Query().Get("user") username := r.URL.Query().Get("user")
if username == "" { if username == "" {
http.Error(w, "please provide a username", 400) http.Error(w, "please provide a username", 400)
@@ -68,60 +88,56 @@ func (c *Controller) ServeChangePassword(w http.ResponseWriter, r *http.Request)
} }
var data templateData var data templateData
data.SelectedUser = &user data.SelectedUser = &user
renderTemplate(w, r, session, "change_password", &data) renderTemplate(w, r, "change_password", &data)
} }
func (c *Controller) ServeChangePasswordDo(w http.ResponseWriter, r *http.Request) { func (c *Controller) ServeChangePasswordDo(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic") session := r.Context().Value("session").(*sessions.Session)
username := r.URL.Query().Get("user") username := r.URL.Query().Get("user")
var user db.User var user db.User
c.DB.Where("name = ?", username).First(&user) c.DB.Where("name = ?", username).First(&user)
password_one := r.FormValue("password_one") passwordOne := r.FormValue("password_one")
password_two := r.FormValue("password_two") passwordTwo := r.FormValue("password_two")
if password_one == "" || password_two == "" { err := utilities.ValidatePasswords(passwordOne, passwordTwo)
session.AddFlash("please provide both passwords") if err != nil {
session.AddFlash(err.Error())
session.Save(r, w) session.Save(r, w)
http.Redirect(w, r, r.Header.Get("Referer"), 302) http.Redirect(w, r, r.Header.Get("Referer"), 302)
return return
} }
if !(password_one == password_two) { user.Password = passwordOne
session.AddFlash("the two passwords entered were not the same")
session.Save(r, w)
http.Redirect(w, r, r.Header.Get("Referer"), 302)
return
}
user.Password = password_one
c.DB.Save(&user) c.DB.Save(&user)
http.Redirect(w, r, "/admin/home", 303) http.Redirect(w, r, "/admin/home", 303)
} }
func (c *Controller) ServeCreateUser(w http.ResponseWriter, r *http.Request) { func (c *Controller) ServeCreateUser(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic") renderTemplate(w, r, "create_user", nil)
renderTemplate(w, r, session, "create_user", &templateData{})
} }
func (c *Controller) ServeCreateUserDo(w http.ResponseWriter, r *http.Request) { func (c *Controller) ServeCreateUserDo(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic") session := r.Context().Value("session").(*sessions.Session)
username := r.FormValue("username") username := r.FormValue("username")
password_one := r.FormValue("password_one") err := utilities.ValidateUsername(username)
password_two := r.FormValue("password_two") if err != nil {
if username == "" || password_one == "" || password_two == "" { session.AddFlash(err.Error())
session.AddFlash("please fill out all fields")
session.Save(r, w) session.Save(r, w)
http.Redirect(w, r, r.Header.Get("Referer"), 302) http.Redirect(w, r, r.Header.Get("Referer"), 302)
return return
} }
if !(password_one == password_two) { passwordOne := r.FormValue("password_one")
session.AddFlash("the two passwords entered were not the same") passwordTwo := r.FormValue("password_two")
err = utilities.ValidatePasswords(passwordOne, passwordTwo)
if err != nil {
session.AddFlash(err.Error())
session.Save(r, w) session.Save(r, w)
http.Redirect(w, r, r.Header.Get("Referer"), 302) http.Redirect(w, r, r.Header.Get("Referer"), 302)
return return
} }
user := db.User{ user := db.User{
Name: username, Name: username,
Password: password_one, Password: passwordOne,
} }
err := c.DB.Create(&user).Error err = c.DB.Create(&user).Error
if err != nil { if err != nil {
session.AddFlash(fmt.Sprintf( session.AddFlash(fmt.Sprintf(
"could not create user `%s`: %v", username, err, "could not create user `%s`: %v", username, err,

View File

@@ -32,22 +32,26 @@ func init() {
filepath.Join("templates", "user.tmpl"), filepath.Join("templates", "user.tmpl"),
filepath.Join("templates", "pages", "home.tmpl"), filepath.Join("templates", "pages", "home.tmpl"),
)) ))
templates["create_user"] = template.Must(template.ParseFiles(
filepath.Join("templates", "layout.tmpl"),
filepath.Join("templates", "user.tmpl"),
filepath.Join("templates", "pages", "create_user.tmpl"),
))
templates["change_password"] = template.Must(template.ParseFiles( templates["change_password"] = template.Must(template.ParseFiles(
filepath.Join("templates", "layout.tmpl"), filepath.Join("templates", "layout.tmpl"),
filepath.Join("templates", "user.tmpl"), filepath.Join("templates", "user.tmpl"),
filepath.Join("templates", "pages", "change_password.tmpl"), filepath.Join("templates", "pages", "change_password.tmpl"),
)) ))
templates["change_own_password"] = template.Must(template.ParseFiles(
filepath.Join("templates", "layout.tmpl"),
filepath.Join("templates", "user.tmpl"),
filepath.Join("templates", "pages", "change_own_password.tmpl"),
))
templates["create_user"] = template.Must(template.ParseFiles(
filepath.Join("templates", "layout.tmpl"),
filepath.Join("templates", "user.tmpl"),
filepath.Join("templates", "pages", "create_user.tmpl"),
))
} }
type Controller struct { type Controller struct {
DB *gorm.DB DB *gorm.DB
SStore *gormstore.Store SStore *gormstore.Store
Templates map[string]*template.Template
} }
type templateData struct { type templateData struct {
@@ -131,15 +135,16 @@ func respondError(w http.ResponseWriter, r *http.Request,
} }
func renderTemplate(w http.ResponseWriter, r *http.Request, func renderTemplate(w http.ResponseWriter, r *http.Request,
s *sessions.Session, name string, data *templateData) { name string, data *templateData) {
// take the flashes from the session and add to template session := r.Context().Value("session").(*sessions.Session)
data.Flashes = s.Flashes() if data == nil {
s.Save(r, w) data = &templateData{}
// take the user gob from the session (if we're logged in and }
// it's there) cast to a user and add to the template data.Flashes = session.Flashes()
userIntf := s.Values["user"] session.Save(r, w)
if userIntf != nil { user, ok := session.Values["user"].(*db.User)
data.User = s.Values["user"].(*db.User) if ok {
data.User = user
} }
err := templates[name].ExecuteTemplate(w, "layout", data) err := templates[name].ExecuteTemplate(w, "layout", data)
if err != nil { if err != nil {

View File

@@ -1,12 +1,14 @@
package handler package handler
import ( import (
"context"
"crypto/md5" "crypto/md5"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"log" "log"
"net/http" "net/http"
"github.com/gorilla/sessions"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"github.com/sentriz/gonic/db" "github.com/sentriz/gonic/db"
) )
@@ -99,16 +101,41 @@ func (c *Controller) WithCORS(next http.HandlerFunc) http.HandlerFunc {
} }
} }
func (c *Controller) WithValidSession(next http.HandlerFunc) http.HandlerFunc { func (c *Controller) WithSession(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic") session, _ := c.SStore.Get(r, "gonic")
user, _ := session.Values["user"] withSession := context.WithValue(r.Context(), "session", session)
if user == nil { next.ServeHTTP(w, r.WithContext(withSession))
}
}
func (c *Controller) WithUserSession(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// session exists at this point
session := r.Context().Value("session").(*sessions.Session)
_, ok := session.Values["user"]
if !ok {
session.AddFlash("you are not authenticated") session.AddFlash("you are not authenticated")
session.Save(r, w) session.Save(r, w)
http.Redirect(w, r, "/admin/login", 303) http.Redirect(w, r, "/admin/login", 303)
return return
} }
withSession := context.WithValue(r.Context(), "session", session)
next.ServeHTTP(w, r.WithContext(withSession))
}
}
func (c *Controller) WithAdminSession(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// session and user exist at this point
session := r.Context().Value("session").(*sessions.Session)
user := session.Values["user"].(*db.User)
if !user.IsAdmin {
session.AddFlash("you are not an admin")
session.Save(r, w)
http.Redirect(w, r, "/admin/login", 303)
return
}
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
} }
} }

View File

@@ -0,0 +1,20 @@
package utilities
import "fmt"
func ValidateUsername(username string) error {
if username == "" {
return fmt.Errorf("please enter the username")
}
return nil
}
func ValidatePasswords(pOne, pTwo string) error {
if pOne == "" || pTwo == "" {
return fmt.Errorf("please enter the password twice")
}
if !(pOne == pTwo) {
return fmt.Errorf("the two passwords entered were not the same")
}
return nil
}

View File

@@ -73,7 +73,6 @@ form input[type=password], form input[type=text] {
} }
#footer { #footer {
background-color: #fdad1b0d;
border-top: 1px solid; border-top: 1px solid;
text-align: right; text-align: right;
} }

View File

@@ -0,0 +1,14 @@
{{ define "title" }}home{{ end }}
{{ define "user" }}
<div class="padded box mono">
<div class="box-title">
<span><u>changing account password</u></span>
</div>
<form id="login-form" action="/admin/change_own_password_do" method="post">
<input type="password" id="password_one" name="password_one" placeholder="new password">
<input type="password" id="password_two" name="password_two" placeholder="verify new password">
<input type="submit" value="change">
</form>
</div>
{{ end }}

View File

@@ -20,6 +20,8 @@
</div> </div>
</div> </div>
<div class="padded box mono"> <div class="padded box mono">
{{ if .User.IsAdmin }}
{{/* admin panel to manage all users */}}
<div class="box-title"> <div class="box-title">
<span><u>users</u></span> <span><u>users</u></span>
</div> </div>
@@ -30,5 +32,14 @@
<br> <br>
<a href="/admin/create_user" class="button">create new</a> <a href="/admin/create_user" class="button">create new</a>
</div> </div>
{{ else }}
{{/* user panel to manage themselves */}}
<div class="box-title">
<span><u>your account</u></span>
</div>
<div class="right">
<a href="/admin/change_own_password" class="button">change password</a>
</div>
{{ end }}
</div> </div>
{{ end }} {{ end }}

View File

@@ -2,7 +2,7 @@
{{ define "content" }} {{ define "content" }}
<div class="light right"> <div class="light right">
<span>welcome <u>{{ .User.Name }}</u> &#124; <a href="/admin/logout">logout</a></span> <span>welcome <u>{{ .User.Name }}</u> &#124; <a href="/admin/home">home</a> &#124; <a href="/admin/logout">logout</a></span>
</div> </div>
{{ template "user" . }} {{ template "user" . }}
{{ end }} {{ end }}