package Auth_test import ( "bytes" "encoding/base64" "encoding/json" "io/ioutil" "log" "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "os" "testing" "time" "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_AddProfileImage(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 } session := Models.Session{ UserID: u.ID, Expiry: time.Now().Add(12 * time.Hour), } err = Database.CreateSession(&session) if err != nil { t.Errorf("Expected nil, recieved %s", err.Error()) return } jar, err := cookiejar.New(nil) if err != nil { t.Errorf("Expected nil, recieved %s", err.Error()) return } url, _ := url.Parse(ts.URL) jar.SetCookies( url, []*http.Cookie{ { Name: "session_token", Value: session.ID.String(), MaxAge: 300, }, }, ) key, err := Seeder.GenerateAesKey() if err != nil { t.Errorf("Expected nil, recieved %s", err.Error()) return } dat, err := os.ReadFile("./profile_picture_test.png") if err != nil { t.Errorf("Expected nil, recieved %s", err.Error()) return } encDat, err := key.AesEncrypt(dat) if err != nil { t.Errorf("Expected nil, recieved %s", err.Error()) return } a := Models.Attachment{ Mimetype: "image/png", Extension: "png", Data: base64.StdEncoding.EncodeToString(encDat), } jsonStr, _ := json.Marshal(a) req, _ := http.NewRequest("POST", ts.URL+"/api/v1/auth/image", bytes.NewBuffer(jsonStr)) req.Header.Set("Content-Type", "application/json") client := &http.Client{ Jar: jar, } resp, err := client.Do(req) if err != nil { t.Errorf("Expected nil, recieved %s", err.Error()) return } if resp.StatusCode != http.StatusNoContent { t.Errorf("Expected %d, recieved %d", http.StatusNoContent, resp.StatusCode) return } u, err = Database.GetUserById(u.ID.String()) if err != nil { t.Errorf("Expected nil, recieved %s", err.Error()) return } if u.AttachmentID.IsNil() { t.Errorf("Attachment not assigned to user") } err = os.Remove("/app/attachments/" + u.Attachment.FilePath) if err != nil { t.Errorf("Expected nil, recieved %s", err.Error()) return } }