Change: Update Database auth to user method

This commit is contained in:
2021-12-12 01:57:54 +08:00
parent 1f960f8f64
commit b96daa07c6
5 changed files with 55 additions and 12 deletions

View File

@@ -6,7 +6,6 @@ import (
)
type WalkRequest struct {
Token string `json:"token"`
Root string `json:"root"`
Pattern []string `json:"pattern"`
}
@@ -24,7 +23,7 @@ func (api *API) HandleReset(w http.ResponseWriter, r *http.Request) {
}
// check token
err = api.CheckToken(w, r, resetRequest.Token)
err = api.CheckAdmin(w, r)
if err != nil {
return
}
@@ -53,7 +52,7 @@ func (api *API) HandleWalk(w http.ResponseWriter, r *http.Request) {
}
// check token match
err = api.CheckToken(w, r, walkRequest.Token)
err = api.CheckAdmin(w, r)
if err != nil {
return
}

View File

@@ -4,6 +4,12 @@ import (
"encoding/json"
"log"
"net/http"
"errors"
)
var (
ErrNotLoggedIn = errors.New("not logged in")
ErrNotAdmin = errors.New("not admin")
)
type Error struct {

View File

@@ -143,3 +143,26 @@ func (api *API) HandleRegister(w http.ResponseWriter, r *http.Request) {
return
}
}
func (api *API) CheckAdmin(w http.ResponseWriter, r *http.Request) error {
session, _ := api.store.Get(r, api.defaultSessionName)
userId, ok := session.Values["userId"]
if !ok {
api.HandleError(w, r, ErrNotLoggedIn)
return ErrNotLoggedIn
}
user, err := api.Db.GetUserById(userId.(int64))
if err != nil {
api.HandleError(w, r, err)
return err
}
if user.Role != database.RoleAdmin {
api.HandleError(w, r, ErrNotAdmin)
return ErrNotAdmin
}
w.WriteHeader(http.StatusOK)
return nil
}