implemented saving cookies and user session to a file

This commit is contained in:
Jaeger Aquila 2023-01-14 17:40:03 -05:00
parent ab9e67bbb1
commit 4ee69f1ed5
2 changed files with 46 additions and 16 deletions

View File

@ -1,22 +1,34 @@
package persistence
import (
"encoding/json"
"offline_twitter/scraper"
"os"
)
func (p Profile) SaveSession(api scraper.API) {
// TODO session-saving:1
// - To understand what's going on here, look at the `MarshalJSON` function in `scraper/api_request_utils.go`,
// and the output of `git show 390c83154117aa2a339a83f05820fb904a32298e`.
// - use `json.Marshal` on the API object and write the resulting bytes to like "[api.UserHandle].session" or something
// - use `os.WriteFile` to write the file
panic("TODO")
data, err := json.Marshal(api)
if err != nil {
panic(err)
}
os.WriteFile(p.ProfileDir+"/"+string(api.UserHandle+".session"), data, os.FileMode(0644))
if err != nil {
panic(err)
}
}
func (p Profile) LoadSession(userhandle scraper.UserHandle) scraper.API {
// TODO session-saving:2
// - use `os.ReadFile` to read "[userhandle].session"
// - create a variable of type scraper.API
// - use `json.Unmarshal` to load the file contents into the new API variable
panic("TODO")
data, err := os.ReadFile(p.ProfileDir + "/" + string(userhandle+".session"))
if err != nil {
panic(err)
}
var result scraper.API
err = json.Unmarshal(data, &result)
if err != nil {
panic(err)
}
return result
}

View File

@ -1,28 +1,46 @@
package persistence_test
import (
"github.com/go-test/deep"
"offline_twitter/persistence"
"fmt"
"math/rand"
"net/http"
"net/http/cookiejar"
"offline_twitter/scraper"
"testing"
"time"
"github.com/go-test/deep"
)
// Save and load an API session; it should come back the same
func TestSaveAndLoadAuthenticatedSession(t *testing.T) {
assert := assert.New(t)
profile_path := "test_profiles/TestSession"
profile := create_or_load_profile(profile_path)
jar, err := cookiejar.New(nil)
if err != nil {
panic(err)
}
api := scraper.API{
// TODO session-saving
// - Fill out some fields here like Cookies and CSRFToken and UserHandle
UserHandle: "testUser",
IsAuthenticated: true,
Client: http.Client{
Timeout: 10 * time.Second,
Jar: jar,
},
CSRFToken: fmt.Sprint(rand.Int()),
}
// Save and load the session; it should come back the same
profile.SaveSession(api)
new_api = profile.LoadSession(api.UserHandle)
new_api := profile.LoadSession(api.UserHandle)
if diff := deep.Equal(api, new_api); diff != nil {
t.Errorf(diff)
t.Error(diff)
}
}