Files
access-handler/db_test.go
2025-11-19 16:29:37 +01:00

218 lines
6.2 KiB
Go

package AccessHandler
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"testing"
"gitea.tecamino.com/paadi/access-handler/models"
"github.com/gin-gonic/gin"
"github.com/go-playground/assert/v2"
)
func TestDatabase(t *testing.T) {
// set enviroment variables
os.Setenv("ACCESS_SECRET", "12345678910111213141516171819202")
os.Setenv("REFRESH_SECRET", "9998979695949392919089888786858")
os.Setenv("DOMAIN", "localhost")
dbName := "user.db"
if _, err := os.Stat(dbName); err == nil {
t.Log("remove user.db to start test with empty database")
if err := os.Remove(dbName); err != nil {
t.Fatal(err)
}
}
t.Log("start access handler test")
t.Log("initialize accessHandler")
accessHandler, err := NewAccessHandler(".", nil)
if err != nil {
t.Fatal(err)
}
r := gin.Default()
accessHandler.SetMiddlewareLogger(r)
r.POST("/users/add", accessHandler.AddUser)
r.GET("/users", accessHandler.GetUser)
r.GET("/roles", accessHandler.GetRole)
r.POST("/roles/add", accessHandler.AddRole)
type request struct {
Log string
Name string
Method string
Path string
Payload any
Cookie *http.Cookie
ignoreError bool
}
var requests []request
requests = append(requests,
request{Log: "add another user", Name: "add user", Method: "POST", Path: "/users/add", Payload: models.User{
Name: "guest",
Password: "passwordd1",
Role: &models.Role{Role: "guest"},
Email: "guest@gmail.com",
}, ignoreError: true},
request{Log: "Get all users", Name: "get all users", Method: "GET", Path: "/users"},
request{Log: "Get user id 1", Name: "get user id 1", Method: "GET", Path: "/users?id=1"},
request{Log: "Add new role", Name: "add new role", Method: "POST", Path: "/roles/add", Payload: models.Role{
Role: "testRole",
}, ignoreError: true},
request{Log: "Get all roles", Name: "get all roles", Method: "GET", Path: "/roles"},
request{Log: "Get all role id 1", Name: "get role id 1", Method: "GET", Path: "/roles?id=1"},
request{Log: "Get user id 2", Name: "get user id 2", Method: "GET", Path: "/users?id=2"},
)
for _, request := range requests {
if request.Log != "" {
t.Log(request.Log)
}
var bodyReader io.Reader
if request.Payload != nil {
jsonBytes, _ := json.Marshal(request.Payload)
bodyReader = bytes.NewBuffer(jsonBytes)
}
req, _ := http.NewRequest(request.Method, request.Path, bodyReader)
if request.Cookie != nil {
req.AddCookie(request.Cookie) // attach refresh_token cookie
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
t.Log(request.Name+" response:", w.Body.String())
if !request.ignoreError {
assert.Equal(t, http.StatusOK, w.Code)
}
}
}
func TestLoginAndAuthorization(t *testing.T) {
os.Setenv("ACCESS_SECRET", "12345678910111213141516171819202")
os.Setenv("REFRESH_SECRET", "9998979695949392919089888786858")
os.Setenv("DOMAIN", "localhost")
gin.SetMode(gin.TestMode)
// Setup your AccessHandler and router
aH, err := NewAccessHandler(".", nil)
if err != nil {
t.Fatal(err)
}
r := gin.Default()
aH.SetMiddlewareLogger(r)
r.POST("/login", aH.Login)
r.POST("/login/refresh", aH.Refresh)
r.POST("/roles/update", aH.UpdateRole)
r.GET("/login/me", aH.Me)
r.GET("/logout", aH.Logout)
middleware := r.Group("", aH.AuthMiddleware())
auth := middleware.Group("/members", aH.AuthorizeRole(""))
auth.GET("", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, "ok")
})
auth2 := middleware.Group("", aH.AuthorizeRole("/login/change", "password"))
auth2.POST("/login/change/password", aH.ChangePassword)
// ---- Step 1: Perform login ----
user := models.User{
Name: "guest",
Password: "passwordd1",
NewPassword: "Newpasswordd1",
}
jsonBody, _ := json.Marshal(user)
req, _ := http.NewRequest(http.MethodPost, "/login", bytes.NewBuffer(jsonBody))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
t.Log("Login response:", w.Body.String())
assert.Equal(t, http.StatusOK, w.Code)
// ---- Step 2: Extract cookies ----
cookies := w.Result().Cookies()
var accessCookie *http.Cookie
var refreshCookie *http.Cookie
for _, c := range cookies {
switch c.Name {
case "refresh_token":
refreshCookie = c
case "access_token":
accessCookie = c
}
}
if refreshCookie == nil {
t.Fatal("refresh_token cookie not found")
}
type request struct {
Name string
Method string
Path string
Payload any
Cookie *http.Cookie
ignoreError bool
}
var requests []request
user.Id = 2
correctUser := user
correctUser.Password = user.NewPassword
requests = append(requests,
request{Name: "Refresh", Method: "POST", Path: "/login/refresh", Cookie: refreshCookie},
request{Name: "Me", Method: "GET", Path: "/login/me", Cookie: accessCookie},
request{Name: "add new role", Method: "POST", Path: "/roles/update", Payload: models.Role{
Role: "guest", Permissions: models.Permissions{{Name: "members", Permission: 31}},
}, ignoreError: true},
request{Name: "Authorization", Method: "GET", Path: "/members", Cookie: accessCookie},
request{Name: "Change Password", Method: "POST", Path: "/login/change/password", Cookie: accessCookie, Payload: user},
request{Name: "Logout", Method: "GET", Path: "/logout", Cookie: refreshCookie},
request{Name: "New wrong login", Method: "POST", Path: "/login", Payload: user, ignoreError: true},
request{Name: "New login", Method: "POST", Path: "/login", Payload: correctUser},
)
for _, request := range requests {
var body io.Reader
if request.Payload != nil {
jsonBytes, err := json.Marshal(request.Payload)
if err != nil {
t.Fatal(err)
}
body = bytes.NewBuffer(jsonBytes)
}
req, _ := http.NewRequest(request.Method, request.Path, body)
if request.Cookie != nil {
req.AddCookie(request.Cookie) // attach refresh_token cookie
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
t.Log(request.Name+" response:", w.Body.String())
if !request.ignoreError {
assert.Equal(t, http.StatusOK, w.Code)
}
}
}