add user manage routes

This commit is contained in:
sentriz
2019-04-16 17:46:15 +01:00
parent 64fb0fdf82
commit 0d1c25a550
13 changed files with 234 additions and 106 deletions

View File

@@ -1,6 +1,7 @@
package main package main
import ( import (
"encoding/gob"
"log" "log"
"net/http" "net/http"
"time" "time"
@@ -35,9 +36,9 @@ func setSubsonicRoutes(mux *http.ServeMux) {
DB: dbCon, DB: dbCon,
} }
withWare := newChain( withWare := newChain(
cont.LogConnection, cont.WithLogging,
cont.EnableCORS, cont.WithCORS,
cont.CheckParameters, cont.WithValidSubsonicArgs,
) )
mux.HandleFunc("/rest/ping", withWare(cont.Ping)) mux.HandleFunc("/rest/ping", withWare(cont.Ping))
mux.HandleFunc("/rest/ping.view", withWare(cont.Ping)) mux.HandleFunc("/rest/ping.view", withWare(cont.Ping))
@@ -66,20 +67,30 @@ func setAdminRoutes(mux *http.ServeMux) {
DB: dbCon, DB: dbCon,
SStore: gormstore.New(dbCon, []byte("saynothinboys")), SStore: gormstore.New(dbCon, []byte("saynothinboys")),
} }
withWare := newChain( withBaseWare := newChain(
cont.LogConnection, cont.WithLogging,
cont.EnableCORS, )
withAuthWare := newChain(
withBaseWare,
cont.WithValidSession,
) )
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", withWare(cont.ServeLogin)) mux.HandleFunc("/admin/login", withBaseWare(cont.ServeLogin))
mux.HandleFunc("/admin/authenticate", withWare(cont.ServeAuthenticate)) mux.HandleFunc("/admin/login_do", withBaseWare(cont.ServeLoginDo))
mux.HandleFunc("/admin/home", withWare(cont.ServeHome)) mux.HandleFunc("/admin/logout", withAuthWare(cont.ServeLogout))
mux.HandleFunc("/admin/create_user", withWare(cont.ServeCreateUser)) mux.HandleFunc("/admin/home", withAuthWare(cont.ServeHome))
mux.HandleFunc("/admin/logout", withWare(cont.ServeLogout)) mux.HandleFunc("/admin/change_password", withAuthWare(cont.ServeChangePassword))
mux.HandleFunc("/admin/change_password_do", withBaseWare(cont.ServeChangePasswordDo))
mux.HandleFunc("/admin/create_user", withAuthWare(cont.ServeCreateUser))
mux.HandleFunc("/admin/create_user_do", withBaseWare(cont.ServeCreateUserDo))
} }
func main() { func main() {
// init stuff. needed to store the current user in
// the gorilla session
gob.Register(&db.User{})
// setup the subsonic and admin routes
address := ":5000" address := ":5000"
mux := http.NewServeMux() mux := http.NewServeMux()
setSubsonicRoutes(mux) setSubsonicRoutes(mux)

View File

@@ -1,8 +1,10 @@
package handler package handler
import ( import (
"fmt"
"net/http" "net/http"
"github.com/jinzhu/gorm"
"github.com/sentriz/gonic/db" "github.com/sentriz/gonic/db"
) )
@@ -11,14 +13,14 @@ func (c *Controller) ServeLogin(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, r, session, "login", &templateData{}) renderTemplate(w, r, session, "login", &templateData{})
} }
func (c *Controller) ServeAuthenticate(w http.ResponseWriter, r *http.Request) { func (c *Controller) ServeLoginDo(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic") session, _ := c.SStore.Get(r, "gonic")
username := r.FormValue("username") username := r.FormValue("username")
password := r.FormValue("password") password := r.FormValue("password")
if username == "" || password == "" { if username == "" || password == "" {
session.AddFlash("please provide both a username and password") session.AddFlash("please provide both a username and password")
session.Save(r, w) session.Save(r, w)
http.Redirect(w, r, "/admin/login", 303) http.Redirect(w, r, r.Header.Get("Referer"), 302)
return return
} }
var user db.User var user db.User
@@ -26,52 +28,107 @@ func (c *Controller) ServeAuthenticate(w http.ResponseWriter, r *http.Request) {
if !(username == user.Name && password == user.Password) { if !(username == user.Name && password == user.Password) {
session.AddFlash("invalid username / password") session.AddFlash("invalid username / password")
session.Save(r, w) session.Save(r, w)
http.Redirect(w, r, "/admin/login", 303) http.Redirect(w, r, r.Header.Get("Referer"), 302)
return return
} }
session.Values["authenticated"] = true session.Values["user"] = user
session.Values["user"] = user.ID
session.Save(r, w) session.Save(r, w)
http.Redirect(w, r, "/admin/home", 303) http.Redirect(w, r, "/admin/home", 303)
} }
func (c *Controller) ServeHome(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic")
authed, _ := session.Values["authenticated"].(bool)
if !authed {
session.AddFlash("you are not authenticated")
session.Save(r, w)
http.Redirect(w, r, "/admin/login", 303)
return
}
var data templateData
var user db.User
c.DB.First(&user, session.Values["user"])
data.UserID = user.ID
data.Username = user.Name
c.DB.Table("album_artists").Count(&data.ArtistCount)
c.DB.Table("albums").Count(&data.AlbumCount)
c.DB.Table("tracks").Count(&data.TrackCount)
c.DB.Find(&data.Users)
renderTemplate(w, r, session, "home", &data)
}
func (c *Controller) ServeCreateUser(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic")
authed, _ := session.Values["authenticated"].(bool)
if !authed {
session.AddFlash("you are not authenticated")
session.Save(r, w)
http.Redirect(w, r, "/admin/login", 303)
return
}
renderTemplate(w, r, session, "create_user", &templateData{})
}
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, _ := c.SStore.Get(r, "gonic")
delete(session.Values, "authenticated")
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) {
session, _ := c.SStore.Get(r, "gonic")
var data templateData
c.DB.Table("album_artists").Count(&data.ArtistCount)
c.DB.Table("albums").Count(&data.AlbumCount)
c.DB.Table("tracks").Count(&data.TrackCount)
c.DB.Find(&data.AllUsers)
renderTemplate(w, r, session, "home", &data)
}
func (c *Controller) ServeChangePassword(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic")
username := r.URL.Query().Get("user")
if username == "" {
http.Error(w, "please provide a username", 400)
return
}
var user db.User
err := c.DB.Where("name = ?", username).First(&user).Error
if gorm.IsRecordNotFoundError(err) {
http.Error(w, "couldn't find a user with that name", 400)
return
}
var data templateData
data.SelectedUser = &user
renderTemplate(w, r, session, "change_password", &data)
}
func (c *Controller) ServeChangePasswordDo(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic")
username := r.URL.Query().Get("user")
var user db.User
c.DB.Where("name = ?", username).First(&user)
password_one := r.FormValue("password_one")
password_two := r.FormValue("password_two")
if password_one == "" || password_two == "" {
session.AddFlash("please provide both passwords")
session.Save(r, w)
http.Redirect(w, r, r.Header.Get("Referer"), 302)
return
}
if !(password_one == password_two) {
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)
http.Redirect(w, r, "/admin/home", 303)
}
func (c *Controller) ServeCreateUser(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic")
renderTemplate(w, r, session, "create_user", &templateData{})
}
func (c *Controller) ServeCreateUserDo(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic")
username := r.FormValue("username")
password_one := r.FormValue("password_one")
password_two := r.FormValue("password_two")
if username == "" || password_one == "" || password_two == "" {
session.AddFlash("please fill out all fields")
session.Save(r, w)
http.Redirect(w, r, r.Header.Get("Referer"), 302)
return
}
if !(password_one == password_two) {
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 := db.User{
Name: username,
Password: password_one,
}
err := c.DB.Create(&user).Error
if err != nil {
session.AddFlash(fmt.Sprintf(
"could not create user `%s`: %v", username, err,
))
session.Save(r, w)
http.Redirect(w, r, r.Header.Get("Referer"), 302)
return
}
http.Redirect(w, r, "/admin/home", 303)
}

View File

@@ -25,17 +25,22 @@ var (
func init() { func init() {
templates["login"] = template.Must(template.ParseFiles( templates["login"] = template.Must(template.ParseFiles(
filepath.Join("templates", "layout.tmpl"), filepath.Join("templates", "layout.tmpl"),
filepath.Join("templates", "admin", "login.tmpl"), filepath.Join("templates", "pages", "login.tmpl"),
)) ))
templates["home"] = template.Must(template.ParseFiles( templates["home"] = 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", "admin", "home.tmpl"), filepath.Join("templates", "pages", "home.tmpl"),
)) ))
templates["create_user"] = template.Must(template.ParseFiles( templates["create_user"] = 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", "admin", "create_user.tmpl"), filepath.Join("templates", "pages", "create_user.tmpl"),
))
templates["change_password"] = template.Must(template.ParseFiles(
filepath.Join("templates", "layout.tmpl"),
filepath.Join("templates", "user.tmpl"),
filepath.Join("templates", "pages", "change_password.tmpl"),
)) ))
} }
@@ -46,13 +51,13 @@ type Controller struct {
} }
type templateData struct { type templateData struct {
Flashes []interface{} Flashes []interface{}
UserID uint User *db.User
Username string SelectedUser *db.User
ArtistCount uint AllUsers []*db.User
AlbumCount uint ArtistCount uint
TrackCount uint AlbumCount uint
Users []*db.User TrackCount uint
} }
func getStrParam(r *http.Request, key string) string { func getStrParam(r *http.Request, key string) string {
@@ -127,9 +132,15 @@ 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) { s *sessions.Session, name string, data *templateData) {
flashes := s.Flashes() // take the flashes from the session and add to template
data.Flashes = s.Flashes()
s.Save(r, w) s.Save(r, w)
data.Flashes = flashes // 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
userIntf := s.Values["user"]
if userIntf != nil {
data.User = s.Values["user"].(*db.User)
}
err := templates[name].ExecuteTemplate(w, "layout", data) err := templates[name].ExecuteTemplate(w, "layout", data)
if err != nil { if err != nil {
http.Error(w, fmt.Sprintf("500 when executing: %v", err), 500) http.Error(w, fmt.Sprintf("500 when executing: %v", err), 500)

View File

@@ -30,14 +30,14 @@ func checkCredentialsBasic(password, givenPassword string) bool {
return password == givenPassword return password == givenPassword
} }
func (c *Controller) LogConnection(next http.HandlerFunc) http.HandlerFunc { func (c *Controller) WithLogging(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
log.Printf("connection from `%s` for `%s`", r.RemoteAddr, r.URL) log.Printf("connection from `%s` for `%s`", r.RemoteAddr, r.URL)
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
} }
} }
func (c *Controller) CheckParameters(next http.HandlerFunc) http.HandlerFunc { func (c *Controller) WithValidSubsonicArgs(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
for _, req := range requiredParameters { for _, req := range requiredParameters {
param := r.URL.Query().Get(req) param := r.URL.Query().Get(req)
@@ -83,7 +83,7 @@ func (c *Controller) CheckParameters(next http.HandlerFunc) http.HandlerFunc {
} }
} }
func (c *Controller) EnableCORS(next http.HandlerFunc) http.HandlerFunc { func (c *Controller) WithCORS(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", w.Header().Set("Access-Control-Allow-Methods",
@@ -98,3 +98,17 @@ func (c *Controller) EnableCORS(next http.HandlerFunc) http.HandlerFunc {
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
} }
} }
func (c *Controller) WithValidSession(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
session, _ := c.SStore.Get(r, "gonic")
user, _ := session.Values["user"]
if user == nil {
session.AddFlash("you are not authenticated")
session.Save(r, w)
http.Redirect(w, r, "/admin/login", 303)
return
}
next.ServeHTTP(w, r)
}
}

