|
|
- package Auth_test
-
- import (
- "bytes"
- "encoding/base64"
- "encoding/json"
- "io/ioutil"
- "log"
- "net/http"
- "net/http/cookiejar"
- "net/http/httptest"
- "net/url"
- "testing"
-
- "git.tovijaeschke.xyz/tovi/Capsule/Backend/Api"
- "git.tovijaeschke.xyz/tovi/Capsule/Backend/Api/Auth"
- "git.tovijaeschke.xyz/tovi/Capsule/Backend/Database"
- "git.tovijaeschke.xyz/tovi/Capsule/Backend/Database/Seeder"
- "git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"
- "github.com/gorilla/mux"
- )
-
- func Test_Logout(t *testing.T) {
- log.SetOutput(ioutil.Discard)
- Database.InitTest()
-
- r := mux.NewRouter()
- Api.InitAPIEndpoints(r)
- ts := httptest.NewServer(r)
- defer ts.Close()
-
- userKey, _ := Seeder.GenerateAesKey()
- pubKey := Seeder.GetPubKey()
-
- p, _ := Auth.HashPassword("password")
-
- u := Models.User{
- Username: "test",
- Password: p,
- AsymmetricPublicKey: Seeder.PublicKey,
- AsymmetricPrivateKey: Seeder.EncryptedPrivateKey,
- SymmetricKey: base64.StdEncoding.EncodeToString(
- Seeder.EncryptWithPublicKey(userKey.Key, pubKey),
- ),
- }
-
- err := Database.CreateUser(&u)
- if err != nil {
- t.Errorf("Expected nil, recieved %s", err.Error())
- return
- }
-
- d := struct {
- Username string `json:"username"`
- Password string `json:"password"`
- }{
- Username: "test",
- Password: "password",
- }
-
- jsonStr, _ := json.Marshal(d)
- req, _ := http.NewRequest("POST", ts.URL+"/api/v1/login", bytes.NewBuffer(jsonStr))
- req.Header.Set("Content-Type", "application/json")
-
- client := &http.Client{}
- resp, err := client.Do(req)
-
- if err != nil {
- t.Errorf("Expected nil, recieved %s", err.Error())
- return
- }
-
- if resp.StatusCode != http.StatusOK {
- t.Errorf("Expected %d, recieved %d", http.StatusOK, resp.StatusCode)
- return
- }
-
- var session Models.Session
-
- err = Database.DB.First(&session, "user_id = ?", u.ID.String()).Error
-
- if err != nil {
- t.Errorf("Expected session record, recieved %s", err.Error())
- return
- }
-
- jar, err := cookiejar.New(nil)
- if err != nil {
- t.Errorf("Expected nil, recieved %s", err.Error())
- }
-
- url, _ := url.Parse(ts.URL)
-
- jar.SetCookies(
- url,
- []*http.Cookie{
- &http.Cookie{
- Name: "session_token",
- Value: session.ID.String(),
- MaxAge: 300,
- },
- },
- )
-
- client = &http.Client{
- Jar: jar,
- }
- resp, err = client.Get(ts.URL + "/api/v1/logout")
-
- if err != nil {
- t.Errorf("Expected user record, recieved %s", err.Error())
- return
- }
-
- if resp.StatusCode != http.StatusOK {
- t.Errorf("Expected %d, recieved %d", http.StatusOK, resp.StatusCode)
- return
- }
-
- err = Database.DB.First(&session, "user_id = ?", u.ID.String()).Error
- if err == nil {
- t.Errorf("Expected no session record, recieved %s", session.UserID)
- return
- }
- }
|