2022-09-28 09:01:17 +02:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
|
|
|
"github.com/photoprism/photoprism/internal/form"
|
|
|
|
"github.com/photoprism/photoprism/internal/session"
|
|
|
|
)
|
|
|
|
|
|
|
|
// AuthenticateAdmin Register session routes and returns valid SessionId.
|
|
|
|
// Call this func after registering other routes and before performing other requests.
|
|
|
|
func AuthenticateAdmin(app *gin.Engine, router *gin.RouterGroup) (sessId string) {
|
|
|
|
return AuthenticateUser(app, router, "admin", "photoprism")
|
|
|
|
}
|
|
|
|
|
|
|
|
// AuthenticateUser Register session routes and returns valid SessionId.
|
|
|
|
// Call this func after registering other routes and before performing other requests.
|
|
|
|
func AuthenticateUser(app *gin.Engine, router *gin.RouterGroup, name string, password string) (sessId string) {
|
|
|
|
CreateSession(router)
|
|
|
|
|
2022-10-12 18:11:20 +02:00
|
|
|
r := PerformRequestWithBody(app, http.MethodPost, "/api/v1/session", form.AsJson(form.Login{
|
2022-09-28 09:01:17 +02:00
|
|
|
UserName: name,
|
|
|
|
Password: password,
|
2022-10-12 18:11:20 +02:00
|
|
|
}))
|
2022-09-28 09:01:17 +02:00
|
|
|
|
|
|
|
sessId = r.Header().Get(session.Header)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Performs authenticated API request with empty request body.
|
|
|
|
func AuthenticatedRequest(r http.Handler, method, path, sess string) *httptest.ResponseRecorder {
|
|
|
|
req, _ := http.NewRequest(method, path, nil)
|
2022-10-02 11:38:30 +02:00
|
|
|
|
|
|
|
if sess != "" {
|
|
|
|
req.Header.Add(session.Header, sess)
|
|
|
|
}
|
|
|
|
|
2022-09-28 09:01:17 +02:00
|
|
|
w := httptest.NewRecorder()
|
|
|
|
r.ServeHTTP(w, req)
|
|
|
|
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
|
|
|
// Performs an authenticated API request containing the request body as a string.
|
|
|
|
func AuthenticatedRequestWithBody(r http.Handler, method, path, body string, sess string) *httptest.ResponseRecorder {
|
|
|
|
reader := strings.NewReader(body)
|
|
|
|
req, _ := http.NewRequest(method, path, reader)
|
2022-10-02 11:38:30 +02:00
|
|
|
|
|
|
|
if sess != "" {
|
|
|
|
req.Header.Add(session.Header, sess)
|
|
|
|
}
|
2022-09-28 09:01:17 +02:00
|
|
|
|
|
|
|
w := httptest.NewRecorder()
|
|
|
|
r.ServeHTTP(w, req)
|
|
|
|
|
|
|
|
return w
|
|
|
|
}
|