View File

@@ -1,3 +1,16 @@
/* reset from awsm */
form input[type], form select, form textarea {
margin-bottom: 0;
}
/* reset from awsm */
form {
max-width: 400px;
margin-left: auto;
margin-right: 0;
}
/* reset from awsm */
div { div {
margin: 0; margin: 0;
padding: 0; padding: 0;
@@ -12,12 +25,13 @@ body {
justify-content: space-between; justify-content: space-between;
} }
form {
max-width: unset; form input[type=password], form input[type=text] {
margin-bottom: 0.25rem;
} }
#content > * { #content > * {
margin: 1rem 0; margin: 2rem 0;
} }
.right { .right {
@@ -40,13 +54,15 @@ form {
background-color: #0000000a; background-color: #0000000a;
} }
.box-title {
margin-bottom: 0.5rem;
}
.padded { .padded {
padding: 1rem; padding: 1rem;
} }
#header { #header {
/* background-color: #fdc71b08; */
background-image: linear-gradient(white, #fdad1b0d);
border-bottom: 1px solid; border-bottom: 1px solid;
padding-top: 3rem; padding-top: 3rem;
} }
@@ -63,7 +79,7 @@ form {
} }
#flashes { #flashes {
background-color: #fd1b1b29; background-color: #fd1b1b1c;
} }
#login-form { #login-form {

