otfe/misc/auth/auth_test.go

114 lines
2.6 KiB
Go

package auth
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.1248.nz/1248/Otfe/misc/helpers"
"git.1248.nz/1248/Otfe/misc/helpers/cookie"
"git.1248.nz/1248/Otfe/models"
"github.com/globalsign/mgo/bson"
)
func TestUser(t *testing.T) {
//Setup user with session
recorder := httptest.NewRecorder()
user, session := userSession(t)
request := request(t, session)
u := User(handler)
//Run
u(recorder, request)
//Check
body := recorder.Body.String()
if !strings.Contains(body, user.ID.Hex()) {
t.Fail()
}
//Setup without session
recorder = httptest.NewRecorder()
request, _ = http.NewRequest("GET", "/", nil)
//Run
u(recorder, request)
//Check
helpers.Equals(t, recorder.Body.String(),
"{ObjectIdHex(\"\") ObjectIdHex(\"\") []}")
}
func TestPerm(t *testing.T) {
p := Perm(handler, UnAuth, "perm")
recorder := httptest.NewRecorder()
user, session := userSession(t)
request := request(t, session)
p(recorder, request)
if !strings.Contains(recorder.Body.String(),
"You are not authorized to view this page") {
t.Log("Authorization fail")
t.Fail()
}
p = Perm(handler, UnAuth, "test")
recorder = httptest.NewRecorder()
p(recorder, request)
if !strings.Contains(recorder.Body.String(), user.ID.Hex()) {
t.Log("Has permission fail")
t.Fail()
}
recorder = httptest.NewRecorder()
request, err := http.NewRequest("GET", "/", nil)
helpers.Ok(t, err)
p(recorder, request)
if !strings.Contains(recorder.Body.String(), "login") {
t.Log("Login fail")
t.Fail()
}
}
func TestGetUserSession(t *testing.T) {
user, session := userSession(t)
request := request(t, session)
//Test
user2, err := getUserSession(request)
helpers.Ok(t, err)
helpers.Equals(t, user, user2)
}
func userSession(t *testing.T) (models.User, models.Session) {
models.DBWipeCollection("user", "session", "group")
group := models.NewGroup("test")
group.ID = bson.NewObjectId()
group.Permissions["test"] = true
//group.Admin = true
helpers.Ok(t, group.Create())
user := models.User{Name: "test",
Email: "test"}
user.ID = bson.NewObjectId()
user.PrimaryGroup = group.ID
helpers.Ok(t, user.Create())
session := models.Session{UserID: user.ID}
session.ID = bson.NewObjectId()
helpers.Ok(t, session.Create())
return user, session
}
func request(t *testing.T, s models.Session) *http.Request {
cookie := &http.Cookie{Name: "session",
Value: cookie.Encode(s.ID.Hex())}
request, err := http.NewRequest("GET", "/", nil)
helpers.Ok(t, err)
request.AddCookie(cookie)
return request
}
func handler(w http.ResponseWriter, r *http.Request, u models.User) {
fmt.Fprint(w, u)
}