diff --git a/cmd/server/main.go b/cmd/server/main.go
index 58256fab291203cc3c2a8b7644559e8e6fa1bf2f..41b2b4a781170e387e42db4d187b3ff91fbfd7d5 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -72,7 +72,7 @@ if err != nil {
panic("failed to decode key database: " + err.Error())
}
- r := mux.NewRouter()
+ r := mux.NewRouter().StrictSlash(false)
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.FS(static.Static))))
// repository
@@ -85,7 +85,7 @@ )
// middleware
var (
- authMiddleware = ext.NewAuthMiddleware(baseKey, logger.WithField("context", "auth"))
+ authMiddleware = ext.NewAuthMiddleware(baseKey, logger.WithField("context", "auth"), userRepository)
logMiddleware = ext.NewLogMiddleare(logger.WithField("context", "http"))
initialMiddleware = ext.NewInitialSetupMiddleware(userRepository)
)
diff --git a/pkg/database/sql/user.go b/pkg/database/sql/user.go
index 2ec86229435c1508c25f5b67f98178a6cfd67647..0c503c2e3c8ea8d30ca2fb70679644e168cb49d4 100644
--- a/pkg/database/sql/user.go
+++ b/pkg/database/sql/user.go
@@ -158,20 +158,16 @@ return user.Model.ID, nil
}
func (self *UserRepository) Update(ctx context.Context, id uint, update *repository.UpdateUser) error {
- user := &User{
- Model: gorm.Model{
- ID: id,
- },
- Username: update.Username,
- Name: update.Name,
- IsAdmin: update.IsAdmin,
- Path: update.Path,
- }
-
result := self.db.
WithContext(ctx).
+ Model(&User{}).
Omit("password").
- Updates(user)
+ Where("id = ?", id).
+ Update("username", update.Username).
+ Update("name", update.Name).
+ Update("is_admin", update.IsAdmin).
+ Update("path", update.Path)
+
if result.Error != nil {
return wrapError(result.Error)
}
diff --git a/pkg/ext/middleware.go b/pkg/ext/middleware.go
index 061cf7cfb849699600e614d2aa7491b8736ef0b0..6a94c4f9442ed01ba1a98eb375b3c106aeda81e5 100644
--- a/pkg/ext/middleware.go
+++ b/pkg/ext/middleware.go
@@ -20,9 +20,17 @@ next(w, r)
}
}
-type LogMiddleware struct {
- entry *logrus.Entry
-}
+type (
+ User string
+
+ LogMiddleware struct {
+ entry *logrus.Entry
+ }
+)
+
+const (
+ UserKey User = "user"
+)
func NewLogMiddleare(log *logrus.Entry) *LogMiddleware {
return &LogMiddleware{
@@ -43,14 +51,20 @@ }
}
type AuthMiddleware struct {
- key []byte
- entry *logrus.Entry
+ key []byte
+ entry *logrus.Entry
+ userRepository repository.UserRepository
}
-func NewAuthMiddleware(key []byte, log *logrus.Entry) *AuthMiddleware {
+func NewAuthMiddleware(
+ key []byte,
+ log *logrus.Entry,
+ userRepository repository.UserRepository,
+) *AuthMiddleware {
return &AuthMiddleware{
- key: key,
- entry: log.WithField("context", "auth"),
+ key: key,
+ entry: log.WithField("context", "auth"),
+ userRepository: userRepository,
}
}
@@ -82,7 +96,14 @@ a.entry.Error(err)
http.Redirect(w, r, redirectLogin, http.StatusTemporaryRedirect)
return
}
- r = r.WithContext(context.WithValue(r.Context(), service.TokenKey, token))
+
+ user, err := a.userRepository.Get(r.Context(), token.UserID)
+ if err != nil {
+ a.entry.Error(err)
+ return
+ }
+
+ r = r.WithContext(context.WithValue(r.Context(), UserKey, user))
a.entry.
WithField("userID", token.UserID).
WithField("username", token.Username).
@@ -91,9 +112,9 @@ next(w, r)
}
}
-func GetTokenFromCtx(r *http.Request) *service.Token {
- tokenValue := r.Context().Value(service.TokenKey)
- if token, ok := tokenValue.(*service.Token); ok {
+func GetUserFromCtx(r *http.Request) *repository.User {
+ tokenValue := r.Context().Value(UserKey)
+ if token, ok := tokenValue.(*repository.User); ok {
return token
}
return nil
@@ -113,7 +134,7 @@ func (i *InitialSetupMiddleware) Check(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// if user has been set to context it is logged in already
- token := GetTokenFromCtx(r)
+ token := GetUserFromCtx(r)
if token != nil {
next(w, r)
return
diff --git a/pkg/ext/responses.go b/pkg/ext/responses.go
index 34e5f278bf1d8e22dc9af9a9fd2584060b81abb1..d8941e8d6df1cb819a90e2834b6d4ffeca28e826 100644
--- a/pkg/ext/responses.go
+++ b/pkg/ext/responses.go
@@ -10,12 +10,12 @@
func NotFound(w http.ResponseWriter) {
templates.WritePageTemplate(w, &templates.ErrorPage{
Err: "Not Found",
- })
+ }, false)
}
func InternalServerError(w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusInternalServerError)
templates.WritePageTemplate(w, &templates.ErrorPage{
Err: fmt.Sprintf("Internal Server Error:\n%s", err.Error()),
- })
+ }, false)
}
diff --git a/pkg/service/auth.go b/pkg/service/auth.go
index 2fc06e383f8f34d2e1ac843d1d48fb1930c6f80a..3811965cf321f71b95522f89d3dc9bf56883fea7 100644
--- a/pkg/service/auth.go
+++ b/pkg/service/auth.go
@@ -147,14 +147,11 @@ return err
}
type (
- AuthKey string
- Token struct {
+ Token struct {
UserID uint
Username string
}
)
-
-const TokenKey AuthKey = "token"
func ReadToken(data []byte, key []byte) (*Token, error) {
block, err := aes.NewCipher(key)
diff --git a/pkg/view/album.go b/pkg/view/album.go
index b19e381bb5008ca4468fc6bd5f7b492ab07d8148..e0ee4053fc724ca3c79404f036b84ebe63218996 100644
--- a/pkg/view/album.go
+++ b/pkg/view/album.go
@@ -30,10 +30,10 @@ }
func (self *AlbumView) Index(w http.ResponseWriter, r *http.Request) error {
p := getPagination(r)
- token := ext.GetTokenFromCtx(r)
+ user := ext.GetUserFromCtx(r)
// TODO: optmize call, GetPathFromUserID may no be necessary
- userPath, err := self.userRepository.GetPathFromUserID(r.Context(), token.UserID)
+ userPath, err := self.userRepository.GetPathFromUserID(r.Context(), user.ID)
if err != nil {
return err
}
@@ -91,12 +91,12 @@ },
Settings: settings,
}
- templates.WritePageTemplate(w, page)
+ templates.WritePageTemplate(w, page, user.IsAdmin)
return nil
}
func (self *AlbumView) SetMyselfIn(r *ext.Router) {
- r.GET("/album/", self.Index)
- r.POST("/album/", self.Index)
+ r.GET("/album", self.Index)
+ r.POST("/album", self.Index)
}
diff --git a/pkg/view/auth.go b/pkg/view/auth.go
index 8d870352e8b7220c8df36582adaeeab7beb054b1..318d0a33ff2bd4a3ef106b71b7334cd4e5af1117 100644
--- a/pkg/view/auth.go
+++ b/pkg/view/auth.go
@@ -20,8 +20,8 @@ userController: userController,
}
}
-func (v *AuthView) LoginView(w http.ResponseWriter, _ *http.Request) error {
- templates.WritePageTemplate(w, &templates.LoginPage{})
+func (v *AuthView) LoginView(w http.ResponseWriter, r *http.Request) error {
+ templates.WritePageTemplate(w, &templates.LoginPage{}, false)
return nil
}
@@ -46,12 +46,15 @@ password = []byte(r.FormValue("password"))
)
auth, err := v.userController.Login(r.Context(), username, password)
+ if err != nil {
+ return err
+ }
if errors.Is(err, service.InvalidLogin) {
templates.WritePageTemplate(w, &templates.LoginPage{
Username: r.FormValue("username"),
Err: err.Error(),
- })
+ }, false)
return nil
}
@@ -82,8 +85,8 @@ func Index(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
}
-func (v *AuthView) InitialRegisterView(w http.ResponseWriter, _ *http.Request) error {
- templates.WritePageTemplate(w, &templates.RegisterPage{})
+func (v *AuthView) InitialRegisterView(w http.ResponseWriter, r *http.Request) error {
+ templates.WritePageTemplate(w, &templates.RegisterPage{}, false)
return nil
}
diff --git a/pkg/view/filesystem.go b/pkg/view/filesystem.go
index 24f0ce61e6d169b2406b7081feeb965377b63036..9071ec0e0cc95d53713c5e753d5a942539db8fec 100644
--- a/pkg/view/filesystem.go
+++ b/pkg/view/filesystem.go
@@ -34,10 +34,10 @@
func (self *FileSystemView) Index(w http.ResponseWriter, r *http.Request) error {
var (
pathValue = r.FormValue("path")
- token = ext.GetTokenFromCtx(r)
+ user = ext.GetUserFromCtx(r)
)
- page, err := self.fsService.GetPage(r.Context(), token.UserID, pathValue)
+ page, err := self.fsService.GetPage(r.Context(), user.ID, pathValue)
if err != nil {
return err
}
@@ -51,7 +51,7 @@ templates.WritePageTemplate(w, &templates.FilePage{
Page: page,
ShowMode: settings.ShowMode,
ShowOwner: settings.ShowOwner,
- })
+ }, user.IsAdmin)
return nil
}
@@ -59,6 +59,6 @@
func (self *FileSystemView) SetMyselfIn(r *ext.Router) {
r.GET("/", self.Index)
r.POST("/", self.Index)
- r.GET("/fs/", self.Index)
- r.POST("/fs/", self.Index)
+ r.GET("/fs", self.Index)
+ r.POST("/fs", self.Index)
}
diff --git a/pkg/view/media.go b/pkg/view/media.go
index 3041998f465d49976d644a3a8b83f292ebe8cb87..8a10fe0792a75afa70e81bd0cc05b080012c4c80 100644
--- a/pkg/view/media.go
+++ b/pkg/view/media.go
@@ -71,9 +71,9 @@ }
func (self *MediaView) Index(w http.ResponseWriter, r *http.Request) error {
p := getPagination(r)
- token := ext.GetTokenFromCtx(r)
+ user := ext.GetUserFromCtx(r)
- userPath, err := self.userRepository.GetPathFromUserID(r.Context(), token.UserID)
+ userPath, err := self.userRepository.GetPathFromUserID(r.Context(), user.ID)
if err != nil {
return err
}
@@ -98,7 +98,7 @@ },
Settings: settings,
}
- templates.WritePageTemplate(w, page)
+ templates.WritePageTemplate(w, page, user.IsAdmin)
return nil
}
@@ -132,9 +132,9 @@ return nil
}
func (self *MediaView) SetMyselfIn(r *ext.Router) {
- r.GET("/media/", self.Index)
- r.POST("/media/", self.Index)
+ r.GET("/media", self.Index)
+ r.POST("/media", self.Index)
- r.GET("/media/image/", self.GetImage)
- r.GET("/media/thumbnail/", self.GetThumbnail)
+ r.GET("/media/image", self.GetImage)
+ r.GET("/media/thumbnail", self.GetThumbnail)
}
diff --git a/pkg/view/settings.go b/pkg/view/settings.go
index bf2dca6d27190c1ada6765d2ee61588edb8e85f0..cdd7baa30aecd90c205e34c3061a52fbc2359aa9 100644
--- a/pkg/view/settings.go
+++ b/pkg/view/settings.go
@@ -39,23 +39,28 @@ if err != nil {
return err
}
+ user := ext.GetUserFromCtx(r)
+
templates.WritePageTemplate(w, &templates.SettingsPage{
Settings: s,
Users: users,
- })
+ }, user.IsAdmin)
return nil
}
func (self *SettingsView) User(w http.ResponseWriter, r *http.Request) error {
- id := r.FormValue("userId")
+ var (
+ id = r.URL.Query().Get("userId")
+ user = ext.GetUserFromCtx(r)
+ )
idValue, err := ParseUint(id)
if err != nil {
return err
}
if idValue == nil {
- templates.WritePageTemplate(w, &templates.UserPage{})
+ templates.WritePageTemplate(w, &templates.UserPage{}, user.IsAdmin)
} else {
user, err := self.userController.Get(r.Context(), *idValue)
if err != nil {
@@ -67,7 +72,7 @@ ID: idValue,
Username: user.Username,
Path: user.Path,
IsAdmin: user.IsAdmin,
- })
+ }, user.IsAdmin)
}
return nil
@@ -87,7 +92,15 @@ if err != nil {
return err
}
- err = self.userController.Upsert(r.Context(), idValue, username, "", password, isAdmin, path)
+ err = self.userController.Upsert(
+ r.Context(),
+ idValue,
+ username,
+ "",
+ password,
+ isAdmin,
+ path,
+ )
if err != nil {
return err
}
@@ -137,12 +150,12 @@ return self.Index(w, r)
}
func (self *SettingsView) SetMyselfIn(r *ext.Router) {
- r.GET("/settings/", self.Index)
- r.POST("/settings/", self.Save)
+ r.GET("/settings", Protect(self.Index))
+ r.POST("/settings", Protect(self.Save))
- r.GET("/users/", self.User)
- r.GET("/users/delete", self.Delete)
- r.POST("/users/", self.UpsertUser)
+ r.GET("/users", Protect(self.User))
+ r.GET("/users/delete", Protect(self.Delete))
+ r.POST("/users", Protect(self.UpsertUser))
}
func ParseUint(id string) (*uint, error) {
diff --git a/pkg/view/view.go b/pkg/view/view.go
index 663738b6c6ac87955d83753445b9ff868959e29a..f8dfa16f0ccfc5261207919be4c1ff7fc5a71a09 100644
--- a/pkg/view/view.go
+++ b/pkg/view/view.go
@@ -1,7 +1,22 @@
package view
-import "git.sr.ht/~gabrielgio/img/pkg/ext"
+import (
+ "net/http"
+
+ "git.sr.ht/~gabrielgio/img/pkg/ext"
+)
type View interface {
SetMyselfIn(r *ext.Router)
}
+
+func Protect(next ext.ErrorRequestHandler) ext.ErrorRequestHandler {
+ return func(w http.ResponseWriter, r *http.Request) error {
+ user := ext.GetUserFromCtx(r)
+ if !user.IsAdmin {
+ http.NotFound(w, r)
+ return nil
+ }
+ return next(w, r)
+ }
+}
diff --git a/templates/album.qtpl b/templates/album.qtpl
index 835db5703c2c07cc98145f76fd435e52d4f5707e..58fc499ccceb04cbb33f4c8f9ec495293b043020 100644
--- a/templates/album.qtpl
+++ b/templates/album.qtpl
@@ -23,14 +23,14 @@ {% func (p *AlbumPage) Content() %}
<h1 class="title text-size-1">{%s p.Name %}</h1>
<div class="tags are-large">
{% for _, a := range p.Albums %}
- <a href="/album/?albumId={%s FromUInttoString(&a.ID) %}" class="tag text-size-2">{%s a.Name %}</a>
+ <a href="/album?albumId={%s FromUInttoString(&a.ID) %}" class="tag text-size-2">{%s a.Name %}</a>
{% endfor %}
</div>
<div class="columns">
{%= Mosaic(p.Medias, p.PreloadAttr()) %}
</div>
<div>
- <a href="/album/?albumId={%s FromUInttoString(p.Next.AlbumID) %}&page={%d p.Next.Page %}" class="button is-pulled-right">next</a>
+ <a href="/album?albumId={%s FromUInttoString(p.Next.AlbumID) %}&page={%d p.Next.Page %}" class="button is-pulled-right">next</a>
</div>
{% endfunc %}
diff --git a/templates/base.qtpl b/templates/base.qtpl
index a80803a50b720b01160069c224084f74ea86fe8b..30b084ebfd71f3a56ecf96c687d66260179ed7b8 100644
--- a/templates/base.qtpl
+++ b/templates/base.qtpl
@@ -21,7 +21,7 @@ %}
Page prints a page implementing Page interface.
-{% func PageTemplate(p Page) %}
+{% func PageTemplate(p Page, isAdmin bool) %}
<html lang="en">
<head>
<meta charset="utf-8">
@@ -33,18 +33,20 @@ </head>
<body>
<nav class="navbar">
<div class="navbar-start">
- <a href="/fs/" class="navbar-item text-size-1">
+ <a href="/fs" class="navbar-item text-size-1">
file
</a>
- <a href="/media/" class="navbar-item text-size-1">
+ <a href="/media" class="navbar-item text-size-1">
media
</a>
- <a href="/album/" class="navbar-item text-size-1">
+ <a href="/album" class="navbar-item text-size-1">
album
</a>
- <a href="/settings/" class="navbar-item text-size-1">
+ {% if isAdmin %}
+ <a href="/settings" class="navbar-item text-size-1">
settings
</a>
+ {% endif %}
</div>
</nav>
<div class="container is-fullhd">
diff --git a/templates/media.qtpl b/templates/media.qtpl
index 4251deb32c1b561ecdbad544bb7adbe42fec0571..737d03d63a2ae301fc37dd3a9926e216a6fe325a 100644
--- a/templates/media.qtpl
+++ b/templates/media.qtpl
@@ -22,7 +22,7 @@ <div class="columns">
{%= Mosaic(p.Medias, p.PreloadAttr()) %}
</div>
<div>
- <a href="/media/?page={%d p.Next.Page %}" class="button is-pulled-right">next</a>
+ <a href="/media?page={%d p.Next.Page %}" class="button is-pulled-right">next</a>
</div>
{% endfunc %}
diff --git a/templates/mosaic.qtpl b/templates/mosaic.qtpl
index 3e6ccf86d9ac5359d8a2a097af4269589af25fb7..18dbcba489fef78faa1326522e834762f3efadba 100644
--- a/templates/mosaic.qtpl
+++ b/templates/mosaic.qtpl
@@ -8,12 +8,12 @@ <div class="column is-2">
{% for _, media := range c %}
<div class="card-image">
{% if media.IsVideo() %}
- <video class="image is-fit" controls muted="true" poster="/media/thumbnail/?path_hash={%s media.PathHash %}" preload="{%s preloadAttr %}">
- <source src="/media/image/?path_hash={%s media.PathHash %}" type="{%s media.MIMEType %}">
+ <video class="image is-fit" controls muted="true" poster="/media/thumbnail?path_hash={%s media.PathHash %}" preload="{%s preloadAttr %}">
+ <source src="/media/image?path_hash={%s media.PathHash %}" type="{%s media.MIMEType %}">
</video>
{% else %}
<figure class="image is-fit">
- <img src="/media/thumbnail/?path_hash={%s media.PathHash %}">
+ <img src="/media/thumbnail?path_hash={%s media.PathHash %}">
</figure>
{% endif %}
</div>
diff --git a/templates/settings.qtpl b/templates/settings.qtpl
index 4439c77c99d834bc2c71f9b277a85c097f3ae8f9..b720a88dc4b7028bb415d668e9844c49f9d0d1e7 100644
--- a/templates/settings.qtpl
+++ b/templates/settings.qtpl
@@ -58,7 +58,7 @@ </div>
</div>
{% endfor %}
<div class="field">
- <a href="/users/" class="button">create</a>
+ <a href="/users" class="button">create</a>
</div>
</div>
{% endfunc %}
diff --git a/templates/user.qtpl b/templates/user.qtpl
index 6ec783d6d9bbc32dcb34efe3deba29230cdc3e39..6fc3ce6cf25de65a3e3ed52ace6c9510740b9049 100644
--- a/templates/user.qtpl
+++ b/templates/user.qtpl
@@ -13,7 +13,7 @@ {% func (p *UserPage) Title() %}User{% endfunc %}
{% func (p *UserPage) Content() %}
<h1>Initial Setup</h1>
-<form action="/users/" method="post">
+<form action="/users" method="post">
{% if p.ID != nil %}
<input type="hidden" name="userId" value="{%s FromUInttoString(p.ID) %}" />
{% endif %}
@@ -41,7 +41,7 @@ </div>
<div class="field">
<label class="label">Is Admin?</label>
<div class="control">
- <input type="checkbox" name="isAdmin" type="password" {% if p.IsAdmin %}checked{% endif %}>
+ <input type="checkbox" name="isAdmin" {% if p.IsAdmin %}checked{% endif %}>
</div>
</div>
<div class="field">