View File

@@ -1,12 +0,0 @@
{{ define "title" }}home{{ end }}
{{ define "user" }}
<div class="padded box mono">
<div>
<span><u>create new user</u></span>
</div>
<div class="right">
<span class="pre">howdy</span><br/>
</div>
</div>
{{ end }}

View File

@@ -1,12 +0,0 @@
{{ define "title" }}gonic{{ end }}
{{ define "content" }}
<div class="light">
<span>login</span>
</div>
<form id="login-form" action="/admin/authenticate" method="post">
<input type="text" id="username" name="username" placeholder="username">
<input type="password" id="password" name="password" placeholder="password">
<input type="submit" value="login">
</form>
{{ end }}

View File

@@ -15,7 +15,7 @@
</div> </div>
<div id="content"> <div id="content">
{{ if .Flashes }} {{ if .Flashes }}
<div id="flashes"> <div id="flashes" class="padded mono">
<p><b>warning:</b> {{ index .Flashes 0 }}</p> <p><b>warning:</b> {{ index .Flashes 0 }}</p>
</div> </div>
{{ end }} {{ end }}

View File

@@ -0,0 +1,14 @@
{{ define "title" }}home{{ end }}
{{ define "user" }}
<div class="padded box mono">
<div class="box-title">
<span><u>changing {{ .SelectedUser.Name }}'s password</u></span>
</div>
<form id="login-form" action="/admin/change_password_do?user={{ .SelectedUser.Name }}" 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

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

View File

@@ -2,7 +2,7 @@
{{ define "user" }} {{ define "user" }}
<div class="padded box mono"> <div class="padded box mono">
<div> <div class="box-title">
<span><u>stats</u></span> <span><u>stats</u></span>
</div> </div>
<div class="right"> <div class="right">
@@ -12,20 +12,20 @@
</div> </div>
</div> </div>
<div class="padded box mono"> <div class="padded box mono">
<div> <div class="box-title">
<span><u>last.fm</u></span> <span><u>last fm</u></span>
</div> </div>
<div class="right"> <div class="right">
<span class="pre">unlinked</span><br/> <span class="pre">unlinked</span><br/>
</div> </div>
</div> </div>
<div class="padded box mono"> <div class="padded box mono">
<div> <div class="box-title">
<span><u>users</u></span> <span><u>users</u></span>
</div> </div>
<div class="right"> <div class="right">
{{ range $user := .Users }} {{ range $user := .AllUsers }}
<span class="pre">{{ $user.Name }} <span class="light">created</span> <u>{{ $user.CreatedAt.Format "Jan 02, 2006" }}</u> <a href="/admin/change_password">change password</a></span><br/> <span class="pre">{{ $user.Name }} <span class="light">created</span> <u>{{ $user.CreatedAt.Format "Jan 02, 2006" }}</u> <a href="/admin/change_password?user={{ $user.Name }}">change password</a></span><br/>
{{ end }} {{ end }}
<br> <br>
<a href="/admin/create_user" class="button">create new</a> <a href="/admin/create_user" class="button">create new</a>

View File

@@ -0,0 +1,14 @@
{{ define "title" }}gonic{{ end }}
{{ define "content" }}
<div class="padded box mono">
<div class="box-title">
<span><u>please login</u></span>
</div>
<form id="login-form" action="/admin/login_do" method="post">
<input type="text" id="username" name="username" placeholder="username">
<input type="password" id="password" name="password" placeholder="password">
<input type="submit" value="login">
</form>
</div>
{{ end }}

View File

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