From f197d8eec55ac4bb1b589905fbfdf02b743914d6 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Sun, 24 Apr 2022 14:24:20 +0930 Subject: [PATCH 01/24] Add initial Backend and flutter mobile app --- .gitignore | 1 + Backend/Api/Auth/Passwords.go | 22 + Backend/Api/Auth/Signup.go | 74 +++ .../JsonSerialization/DeserializeUserJson.go | 76 +++ Backend/Api/JsonSerialization/VerifyJson.go | 109 ++++ Backend/Api/Routes.go | 75 +++ Backend/Database/Init.go | 64 +++ Backend/Database/Users.go | 99 ++++ Backend/Models/Base.go | 27 + Backend/Models/Messages.go | 15 + Backend/Models/Users.go | 23 + Backend/go.mod | 26 + Backend/go.sum | 192 +++++++ Backend/main.go | 26 + mobile/.gitignore | 46 ++ mobile/.metadata | 10 + mobile/README.md | 16 + mobile/analysis_options.yaml | 29 ++ mobile/android/.gitignore | 13 + mobile/android/app/build.gradle | 68 +++ .../android/app/src/debug/AndroidManifest.xml | 7 + .../android/app/src/main/AndroidManifest.xml | 34 ++ .../kotlin/com/example/mobile/MainActivity.kt | 6 + .../res/drawable-v21/launch_background.xml | 12 + .../main/res/drawable/launch_background.xml | 12 + .../src/main/res/mipmap-hdpi/ic_launcher.png | Bin 0 -> 544 bytes .../src/main/res/mipmap-mdpi/ic_launcher.png | Bin 0 -> 442 bytes .../src/main/res/mipmap-xhdpi/ic_launcher.png | Bin 0 -> 721 bytes .../main/res/mipmap-xxhdpi/ic_launcher.png | Bin 0 -> 1031 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 1443 bytes .../app/src/main/res/values-night/styles.xml | 18 + .../app/src/main/res/values/styles.xml | 18 + .../app/src/profile/AndroidManifest.xml | 7 + mobile/android/build.gradle | 31 ++ mobile/android/gradle.properties | 3 + .../gradle/wrapper/gradle-wrapper.properties | 6 + mobile/android/settings.gradle | 11 + mobile/ios/.gitignore | 34 ++ mobile/ios/Flutter/AppFrameworkInfo.plist | 26 + mobile/ios/Flutter/Debug.xcconfig | 1 + mobile/ios/Flutter/Release.xcconfig | 1 + mobile/ios/Runner.xcodeproj/project.pbxproj | 481 ++++++++++++++++++ .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../xcshareddata/WorkspaceSettings.xcsettings | 8 + .../xcshareddata/xcschemes/Runner.xcscheme | 87 ++++ .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../xcshareddata/WorkspaceSettings.xcsettings | 8 + mobile/ios/Runner/AppDelegate.swift | 13 + .../AppIcon.appiconset/Contents.json | 122 +++++ .../Icon-App-1024x1024@1x.png | Bin 0 -> 10932 bytes .../AppIcon.appiconset/Icon-App-20x20@1x.png | Bin 0 -> 564 bytes .../AppIcon.appiconset/Icon-App-20x20@2x.png | Bin 0 -> 1283 bytes .../AppIcon.appiconset/Icon-App-20x20@3x.png | Bin 0 -> 1588 bytes .../AppIcon.appiconset/Icon-App-29x29@1x.png | Bin 0 -> 1025 bytes .../AppIcon.appiconset/Icon-App-29x29@2x.png | Bin 0 -> 1716 bytes .../AppIcon.appiconset/Icon-App-29x29@3x.png | Bin 0 -> 1920 bytes .../AppIcon.appiconset/Icon-App-40x40@1x.png | Bin 0 -> 1283 bytes .../AppIcon.appiconset/Icon-App-40x40@2x.png | Bin 0 -> 1895 bytes .../AppIcon.appiconset/Icon-App-40x40@3x.png | Bin 0 -> 2665 bytes .../AppIcon.appiconset/Icon-App-60x60@2x.png | Bin 0 -> 2665 bytes .../AppIcon.appiconset/Icon-App-60x60@3x.png | Bin 0 -> 3831 bytes .../AppIcon.appiconset/Icon-App-76x76@1x.png | Bin 0 -> 1888 bytes .../AppIcon.appiconset/Icon-App-76x76@2x.png | Bin 0 -> 3294 bytes .../Icon-App-83.5x83.5@2x.png | Bin 0 -> 3612 bytes .../LaunchImage.imageset/Contents.json | 23 + .../LaunchImage.imageset/LaunchImage.png | Bin 0 -> 68 bytes .../LaunchImage.imageset/LaunchImage@2x.png | Bin 0 -> 68 bytes .../LaunchImage.imageset/LaunchImage@3x.png | Bin 0 -> 68 bytes .../LaunchImage.imageset/README.md | 5 + .../Runner/Base.lproj/LaunchScreen.storyboard | 37 ++ mobile/ios/Runner/Base.lproj/Main.storyboard | 26 + mobile/ios/Runner/Info.plist | 47 ++ mobile/ios/Runner/Runner-Bridging-Header.h | 1 + mobile/lib/authentication/signup.dart | 172 +++++++ .../unauthenticated_landing.dart | 75 +++ mobile/lib/main.dart | 25 + mobile/pubspec.lock | 202 ++++++++ mobile/pubspec.yaml | 28 + mobile/test/widget_test.dart | 30 ++ mobile/web/favicon.png | Bin 0 -> 917 bytes mobile/web/icons/Icon-192.png | Bin 0 -> 5292 bytes mobile/web/icons/Icon-512.png | Bin 0 -> 8252 bytes mobile/web/icons/Icon-maskable-192.png | Bin 0 -> 5594 bytes mobile/web/icons/Icon-maskable-512.png | Bin 0 -> 20998 bytes mobile/web/index.html | 104 ++++ mobile/web/manifest.json | 35 ++ mobile/windows/.gitignore | 17 + mobile/windows/CMakeLists.txt | 95 ++++ mobile/windows/flutter/CMakeLists.txt | 103 ++++ .../flutter/generated_plugin_registrant.cc | 11 + .../flutter/generated_plugin_registrant.h | 15 + .../windows/flutter/generated_plugins.cmake | 15 + mobile/windows/runner/CMakeLists.txt | 17 + mobile/windows/runner/Runner.rc | 121 +++++ mobile/windows/runner/flutter_window.cpp | 61 +++ mobile/windows/runner/flutter_window.h | 33 ++ mobile/windows/runner/main.cpp | 43 ++ mobile/windows/runner/resource.h | 16 + mobile/windows/runner/resources/app_icon.ico | Bin 0 -> 33772 bytes mobile/windows/runner/runner.exe.manifest | 20 + mobile/windows/runner/utils.cpp | 64 +++ mobile/windows/runner/utils.h | 19 + mobile/windows/runner/win32_window.cpp | 245 +++++++++ mobile/windows/runner/win32_window.h | 98 ++++ 106 files changed, 3790 insertions(+) create mode 100644 .gitignore create mode 100644 Backend/Api/Auth/Passwords.go create mode 100644 Backend/Api/Auth/Signup.go create mode 100644 Backend/Api/JsonSerialization/DeserializeUserJson.go create mode 100644 Backend/Api/JsonSerialization/VerifyJson.go create mode 100644 Backend/Api/Routes.go create mode 100644 Backend/Database/Init.go create mode 100644 Backend/Database/Users.go create mode 100644 Backend/Models/Base.go create mode 100644 Backend/Models/Messages.go create mode 100644 Backend/Models/Users.go create mode 100644 Backend/go.mod create mode 100644 Backend/go.sum create mode 100644 Backend/main.go create mode 100644 mobile/.gitignore create mode 100644 mobile/.metadata create mode 100644 mobile/README.md create mode 100644 mobile/analysis_options.yaml create mode 100644 mobile/android/.gitignore create mode 100644 mobile/android/app/build.gradle create mode 100644 mobile/android/app/src/debug/AndroidManifest.xml create mode 100644 mobile/android/app/src/main/AndroidManifest.xml create mode 100644 mobile/android/app/src/main/kotlin/com/example/mobile/MainActivity.kt create mode 100644 mobile/android/app/src/main/res/drawable-v21/launch_background.xml create mode 100644 mobile/android/app/src/main/res/drawable/launch_background.xml create mode 100644 mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png create mode 100644 mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png create mode 100644 mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png create mode 100644 mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png create mode 100644 mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 mobile/android/app/src/main/res/values-night/styles.xml create mode 100644 mobile/android/app/src/main/res/values/styles.xml create mode 100644 mobile/android/app/src/profile/AndroidManifest.xml create mode 100644 mobile/android/build.gradle create mode 100644 mobile/android/gradle.properties create mode 100644 mobile/android/gradle/wrapper/gradle-wrapper.properties create mode 100644 mobile/android/settings.gradle create mode 100644 mobile/ios/.gitignore create mode 100644 mobile/ios/Flutter/AppFrameworkInfo.plist create mode 100644 mobile/ios/Flutter/Debug.xcconfig create mode 100644 mobile/ios/Flutter/Release.xcconfig create mode 100644 mobile/ios/Runner.xcodeproj/project.pbxproj create mode 100644 mobile/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings create mode 100644 mobile/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme create mode 100644 mobile/ios/Runner.xcworkspace/contents.xcworkspacedata create mode 100644 mobile/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 mobile/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings create mode 100644 mobile/ios/Runner/AppDelegate.swift create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json create mode 100644 mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png create mode 100644 mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png create mode 100644 mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md create mode 100644 mobile/ios/Runner/Base.lproj/LaunchScreen.storyboard create mode 100644 mobile/ios/Runner/Base.lproj/Main.storyboard create mode 100644 mobile/ios/Runner/Info.plist create mode 100644 mobile/ios/Runner/Runner-Bridging-Header.h create mode 100644 mobile/lib/authentication/signup.dart create mode 100644 mobile/lib/authentication/unauthenticated_landing.dart create mode 100644 mobile/lib/main.dart create mode 100644 mobile/pubspec.lock create mode 100644 mobile/pubspec.yaml create mode 100644 mobile/test/widget_test.dart create mode 100644 mobile/web/favicon.png create mode 100644 mobile/web/icons/Icon-192.png create mode 100644 mobile/web/icons/Icon-512.png create mode 100644 mobile/web/icons/Icon-maskable-192.png create mode 100644 mobile/web/icons/Icon-maskable-512.png create mode 100644 mobile/web/index.html create mode 100644 mobile/web/manifest.json create mode 100644 mobile/windows/.gitignore create mode 100644 mobile/windows/CMakeLists.txt create mode 100644 mobile/windows/flutter/CMakeLists.txt create mode 100644 mobile/windows/flutter/generated_plugin_registrant.cc create mode 100644 mobile/windows/flutter/generated_plugin_registrant.h create mode 100644 mobile/windows/flutter/generated_plugins.cmake create mode 100644 mobile/windows/runner/CMakeLists.txt create mode 100644 mobile/windows/runner/Runner.rc create mode 100644 mobile/windows/runner/flutter_window.cpp create mode 100644 mobile/windows/runner/flutter_window.h create mode 100644 mobile/windows/runner/main.cpp create mode 100644 mobile/windows/runner/resource.h create mode 100644 mobile/windows/runner/resources/app_icon.ico create mode 100644 mobile/windows/runner/runner.exe.manifest create mode 100644 mobile/windows/runner/utils.cpp create mode 100644 mobile/windows/runner/utils.h create mode 100644 mobile/windows/runner/win32_window.cpp create mode 100644 mobile/windows/runner/win32_window.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e46bbea --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/mobile/nsconfig.json diff --git a/Backend/Api/Auth/Passwords.go b/Backend/Api/Auth/Passwords.go new file mode 100644 index 0000000..779c48e --- /dev/null +++ b/Backend/Api/Auth/Passwords.go @@ -0,0 +1,22 @@ +package Auth + +import ( + "golang.org/x/crypto/bcrypt" +) + +func HashPassword(password string) (string, error) { + var ( + bytes []byte + err error + ) + bytes, err = bcrypt.GenerateFromPassword([]byte(password), 14) + return string(bytes), err +} + +func CheckPasswordHash(password, hash string) bool { + var ( + err error + ) + err = bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) + return err == nil +} diff --git a/Backend/Api/Auth/Signup.go b/Backend/Api/Auth/Signup.go new file mode 100644 index 0000000..4c6ac5b --- /dev/null +++ b/Backend/Api/Auth/Signup.go @@ -0,0 +1,74 @@ +package Auth + +import ( + "encoding/json" + "io/ioutil" + "log" + "net/http" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/JsonSerialization" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +func Signup(w http.ResponseWriter, r *http.Request) { + var ( + userData Models.User + requestBody []byte + returnJson []byte + err error + ) + + requestBody, err = ioutil.ReadAll(r.Body) + if err != nil { + log.Printf("Error encountered reading POST body: %s\n", err.Error()) + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + userData, err = JsonSerialization.DeserializeUser(requestBody, []string{ + "id", + }, false) + if err != nil { + log.Printf("Invalid data provided to Signup: %s\n", err.Error()) + http.Error(w, "Invalid Data", http.StatusUnprocessableEntity) + return + } + + if userData.Username == "" || + userData.Password == "" || + userData.ConfirmPassword == "" || + len(userData.AsymmetricPrivateKey) == 0 || + len(userData.AsymmetricPublicKey) == 0 { + http.Error(w, "Invalid Data", http.StatusUnprocessableEntity) + return + } + + err = Database.CheckUniqueUsername(userData.Username) + if err != nil { + http.Error(w, "Invalid Data", http.StatusUnprocessableEntity) + return + } + + userData.Password, err = HashPassword(userData.Password) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + err = Database.CreateUser(&userData) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + returnJson, err = json.MarshalIndent(userData, "", " ") + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + // Return updated json + w.WriteHeader(http.StatusOK) + w.Write(returnJson) +} diff --git a/Backend/Api/JsonSerialization/DeserializeUserJson.go b/Backend/Api/JsonSerialization/DeserializeUserJson.go new file mode 100644 index 0000000..9220be8 --- /dev/null +++ b/Backend/Api/JsonSerialization/DeserializeUserJson.go @@ -0,0 +1,76 @@ +package JsonSerialization + +import ( + "encoding/json" + "errors" + "fmt" + "strings" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + schema "github.com/Kangaroux/go-map-schema" +) + +func DeserializeUser(data []byte, allowMissing []string, allowAllMissing bool) (Models.User, error) { + var ( + userData Models.User = Models.User{} + jsonStructureTest map[string]interface{} = make(map[string]interface{}) + jsonStructureTestResults *schema.CompareResults + field schema.FieldMissing + allowed string + missingFields []string + i int + err error + ) + + // Verify the JSON has the correct structure + json.Unmarshal(data, &jsonStructureTest) + jsonStructureTestResults, err = schema.CompareMapToStruct( + &userData, + jsonStructureTest, + &schema.CompareOpts{ + ConvertibleFunc: CanConvert, + TypeNameFunc: schema.DetailedTypeName, + }) + if err != nil { + return userData, err + } + + if len(jsonStructureTestResults.MismatchedFields) > 0 { + return userData, errors.New(fmt.Sprintf( + "MismatchedFields found when deserializing data: %s", + jsonStructureTestResults.Errors().Error(), + )) + } + + // Remove allowed missing fields from MissingFields + for _, allowed = range allowMissing { + for i, field = range jsonStructureTestResults.MissingFields { + if allowed == field.String() { + jsonStructureTestResults.MissingFields = append( + jsonStructureTestResults.MissingFields[:i], + jsonStructureTestResults.MissingFields[i+1:]..., + ) + } + } + } + + if !allowAllMissing && len(jsonStructureTestResults.MissingFields) > 0 { + for _, field = range jsonStructureTestResults.MissingFields { + missingFields = append(missingFields, field.String()) + } + + return userData, errors.New(fmt.Sprintf( + "MissingFields found when deserializing data: %s", + strings.Join(missingFields, ", "), + )) + } + + // Deserialize the JSON into the struct + err = json.Unmarshal(data, &userData) + if err != nil { + return userData, err + } + + return userData, err +} diff --git a/Backend/Api/JsonSerialization/VerifyJson.go b/Backend/Api/JsonSerialization/VerifyJson.go new file mode 100644 index 0000000..3a3ae78 --- /dev/null +++ b/Backend/Api/JsonSerialization/VerifyJson.go @@ -0,0 +1,109 @@ +package JsonSerialization + +import ( + "math" + "reflect" +) + +// isIntegerType returns whether the type is an integer and if it's unsigned. +// See: https://github.com/Kangaroux/go-map-schema/blob/master/schema.go#L328 +func isIntegerType(t reflect.Type) (bool, bool) { + var ( + yes bool + unsigned bool + ) + switch t.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + yes = true + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + yes = true + unsigned = true + } + + return yes, unsigned +} + +// isFloatType returns true if the type is a floating point. Note that this doesn't +// care about the value -- unmarshaling the number "0" gives a float, not an int. +// See: https://github.com/Kangaroux/go-map-schema/blob/master/schema.go#L319 +func isFloatType(t reflect.Type) bool { + var ( + yes bool + ) + switch t.Kind() { + case reflect.Float32, reflect.Float64: + yes = true + } + + return yes +} + +// CanConvert returns whether value v is convertible to type t. +// +// If t is a pointer and v is not nil, it checks if v is convertible to the type that +// t points to. +// Modified due to not handling slices (DefaultCanConvert fails on PhotoUrls and Tags) +// See: https://github.com/Kangaroux/go-map-schema/blob/master/schema.go#L191 +func CanConvert(t reflect.Type, v reflect.Value) bool { + var ( + isPtr bool + isStruct bool + isArray bool + dstType reflect.Type + dstInt bool + unsigned bool + f float64 + srcInt bool + ) + + isPtr = t.Kind() == reflect.Ptr + isStruct = t.Kind() == reflect.Struct + isArray = t.Kind() == reflect.Array + dstType = t + + // Check if v is a nil value. + if !v.IsValid() || (v.CanAddr() && v.IsNil()) { + return isPtr + } + + // If the dst is a pointer, check if we can convert to the type it's pointing to. + if isPtr { + dstType = t.Elem() + isStruct = t.Elem().Kind() == reflect.Struct + } + + // If the dst is a struct, we should check its nested fields. + if isStruct { + return v.Kind() == reflect.Map + } + + if isArray { + return v.Kind() == reflect.String + } + + if t.Kind() == reflect.Slice { + return v.Kind() == reflect.Slice + } + + if !v.Type().ConvertibleTo(dstType) { + return false + } + + // Handle converting to an integer type. + dstInt, unsigned = isIntegerType(dstType) + if dstInt { + if isFloatType(v.Type()) { + f = v.Float() + + if math.Trunc(f) != f || unsigned && f < 0 { + return false + } + } + srcInt, _ = isIntegerType(v.Type()) + if srcInt && unsigned && v.Int() < 0 { + return false + } + } + + return true +} diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go new file mode 100644 index 0000000..bb597bd --- /dev/null +++ b/Backend/Api/Routes.go @@ -0,0 +1,75 @@ +package Api + +import ( + "log" + "net/http" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" + + "github.com/gorilla/mux" +) + +func loggingMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + log.Printf( + "%s %s %s, Content Length: %d", + r.RemoteAddr, + r.Method, + r.RequestURI, + r.ContentLength, + ) + + next.ServeHTTP(w, r) + }) +} + +func authenticationMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var ( + //userSession Auth.Session + //err error + ) + + http.Error(w, "Forbidden", http.StatusUnauthorized) + return + + /** + userSession, err = Auth.CheckCookie(r) + + if err != nil { + http.Error(w, "Forbidden", http.StatusUnauthorized) + return + } + + log.Printf( + "Authenticated user: %s (%s)", + userSession.Email, + userSession.UserID, + ) + + next.ServeHTTP(w, r) + */ + }) +} + +func InitApiEndpoints(router *mux.Router) { + var ( + api *mux.Router + adminApi *mux.Router + ) + + log.Println("Initializing API routes...") + + api = router.PathPrefix("/api/v1/").Subrouter() + + api.Use(loggingMiddleware) + + // Define routes for authentication + api.HandleFunc("/signup", Auth.Signup).Methods("POST") + // api.HandleFunc("/login", Auth.Login).Methods("POST") + // api.HandleFunc("/logout", Auth.Logout).Methods("GET") + + adminApi = api.PathPrefix("/message/").Subrouter() + + adminApi.Use(authenticationMiddleware) +} diff --git a/Backend/Database/Init.go b/Backend/Database/Init.go new file mode 100644 index 0000000..5d4d7df --- /dev/null +++ b/Backend/Database/Init.go @@ -0,0 +1,64 @@ +package Database + +import ( + "log" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +const dbUrl = "postgres://postgres:@localhost:5432/envelope" +const dbTestUrl = "postgres://postgres:@localhost:5432/envelope_test" + +var ( + DB *gorm.DB +) + +func GetModels() []interface{} { + return []interface{}{ + &Models.User{}, + &Models.MessageData{}, + &Models.MessageKey{}, + } +} + +func Init() { + var ( + model interface{} + err error + ) + + log.Println("Initializing database...") + + DB, err = gorm.Open(postgres.Open(dbUrl), &gorm.Config{}) + + if err != nil { + log.Fatalln(err) + } + + log.Println("Running AutoMigrate...") + + for _, model = range GetModels() { + DB.AutoMigrate(model) + } +} + +func InitTest() { + var ( + model interface{} + err error + ) + + DB, err = gorm.Open(postgres.Open(dbTestUrl), &gorm.Config{}) + + if err != nil { + log.Fatalln(err) + } + + for _, model = range GetModels() { + DB.Migrator().DropTable(model) + DB.AutoMigrate(model) + } +} diff --git a/Backend/Database/Users.go b/Backend/Database/Users.go new file mode 100644 index 0000000..22e3f90 --- /dev/null +++ b/Backend/Database/Users.go @@ -0,0 +1,99 @@ +package Database + +import ( + "errors" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +func GetUserById(id string) (Models.User, error) { + var ( + userData Models.User + err error + ) + + err = DB.Preload(clause.Associations). + First(&userData, "id = ?", id). + Error + + return userData, err +} + +func GetUserByUsername(username string) (Models.User, error) { + var ( + userData Models.User + err error + ) + + err = DB.Preload(clause.Associations). + First(&userData, "username = ?", username). + Error + + return userData, err +} + +func CheckUniqueUsername(username string) error { + var ( + exists bool + err error + ) + + err = DB.Model(Models.User{}). + Select("count(*) > 0"). + Where("username = ?", username). + Find(&exists). + Error + + if err != nil { + return err + } + + if exists { + return errors.New("Invalid username") + } + + return nil +} + +func CreateUser(userData *Models.User) error { + var ( + err error + ) + + err = DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(userData). + Error + + return err +} + +func UpdateUser(id string, userData *Models.User) error { + var ( + err error + ) + err = DB.Model(&userData). + Omit("id"). + Where("id = ?", id). + Updates(userData). + Error + + if err != nil { + return err + } + + err = DB.Model(Models.User{}). + Where("id = ?", id). + First(userData). + Error + + return err +} + +func DeleteUser(userData *Models.User) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Delete(userData). + Error +} diff --git a/Backend/Models/Base.go b/Backend/Models/Base.go new file mode 100644 index 0000000..2fdcd07 --- /dev/null +++ b/Backend/Models/Base.go @@ -0,0 +1,27 @@ +package Models + +import ( + "github.com/gofrs/uuid" + "gorm.io/gorm" +) + +// Base contains common columns for all tables. +type Base struct { + ID uuid.UUID `gorm:"type:uuid;primary_key;" json:"id"` +} + +// BeforeCreate will set a UUID rather than numeric ID. +func (base *Base) BeforeCreate(tx *gorm.DB) error { + var ( + id uuid.UUID + err error + ) + + id, err = uuid.NewV4() + if err != nil { + return err + } + + base.ID = id + return nil +} diff --git a/Backend/Models/Messages.go b/Backend/Models/Messages.go new file mode 100644 index 0000000..cd2bd6a --- /dev/null +++ b/Backend/Models/Messages.go @@ -0,0 +1,15 @@ +package Models + +import "github.com/gofrs/uuid" + +type MessageData struct { + Base + Data []byte `gorm:"not null" json:"data"` // Stored encrypted +} + +type MessageKey struct { + Base + UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` + MessageDataID uuid.UUID `gorm:"type:uuid;column:message_data_id;not null;" json:"message_data_id"` + SymmetricKey []byte `gorm:"not null" json:"symmetric_key"` // Stored encrypted +} diff --git a/Backend/Models/Users.go b/Backend/Models/Users.go new file mode 100644 index 0000000..b267a27 --- /dev/null +++ b/Backend/Models/Users.go @@ -0,0 +1,23 @@ +package Models + +import ( + "gorm.io/gorm" +) + +// Prevent updating the email if it has not changed +// This stops a unique constraint error +func (u *User) BeforeUpdate(tx *gorm.DB) (err error) { + if !tx.Statement.Changed("Username") { + tx.Statement.Omit("Username") + } + return nil +} + +type User struct { + Base + Username string `gorm:"not null;unique" json:"username"` + Password string `gorm:"not null" json:"password"` + ConfirmPassword string `gorm:"-" json:"confirm_password"` + AsymmetricPrivateKey []byte `gorm:"not null" json:"asymmetric_private_key"` // Stored encrypted + AsymmetricPublicKey []byte `gorm:"not null" json:"asymmetric_public_key"` +} diff --git a/Backend/go.mod b/Backend/go.mod new file mode 100644 index 0000000..b67be65 --- /dev/null +++ b/Backend/go.mod @@ -0,0 +1,26 @@ +module git.tovijaeschke.xyz/tovi/Envelope/Backend + +go 1.18 + +require ( + github.com/Kangaroux/go-map-schema v0.6.1 + github.com/gofrs/uuid v4.2.0+incompatible + github.com/gorilla/mux v1.8.0 + gorm.io/driver/postgres v1.3.4 + gorm.io/gorm v1.23.4 +) + +require ( + github.com/jackc/chunkreader/v2 v2.0.1 // indirect + github.com/jackc/pgconn v1.11.0 // indirect + github.com/jackc/pgio v1.0.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgproto3/v2 v2.2.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect + github.com/jackc/pgtype v1.10.0 // indirect + github.com/jackc/pgx/v4 v4.15.0 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.4 // indirect + golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect + golang.org/x/text v0.3.7 // indirect +) diff --git a/Backend/go.sum b/Backend/go.sum new file mode 100644 index 0000000..0756bc4 --- /dev/null +++ b/Backend/go.sum @@ -0,0 +1,192 @@ +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Kangaroux/go-map-schema v0.6.1 h1:jXpOzi7kNFC6M8QSvJuI7xeDxObBrVHwA3D6vSrxuG4= +github.com/Kangaroux/go-map-schema v0.6.1/go.mod h1:56jN+6h/N8Pmn5D+JL9gREOvZTlVEAvXtXyLd/NRjh4= +github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030IGemrRc= +github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= +github.com/cockroachdb/apd v1.1.0 h1:3LFP3629v+1aKXU5Q37mxmRxX/pIu1nijXydLShEq5I= +github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= +github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0= +github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo= +github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= +github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8= +github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= +github.com/jackc/pgconn v0.0.0-20190420214824-7e0022ef6ba3/go.mod h1:jkELnwuX+w9qN5YIfX0fl88Ehu4XC3keFuOJJk9pcnA= +github.com/jackc/pgconn v0.0.0-20190824142844-760dd75542eb/go.mod h1:lLjNuW/+OfW9/pnVKPazfWOgNfH2aPem8YQ7ilXGvJE= +github.com/jackc/pgconn v0.0.0-20190831204454-2fabfa3c18b7/go.mod h1:ZJKsE/KZfsUgOEh9hBm+xYTstcNHg7UPMVJqRfQxq4s= +github.com/jackc/pgconn v1.8.0/go.mod h1:1C2Pb36bGIP9QHGBYCjnyhqu7Rv3sGshaQUvmfGIB/o= +github.com/jackc/pgconn v1.9.0/go.mod h1:YctiPyvzfU11JFxoXokUOOKQXQmDMoJL9vJzHH8/2JY= +github.com/jackc/pgconn v1.9.1-0.20210724152538-d89c8390a530/go.mod h1:4z2w8XhRbP1hYxkpTuBjTS3ne3J48K83+u0zoyvg2pI= +github.com/jackc/pgconn v1.11.0 h1:HiHArx4yFbwl91X3qqIHtUFoiIfLNJXCQRsnzkiwwaQ= +github.com/jackc/pgconn v1.11.0/go.mod h1:4z2w8XhRbP1hYxkpTuBjTS3ne3J48K83+u0zoyvg2pI= +github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE= +github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= +github.com/jackc/pgmock v0.0.0-20190831213851-13a1b77aafa2/go.mod h1:fGZlG77KXmcq05nJLRkk0+p82V8B8Dw8KN2/V9c/OAE= +github.com/jackc/pgmock v0.0.0-20201204152224-4fe30f7445fd/go.mod h1:hrBW0Enj2AZTNpt/7Y5rr2xe/9Mn757Wtb2xeBzPv2c= +github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65 h1:DadwsjnMwFjfWc9y5Wi/+Zz7xoE5ALHsRQlOctkOiHc= +github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgproto3 v1.1.0/go.mod h1:eR5FA3leWg7p9aeAqi37XOTgTIbkABlvcPB3E5rlc78= +github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190420180111-c116219b62db/go.mod h1:bhq50y+xrl9n5mRYyCBFKkpRVTLYJVWeCc+mEAI3yXA= +github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190609003834-432c2951c711/go.mod h1:uH0AWtUmuShn0bcesswc4aBTWGvw0cAxIJp+6OB//Wg= +github.com/jackc/pgproto3/v2 v2.0.0-rc3/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= +github.com/jackc/pgproto3/v2 v2.0.0-rc3.0.20190831210041-4c03ce451f29/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= +github.com/jackc/pgproto3/v2 v2.0.6/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= +github.com/jackc/pgproto3/v2 v2.1.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= +github.com/jackc/pgproto3/v2 v2.2.0 h1:r7JypeP2D3onoQTCxWdTpCtJ4D+qpKr0TxvoyMhZ5ns= +github.com/jackc/pgproto3/v2 v2.2.0/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= +github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b h1:C8S2+VttkHFdOOCXJe+YGfa4vHYwlt4Zx+IVXQ97jYg= +github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b/go.mod h1:vsD4gTJCa9TptPL8sPkXrLZ+hDuNrZCnj29CQpr4X1E= +github.com/jackc/pgtype v0.0.0-20190421001408-4ed0de4755e0/go.mod h1:hdSHsc1V01CGwFsrv11mJRHWJ6aifDLfdV3aVjFF0zg= +github.com/jackc/pgtype v0.0.0-20190824184912-ab885b375b90/go.mod h1:KcahbBH1nCMSo2DXpzsoWOAfFkdEtEJpPbVLq8eE+mc= +github.com/jackc/pgtype v0.0.0-20190828014616-a8802b16cc59/go.mod h1:MWlu30kVJrUS8lot6TQqcg7mtthZ9T0EoIBFiJcmcyw= +github.com/jackc/pgtype v1.8.1-0.20210724151600-32e20a603178/go.mod h1:C516IlIV9NKqfsMCXTdChteoXmwgUceqaLfjg2e3NlM= +github.com/jackc/pgtype v1.10.0 h1:ILnBWrRMSXGczYvmkYD6PsYyVFUNLTnIUJHHDLmqk38= +github.com/jackc/pgtype v1.10.0/go.mod h1:LUMuVrfsFfdKGLw+AFFVv6KtHOFMwRgDDzBt76IqCA4= +github.com/jackc/pgx/v4 v4.0.0-20190420224344-cc3461e65d96/go.mod h1:mdxmSJJuR08CZQyj1PVQBHy9XOp5p8/SHH6a0psbY9Y= +github.com/jackc/pgx/v4 v4.0.0-20190421002000-1b8f0016e912/go.mod h1:no/Y67Jkk/9WuGR0JG/JseM9irFbnEPbuWV2EELPNuM= +github.com/jackc/pgx/v4 v4.0.0-pre1.0.20190824185557-6972a5742186/go.mod h1:X+GQnOEnf1dqHGpw7JmHqHc1NxDoalibchSk9/RWuDc= +github.com/jackc/pgx/v4 v4.12.1-0.20210724153913-640aa07df17c/go.mod h1:1QD0+tgSXP7iUjYm9C1NxKhny7lq6ee99u/z+IHFcgs= +github.com/jackc/pgx/v4 v4.15.0 h1:B7dTkXsdILD3MF987WGGCcg+tvLW6bZJdEcqVFeU//w= +github.com/jackc/pgx/v4 v4.15.0/go.mod h1:D/zyOyXiaM1TmVWnOM18p0xdDtdakRBa0RsVGI3U3bw= +github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= +github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= +github.com/jackc/puddle v1.1.3/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= +github.com/jackc/puddle v1.2.1/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.4 h1:tHnRBy1i5F2Dh8BAFxqFzxKqqvezXrL2OW1TnX+Mlas= +github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.10.2 h1:AqzbZs4ZoCBp+GtejcpCpcxM3zlSMx29dXbUSeVtJb8= +github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= +github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= +github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= +github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= +github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= +github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= +github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= +go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= +golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190823170909-c4a336ef6a2f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/postgres v1.3.4 h1:evZ7plF+Bp+Lr1mO5NdPvd6M/N98XtwHixGB+y7fdEQ= +gorm.io/driver/postgres v1.3.4/go.mod h1:y0vEuInFKJtijuSGu9e5bs5hzzSzPK+LancpKpvbRBw= +gorm.io/gorm v1.23.1/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk= +gorm.io/gorm v1.23.4 h1:1BKWM67O6CflSLcwGQR7ccfmC4ebOxQrTfOQGRE9wjg= +gorm.io/gorm v1.23.4/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= diff --git a/Backend/main.go b/Backend/main.go new file mode 100644 index 0000000..009e8ae --- /dev/null +++ b/Backend/main.go @@ -0,0 +1,26 @@ +package main + +import ( + "net/http" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + + "github.com/gorilla/mux" +) + +func init() { + Database.Init() +} + +func main() { + var ( + router *mux.Router + ) + + router = mux.NewRouter() + + Api.InitApiEndpoints(router) + + http.ListenAndServe(":8080", router) +} diff --git a/mobile/.gitignore b/mobile/.gitignore new file mode 100644 index 0000000..0fa6b67 --- /dev/null +++ b/mobile/.gitignore @@ -0,0 +1,46 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# Web related +lib/generated_plugin_registrant.dart + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/mobile/.metadata b/mobile/.metadata new file mode 100644 index 0000000..166a998 --- /dev/null +++ b/mobile/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: c860cba910319332564e1e9d470a17074c1f2dfd + channel: stable + +project_type: app diff --git a/mobile/README.md b/mobile/README.md new file mode 100644 index 0000000..f0f6dc1 --- /dev/null +++ b/mobile/README.md @@ -0,0 +1,16 @@ +# mobile + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook) + +For help getting started with Flutter, view our +[online documentation](https://flutter.dev/docs), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/mobile/analysis_options.yaml b/mobile/analysis_options.yaml new file mode 100644 index 0000000..61b6c4d --- /dev/null +++ b/mobile/analysis_options.yaml @@ -0,0 +1,29 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at + # https://dart-lang.github.io/linter/lints/index.html. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/mobile/android/.gitignore b/mobile/android/.gitignore new file mode 100644 index 0000000..6f56801 --- /dev/null +++ b/mobile/android/.gitignore @@ -0,0 +1,13 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java + +# Remember to never publicly share your keystore. +# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app +key.properties +**/*.keystore +**/*.jks diff --git a/mobile/android/app/build.gradle b/mobile/android/app/build.gradle new file mode 100644 index 0000000..5536a1b --- /dev/null +++ b/mobile/android/app/build.gradle @@ -0,0 +1,68 @@ +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterRoot = localProperties.getProperty('flutter.sdk') +if (flutterRoot == null) { + throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" + +android { + compileSdkVersion flutter.compileSdkVersion + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = '1.8' + } + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId "com.example.mobile" + minSdkVersion flutter.minSdkVersion + targetSdkVersion flutter.targetSdkVersion + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig signingConfigs.debug + } + } +} + +flutter { + source '../..' +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" +} diff --git a/mobile/android/app/src/debug/AndroidManifest.xml b/mobile/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..4e87af5 --- /dev/null +++ b/mobile/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..c655c32 --- /dev/null +++ b/mobile/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + diff --git a/mobile/android/app/src/main/kotlin/com/example/mobile/MainActivity.kt b/mobile/android/app/src/main/kotlin/com/example/mobile/MainActivity.kt new file mode 100644 index 0000000..5b736d4 --- /dev/null +++ b/mobile/android/app/src/main/kotlin/com/example/mobile/MainActivity.kt @@ -0,0 +1,6 @@ +package com.example.mobile + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() { +} diff --git a/mobile/android/app/src/main/res/drawable-v21/launch_background.xml b/mobile/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/mobile/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/mobile/android/app/src/main/res/drawable/launch_background.xml b/mobile/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/mobile/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..db77bb4b7b0906d62b1847e87f15cdcacf6a4f29 GIT binary patch literal 544 zcmeAS@N?(olHy`uVBq!ia0vp^9w5xY3?!3`olAj~WQl7;NpOBzNqJ&XDuZK6ep0G} zXKrG8YEWuoN@d~6R2!h8bpbvhu0Wd6uZuB!w&u2PAxD2eNXD>P5D~Wn-+_Wa#27Xc zC?Zj|6r#X(-D3u$NCt}(Ms06KgJ4FxJVv{GM)!I~&n8Bnc94O7-Hd)cjDZswgC;Qs zO=b+9!WcT8F?0rF7!Uys2bs@gozCP?z~o%U|N3vA*22NaGQG zlg@K`O_XuxvZ&Ks^m&R!`&1=spLvfx7oGDKDwpwW`#iqdw@AL`7MR}m`rwr|mZgU`8P7SBkL78fFf!WnuYWm$5Z0 zNXhDbCv&49sM544K|?c)WrFfiZvCi9h0O)B3Pgg&ebxsLQ05GG~ AQ2+n{ literal 0 HcmV?d00001 diff --git a/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..17987b79bb8a35cc66c3c1fd44f5a5526c1b78be GIT binary patch literal 442 zcmeAS@N?(olHy`uVBq!ia0vp^1|ZDA3?vioaBc-sk|nMYCBgY=CFO}lsSJ)O`AMk? zp1FzXsX?iUDV2pMQ*D5Xx&nMcT!A!W`0S9QKQy;}1Cl^CgaH=;G9cpY;r$Q>i*pfB zP2drbID<_#qf;rPZx^FqH)F_D#*k@@q03KywUtLX8Ua?`H+NMzkczFPK3lFz@i_kW%1NOn0|D2I9n9wzH8m|-tHjsw|9>@K=iMBhxvkv6m8Y-l zytQ?X=U+MF$@3 zt`~i=@j|6y)RWMK--}M|=T`o&^Ni>IoWKHEbBXz7?A@mgWoL>!*SXo`SZH-*HSdS+ yn*9;$7;m`l>wYBC5bq;=U}IMqLzqbYCidGC!)_gkIk_C@Uy!y&wkt5C($~2D>~)O*cj@FGjOCM)M>_ixfudOh)?xMu#Fs z#}Y=@YDTwOM)x{K_j*Q;dPdJ?Mz0n|pLRx{4n|)f>SXlmV)XB04CrSJn#dS5nK2lM zrZ9#~WelCp7&e13Y$jvaEXHskn$2V!!DN-nWS__6T*l;H&Fopn?A6HZ-6WRLFP=R` zqG+CE#d4|IbyAI+rJJ`&x9*T`+a=p|0O(+s{UBcyZdkhj=yS1>AirP+0R;mf2uMgM zC}@~JfByORAh4SyRgi&!(cja>F(l*O+nd+@4m$|6K6KDn_&uvCpV23&>G9HJp{xgg zoq1^2_p9@|WEo z*X_Uko@K)qYYv~>43eQGMdbiGbo>E~Q& zrYBH{QP^@Sti!`2)uG{irBBq@y*$B zi#&(U-*=fp74j)RyIw49+0MRPMRU)+a2r*PJ$L5roHt2$UjExCTZSbq%V!HeS7J$N zdG@vOZB4v_lF7Plrx+hxo7(fCV&}fHq)$ literal 0 HcmV?d00001 diff --git a/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..d5f1c8d34e7a88e3f88bea192c3a370d44689c3c GIT binary patch literal 1031 zcmeAS@N?(olHy`uVBq!ia0vp^6F``Q8Ax83A=Cw=BuiW)N`mv#O3D+9QW+dm@{>{( zJaZG%Q-e|yQz{EjrrIztFa`(sgt!6~Yi|1%a`XoT0ojZ}lNrNjb9xjc(B0U1_% zz5^97Xt*%oq$rQy4?0GKNfJ44uvxI)gC`h-NZ|&0-7(qS@?b!5r36oQ}zyZrNO3 zMO=Or+<~>+A&uN&E!^Sl+>xE!QC-|oJv`ApDhqC^EWD|@=#J`=d#Xzxs4ah}w&Jnc z$|q_opQ^2TrnVZ0o~wh<3t%W&flvYGe#$xqda2bR_R zvPYgMcHgjZ5nSA^lJr%;<&0do;O^tDDh~=pIxA#coaCY>&N%M2^tq^U%3DB@ynvKo}b?yu-bFc-u0JHzced$sg7S3zqI(2 z#Km{dPr7I=pQ5>FuK#)QwK?Y`E`B?nP+}U)I#c1+FM*1kNvWG|a(TpksZQ3B@sD~b zpQ2)*V*TdwjFOtHvV|;OsiDqHi=6%)o4b!)x$)%9pGTsE z-JL={-Ffv+T87W(Xpooq<`r*VzWQcgBN$$`u}f>-ZQI1BB8ykN*=e4rIsJx9>z}*o zo~|9I;xof literal 0 HcmV?d00001 diff --git a/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..4d6372eebdb28e45604e46eeda8dd24651419bc0 GIT binary patch literal 1443 zcmb`G{WsKk6vsdJTdFg%tJav9_E4vzrOaqkWF|A724Nly!y+?N9`YV6wZ}5(X(D_N(?!*n3`|_r0Hc?=PQw&*vnU?QTFY zB_MsH|!j$PP;I}?dppoE_gA(4uc!jV&0!l7_;&p2^pxNo>PEcNJv za5_RT$o2Mf!<+r?&EbHH6nMoTsDOa;mN(wv8RNsHpG)`^ymG-S5By8=l9iVXzN_eG%Xg2@Xeq76tTZ*dGh~Lo9vl;Zfs+W#BydUw zCkZ$o1LqWQO$FC9aKlLl*7x9^0q%0}$OMlp@Kk_jHXOjofdePND+j!A{q!8~Jn+s3 z?~~w@4?egS02}8NuulUA=L~QQfm;MzCGd)XhiftT;+zFO&JVyp2mBww?;QByS_1w! zrQlx%{^cMj0|Bo1FjwY@Q8?Hx0cIPF*@-ZRFpPc#bBw{5@tD(5%sClzIfl8WU~V#u zm5Q;_F!wa$BSpqhN>W@2De?TKWR*!ujY;Yylk_X5#~V!L*Gw~;$%4Q8~Mad z@`-kG?yb$a9cHIApZDVZ^U6Xkp<*4rU82O7%}0jjHlK{id@?-wpN*fCHXyXh(bLt* zPc}H-x0e4E&nQ>y%B-(EL=9}RyC%MyX=upHuFhAk&MLbsF0LP-q`XnH78@fT+pKPW zu72MW`|?8ht^tz$iC}ZwLp4tB;Q49K!QCF3@!iB1qOI=?w z7In!}F~ij(18UYUjnbmC!qKhPo%24?8U1x{7o(+?^Zu0Hx81|FuS?bJ0jgBhEMzf< zCgUq7r2OCB(`XkKcN-TL>u5y#dD6D!)5W?`O5)V^>jb)P)GBdy%t$uUMpf$SNV31$ zb||OojAbvMP?T@$h_ZiFLFVHDmbyMhJF|-_)HX3%m=CDI+ID$0^C>kzxprBW)hw(v zr!Gmda);ICoQyhV_oP5+C%?jcG8v+D@9f?Dk*!BxY}dazmrT@64UrP3hlslANK)bq z$67n83eh}OeW&SV@HG95P|bjfqJ7gw$e+`Hxo!4cx`jdK1bJ>YDSpGKLPZ^1cv$ek zIB?0S<#tX?SJCLWdMd{-ME?$hc7A$zBOdIJ)4!KcAwb=VMov)nK;9z>x~rfT1>dS+ zZ6#`2v@`jgbqq)P22H)Tx2CpmM^o1$B+xT6`(v%5xJ(?j#>Q$+rx_R|7TzDZe{J6q zG1*EcU%tE?!kO%^M;3aM6JN*LAKUVb^xz8-Pxo#jR5(-KBeLJvA@-gxNHx0M-ZJLl z;#JwQoh~9V?`UVo#}{6ka@II>++D@%KqGpMdlQ}?9E*wFcf5(#XQnP$Dk5~%iX^>f z%$y;?M0BLp{O3a(-4A?ewryHrrD%cx#Q^%KY1H zNre$ve+vceSLZcNY4U(RBX&)oZn*Py()h)XkE?PL$!bNb{N5FVI2Y%LKEm%yvpyTP z(1P?z~7YxD~Rf<(a@_y` literal 0 HcmV?d00001 diff --git a/mobile/android/app/src/main/res/values-night/styles.xml b/mobile/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..3db14bb --- /dev/null +++ b/mobile/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/mobile/android/app/src/main/res/values/styles.xml b/mobile/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..d460d1e --- /dev/null +++ b/mobile/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/mobile/android/app/src/profile/AndroidManifest.xml b/mobile/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..4e87af5 --- /dev/null +++ b/mobile/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/mobile/android/build.gradle b/mobile/android/build.gradle new file mode 100644 index 0000000..4256f91 --- /dev/null +++ b/mobile/android/build.gradle @@ -0,0 +1,31 @@ +buildscript { + ext.kotlin_version = '1.6.10' + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:4.1.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = '../build' +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(':app') +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/mobile/android/gradle.properties b/mobile/android/gradle.properties new file mode 100644 index 0000000..94adc3a --- /dev/null +++ b/mobile/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx1536M +android.useAndroidX=true +android.enableJetifier=true diff --git a/mobile/android/gradle/wrapper/gradle-wrapper.properties b/mobile/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..bc6a58a --- /dev/null +++ b/mobile/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Jun 23 08:50:38 CEST 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip diff --git a/mobile/android/settings.gradle b/mobile/android/settings.gradle new file mode 100644 index 0000000..44e62bc --- /dev/null +++ b/mobile/android/settings.gradle @@ -0,0 +1,11 @@ +include ':app' + +def localPropertiesFile = new File(rootProject.projectDir, "local.properties") +def properties = new Properties() + +assert localPropertiesFile.exists() +localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } + +def flutterSdkPath = properties.getProperty("flutter.sdk") +assert flutterSdkPath != null, "flutter.sdk not set in local.properties" +apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" diff --git a/mobile/ios/.gitignore b/mobile/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/mobile/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/mobile/ios/Flutter/AppFrameworkInfo.plist b/mobile/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..8d4492f --- /dev/null +++ b/mobile/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 9.0 + + diff --git a/mobile/ios/Flutter/Debug.xcconfig b/mobile/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/mobile/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/mobile/ios/Flutter/Release.xcconfig b/mobile/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/mobile/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/mobile/ios/Runner.xcodeproj/project.pbxproj b/mobile/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..e400c34 --- /dev/null +++ b/mobile/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,481 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 1300; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.mobile; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.mobile; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.mobile; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/mobile/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/mobile/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/mobile/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/mobile/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/mobile/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..c87d15a --- /dev/null +++ b/mobile/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mobile/ios/Runner.xcworkspace/contents.xcworkspacedata b/mobile/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/mobile/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/mobile/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/mobile/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/mobile/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/mobile/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/mobile/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/mobile/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..70693e4 --- /dev/null +++ b/mobile/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import UIKit +import Flutter + +@UIApplicationMain +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000000000000000000000000000000000000..dc9ada4725e9b0ddb1deab583e5b5102493aa332 GIT binary patch literal 10932 zcmeHN2~<R zh`|8`A_PQ1nSu(UMFx?8j8PC!!VDphaL#`F42fd#7Vlc`zIE4n%Y~eiz4y1j|NDpi z?<@|pSJ-HM`qifhf@m%MamgwK83`XpBA<+azdF#2QsT{X@z0A9Bq>~TVErigKH1~P zRX-!h-f0NJ4Mh++{D}J+K>~~rq}d%o%+4dogzXp7RxX4C>Km5XEI|PAFDmo;DFm6G zzjVoB`@qW98Yl0Kvc-9w09^PrsobmG*Eju^=3f?0o-t$U)TL1B3;sZ^!++3&bGZ!o-*6w?;oOhf z=A+Qb$scV5!RbG+&2S}BQ6YH!FKb0``VVX~T$dzzeSZ$&9=X$3)_7Z{SspSYJ!lGE z7yig_41zpQ)%5dr4ff0rh$@ky3-JLRk&DK)NEIHecf9c*?Z1bUB4%pZjQ7hD!A0r-@NF(^WKdr(LXj|=UE7?gBYGgGQV zidf2`ZT@pzXf7}!NH4q(0IMcxsUGDih(0{kRSez&z?CFA0RVXsVFw3^u=^KMtt95q z43q$b*6#uQDLoiCAF_{RFc{!H^moH_cmll#Fc^KXi{9GDl{>%+3qyfOE5;Zq|6#Hb zp^#1G+z^AXfRKaa9HK;%b3Ux~U@q?xg<2DXP%6k!3E)PA<#4$ui8eDy5|9hA5&{?v z(-;*1%(1~-NTQ`Is1_MGdQ{+i*ccd96ab$R$T3=% zw_KuNF@vI!A>>Y_2pl9L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VnBMKvT*)ew*R;&8vu%?Z&S>s?8?)3*YawM0P4!q$Kv zMmKh3lgE~&w&v%wVzH3Oe=jeNT=n@Y6J6TdHWTjXfX~-=1A1Bw`EW8rn}MqeI34nh zexFeA?&C3B2(E?0{drE@DA2pu(A#ElY&6el60Rn|Qpn-FkfQ8M93AfWIr)drgDFEU zghdWK)^71EWCP(@(=c4kfH1Y(4iugD4fve6;nSUpLT%!)MUHs1!zJYy4y||C+SwQ! z)KM&$7_tyM`sljP2fz6&Z;jxRn{Wup8IOUx8D4uh&(=O zx-7$a;U><*5L^!%xRlw)vAbh;sdlR||& ze}8_8%)c2Fwy=F&H|LM+p{pZB5DKTx>Y?F1N%BlZkXf!}JeGuMZk~LPi7{cidvUGB zAJ4LVeNV%XO>LTrklB#^-;8nb;}6l;1oW&WS=Mz*Az!4cqqQzbOSFq`$Q%PfD7srM zpKgP-D_0XPTRX*hAqeq0TDkJ;5HB1%$3Np)99#16c{ zJImlNL(npL!W|Gr_kxl1GVmF5&^$^YherS7+~q$p zt}{a=*RiD2Ikv6o=IM1kgc7zqpaZ;OB)P!1zz*i3{U()Dq#jG)egvK}@uFLa`oyWZ zf~=MV)|yJn`M^$N%ul5);JuQvaU1r2wt(}J_Qgyy`qWQI`hEeRX0uC@c1(dQ2}=U$ tNIIaX+dr)NRWXcxoR{>fqI{SF_dm1Ylv~=3YHI)h002ovPDHLkV1g(pWS;;4 literal 0 HcmV?d00001 diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..f091b6b0bca859a3f474b03065bef75ba58a9e4c GIT binary patch literal 1588 zcmV-42Fv-0P)C1SqPt}wig>|5Crh^=oyX$BK<}M8eLU3e2hGT;=G|!_SP)7zNI6fqUMB=)y zRAZ>eDe#*r`yDAVgB_R*LB*MAc)8(b{g{9McCXW!lq7r(btRoB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ga6=hxw6QasLPnee@3^Rr*M{CdaL5=R41nLs(AHk_=Y+A9$2&H(B7!_pURs&8aNw7?`&Z&xY_Ye z)~D5Bog^td-^QbUtkTirdyK^mTHAOuptDflut!#^lnKqU md>ggs(5nOWAqO?umG&QVYK#ibz}*4>0000U6E9hRK9^#O7(mu>ETqrXGsduA8$)?`v2seloOCza43C{NQ$$gAOH**MCn0Q?+L7dl7qnbRdqZ8LSVp1ItDxhxD?t@5_yHg6A8yI zC*%Wgg22K|8E#!~cTNYR~@Y9KepMPrrB8cABapAFa=`H+UGhkXUZV1GnwR1*lPyZ;*K(i~2gp|@bzp8}og7e*#% zEnr|^CWdVV!-4*Y_7rFvlww2Ze+>j*!Z!pQ?2l->4q#nqRu9`ELo6RMS5=br47g_X zRw}P9a7RRYQ%2Vsd0Me{_(EggTnuN6j=-?uFS6j^u69elMypu?t>op*wBx<=Wx8?( ztpe^(fwM6jJX7M-l*k3kEpWOl_Vk3@(_w4oc}4YF4|Rt=2V^XU?#Yz`8(e?aZ@#li0n*=g^qOcVpd-Wbok=@b#Yw zqn8u9a)z>l(1kEaPYZ6hwubN6i<8QHgsu0oE) ziJ(p;Wxm>sf!K+cw>R-(^Y2_bahB+&KI9y^);#0qt}t-$C|Bo71lHi{_+lg#f%RFy z0um=e3$K3i6K{U_4K!EX?F&rExl^W|G8Z8;`5z-k}OGNZ0#WVb$WCpQu-_YsiqKP?BB# vzVHS-CTUF4Ozn5G+mq_~Qqto~ahA+K`|lyv3(-e}00000NkvXXu0mjfd`9t{ literal 0 HcmV?d00001 diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..d0ef06e7edb86cdfe0d15b4b0d98334a86163658 GIT binary patch literal 1716 zcmds$`#;kQ7{|XelZftyR5~xW7?MLxS4^|Hw3&P7^y)@A9Fj{Xm1~_CIV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XfX~-=1A1Bw`EW8rn}MqeI34nh zexFeA?&C3B2(E?0{drE@DA2pu(A#ElY&6el60Rn|Qpn-FkfQ8M93AfWIr)drgDFEU zghdWK)^71EWCP(@(=c4kfH1Y(4iugD4fve6;nSUpLT%!)MUHs1!zJYy4y||C+SwQ! z)KM&$7_tyM`sljP2fz6&Z;jxRn{Wup8IOUx8D4uh&(=O zx-7$a;U><*5L^!%xRlw)vAbh;sdlR||& ze}8_8%)c2Fwy=F&H|LM+p{pZB5DKTx>Y?F1N%BlZkXf!}JeGuMZk~LPi7{cidvUGB zAJ4LVeNV%XO>LTrklB#^-;8nb;}6l;1oW&WS=Mz*Az!4cqqQzbOSFq`$Q%PfD7srM zpKgP-D_0XPTRX*hAqeq0TDkJ;5HB1%$3Np)99#16c{ zJImlNL(npL!W|Gr_kxl1GVmF5&^$^YherS7+~q$p zt}{a=*RiD2Ikv6o=IM1kgc7zqpaZ;OB)P!1zz*i3{U()Dq#jG)egvK}@uFLa`oyWZ zf~=MV)|yJn`M^$N%ul5);JuQvaU1r2wt(}J_Qgyy`qWQI`hEeRX0uC@c1(dQ2}=U$ tNIIaX+dr)NRWXcxoR{>fqI{SF_dm1Ylv~=3YHI)h002ovPDHLkV1g(pWS;;4 literal 0 HcmV?d00001 diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..c8f9ed8f5cee1c98386d13b17e89f719e83555b2 GIT binary patch literal 1895 zcmV-t2blPYP)FQtfgmafE#=YDCq`qUBt#QpG%*H6QHY765~R=q zZ6iudfM}q!Pz#~9JgOi8QJ|DSu?1-*(kSi1K4#~5?#|rh?sS)(-JQqX*}ciXJ56_H zdw=^s_srbAdqxlvGyrgGet#6T7_|j;95sL%MtM;q86vOxKM$f#puR)Bjv9Zvz9-di zXOTSsZkM83)E9PYBXC<$6(|>lNLV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ckUFs;ry9Ow$CD@ztz5K-*D$^{i(_1llhSh^ zEkL$}tsQt5>QA^;QgjgIfBDmcOgi5YDyu?t6vSnbp=1+@6D& z5MJ}B8q;bRlVoxasyhcUF1+)o`&3r0colr}QJ3hcSdLu;9;td>kf@Tcn<@9sIx&=m z;AD;SCh95=&p;$r{Xz3iWCO^MX83AGJ(yH&eTXgv|0=34#-&WAmw{)U7OU9!Wz^!7 zZ%jZFi@JR;>Mhi7S>V7wQ176|FdW2m?&`qa(ScO^CFPR80HucLHOTy%5s*HR0^8)i h0WYBP*#0Ks^FNSabJA*5${_#%002ovPDHLkV1oKhTl@e3 literal 0 HcmV?d00001 diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..a6d6b8609df07bf62e5100a53a01510388bd2b22 GIT binary patch literal 2665 zcmV-v3YPVWP)oFh3q0MFesq&64WThn3$;G69TfjsAv=f2G9}p zgSx99+!YV6qME!>9MD13x)k(+XE7W?_O4LoLb5ND8 zaV{9+P@>42xDfRiYBMSgD$0!vssptcb;&?u9u(LLBKmkZ>RMD=kvD3h`sk6!QYtBa ztlZI#nu$8lJ^q2Z79UTgZe>BU73(Aospiq+?SdMt8lDZ;*?@tyWVZVS_Q7S&*tJaiRlJ z+aSMOmbg3@h5}v;A*c8SbqM3icg-`Cnwl;7Ts%A1RkNIp+Txl-Ckkvg4oxrqGA5ewEgYqwtECD<_3Egu)xGllKt&J8g&+=ac@Jq4-?w6M3b*>w5 z69N3O%=I^6&UL5gZ!}trC7bUj*12xLdkNs~Bz4QdJJ*UDZox2UGR}SNg@lmOvhCc~ z*f_UeXv(=#I#*7>VZx2ObEN~UoGUTl=-@)E;YtCRZ>SVp$p9yG5hEFZ!`wI!spd)n zSk+vK0Vin7FL{7f&6OB%f;SH22dtbcF<|9fi2Fp%q4kxL!b1#l^)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YJ9zD=M%4AFQ`}k8OC$9s XsPq=LnkwKG00000NkvXXu0mjfhAk5^ literal 0 HcmV?d00001 diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..a6d6b8609df07bf62e5100a53a01510388bd2b22 GIT binary patch literal 2665 zcmV-v3YPVWP)oFh3q0MFesq&64WThn3$;G69TfjsAv=f2G9}p zgSx99+!YV6qME!>9MD13x)k(+XE7W?_O4LoLb5ND8 zaV{9+P@>42xDfRiYBMSgD$0!vssptcb;&?u9u(LLBKmkZ>RMD=kvD3h`sk6!QYtBa ztlZI#nu$8lJ^q2Z79UTgZe>BU73(Aospiq+?SdMt8lDZ;*?@tyWVZVS_Q7S&*tJaiRlJ z+aSMOmbg3@h5}v;A*c8SbqM3icg-`Cnwl;7Ts%A1RkNIp+Txl-Ckkvg4oxrqGA5ewEgYqwtECD<_3Egu)xGllKt&J8g&+=ac@Jq4-?w6M3b*>w5 z69N3O%=I^6&UL5gZ!}trC7bUj*12xLdkNs~Bz4QdJJ*UDZox2UGR}SNg@lmOvhCc~ z*f_UeXv(=#I#*7>VZx2ObEN~UoGUTl=-@)E;YtCRZ>SVp$p9yG5hEFZ!`wI!spd)n zSk+vK0Vin7FL{7f&6OB%f;SH22dtbcF<|9fi2Fp%q4kxL!b1#l^)8dUwJ zwEf{(wJj@8iYDVnKB`eSU+;ml-t2`@%_)0jDM`+a46xhDbBj2+&Ih>1A>6aky#(-SYyE{R3f#y57wfLs z6w1p~$bp;6!9DX$M+J~S@D6vJAaElETnsX4h9a5tvPhC3L@qB~bOzkL@^z0k_hS{T4PF*TDrgdXp+dzsE? z>V|VR035Pl9n5&-RePFdS{7KAr2vPOqR9=M$vXA1Yy5>w;EsF`;OK{2pkn-kpp9Pw z)r;5JfJKKaT$4qCb{TaXHjb$QA{y0EYy*+b1XI;6Ah- zw13P)xT`>~eFoJC!>{2XL(a_#upp3gaR1#5+L(Jmzp4TBnx{~WHedpJ1ch8JFk~Sw z>F+gN+i+VD?gMXwcIhn8rz`>e>J^TI3E-MW>f}6R-pL}>WMOa0k#jN+`RyUVUC;#D zg|~oS^$6%wpF{^Qr+}X>0PKcr3Fc&>Z>uv@C);pwDs@2bZWhYP!rvGx?_|q{d`t<*XEb#=aOb=N+L@CVBGqImZf&+a zCQEa3$~@#kC);pasdG=f6tuIi0PO-y&tvX%>Mv=oY3U$nD zJ#gMegnQ46pq+3r=;zmgcG+zRc9D~c>z+jo9&D+`E6$LmyFqlmCYw;-Zooma{sR@~ z)_^|YL1&&@|GXo*pivH7k!msl+$Sew3%XJnxajt0K%3M6Bd&YFNy9}tWG^aovK2eX z1aL1%7;KRDrA@eG-Wr6w+;*H_VD~qLiVI`{_;>o)k`{8xa3EJT1O_>#iy_?va0eR? zDV=N%;Zjb%Z2s$@O>w@iqt!I}tLjGk!=p`D23I}N4Be@$(|iSA zf3Ih7b<{zqpDB4WF_5X1(peKe+rASze%u8eKLn#KKXt;UZ+Adf$_TO+vTqshLLJ5c z52HucO=lrNVae5XWOLm!V@n-ObU11!b+DN<$RuU+YsrBq*lYT;?AwJpmNKniF0Q1< zJCo>Q$=v$@&y=sj6{r!Y&y&`0$-I}S!H_~pI&2H8Z1C|BX4VgZ^-! zje3-;x0PBD!M`v*J_)rL^+$<1VJhH*2Fi~aA7s&@_rUHYJ9zD=M%4AFQ`}k8OC$9s XsPq=LnkwKG00000NkvXXu0mjfhAk5^ literal 0 HcmV?d00001 diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..75b2d164a5a98e212cca15ea7bf2ab5de5108680 GIT binary patch literal 3831 zcmVjJBgitF5mAp-i>4+KS_oR{|13AP->1TD4=w)g|)JHOx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N7BN3!8>hajGaTVk-wl=9rxmfWtIhC{mheHgStLi^+Nz12a?4r(fz)?3A%at zMlvQmL<2-R)-@G1wJ0^zQK%mR=r4d{Y3fHp){nWXUL#|CqXl(+v+qDh>FkF9`eWrW zfr^D%LNfOcTNvtx0JXR35J0~Jpi2#P3Q&80w+nqNfc}&G0A~*)lGHKv=^FE+b(37|)zL;KLF>oiGfb(?&1 zV3XRu!Sw>@quKiab%g6jun#oZ%!>V#A%+lNc?q>6+VvyAn=kf_6z^(TZUa4Eelh{{ zqFX-#dY(EV@7l$NE&kv9u9BR8&Ojd#ZGJ6l8_BW}^r?DIS_rU2(XaGOK z225E@kH5Opf+CgD^{y29jD4gHbGf{1MD6ggQ&%>UG4WyPh5q_tb`{@_34B?xfSO*| zZv8!)q;^o-bz`MuxXk*G^}(6)ACb@=Lfs`Hxoh>`Y0NE8QRQ!*p|SH@{r8=%RKd4p z+#Ty^-0kb=-H-O`nAA3_6>2z(D=~Tbs(n8LHxD0`R0_ATFqp-SdY3(bZ3;VUM?J=O zKCNsxsgt@|&nKMC=*+ZqmLHhX1KHbAJs{nGVMs6~TiF%Q)P@>!koa$%oS zjXa=!5>P`vC-a}ln!uH1ooeI&v?=?v7?1n~P(wZ~0>xWxd_Aw;+}9#eULM7M8&E?Y zC-ZLhi3RoM92SXUb-5i-Lmt5_rfjE{6y^+24`y$1lywLyHO!)Boa7438K4#iLe?rh z2O~YGSgFUBH?og*6=r9rme=peP~ah`(8Zt7V)j5!V0KPFf_mebo3z95U8(up$-+EA^9dTRLq>Yl)YMBuch9%=e5B`Vnb>o zt03=kq;k2TgGe4|lGne&zJa~h(UGutjP_zr?a7~#b)@15XNA>Dj(m=gg2Q5V4-$)D|Q9}R#002ovPDHLkV1o7DH3k3x literal 0 HcmV?d00001 diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 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`l;s%Lb2&=8$&Ct-fV`E^4CUs)=jTk!I}2d&n!f@)bm z@ z_4Dc86+3l2*p|~;o-Sb~oXb_RuLmoifDU^&Te$*FevycC0*nE3Xws8gsWp|Rj2>SM zns)qcYj?^2sd8?N!_w~4v+f-HCF|a$TNZDoNl$I1Uq87euoNgKb6&r26TNrfkUa@o zfdiFA@p{K&mH3b8i!lcoz)V{n8Q@g(vR4ns4r6w;K z>1~ecQR0-<^J|Ndg5fvVUM9g;lbu-){#ghGw(fg>L zh)T5Ljb%lWE;V9L!;Cqk>AV1(rULYF07ZBJbGb9qbSoLAd;in9{)95YqX$J43-dY7YU*k~vrM25 zxh5_IqO0LYZW%oxQ5HOzmk4x{atE*vipUk}sh88$b2tn?!ujEHn`tQLe&vo}nMb&{ zio`xzZ&GG6&ZyN3jnaQy#iVqXE9VT(3tWY$n-)uWDQ|tc{`?fq2F`oQ{;d3aWPg4Hp-(iE{ry>MIPWL> iW8Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/mobile/ios/Runner/Base.lproj/LaunchScreen.storyboard b/mobile/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/mobile/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mobile/ios/Runner/Base.lproj/Main.storyboard b/mobile/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/mobile/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mobile/ios/Runner/Info.plist b/mobile/ios/Runner/Info.plist new file mode 100644 index 0000000..7c170fc --- /dev/null +++ b/mobile/ios/Runner/Info.plist @@ -0,0 +1,47 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Mobile + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + mobile + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + + diff --git a/mobile/ios/Runner/Runner-Bridging-Header.h b/mobile/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/mobile/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/mobile/lib/authentication/signup.dart b/mobile/lib/authentication/signup.dart new file mode 100644 index 0000000..2b3641a --- /dev/null +++ b/mobile/lib/authentication/signup.dart @@ -0,0 +1,172 @@ +import 'package:flutter/material.dart'; +import 'package:pointycastle/api.dart'; + +class Signup extends StatelessWidget { + const Signup({Key? key}) : super(key: key); + + static const String _title = 'Envelope'; + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: _title, + home: Scaffold( + backgroundColor: Colors.cyan, + appBar: AppBar( + title: null, + automaticallyImplyLeading: true, + //`true` if you want Flutter to automatically add Back Button when needed, + //or `false` if you want to force your own back button every where + leading: IconButton(icon: const Icon(Icons.arrow_back), + //onPressed:() => Navigator.pop(context, false), + onPressed:() => { + Navigator.pop(context) + } + ) + ), + body: const SafeArea( + child: SignupWidget(), + ) + ), + theme: ThemeData( + appBarTheme: const AppBarTheme( + backgroundColor: Colors.cyan, + elevation: 0, + ), + inputDecorationTheme: const InputDecorationTheme( + border: OutlineInputBorder(), + focusedBorder: OutlineInputBorder(), + labelStyle: TextStyle( + color: Colors.white, + fontSize: 30, + ), + filled: true, + fillColor: Colors.white, + ), + + ), + ); + } +} + +class SignupWidget extends StatefulWidget { + const SignupWidget({Key? key}) : super(key: key); + + @override + State createState() => _SignupWidgetState(); +} + +class _SignupWidgetState extends State { + final _formKey = GlobalKey(); + + TextEditingController usernameController = TextEditingController(); + TextEditingController passwordController = TextEditingController(); + TextEditingController passwordConfirmController = TextEditingController(); + + @override + Widget build(BuildContext context) { + const TextStyle _inputTextStyle = TextStyle(fontSize: 18, color: Colors.black); + + final ButtonStyle _buttonStyle = ElevatedButton.styleFrom( + primary: Colors.white, + onPrimary: Colors.cyan, + minimumSize: const Size.fromHeight(50), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + textStyle: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Colors.red, + ), + ); + + return Center( + child: Form( + key: _formKey, + child: Center( + child: Padding( + padding: const EdgeInsets.all(15), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + const Text('Sign Up', style: TextStyle(fontSize: 35, color: Colors.white),), + const SizedBox(height: 30), + TextFormField( + controller: usernameController, + decoration: const InputDecoration( + hintText: 'Username', + ), + style: _inputTextStyle, + // The validator receives the text that the user has entered. + validator: (value) { + if (value == null || value.isEmpty) { + return 'Create a username'; + } + return null; + }, + ), + const SizedBox(height: 5), + TextFormField( + controller: passwordController, + obscureText: true, + enableSuggestions: false, + autocorrect: false, + decoration: const InputDecoration( + hintText: 'Password', + ), + style: _inputTextStyle, + // The validator receives the text that the user has entered. + validator: (value) { + if (value == null || value.isEmpty) { + return 'Enter a password'; + } + return null; + }, + ), + const SizedBox(height: 5), + TextFormField( + controller: passwordConfirmController, + obscureText: true, + enableSuggestions: false, + autocorrect: false, + decoration: const InputDecoration( + hintText: 'Password', + ), + style: _inputTextStyle, + // The validator receives the text that the user has entered. + validator: (value) { + if (value == null || value.isEmpty) { + return 'Confirm your password'; + } + if (value != passwordController.text) { + return 'Passwords do not match'; + } + return null; + }, + ), + const SizedBox(height: 5), + ElevatedButton( + style: _buttonStyle, + onPressed: () { + if (_formKey.currentState!.validate()) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Processing Data')), + ); + + signup(context); + } + }, + child: const Text('Submit'), + ), + ], + ) + ) + ) + + ) + ); + } +} + +void signup(context) { +} diff --git a/mobile/lib/authentication/unauthenticated_landing.dart b/mobile/lib/authentication/unauthenticated_landing.dart new file mode 100644 index 0000000..515e34f --- /dev/null +++ b/mobile/lib/authentication/unauthenticated_landing.dart @@ -0,0 +1,75 @@ +import 'package:flutter/material.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import './signup.dart'; + +class UnauthenticatedLandingWidget extends StatefulWidget { + const UnauthenticatedLandingWidget({Key? key}) : super(key: key); + + @override + State createState() => _UnauthenticatedLandingWidgetState(); +} + + +class _UnauthenticatedLandingWidgetState extends State { + @override + Widget build(BuildContext context) { + final ButtonStyle buttonStyle = ElevatedButton.styleFrom( + primary: Colors.white, + onPrimary: Colors.cyan, + minimumSize: const Size.fromHeight(50), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + textStyle: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Colors.red, + ), + ); + + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Center( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: const [ + FaIcon(FontAwesomeIcons.envelope, color: Colors.white, size: 40), + SizedBox(width: 15), + Text('Envelope', style: TextStyle(fontSize: 40, color: Colors.white),) + ] + ), + ), + const SizedBox(height: 10), + Padding( + padding: const EdgeInsets.all(15), + child: Column ( + children: [ + ElevatedButton( + child: const Text('Login'), + onPressed: loginButton, + style: buttonStyle, + ), + const SizedBox(height: 20), + ElevatedButton( + child: const Text('Sign Up'), + onPressed: () => { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => const Signup()), + ), + }, + style: buttonStyle, + ), + ] + ), + ), + ], + ), + ); + } +} + +void loginButton() { +} diff --git a/mobile/lib/main.dart b/mobile/lib/main.dart new file mode 100644 index 0000000..cff251d --- /dev/null +++ b/mobile/lib/main.dart @@ -0,0 +1,25 @@ +import 'package:flutter/material.dart'; +import './authentication/unauthenticated_landing.dart'; + +void main() { + runApp(const Home()); +} + +class Home extends StatelessWidget { + const Home({Key? key}) : super(key: key); + + static const String _title = 'Envelope'; + + @override + Widget build(BuildContext context) { + return const MaterialApp( + title: _title, + home: Scaffold( + backgroundColor: Colors.cyan, + body: SafeArea( + child: UnauthenticatedLandingWidget(), + ) + ) + ); + } +} diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock new file mode 100644 index 0000000..3c4fda5 --- /dev/null +++ b/mobile/pubspec.lock @@ -0,0 +1,202 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + url: "https://pub.dartlang.org" + source: hosted + version: "2.8.2" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + characters: + dependency: transitive + description: + name: characters + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.0" + charcode: + dependency: transitive + description: + name: charcode + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.1" + clock: + dependency: transitive + description: + name: clock + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + collection: + dependency: transitive + description: + name: collection + url: "https://pub.dartlang.org" + source: hosted + version: "1.15.0" + convert: + dependency: transitive + description: + name: convert + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.1" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.4" + fake_async: + dependency: transitive + description: + name: fake_async + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.0" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.4" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + font_awesome_flutter: + dependency: "direct main" + description: + name: font_awesome_flutter + url: "https://pub.dartlang.org" + source: hosted + version: "10.1.0" + js: + dependency: transitive + description: + name: js + url: "https://pub.dartlang.org" + source: hosted + version: "0.6.4" + lints: + dependency: transitive + description: + name: lints + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" + matcher: + dependency: transitive + description: + name: matcher + url: "https://pub.dartlang.org" + source: hosted + version: "0.12.11" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.3" + meta: + dependency: transitive + description: + name: meta + url: "https://pub.dartlang.org" + source: hosted + version: "1.7.0" + path: + dependency: transitive + description: + name: path + url: "https://pub.dartlang.org" + source: hosted + version: "1.8.0" + pointycastle: + dependency: "direct main" + description: + name: pointycastle + url: "https://pub.dartlang.org" + source: hosted + version: "3.5.2" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_span: + dependency: transitive + description: + name: source_span + url: "https://pub.dartlang.org" + source: hosted + version: "1.8.1" + stack_trace: + dependency: transitive + description: + name: stack_trace + url: "https://pub.dartlang.org" + source: hosted + version: "1.10.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + string_scanner: + dependency: transitive + description: + name: string_scanner + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.0" + test_api: + dependency: transitive + description: + name: test_api + url: "https://pub.dartlang.org" + source: hosted + version: "0.4.8" + typed_data: + dependency: transitive + description: + name: typed_data + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.0" + vector_math: + dependency: transitive + description: + name: vector_math + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.1" +sdks: + dart: ">=2.16.2 <3.0.0" diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml new file mode 100644 index 0000000..4834078 --- /dev/null +++ b/mobile/pubspec.yaml @@ -0,0 +1,28 @@ +name: mobile +description: A new Flutter project. + +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +version: 1.0.0+1 + +environment: + sdk: ">=2.16.2 <3.0.0" + +dependencies: + flutter: + sdk: flutter + + cupertino_icons: ^1.0.2 + font_awesome_flutter: ^10.1.0 + pointycastle: ^3.5.2 + +dev_dependencies: + flutter_test: + sdk: flutter + + flutter_lints: ^1.0.0 + +flutter: + + uses-material-design: true + diff --git a/mobile/test/widget_test.dart b/mobile/test/widget_test.dart new file mode 100644 index 0000000..55376ce --- /dev/null +++ b/mobile/test/widget_test.dart @@ -0,0 +1,30 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility that Flutter provides. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:mobile/main.dart'; + +void main() { + testWidgets('Counter increments smoke test', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MyApp()); + + // Verify that our counter starts at 0. + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + + // Tap the '+' icon and trigger a frame. + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + + // Verify that our counter has incremented. + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + }); +} diff --git a/mobile/web/favicon.png b/mobile/web/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..8aaa46ac1ae21512746f852a42ba87e4165dfdd1 GIT binary patch literal 917 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|I14-?iy0X7 zltGxWVyS%@P(fs7NJL45ua8x7ey(0(N`6wRUPW#JP&EUCO@$SZnVVXYs8ErclUHn2 zVXFjIVFhG^g!Ppaz)DK8ZIvQ?0~DO|i&7O#^-S~(l1AfjnEK zjFOT9D}DX)@^Za$W4-*MbbUihOG|wNBYh(yU7!lx;>x^|#0uTKVr7USFmqf|i<65o z3raHc^AtelCMM;Vme?vOfh>Xph&xL%(-1c06+^uR^q@XSM&D4+Kp$>4P^%3{)XKjo zGZknv$b36P8?Z_gF{nK@`XI}Z90TzwSQO}0J1!f2c(B=V`5aP@1P1a|PZ!4!3&Gl8 zTYqUsf!gYFyJnXpu0!n&N*SYAX-%d(5gVjrHJWqXQshj@!Zm{!01WsQrH~9=kTxW#6SvuapgMqt>$=j#%eyGrQzr zP{L-3gsMA^$I1&gsBAEL+vxi1*Igl=8#8`5?A-T5=z-sk46WA1IUT)AIZHx1rdUrf zVJrJn<74DDw`j)Ki#gt}mIT-Q`XRa2-jQXQoI%w`nb|XblvzK${ZzlV)m-XcwC(od z71_OEC5Bt9GEXosOXaPTYOia#R4ID2TiU~`zVMl08TV_C%DnU4^+HE>9(CE4D6?Fz oujB08i7adh9xk7*FX66dWH6F5TM;?E2b5PlUHx3vIVCg!0Dx9vYXATM literal 0 HcmV?d00001 diff --git a/mobile/web/icons/Icon-192.png b/mobile/web/icons/Icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..b749bfef07473333cf1dd31e9eed89862a5d52aa GIT binary patch literal 5292 zcmZ`-2T+sGz6~)*FVZ`aW+(v>MIm&M-g^@e2u-B-DoB?qO+b1Tq<5uCCv>ESfRum& zp%X;f!~1{tzL__3=gjVJ=j=J>+nMj%ncXj1Q(b|Ckbw{Y0FWpt%4y%$uD=Z*c-x~o zE;IoE;xa#7Ll5nj-e4CuXB&G*IM~D21rCP$*xLXAK8rIMCSHuSu%bL&S3)8YI~vyp@KBu9Ph7R_pvKQ@xv>NQ`dZp(u{Z8K3yOB zn7-AR+d2JkW)KiGx0hosml;+eCXp6+w%@STjFY*CJ?udJ64&{BCbuebcuH;}(($@@ znNlgBA@ZXB)mcl9nbX#F!f_5Z=W>0kh|UVWnf!At4V*LQP%*gPdCXd6P@J4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bglbxep-w)PbFG!J17`<$g8lVhqD2w;Z0zGsh-r zxZ13G$G<48leNqR!DCVt9)@}(zMI5w6Wo=N zpP1*3DI;~h2WDWgcKn*f!+ORD)f$DZFwgKBafEZmeXQMAsq9sxP9A)7zOYnkHT9JU zRA`umgmP9d6=PHmFIgx=0$(sjb>+0CHG)K@cPG{IxaJ&Ueo8)0RWgV9+gO7+Bl1(F z7!BslJ2MP*PWJ;x)QXbR$6jEr5q3 z(3}F@YO_P1NyTdEXRLU6fp?9V2-S=E+YaeLL{Y)W%6`k7$(EW8EZSA*(+;e5@jgD^I zaJQ2|oCM1n!A&-8`;#RDcZyk*+RPkn_r8?Ak@agHiSp*qFNX)&i21HE?yuZ;-C<3C zwJGd1lx5UzViP7sZJ&|LqH*mryb}y|%AOw+v)yc`qM)03qyyrqhX?ub`Cjwx2PrR! z)_z>5*!*$x1=Qa-0uE7jy0z`>|Ni#X+uV|%_81F7)b+nf%iz=`fF4g5UfHS_?PHbr zB;0$bK@=di?f`dS(j{l3-tSCfp~zUuva+=EWxJcRfp(<$@vd(GigM&~vaYZ0c#BTs z3ijkxMl=vw5AS&DcXQ%eeKt!uKvh2l3W?&3=dBHU=Gz?O!40S&&~ei2vg**c$o;i89~6DVns zG>9a*`k5)NI9|?W!@9>rzJ;9EJ=YlJTx1r1BA?H`LWijk(rTax9(OAu;q4_wTj-yj z1%W4GW&K4T=uEGb+E!>W0SD_C0RR91 literal 0 HcmV?d00001 diff --git a/mobile/web/icons/Icon-512.png b/mobile/web/icons/Icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..88cfd48dff1169879ba46840804b412fe02fefd6 GIT binary patch literal 8252 zcmd5=2T+s!lYZ%-(h(2@5fr2dC?F^$C=i-}R6$UX8af(!je;W5yC_|HmujSgN*6?W z3knF*TL1$|?oD*=zPbBVex*RUIKsL<(&Rj9%^UD2IK3W?2j>D?eWQgvS-HLymHo9%~|N2Q{~j za?*X-{b9JRowv_*Mh|;*-kPFn>PI;r<#kFa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%}9mUsjUR%T!?k^(q)6FH6Af^b6 zlPg~IEwg0y;`t9y;#D+uz!oE4VP&Je!<#q*F?m5L5?J3i@!0J6q#eu z!RRU`-)HeqGi_UJZ(n~|PSNsv+Wgl{P-TvaUQ9j?ZCtvb^37U$sFpBrkT{7Jpd?HpIvj2!}RIq zH{9~+gErN2+}J`>Jvng2hwM`=PLNkc7pkjblKW|+Fk9rc)G1R>Ww>RC=r-|!m-u7( zc(a$9NG}w#PjWNMS~)o=i~WA&4L(YIW25@AL9+H9!?3Y}sv#MOdY{bb9j>p`{?O(P zIvb`n?_(gP2w3P#&91JX*md+bBEr%xUHMVqfB;(f?OPtMnAZ#rm5q5mh;a2f_si2_ z3oXWB?{NF(JtkAn6F(O{z@b76OIqMC$&oJ_&S|YbFJ*)3qVX_uNf5b8(!vGX19hsG z(OP>RmZp29KH9Ge2kKjKigUmOe^K_!UXP`von)PR8Qz$%=EmOB9xS(ZxE_tnyzo}7 z=6~$~9k0M~v}`w={AeqF?_)9q{m8K#6M{a&(;u;O41j)I$^T?lx5(zlebpY@NT&#N zR+1bB)-1-xj}R8uwqwf=iP1GbxBjneCC%UrSdSxK1vM^i9;bUkS#iRZw2H>rS<2<$ zNT3|sDH>{tXb=zq7XZi*K?#Zsa1h1{h5!Tq_YbKFm_*=A5-<~j63he;4`77!|LBlo zR^~tR3yxcU=gDFbshyF6>o0bdp$qmHS7D}m3;^QZq9kBBU|9$N-~oU?G5;jyFR7>z hN`IR97YZXIo@y!QgFWddJ3|0`sjFx!m))><{BI=FK%f8s literal 0 HcmV?d00001 diff --git a/mobile/web/icons/Icon-maskable-192.png b/mobile/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000000000000000000000000000000000000..eb9b4d76e525556d5d89141648c724331630325d GIT binary patch literal 5594 zcmdT|`#%%j|KDb2V@0DPm$^(Lx5}lO%Yv(=e*7hl@QqKS50#~#^IQPxBmuh|i9sXnt4ch@VT0F7% zMtrs@KWIOo+QV@lSs66A>2pz6-`9Jk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>(1 z@Y3Nfd>fmqvjL;?+DmZk*KsfXJf<%~(gcLwEez%>1c6XSboURUh&k=B)MS>6kw9bY z{7vdev7;A}5fy*ZE23DS{J?8at~xwVk`pEwP5^k?XMQ7u64;KmFJ#POzdG#np~F&H ze-BUh@g54)dsS%nkBb}+GuUEKU~pHcYIg4vSo$J(J|U36bs0Use+3A&IMcR%6@jv$ z=+QI+@wW@?iu}Hpyzlvj-EYeop{f65GX0O%>w#0t|V z1-svWk`hU~m`|O$kw5?Yn5UhI%9P-<45A(v0ld1n+%Ziq&TVpBcV9n}L9Tus-TI)f zd_(g+nYCDR@+wYNQm1GwxhUN4tGMLCzDzPqY$~`l<47{+l<{FZ$L6(>J)|}!bi<)| zE35dl{a2)&leQ@LlDxLQOfUDS`;+ZQ4ozrleQwaR-K|@9T{#hB5Z^t#8 zC-d_G;B4;F#8A2EBL58s$zF-=SCr`P#z zNCTnHF&|X@q>SkAoYu>&s9v@zCpv9lLSH-UZzfhJh`EZA{X#%nqw@@aW^vPcfQrlPs(qQxmC|4tp^&sHy!H!2FH5eC{M@g;ElWNzlb-+ zxpfc0m4<}L){4|RZ>KReag2j%Ot_UKkgpJN!7Y_y3;Ssz{9 z!K3isRtaFtQII5^6}cm9RZd5nTp9psk&u1C(BY`(_tolBwzV_@0F*m%3G%Y?2utyS zY`xM0iDRT)yTyYukFeGQ&W@ReM+ADG1xu@ruq&^GK35`+2r}b^V!m1(VgH|QhIPDE X>c!)3PgKfL&lX^$Z>Cpu&6)6jvi^Z! literal 0 HcmV?d00001 diff --git a/mobile/web/icons/Icon-maskable-512.png b/mobile/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000000000000000000000000000000000000..d69c56691fbdb0b7efa65097c7cc1edac12a6d3e GIT binary patch literal 20998 zcmeFZ_gj-)&^4Nb2tlbLMU<{!p(#yjqEe+=0IA_oih%ScH9@5#MNp&}Y#;;(h=A0@ zh7{>lT2MkSQ344eAvrhici!td|HJuyvJm#Y_w1Q9Yu3!26dNl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gF2|2Usww0nL^;x@1eaB)=+Clj+$fF@H( z-fqP??~QMT$KI-#m;QC*&6vkp&8699G3)Bq0*kFZXINw=b9OVaed(3(3kS|IZ)CM? zJdnW&%t8MveBuK21uiYj)_a{Fnw0OErMzMN?d$QoPwkhOwcP&p+t>P)4tHlYw-pPN z^oJ=uc$Sl>pv@fZH~ZqxSvdhF@F1s=oZawpr^-#l{IIOGG=T%QXjtwPhIg-F@k@uIlr?J->Ia zpEUQ*=4g|XYn4Gez&aHr*;t$u3oODPmc2Ku)2Og|xjc%w;q!Zz+zY)*3{7V8bK4;& zYV82FZ+8?v)`J|G1w4I0fWdKg|2b#iaazCv;|?(W-q}$o&Y}Q5d@BRk^jL7#{kbCK zSgkyu;=DV+or2)AxCBgq-nj5=@n^`%T#V+xBGEkW4lCqrE)LMv#f;AvD__cQ@Eg3`~x| zW+h9mofSXCq5|M)9|ez(#X?-sxB%Go8};sJ?2abp(Y!lyi>k)|{M*Z$c{e1-K4ky` MPgg&ebxsLQ025IeI{*Lx literal 0 HcmV?d00001 diff --git a/mobile/web/index.html b/mobile/web/index.html new file mode 100644 index 0000000..6dd6e36 --- /dev/null +++ b/mobile/web/index.html @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + mobile + + + + + + + diff --git a/mobile/web/manifest.json b/mobile/web/manifest.json new file mode 100644 index 0000000..9dc3ff2 --- /dev/null +++ b/mobile/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "mobile", + "short_name": "mobile", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/mobile/windows/.gitignore b/mobile/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/mobile/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/mobile/windows/CMakeLists.txt b/mobile/windows/CMakeLists.txt new file mode 100644 index 0000000..6d6c5b1 --- /dev/null +++ b/mobile/windows/CMakeLists.txt @@ -0,0 +1,95 @@ +cmake_minimum_required(VERSION 3.14) +project(mobile LANGUAGES CXX) + +set(BINARY_NAME "mobile") + +cmake_policy(SET CMP0063 NEW) + +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Configure build options. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() + +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") + +# Flutter library and tool build rules. +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build +add_subdirectory("runner") + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/mobile/windows/flutter/CMakeLists.txt b/mobile/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..b2e4bd8 --- /dev/null +++ b/mobile/windows/flutter/CMakeLists.txt @@ -0,0 +1,103 @@ +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + windows-x64 $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/mobile/windows/flutter/generated_plugin_registrant.cc b/mobile/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/mobile/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/mobile/windows/flutter/generated_plugin_registrant.h b/mobile/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/mobile/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/mobile/windows/flutter/generated_plugins.cmake b/mobile/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..4d10c25 --- /dev/null +++ b/mobile/windows/flutter/generated_plugins.cmake @@ -0,0 +1,15 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) diff --git a/mobile/windows/runner/CMakeLists.txt b/mobile/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..de2d891 --- /dev/null +++ b/mobile/windows/runner/CMakeLists.txt @@ -0,0 +1,17 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) +apply_standard_settings(${BINARY_NAME}) +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/mobile/windows/runner/Runner.rc b/mobile/windows/runner/Runner.rc new file mode 100644 index 0000000..c587bd0 --- /dev/null +++ b/mobile/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#ifdef FLUTTER_BUILD_NUMBER +#define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER +#else +#define VERSION_AS_NUMBER 1,0,0 +#endif + +#ifdef FLUTTER_BUILD_NAME +#define VERSION_AS_STRING #FLUTTER_BUILD_NAME +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "mobile" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "mobile" "\0" + VALUE "LegalCopyright", "Copyright (C) 2022 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "mobile.exe" "\0" + VALUE "ProductName", "mobile" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/mobile/windows/runner/flutter_window.cpp b/mobile/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..b43b909 --- /dev/null +++ b/mobile/windows/runner/flutter_window.cpp @@ -0,0 +1,61 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/mobile/windows/runner/flutter_window.h b/mobile/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/mobile/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/mobile/windows/runner/main.cpp b/mobile/windows/runner/main.cpp new file mode 100644 index 0000000..f8e235f --- /dev/null +++ b/mobile/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.CreateAndShow(L"mobile", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/mobile/windows/runner/resource.h b/mobile/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/mobile/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/mobile/windows/runner/resources/app_icon.ico b/mobile/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..c04e20caf6370ebb9253ad831cc31de4a9c965f6 GIT binary patch literal 33772 zcmeHQc|26z|35SKE&G-*mXah&B~fFkXr)DEO&hIfqby^T&>|8^_Ub8Vp#`BLl3lbZ zvPO!8k!2X>cg~Elr=IVxo~J*a`+9wR=A83c-k-DFd(XM&UI1VKCqM@V;DDtJ09WB} zRaHKiW(GT00brH|0EeTeKVbpbGZg?nK6-j827q-+NFM34gXjqWxJ*a#{b_apGN<-L_m3#8Z26atkEn& ze87Bvv^6vVmM+p+cQ~{u%=NJF>#(d;8{7Q{^rWKWNtf14H}>#&y7$lqmY6xmZryI& z($uy?c5-+cPnt2%)R&(KIWEXww>Cnz{OUpT>W$CbO$h1= z#4BPMkFG1Y)x}Ui+WXr?Z!w!t_hjRq8qTaWpu}FH{MsHlU{>;08goVLm{V<&`itk~ zE_Ys=D(hjiy+5=?=$HGii=Y5)jMe9|wWoD_K07(}edAxh`~LBorOJ!Cf@f{_gNCC| z%{*04ViE!#>@hc1t5bb+NO>ncf@@Dv01K!NxH$3Eg1%)|wLyMDF8^d44lV!_Sr}iEWefOaL z8f?ud3Q%Sen39u|%00W<#!E=-RpGa+H8}{ulxVl4mwpjaU+%2pzmi{3HM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2^9!Qk`!A$wUE z7$Ar5?NRg2&G!AZqnmE64eh^Anss3i!{}%6@Et+4rr!=}!SBF8eZ2*J3ujCWbl;3; z48H~goPSv(8X61fKKdpP!Z7$88NL^Z?j`!^*I?-P4X^pMxyWz~@$(UeAcTSDd(`vO z{~rc;9|GfMJcApU3k}22a!&)k4{CU!e_ny^Y3cO;tOvOMKEyWz!vG(Kp*;hB?d|R3`2X~=5a6#^o5@qn?J-bI8Ppip{-yG z!k|VcGsq!jF~}7DMr49Wap-s&>o=U^T0!Lcy}!(bhtYsPQy z4|EJe{12QL#=c(suQ89Mhw9<`bui%nx7Nep`C&*M3~vMEACmcRYYRGtANq$F%zh&V zc)cEVeHz*Z1N)L7k-(k3np#{GcDh2Q@ya0YHl*n7fl*ZPAsbU-a94MYYtA#&!c`xGIaV;yzsmrjfieTEtqB_WgZp2*NplHx=$O{M~2#i_vJ{ps-NgK zQsxKK_CBM2PP_je+Xft`(vYfXXgIUr{=PA=7a8`2EHk)Ym2QKIforz# tySWtj{oF3N9@_;i*Fv5S)9x^z=nlWP>jpp-9)52ZmLVA=i*%6g{{fxOO~wEK literal 0 HcmV?d00001 diff --git a/mobile/windows/runner/runner.exe.manifest b/mobile/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..c977c4a --- /dev/null +++ b/mobile/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/mobile/windows/runner/utils.cpp b/mobile/windows/runner/utils.cpp new file mode 100644 index 0000000..d19bdbb --- /dev/null +++ b/mobile/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr); + if (target_length == 0) { + return std::string(); + } + std::string utf8_string; + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/mobile/windows/runner/utils.h b/mobile/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/mobile/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/mobile/windows/runner/win32_window.cpp b/mobile/windows/runner/win32_window.cpp new file mode 100644 index 0000000..c10f08d --- /dev/null +++ b/mobile/windows/runner/win32_window.cpp @@ -0,0 +1,245 @@ +#include "win32_window.h" + +#include + +#include "resource.h" + +namespace { + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + FreeLibrary(user32_module); + } +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + return OnCreate(); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} diff --git a/mobile/windows/runner/win32_window.h b/mobile/windows/runner/win32_window.h new file mode 100644 index 0000000..17ba431 --- /dev/null +++ b/mobile/windows/runner/win32_window.h @@ -0,0 +1,98 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates and shows a win32 window with |title| and position and size using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size to will treat the width height passed in to this function + // as logical pixels and scale to appropriate for the default monitor. Returns + // true if the window was created successfully. + bool CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responsponds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ -- 2.17.1 From 00e3cc3620adf80cb7628e7d841d3734bc035496 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Sat, 28 May 2022 16:12:47 +0930 Subject: [PATCH 02/24] Working on initial encryption key generation & authentication --- Backend/Api/Auth/Login.go | 107 ++++++++ Backend/Api/Auth/Session.go | 79 ++++++ Backend/Api/Auth/Signup.go | 54 ++-- Backend/Api/Routes.go | 2 +- Backend/Models/Users.go | 4 +- .../android/app/src/main/AndroidManifest.xml | 3 +- .../unauthenticated_landing.dart | 75 ----- mobile/lib/main.dart | 4 +- mobile/lib/utils/encryption/aes_helper.dart | 138 ++++++++++ .../lib/utils/encryption/rsa_key_helper.dart | 257 ++++++++++++++++++ mobile/lib/utils/storage/encryption_keys.dart | 22 ++ mobile/lib/views/authentication/login.dart | 217 +++++++++++++++ .../{ => views}/authentication/signup.dart | 79 +++++- .../unauthenticated_landing.dart | 85 ++++++ mobile/lib/views/main/conversations_list.dart | 112 ++++++++ mobile/pubspec.lock | 155 ++++++++++- mobile/pubspec.yaml | 5 +- 17 files changed, 1294 insertions(+), 104 deletions(-) create mode 100644 Backend/Api/Auth/Login.go create mode 100644 Backend/Api/Auth/Session.go delete mode 100644 mobile/lib/authentication/unauthenticated_landing.dart create mode 100644 mobile/lib/utils/encryption/aes_helper.dart create mode 100644 mobile/lib/utils/encryption/rsa_key_helper.dart create mode 100644 mobile/lib/utils/storage/encryption_keys.dart create mode 100644 mobile/lib/views/authentication/login.dart rename mobile/lib/{ => views}/authentication/signup.dart (76%) create mode 100644 mobile/lib/views/authentication/unauthenticated_landing.dart create mode 100644 mobile/lib/views/main/conversations_list.dart diff --git a/Backend/Api/Auth/Login.go b/Backend/Api/Auth/Login.go new file mode 100644 index 0000000..4d3e3f2 --- /dev/null +++ b/Backend/Api/Auth/Login.go @@ -0,0 +1,107 @@ +package Auth + +import ( + "encoding/json" + "net/http" + "time" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "github.com/gofrs/uuid" +) + +type Credentials struct { + Username string `json:"username"` + Password string `json:"password"` +} + +type loginResponse struct { + Status string `json:"status"` + Message string `json:"message"` + AsymmetricPublicKey string `json:"asymmetric_public_key"` + AsymmetricPrivateKey string `json:"asymmetric_private_key"` +} + +func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey string) { + var ( + status string = "error" + returnJson []byte + err error + ) + if code > 200 && code < 300 { + status = "success" + } + + returnJson, err = json.MarshalIndent(loginResponse{ + Status: status, + Message: message, + AsymmetricPublicKey: pubKey, + AsymmetricPrivateKey: privKey, + }, "", " ") + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + // Return updated json + w.WriteHeader(code) + w.Write(returnJson) + +} + +func Login(w http.ResponseWriter, r *http.Request) { + var ( + creds Credentials + userData Models.User + sessionToken uuid.UUID + expiresAt time.Time + err error + ) + + err = json.NewDecoder(r.Body).Decode(&creds) + if err != nil { + makeLoginResponse(w, http.StatusInternalServerError, "An error occurred", "", "") + return + } + + userData, err = Database.GetUserByUsername(creds.Username) + if err != nil { + makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "") + return + } + + if !CheckPasswordHash(creds.Password, userData.Password) { + makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "") + return + } + + sessionToken, err = uuid.NewV4() + if err != nil { + makeLoginResponse(w, http.StatusInternalServerError, "An error occurred", "", "") + return + } + + expiresAt = time.Now().Add(1 * time.Hour) + + Sessions[sessionToken.String()] = Session{ + UserID: userData.ID.String(), + Username: userData.Username, + Expiry: expiresAt, + } + + http.SetCookie(w, &http.Cookie{ + Name: "session_token", + Value: sessionToken.String(), + Expires: expiresAt, + }) + + makeLoginResponse( + w, + http.StatusOK, + "Successfully logged in", + userData.AsymmetricPublicKey, + userData.AsymmetricPrivateKey, + ) +} diff --git a/Backend/Api/Auth/Session.go b/Backend/Api/Auth/Session.go new file mode 100644 index 0000000..f97bbaf --- /dev/null +++ b/Backend/Api/Auth/Session.go @@ -0,0 +1,79 @@ +package Auth + +import ( + "errors" + "net/http" + "time" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +var ( + Sessions = map[string]Session{} +) + +type Session struct { + UserID string + Username string + Expiry time.Time +} + +func (s Session) IsExpired() bool { + return s.Expiry.Before(time.Now()) +} + +func CheckCookie(r *http.Request) (Session, error) { + var ( + c *http.Cookie + sessionToken string + userSession Session + exists bool + err error + ) + + c, err = r.Cookie("session_token") + if err != nil { + return userSession, err + } + sessionToken = c.Value + + // We then get the session from our session map + userSession, exists = Sessions[sessionToken] + if !exists { + return userSession, errors.New("Cookie not found") + } + + // If the session is present, but has expired, we can delete the session, and return + // an unauthorized status + if userSession.IsExpired() { + delete(Sessions, sessionToken) + return userSession, errors.New("Cookie expired") + } + + return userSession, nil +} + +func CheckCookieCurrentUser(w http.ResponseWriter, r *http.Request) (Models.User, error) { + var ( + userSession Session + userData Models.User + err error + ) + + userSession, err = CheckCookie(r) + if err != nil { + return userData, err + } + + userData, err = Database.GetUserById(userSession.UserID) + if err != nil { + return userData, err + } + + if userData.ID.String() != userSession.UserID { + return userData, errors.New("Is not current user") + } + + return userData, nil +} diff --git a/Backend/Api/Auth/Signup.go b/Backend/Api/Auth/Signup.go index 4c6ac5b..232611f 100644 --- a/Backend/Api/Auth/Signup.go +++ b/Backend/Api/Auth/Signup.go @@ -11,18 +11,48 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" ) +type signupResponse struct { + Status string `json:"status"` + Message string `json:"message"` +} + +func makeSignupResponse(w http.ResponseWriter, code int, message string) { + var ( + status string = "error" + returnJson []byte + err error + ) + if code > 200 && code < 300 { + status = "success" + } + + returnJson, err = json.MarshalIndent(signupResponse{ + Status: status, + Message: message, + }, "", " ") + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + // Return updated json + w.WriteHeader(code) + w.Write(returnJson) + +} + func Signup(w http.ResponseWriter, r *http.Request) { var ( userData Models.User requestBody []byte - returnJson []byte err error ) requestBody, err = ioutil.ReadAll(r.Body) if err != nil { log.Printf("Error encountered reading POST body: %s\n", err.Error()) - http.Error(w, "Error", http.StatusInternalServerError) + makeSignupResponse(w, http.StatusInternalServerError, "An error occurred") return } @@ -31,7 +61,7 @@ func Signup(w http.ResponseWriter, r *http.Request) { }, false) if err != nil { log.Printf("Invalid data provided to Signup: %s\n", err.Error()) - http.Error(w, "Invalid Data", http.StatusUnprocessableEntity) + makeSignupResponse(w, http.StatusUnprocessableEntity, "Invalid data provided") return } @@ -40,35 +70,27 @@ func Signup(w http.ResponseWriter, r *http.Request) { userData.ConfirmPassword == "" || len(userData.AsymmetricPrivateKey) == 0 || len(userData.AsymmetricPublicKey) == 0 { - http.Error(w, "Invalid Data", http.StatusUnprocessableEntity) + makeSignupResponse(w, http.StatusUnprocessableEntity, "Invalid data provided") return } err = Database.CheckUniqueUsername(userData.Username) if err != nil { - http.Error(w, "Invalid Data", http.StatusUnprocessableEntity) + makeSignupResponse(w, http.StatusUnprocessableEntity, "Invalid data provided") return } userData.Password, err = HashPassword(userData.Password) if err != nil { - http.Error(w, "Error", http.StatusInternalServerError) + makeSignupResponse(w, http.StatusInternalServerError, "An error occurred") return } err = Database.CreateUser(&userData) if err != nil { - http.Error(w, "Error", http.StatusInternalServerError) + makeSignupResponse(w, http.StatusInternalServerError, "An error occurred") return } - returnJson, err = json.MarshalIndent(userData, "", " ") - if err != nil { - http.Error(w, "Error", http.StatusInternalServerError) - return - } - - // Return updated json - w.WriteHeader(http.StatusOK) - w.Write(returnJson) + makeSignupResponse(w, http.StatusCreated, "Successfully signed up") } diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index bb597bd..ad4d271 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -66,7 +66,7 @@ func InitApiEndpoints(router *mux.Router) { // Define routes for authentication api.HandleFunc("/signup", Auth.Signup).Methods("POST") - // api.HandleFunc("/login", Auth.Login).Methods("POST") + api.HandleFunc("/login", Auth.Login).Methods("POST") // api.HandleFunc("/logout", Auth.Logout).Methods("GET") adminApi = api.PathPrefix("/message/").Subrouter() diff --git a/Backend/Models/Users.go b/Backend/Models/Users.go index b267a27..1c688c3 100644 --- a/Backend/Models/Users.go +++ b/Backend/Models/Users.go @@ -18,6 +18,6 @@ type User struct { Username string `gorm:"not null;unique" json:"username"` Password string `gorm:"not null" json:"password"` ConfirmPassword string `gorm:"-" json:"confirm_password"` - AsymmetricPrivateKey []byte `gorm:"not null" json:"asymmetric_private_key"` // Stored encrypted - AsymmetricPublicKey []byte `gorm:"not null" json:"asymmetric_public_key"` + AsymmetricPrivateKey string `gorm:"not null" json:"asymmetric_private_key"` // Stored encrypted + AsymmetricPublicKey string `gorm:"not null" json:"asymmetric_public_key"` } diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml index c655c32..c3bfaaa 100644 --- a/mobile/android/app/src/main/AndroidManifest.xml +++ b/mobile/android/app/src/main/AndroidManifest.xml @@ -1,7 +1,8 @@ + createState() => _UnauthenticatedLandingWidgetState(); -} - - -class _UnauthenticatedLandingWidgetState extends State { - @override - Widget build(BuildContext context) { - final ButtonStyle buttonStyle = ElevatedButton.styleFrom( - primary: Colors.white, - onPrimary: Colors.cyan, - minimumSize: const Size.fromHeight(50), - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), - textStyle: const TextStyle( - fontSize: 20, - fontWeight: FontWeight.bold, - color: Colors.red, - ), - ); - - return Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Center( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: const [ - FaIcon(FontAwesomeIcons.envelope, color: Colors.white, size: 40), - SizedBox(width: 15), - Text('Envelope', style: TextStyle(fontSize: 40, color: Colors.white),) - ] - ), - ), - const SizedBox(height: 10), - Padding( - padding: const EdgeInsets.all(15), - child: Column ( - children: [ - ElevatedButton( - child: const Text('Login'), - onPressed: loginButton, - style: buttonStyle, - ), - const SizedBox(height: 20), - ElevatedButton( - child: const Text('Sign Up'), - onPressed: () => { - Navigator.push( - context, - MaterialPageRoute(builder: (context) => const Signup()), - ), - }, - style: buttonStyle, - ), - ] - ), - ), - ], - ), - ); - } -} - -void loginButton() { -} diff --git a/mobile/lib/main.dart b/mobile/lib/main.dart index cff251d..3eceed5 100644 --- a/mobile/lib/main.dart +++ b/mobile/lib/main.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import './authentication/unauthenticated_landing.dart'; +import '/views/main/conversations_list.dart'; void main() { runApp(const Home()); @@ -17,7 +17,7 @@ class Home extends StatelessWidget { home: Scaffold( backgroundColor: Colors.cyan, body: SafeArea( - child: UnauthenticatedLandingWidget(), + child: ConversationsList(), ) ) ); diff --git a/mobile/lib/utils/encryption/aes_helper.dart b/mobile/lib/utils/encryption/aes_helper.dart new file mode 100644 index 0000000..04f2ece --- /dev/null +++ b/mobile/lib/utils/encryption/aes_helper.dart @@ -0,0 +1,138 @@ +import 'dart:convert'; +import 'dart:typed_data'; +import "package:pointycastle/export.dart"; + +Uint8List createUint8ListFromString(String s) { + var ret = Uint8List(s.length); + for (var i = 0; i < s.length; i++) { + ret[i] = s.codeUnitAt(i); + } + return ret; +} + +// AES key size +const keySize = 32; // 32 byte key for AES-256 +const iterationCount = 1000; + +class AesHelper { + static const cbcMode = 'CBC'; + static const cfbMode = 'CFB'; + + static Uint8List deriveKey(dynamic password, + {String salt = '', + int iterationCount = iterationCount, + int derivedKeyLength = keySize}) { + + if (password == null || password.isEmpty) { + throw ArgumentError('password must not be empty'); + } + + if (password is String) { + password = createUint8ListFromString(password); + } + + Uint8List saltBytes = createUint8ListFromString(salt); + Pbkdf2Parameters params = Pbkdf2Parameters(saltBytes, iterationCount, derivedKeyLength); + KeyDerivator keyDerivator = PBKDF2KeyDerivator(HMac(SHA256Digest(), 64)); + keyDerivator.init(params); + + return keyDerivator.process(password); + } + + static Uint8List pad(Uint8List src, int blockSize) { + var pad = PKCS7Padding(); + pad.init(null); + + int padLength = blockSize - (src.length % blockSize); + var out = Uint8List(src.length + padLength)..setAll(0, src); + pad.addPadding(out, src.length); + + return out; + } + + static Uint8List unpad(Uint8List src) { + var pad = PKCS7Padding(); + pad.init(null); + + int padLength = pad.padCount(src); + int len = src.length - padLength; + + return Uint8List(len)..setRange(0, len, src); + } + + static String aesEncrypt(String password, Uint8List plaintext, + {String mode = cbcMode}) { + Uint8List derivedKey = deriveKey(password); + KeyParameter keyParam = KeyParameter(derivedKey); + BlockCipher aes = AESEngine(); + + var rnd = FortunaRandom(); + rnd.seed(keyParam); + Uint8List iv = rnd.nextBytes(aes.blockSize); + + BlockCipher cipher; + ParametersWithIV params = ParametersWithIV(keyParam, iv); + switch (mode) { + case cbcMode: + cipher = CBCBlockCipher(aes); + break; + case cfbMode: + cipher = CFBBlockCipher(aes, aes.blockSize); + break; + default: + throw ArgumentError('incorrect value of the "mode" parameter'); + } + cipher.init(true, params); + + Uint8List paddedText = pad(plaintext, aes.blockSize); + Uint8List cipherBytes = _processBlocks(cipher, paddedText); + Uint8List cipherIvBytes = Uint8List(cipherBytes.length + iv.length) + ..setAll(0, iv) + ..setAll(iv.length, cipherBytes); + + return base64.encode(cipherIvBytes); + } + + static String aesDecrypt(String password, Uint8List ciphertext, + {String mode = cbcMode}) { + Uint8List derivedKey = deriveKey(password); + KeyParameter keyParam = KeyParameter(derivedKey); + BlockCipher aes = AESEngine(); + + Uint8List iv = Uint8List(aes.blockSize) + ..setRange(0, aes.blockSize, ciphertext); + + BlockCipher cipher; + ParametersWithIV params = ParametersWithIV(keyParam, iv); + switch (mode) { + case cbcMode: + cipher = CBCBlockCipher(aes); + break; + case cfbMode: + cipher = CFBBlockCipher(aes, aes.blockSize); + break; + default: + throw ArgumentError('incorrect value of the "mode" parameter'); + } + cipher.init(false, params); + + int cipherLen = ciphertext.length - aes.blockSize; + Uint8List cipherBytes = Uint8List(cipherLen) + ..setRange(0, cipherLen, ciphertext, aes.blockSize); + Uint8List paddedText = _processBlocks(cipher, cipherBytes); + Uint8List textBytes = unpad(paddedText); + + return String.fromCharCodes(textBytes); + } + + static Uint8List _processBlocks(BlockCipher cipher, Uint8List inp) { + var out = Uint8List(inp.lengthInBytes); + + for (var offset = 0; offset < inp.lengthInBytes;) { + var len = cipher.processBlock(inp, offset, out, offset); + offset += len; + } + + return out; + } +} diff --git a/mobile/lib/utils/encryption/rsa_key_helper.dart b/mobile/lib/utils/encryption/rsa_key_helper.dart new file mode 100644 index 0000000..2d3510e --- /dev/null +++ b/mobile/lib/utils/encryption/rsa_key_helper.dart @@ -0,0 +1,257 @@ +import 'dart:convert'; +import 'dart:math'; +import 'dart:typed_data'; +import 'package:pointycastle/src/platform_check/platform_check.dart'; +import "package:pointycastle/export.dart"; +import "package:asn1lib/asn1lib.dart"; + +/* +var rsaKeyHelper = RsaKeyHelper(); +var keyPair = rsaKeyHelper.generateRSAkeyPair(); +var rsaPub = keyPair.publicKey; +var rsaPriv = keyPair.privateKey; +var cipherText = rsaKeyHelper.rsaEncrypt(rsaPub, Uint8List.fromList('Test Data'.codeUnits)); +print(cipherText); +var plainText = rsaKeyHelper.rsaDecrypt(rsaPriv, cipherText); +print(String.fromCharCodes(plainText)); + */ + + +List decodePEM(String pem) { + var startsWith = [ + "-----BEGIN PUBLIC KEY-----", + "-----BEGIN PRIVATE KEY-----", + "-----BEGIN PGP PUBLIC KEY BLOCK-----\r\nVersion: React-Native-OpenPGP.js 0.1\r\nComment: http://openpgpjs.org\r\n\r\n", + "-----BEGIN PGP PRIVATE KEY BLOCK-----\r\nVersion: React-Native-OpenPGP.js 0.1\r\nComment: http://openpgpjs.org\r\n\r\n", + ]; + var endsWith = [ + "-----END PUBLIC KEY-----", + "-----END PRIVATE KEY-----", + "-----END PGP PUBLIC KEY BLOCK-----", + "-----END PGP PRIVATE KEY BLOCK-----", + ]; + bool isOpenPgp = pem.contains('BEGIN PGP'); + + for (var s in startsWith) { + if (pem.startsWith(s)) { + pem = pem.substring(s.length); + } + } + + for (var s in endsWith) { + if (pem.endsWith(s)) { + pem = pem.substring(0, pem.length - s.length); + } + } + + if (isOpenPgp) { + var index = pem.indexOf('\r\n'); + pem = pem.substring(0, index); + } + + pem = pem.replaceAll('\n', ''); + pem = pem.replaceAll('\r', ''); + + return base64.decode(pem); +} + + +class RsaKeyHelper { + + // Generate secure random sequence for seed + SecureRandom secureRandom() { + var secureRandom = FortunaRandom(); + var random = Random.secure(); + List seeds = []; + for (int i = 0; i < 32; i++) { + seeds.add(random.nextInt(255)); + } + secureRandom.seed(KeyParameter(Uint8List.fromList(seeds))); + + return secureRandom; + } + + // Generate RSA key pair + AsymmetricKeyPair generateRSAkeyPair({int bitLength = 2048}) { + var secureRandom = this.secureRandom(); + + // final keyGen = KeyGenerator('RSA'); // Get using registry + final keyGen = RSAKeyGenerator(); + + keyGen.init(ParametersWithRandom( + RSAKeyGeneratorParameters(BigInt.parse('65537'), bitLength, 64), + secureRandom)); + + // Use the generator + + final pair = keyGen.generateKeyPair(); + + // Cast the generated key pair into the RSA key types + + final myPublic = pair.publicKey as RSAPublicKey; + final myPrivate = pair.privateKey as RSAPrivateKey; + + return AsymmetricKeyPair(myPublic, myPrivate); + } + + + // Encrypt data using RSA key + Uint8List rsaEncrypt(RSAPublicKey myPublic, Uint8List dataToEncrypt) { + final encryptor = OAEPEncoding(RSAEngine()) + ..init(true, PublicKeyParameter(myPublic)); // true=encrypt + + return _processInBlocks(encryptor, dataToEncrypt); + } + + + // Decrypt data using RSA key + Uint8List rsaDecrypt(RSAPrivateKey myPrivate, Uint8List cipherText) { + final decryptor = OAEPEncoding(RSAEngine()) + ..init(false, PrivateKeyParameter(myPrivate)); // false=decrypt + + return _processInBlocks(decryptor, cipherText); + } + + + // Process blocks after encryption/descryption + Uint8List _processInBlocks(AsymmetricBlockCipher engine, Uint8List input) { + final numBlocks = input.length ~/ engine.inputBlockSize + + ((input.length % engine.inputBlockSize != 0) ? 1 : 0); + + final output = Uint8List(numBlocks * engine.outputBlockSize); + + var inputOffset = 0; + var outputOffset = 0; + while (inputOffset < input.length) { + final chunkSize = (inputOffset + engine.inputBlockSize <= input.length) + ? engine.inputBlockSize + : input.length - inputOffset; + + outputOffset += engine.processBlock( + input, inputOffset, chunkSize, output, outputOffset); + + inputOffset += chunkSize; + } + + return (output.length == outputOffset) + ? output + : output.sublist(0, outputOffset); + } + + + // Encode RSA public key to pem format + static encodePublicKeyToPem(RSAPublicKey publicKey) { + var algorithmSeq = ASN1Sequence(); + var algorithmAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList([0x6, 0x9, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0xd, 0x1, 0x1, 0x1])); + var paramsAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList([0x5, 0x0])); + algorithmSeq.add(algorithmAsn1Obj); + algorithmSeq.add(paramsAsn1Obj); + + var publicKeySeq = ASN1Sequence(); + publicKeySeq.add(ASN1Integer(publicKey.modulus!)); + publicKeySeq.add(ASN1Integer(publicKey.exponent!)); + var publicKeySeqBitString = ASN1BitString(Uint8List.fromList(publicKeySeq.encodedBytes)); + + var topLevelSeq = ASN1Sequence(); + topLevelSeq.add(algorithmSeq); + topLevelSeq.add(publicKeySeqBitString); + var dataBase64 = base64.encode(topLevelSeq.encodedBytes); + + return """-----BEGIN PUBLIC KEY-----\r\n$dataBase64\r\n-----END PUBLIC KEY-----"""; + } + + // Parse public key PEM file + static parsePublicKeyFromPem(pemString) { + List publicKeyDER = decodePEM(pemString); + var asn1Parser = ASN1Parser(Uint8List.fromList(publicKeyDER)); + var topLevelSeq = asn1Parser.nextObject() as ASN1Sequence; + var publicKeyBitString = topLevelSeq.elements[1]; + + var publicKeyAsn = ASN1Parser(publicKeyBitString.contentBytes()!, relaxedParsing: true); + var publicKeySeq = publicKeyAsn.nextObject() as ASN1Sequence; + var modulus = publicKeySeq.elements[0] as ASN1Integer; + var exponent = publicKeySeq.elements[1] as ASN1Integer; + + RSAPublicKey rsaPublicKey = RSAPublicKey( + modulus.valueAsBigInteger!, + exponent.valueAsBigInteger! + ); + + return rsaPublicKey; + } + + + // Encode RSA private key to pem format + static encodePrivateKeyToPem(RSAPrivateKey privateKey) { + var version = ASN1Integer(BigInt.from(0)); + + var algorithmSeq = ASN1Sequence(); + var algorithmAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList([0x6, 0x9, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0xd, 0x1, 0x1, 0x1])); + var paramsAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList([0x5, 0x0])); + algorithmSeq.add(algorithmAsn1Obj); + algorithmSeq.add(paramsAsn1Obj); + + var privateKeySeq = ASN1Sequence(); + var modulus = ASN1Integer(privateKey.n!); + var publicExponent = ASN1Integer(BigInt.parse('65537')); + var privateExponent = ASN1Integer(privateKey.privateExponent!); + var p = ASN1Integer(privateKey.p!); + var q = ASN1Integer(privateKey.q!); + var dP = privateKey.privateExponent! % (privateKey.p! - BigInt.from(1)); + var exp1 = ASN1Integer(dP); + var dQ = privateKey.privateExponent! % (privateKey.q! - BigInt.from(1)); + var exp2 = ASN1Integer(dQ); + var iQ = privateKey.q?.modInverse(privateKey.p!); + var co = ASN1Integer(iQ!); + + privateKeySeq.add(version); + privateKeySeq.add(modulus); + privateKeySeq.add(publicExponent); + privateKeySeq.add(privateExponent); + privateKeySeq.add(p); + privateKeySeq.add(q); + privateKeySeq.add(exp1); + privateKeySeq.add(exp2); + privateKeySeq.add(co); + var publicKeySeqOctetString = ASN1OctetString(Uint8List.fromList(privateKeySeq.encodedBytes)); + + var topLevelSeq = ASN1Sequence(); + topLevelSeq.add(version); + topLevelSeq.add(algorithmSeq); + topLevelSeq.add(publicKeySeqOctetString); + var dataBase64 = base64.encode(topLevelSeq.encodedBytes); + + return """-----BEGIN PRIVATE KEY-----\r\n$dataBase64\r\n-----END PRIVATE KEY-----"""; + } + + static parsePrivateKeyFromPem(pemString) { + List privateKeyDER = decodePEM(pemString); + var asn1Parser = ASN1Parser(Uint8List.fromList(privateKeyDER)); + var topLevelSeq = asn1Parser.nextObject() as ASN1Sequence; + var version = topLevelSeq.elements[0]; + var algorithm = topLevelSeq.elements[1]; + var privateKey = topLevelSeq.elements[2]; + + asn1Parser = ASN1Parser(privateKey.contentBytes()!); + var pkSeq = asn1Parser.nextObject() as ASN1Sequence; + + version = pkSeq.elements[0]; + var modulus = pkSeq.elements[1] as ASN1Integer; + //var publicExponent = pkSeq.elements[2] as ASN1Integer; + var privateExponent = pkSeq.elements[3] as ASN1Integer; + var p = pkSeq.elements[4] as ASN1Integer; + var q = pkSeq.elements[5] as ASN1Integer; + var exp1 = pkSeq.elements[6] as ASN1Integer; + var exp2 = pkSeq.elements[7] as ASN1Integer; + var co = pkSeq.elements[8] as ASN1Integer; + + RSAPrivateKey rsaPrivateKey = RSAPrivateKey( + modulus.valueAsBigInteger!, + privateExponent.valueAsBigInteger!, + p.valueAsBigInteger, + q.valueAsBigInteger + ); + + return rsaPrivateKey; + } +} diff --git a/mobile/lib/utils/storage/encryption_keys.dart b/mobile/lib/utils/storage/encryption_keys.dart new file mode 100644 index 0000000..d27bfc7 --- /dev/null +++ b/mobile/lib/utils/storage/encryption_keys.dart @@ -0,0 +1,22 @@ +import 'package:shared_preferences/shared_preferences.dart'; +import "package:pointycastle/export.dart"; +import '/utils/encryption/rsa_key_helper.dart'; + +const rsaPrivateKeyName = 'rsaPrivateKey'; + +void setPrivateKey(RSAPrivateKey key) async { + String keyPem = RsaKeyHelper.encodePrivateKeyToPem(key); + + final prefs = await SharedPreferences.getInstance(); + prefs.setString(rsaPrivateKeyName, keyPem); +} + +Future getPrivateKey() async { + final prefs = await SharedPreferences.getInstance(); + String? keyPem = prefs.getString(rsaPrivateKeyName); + if (keyPem == null) { + throw Exception('No RSA private key set'); + } + + return RsaKeyHelper.parsePrivateKeyFromPem(keyPem); +} diff --git a/mobile/lib/views/authentication/login.dart b/mobile/lib/views/authentication/login.dart new file mode 100644 index 0000000..0a087f8 --- /dev/null +++ b/mobile/lib/views/authentication/login.dart @@ -0,0 +1,217 @@ +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +import '/views/main/conversations_list.dart'; + +import '/utils/encryption/rsa_key_helper.dart'; +import '/utils/encryption/aes_helper.dart'; +import '/utils/storage/encryption_keys.dart'; + +class LoginResponse { + final String status; + final String message; + final String asymmetricPublicKey; + final String asymmetricPrivateKey; + + const LoginResponse({ + required this.status, + required this.message, + required this.asymmetricPublicKey, + required this.asymmetricPrivateKey, + }); + + factory LoginResponse.fromJson(Map json) { + return LoginResponse( + status: json['status'], + message: json['message'], + asymmetricPublicKey: json['asymmetric_public_key'], + asymmetricPrivateKey: json['asymmetric_private_key'], + ); + } +} + +Future login(context, String username, String password) async { + final resp = await http.post( + Uri.parse('http://192.168.1.5:8080/api/v1/login'), + headers: { + 'Content-Type': 'application/json; charset=UTF-8', + }, + body: jsonEncode({ + 'username': username, + 'password': password, + }), + ); + + LoginResponse response = LoginResponse.fromJson(jsonDecode(resp.body)); + + if (resp.statusCode != 200) { + throw Exception(response.message); + } + + var rsaPrivPem = AesHelper.aesDecrypt(password, base64.decode(response.asymmetricPrivateKey)); + var rsaPriv = RsaKeyHelper.parsePrivateKeyFromPem(rsaPrivPem); + setPrivateKey(rsaPriv); + + final preferences = await SharedPreferences.getInstance(); + preferences.setBool('islogin', true); + + return response; +} + +class Login extends StatelessWidget { + const Login({Key? key}) : super(key: key); + + static const String _title = 'Envelope'; + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: _title, + home: Scaffold( + backgroundColor: Colors.cyan, + appBar: AppBar( + title: null, + automaticallyImplyLeading: true, + //`true` if you want Flutter to automatically add Back Button when needed, + //or `false` if you want to force your own back button every where + leading: IconButton(icon: const Icon(Icons.arrow_back), + //onPressed:() => Navigator.pop(context, false), + onPressed:() => { + Navigator.pop(context) + } + ) + ), + body: const SafeArea( + child: LoginWidget(), + ) + ), + theme: ThemeData( + appBarTheme: const AppBarTheme( + backgroundColor: Colors.cyan, + elevation: 0, + ), + inputDecorationTheme: const InputDecorationTheme( + border: OutlineInputBorder(), + focusedBorder: OutlineInputBorder(), + labelStyle: TextStyle( + color: Colors.white, + fontSize: 30, + ), + filled: true, + fillColor: Colors.white, + ), + + ), + ); + } +} + +class LoginWidget extends StatefulWidget { + const LoginWidget({Key? key}) : super(key: key); + + @override + State createState() => _LoginWidgetState(); +} + +class _LoginWidgetState extends State { + final _formKey = GlobalKey(); + + TextEditingController usernameController = TextEditingController(); + TextEditingController passwordController = TextEditingController(); + + @override + Widget build(BuildContext context) { + const TextStyle _inputTextStyle = TextStyle(fontSize: 18, color: Colors.black); + + final ButtonStyle _buttonStyle = ElevatedButton.styleFrom( + primary: Colors.white, + onPrimary: Colors.cyan, + minimumSize: const Size.fromHeight(50), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + textStyle: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Colors.red, + ), + ); + + return Center( + child: Form( + key: _formKey, + child: Center( + child: Padding( + padding: const EdgeInsets.all(15), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + const Text('Login', style: TextStyle(fontSize: 35, color: Colors.white),), + const SizedBox(height: 30), + TextFormField( + controller: usernameController, + decoration: const InputDecoration( + hintText: 'Username', + ), + style: _inputTextStyle, + // The validator receives the text that the user has entered. + validator: (value) { + if (value == null || value.isEmpty) { + return 'Create a username'; + } + return null; + }, + ), + const SizedBox(height: 5), + TextFormField( + controller: passwordController, + obscureText: true, + enableSuggestions: false, + autocorrect: false, + decoration: const InputDecoration( + hintText: 'Password', + ), + style: _inputTextStyle, + // The validator receives the text that the user has entered. + validator: (value) { + if (value == null || value.isEmpty) { + return 'Enter a password'; + } + return null; + }, + ), + const SizedBox(height: 5), + ElevatedButton( + style: _buttonStyle, + onPressed: () { + if (_formKey.currentState!.validate()) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Processing Data')), + ); + + login( + context, + usernameController.text, + passwordController.text, + ).then((value) { + Navigator.of(context).popUntil((route) { + print(route.isFirst); + return route.isFirst; + }); + }).catchError((error) { + print(error); // TODO: Show error on interface + }); + } + }, + child: const Text('Submit'), + ), + ], + ) + ) + ) + + ) + ); + } +} diff --git a/mobile/lib/authentication/signup.dart b/mobile/lib/views/authentication/signup.dart similarity index 76% rename from mobile/lib/authentication/signup.dart rename to mobile/lib/views/authentication/signup.dart index 2b3641a..99654cf 100644 --- a/mobile/lib/authentication/signup.dart +++ b/mobile/lib/views/authentication/signup.dart @@ -1,5 +1,68 @@ +import 'dart:typed_data'; +import 'dart:convert'; import 'package:flutter/material.dart'; -import 'package:pointycastle/api.dart'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +import '/views/main/conversations_list.dart'; + +import '/utils/encryption/rsa_key_helper.dart'; +import '/utils/encryption/aes_helper.dart'; +import '/utils/storage/encryption_keys.dart'; + +class SignupResponse { + final String status; + final String message; + + const SignupResponse({ + required this.status, + required this.message, + }); + + factory SignupResponse.fromJson(Map json) { + return SignupResponse( + status: json['status'], + message: json['message'], + ); + } +} + +Future signUp(context, String username, String password, String confirmPassword) async { + var rsaKeyHelper = RsaKeyHelper(); + var keyPair = rsaKeyHelper.generateRSAkeyPair(); + + setPrivateKey(keyPair.privateKey); + + var rsaPubPem = RsaKeyHelper.encodePublicKeyToPem(keyPair.publicKey); + var rsaPrivPem = RsaKeyHelper.encodePrivateKeyToPem(keyPair.privateKey); + + var encRsaPriv = AesHelper.aesEncrypt(password, Uint8List.fromList(rsaPrivPem.codeUnits)); + + final resp = await http.post( + Uri.parse('http://192.168.1.5:8080/api/v1/signup'), + headers: { + 'Content-Type': 'application/json; charset=UTF-8', + }, + body: jsonEncode({ + 'username': username, + 'password': password, + 'confirm_password': confirmPassword, + 'asymmetric_public_key': rsaPubPem, + 'asymmetric_private_key': encRsaPriv, + }), + ); + + SignupResponse response = SignupResponse.fromJson(jsonDecode(resp.body)); + + if (resp.statusCode != 201) { + throw Exception(response.message); + } + + final preferences = await SharedPreferences.getInstance(); + preferences.setBool('islogin', true); + + return response; +} class Signup extends StatelessWidget { const Signup({Key? key}) : super(key: key); @@ -153,7 +216,16 @@ class _SignupWidgetState extends State { const SnackBar(content: Text('Processing Data')), ); - signup(context); + signUp( + context, + usernameController.text, + passwordController.text, + passwordConfirmController.text + ).then((value) { + Navigator.of(context).popUntil((route) => route.isFirst); + }).catchError((error) { + print(error); // TODO: Show error on interface + }); } }, child: const Text('Submit'), @@ -167,6 +239,3 @@ class _SignupWidgetState extends State { ); } } - -void signup(context) { -} diff --git a/mobile/lib/views/authentication/unauthenticated_landing.dart b/mobile/lib/views/authentication/unauthenticated_landing.dart new file mode 100644 index 0000000..e17a06f --- /dev/null +++ b/mobile/lib/views/authentication/unauthenticated_landing.dart @@ -0,0 +1,85 @@ +import 'package:flutter/material.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import './login.dart'; +import './signup.dart'; + +class UnauthenticatedLandingWidget extends StatefulWidget { + const UnauthenticatedLandingWidget({Key? key}) : super(key: key); + + @override + State createState() => _UnauthenticatedLandingWidgetState(); +} + + +class _UnauthenticatedLandingWidgetState extends State { + @override + Widget build(BuildContext context) { + final ButtonStyle buttonStyle = ElevatedButton.styleFrom( + primary: Colors.white, + onPrimary: Colors.cyan, + minimumSize: const Size.fromHeight(50), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + textStyle: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Colors.red, + ), + ); + + return WillPopScope( + onWillPop: () async => false, + child: Scaffold( + backgroundColor: Colors.cyan, + body: SafeArea( + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Center( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: const [ + FaIcon(FontAwesomeIcons.envelope, color: Colors.white, size: 40), + SizedBox(width: 15), + Text('Envelope', style: TextStyle(fontSize: 40, color: Colors.white),) + ] + ), + ), + const SizedBox(height: 10), + Padding( + padding: const EdgeInsets.all(15), + child: Column ( + children: [ + ElevatedButton( + child: const Text('Login'), + onPressed: () => { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => const Login()), + ), + }, + + style: buttonStyle, + ), + const SizedBox(height: 20), + ElevatedButton( + child: const Text('Sign Up'), + onPressed: () => { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => const Signup()), + ), + }, + style: buttonStyle, + ), + ] + ), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/mobile/lib/views/main/conversations_list.dart b/mobile/lib/views/main/conversations_list.dart new file mode 100644 index 0000000..29e6f2c --- /dev/null +++ b/mobile/lib/views/main/conversations_list.dart @@ -0,0 +1,112 @@ +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; + +import '/views/authentication/unauthenticated_landing.dart'; + +class ConversationsList extends StatefulWidget { + const ConversationsList({Key? key}) : super(key: key); + + @override + State createState() => _ConversationsListState(); +} + +class _ConversationsListState extends State { + @override + void initState() { + checkLogin(); + + super.initState(); + } + + final _suggestions = []; + final _biggerFont = const TextStyle(fontSize: 18); + + Future checkLogin() async { + SharedPreferences preferences = await SharedPreferences.getInstance(); + print(preferences.getBool('islogin')); + if (preferences.getBool('islogin') != true) { + setState(() { + Navigator.of(context).push(MaterialPageRoute( + builder: (context) => const UnauthenticatedLandingWidget(), + )); + }); + } + } + + Widget list() { + + if (_suggestions.isEmpty) { + return const Center( + child: Text('No Conversations'), + ); + } + + return ListView.builder( + itemCount: _suggestions.length, + padding: const EdgeInsets.all(16.0), + itemBuilder: /*1*/ (context, i) { + //if (i >= _suggestions.length) { + // TODO: Check for more conversations here. Remove the itemCount to use this section + //_suggestions.addAll(generateWordPairs().take(10)); /*4*/ + //} + return Column( + children: [ + ListTile( + title: Text( + _suggestions[i], + style: _biggerFont, + ), + ), + const Divider(), + ] + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return WillPopScope( + onWillPop: () async => false, + child: Scaffold( + appBar: AppBar( + title: Text('Envelope'), + actions: [ + PopupMenuButton( + icon: const FaIcon(FontAwesomeIcons.ellipsisVertical, color: Colors.white, size: 40), + itemBuilder: (context) => [ + const PopupMenuItem( + value: 0, + child: Text("Settings"), + ), + const PopupMenuItem( + value: 1, + child: Text("Logout"), + ), + + ], + onSelected: (item) => selectedMenuItem(context, item), + ), + ], + ), + body: list(), + ), + ); + } + + void selectedMenuItem(BuildContext context, item) async { + switch (item) { + case 0: + print("Settings"); + break; + case 1: + SharedPreferences preferences = await SharedPreferences.getInstance(); + preferences.setBool('islogin', false); + Navigator.of(context).push(MaterialPageRoute( + builder: (context) => const UnauthenticatedLandingWidget(), + )); + break; + } + } +} diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock index 3c4fda5..1a1eab8 100644 --- a/mobile/pubspec.lock +++ b/mobile/pubspec.lock @@ -1,6 +1,13 @@ # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: + asn1lib: + dependency: "direct main" + description: + name: asn1lib + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" async: dependency: transitive description: @@ -64,6 +71,20 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.2.0" + ffi: + dependency: transitive + description: + name: ffi + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.1" + file: + dependency: transitive + description: + name: file + url: "https://pub.dartlang.org" + source: hosted + version: "6.1.2" flutter: dependency: "direct main" description: flutter @@ -81,6 +102,11 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" font_awesome_flutter: dependency: "direct main" description: @@ -88,13 +114,27 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "10.1.0" + http: + dependency: "direct main" + description: + name: http + url: "https://pub.dartlang.org" + source: hosted + version: "0.13.4" + http_parser: + dependency: transitive + description: + name: http_parser + url: "https://pub.dartlang.org" + source: hosted + version: "4.0.1" js: dependency: transitive description: name: js url: "https://pub.dartlang.org" source: hosted - version: "0.6.4" + version: "0.6.3" lints: dependency: transitive description: @@ -130,6 +170,41 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.8.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.6" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.4" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.6" + platform: + dependency: transitive + description: + name: platform + url: "https://pub.dartlang.org" + source: hosted + version: "3.1.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.2" pointycastle: dependency: "direct main" description: @@ -137,6 +212,69 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "3.5.2" + process: + dependency: transitive + description: + name: process + url: "https://pub.dartlang.org" + source: hosted + version: "4.2.4" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.15" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.12" + shared_preferences_ios: + dependency: transitive + description: + name: shared_preferences_ios + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.1" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.1" + shared_preferences_macos: + dependency: transitive + description: + name: shared_preferences_macos + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.4" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.0" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.4" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.1" sky_engine: dependency: transitive description: flutter @@ -198,5 +336,20 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.1.1" + win32: + dependency: transitive + description: + name: win32 + url: "https://pub.dartlang.org" + source: hosted + version: "2.5.2" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.0+1" sdks: dart: ">=2.16.2 <3.0.0" + flutter: ">=2.8.0" diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml index 4834078..1cba398 100644 --- a/mobile/pubspec.yaml +++ b/mobile/pubspec.yaml @@ -1,4 +1,4 @@ -name: mobile +name: Envelope description: A new Flutter project. publish_to: 'none' # Remove this line if you wish to publish to pub.dev @@ -15,6 +15,9 @@ dependencies: cupertino_icons: ^1.0.2 font_awesome_flutter: ^10.1.0 pointycastle: ^3.5.2 + asn1lib: ^1.1.0 + http: ^0.13.4 + shared_preferences: ^2.0.15 dev_dependencies: flutter_test: -- 2.17.1 From 52576132cc865a65c5e5702cd5bcc37116bed4d8 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Sun, 5 Jun 2022 15:17:32 +0930 Subject: [PATCH 03/24] Add initial conversation list/friend list --- Backend/Database/Init.go | 1 + Backend/Models/Friends.go | 9 ++ Backend/Models/Messages.go | 4 +- mobile/lib/main.dart | 43 +++++-- mobile/lib/models/friends.dart | 9 ++ mobile/lib/views/authentication/login.dart | 56 +++------ mobile/lib/views/authentication/signup.dart | 52 +++----- mobile/lib/views/main/conversation_list.dart | 56 +++++++++ mobile/lib/views/main/conversations_list.dart | 112 ------------------ mobile/lib/views/main/friend_list.dart | 105 ++++++++++++++++ mobile/lib/views/main/friend_list_item.dart | 56 +++++++++ mobile/lib/views/main/home.dart | 72 +++++++++++ mobile/pubspec.lock | 18 +-- .../windows/flutter/generated_plugins.cmake | 8 ++ 14 files changed, 397 insertions(+), 204 deletions(-) create mode 100644 Backend/Models/Friends.go create mode 100644 mobile/lib/models/friends.dart create mode 100644 mobile/lib/views/main/conversation_list.dart delete mode 100644 mobile/lib/views/main/conversations_list.dart create mode 100644 mobile/lib/views/main/friend_list.dart create mode 100644 mobile/lib/views/main/friend_list_item.dart create mode 100644 mobile/lib/views/main/home.dart diff --git a/Backend/Database/Init.go b/Backend/Database/Init.go index 5d4d7df..b9de172 100644 --- a/Backend/Database/Init.go +++ b/Backend/Database/Init.go @@ -19,6 +19,7 @@ var ( func GetModels() []interface{} { return []interface{}{ &Models.User{}, + &Models.Friend{}, &Models.MessageData{}, &Models.MessageKey{}, } diff --git a/Backend/Models/Friends.go b/Backend/Models/Friends.go new file mode 100644 index 0000000..c0b9abd --- /dev/null +++ b/Backend/Models/Friends.go @@ -0,0 +1,9 @@ +package Models + +import "github.com/gofrs/uuid" + +type Friend struct { + Base + UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` + FriendId string `gorm:"column:friend_id;not null" json:"friend_id"` // Stored encrypted +} diff --git a/Backend/Models/Messages.go b/Backend/Models/Messages.go index cd2bd6a..ce2fc1b 100644 --- a/Backend/Models/Messages.go +++ b/Backend/Models/Messages.go @@ -4,12 +4,12 @@ import "github.com/gofrs/uuid" type MessageData struct { Base - Data []byte `gorm:"not null" json:"data"` // Stored encrypted + Data string `gorm:"not null" json:"data"` // Stored encrypted } type MessageKey struct { Base UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` MessageDataID uuid.UUID `gorm:"type:uuid;column:message_data_id;not null;" json:"message_data_id"` - SymmetricKey []byte `gorm:"not null" json:"symmetric_key"` // Stored encrypted + SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted } diff --git a/mobile/lib/main.dart b/mobile/lib/main.dart index 3eceed5..8bad991 100644 --- a/mobile/lib/main.dart +++ b/mobile/lib/main.dart @@ -1,25 +1,52 @@ import 'package:flutter/material.dart'; -import '/views/main/conversations_list.dart'; +import '/views/main/home.dart'; +import '/views/authentication/unauthenticated_landing.dart'; +import '/views/authentication/login.dart'; +import '/views/authentication/signup.dart'; void main() { - runApp(const Home()); + runApp(const MyApp()); } -class Home extends StatelessWidget { - const Home({Key? key}) : super(key: key); +class MyApp extends StatelessWidget { + const MyApp({Key? key}) : super(key: key); static const String _title = 'Envelope'; @override Widget build(BuildContext context) { - return const MaterialApp( + return MaterialApp( title: _title, - home: Scaffold( + routes: { + '/home': (context) => const Home(), + '/landing': (context) => const UnauthenticatedLandingWidget(), + '/login': (context) => const Login(), + '/signup': (context) => const Signup(), + }, + home: const Scaffold( backgroundColor: Colors.cyan, body: SafeArea( - child: ConversationsList(), + child: Home(), ) - ) + ), + theme: ThemeData( + appBarTheme: const AppBarTheme( + backgroundColor: Colors.cyan, + elevation: 0, + ), + inputDecorationTheme: const InputDecorationTheme( + border: OutlineInputBorder(), + focusedBorder: OutlineInputBorder(), + labelStyle: TextStyle( + color: Colors.white, + fontSize: 30, + ), + filled: true, + fillColor: Colors.white, + ), + + ), + ); } } diff --git a/mobile/lib/models/friends.dart b/mobile/lib/models/friends.dart new file mode 100644 index 0000000..832d637 --- /dev/null +++ b/mobile/lib/models/friends.dart @@ -0,0 +1,9 @@ + +class Friend{ + String id; + String username; + Friend({ + required this.id, + required this.username, + }); +} diff --git a/mobile/lib/views/authentication/login.dart b/mobile/lib/views/authentication/login.dart index 0a087f8..a2d6595 100644 --- a/mobile/lib/views/authentication/login.dart +++ b/mobile/lib/views/authentication/login.dart @@ -2,9 +2,7 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; - -import '/views/main/conversations_list.dart'; - +import '/views/main/conversation_list.dart'; import '/utils/encryption/rsa_key_helper.dart'; import '/utils/encryption/aes_helper.dart'; import '/utils/storage/encryption_keys.dart'; @@ -67,42 +65,22 @@ class Login extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp( - title: _title, - home: Scaffold( - backgroundColor: Colors.cyan, - appBar: AppBar( - title: null, - automaticallyImplyLeading: true, - //`true` if you want Flutter to automatically add Back Button when needed, - //or `false` if you want to force your own back button every where - leading: IconButton(icon: const Icon(Icons.arrow_back), - //onPressed:() => Navigator.pop(context, false), - onPressed:() => { - Navigator.pop(context) - } - ) - ), - body: const SafeArea( - child: LoginWidget(), + return Scaffold( + backgroundColor: Colors.cyan, + appBar: AppBar( + title: null, + automaticallyImplyLeading: true, + //`true` if you want Flutter to automatically add Back Button when needed, + //or `false` if you want to force your own back button every where + leading: IconButton(icon: const Icon(Icons.arrow_back), + //onPressed:() => Navigator.pop(context, false), + onPressed:() => { + Navigator.pop(context) + } ) ), - theme: ThemeData( - appBarTheme: const AppBarTheme( - backgroundColor: Colors.cyan, - elevation: 0, - ), - inputDecorationTheme: const InputDecorationTheme( - border: OutlineInputBorder(), - focusedBorder: OutlineInputBorder(), - labelStyle: TextStyle( - color: Colors.white, - fontSize: 30, - ), - filled: true, - fillColor: Colors.white, - ), - + body: const SafeArea( + child: LoginWidget(), ), ); } @@ -195,10 +173,14 @@ class _LoginWidgetState extends State { usernameController.text, passwordController.text, ).then((value) { + /* Navigator.of(context).popUntil((route) { print(route.isFirst); return route.isFirst; }); + */ + + Navigator.pushNamedAndRemoveUntil(context, '/home', ModalRoute.withName('/home')); }).catchError((error) { print(error); // TODO: Show error on interface }); diff --git a/mobile/lib/views/authentication/signup.dart b/mobile/lib/views/authentication/signup.dart index 99654cf..43af372 100644 --- a/mobile/lib/views/authentication/signup.dart +++ b/mobile/lib/views/authentication/signup.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; -import '/views/main/conversations_list.dart'; +import '/views/main/conversation_list.dart'; import '/utils/encryption/rsa_key_helper.dart'; import '/utils/encryption/aes_helper.dart'; @@ -71,43 +71,23 @@ class Signup extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp( - title: _title, - home: Scaffold( - backgroundColor: Colors.cyan, - appBar: AppBar( - title: null, - automaticallyImplyLeading: true, - //`true` if you want Flutter to automatically add Back Button when needed, - //or `false` if you want to force your own back button every where - leading: IconButton(icon: const Icon(Icons.arrow_back), - //onPressed:() => Navigator.pop(context, false), - onPressed:() => { - Navigator.pop(context) - } - ) - ), - body: const SafeArea( - child: SignupWidget(), + return Scaffold( + backgroundColor: Colors.cyan, + appBar: AppBar( + title: null, + automaticallyImplyLeading: true, + //`true` if you want Flutter to automatically add Back Button when needed, + //or `false` if you want to force your own back button every where + leading: IconButton(icon: const Icon(Icons.arrow_back), + //onPressed:() => Navigator.pop(context, false), + onPressed:() => { + Navigator.pop(context) + } ) ), - theme: ThemeData( - appBarTheme: const AppBarTheme( - backgroundColor: Colors.cyan, - elevation: 0, - ), - inputDecorationTheme: const InputDecorationTheme( - border: OutlineInputBorder(), - focusedBorder: OutlineInputBorder(), - labelStyle: TextStyle( - color: Colors.white, - fontSize: 30, - ), - filled: true, - fillColor: Colors.white, - ), - - ), + body: const SafeArea( + child: SignupWidget(), + ) ); } } diff --git a/mobile/lib/views/main/conversation_list.dart b/mobile/lib/views/main/conversation_list.dart new file mode 100644 index 0000000..1f414d4 --- /dev/null +++ b/mobile/lib/views/main/conversation_list.dart @@ -0,0 +1,56 @@ +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class ConversationList extends StatefulWidget { + const ConversationList({Key? key}) : super(key: key); + + @override + State createState() => _ConversationListState(); +} + +class _ConversationListState extends State { + final _suggestions = []; + final _biggerFont = const TextStyle(fontSize: 18); + + Widget list() { + + if (_suggestions.isEmpty) { + return const Center( + child: Text('No Conversations'), + ); + } + + return ListView.builder( + itemCount: _suggestions.length, + padding: const EdgeInsets.all(16.0), + itemBuilder: /*1*/ (context, i) { + //if (i >= _suggestions.length) { + // TODO: Check for more conversations here. Remove the itemCount to use this section + //_suggestions.addAll(generateWordPairs().take(10)); /*4*/ + //} + return Column( + children: [ + ListTile( + title: Text( + _suggestions[i], + style: _biggerFont, + ), + ), + const Divider(), + ] + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Envelope'), + ), + body: list(), + ); + + } +} diff --git a/mobile/lib/views/main/conversations_list.dart b/mobile/lib/views/main/conversations_list.dart deleted file mode 100644 index 29e6f2c..0000000 --- a/mobile/lib/views/main/conversations_list.dart +++ /dev/null @@ -1,112 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import 'package:font_awesome_flutter/font_awesome_flutter.dart'; - -import '/views/authentication/unauthenticated_landing.dart'; - -class ConversationsList extends StatefulWidget { - const ConversationsList({Key? key}) : super(key: key); - - @override - State createState() => _ConversationsListState(); -} - -class _ConversationsListState extends State { - @override - void initState() { - checkLogin(); - - super.initState(); - } - - final _suggestions = []; - final _biggerFont = const TextStyle(fontSize: 18); - - Future checkLogin() async { - SharedPreferences preferences = await SharedPreferences.getInstance(); - print(preferences.getBool('islogin')); - if (preferences.getBool('islogin') != true) { - setState(() { - Navigator.of(context).push(MaterialPageRoute( - builder: (context) => const UnauthenticatedLandingWidget(), - )); - }); - } - } - - Widget list() { - - if (_suggestions.isEmpty) { - return const Center( - child: Text('No Conversations'), - ); - } - - return ListView.builder( - itemCount: _suggestions.length, - padding: const EdgeInsets.all(16.0), - itemBuilder: /*1*/ (context, i) { - //if (i >= _suggestions.length) { - // TODO: Check for more conversations here. Remove the itemCount to use this section - //_suggestions.addAll(generateWordPairs().take(10)); /*4*/ - //} - return Column( - children: [ - ListTile( - title: Text( - _suggestions[i], - style: _biggerFont, - ), - ), - const Divider(), - ] - ); - }, - ); - } - - @override - Widget build(BuildContext context) { - return WillPopScope( - onWillPop: () async => false, - child: Scaffold( - appBar: AppBar( - title: Text('Envelope'), - actions: [ - PopupMenuButton( - icon: const FaIcon(FontAwesomeIcons.ellipsisVertical, color: Colors.white, size: 40), - itemBuilder: (context) => [ - const PopupMenuItem( - value: 0, - child: Text("Settings"), - ), - const PopupMenuItem( - value: 1, - child: Text("Logout"), - ), - - ], - onSelected: (item) => selectedMenuItem(context, item), - ), - ], - ), - body: list(), - ), - ); - } - - void selectedMenuItem(BuildContext context, item) async { - switch (item) { - case 0: - print("Settings"); - break; - case 1: - SharedPreferences preferences = await SharedPreferences.getInstance(); - preferences.setBool('islogin', false); - Navigator.of(context).push(MaterialPageRoute( - builder: (context) => const UnauthenticatedLandingWidget(), - )); - break; - } - } -} diff --git a/mobile/lib/views/main/friend_list.dart b/mobile/lib/views/main/friend_list.dart new file mode 100644 index 0000000..8d2f4af --- /dev/null +++ b/mobile/lib/views/main/friend_list.dart @@ -0,0 +1,105 @@ +import 'package:flutter/material.dart'; +import '/models/friends.dart'; +import '/views/main/friend_list_item.dart'; + +class FriendList extends StatefulWidget { + const FriendList({Key? key}) : super(key: key); + + @override + State createState() => _FriendListState(); +} + +class _FriendListState extends State { + List friends = [ + Friend(id: 'abc', username: 'Test1'), + Friend(id: 'abc', username: 'Test2'), + Friend(id: 'abc', username: 'Test3'), + Friend(id: 'abc', username: 'Test4'), + Friend(id: 'abc', username: 'Test5'), + ]; + + Widget list() { + + if (friends.isEmpty) { + return const Center( + child: Text('No Friends'), + ); + } + + return ListView.builder( + itemCount: friends.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 16), + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, i) { + return FriendListItem( + id: friends[i].id, + username: friends[i].username, + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SafeArea( + child: Padding( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text("Friends",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), + Container( + padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), + height: 30, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(30), + color: Colors.pink[50], + ), + child: Row( + children: const [ + Icon(Icons.add,color: Colors.pink,size: 20,), + SizedBox(width: 2,), + Text("Add",style: TextStyle(fontSize: 14,fontWeight: FontWeight.bold),), + ], + ), + ) + ], + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: TextField( + decoration: InputDecoration( + hintText: "Search...", + hintStyle: TextStyle(color: Colors.grey.shade600), + prefixIcon: Icon(Icons.search,color: Colors.grey.shade600, size: 20,), + filled: true, + fillColor: Colors.grey.shade100, + contentPadding: const EdgeInsets.all(8), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(20), + borderSide: BorderSide( + color: Colors.grey.shade100 + ) + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: list(), + ), + ], + ), + ), + ); + } +} diff --git a/mobile/lib/views/main/friend_list_item.dart b/mobile/lib/views/main/friend_list_item.dart new file mode 100644 index 0000000..42c5215 --- /dev/null +++ b/mobile/lib/views/main/friend_list_item.dart @@ -0,0 +1,56 @@ +import 'package:flutter/material.dart'; + +class FriendListItem extends StatefulWidget{ + final String id; + final String username; + const FriendListItem({ + Key? key, + required this.id, + required this.username, + }) : super(key: key); + + @override + _FriendListItemState createState() => _FriendListItemState(); +} + +class _FriendListItemState extends State { + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: (){ + }, + child: Container( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + // CircleAvatar( + // backgroundImage: NetworkImage(widget.imageUrl), + // maxRadius: 30, + // ), + //const SizedBox(width: 16), + Expanded( + child: Container( + color: Colors.transparent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(widget.username, style: const TextStyle(fontSize: 16)), + const SizedBox(height: 6), + //Text(widget.messageText,style: TextStyle(fontSize: 13,color: Colors.grey.shade600, fontWeight: widget.isMessageRead?FontWeight.bold:FontWeight.normal),), + const Divider(), + ], + ), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart new file mode 100644 index 0000000..c157055 --- /dev/null +++ b/mobile/lib/views/main/home.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '/views/main/conversation_list.dart'; +import '/views/main/friend_list.dart'; + +class Home extends StatefulWidget { + const Home({Key? key}) : super(key: key); + + @override + State createState() => _HomeState(); +} + +class _HomeState extends State { + @override + void initState() { + checkLogin(); + super.initState(); + } + + Future checkLogin() async { + SharedPreferences preferences = await SharedPreferences.getInstance(); + if (preferences.getBool('islogin') != true) { + Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); + } + } + + int _selectedIndex = 0; + static const List _widgetOptions = [ + ConversationList(), + FriendList(), + Text('Not Implemented'), + ]; + + void _onItemTapped(int index) { + setState(() { + _selectedIndex = index; + }); + } + + @override + Widget build(BuildContext context) { + return WillPopScope( + onWillPop: () async => false, + child: Scaffold( + body: _widgetOptions.elementAt(_selectedIndex), + bottomNavigationBar: BottomNavigationBar( + currentIndex: _selectedIndex, + onTap: _onItemTapped, + selectedItemColor: Colors.red, + unselectedItemColor: Colors.grey.shade600, + selectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600), + unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600), + type: BottomNavigationBarType.fixed, + items: const [ + BottomNavigationBarItem( + icon: Icon(Icons.message), + label: "Chats", + ), + BottomNavigationBarItem( + icon: Icon(Icons.group_work), + label: "Friends", + ), + BottomNavigationBarItem( + icon: Icon(Icons.account_box), + label: "Profile", + ), + ], + ), + ), + ); + } +} diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock index 1a1eab8..8bafdc8 100644 --- a/mobile/pubspec.lock +++ b/mobile/pubspec.lock @@ -49,7 +49,7 @@ packages: name: collection url: "https://pub.dartlang.org" source: hosted - version: "1.15.0" + version: "1.16.0" convert: dependency: transitive description: @@ -70,7 +70,7 @@ packages: name: fake_async url: "https://pub.dartlang.org" source: hosted - version: "1.2.0" + version: "1.3.0" ffi: dependency: transitive description: @@ -134,7 +134,7 @@ packages: name: js url: "https://pub.dartlang.org" source: hosted - version: "0.6.3" + version: "0.6.4" lints: dependency: transitive description: @@ -155,7 +155,7 @@ packages: name: material_color_utilities url: "https://pub.dartlang.org" source: hosted - version: "0.1.3" + version: "0.1.4" meta: dependency: transitive description: @@ -169,7 +169,7 @@ packages: name: path url: "https://pub.dartlang.org" source: hosted - version: "1.8.0" + version: "1.8.1" path_provider_linux: dependency: transitive description: @@ -286,7 +286,7 @@ packages: name: source_span url: "https://pub.dartlang.org" source: hosted - version: "1.8.1" + version: "1.8.2" stack_trace: dependency: transitive description: @@ -321,7 +321,7 @@ packages: name: test_api url: "https://pub.dartlang.org" source: hosted - version: "0.4.8" + version: "0.4.9" typed_data: dependency: transitive description: @@ -335,7 +335,7 @@ packages: name: vector_math url: "https://pub.dartlang.org" source: hosted - version: "2.1.1" + version: "2.1.2" win32: dependency: transitive description: @@ -351,5 +351,5 @@ packages: source: hosted version: "0.2.0+1" sdks: - dart: ">=2.16.2 <3.0.0" + dart: ">=2.17.0-0 <3.0.0" flutter: ">=2.8.0" diff --git a/mobile/windows/flutter/generated_plugins.cmake b/mobile/windows/flutter/generated_plugins.cmake index 4d10c25..b93c4c3 100644 --- a/mobile/windows/flutter/generated_plugins.cmake +++ b/mobile/windows/flutter/generated_plugins.cmake @@ -5,6 +5,9 @@ list(APPEND FLUTTER_PLUGIN_LIST ) +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + set(PLUGIN_BUNDLED_LIBRARIES) foreach(plugin ${FLUTTER_PLUGIN_LIST}) @@ -13,3 +16,8 @@ foreach(plugin ${FLUTTER_PLUGIN_LIST}) list(APPEND PLUGIN_BUNDLED_LIBRARIES $) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) -- 2.17.1 From 1a9f76311279956963e9444c282adbf4418afab3 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Wed, 8 Jun 2022 20:39:50 +0930 Subject: [PATCH 04/24] Start adding routes for mobile interaction Add data seeders for testing --- Backend/Api/Auth/Login.go | 1 - Backend/Api/Auth/Logout.go | 34 ++++ Backend/Api/Friends/EncryptedFriendsList.go | 41 +++++ Backend/Api/Friends/FriendRequest.go | 59 +++++++ Backend/Api/Friends/Friends.go | 32 ++++ Backend/Api/Messages/MessageThread.go | 43 +++++ Backend/Api/Routes.go | 39 ++--- Backend/Database/Friends.go | 57 ++++++ Backend/Database/Init.go | 2 +- Backend/Database/Messages.go | 52 ++++++ Backend/Database/Seeder/FriendSeeder.go | 67 ++++++++ Backend/Database/Seeder/MessageSeeder.go | 136 +++++++++++++++ Backend/Database/Seeder/Seed.go | 50 ++++++ Backend/Database/Seeder/UserSeeder.go | 68 ++++++++ Backend/Models/Friends.go | 15 +- Backend/Models/Messages.go | 21 ++- Backend/Util/Bytes.go | 21 +++ Backend/Util/UserHelper.go | 51 ++++++ Backend/go.mod | 2 +- Backend/main.go | 15 ++ mobile/lib/models/conversations.dart | 30 ++++ mobile/lib/utils/storage/encryption_keys.dart | 5 + mobile/lib/views/authentication/login.dart | 2 - .../lib/views/main/conversation_detail.dart | 162 ++++++++++++++++++ mobile/lib/views/main/conversation_list.dart | 113 +++++++++--- .../views/main/conversation_list_item.dart | 60 +++++++ mobile/lib/views/main/home.dart | 3 +- mobile/lib/views/main/profile.dart | 64 +++++++ 28 files changed, 1182 insertions(+), 63 deletions(-) create mode 100644 Backend/Api/Auth/Logout.go create mode 100644 Backend/Api/Friends/EncryptedFriendsList.go create mode 100644 Backend/Api/Friends/FriendRequest.go create mode 100644 Backend/Api/Friends/Friends.go create mode 100644 Backend/Api/Messages/MessageThread.go create mode 100644 Backend/Database/Friends.go create mode 100644 Backend/Database/Messages.go create mode 100644 Backend/Database/Seeder/FriendSeeder.go create mode 100644 Backend/Database/Seeder/MessageSeeder.go create mode 100644 Backend/Database/Seeder/Seed.go create mode 100644 Backend/Database/Seeder/UserSeeder.go create mode 100644 Backend/Util/Bytes.go create mode 100644 Backend/Util/UserHelper.go create mode 100644 mobile/lib/models/conversations.dart create mode 100644 mobile/lib/views/main/conversation_detail.dart create mode 100644 mobile/lib/views/main/conversation_list_item.dart create mode 100644 mobile/lib/views/main/profile.dart diff --git a/Backend/Api/Auth/Login.go b/Backend/Api/Auth/Login.go index 4d3e3f2..d3e5116 100644 --- a/Backend/Api/Auth/Login.go +++ b/Backend/Api/Auth/Login.go @@ -48,7 +48,6 @@ func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey // Return updated json w.WriteHeader(code) w.Write(returnJson) - } func Login(w http.ResponseWriter, r *http.Request) { diff --git a/Backend/Api/Auth/Logout.go b/Backend/Api/Auth/Logout.go new file mode 100644 index 0000000..822b21d --- /dev/null +++ b/Backend/Api/Auth/Logout.go @@ -0,0 +1,34 @@ +package Auth + +import ( + "net/http" + "time" +) + +func Logout(w http.ResponseWriter, r *http.Request) { + var ( + c *http.Cookie + sessionToken string + err error + ) + + c, err = r.Cookie("session_token") + if err != nil { + if err == http.ErrNoCookie { + w.WriteHeader(http.StatusUnauthorized) + return + } + w.WriteHeader(http.StatusBadRequest) + return + } + + sessionToken = c.Value + + delete(Sessions, sessionToken) + + http.SetCookie(w, &http.Cookie{ + Name: "session_token", + Value: "", + Expires: time.Now(), + }) +} diff --git a/Backend/Api/Friends/EncryptedFriendsList.go b/Backend/Api/Friends/EncryptedFriendsList.go new file mode 100644 index 0000000..5179c9a --- /dev/null +++ b/Backend/Api/Friends/EncryptedFriendsList.go @@ -0,0 +1,41 @@ +package Friends + +import ( + "encoding/json" + "net/http" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +func EncryptedFriendList(w http.ResponseWriter, r *http.Request) { + var ( + userSession Auth.Session + friends []Models.Friend + returnJson []byte + err error + ) + + userSession, err = Auth.CheckCookie(r) + + if err != nil { + http.Error(w, "Forbidden", http.StatusUnauthorized) + return + } + + friends, err = Database.GetFriendsByUserId(userSession.UserID) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + returnJson, err = json.MarshalIndent(friends, "", " ") + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) + w.Write(returnJson) +} diff --git a/Backend/Api/Friends/FriendRequest.go b/Backend/Api/Friends/FriendRequest.go new file mode 100644 index 0000000..078bdcb --- /dev/null +++ b/Backend/Api/Friends/FriendRequest.go @@ -0,0 +1,59 @@ +package Friends + +import ( + "encoding/json" + "io/ioutil" + "net/http" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Util" +) + +func FriendRequest(w http.ResponseWriter, r *http.Request) { + var ( + user Models.User + requestBody []byte + requestJson map[string]interface{} + friendID []byte + friendRequest Models.Friend + err error + ) + + user, err = Util.GetUserById(w, r) + if err != nil { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + requestBody, err = ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + json.Unmarshal(requestBody, &requestJson) + if requestJson["id"] == nil { + http.Error(w, "Invalid Data", http.StatusBadRequest) + return + } + + friendID, err = Util.ToBytes(requestJson["id"]) + if requestJson["id"] == nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + friendRequest = Models.Friend{ + UserID: user.ID, + FriendID: friendID, + } + + err = Database.CreateFriendRequest(&friendRequest) + if requestJson["id"] == nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusNoContent) +} diff --git a/Backend/Api/Friends/Friends.go b/Backend/Api/Friends/Friends.go new file mode 100644 index 0000000..0706e14 --- /dev/null +++ b/Backend/Api/Friends/Friends.go @@ -0,0 +1,32 @@ +package Friends + +import ( + "encoding/json" + "net/http" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Util" +) + +func Friend(w http.ResponseWriter, r *http.Request) { + var ( + userData Models.User + returnJson []byte + err error + ) + + userData, err = Util.GetUserById(w, r) + if err != nil { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + returnJson, err = json.MarshalIndent(userData, "", " ") + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) + w.Write(returnJson) +} diff --git a/Backend/Api/Messages/MessageThread.go b/Backend/Api/Messages/MessageThread.go new file mode 100644 index 0000000..cd2e08e --- /dev/null +++ b/Backend/Api/Messages/MessageThread.go @@ -0,0 +1,43 @@ +package Messages + +import ( + "encoding/json" + "net/http" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + "github.com/gorilla/mux" +) + +func MessageThread(w http.ResponseWriter, r *http.Request) { + var ( + messages []Models.Message + urlVars map[string]string + threadID string + returnJson []byte + ok bool + err error + ) + + urlVars = mux.Vars(r) + threadID, ok = urlVars["threadID"] + if !ok { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + messages, err = Database.GetMessagesByThreadId(threadID) + if !ok { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + returnJson, err = json.MarshalIndent(messages, "", " ") + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) + w.Write(returnJson) +} diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index ad4d271..9715739 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -5,6 +5,8 @@ import ( "net/http" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Friends" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Messages" "github.com/gorilla/mux" ) @@ -12,8 +14,7 @@ import ( func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf( - "%s %s %s, Content Length: %d", - r.RemoteAddr, + "%s %s, Content Length: %d", r.Method, r.RequestURI, r.ContentLength, @@ -26,50 +27,44 @@ func loggingMiddleware(next http.Handler) http.Handler { func authenticationMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var ( - //userSession Auth.Session - //err error + err error ) - http.Error(w, "Forbidden", http.StatusUnauthorized) - return - - /** - userSession, err = Auth.CheckCookie(r) + _, err = Auth.CheckCookie(r) if err != nil { http.Error(w, "Forbidden", http.StatusUnauthorized) return } - log.Printf( - "Authenticated user: %s (%s)", - userSession.Email, - userSession.UserID, - ) - next.ServeHTTP(w, r) - */ }) } func InitApiEndpoints(router *mux.Router) { var ( - api *mux.Router - adminApi *mux.Router + api *mux.Router + authApi *mux.Router ) log.Println("Initializing API routes...") api = router.PathPrefix("/api/v1/").Subrouter() - api.Use(loggingMiddleware) // Define routes for authentication api.HandleFunc("/signup", Auth.Signup).Methods("POST") api.HandleFunc("/login", Auth.Login).Methods("POST") - // api.HandleFunc("/logout", Auth.Logout).Methods("GET") + api.HandleFunc("/logout", Auth.Logout).Methods("GET") + + authApi = api.PathPrefix("/auth/").Subrouter() + authApi.Use(authenticationMiddleware) - adminApi = api.PathPrefix("/message/").Subrouter() + // Define routes for friends and friend requests + authApi.HandleFunc("/friends", Friends.EncryptedFriendList).Methods("GET") + authApi.HandleFunc("/friend/{userID}", Friends.Friend).Methods("GET") + authApi.HandleFunc("/friend/{userID}/request", Friends.FriendRequest).Methods("POST") - adminApi.Use(authenticationMiddleware) + // Define routes for messages + authApi.HandleFunc("/messages/{threadID}", Messages.MessageThread).Methods("GET") } diff --git a/Backend/Database/Friends.go b/Backend/Database/Friends.go new file mode 100644 index 0000000..946a1d3 --- /dev/null +++ b/Backend/Database/Friends.go @@ -0,0 +1,57 @@ +package Database + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + "github.com/gofrs/uuid" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +func GetFriendById(id string) (Models.Friend, error) { + var ( + friend Models.Friend + err error + ) + + err = DB.Preload(clause.Associations). + First(&friend, "id = ?", id). + Error + + return friend, err +} + +func GetFriendsByUserId(userID string) ([]Models.Friend, error) { + var ( + friends []Models.Friend + err error + ) + + err = DB.Model(Models.Friend{}). + Where("user_id = ?", userID). + Find(&friends). + Error + + return friends, err +} + +func CreateFriendRequest(friend *Models.Friend) error { + var ( + err error + ) + + friend.ThreadID, err = uuid.NewV1() + if err != nil { + return err + } + + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(friend). + Error +} + +func DeleteFriend(friend *Models.Friend) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Delete(friend). + Error +} diff --git a/Backend/Database/Init.go b/Backend/Database/Init.go index b9de172..7918085 100644 --- a/Backend/Database/Init.go +++ b/Backend/Database/Init.go @@ -21,7 +21,7 @@ func GetModels() []interface{} { &Models.User{}, &Models.Friend{}, &Models.MessageData{}, - &Models.MessageKey{}, + &Models.Message{}, } } diff --git a/Backend/Database/Messages.go b/Backend/Database/Messages.go new file mode 100644 index 0000000..1d17b09 --- /dev/null +++ b/Backend/Database/Messages.go @@ -0,0 +1,52 @@ +package Database + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +func GetMessageById(id string) (Models.Message, error) { + var ( + message Models.Message + err error + ) + + err = DB.Preload(clause.Associations). + First(&message, "id = ?", id). + Error + + return message, err +} + +func GetMessagesByThreadId(id string) ([]Models.Message, error) { + var ( + messages []Models.Message + err error + ) + + err = DB.Preload(clause.Associations). + Find(&messages, "thread_id = ?", id). + Error + + return messages, err +} + +func CreateMessage(message *Models.Message) error { + var ( + err error + ) + + err = DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(message). + Error + + return err +} + +func DeleteMessage(message *Models.Message) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Delete(message). + Error +} diff --git a/Backend/Database/Seeder/FriendSeeder.go b/Backend/Database/Seeder/FriendSeeder.go new file mode 100644 index 0000000..771dcad --- /dev/null +++ b/Backend/Database/Seeder/FriendSeeder.go @@ -0,0 +1,67 @@ +package Seeder + +import ( + "time" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +func seedFriend(user, friendUser Models.User) error { + var ( + friend Models.Friend + err error + ) + + friend = Models.Friend{ + UserID: user.ID, + FriendID: encryptWithPublicKey(friendUser.ID.Bytes(), decodedPublicKey), + AcceptedAt: time.Now(), + } + + err = Database.CreateFriendRequest(&friend) + if err != nil { + return err + } + + friend = Models.Friend{ + UserID: friendUser.ID, + FriendID: encryptWithPublicKey(user.ID.Bytes(), decodedPublicKey), + AcceptedAt: time.Now(), + } + + return Database.CreateFriendRequest(&friend) +} + +func SeedFriends() { + var ( + primaryUser Models.User + secondaryUser Models.User + i int + err error + ) + + primaryUser, err = Database.GetUserByUsername("testUser") + if err != nil { + panic(err) + } + + secondaryUser, err = Database.GetUserByUsername("testUser2") + if err != nil { + panic(err) + } + + err = seedFriend(primaryUser, secondaryUser) + + for i = 0; i <= 3; i++ { + secondaryUser, err = Database.GetUserByUsername(userNames[i]) + if err != nil { + panic(err) + } + + err = seedFriend(primaryUser, secondaryUser) + if err != nil { + panic(err) + } + } +} diff --git a/Backend/Database/Seeder/MessageSeeder.go b/Backend/Database/Seeder/MessageSeeder.go new file mode 100644 index 0000000..4b36671 --- /dev/null +++ b/Backend/Database/Seeder/MessageSeeder.go @@ -0,0 +1,136 @@ +package Seeder + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "crypto/rsa" + "crypto/sha512" + "encoding/pem" + "hash" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + "github.com/gofrs/uuid" +) + +// EncryptWithPublicKey encrypts data with public key +func encryptWithPublicKey(msg []byte, pub *rsa.PublicKey) []byte { + var ( + hash hash.Hash + ) + + hash = sha512.New() + ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pub, msg, nil) + if err != nil { + panic(err) + } + return ciphertext +} + +func PKCS5Padding(ciphertext []byte, blockSize int, after int) []byte { + var ( + padding int + padtext []byte + ) + padding = (blockSize - len(ciphertext)%blockSize) + padtext = bytes.Repeat([]byte{byte(padding)}, padding) + return append(ciphertext, padtext...) +} + +func seedMessage(primaryUser, secondaryUser Models.User, threadID uuid.UUID, i int) error { + var ( + messageKey Models.Message + messageData Models.MessageData + + block cipher.Block + mode cipher.BlockMode + pemBlock *pem.Block + + plaintext string + ciphertext []byte + + bKey []byte + bIV []byte + bPlaintext []byte + + err error + ) + + plaintext = "Test Message" + + bKey = make([]byte, 32) + _, err = rand.Read(bKey) + if err != nil { + panic(err) + } + bIV = make([]byte, 16) + _, err = rand.Read(bIV) + if err != nil { + panic(err) + } + bPlaintext = PKCS5Padding([]byte(plaintext), aes.BlockSize, len(plaintext)) + + pemBlock = &pem.Block{ + Type: "AES KEY", + Bytes: bKey, + } + + block, err = aes.NewCipher(bKey) + if err != nil { + panic(err) + } + + ciphertext = make([]byte, len(bPlaintext)) + + mode = cipher.NewCBCEncrypter(block, bIV) + + mode.CryptBlocks(ciphertext, bPlaintext) + + messageData = Models.MessageData{ + Data: ciphertext, + } + + messageKey = Models.Message{ + UserID: primaryUser.ID, + MessageData: messageData, + MessageType: "sender", + RelationalUserId: encryptWithPublicKey(secondaryUser.ID.Bytes(), decodedPublicKey), + SymmetricKey: string(pem.EncodeToMemory(pemBlock)), + } + + return Database.CreateMessage(&messageKey) +} + +func SeedMessages() { + var ( + primaryUser Models.User + secondaryUser Models.User + threadID uuid.UUID + i int + err error + ) + + primaryUser, err = Database.GetUserByUsername("testUser") + if err != nil { + panic(err) + } + + secondaryUser, err = Database.GetUserByUsername("testUser2") + if err != nil { + panic(err) + } + + threadID, err = uuid.NewV4() + if err != nil { + panic(err) + } + + for i = 0; i <= 20; i++ { + err = seedMessage(primaryUser, secondaryUser, threadID, i) + if err != nil { + panic(err) + } + } +} diff --git a/Backend/Database/Seeder/Seed.go b/Backend/Database/Seeder/Seed.go new file mode 100644 index 0000000..e1d2531 --- /dev/null +++ b/Backend/Database/Seeder/Seed.go @@ -0,0 +1,50 @@ +package Seeder + +import ( + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "log" +) + +const ( + // Encrypted with "password" + encryptedPrivateKey string = ` +sPhQsHpXYFqPb7qdmTY7APFwBb4m7meCITujDeKMQFnz2F4v8Ovq5fH98j36v9Ayqcf/p/SyRnzP+NAEZI3fZ9iQKrHhioZ13C+Qx3Uz8Z6h44laJatagb7WOIPJSf28tNGZ38vLb0CU5fOOXuTZn4PJIkMprc8sS9eynZoCAvlUqvQTz6pOiguLcKjlwpZN2AAclnBS58j3XmYPK+Vcl1Lidq2sQLnBuwjbLvXxpVIWdw3TcQebVVIdZUZfoTF50tWozjUiuyW7SfVwQ2d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ZulVy1Yv3e+GMzgQhAuxhz/8wsHkFkUTweDZCrCZPhkTXlCrxDIuKykQ0el+RnpSjyyljOsAWAdTmrz0a2Nh9FOmF1v49pWy3Z3aJG58xl1dmFkpXjT3m36GB4Z30iR1uOMnNdrtfwIfLQAc7nmle2LxCHeEMYzlA9y6JChm5kGI6FmglSKYTxvDm40jA5mYyDCPADeCodbIw4Mtm0nwrM3QqKWj+jlaL8BY7/jjaosmz7VK2do4wIDAQAB +-----END PUBLIC KEY----- +` +) + +var ( + decodedPublicKey *rsa.PublicKey +) + +func Seed() { + var ( + block *pem.Block + decKey any + err error + ) + + // TODO: Fix this parsing + block, _ = pem.Decode([]byte(publicKey)) + decKey, err = x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + panic(err) + } + decodedPublicKey = decKey.(*rsa.PublicKey) + + log.Println("Seeding users...") + SeedUsers() + + log.Println("Seeding friend connections...") + SeedFriends() + + log.Println("Seeding messages...") + SeedMessages() +} diff --git a/Backend/Database/Seeder/UserSeeder.go b/Backend/Database/Seeder/UserSeeder.go new file mode 100644 index 0000000..fd7cc7e --- /dev/null +++ b/Backend/Database/Seeder/UserSeeder.go @@ -0,0 +1,68 @@ +package Seeder + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +var userNames = []string{ + "assuredcoot", + "quotesteeve", + "blueberriessiemens", + "eliteexaggerate", + "twotrice", + "moderagged", + "duleelderly", + "stringdetailed", + "nodesanymore", + "sacredpolitical", + "pajamasenergy", +} + +func createUser(username string) (Models.User, error) { + var ( + userData Models.User + password string + err error + ) + + password, err = Auth.HashPassword("password") + if err != nil { + return Models.User{}, err + } + + userData = Models.User{ + Username: username, + Password: password, + AsymmetricPrivateKey: encryptedPrivateKey, + AsymmetricPublicKey: publicKey, + } + + err = Database.CreateUser(&userData) + return userData, err +} + +func SeedUsers() { + var ( + i int + err error + ) + + // Seed users used for conversation seeding + _, err = createUser("testUser") + if err != nil { + panic(err) + } + _, err = createUser("testUser2") + if err != nil { + panic(err) + } + + for i = 0; i <= 10; i++ { + _, err = createUser(userNames[i]) + if err != nil { + panic(err) + } + } +} diff --git a/Backend/Models/Friends.go b/Backend/Models/Friends.go index c0b9abd..b56b8ab 100644 --- a/Backend/Models/Friends.go +++ b/Backend/Models/Friends.go @@ -1,9 +1,18 @@ package Models -import "github.com/gofrs/uuid" +import ( + "time" + "github.com/gofrs/uuid" +) + +// Set with User being the requestee, and FriendID being the requester type Friend struct { Base - UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` - FriendId string `gorm:"column:friend_id;not null" json:"friend_id"` // Stored encrypted + UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` + User User `json:"user"` + FriendID []byte `gorm:"not null" json:"friend_id"` // Stored encrypted + ThreadID uuid.UUID `gorm:"type:uuid;column:thread_id;not null;" json:"thread_id"` + Thread []Message `gorm:"foreignKey:thread_id" json:"-"` + AcceptedAt time.Time `json:"accepted_at"` } diff --git a/Backend/Models/Messages.go b/Backend/Models/Messages.go index ce2fc1b..35e903d 100644 --- a/Backend/Models/Messages.go +++ b/Backend/Models/Messages.go @@ -2,14 +2,25 @@ package Models import "github.com/gofrs/uuid" +const ( + MessageTypeSender = "sender" + MessageTypeReceiver = "reciever" +) + type MessageData struct { Base - Data string `gorm:"not null" json:"data"` // Stored encrypted + Data []byte `gorm:"not null" json:"data"` // Stored encrypted } -type MessageKey struct { +// TODO: Rename this to something better +type Message struct { Base - UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` - MessageDataID uuid.UUID `gorm:"type:uuid;column:message_data_id;not null;" json:"message_data_id"` - SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted + ThreadID uuid.UUID `gorm:"not null" json:"thread_id"` + UserID uuid.UUID `json:"-"` + User User `json:"user"` + MessageDataID uuid.UUID `json:"-"` + MessageData MessageData `json:"message_data"` + MessageType string `gorm:"not null" json:"message_type"` // sender / reciever + RelationalUserId []byte `gorm:"not null" json:"relational_user_id"` // Stored encrypted. UserID for the user this message is in relation to + SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted } diff --git a/Backend/Util/Bytes.go b/Backend/Util/Bytes.go new file mode 100644 index 0000000..cfef327 --- /dev/null +++ b/Backend/Util/Bytes.go @@ -0,0 +1,21 @@ +package Util + +import ( + "bytes" + "encoding/gob" +) + +func ToBytes(key interface{}) ([]byte, error) { + var ( + buf bytes.Buffer + enc *gob.Encoder + err error + ) + enc = gob.NewEncoder(&buf) + err = enc.Encode(key) + if err != nil { + return nil, err + } + return buf.Bytes(), nil + +} diff --git a/Backend/Util/UserHelper.go b/Backend/Util/UserHelper.go new file mode 100644 index 0000000..32616a6 --- /dev/null +++ b/Backend/Util/UserHelper.go @@ -0,0 +1,51 @@ +package Util + +import ( + "errors" + "log" + "net/http" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "github.com/gorilla/mux" +) + +func GetUserId(r *http.Request) (string, error) { + var ( + urlVars map[string]string + id string + ok bool + ) + + urlVars = mux.Vars(r) + id, ok = urlVars["userID"] + if !ok { + return id, errors.New("Could not get id") + } + return id, nil +} + +func GetUserById(w http.ResponseWriter, r *http.Request) (Models.User, error) { + var ( + postData Models.User + id string + err error + ) + + id, err = GetUserId(r) + if err != nil { + log.Printf("Error encountered getting id\n") + http.Error(w, "Error", http.StatusInternalServerError) + return postData, err + } + + postData, err = Database.GetUserById(id) + if err != nil { + log.Printf("Could not find user with id %s\n", id) + http.Error(w, "Error", http.StatusInternalServerError) + return postData, err + } + + return postData, nil +} diff --git a/Backend/go.mod b/Backend/go.mod index b67be65..127bb75 100644 --- a/Backend/go.mod +++ b/Backend/go.mod @@ -6,6 +6,7 @@ require ( github.com/Kangaroux/go-map-schema v0.6.1 github.com/gofrs/uuid v4.2.0+incompatible github.com/gorilla/mux v1.8.0 + golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 gorm.io/driver/postgres v1.3.4 gorm.io/gorm v1.23.4 ) @@ -21,6 +22,5 @@ require ( github.com/jackc/pgx/v4 v4.15.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.4 // indirect - golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect golang.org/x/text v0.3.7 // indirect ) diff --git a/Backend/main.go b/Backend/main.go index 009e8ae..2978a6f 100644 --- a/Backend/main.go +++ b/Backend/main.go @@ -1,16 +1,26 @@ package main import ( + "flag" "net/http" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder" "github.com/gorilla/mux" ) +var ( + seed bool +) + func init() { Database.Init() + + flag.BoolVar(&seed, "seed", false, "Seed database for development") + + flag.Parse() } func main() { @@ -18,6 +28,11 @@ func main() { router *mux.Router ) + if seed { + Seeder.Seed() + return + } + router = mux.NewRouter() Api.InitApiEndpoints(router) diff --git a/mobile/lib/models/conversations.dart b/mobile/lib/models/conversations.dart new file mode 100644 index 0000000..89a5373 --- /dev/null +++ b/mobile/lib/models/conversations.dart @@ -0,0 +1,30 @@ +const messageTypeSender = 'sender'; +const messageTypeReceiver = 'receiver'; + +class Message { + String id; + String conversationId; + String symmetricKey; + String data; + String messageType; + String? decryptedData; + Message({ + required this.id, + required this.conversationId, + required this.symmetricKey, + required this.data, + required this.messageType, + this.decryptedData, + }); +} + +class Conversation { + String id; + String friendId; + String recentMessageId; + Conversation({ + required this.id, + required this.friendId, + required this.recentMessageId, + }); +} diff --git a/mobile/lib/utils/storage/encryption_keys.dart b/mobile/lib/utils/storage/encryption_keys.dart index d27bfc7..edcd727 100644 --- a/mobile/lib/utils/storage/encryption_keys.dart +++ b/mobile/lib/utils/storage/encryption_keys.dart @@ -11,6 +11,11 @@ void setPrivateKey(RSAPrivateKey key) async { prefs.setString(rsaPrivateKeyName, keyPem); } +void unsetPrivateKey() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(rsaPrivateKeyName); +} + Future getPrivateKey() async { final prefs = await SharedPreferences.getInstance(); String? keyPem = prefs.getString(rsaPrivateKeyName); diff --git a/mobile/lib/views/authentication/login.dart b/mobile/lib/views/authentication/login.dart index a2d6595..98a3ce9 100644 --- a/mobile/lib/views/authentication/login.dart +++ b/mobile/lib/views/authentication/login.dart @@ -2,7 +2,6 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; -import '/views/main/conversation_list.dart'; import '/utils/encryption/rsa_key_helper.dart'; import '/utils/encryption/aes_helper.dart'; import '/utils/storage/encryption_keys.dart'; @@ -73,7 +72,6 @@ class Login extends StatelessWidget { //`true` if you want Flutter to automatically add Back Button when needed, //or `false` if you want to force your own back button every where leading: IconButton(icon: const Icon(Icons.arrow_back), - //onPressed:() => Navigator.pop(context, false), onPressed:() => { Navigator.pop(context) } diff --git a/mobile/lib/views/main/conversation_detail.dart b/mobile/lib/views/main/conversation_detail.dart new file mode 100644 index 0000000..8732f80 --- /dev/null +++ b/mobile/lib/views/main/conversation_detail.dart @@ -0,0 +1,162 @@ +import 'package:flutter/material.dart'; +import '/models/conversations.dart'; + +class ConversationDetail extends StatefulWidget{ + const ConversationDetail({Key? key}) : super(key: key); + + @override + _ConversationDetailState createState() => _ConversationDetailState(); +} + +class _ConversationDetailState extends State { + Conversation conversation = Conversation( + id: '777', + friendId: 'abc', + recentMessageId: '111', + ); + + List messages = [ + Message( + id: '444', + conversationId: '777', + symmetricKey: '', + data: 'This is a message', + messageType: messageTypeSender, + ), + Message( + id: '444', + conversationId: '777', + symmetricKey: '', + data: 'This is a message', + messageType: messageTypeReceiver, + ), + Message( + id: '444', + conversationId: '777', + symmetricKey: '', + data: 'This is a message', + messageType: messageTypeSender + ), + Message( + id: '444', + conversationId: '777', + symmetricKey: '', + data: 'This is a message', + messageType: messageTypeReceiver, + ), + ]; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + elevation: 0, + automaticallyImplyLeading: false, + backgroundColor: Colors.white, + flexibleSpace: SafeArea( + child: Container( + padding: const EdgeInsets.only(right: 16), + child: Row( + children: [ + IconButton( + onPressed: (){ + Navigator.pop(context); + }, + icon: const Icon(Icons.arrow_back,color: Colors.black,), + ), + const SizedBox(width: 2,), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: const [ + Text("Kriss Benwat",style: TextStyle( fontSize: 16 ,fontWeight: FontWeight.w600),), + ], + ), + ), + const Icon(Icons.settings,color: Colors.black54,), + ], + ), + ), + ), + ), + body: Stack( + children: [ + ListView.builder( + itemCount: messages.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 10,bottom: 10), + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, index) { + return Container( + padding: const EdgeInsets.only(left: 14,right: 14,top: 10,bottom: 10), + child: Align( + alignment: (messages[index].messageType == messageTypeReceiver ? Alignment.topLeft:Alignment.topRight), + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + color: (messages[index].messageType == messageTypeReceiver ? Colors.grey.shade200:Colors.blue[200]), + ), + padding: const EdgeInsets.all(16), + child: Text(messages[index].data, style: const TextStyle(fontSize: 15)), + ), + ), + ); + }, + ), + Align( + alignment: Alignment.bottomLeft, + child: ConstrainedBox( + constraints: const BoxConstraints( + maxHeight: 200.0, + ), + child: Container( + padding: const EdgeInsets.only(left: 10,bottom: 10,top: 10), + // height: 60, + width: double.infinity, + color: Colors.white, + child: Row( + children: [ + GestureDetector( + onTap: (){ + }, + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + color: Colors.lightBlue, + borderRadius: BorderRadius.circular(30), + ), + child: const Icon(Icons.add, color: Colors.white, size: 20, ), + ), + ), + const SizedBox(width: 15,), + const Expanded( + child: TextField( + decoration: InputDecoration( + hintText: "Write message...", + hintStyle: TextStyle(color: Colors.black54), + border: InputBorder.none, + ), + maxLines: null, + ), + ), + const SizedBox(width: 15,), + FloatingActionButton( + onPressed: () { + }, + child: const Icon(Icons.send,color: Colors.white,size: 18,), + backgroundColor: Colors.blue, + elevation: 0, + ), + ], + + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/mobile/lib/views/main/conversation_list.dart b/mobile/lib/views/main/conversation_list.dart index 1f414d4..b47e678 100644 --- a/mobile/lib/views/main/conversation_list.dart +++ b/mobile/lib/views/main/conversation_list.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; +import '/models/conversations.dart'; +import '/views/main/conversation_list_item.dart'; class ConversationList extends StatefulWidget { const ConversationList({Key? key}) : super(key: key); @@ -9,35 +10,41 @@ class ConversationList extends StatefulWidget { } class _ConversationListState extends State { - final _suggestions = []; - final _biggerFont = const TextStyle(fontSize: 18); + List messages = [ + Message( + id: '123', + conversationId: 'xyz', + data: '', + symmetricKey: '', + messageType: 'reciever', + ), + ]; + + List friends = [ + Conversation( + id: 'xyz', + friendId: 'abc', + recentMessageId: '123', + ), + ]; Widget list() { - if (_suggestions.isEmpty) { + if (friends.isEmpty) { return const Center( child: Text('No Conversations'), ); } return ListView.builder( - itemCount: _suggestions.length, - padding: const EdgeInsets.all(16.0), - itemBuilder: /*1*/ (context, i) { - //if (i >= _suggestions.length) { - // TODO: Check for more conversations here. Remove the itemCount to use this section - //_suggestions.addAll(generateWordPairs().take(10)); /*4*/ - //} - return Column( - children: [ - ListTile( - title: Text( - _suggestions[i], - style: _biggerFont, - ), - ), - const Divider(), - ] + itemCount: friends.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 16), + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, i) { + return ConversationListItem( + id: friends[i].id, + username: 'Test', ); }, ); @@ -46,11 +53,63 @@ class _ConversationListState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Envelope'), - ), - body: list(), - ); - + body: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SafeArea( + child: Padding( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text("Conversations",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), + Container( + padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), + height: 30, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(30), + color: Colors.pink[50], + ), + child: Row( + children: const [ + Icon(Icons.add,color: Colors.pink,size: 20,), + SizedBox(width: 2,), + Text("Add",style: TextStyle(fontSize: 14,fontWeight: FontWeight.bold),), + ], + ), + ) + ], + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: TextField( + decoration: InputDecoration( + hintText: "Search...", + hintStyle: TextStyle(color: Colors.grey.shade600), + prefixIcon: Icon(Icons.search,color: Colors.grey.shade600, size: 20,), + filled: true, + fillColor: Colors.grey.shade100, + contentPadding: const EdgeInsets.all(8), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(20), + borderSide: BorderSide( + color: Colors.grey.shade100 + ) + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: list(), + ), + ], + ), + ), + ); } } diff --git a/mobile/lib/views/main/conversation_list_item.dart b/mobile/lib/views/main/conversation_list_item.dart new file mode 100644 index 0000000..e8b6c23 --- /dev/null +++ b/mobile/lib/views/main/conversation_list_item.dart @@ -0,0 +1,60 @@ +import 'package:flutter/material.dart'; +import '/views/main/conversation_detail.dart'; + +class ConversationListItem extends StatefulWidget{ + final String id; + final String username; + const ConversationListItem({ + Key? key, + required this.id, + required this.username, + }) : super(key: key); + + @override + _ConversationListItemState createState() => _ConversationListItemState(); +} + +class _ConversationListItemState extends State { + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: () { + Navigator.push(context, MaterialPageRoute(builder: (context){ + return ConversationDetail(); + })); + }, + child: Container( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + // CircleAvatar( + // backgroundImage: NetworkImage(widget.imageUrl), + // maxRadius: 30, + // ), + //const SizedBox(width: 16), + Expanded( + child: Container( + color: Colors.transparent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(widget.username, style: const TextStyle(fontSize: 16)), + const SizedBox(height: 6), + //Text(widget.messageText,style: TextStyle(fontSize: 13,color: Colors.grey.shade600, fontWeight: widget.isMessageRead?FontWeight.bold:FontWeight.normal),), + const Divider(), + ], + ), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index c157055..85b3ecc 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '/views/main/conversation_list.dart'; import '/views/main/friend_list.dart'; +import '/views/main/profile.dart'; class Home extends StatefulWidget { const Home({Key? key}) : super(key: key); @@ -28,7 +29,7 @@ class _HomeState extends State { static const List _widgetOptions = [ ConversationList(), FriendList(), - Text('Not Implemented'), + Profile(), ]; void _onItemTapped(int index) { diff --git a/mobile/lib/views/main/profile.dart b/mobile/lib/views/main/profile.dart new file mode 100644 index 0000000..488d1b6 --- /dev/null +++ b/mobile/lib/views/main/profile.dart @@ -0,0 +1,64 @@ +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '/utils/storage/encryption_keys.dart'; + +class Profile extends StatefulWidget { + const Profile({Key? key}) : super(key: key); + + @override + State createState() => _ProfileState(); +} + +class _ProfileState extends State { + @override + Widget build(BuildContext context) { + return Scaffold( + body: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SafeArea( + child: Padding( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text("Profile",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), + Container( + padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), + height: 30, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(30), + color: Colors.pink[50], + ), + child: GestureDetector( + onTap: () async { + final preferences = await SharedPreferences.getInstance(); + preferences.setBool('islogin', false); + preferences.remove(rsaPrivateKeyName); + Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); + }, + child: Row( + children: const [ + Icon(Icons.logout, color: Colors.pink, size: 20,), + SizedBox(width: 2,), + Text("Logout",style: TextStyle(fontSize: 14,fontWeight: FontWeight.bold),), + ], + ), + ), + ) + ], + ), + ), + ), + const Padding( + padding: EdgeInsets.only(top: 16,left: 16,right: 16), + child: Text('Test'), + ), + ], + ), + ), + ); + } +} -- 2.17.1 From d67e4e89ba385013c754e897c5fe1c21734754a2 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Mon, 13 Jun 2022 13:55:29 +0930 Subject: [PATCH 05/24] Update the message/thread structure, and fix the db seeder --- Backend/Api/Messages/CreateMessage.go | 23 ++ Backend/Api/Messages/MessageThread.go | 26 ++- Backend/Api/Routes.go | 2 +- Backend/Database/Friends.go | 10 - Backend/Database/Init.go | 2 + Backend/Database/MessageThreadUsers.go | 39 ++++ Backend/Database/MessageThreads.go | 42 ++++ Backend/Database/Messages.go | 13 -- Backend/Database/Seeder/MessageSeeder.go | 262 ++++++++++++++++++++--- Backend/Database/Seeder/Seed.go | 1 - Backend/Models/Friends.go | 2 - Backend/Models/Messages.go | 33 +-- Backend/Util/Strings.go | 21 ++ 13 files changed, 393 insertions(+), 83 deletions(-) create mode 100644 Backend/Api/Messages/CreateMessage.go create mode 100644 Backend/Database/MessageThreadUsers.go create mode 100644 Backend/Database/MessageThreads.go create mode 100644 Backend/Util/Strings.go diff --git a/Backend/Api/Messages/CreateMessage.go b/Backend/Api/Messages/CreateMessage.go new file mode 100644 index 0000000..d73977c --- /dev/null +++ b/Backend/Api/Messages/CreateMessage.go @@ -0,0 +1,23 @@ +package Messages + +import ( + "encoding/json" + "fmt" + "net/http" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +func CreateMessage(w http.ResponseWriter, r *http.Request) { + var ( + message Models.Message + err error + ) + + err = json.NewDecoder(r.Body).Decode(&message) + if err != nil { + return + } + + fmt.Println(message) +} diff --git a/Backend/Api/Messages/MessageThread.go b/Backend/Api/Messages/MessageThread.go index cd2e08e..8a86209 100644 --- a/Backend/Api/Messages/MessageThread.go +++ b/Backend/Api/Messages/MessageThread.go @@ -4,6 +4,7 @@ import ( "encoding/json" "net/http" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" "github.com/gorilla/mux" @@ -11,28 +12,35 @@ import ( func MessageThread(w http.ResponseWriter, r *http.Request) { var ( - messages []Models.Message - urlVars map[string]string - threadID string - returnJson []byte - ok bool - err error + userData Models.User + messageThread Models.MessageThread + urlVars map[string]string + threadKey string + returnJson []byte + ok bool + err error ) + userData, err = Auth.CheckCookieCurrentUser(w, r) + if !ok { + http.Error(w, "Forbidden", http.StatusUnauthorized) + return + } + urlVars = mux.Vars(r) - threadID, ok = urlVars["threadID"] + threadKey, ok = urlVars["threadKey"] if !ok { http.Error(w, "Not Found", http.StatusNotFound) return } - messages, err = Database.GetMessagesByThreadId(threadID) + messageThread, err = Database.GetMessageThreadById(threadKey, userData) if !ok { http.Error(w, "Not Found", http.StatusNotFound) return } - returnJson, err = json.MarshalIndent(messages, "", " ") + returnJson, err = json.MarshalIndent(messageThread, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) return diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index 9715739..adc2f4a 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -66,5 +66,5 @@ func InitApiEndpoints(router *mux.Router) { authApi.HandleFunc("/friend/{userID}/request", Friends.FriendRequest).Methods("POST") // Define routes for messages - authApi.HandleFunc("/messages/{threadID}", Messages.MessageThread).Methods("GET") + authApi.HandleFunc("/messages/{threadKey}", Messages.MessageThread).Methods("GET") } diff --git a/Backend/Database/Friends.go b/Backend/Database/Friends.go index 946a1d3..d82ccab 100644 --- a/Backend/Database/Friends.go +++ b/Backend/Database/Friends.go @@ -2,7 +2,6 @@ package Database import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" - "github.com/gofrs/uuid" "gorm.io/gorm" "gorm.io/gorm/clause" @@ -36,15 +35,6 @@ func GetFriendsByUserId(userID string) ([]Models.Friend, error) { } func CreateFriendRequest(friend *Models.Friend) error { - var ( - err error - ) - - friend.ThreadID, err = uuid.NewV1() - if err != nil { - return err - } - return DB.Session(&gorm.Session{FullSaveAssociations: true}). Create(friend). Error diff --git a/Backend/Database/Init.go b/Backend/Database/Init.go index 7918085..12f90ae 100644 --- a/Backend/Database/Init.go +++ b/Backend/Database/Init.go @@ -22,6 +22,8 @@ func GetModels() []interface{} { &Models.Friend{}, &Models.MessageData{}, &Models.Message{}, + &Models.MessageThread{}, + &Models.MessageThreadUser{}, } } diff --git a/Backend/Database/MessageThreadUsers.go b/Backend/Database/MessageThreadUsers.go new file mode 100644 index 0000000..842bc15 --- /dev/null +++ b/Backend/Database/MessageThreadUsers.go @@ -0,0 +1,39 @@ +package Database + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +func GetMessageThreadUserById(id string) (Models.MessageThreadUser, error) { + var ( + message Models.MessageThreadUser + err error + ) + + err = DB.Preload(clause.Associations). + First(&message, "id = ?", id). + Error + + return message, err +} + +func CreateMessageThreadUser(messageThreadUser *Models.MessageThreadUser) error { + var ( + err error + ) + + err = DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(messageThreadUser). + Error + + return err +} + +func DeleteMessageThreadUser(messageThreadUser *Models.MessageThreadUser) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Delete(messageThreadUser). + Error +} diff --git a/Backend/Database/MessageThreads.go b/Backend/Database/MessageThreads.go new file mode 100644 index 0000000..be3ffc1 --- /dev/null +++ b/Backend/Database/MessageThreads.go @@ -0,0 +1,42 @@ +package Database + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +func GetMessageThreadById(id string, user Models.User) (Models.MessageThread, error) { + var ( + messageThread Models.MessageThread + err error + ) + + err = DB.Preload(clause.Associations). + Where("id = ?", id). + Where("user_id = ?", user.ID). + First(&messageThread). + Error + + return messageThread, err +} + +func CreateMessageThread(messageThread *Models.MessageThread) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(messageThread). + Error +} + +func UpdateMessageThread(messageThread *Models.MessageThread) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Where("id = ?", messageThread.ID). + Updates(messageThread). + Error +} + +func DeleteMessageThread(messageThread *Models.MessageThread) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Delete(messageThread). + Error +} diff --git a/Backend/Database/Messages.go b/Backend/Database/Messages.go index 1d17b09..866cc40 100644 --- a/Backend/Database/Messages.go +++ b/Backend/Database/Messages.go @@ -20,19 +20,6 @@ func GetMessageById(id string) (Models.Message, error) { return message, err } -func GetMessagesByThreadId(id string) ([]Models.Message, error) { - var ( - messages []Models.Message - err error - ) - - err = DB.Preload(clause.Associations). - Find(&messages, "thread_id = ?", id). - Error - - return messages, err -} - func CreateMessage(message *Models.Message) error { var ( err error diff --git a/Backend/Database/Seeder/MessageSeeder.go b/Backend/Database/Seeder/MessageSeeder.go index 4b36671..6a7504d 100644 --- a/Backend/Database/Seeder/MessageSeeder.go +++ b/Backend/Database/Seeder/MessageSeeder.go @@ -8,10 +8,12 @@ import ( "crypto/rsa" "crypto/sha512" "encoding/pem" + "fmt" "hash" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Util" "github.com/gofrs/uuid" ) @@ -39,27 +41,17 @@ func PKCS5Padding(ciphertext []byte, blockSize int, after int) []byte { return append(ciphertext, padtext...) } -func seedMessage(primaryUser, secondaryUser Models.User, threadID uuid.UUID, i int) error { +func generateAesKey() (*pem.Block, cipher.BlockMode) { var ( - messageKey Models.Message - messageData Models.MessageData - - block cipher.Block - mode cipher.BlockMode pemBlock *pem.Block + block cipher.Block - plaintext string - ciphertext []byte - - bKey []byte - bIV []byte - bPlaintext []byte + bKey []byte + bIV []byte err error ) - plaintext = "Test Message" - bKey = make([]byte, 32) _, err = rand.Read(bKey) if err != nil { @@ -70,7 +62,6 @@ func seedMessage(primaryUser, secondaryUser Models.User, threadID uuid.UUID, i i if err != nil { panic(err) } - bPlaintext = PKCS5Padding([]byte(plaintext), aes.BlockSize, len(plaintext)) pemBlock = &pem.Block{ Type: "AES KEY", @@ -82,53 +73,256 @@ func seedMessage(primaryUser, secondaryUser Models.User, threadID uuid.UUID, i i panic(err) } - ciphertext = make([]byte, len(bPlaintext)) + return pemBlock, cipher.NewCBCEncrypter(block, bIV) +} + +func seedMessage( + primaryUser Models.User, + primaryUserThreadKey, secondaryUserThreadKey string, + thread Models.MessageThread, + i int, +) error { + var ( + message Models.Message + messageData Models.MessageData + + messagePemBlock *pem.Block + messageMode cipher.BlockMode + + plaintext string + dataCiphertext []byte + senderIdCiphertext []byte + + bPlaintext []byte + bSenderIdPlaintext []byte + + err error + ) + + plaintext = "Test Message" + bPlaintext = PKCS5Padding([]byte(plaintext), aes.BlockSize, len(plaintext)) + bSenderIdPlaintext = PKCS5Padding(primaryUser.ID.Bytes(), aes.BlockSize, len(primaryUser.ID.Bytes())) + + dataCiphertext = make([]byte, len(bPlaintext)) + senderIdCiphertext = make([]byte, len(bSenderIdPlaintext)) - mode = cipher.NewCBCEncrypter(block, bIV) + messagePemBlock, messageMode = generateAesKey() - mode.CryptBlocks(ciphertext, bPlaintext) + messageMode.CryptBlocks(dataCiphertext, bPlaintext) + messageMode.CryptBlocks(senderIdCiphertext, bSenderIdPlaintext) messageData = Models.MessageData{ - Data: ciphertext, + Data: dataCiphertext, + SenderID: senderIdCiphertext, } - messageKey = Models.Message{ - UserID: primaryUser.ID, + message = Models.Message{ MessageData: messageData, - MessageType: "sender", - RelationalUserId: encryptWithPublicKey(secondaryUser.ID.Bytes(), decodedPublicKey), - SymmetricKey: string(pem.EncodeToMemory(pemBlock)), + SymmetricKey: encryptWithPublicKey(pem.EncodeToMemory(messagePemBlock), decodedPublicKey), + MessageThreadKey: primaryUserThreadKey, + } + + err = Database.CreateMessage(&message) + if err != nil { + return err + } + + // The symmetric key would be encrypted with secondary users public key in production + // But due to using the same pub/priv key pair for all users, we will just duplicate it + message = Models.Message{ + MessageDataID: message.MessageDataID, + SymmetricKey: encryptWithPublicKey(pem.EncodeToMemory(messagePemBlock), decodedPublicKey), + MessageThreadKey: secondaryUserThreadKey, + } + + err = Database.CreateMessage(&message) + if err != nil { + return err } - return Database.CreateMessage(&messageKey) + return err +} + +func seedMessageThread(threadPemBlock *pem.Block, threadMode cipher.BlockMode) (Models.MessageThread, error) { + var ( + messageThread Models.MessageThread + + name string + bNamePlaintext []byte + nameCiphertext []byte + + err error + ) + + name = "Test Conversation" + + bNamePlaintext = PKCS5Padding([]byte(name), aes.BlockSize, len(name)) + nameCiphertext = make([]byte, len(bNamePlaintext)) + + threadMode.CryptBlocks(nameCiphertext, bNamePlaintext) + + messageThread = Models.MessageThread{ + Name: nameCiphertext, + } + + err = Database.CreateMessageThread(&messageThread) + return messageThread, err +} + +func seedUpdateMessageThreadUsers( + userJson string, + threadPemBlock *pem.Block, + threadMode cipher.BlockMode, + messageThread Models.MessageThread, +) (Models.MessageThread, error) { + var ( + bUsersPlaintext []byte + usersCiphertext []byte + err error + ) + + bUsersPlaintext = PKCS5Padding([]byte(userJson), aes.BlockSize, len(userJson)) + usersCiphertext = make([]byte, len(bUsersPlaintext)) + + threadMode.CryptBlocks(usersCiphertext, bUsersPlaintext) + + messageThread.Users = usersCiphertext + err = Database.UpdateMessageThread(&messageThread) + return messageThread, err +} + +func seedMessageThreadUser( + user Models.User, + threadID uuid.UUID, + messageThreadKey string, + threadPemBlock *pem.Block, + threadMode cipher.BlockMode, +) (Models.MessageThreadUser, error) { + var ( + messageThreadUser Models.MessageThreadUser + + bThreadIdPlaintext []byte + threadIdCiphertext []byte + + bKeyPlaintext []byte + keyCiphertext []byte + + bAdminPlaintext []byte + adminCiphertext []byte + + err error + ) + + bThreadIdPlaintext = PKCS5Padding(threadID.Bytes(), aes.BlockSize, len(threadID.String())) + threadIdCiphertext = make([]byte, len(bThreadIdPlaintext)) + + bKeyPlaintext = PKCS5Padding([]byte(messageThreadKey), aes.BlockSize, len(messageThreadKey)) + keyCiphertext = make([]byte, len(bKeyPlaintext)) + + bAdminPlaintext = PKCS5Padding([]byte("true"), aes.BlockSize, len("true")) + adminCiphertext = make([]byte, len(bAdminPlaintext)) + + threadMode.CryptBlocks(threadIdCiphertext, bThreadIdPlaintext) + threadMode.CryptBlocks(keyCiphertext, bKeyPlaintext) + threadMode.CryptBlocks(adminCiphertext, bAdminPlaintext) + + messageThreadUser = Models.MessageThreadUser{ + UserID: user.ID, + MessageThreadID: threadIdCiphertext, + MessageThreadKey: keyCiphertext, + Admin: adminCiphertext, + SymmetricKey: encryptWithPublicKey(pem.EncodeToMemory(threadPemBlock), decodedPublicKey), + } + + err = Database.CreateMessageThreadUser(&messageThreadUser) + return messageThreadUser, err } func SeedMessages() { var ( - primaryUser Models.User - secondaryUser Models.User - threadID uuid.UUID - i int - err error + messageThread Models.MessageThread + threadPemBlock *pem.Block + threadMode cipher.BlockMode + + primaryUser Models.User + primaryUserThreadKey string + secondaryUser Models.User + secondaryUserThreadKey string + + userJson string + + thread Models.MessageThread + i int + err error ) + threadPemBlock, threadMode = generateAesKey() + messageThread, err = seedMessageThread(threadPemBlock, threadMode) + primaryUserThreadKey = Util.RandomString(32) + secondaryUserThreadKey = Util.RandomString(32) + primaryUser, err = Database.GetUserByUsername("testUser") if err != nil { panic(err) } + _, err = seedMessageThreadUser( + primaryUser, + messageThread.ID, + primaryUserThreadKey, + threadPemBlock, + threadMode, + ) + secondaryUser, err = Database.GetUserByUsername("testUser2") if err != nil { panic(err) } - threadID, err = uuid.NewV4() - if err != nil { - panic(err) + _, err = seedMessageThreadUser( + secondaryUser, + messageThread.ID, + secondaryUserThreadKey, + threadPemBlock, + threadMode, + ) + + userJson = fmt.Sprintf( + ` +[ + { + "id": "%s", + "username": "%s", + "admin": "true" + }, + { + "id": "%s", + "username": "%s", + "admin": "true" } +] + `, + primaryUser.ID.String(), + primaryUser.Username, + secondaryUser.ID.String(), + secondaryUser.Username, + ) + + messageThread, err = seedUpdateMessageThreadUsers( + userJson, + threadPemBlock, + threadMode, + messageThread, + ) for i = 0; i <= 20; i++ { - err = seedMessage(primaryUser, secondaryUser, threadID, i) + err = seedMessage( + primaryUser, + primaryUserThreadKey, + secondaryUserThreadKey, + thread, + i, + ) if err != nil { panic(err) } diff --git a/Backend/Database/Seeder/Seed.go b/Backend/Database/Seeder/Seed.go index e1d2531..07b7248 100644 --- a/Backend/Database/Seeder/Seed.go +++ b/Backend/Database/Seeder/Seed.go @@ -31,7 +31,6 @@ func Seed() { err error ) - // TODO: Fix this parsing block, _ = pem.Decode([]byte(publicKey)) decKey, err = x509.ParsePKIXPublicKey(block.Bytes) if err != nil { diff --git a/Backend/Models/Friends.go b/Backend/Models/Friends.go index b56b8ab..b76d530 100644 --- a/Backend/Models/Friends.go +++ b/Backend/Models/Friends.go @@ -12,7 +12,5 @@ type Friend struct { UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` User User `json:"user"` FriendID []byte `gorm:"not null" json:"friend_id"` // Stored encrypted - ThreadID uuid.UUID `gorm:"type:uuid;column:thread_id;not null;" json:"thread_id"` - Thread []Message `gorm:"foreignKey:thread_id" json:"-"` AcceptedAt time.Time `json:"accepted_at"` } diff --git a/Backend/Models/Messages.go b/Backend/Models/Messages.go index 35e903d..6e1893e 100644 --- a/Backend/Models/Messages.go +++ b/Backend/Models/Messages.go @@ -2,25 +2,32 @@ package Models import "github.com/gofrs/uuid" -const ( - MessageTypeSender = "sender" - MessageTypeReceiver = "reciever" -) - type MessageData struct { Base - Data []byte `gorm:"not null" json:"data"` // Stored encrypted + Data []byte `gorm:"not null" json:"data"` // Stored encrypted + SenderID []byte `gorm:"not null" json:"sender_id"` } -// TODO: Rename this to something better type Message struct { Base - ThreadID uuid.UUID `gorm:"not null" json:"thread_id"` - UserID uuid.UUID `json:"-"` - User User `json:"user"` MessageDataID uuid.UUID `json:"-"` MessageData MessageData `json:"message_data"` - MessageType string `gorm:"not null" json:"message_type"` // sender / reciever - RelationalUserId []byte `gorm:"not null" json:"relational_user_id"` // Stored encrypted. UserID for the user this message is in relation to - SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted + SymmetricKey []byte `gorm:"not null" json:"symmetric_key"` // Stored encrypted + MessageThreadKey string `gorm:"not null" json:"message_thread_key"` +} + +type MessageThread struct { + Base + Name []byte `gorm:"not null" json:"name"` + Users []byte `json:"users"` +} + +type MessageThreadUser struct { + Base + UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` + User User `json:"user"` + MessageThreadID []byte `gorm:"not null" json:"message_thread_link_id"` + MessageThreadKey []byte `gorm:"not null" json:"message_thread_key"` + Admin []byte `gorm:"not null" json:"admin"` // Bool if user is admin of thread, stored encrypted + SymmetricKey []byte `gorm:"not null" json:"symmetric_key"` // Stored encrypted } diff --git a/Backend/Util/Strings.go b/Backend/Util/Strings.go new file mode 100644 index 0000000..a2d5d0f --- /dev/null +++ b/Backend/Util/Strings.go @@ -0,0 +1,21 @@ +package Util + +import ( + "math/rand" +) + +var ( + letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") +) + +func RandomString(n int) string { + var ( + b []rune + i int + ) + b = make([]rune, n) + for i = range b { + b[i] = letterRunes[rand.Intn(len(letterRunes))] + } + return string(b) +} -- 2.17.1 From 5eb1aed5c4ede57ea1467c61420ce11acc9fac25 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Wed, 15 Jun 2022 19:34:04 +0930 Subject: [PATCH 06/24] WIP - Working encryption with seeder --- Backend/Api/Friends/EncryptedFriendsList.go | 1 - Backend/Api/Friends/FriendRequest.go | 7 +- Backend/Api/Friends/Friends.go | 37 + Backend/Api/Routes.go | 2 +- Backend/Database/Seeder/FriendSeeder.go | 5 +- Backend/Database/Seeder/MessageSeeder.go | 4 +- Backend/Database/Seeder/Seed.go | 70 +- Backend/Models/Friends.go | 2 +- mobile/lib/models/friends.dart | 49 +- mobile/lib/utils/encryption/crypto_utils.dart | 979 ++++++++++++++++++ .../lib/utils/encryption/rsa_key_helper.dart | 29 +- mobile/lib/utils/encryption/string_utils.dart | 463 +++++++++ mobile/lib/utils/storage/database.dart | 35 + mobile/lib/utils/storage/encryption_keys.dart | 6 +- mobile/lib/utils/storage/friends.dart | 38 + mobile/lib/utils/storage/session_cookie.dart | 23 + mobile/lib/views/authentication/login.dart | 34 +- mobile/lib/views/authentication/signup.dart | 21 +- mobile/lib/views/main/friend_list.dart | 18 +- mobile/pubspec.lock | 23 +- mobile/pubspec.yaml | 3 +- 21 files changed, 1776 insertions(+), 73 deletions(-) create mode 100644 mobile/lib/utils/encryption/crypto_utils.dart create mode 100644 mobile/lib/utils/encryption/string_utils.dart create mode 100644 mobile/lib/utils/storage/database.dart create mode 100644 mobile/lib/utils/storage/friends.dart create mode 100644 mobile/lib/utils/storage/session_cookie.dart diff --git a/Backend/Api/Friends/EncryptedFriendsList.go b/Backend/Api/Friends/EncryptedFriendsList.go index 5179c9a..2db0531 100644 --- a/Backend/Api/Friends/EncryptedFriendsList.go +++ b/Backend/Api/Friends/EncryptedFriendsList.go @@ -18,7 +18,6 @@ func EncryptedFriendList(w http.ResponseWriter, r *http.Request) { ) userSession, err = Auth.CheckCookie(r) - if err != nil { http.Error(w, "Forbidden", http.StatusUnauthorized) return diff --git a/Backend/Api/Friends/FriendRequest.go b/Backend/Api/Friends/FriendRequest.go index 078bdcb..4943f17 100644 --- a/Backend/Api/Friends/FriendRequest.go +++ b/Backend/Api/Friends/FriendRequest.go @@ -15,8 +15,9 @@ func FriendRequest(w http.ResponseWriter, r *http.Request) { user Models.User requestBody []byte requestJson map[string]interface{} - friendID []byte + friendID string friendRequest Models.Friend + ok bool err error ) @@ -38,8 +39,8 @@ func FriendRequest(w http.ResponseWriter, r *http.Request) { return } - friendID, err = Util.ToBytes(requestJson["id"]) - if requestJson["id"] == nil { + friendID, ok = requestJson["id"].(string) + if !ok { http.Error(w, "Error", http.StatusInternalServerError) return } diff --git a/Backend/Api/Friends/Friends.go b/Backend/Api/Friends/Friends.go index 0706e14..a991fb6 100644 --- a/Backend/Api/Friends/Friends.go +++ b/Backend/Api/Friends/Friends.go @@ -2,8 +2,10 @@ package Friends import ( "encoding/json" + "io/ioutil" "net/http" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Util" ) @@ -30,3 +32,38 @@ func Friend(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write(returnJson) } + +func CreateFriendRequest(w http.ResponseWriter, r *http.Request) { + var ( + friendData Models.Friend + requestBody []byte + returnJson []byte + err error + ) + + requestBody, err = ioutil.ReadAll(r.Body) + if err != nil { + panic(err) + } + + err = json.Unmarshal(requestBody, &friendData) + if err != nil { + panic(err) + } + + err = Database.CreateFriendRequest(&friendData) + if err != nil { + panic(err) + } + + returnJson, err = json.MarshalIndent(friendData, "", " ") + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + // Return updated json + w.WriteHeader(http.StatusOK) + w.Write(returnJson) +} diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index adc2f4a..a362154 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -31,7 +31,6 @@ func authenticationMiddleware(next http.Handler) http.Handler { ) _, err = Auth.CheckCookie(r) - if err != nil { http.Error(w, "Forbidden", http.StatusUnauthorized) return @@ -61,6 +60,7 @@ func InitApiEndpoints(router *mux.Router) { authApi.Use(authenticationMiddleware) // Define routes for friends and friend requests + authApi.HandleFunc("/friend", Friends.CreateFriendRequest).Methods("POST") authApi.HandleFunc("/friends", Friends.EncryptedFriendList).Methods("GET") authApi.HandleFunc("/friend/{userID}", Friends.Friend).Methods("GET") authApi.HandleFunc("/friend/{userID}/request", Friends.FriendRequest).Methods("POST") diff --git a/Backend/Database/Seeder/FriendSeeder.go b/Backend/Database/Seeder/FriendSeeder.go index 771dcad..bcacf9d 100644 --- a/Backend/Database/Seeder/FriendSeeder.go +++ b/Backend/Database/Seeder/FriendSeeder.go @@ -1,6 +1,7 @@ package Seeder import ( + "encoding/base64" "time" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" @@ -15,7 +16,7 @@ func seedFriend(user, friendUser Models.User) error { friend = Models.Friend{ UserID: user.ID, - FriendID: encryptWithPublicKey(friendUser.ID.Bytes(), decodedPublicKey), + FriendID: base64.StdEncoding.EncodeToString(encryptWithPublicKey([]byte(friendUser.ID.String()), decodedPublicKey)), AcceptedAt: time.Now(), } @@ -26,7 +27,7 @@ func seedFriend(user, friendUser Models.User) error { friend = Models.Friend{ UserID: friendUser.ID, - FriendID: encryptWithPublicKey(user.ID.Bytes(), decodedPublicKey), + FriendID: base64.StdEncoding.EncodeToString(encryptWithPublicKey([]byte(user.ID.String()), decodedPublicKey)), AcceptedAt: time.Now(), } diff --git a/Backend/Database/Seeder/MessageSeeder.go b/Backend/Database/Seeder/MessageSeeder.go index 6a7504d..29de572 100644 --- a/Backend/Database/Seeder/MessageSeeder.go +++ b/Backend/Database/Seeder/MessageSeeder.go @@ -6,7 +6,7 @@ import ( "crypto/cipher" "crypto/rand" "crypto/rsa" - "crypto/sha512" + "crypto/sha256" "encoding/pem" "fmt" "hash" @@ -23,7 +23,7 @@ func encryptWithPublicKey(msg []byte, pub *rsa.PublicKey) []byte { hash hash.Hash ) - hash = sha512.New() + hash = sha256.New() ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pub, msg, nil) if err != nil { panic(err) diff --git a/Backend/Database/Seeder/Seed.go b/Backend/Database/Seeder/Seed.go index 07b7248..28825f4 100644 --- a/Backend/Database/Seeder/Seed.go +++ b/Backend/Database/Seeder/Seed.go @@ -1,33 +1,80 @@ package Seeder import ( + "crypto/rand" "crypto/rsa" + "crypto/sha256" "crypto/x509" "encoding/pem" + "errors" "log" ) const ( // Encrypted with "password" - encryptedPrivateKey string = ` -sPhQsHpXYFqPb7qdmTY7APFwBb4m7meCITujDeKMQFnz2F4v8Ovq5fH98j36v9Ayqcf/p/SyRnzP+NAEZI3fZ9iQKrHhioZ13C+Qx3Uz8Z6h44laJatagb7WOIPJSf28tNGZ38vLb0CU5fOOXuTZn4PJIkMprc8sS9eynZoCAvlUqvQTz6pOiguLcKjlwpZN2AAclnBS58j3XmYPK+Vcl1Lidq2sQLnBuwjbLvXxpVIWdw3TcQebVVIdZUZfoTF50tWozjUiuyW7SfVwQ2dwtF6N6yCvEh40zlwjKMv8LW/JNdoPLear7MVe3ngRd7Rw6n8u8/v/yXqe+gCR0WTv9XJp1FYhttO2KRmFWgNXNog+DTa7iKA+S0nFv0O8AI7+XIdRzxXAoDEN/6gR5XKwqwgwYl2hW4f59c/vLU4fWtqvZE2g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LniT0yD1/gkqAG2HpwaXEcSqX8Ofrbpd/IA7R7iCXYE5Q1mAvSvICpPg9Cf3CHjLyAEDz9cwKnZHkocXC8evdsTf2e7Wz8FFPAI3onFvym0MfZuRrIZitX1V8NOLedd3y74CwuErfzrr60DjyPRxGbJ4llMbm+ojeENe0HBedNm71jf+McSihKbSo5GDBxfVYVreYZ8A4iP0LsxtzQFxuzdeDL5KA9uNNw+LN9FN9vKhdALhQSnSfLPfMBsM/ey7dbxb4eRT0fpApX` + + // Private key for testing server side + privateKey string = `-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJScQQJxWxKwqf +FmXH64QnRBVyW7cU25F+O9Zy96dqTjbV4ruWrzb4+txmK20ZPQvMxDLefhEzTXWb +HZV1P/XxgmEpaBVHwHnkhaPzzChOa/G18CDoCNrgyVzh5a31OotTCuGlS1bSkR53 +ExPXQq8nPJKqN1tdwAslr4cT61zypKSmZsJa919IZeHL9p1/UMXknfThcR9z3rR4 +ll6O7+dmrZzaDdJz39IC38K5yJsThau5hnddpssw76k4rZ9KFFlbWJSHFvWIAhst +lCV0kCwdAmPNVNavzQfvTxWeN1x9uJUstVlg60DRCmRhjC88K77sU+1jp4cp/Uv8 +aSGRpytlAgMBAAECggEBALFbJr8YwRs/EnfEU2AI24OBkOgXecSOBq9UaAsavU+E +pPpmceU+c1CEMUhwwQs457m/shaqu9sZSCOpuHP8LGdk+tlyFTYImR5KxoBdBbK7 +l9k4QLZSfxELO6TrLBDkSbic4N8098ZHCbHfhF7qKcyHqa8DYaTEPs4wz/M0Mcy0 +xziCxMUFh/LhSLDH8PMMXZ+HV3+zmxdEqmaZvk3FQOGD1O39I9TA8PnFa11whVbN +nMSjxgmK+byPIM4LFXNHk+TZsJm1FaYaGVdLetAPET7p6XMrMWy+z/4dcb4GbYjY +0i5Xv1lVlIRgDB9xj0MOW5hzQzTPHC4JN4nIoBFSc20CgYEA5IgymckwqKJJWXRn +AIJ3guuEp4vBtjmdVCJnFmbPEeW+WY+CNuwn9DK78Zavfn1HruryE/hkYLVNPm8y +KSf16+tIadUXcao1UIVDNSVC6jtFmRLgWuPXbNKFQwUor1ai9IK+F3JV8pfr36HE +8rk/LEM0DIgsTg+j+IKT39a7IucCgYEA4XtKGhvnGUdcveMPcrvuQlSnucSpw5Ly +4KuRsTySdMihhxX1GSyg6F2T4YKFRqKZERsYgYk6A32u53If+VkXacvOsInwuoBa +FTb3fOQpw1xBSI7R3RgiriY4cCsDetexEBbg7/SrodpQu254A8+5PKxrSR1U+idx +boX745k1gdMCgYEAuZ7CctTOV/pQ137LdseBqO4BNlE2yvrrBf5XewOQZzoTLQ16 +N4ADR765lxXMf1HkmnesnnnflglMr0yEEpepkLDvhT6WpzUXzsoe95jHTBdOhXGm +l0x+mp43rWMQU7Jr82wKWGL+2md5J5ButrOuUxZWvWMRkWn0xhHRaDsyjrsCgYAq +zNRMEG/VhI4+HROZm8KmJJuRz5rJ3OLtcqO9GNpUAKFomupjVO1WLi0b6UKTHdog +PRxxujKg5wKEPE2FbzvagS1CpWxkemifDkf8FPM4ehKKS1HavfIXTHn6ELAgaUDa +5Pzdj3vkxSP98AIn9w4aTkAvKLowobwOVrBxi2t0sQKBgHh2TrGSnlV3s1DijfNM +0JiwsHWz0hljybcZaZP45nsgGRiR15TcIiOLwkjaCws2tYtOSOT4sM7HV/s2mpPa +b0XvaLzh1iKG7HZ9tvPt/VhHlKKosNBK/j4fvgMZg7/bhRfHmaDQKoqlGbtyWjEQ +mj1b2/Gnbk3VYDR16BFfj7m2 +-----END PRIVATE KEY-----` + + publicKey string = `-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyUnEECcVsSsKnxZlx+uE +J0QVclu3FNuRfjvWcvenak421eK7lq82+PrcZittGT0LzMQy3n4RM011mx2VdT/1 +8YJhKWgVR8B55IWj88woTmvxtfAg6Aja4Mlc4eWt9TqLUwrhpUtW0pEedxMT10Kv +JzySqjdbXcALJa+HE+tc8qSkpmbCWvdfSGXhy/adf1DF5J304XEfc960eJZeju/n +Zq2c2g3Sc9/SAt/CucibE4WruYZ3XabLMO+pOK2fShRZW1iUhxb1iAIbLZQldJAs +HQJjzVTWr80H708VnjdcfbiVLLVZYOtA0QpkYYwvPCu+7FPtY6eHKf1L/Gkhkacr +ZQIDAQAB +-----END PUBLIC KEY-----` ) var ( decodedPublicKey *rsa.PublicKey + // decodedPrivateKey *rsa.PrivateKey ) +// DecryptWithPrivateKey decrypts data with private key +func decryptWithPrivateKey(ciphertext []byte, priv *rsa.PrivateKey) []byte { + hash := sha256.New() + plaintext, err := rsa.DecryptOAEP(hash, rand.Reader, priv, ciphertext, nil) + if err != nil { + panic(err) + } + return plaintext +} + func Seed() { var ( block *pem.Block decKey any + ok bool err error ) @@ -36,7 +83,10 @@ func Seed() { if err != nil { panic(err) } - decodedPublicKey = decKey.(*rsa.PublicKey) + decodedPublicKey, ok = decKey.(*rsa.PublicKey) + if !ok { + panic(errors.New("Invalid decodedPublicKey")) + } log.Println("Seeding users...") SeedUsers() diff --git a/Backend/Models/Friends.go b/Backend/Models/Friends.go index b76d530..b435223 100644 --- a/Backend/Models/Friends.go +++ b/Backend/Models/Friends.go @@ -11,6 +11,6 @@ type Friend struct { Base UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` User User `json:"user"` - FriendID []byte `gorm:"not null" json:"friend_id"` // Stored encrypted + FriendID string `gorm:"not null" json:"friend_id"` // Stored encrypted AcceptedAt time.Time `json:"accepted_at"` } diff --git a/mobile/lib/models/friends.dart b/mobile/lib/models/friends.dart index 832d637..8afdcb4 100644 --- a/mobile/lib/models/friends.dart +++ b/mobile/lib/models/friends.dart @@ -1,9 +1,54 @@ +import 'dart:convert'; +import "package:pointycastle/export.dart"; +import '/utils/encryption/crypto_utils.dart'; class Friend{ String id; - String username; + String userId; + String friendId; + String friendIdDecrypted; + String acceptedAt; Friend({ required this.id, - required this.username, + required this.userId, + required this.friendId, + required this.friendIdDecrypted, + required this.acceptedAt, }); + + factory Friend.fromJson(Map json, RSAPrivateKey privKey) { + var friendIdDecrypted = CryptoUtils.rsaDecrypt( + base64.decode(json['friend_id']), + privKey, + ); + + return Friend( + id: json['id'], + userId: json['user_id'], + friendId: json['friend_id'], + friendIdDecrypted: String.fromCharCodes(friendIdDecrypted), + acceptedAt: json['accepted_at'], + ); + } + + @override + String toString() { + return ''' +id: $id +userId: $userId, +friendId: $friendId, +friendIdDecrypted: $friendIdDecrypted, +accepted_at: $acceptedAt, +'''; + } + + Map toMap() { + return { + 'id': id, + 'user_id': userId, + 'friend_id': friendId, + 'friend_id_decrypted': friendIdDecrypted, + 'accepted_at': acceptedAt, + }; + } } diff --git a/mobile/lib/utils/encryption/crypto_utils.dart b/mobile/lib/utils/encryption/crypto_utils.dart new file mode 100644 index 0000000..d580eda --- /dev/null +++ b/mobile/lib/utils/encryption/crypto_utils.dart @@ -0,0 +1,979 @@ +import 'dart:convert'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:pointycastle/asn1/object_identifiers.dart'; +import 'package:pointycastle/export.dart'; +import 'package:pointycastle/pointycastle.dart'; +import 'package:pointycastle/src/utils.dart' as thing; +import 'package:pointycastle/ecc/ecc_fp.dart' as ecc_fp; + +import './string_utils.dart'; + +/// +/// Helper class for cryptographic operations +/// +class CryptoUtils { + static const BEGIN_PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----'; + static const END_PRIVATE_KEY = '-----END PRIVATE KEY-----'; + + static const BEGIN_PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----'; + static const END_PUBLIC_KEY = '-----END PUBLIC KEY-----'; + + static const BEGIN_EC_PRIVATE_KEY = '-----BEGIN EC PRIVATE KEY-----'; + static const END_EC_PRIVATE_KEY = '-----END EC PRIVATE KEY-----'; + + static const BEGIN_EC_PUBLIC_KEY = '-----BEGIN EC PUBLIC KEY-----'; + static const END_EC_PUBLIC_KEY = '-----END EC PUBLIC KEY-----'; + + static const BEGIN_RSA_PRIVATE_KEY = '-----BEGIN RSA PRIVATE KEY-----'; + static const END_RSA_PRIVATE_KEY = '-----END RSA PRIVATE KEY-----'; + + static const BEGIN_RSA_PUBLIC_KEY = '-----BEGIN RSA PUBLIC KEY-----'; + static const END_RSA_PUBLIC_KEY = '-----END RSA PUBLIC KEY-----'; + + /// + /// Converts the [RSAPublicKey.modulus] from the given [publicKey] to a [Uint8List]. + /// + static Uint8List rsaPublicKeyModulusToBytes(RSAPublicKey publicKey) => + thing.encodeBigInt(publicKey.modulus); + + /// + /// Converts the [RSAPublicKey.exponent] from the given [publicKey] to a [Uint8List]. + /// + static Uint8List rsaPublicKeyExponentToBytes(RSAPublicKey publicKey) => + thing.encodeBigInt(publicKey.exponent); + + /// + /// Converts the [RSAPrivateKey.modulus] from the given [privateKey] to a [Uint8List]. + /// + static Uint8List rsaPrivateKeyModulusToBytes(RSAPrivateKey privateKey) => + thing.encodeBigInt(privateKey.modulus); + + /// + /// Converts the [RSAPrivateKey.exponent] from the given [privateKey] to a [Uint8List]. + /// + static Uint8List rsaPrivateKeyExponentToBytes(RSAPrivateKey privateKey) => + thing.encodeBigInt(privateKey.exponent); + + /// + /// Get a SHA1 Thumbprint for the given [bytes]. + /// + @Deprecated('Use [getHash]') + static String getSha1ThumbprintFromBytes(Uint8List bytes) { + return getHash(bytes, algorithmName: 'SHA-1'); + } + + /// + /// Get a SHA256 Thumbprint for the given [bytes]. + /// + @Deprecated('Use [getHash]') + static String getSha256ThumbprintFromBytes(Uint8List bytes) { + return getHash(bytes, algorithmName: 'SHA-256'); + } + + /// + /// Get a MD5 Thumbprint for the given [bytes]. + /// + @Deprecated('Use [getHash]') + static String getMd5ThumbprintFromBytes(Uint8List bytes) { + return getHash(bytes, algorithmName: 'MD5'); + } + + /// + /// Get a hash for the given [bytes] using the given [algorithm] + /// + /// The default [algorithm] used is **SHA-256**. All supported algorihms are : + /// + /// * SHA-1 + /// * SHA-224 + /// * SHA-256 + /// * SHA-384 + /// * SHA-512 + /// * SHA-512/224 + /// * SHA-512/256 + /// * MD5 + /// + static String getHash(Uint8List bytes, {String algorithmName = 'SHA-256'}) { + var hash = getHashPlain(bytes, algorithmName: algorithmName); + + const hexDigits = '0123456789abcdef'; + var charCodes = Uint8List(hash.length * 2); + for (var i = 0, j = 0; i < hash.length; i++) { + var byte = hash[i]; + charCodes[j++] = hexDigits.codeUnitAt((byte >> 4) & 0xF); + charCodes[j++] = hexDigits.codeUnitAt(byte & 0xF); + } + + return String.fromCharCodes(charCodes).toUpperCase(); + } + + /// + /// Get a hash for the given [bytes] using the given [algorithm] + /// + /// The default [algorithm] used is **SHA-256**. All supported algorihms are : + /// + /// * SHA-1 + /// * SHA-224 + /// * SHA-256 + /// * SHA-384 + /// * SHA-512 + /// * SHA-512/224 + /// * SHA-512/256 + /// * MD5 + /// + static Uint8List getHashPlain(Uint8List bytes, + {String algorithmName = 'SHA-256'}) { + Uint8List hash; + switch (algorithmName) { + case 'SHA-1': + hash = Digest('SHA-1').process(bytes); + break; + case 'SHA-224': + hash = Digest('SHA-224').process(bytes); + break; + case 'SHA-256': + hash = Digest('SHA-256').process(bytes); + break; + case 'SHA-384': + hash = Digest('SHA-384').process(bytes); + break; + case 'SHA-512': + hash = Digest('SHA-512').process(bytes); + break; + case 'SHA-512/224': + hash = Digest('SHA-512/224').process(bytes); + break; + case 'SHA-512/256': + hash = Digest('SHA-512/256').process(bytes); + break; + case 'MD5': + hash = Digest('MD5').process(bytes); + break; + default: + throw ArgumentError('Hash not supported'); + } + + return hash; + } + + /// + /// Generates a RSA [AsymmetricKeyPair] with the given [keySize]. + /// The default value for the [keySize] is 2048 bits. + /// + /// The following keySize is supported: + /// * 1024 + /// * 2048 + /// * 4096 + /// * 8192 + /// + static AsymmetricKeyPair generateRSAKeyPair({int keySize = 2048}) { + var keyParams = + RSAKeyGeneratorParameters(BigInt.parse('65537'), keySize, 12); + + var secureRandom = _getSecureRandom(); + + var rngParams = ParametersWithRandom(keyParams, secureRandom); + var generator = RSAKeyGenerator(); + generator.init(rngParams); + + final pair = generator.generateKeyPair(); + + final myPublic = pair.publicKey as RSAPublicKey; + final myPrivate = pair.privateKey as RSAPrivateKey; + + return AsymmetricKeyPair(myPublic, myPrivate); + } + + /// + /// Generates a elliptic curve [AsymmetricKeyPair]. + /// + /// The default curve is **prime256v1** + /// + /// The following curves are supported: + /// + /// * brainpoolp160r1 + /// * brainpoolp160t1 + /// * brainpoolp192r1 + /// * brainpoolp192t1 + /// * brainpoolp224r1 + /// * brainpoolp224t1 + /// * brainpoolp256r1 + /// * brainpoolp256t1 + /// * brainpoolp320r1 + /// * brainpoolp320t1 + /// * brainpoolp384r1 + /// * brainpoolp384t1 + /// * brainpoolp512r1 + /// * brainpoolp512t1 + /// * GostR3410-2001-CryptoPro-A + /// * GostR3410-2001-CryptoPro-B + /// * GostR3410-2001-CryptoPro-C + /// * GostR3410-2001-CryptoPro-XchA + /// * GostR3410-2001-CryptoPro-XchB + /// * prime192v1 + /// * prime192v2 + /// * prime192v3 + /// * prime239v1 + /// * prime239v2 + /// * prime239v3 + /// * prime256v1 + /// * secp112r1 + /// * secp112r2 + /// * secp128r1 + /// * secp128r2 + /// * secp160k1 + /// * secp160r1 + /// * secp160r2 + /// * secp192k1 + /// * secp192r1 + /// * secp224k1 + /// * secp224r1 + /// * secp256k1 + /// * secp256r1 + /// * secp384r1 + /// * secp521r1 + /// + static AsymmetricKeyPair generateEcKeyPair({String curve = 'prime256v1'}) { + var ecDomainParameters = ECDomainParameters(curve); + var keyParams = ECKeyGeneratorParameters(ecDomainParameters); + + var secureRandom = _getSecureRandom(); + + var rngParams = ParametersWithRandom(keyParams, secureRandom); + var generator = ECKeyGenerator(); + generator.init(rngParams); + + return generator.generateKeyPair(); + } + + /// + /// Generates a secure [FortunaRandom] + /// + static SecureRandom _getSecureRandom() { + var secureRandom = FortunaRandom(); + var random = Random.secure(); + var seeds = []; + for (var i = 0; i < 32; i++) { + seeds.add(random.nextInt(255)); + } + secureRandom.seed(KeyParameter(Uint8List.fromList(seeds))); + return secureRandom; + } + + /// + /// Enode the given [publicKey] to PEM format using the PKCS#8 standard. + /// + static String encodeRSAPublicKeyToPem(RSAPublicKey publicKey) { + var algorithmSeq = ASN1Sequence(); + var paramsAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList([0x5, 0x0])); + algorithmSeq.add(ASN1ObjectIdentifier.fromName('rsaEncryption')); + algorithmSeq.add(paramsAsn1Obj); + + var publicKeySeq = ASN1Sequence(); + publicKeySeq.add(ASN1Integer(publicKey.modulus)); + publicKeySeq.add(ASN1Integer(publicKey.exponent)); + var publicKeySeqBitString = + ASN1BitString(stringValues: Uint8List.fromList(publicKeySeq.encode())); + + var topLevelSeq = ASN1Sequence(); + topLevelSeq.add(algorithmSeq); + topLevelSeq.add(publicKeySeqBitString); + var dataBase64 = base64.encode(topLevelSeq.encode()); + var chunks = StringUtils.chunk(dataBase64, 64); + + return '$BEGIN_PUBLIC_KEY\n${chunks.join('\n')}\n$END_PUBLIC_KEY'; + } + + /// + /// Enode the given [rsaPublicKey] to PEM format using the PKCS#1 standard. + /// + /// The ASN1 structure is decripted at . + /// + /// ``` + /// RSAPublicKey ::= SEQUENCE { + /// modulus INTEGER, -- n + /// publicExponent INTEGER -- e + /// } + /// ``` + /// + static String encodeRSAPublicKeyToPemPkcs1(RSAPublicKey rsaPublicKey) { + var topLevelSeq = ASN1Sequence(); + topLevelSeq.add(ASN1Integer(rsaPublicKey.modulus)); + topLevelSeq.add(ASN1Integer(rsaPublicKey.exponent)); + + var dataBase64 = base64.encode(topLevelSeq.encode()); + var chunks = StringUtils.chunk(dataBase64, 64); + + return '$BEGIN_RSA_PUBLIC_KEY\n${chunks.join('\n')}\n$END_RSA_PUBLIC_KEY'; + } + + /// + /// Enode the given [rsaPrivateKey] to PEM format using the PKCS#1 standard. + /// + /// The ASN1 structure is decripted at . + /// + /// ``` + /// RSAPrivateKey ::= SEQUENCE { + /// version Version, + /// modulus INTEGER, -- n + /// publicExponent INTEGER, -- e + /// privateExponent INTEGER, -- d + /// prime1 INTEGER, -- p + /// prime2 INTEGER, -- q + /// exponent1 INTEGER, -- d mod (p-1) + /// exponent2 INTEGER, -- d mod (q-1) + /// coefficient INTEGER, -- (inverse of q) mod p + /// otherPrimeInfos OtherPrimeInfos OPTIONAL + /// } + /// ``` + static String encodeRSAPrivateKeyToPemPkcs1(RSAPrivateKey rsaPrivateKey) { + var version = ASN1Integer(BigInt.from(0)); + var modulus = ASN1Integer(rsaPrivateKey.n); + var publicExponent = ASN1Integer(BigInt.parse('65537')); + var privateExponent = ASN1Integer(rsaPrivateKey.privateExponent); + + var p = ASN1Integer(rsaPrivateKey.p); + var q = ASN1Integer(rsaPrivateKey.q); + var dP = + rsaPrivateKey.privateExponent! % (rsaPrivateKey.p! - BigInt.from(1)); + var exp1 = ASN1Integer(dP); + var dQ = + rsaPrivateKey.privateExponent! % (rsaPrivateKey.q! - BigInt.from(1)); + var exp2 = ASN1Integer(dQ); + var iQ = rsaPrivateKey.q!.modInverse(rsaPrivateKey.p!); + var co = ASN1Integer(iQ); + + var topLevelSeq = ASN1Sequence(); + topLevelSeq.add(version); + topLevelSeq.add(modulus); + topLevelSeq.add(publicExponent); + topLevelSeq.add(privateExponent); + topLevelSeq.add(p); + topLevelSeq.add(q); + topLevelSeq.add(exp1); + topLevelSeq.add(exp2); + topLevelSeq.add(co); + var dataBase64 = base64.encode(topLevelSeq.encode()); + var chunks = StringUtils.chunk(dataBase64, 64); + return '$BEGIN_RSA_PRIVATE_KEY\n${chunks.join('\n')}\n$END_RSA_PRIVATE_KEY'; + } + + /// + /// Enode the given [rsaPrivateKey] to PEM format using the PKCS#8 standard. + /// + /// The ASN1 structure is decripted at . + /// ``` + /// PrivateKeyInfo ::= SEQUENCE { + /// version Version, + /// algorithm AlgorithmIdentifier, + /// PrivateKey BIT STRING + /// } + /// ``` + /// + static String encodeRSAPrivateKeyToPem(RSAPrivateKey rsaPrivateKey) { + var version = ASN1Integer(BigInt.from(0)); + + var algorithmSeq = ASN1Sequence(); + var algorithmAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList( + [0x6, 0x9, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0xd, 0x1, 0x1, 0x1])); + var paramsAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList([0x5, 0x0])); + algorithmSeq.add(algorithmAsn1Obj); + algorithmSeq.add(paramsAsn1Obj); + + var privateKeySeq = ASN1Sequence(); + var modulus = ASN1Integer(rsaPrivateKey.n); + var publicExponent = ASN1Integer(BigInt.parse('65537')); + var privateExponent = ASN1Integer(rsaPrivateKey.privateExponent); + var p = ASN1Integer(rsaPrivateKey.p); + var q = ASN1Integer(rsaPrivateKey.q); + var dP = + rsaPrivateKey.privateExponent! % (rsaPrivateKey.p! - BigInt.from(1)); + var exp1 = ASN1Integer(dP); + var dQ = + rsaPrivateKey.privateExponent! % (rsaPrivateKey.q! - BigInt.from(1)); + var exp2 = ASN1Integer(dQ); + var iQ = rsaPrivateKey.q!.modInverse(rsaPrivateKey.p!); + var co = ASN1Integer(iQ); + + privateKeySeq.add(version); + privateKeySeq.add(modulus); + privateKeySeq.add(publicExponent); + privateKeySeq.add(privateExponent); + privateKeySeq.add(p); + privateKeySeq.add(q); + privateKeySeq.add(exp1); + privateKeySeq.add(exp2); + privateKeySeq.add(co); + var publicKeySeqOctetString = + ASN1OctetString(octets: Uint8List.fromList(privateKeySeq.encode())); + + var topLevelSeq = ASN1Sequence(); + topLevelSeq.add(version); + topLevelSeq.add(algorithmSeq); + topLevelSeq.add(publicKeySeqOctetString); + var dataBase64 = base64.encode(topLevelSeq.encode()); + var chunks = StringUtils.chunk(dataBase64, 64); + return '$BEGIN_PRIVATE_KEY\n${chunks.join('\n')}\n$END_PRIVATE_KEY'; + } + + /// + /// Decode a [RSAPrivateKey] from the given [pem] String. + /// + static RSAPrivateKey rsaPrivateKeyFromPem(String pem) { + var bytes = getBytesFromPEMString(pem); + return rsaPrivateKeyFromDERBytes(bytes); + } + + /// + /// Decode the given [bytes] into an [RSAPrivateKey]. + /// + static RSAPrivateKey rsaPrivateKeyFromDERBytes(Uint8List bytes) { + var asn1Parser = ASN1Parser(bytes); + var topLevelSeq = asn1Parser.nextObject() as ASN1Sequence; + //ASN1Object version = topLevelSeq.elements[0]; + //ASN1Object algorithm = topLevelSeq.elements[1]; + var privateKey = topLevelSeq.elements![2]; + + asn1Parser = ASN1Parser(privateKey.valueBytes); + var pkSeq = asn1Parser.nextObject() as ASN1Sequence; + + var modulus = pkSeq.elements![1] as ASN1Integer; + //ASN1Integer publicExponent = pkSeq.elements[2] as ASN1Integer; + var privateExponent = pkSeq.elements![3] as ASN1Integer; + var p = pkSeq.elements![4] as ASN1Integer; + var q = pkSeq.elements![5] as ASN1Integer; + //ASN1Integer exp1 = pkSeq.elements[6] as ASN1Integer; + //ASN1Integer exp2 = pkSeq.elements[7] as ASN1Integer; + //ASN1Integer co = pkSeq.elements[8] as ASN1Integer; + + var rsaPrivateKey = RSAPrivateKey( + modulus.integer!, privateExponent.integer!, p.integer, q.integer); + + return rsaPrivateKey; + } + + /// + /// Decode a [RSAPrivateKey] from the given [pem] string formated in the pkcs1 standard. + /// + static RSAPrivateKey rsaPrivateKeyFromPemPkcs1(String pem) { + var bytes = getBytesFromPEMString(pem); + return rsaPrivateKeyFromDERBytesPkcs1(bytes); + } + + /// + /// Decode the given [bytes] into an [RSAPrivateKey]. + /// + /// The [bytes] need to follow the the pkcs1 standard + /// + static RSAPrivateKey rsaPrivateKeyFromDERBytesPkcs1(Uint8List bytes) { + var asn1Parser = ASN1Parser(bytes); + var pkSeq = asn1Parser.nextObject() as ASN1Sequence; + + var modulus = pkSeq.elements![1] as ASN1Integer; + //ASN1Integer publicExponent = pkSeq.elements[2] as ASN1Integer; + var privateExponent = pkSeq.elements![3] as ASN1Integer; + var p = pkSeq.elements![4] as ASN1Integer; + var q = pkSeq.elements![5] as ASN1Integer; + //ASN1Integer exp1 = pkSeq.elements[6] as ASN1Integer; + //ASN1Integer exp2 = pkSeq.elements[7] as ASN1Integer; + //ASN1Integer co = pkSeq.elements[8] as ASN1Integer; + + var rsaPrivateKey = RSAPrivateKey( + modulus.integer!, privateExponent.integer!, p.integer, q.integer); + + return rsaPrivateKey; + } + + /// + /// Helper function for decoding the base64 in [pem]. + /// + /// Throws an ArgumentError if the given [pem] is not sourounded by begin marker -----BEGIN and + /// endmarker -----END or the [pem] consists of less than two lines. + /// + /// The PEM header check can be skipped by setting the optional paramter [checkHeader] to false. + /// + static Uint8List getBytesFromPEMString(String pem, + {bool checkHeader = true}) { + var lines = LineSplitter.split(pem) + .map((line) => line.trim()) + .where((line) => line.isNotEmpty) + .toList(); + var base64; + if (checkHeader) { + if (lines.length < 2 || + !lines.first.startsWith('-----BEGIN') || + !lines.last.startsWith('-----END')) { + throw ArgumentError('The given string does not have the correct ' + 'begin/end markers expected in a PEM file.'); + } + base64 = lines.sublist(1, lines.length - 1).join(''); + } else { + base64 = lines.join(''); + } + + return Uint8List.fromList(base64Decode(base64)); + } + + /// + /// Decode a [RSAPublicKey] from the given [pem] String. + /// + static RSAPublicKey rsaPublicKeyFromPem(String pem) { + var bytes = CryptoUtils.getBytesFromPEMString(pem); + return rsaPublicKeyFromDERBytes(bytes); + } + + /// + /// Decode the given [bytes] into an [RSAPublicKey]. + /// + static RSAPublicKey rsaPublicKeyFromDERBytes(Uint8List bytes) { + var asn1Parser = ASN1Parser(bytes); + var topLevelSeq = asn1Parser.nextObject() as ASN1Sequence; + var publicKeySeq; + if (topLevelSeq.elements![1].runtimeType == ASN1BitString) { + var publicKeyBitString = topLevelSeq.elements![1] as ASN1BitString; + + var publicKeyAsn = + ASN1Parser(publicKeyBitString.stringValues as Uint8List?); + publicKeySeq = publicKeyAsn.nextObject() as ASN1Sequence; + } else { + publicKeySeq = topLevelSeq; + } + var modulus = publicKeySeq.elements![0] as ASN1Integer; + var exponent = publicKeySeq.elements![1] as ASN1Integer; + + var rsaPublicKey = RSAPublicKey(modulus.integer!, exponent.integer!); + + return rsaPublicKey; + } + + /// + /// Decode a [RSAPublicKey] from the given [pem] string formated in the pkcs1 standard. + /// + static RSAPublicKey rsaPublicKeyFromPemPkcs1(String pem) { + var bytes = CryptoUtils.getBytesFromPEMString(pem); + return rsaPublicKeyFromDERBytesPkcs1(bytes); + } + + /// + /// Decode the given [bytes] into an [RSAPublicKey]. + /// + /// The [bytes] need to follow the the pkcs1 standard + /// + static RSAPublicKey rsaPublicKeyFromDERBytesPkcs1(Uint8List bytes) { + var publicKeyAsn = ASN1Parser(bytes); + var publicKeySeq = publicKeyAsn.nextObject() as ASN1Sequence; + var modulus = publicKeySeq.elements![0] as ASN1Integer; + var exponent = publicKeySeq.elements![1] as ASN1Integer; + + var rsaPublicKey = RSAPublicKey(modulus.integer!, exponent.integer!); + return rsaPublicKey; + } + + /// + /// Enode the given elliptic curve [publicKey] to PEM format. + /// + /// This is descripted in + /// + /// ```ASN1 + /// ECPrivateKey ::= SEQUENCE { + /// version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), + /// privateKey OCTET STRING + /// parameters [0] ECParameters {{ NamedCurve }} OPTIONAL + /// publicKey [1] BIT STRING OPTIONAL + /// } + /// + /// ``` + /// + /// As descripted in the mentioned RFC, all optional values will always be set. + /// + static String encodeEcPrivateKeyToPem(ECPrivateKey ecPrivateKey) { + var outer = ASN1Sequence(); + + var version = ASN1Integer(BigInt.from(1)); + var privateKeyAsBytes = thing.encodeBigInt(ecPrivateKey.d); + var privateKey = ASN1OctetString(octets: privateKeyAsBytes); + var choice = ASN1Sequence(tag: 0xA0); + + choice.add( + ASN1ObjectIdentifier.fromName(ecPrivateKey.parameters!.domainName)); + + var publicKey = ASN1Sequence(tag: 0xA1); + + var subjectPublicKey = ASN1BitString( + stringValues: ecPrivateKey.parameters!.G.getEncoded(false)); + publicKey.add(subjectPublicKey); + + outer.add(version); + outer.add(privateKey); + outer.add(choice); + outer.add(publicKey); + var dataBase64 = base64.encode(outer.encode()); + var chunks = StringUtils.chunk(dataBase64, 64); + + return '$BEGIN_EC_PRIVATE_KEY\n${chunks.join('\n')}\n$END_EC_PRIVATE_KEY'; + } + + /// + /// Enode the given elliptic curve [publicKey] to PEM format. + /// + /// This is descripted in + /// + /// ```ASN1 + /// SubjectPublicKeyInfo ::= SEQUENCE { + /// algorithm AlgorithmIdentifier, + /// subjectPublicKey BIT STRING + /// } + /// ``` + /// + static String encodeEcPublicKeyToPem(ECPublicKey publicKey) { + var outer = ASN1Sequence(); + var algorithm = ASN1Sequence(); + algorithm.add(ASN1ObjectIdentifier.fromName('ecPublicKey')); + algorithm.add(ASN1ObjectIdentifier.fromName('prime256v1')); + var encodedBytes = publicKey.Q!.getEncoded(false); + + var subjectPublicKey = ASN1BitString(stringValues: encodedBytes); + + outer.add(algorithm); + outer.add(subjectPublicKey); + var dataBase64 = base64.encode(outer.encode()); + var chunks = StringUtils.chunk(dataBase64, 64); + + return '$BEGIN_EC_PUBLIC_KEY\n${chunks.join('\n')}\n$END_EC_PUBLIC_KEY'; + } + + /// + /// Decode a [ECPublicKey] from the given [pem] String. + /// + /// Throws an ArgumentError if the given string [pem] is null or empty. + /// + static ECPublicKey ecPublicKeyFromPem(String pem) { + if (pem.isEmpty) { + throw ArgumentError('Argument must not be null.'); + } + var bytes = CryptoUtils.getBytesFromPEMString(pem); + return ecPublicKeyFromDerBytes(bytes); + } + + /// + /// Decode a [ECPrivateKey] from the given [pem] String. + /// + /// Throws an ArgumentError if the given string [pem] is null or empty. + /// + static ECPrivateKey ecPrivateKeyFromPem(String pem) { + if (pem.isEmpty) { + throw ArgumentError('Argument must not be null.'); + } + var bytes = CryptoUtils.getBytesFromPEMString(pem); + return ecPrivateKeyFromDerBytes( + bytes, + pkcs8: pem.startsWith(BEGIN_PRIVATE_KEY), + ); + } + + /// + /// Decode the given [bytes] into an [ECPrivateKey]. + /// + /// [pkcs8] defines the ASN1 format of the given [bytes]. The default is false, so SEC1 is assumed. + /// + /// Supports SEC1 () and PKCS8 () + /// + static ECPrivateKey ecPrivateKeyFromDerBytes(Uint8List bytes, + {bool pkcs8 = false}) { + var asn1Parser = ASN1Parser(bytes); + var topLevelSeq = asn1Parser.nextObject() as ASN1Sequence; + var curveName; + var x; + if (pkcs8) { + // Parse the PKCS8 format + var innerSeq = topLevelSeq.elements!.elementAt(1) as ASN1Sequence; + var b2 = innerSeq.elements!.elementAt(1) as ASN1ObjectIdentifier; + var b2Data = b2.objectIdentifierAsString; + var b2Curvedata = ObjectIdentifiers.getIdentifierByIdentifier(b2Data); + if (b2Curvedata != null) { + curveName = b2Curvedata['readableName']; + } + + var octetString = topLevelSeq.elements!.elementAt(2) as ASN1OctetString; + asn1Parser = ASN1Parser(octetString.valueBytes); + var octetStringSeq = asn1Parser.nextObject() as ASN1Sequence; + var octetStringKeyData = + octetStringSeq.elements!.elementAt(1) as ASN1OctetString; + + x = octetStringKeyData.valueBytes!; + } else { + // Parse the SEC1 format + var privateKeyAsOctetString = + topLevelSeq.elements!.elementAt(1) as ASN1OctetString; + var choice = topLevelSeq.elements!.elementAt(2); + var s = ASN1Sequence(); + var parser = ASN1Parser(choice.valueBytes); + while (parser.hasNext()) { + s.add(parser.nextObject()); + } + var curveNameOi = s.elements!.elementAt(0) as ASN1ObjectIdentifier; + var data = ObjectIdentifiers.getIdentifierByIdentifier( + curveNameOi.objectIdentifierAsString); + if (data != null) { + curveName = data['readableName']; + } + + x = privateKeyAsOctetString.valueBytes!; + } + + return ECPrivateKey(thing.decodeBigInt(x), ECDomainParameters(curveName)); + } + + /// + /// Decode the given [bytes] into an [ECPublicKey]. + /// + static ECPublicKey ecPublicKeyFromDerBytes(Uint8List bytes) { + if (bytes.elementAt(0) == 0) { + bytes = bytes.sublist(1); + } + var asn1Parser = ASN1Parser(bytes); + var topLevelSeq = asn1Parser.nextObject() as ASN1Sequence; + + var algorithmIdentifierSequence = topLevelSeq.elements![0] as ASN1Sequence; + var curveNameOi = algorithmIdentifierSequence.elements!.elementAt(1) + as ASN1ObjectIdentifier; + var curveName; + var data = ObjectIdentifiers.getIdentifierByIdentifier( + curveNameOi.objectIdentifierAsString); + if (data != null) { + curveName = data['readableName']; + } + + var subjectPublicKey = topLevelSeq.elements![1] as ASN1BitString; + var compressed = false; + var pubBytes = subjectPublicKey.valueBytes!; + if (pubBytes.elementAt(0) == 0) { + pubBytes = pubBytes.sublist(1); + } + + // Looks good so far! + var firstByte = pubBytes.elementAt(0); + if (firstByte != 4) { + compressed = true; + } + var x = pubBytes.sublist(1, (pubBytes.length / 2).round()); + var y = pubBytes.sublist(1 + x.length, pubBytes.length); + var params = ECDomainParameters(curveName); + var bigX = thing.decodeBigIntWithSign(1, x); + var bigY = thing.decodeBigIntWithSign(1, y); + var pubKey = ECPublicKey( + ecc_fp.ECPoint( + params.curve as ecc_fp.ECCurve, + params.curve.fromBigInteger(bigX) as ecc_fp.ECFieldElement?, + params.curve.fromBigInteger(bigY) as ecc_fp.ECFieldElement?, + compressed), + params); + return pubKey; + } + + /// + /// Encrypt the given [message] using the given RSA [publicKey]. + /// + static Uint8List rsaEncrypt(Uint8List message, RSAPublicKey publicKey) { + var cipher = OAEPEncoding.withSHA256(RSAEngine()) + ..init(true, PublicKeyParameter(publicKey)); + + return _processInBlocks(cipher, message); + } + + /// + /// Decrypt the given [cipherMessage] using the given RSA [privateKey]. + /// + static Uint8List rsaDecrypt(Uint8List cipherMessage, RSAPrivateKey privateKey) { + var cipher = OAEPEncoding.withSHA256(RSAEngine()) + ..init(false, PrivateKeyParameter(privateKey)); + + return _processInBlocks(cipher, cipherMessage); + } + + static Uint8List _processInBlocks(AsymmetricBlockCipher engine, Uint8List input) { + final numBlocks = input.length ~/ engine.inputBlockSize + + ((input.length % engine.inputBlockSize != 0) ? 1 : 0); + + final output = Uint8List(numBlocks * engine.outputBlockSize); + + var inputOffset = 0; + var outputOffset = 0; + while (inputOffset < input.length) { + final chunkSize = (inputOffset + engine.inputBlockSize <= input.length) + ? engine.inputBlockSize + : input.length - inputOffset; + + outputOffset += engine.processBlock( + input, inputOffset, chunkSize, output, outputOffset); + + inputOffset += chunkSize; + } + + return (output.length == outputOffset) + ? output + : output.sublist(0, outputOffset); + } + + /// + /// Signing the given [dataToSign] with the given [privateKey]. + /// + /// The default [algorithm] used is **SHA-256/RSA**. All supported algorihms are : + /// + /// * MD2/RSA + /// * MD4/RSA + /// * MD5/RSA + /// * RIPEMD-128/RSA + /// * RIPEMD-160/RSA + /// * RIPEMD-256/RSA + /// * SHA-1/RSA + /// * SHA-224/RSA + /// * SHA-256/RSA + /// * SHA-384/RSA + /// * SHA-512/RSA + /// + static Uint8List rsaSign(RSAPrivateKey privateKey, Uint8List dataToSign, + {String algorithmName = 'SHA-256/RSA'}) { + var signer = Signer(algorithmName) as RSASigner; + + signer.init(true, PrivateKeyParameter(privateKey)); + + var sig = signer.generateSignature(dataToSign); + + return sig.bytes; + } + + /// + /// Verifying the given [signedData] with the given [publicKey] and the given [signature]. + /// Will return **true** if the given [signature] matches the [signedData]. + /// + /// The default [algorithm] used is **SHA-256/RSA**. All supported algorihms are : + /// + /// * MD2/RSA + /// * MD4/RSA + /// * MD5/RSA + /// * RIPEMD-128/RSA + /// * RIPEMD-160/RSA + /// * RIPEMD-256/RSA + /// * SHA-1/RSA + /// * SHA-224/RSA + /// * SHA-256/RSA + /// * SHA-384/RSA + /// * SHA-512/RSA + /// + static bool rsaVerify( + RSAPublicKey publicKey, Uint8List signedData, Uint8List signature, + {String algorithm = 'SHA-256/RSA'}) { + final sig = RSASignature(signature); + + final verifier = Signer(algorithm); + + verifier.init(false, PublicKeyParameter(publicKey)); + + try { + return verifier.verifySignature(signedData, sig); + } on ArgumentError { + return false; + } + } + + /// + /// Signing the given [dataToSign] with the given [privateKey]. + /// + /// The default [algorithm] used is **SHA-1/ECDSA**. All supported algorihms are : + /// + /// * SHA-1/ECDSA + /// * SHA-224/ECDSA + /// * SHA-256/ECDSA + /// * SHA-384/ECDSA + /// * SHA-512/ECDSA + /// * SHA-1/DET-ECDSA + /// * SHA-224/DET-ECDSA + /// * SHA-256/DET-ECDSA + /// * SHA-384/DET-ECDSA + /// * SHA-512/DET-ECDSA + /// + static ECSignature ecSign(ECPrivateKey privateKey, Uint8List dataToSign, + {String algorithmName = 'SHA-1/ECDSA'}) { + var signer = Signer(algorithmName) as ECDSASigner; + + var params = ParametersWithRandom( + PrivateKeyParameter(privateKey), _getSecureRandom()); + signer.init(true, params); + + var sig = signer.generateSignature(dataToSign) as ECSignature; + + return sig; + } + + /// + /// Verifying the given [signedData] with the given [publicKey] and the given [signature]. + /// Will return **true** if the given [signature] matches the [signedData]. + /// + /// The default [algorithm] used is **SHA-1/ECDSA**. All supported algorihms are : + /// + /// * SHA-1/ECDSA + /// * SHA-224/ECDSA + /// * SHA-256/ECDSA + /// * SHA-384/ECDSA + /// * SHA-512/ECDSA + /// * SHA-1/DET-ECDSA + /// * SHA-224/DET-ECDSA + /// * SHA-256/DET-ECDSA + /// * SHA-384/DET-ECDSA + /// * SHA-512/DET-ECDSA + /// + static bool ecVerify( + ECPublicKey publicKey, Uint8List signedData, ECSignature signature, + {String algorithm = 'SHA-1/ECDSA'}) { + final verifier = Signer(algorithm) as ECDSASigner; + + verifier.init(false, PublicKeyParameter(publicKey)); + + try { + return verifier.verifySignature(signedData, signature); + } on ArgumentError { + return false; + } + } + + /// + /// Returns the modulus of the given [pem] that represents an RSA private key. + /// + /// This equals the following openssl command: + /// ``` + /// openssl rsa -noout -modulus -in FILE.key + /// ``` + /// + static BigInt getModulusFromRSAPrivateKeyPem(String pem) { + RSAPrivateKey privateKey; + switch (_getPrivateKeyType(pem)) { + case 'RSA': + privateKey = rsaPrivateKeyFromPem(pem); + return privateKey.modulus!; + case 'RSA_PKCS1': + privateKey = rsaPrivateKeyFromPemPkcs1(pem); + return privateKey.modulus!; + case 'ECC': + throw ArgumentError('ECC private key not supported.'); + default: + privateKey = rsaPrivateKeyFromPem(pem); + return privateKey.modulus!; + } + } + + /// + /// Returns the private key type of the given [pem] + /// + static String _getPrivateKeyType(String pem) { + if (pem.startsWith(BEGIN_RSA_PRIVATE_KEY)) { + return 'RSA_PKCS1'; + } else if (pem.startsWith(BEGIN_PRIVATE_KEY)) { + return 'RSA'; + } else if (pem.startsWith(BEGIN_EC_PRIVATE_KEY)) { + return 'ECC'; + } + return 'RSA'; + } +} diff --git a/mobile/lib/utils/encryption/rsa_key_helper.dart b/mobile/lib/utils/encryption/rsa_key_helper.dart index 2d3510e..72e854b 100644 --- a/mobile/lib/utils/encryption/rsa_key_helper.dart +++ b/mobile/lib/utils/encryption/rsa_key_helper.dart @@ -1,7 +1,6 @@ import 'dart:convert'; import 'dart:math'; import 'dart:typed_data'; -import 'package:pointycastle/src/platform_check/platform_check.dart'; import "package:pointycastle/export.dart"; import "package:asn1lib/asn1lib.dart"; @@ -19,16 +18,18 @@ print(String.fromCharCodes(plainText)); List decodePEM(String pem) { var startsWith = [ - "-----BEGIN PUBLIC KEY-----", - "-----BEGIN PRIVATE KEY-----", - "-----BEGIN PGP PUBLIC KEY BLOCK-----\r\nVersion: React-Native-OpenPGP.js 0.1\r\nComment: http://openpgpjs.org\r\n\r\n", - "-----BEGIN PGP PRIVATE KEY BLOCK-----\r\nVersion: React-Native-OpenPGP.js 0.1\r\nComment: http://openpgpjs.org\r\n\r\n", + '-----BEGIN PUBLIC KEY-----', + '-----BEGIN PUBLIC KEY-----', + '\n-----BEGIN PUBLIC KEY-----', + '-----BEGIN PRIVATE KEY-----', + '-----BEGIN PGP PUBLIC KEY BLOCK-----\r\nVersion: React-Native-OpenPGP.js 0.1\r\nComment: http://openpgpjs.org\r\n\r\n', + '-----BEGIN PGP PRIVATE KEY BLOCK-----\r\nVersion: React-Native-OpenPGP.js 0.1\r\nComment: http://openpgpjs.org\r\n\r\n', ]; var endsWith = [ - "-----END PUBLIC KEY-----", - "-----END PRIVATE KEY-----", - "-----END PGP PUBLIC KEY BLOCK-----", - "-----END PGP PRIVATE KEY BLOCK-----", + '-----END PUBLIC KEY-----', + '-----END PRIVATE KEY-----', + '-----END PGP PUBLIC KEY BLOCK-----', + '-----END PGP PRIVATE KEY BLOCK-----', ]; bool isOpenPgp = pem.contains('BEGIN PGP'); @@ -183,10 +184,12 @@ class RsaKeyHelper { // Encode RSA private key to pem format static encodePrivateKeyToPem(RSAPrivateKey privateKey) { - var version = ASN1Integer(BigInt.from(0)); + var version = ASN1Integer(BigInt.zero); var algorithmSeq = ASN1Sequence(); - var algorithmAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList([0x6, 0x9, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0xd, 0x1, 0x1, 0x1])); + var algorithmAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList([ + 0x6, 0x9, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0xd, 0x1, 0x1, 0x1 + ])); var paramsAsn1Obj = ASN1Object.fromBytes(Uint8List.fromList([0x5, 0x0])); algorithmSeq.add(algorithmAsn1Obj); algorithmSeq.add(paramsAsn1Obj); @@ -197,9 +200,9 @@ class RsaKeyHelper { var privateExponent = ASN1Integer(privateKey.privateExponent!); var p = ASN1Integer(privateKey.p!); var q = ASN1Integer(privateKey.q!); - var dP = privateKey.privateExponent! % (privateKey.p! - BigInt.from(1)); + var dP = privateKey.privateExponent! % (privateKey.p! - BigInt.one); var exp1 = ASN1Integer(dP); - var dQ = privateKey.privateExponent! % (privateKey.q! - BigInt.from(1)); + var dQ = privateKey.privateExponent! % (privateKey.q! - BigInt.one); var exp2 = ASN1Integer(dQ); var iQ = privateKey.q?.modInverse(privateKey.p!); var co = ASN1Integer(iQ!); diff --git a/mobile/lib/utils/encryption/string_utils.dart b/mobile/lib/utils/encryption/string_utils.dart new file mode 100644 index 0000000..ca40eee --- /dev/null +++ b/mobile/lib/utils/encryption/string_utils.dart @@ -0,0 +1,463 @@ +import 'dart:convert'; +import 'dart:math'; + +/// +/// Helper class for String operations +/// +class StringUtils { + static AsciiCodec asciiCodec = AsciiCodec(); + + /// + /// Returns the given string or the default string if the given string is null + /// + static String defaultString(String? str, {String defaultStr = ''}) { + return str ?? defaultStr; + } + + /// + /// Checks if the given String [s] is null or empty + /// + static bool isNullOrEmpty(String? s) => + (s == null || s.isEmpty) ? true : false; + + /// + /// Checks if the given String [s] is not null or empty + /// + static bool isNotNullOrEmpty(String? s) => !isNullOrEmpty(s); + + /// + /// Transfers the given String [s] from camcelCase to upperCaseUnderscore + /// Example : helloWorld => HELLO_WORLD + /// + static String camelCaseToUpperUnderscore(String s) { + var sb = StringBuffer(); + var first = true; + s.runes.forEach((int rune) { + var char = String.fromCharCode(rune); + if (isUpperCase(char) && !first) { + sb.write('_'); + sb.write(char.toUpperCase()); + } else { + first = false; + sb.write(char.toUpperCase()); + } + }); + return sb.toString(); + } + + /// + /// Transfers the given String [s] from camcelCase to lowerCaseUnderscore + /// Example : helloWorld => hello_world + /// + static String camelCaseToLowerUnderscore(String s) { + var sb = StringBuffer(); + var first = true; + s.runes.forEach((int rune) { + var char = String.fromCharCode(rune); + if (isUpperCase(char) && !first) { + if (char != '_') { + sb.write('_'); + } + sb.write(char.toLowerCase()); + } else { + first = false; + sb.write(char.toLowerCase()); + } + }); + return sb.toString(); + } + + /// + /// Checks if the given string [s] is lower case + /// + static bool isLowerCase(String s) { + return s == s.toLowerCase(); + } + + /// + /// Checks if the given string [s] is upper case + /// + static bool isUpperCase(String s) { + return s == s.toUpperCase(); + } + + /// + /// Checks if the given string [s] contains only ascii chars + /// + static bool isAscii(String s) { + try { + asciiCodec.decode(s.codeUnits); + } catch (e) { + return false; + } + return true; + } + + /// + /// Capitalize the given string [s]. If [allWords] is set to true, it will capitalize all words within the given string [s]. + /// + /// The string [s] is there fore splitted by " " (space). + /// + /// Example : + /// + /// * [s] = "world" => World + /// * [s] = "WORLD" => World + /// * [s] = "the quick lazy fox" => The quick lazy fox + /// * [s] = "the quick lazy fox" and [allWords] = true => The Quick Lazy Fox + /// + static String capitalize(String s, {bool allWords = false}) { + if (s.isEmpty) { + return ''; + } + s = s.trim(); + if (allWords) { + var words = s.split(' '); + var capitalized = []; + for (var w in words) { + capitalized.add(capitalize(w)); + } + return capitalized.join(' '); + } else { + return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase(); + } + } + + /// + /// Reverse the given string [s] + /// Example : hello => olleh + /// + static String reverse(String s) { + return String.fromCharCodes(s.runes.toList().reversed); + } + + /// + /// Counts how offen the given [char] apears in the given string [s]. + /// The value [caseSensitive] controlls whether it should only look for the given [char] + /// or also the equivalent lower/upper case version. + /// Example: Hello and char l => 2 + /// + static int countChars(String s, String char, {bool caseSensitive = true}) { + var count = 0; + s.codeUnits.toList().forEach((i) { + if (caseSensitive) { + if (i == char.runes.first) { + count++; + } + } else { + if (i == char.toLowerCase().runes.first || + i == char.toUpperCase().runes.first) { + count++; + } + } + }); + return count; + } + + /// + /// Checks if the given string [s] is a digit. + /// + /// Will return false if the given string [s] is empty. + /// + static bool isDigit(String s) { + if (s.isEmpty) { + return false; + } + if (s.length > 1) { + for (var r in s.runes) { + if (r ^ 0x30 > 9) { + return false; + } + } + return true; + } else { + return s.runes.first ^ 0x30 <= 9; + } + } + + /// + /// Compares the given strings [a] and [b]. + /// + static bool equalsIgnoreCase(String a, String b) => + a.toLowerCase() == b.toLowerCase(); + + /// + /// Checks if the given [list] contains the string [s] + /// + static bool inList(String s, List list, {bool ignoreCase = false}) { + for (var l in list) { + if (ignoreCase) { + if (equalsIgnoreCase(s, l)) { + return true; + } + } else { + if (s == l) { + return true; + } + } + } + return false; + } + + /// + /// Checks if the given string [s] is a palindrome + /// Example : + /// aha => true + /// hello => false + /// + static bool isPalindrome(String s) { + for (var i = 0; i < s.length / 2; i++) { + if (s[i] != s[s.length - 1 - i]) return false; + } + return true; + } + + /// + /// Replaces chars of the given String [s] with [replace]. + /// + /// The default value of [replace] is *. + /// [begin] determines the start of the 'replacing'. If [begin] is null, it starts from index 0. + /// [end] defines the end of the 'replacing'. If [end] is null, it ends at [s] length divided by 2. + /// If [s] is empty or consists of only 1 char, the method returns null. + /// + /// Example : + /// 1234567890 => *****67890 + /// 1234567890 with begin 2 and end 6 => 12****7890 + /// 1234567890 with begin 1 => 1****67890 + /// + static String? hidePartial(String s, + {int begin = 0, int? end, String replace = '*'}) { + var buffer = StringBuffer(); + if (s.length <= 1) { + return null; + } + if (end == null) { + end = (s.length / 2).round(); + } else { + if (end > s.length) { + end = s.length; + } + } + for (var i = 0; i < s.length; i++) { + if (i >= end) { + buffer.write(String.fromCharCode(s.runes.elementAt(i))); + continue; + } + if (i >= begin) { + buffer.write(replace); + continue; + } + buffer.write(String.fromCharCode(s.runes.elementAt(i))); + } + return buffer.toString(); + } + + /// + /// Add a [char] at a [position] with the given String [s]. + /// + /// The boolean [repeat] defines whether to add the [char] at every [position]. + /// If [position] is greater than the length of [s], it will return [s]. + /// If [repeat] is true and [position] is 0, it will return [s]. + /// + /// Example : + /// 1234567890 , '-', 3 => 123-4567890 + /// 1234567890 , '-', 3, true => 123-456-789-0 + /// + static String addCharAtPosition(String s, String char, int position, + {bool repeat = false}) { + if (!repeat) { + if (s.length < position) { + return s; + } + var before = s.substring(0, position); + var after = s.substring(position, s.length); + return before + char + after; + } else { + if (position == 0) { + return s; + } + var buffer = StringBuffer(); + for (var i = 0; i < s.length; i++) { + if (i != 0 && i % position == 0) { + buffer.write(char); + } + buffer.write(String.fromCharCode(s.runes.elementAt(i))); + } + return buffer.toString(); + } + } + + /// + /// Splits the given String [s] in chunks with the given [chunkSize]. + /// + static List chunk(String s, int chunkSize) { + var chunked = []; + for (var i = 0; i < s.length; i += chunkSize) { + var end = (i + chunkSize < s.length) ? i + chunkSize : s.length; + chunked.add(s.substring(i, end)); + } + return chunked; + } + + /// + /// Picks only required string[value] starting [from] and ending at [to] + /// + /// Example : + /// pickOnly('123456789',from:3,to:7); + /// returns '34567' + /// + static String pickOnly(value, {int from = 1, int to = -1}) { + try { + return value.substring( + from == 0 ? 0 : from - 1, to == -1 ? value.length : to); + } catch (e) { + return value; + } + } + + /// + /// Removes character with [index] from a String [value] + /// + /// Example: + /// removeCharAtPosition('flutterr', 8); + /// returns 'flutter' + static String removeCharAtPosition(String value, int index) { + try { + return value.substring(0, -1 + index) + + value.substring(index, value.length); + } catch (e) { + return value; + } + } + + /// + ///Remove String[value] with [pattern] + /// + ///[repeat]:boolean => if(true) removes all occurence + /// + ///[casensitive]:boolean => if(true) a != A + /// + ///Example: removeExp('Hello This World', 'This'); returns 'Hello World' + /// + static String removeExp(String value, String pattern, + {bool repeat = true, + bool caseSensitive = true, + bool multiLine = false, + bool dotAll = false, + bool unicode = false}) { + var result = value; + if (repeat) { + result = value + .replaceAll( + RegExp(pattern, + caseSensitive: caseSensitive, + multiLine: multiLine, + dotAll: dotAll, + unicode: unicode), + '') + .replaceAll(RegExp(' +'), ' ') + .trim(); + } else { + result = value + .replaceFirst( + RegExp(pattern, + caseSensitive: caseSensitive, + multiLine: multiLine, + dotAll: dotAll, + unicode: unicode), + '') + .replaceAll(RegExp(' +'), ' ') + .trim(); + } + return result; + } + + /// + /// Takes in a String[value] and truncates it with [length] + /// [symbol] default is '...' + ///truncate('This is a Dart Utility Library', 26) + /// returns 'This is a Dart Utility Lib...' + static String truncate(String value, int length, {String symbol = '...'}) { + var result = value; + + try { + result = value.substring(0, length) + symbol; + } catch (e) { + print(e.toString()); + } + return result; + } + + ///Generates a Random string + /// + ///[length]: length of string, + /// + ///[alphabet]:(boolean) add alphabet to string[uppercase]ABCD and [lowercase]abcd, + /// + ///[numeric]:(boolean) add integers to string like 3622737 + /// + ///[special]:(boolean) add special characters like $#@&^ + /// + ///[from]:where you want to generate string from + /// + static String generateRandomString(int length, + {alphabet = true, + numeric = true, + special = true, + uppercase = true, + lowercase = true, + String from = ''}) { + var res = ''; + + do { + res += randomizer(alphabet, numeric, lowercase, uppercase, special, from); + } while (res.length < length); + + var possible = res.split(''); + possible.shuffle(); //all possible combinations shuffled + var result = []; + + for (var i = 0; i < length; i++) { + var randomNumber = Random().nextInt(length); + result.add(possible[randomNumber]); + } + + return result.join(); + } + + static String randomizer(bool alphabet, bool numeric, bool lowercase, + bool uppercase, bool special, String from) { + var a = 'ABCDEFGHIJKLMNOPQRXYZ'; + var la = 'abcdefghijklmnopqrxyz'; + var b = '0123456789'; + var c = '~^!@#\$%^&*;`(=?]:[.)_+-|\{}'; + var result = ''; + + if (alphabet) { + if (lowercase) { + result += la; + } + if (uppercase) { + result += a; + } + + if (!uppercase && !lowercase) { + result += a; + result += la; + } + } + if (numeric) { + result += b; + } + + if (special) { + result += c; + } + + if (from != '') { + //if set return it + result = from; + } + + return result; + } +} diff --git a/mobile/lib/utils/storage/database.dart b/mobile/lib/utils/storage/database.dart new file mode 100644 index 0000000..0b306c4 --- /dev/null +++ b/mobile/lib/utils/storage/database.dart @@ -0,0 +1,35 @@ +import 'dart:async'; +import 'package:flutter/widgets.dart'; +import 'package:path/path.dart'; +import 'package:sqflite/sqflite.dart'; + +Future getDatabaseConnection() async { + WidgetsFlutterBinding.ensureInitialized(); + + final database = openDatabase( + // Set the path to the database. Note: Using the `join` function from the + // `path` package is best practice to ensure the path is correctly + // constructed for each platform. + join(await getDatabasesPath(), 'envelope.db'), + // When the database is first created, create a table to store dogs. + onCreate: (db, version) { + // Run the CREATE TABLE statement on the database. + return db.execute( + ''' + CREATE TABLE IF NOT EXISTS friends( + id BLOB PRIMARY KEY, + user_id BLOB, + friend_id BLOB, + friend_id_decrypted BLOB, + accepted_at TEXT + ); + ''', + ); + }, + // Set the version. This executes the onCreate function and provides a + // path to perform database upgrades and downgrades. + version: 1, + ); + + return database; +} diff --git a/mobile/lib/utils/storage/encryption_keys.dart b/mobile/lib/utils/storage/encryption_keys.dart index edcd727..edc2f5c 100644 --- a/mobile/lib/utils/storage/encryption_keys.dart +++ b/mobile/lib/utils/storage/encryption_keys.dart @@ -1,11 +1,11 @@ import 'package:shared_preferences/shared_preferences.dart'; import "package:pointycastle/export.dart"; -import '/utils/encryption/rsa_key_helper.dart'; +import '/utils/encryption/crypto_utils.dart'; const rsaPrivateKeyName = 'rsaPrivateKey'; void setPrivateKey(RSAPrivateKey key) async { - String keyPem = RsaKeyHelper.encodePrivateKeyToPem(key); + String keyPem = CryptoUtils.encodeRSAPrivateKeyToPem(key); final prefs = await SharedPreferences.getInstance(); prefs.setString(rsaPrivateKeyName, keyPem); @@ -23,5 +23,5 @@ Future getPrivateKey() async { throw Exception('No RSA private key set'); } - return RsaKeyHelper.parsePrivateKeyFromPem(keyPem); + return CryptoUtils.rsaPrivateKeyFromPem(keyPem); } diff --git a/mobile/lib/utils/storage/friends.dart b/mobile/lib/utils/storage/friends.dart new file mode 100644 index 0000000..3e564ae --- /dev/null +++ b/mobile/lib/utils/storage/friends.dart @@ -0,0 +1,38 @@ +// import 'package:sqflite/sqflite.dart'; +import 'package:http/http.dart' as http; +import 'dart:convert'; +import "package:pointycastle/export.dart"; +import '/models/friends.dart'; +import '/utils/storage/encryption_keys.dart'; +import '/utils/storage/session_cookie.dart'; + +void getFriends() async { + RSAPrivateKey privKey = await getPrivateKey(); + + final resp = await http.get( + Uri.parse('http://192.168.1.5:8080/api/v1/auth/friends'), + headers: { + 'cookie': await getSessionCookie(), + } + ); + + if (resp.statusCode != 200) { + throw Exception(resp.body); + } + + List friends = []; + + List friendsJson = jsonDecode(resp.body); + + for (var i = 0; i < friendsJson.length; i++) { + friends.add( + Friend.fromJson( + friendsJson[i] as Map, + privKey, + ) + ); + } + + print(friends); +} + diff --git a/mobile/lib/utils/storage/session_cookie.dart b/mobile/lib/utils/storage/session_cookie.dart new file mode 100644 index 0000000..1070de6 --- /dev/null +++ b/mobile/lib/utils/storage/session_cookie.dart @@ -0,0 +1,23 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +const sessionCookieName = 'sessionCookie'; + +void setSessionCookie(String cookie) async { + final prefs = await SharedPreferences.getInstance(); + prefs.setString(sessionCookieName, cookie); +} + +void unsetSessionCookie() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(sessionCookieName); +} + +Future getSessionCookie() async { + final prefs = await SharedPreferences.getInstance(); + String? sessionCookie = prefs.getString(sessionCookieName); + if (sessionCookie == null) { + throw Exception('No session cookie set'); + } + + return sessionCookie; +} diff --git a/mobile/lib/views/authentication/login.dart b/mobile/lib/views/authentication/login.dart index 98a3ce9..806729b 100644 --- a/mobile/lib/views/authentication/login.dart +++ b/mobile/lib/views/authentication/login.dart @@ -2,9 +2,10 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; -import '/utils/encryption/rsa_key_helper.dart'; +import '/utils/encryption/crypto_utils.dart'; import '/utils/encryption/aes_helper.dart'; import '/utils/storage/encryption_keys.dart'; +import '/utils/storage/session_cookie.dart'; class LoginResponse { final String status; @@ -40,15 +41,24 @@ Future login(context, String username, String password) async { 'password': password, }), ); - - LoginResponse response = LoginResponse.fromJson(jsonDecode(resp.body)); if (resp.statusCode != 200) { - throw Exception(response.message); + throw Exception(resp.body); + } + + String? rawCookie = resp.headers['set-cookie']; + if (rawCookie != null) { + int index = rawCookie.indexOf(';'); + setSessionCookie((index == -1) ? rawCookie : rawCookie.substring(0, index)); } + LoginResponse response = LoginResponse.fromJson(jsonDecode(resp.body)); + var rsaPrivPem = AesHelper.aesDecrypt(password, base64.decode(response.asymmetricPrivateKey)); - var rsaPriv = RsaKeyHelper.parsePrivateKeyFromPem(rsaPrivPem); + + debugPrint(rsaPrivPem); + + var rsaPriv = CryptoUtils.rsaPrivateKeyFromPem(rsaPrivPem); setPrivateKey(rsaPriv); final preferences = await SharedPreferences.getInstance(); @@ -171,14 +181,12 @@ class _LoginWidgetState extends State { usernameController.text, passwordController.text, ).then((value) { - /* - Navigator.of(context).popUntil((route) { - print(route.isFirst); - return route.isFirst; - }); - */ - - Navigator.pushNamedAndRemoveUntil(context, '/home', ModalRoute.withName('/home')); + Navigator. + pushNamedAndRemoveUntil( + context, + '/home', + ModalRoute.withName('/home'), + ); }).catchError((error) { print(error); // TODO: Show error on interface }); diff --git a/mobile/lib/views/authentication/signup.dart b/mobile/lib/views/authentication/signup.dart index 43af372..d179a21 100644 --- a/mobile/lib/views/authentication/signup.dart +++ b/mobile/lib/views/authentication/signup.dart @@ -4,11 +4,9 @@ import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; -import '/views/main/conversation_list.dart'; - -import '/utils/encryption/rsa_key_helper.dart'; import '/utils/encryption/aes_helper.dart'; import '/utils/storage/encryption_keys.dart'; +import '/utils/encryption/crypto_utils.dart'; class SignupResponse { final String status; @@ -28,16 +26,14 @@ class SignupResponse { } Future signUp(context, String username, String password, String confirmPassword) async { - var rsaKeyHelper = RsaKeyHelper(); - var keyPair = rsaKeyHelper.generateRSAkeyPair(); - - setPrivateKey(keyPair.privateKey); + var keyPair = CryptoUtils.generateRSAKeyPair(); - var rsaPubPem = RsaKeyHelper.encodePublicKeyToPem(keyPair.publicKey); - var rsaPrivPem = RsaKeyHelper.encodePrivateKeyToPem(keyPair.privateKey); + var rsaPubPem = CryptoUtils.encodeRSAPublicKeyToPem(keyPair.publicKey); + var rsaPrivPem = CryptoUtils.encodeRSAPrivateKeyToPem(keyPair.privateKey); var encRsaPriv = AesHelper.aesEncrypt(password, Uint8List.fromList(rsaPrivPem.codeUnits)); + // TODO: Check for timeout here final resp = await http.post( Uri.parse('http://192.168.1.5:8080/api/v1/signup'), headers: { @@ -52,14 +48,15 @@ Future signUp(context, String username, String password, String }), ); - SignupResponse response = SignupResponse.fromJson(jsonDecode(resp.body)); + SignupResponse response = SignupResponse.fromJson(jsonDecode(resp.body)); if (resp.statusCode != 201) { throw Exception(response.message); } - final preferences = await SharedPreferences.getInstance(); - preferences.setBool('islogin', true); + debugPrint(rsaPubPem); + debugPrint(rsaPrivPem); + debugPrint(resp.body); return response; } diff --git a/mobile/lib/views/main/friend_list.dart b/mobile/lib/views/main/friend_list.dart index 8d2f4af..9299cb0 100644 --- a/mobile/lib/views/main/friend_list.dart +++ b/mobile/lib/views/main/friend_list.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import '/models/friends.dart'; import '/views/main/friend_list_item.dart'; +import '/utils/storage/friends.dart'; class FriendList extends StatefulWidget { const FriendList({Key? key}) : super(key: key); @@ -10,13 +11,14 @@ class FriendList extends StatefulWidget { } class _FriendListState extends State { - List friends = [ - Friend(id: 'abc', username: 'Test1'), - Friend(id: 'abc', username: 'Test2'), - Friend(id: 'abc', username: 'Test3'), - Friend(id: 'abc', username: 'Test4'), - Friend(id: 'abc', username: 'Test5'), - ]; + List friends = []; + + @override + void initState() { + getFriends(); + super.initState(); + } + Widget list() { @@ -34,7 +36,7 @@ class _FriendListState extends State { itemBuilder: (context, i) { return FriendListItem( id: friends[i].id, - username: friends[i].username, + username: 'test', ); }, ); diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock index 8bafdc8..e09490d 100644 --- a/mobile/pubspec.lock +++ b/mobile/pubspec.lock @@ -164,7 +164,7 @@ packages: source: hosted version: "1.7.0" path: - dependency: transitive + dependency: "direct main" description: name: path url: "https://pub.dartlang.org" @@ -287,6 +287,20 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.8.2" + sqflite: + dependency: "direct main" + description: + name: sqflite + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.2+1" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + url: "https://pub.dartlang.org" + source: hosted + version: "2.2.1+1" stack_trace: dependency: transitive description: @@ -308,6 +322,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.1.0" + synchronized: + dependency: transitive + description: + name: synchronized + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.0+2" term_glyph: dependency: transitive description: diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml index 1cba398..86d417a 100644 --- a/mobile/pubspec.yaml +++ b/mobile/pubspec.yaml @@ -11,13 +11,14 @@ environment: dependencies: flutter: sdk: flutter - cupertino_icons: ^1.0.2 font_awesome_flutter: ^10.1.0 pointycastle: ^3.5.2 asn1lib: ^1.1.0 http: ^0.13.4 shared_preferences: ^2.0.15 + sqflite: ^2.0.2 + path: 1.8.1 dev_dependencies: flutter_test: -- 2.17.1 From b5701cf7772780c870e48a8610681691a6d08083 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Sun, 26 Jun 2022 15:46:19 +0930 Subject: [PATCH 07/24] Friends and conversations sync to device --- .gitignore | 2 +- Backend/Api/Auth/Login.go | 33 ++- Backend/Api/Auth/Logout.go | 8 +- Backend/Api/Auth/Session.go | 45 +--- Backend/Api/Friends/EncryptedFriendsList.go | 46 +++- Backend/Api/Friends/FriendRequest.go | 4 +- Backend/Api/Friends/Friends.go | 14 +- Backend/Api/Messages/Conversations.go | 83 ++++++ Backend/Api/Messages/MessageThread.go | 26 +- Backend/Api/Routes.go | 14 +- Backend/Database/ConversationDetails.go | 55 ++++ Backend/Database/FriendRequests.go | 47 ++++ Backend/Database/Friends.go | 59 ++-- Backend/Database/Init.go | 6 +- Backend/Database/MessageThreadUsers.go | 39 --- Backend/Database/MessageThreads.go | 42 --- Backend/Database/Seeder/FriendSeeder.go | 50 +++- Backend/Database/Seeder/MessageSeeder.go | 252 ++++++------------ Backend/Database/Seeder/Seed.go | 26 +- Backend/Database/Seeder/UserSeeder.go | 40 ++- Backend/Database/Seeder/encryption.go | 188 +++++++++++++ Backend/Database/Sessions.go | 38 +++ Backend/Database/UserConversations.go | 49 ++++ Backend/Models/Friends.go | 18 +- Backend/Models/Messages.go | 28 +- Backend/Models/Sessions.go | 18 ++ Backend/Models/Users.go | 2 + .../lib/components/custom_circle_avatar.dart | 39 +++ mobile/lib/main.dart | 4 +- mobile/lib/models/conversations.dart | 126 +++++++-- mobile/lib/models/friends.dart | 60 ++++- mobile/lib/models/messages.dart | 20 ++ mobile/lib/utils/encryption/aes_helper.dart | 22 +- mobile/lib/utils/storage/conversations.dart | 79 ++++++ mobile/lib/utils/storage/database.dart | 59 ++-- mobile/lib/utils/storage/friends.dart | 61 ++++- mobile/lib/views/authentication/login.dart | 5 +- .../lib/views/main/conversation_detail.dart | 64 ++--- mobile/lib/views/main/conversation_list.dart | 34 +-- .../views/main/conversation_list_item.dart | 106 ++++---- mobile/lib/views/main/friend_list.dart | 9 +- mobile/lib/views/main/friend_list_item.dart | 105 ++++---- mobile/lib/views/main/home.dart | 121 +++++---- mobile/pubspec.lock | 7 + mobile/pubspec.yaml | 6 +- 45 files changed, 1474 insertions(+), 685 deletions(-) create mode 100644 Backend/Api/Messages/Conversations.go create mode 100644 Backend/Database/ConversationDetails.go create mode 100644 Backend/Database/FriendRequests.go delete mode 100644 Backend/Database/MessageThreadUsers.go delete mode 100644 Backend/Database/MessageThreads.go create mode 100644 Backend/Database/Seeder/encryption.go create mode 100644 Backend/Database/Sessions.go create mode 100644 Backend/Database/UserConversations.go create mode 100644 Backend/Models/Sessions.go create mode 100644 mobile/lib/components/custom_circle_avatar.dart create mode 100644 mobile/lib/models/messages.dart create mode 100644 mobile/lib/utils/storage/conversations.dart diff --git a/.gitignore b/.gitignore index e46bbea..f7fec7f 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -/mobile/nsconfig.json +/mobile/.env diff --git a/Backend/Api/Auth/Login.go b/Backend/Api/Auth/Login.go index d3e5116..39c374f 100644 --- a/Backend/Api/Auth/Login.go +++ b/Backend/Api/Auth/Login.go @@ -7,8 +7,6 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" - - "github.com/gofrs/uuid" ) type Credentials struct { @@ -52,11 +50,11 @@ func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey func Login(w http.ResponseWriter, r *http.Request) { var ( - creds Credentials - userData Models.User - sessionToken uuid.UUID - expiresAt time.Time - err error + creds Credentials + userData Models.User + session Models.Session + expiresAt time.Time + err error ) err = json.NewDecoder(r.Body).Decode(&creds) @@ -76,23 +74,22 @@ func Login(w http.ResponseWriter, r *http.Request) { return } - sessionToken, err = uuid.NewV4() - if err != nil { - makeLoginResponse(w, http.StatusInternalServerError, "An error occurred", "", "") - return - } + expiresAt = time.Now().Add(12 * time.Hour) - expiresAt = time.Now().Add(1 * time.Hour) + session = Models.Session{ + UserID: userData.ID, + Expiry: expiresAt, + } - Sessions[sessionToken.String()] = Session{ - UserID: userData.ID.String(), - Username: userData.Username, - Expiry: expiresAt, + err = Database.CreateSession(&session) + if err != nil { + makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "") + return } http.SetCookie(w, &http.Cookie{ Name: "session_token", - Value: sessionToken.String(), + Value: session.ID.String(), Expires: expiresAt, }) diff --git a/Backend/Api/Auth/Logout.go b/Backend/Api/Auth/Logout.go index 822b21d..486b575 100644 --- a/Backend/Api/Auth/Logout.go +++ b/Backend/Api/Auth/Logout.go @@ -1,8 +1,11 @@ package Auth import ( + "log" "net/http" "time" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" ) func Logout(w http.ResponseWriter, r *http.Request) { @@ -24,7 +27,10 @@ func Logout(w http.ResponseWriter, r *http.Request) { sessionToken = c.Value - delete(Sessions, sessionToken) + err = Database.DeleteSessionById(sessionToken) + if err != nil { + log.Println("Could not delete session cookie") + } http.SetCookie(w, &http.Cookie{ Name: "session_token", diff --git a/Backend/Api/Auth/Session.go b/Backend/Api/Auth/Session.go index f97bbaf..ffcfae2 100644 --- a/Backend/Api/Auth/Session.go +++ b/Backend/Api/Auth/Session.go @@ -3,32 +3,16 @@ package Auth import ( "errors" "net/http" - "time" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" ) -var ( - Sessions = map[string]Session{} -) - -type Session struct { - UserID string - Username string - Expiry time.Time -} - -func (s Session) IsExpired() bool { - return s.Expiry.Before(time.Now()) -} - -func CheckCookie(r *http.Request) (Session, error) { +func CheckCookie(r *http.Request) (Models.Session, error) { var ( c *http.Cookie sessionToken string - userSession Session - exists bool + userSession Models.Session err error ) @@ -39,15 +23,15 @@ func CheckCookie(r *http.Request) (Session, error) { sessionToken = c.Value // We then get the session from our session map - userSession, exists = Sessions[sessionToken] - if !exists { + userSession, err = Database.GetSessionById(sessionToken) + if err != nil { return userSession, errors.New("Cookie not found") } // If the session is present, but has expired, we can delete the session, and return // an unauthorized status if userSession.IsExpired() { - delete(Sessions, sessionToken) + Database.DeleteSession(&userSession) return userSession, errors.New("Cookie expired") } @@ -56,24 +40,15 @@ func CheckCookie(r *http.Request) (Session, error) { func CheckCookieCurrentUser(w http.ResponseWriter, r *http.Request) (Models.User, error) { var ( - userSession Session - userData Models.User - err error + session Models.Session + userData Models.User + err error ) - userSession, err = CheckCookie(r) + session, err = CheckCookie(r) if err != nil { return userData, err } - userData, err = Database.GetUserById(userSession.UserID) - if err != nil { - return userData, err - } - - if userData.ID.String() != userSession.UserID { - return userData, errors.New("Is not current user") - } - - return userData, nil + return session.User, nil } diff --git a/Backend/Api/Friends/EncryptedFriendsList.go b/Backend/Api/Friends/EncryptedFriendsList.go index 2db0531..d9f8d61 100644 --- a/Backend/Api/Friends/EncryptedFriendsList.go +++ b/Backend/Api/Friends/EncryptedFriendsList.go @@ -3,16 +3,18 @@ package Friends import ( "encoding/json" "net/http" + "net/url" + "strings" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" ) -func EncryptedFriendList(w http.ResponseWriter, r *http.Request) { +func EncryptedFriendRequestList(w http.ResponseWriter, r *http.Request) { var ( - userSession Auth.Session - friends []Models.Friend + userSession Models.Session + friends []Models.FriendRequest returnJson []byte err error ) @@ -23,7 +25,43 @@ func EncryptedFriendList(w http.ResponseWriter, r *http.Request) { return } - friends, err = Database.GetFriendsByUserId(userSession.UserID) + friends, err = Database.GetFriendRequestsByUserId(userSession.UserID.String()) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + returnJson, err = json.MarshalIndent(friends, "", " ") + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) + w.Write(returnJson) +} + +func EncryptedFriendList(w http.ResponseWriter, r *http.Request) { + var ( + friends []Models.Friend + query url.Values + friendIds []string + returnJson []byte + ok bool + err error + ) + + query = r.URL.Query() + friendIds, ok = query["friend_ids"] + if !ok { + http.Error(w, "Invalid Data", http.StatusBadGateway) + return + } + + // TODO: Fix error handling here + friendIds = strings.Split(friendIds[0], ",") + + friends, err = Database.GetFriendsByIds(friendIds) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) return diff --git a/Backend/Api/Friends/FriendRequest.go b/Backend/Api/Friends/FriendRequest.go index 4943f17..126605d 100644 --- a/Backend/Api/Friends/FriendRequest.go +++ b/Backend/Api/Friends/FriendRequest.go @@ -16,7 +16,7 @@ func FriendRequest(w http.ResponseWriter, r *http.Request) { requestBody []byte requestJson map[string]interface{} friendID string - friendRequest Models.Friend + friendRequest Models.FriendRequest ok bool err error ) @@ -45,7 +45,7 @@ func FriendRequest(w http.ResponseWriter, r *http.Request) { return } - friendRequest = Models.Friend{ + friendRequest = Models.FriendRequest{ UserID: user.ID, FriendID: friendID, } diff --git a/Backend/Api/Friends/Friends.go b/Backend/Api/Friends/Friends.go index a991fb6..050b4d8 100644 --- a/Backend/Api/Friends/Friends.go +++ b/Backend/Api/Friends/Friends.go @@ -35,10 +35,10 @@ func Friend(w http.ResponseWriter, r *http.Request) { func CreateFriendRequest(w http.ResponseWriter, r *http.Request) { var ( - friendData Models.Friend - requestBody []byte - returnJson []byte - err error + friendRequest Models.FriendRequest + requestBody []byte + returnJson []byte + err error ) requestBody, err = ioutil.ReadAll(r.Body) @@ -46,17 +46,17 @@ func CreateFriendRequest(w http.ResponseWriter, r *http.Request) { panic(err) } - err = json.Unmarshal(requestBody, &friendData) + err = json.Unmarshal(requestBody, &friendRequest) if err != nil { panic(err) } - err = Database.CreateFriendRequest(&friendData) + err = Database.CreateFriendRequest(&friendRequest) if err != nil { panic(err) } - returnJson, err = json.MarshalIndent(friendData, "", " ") + returnJson, err = json.MarshalIndent(friendRequest, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError) diff --git a/Backend/Api/Messages/Conversations.go b/Backend/Api/Messages/Conversations.go new file mode 100644 index 0000000..c0beeee --- /dev/null +++ b/Backend/Api/Messages/Conversations.go @@ -0,0 +1,83 @@ +package Messages + +import ( + "encoding/json" + "net/http" + "net/url" + "strings" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +func EncryptedConversationList(w http.ResponseWriter, r *http.Request) { + var ( + userConversations []Models.UserConversation + userSession Models.Session + returnJson []byte + err error + ) + + userSession, err = Auth.CheckCookie(r) + if err != nil { + http.Error(w, "Forbidden", http.StatusUnauthorized) + return + } + + userConversations, err = Database.GetUserConversationsByUserId( + userSession.UserID.String(), + ) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + returnJson, err = json.MarshalIndent(userConversations, "", " ") + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) + w.Write(returnJson) +} + +func EncryptedConversationDetailsList(w http.ResponseWriter, r *http.Request) { + var ( + userConversations []Models.ConversationDetail + query url.Values + conversationIds []string + returnJson []byte + ok bool + err error + ) + + query = r.URL.Query() + conversationIds, ok = query["conversation_detail_ids"] + if !ok { + http.Error(w, "Invalid Data", http.StatusBadGateway) + return + } + + // TODO: Fix error handling here + conversationIds = strings.Split(conversationIds[0], ",") + + userConversations, err = Database.GetConversationDetailsByIds( + conversationIds, + ) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + returnJson, err = json.MarshalIndent(userConversations, "", " ") + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) + w.Write(returnJson) + +} diff --git a/Backend/Api/Messages/MessageThread.go b/Backend/Api/Messages/MessageThread.go index 8a86209..3fef1d3 100644 --- a/Backend/Api/Messages/MessageThread.go +++ b/Backend/Api/Messages/MessageThread.go @@ -4,29 +4,21 @@ import ( "encoding/json" "net/http" - "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" "github.com/gorilla/mux" ) -func MessageThread(w http.ResponseWriter, r *http.Request) { +func ConversationDetail(w http.ResponseWriter, r *http.Request) { var ( - userData Models.User - messageThread Models.MessageThread - urlVars map[string]string - threadKey string - returnJson []byte - ok bool - err error + conversationDetail Models.ConversationDetail + urlVars map[string]string + threadKey string + returnJson []byte + ok bool + err error ) - userData, err = Auth.CheckCookieCurrentUser(w, r) - if !ok { - http.Error(w, "Forbidden", http.StatusUnauthorized) - return - } - urlVars = mux.Vars(r) threadKey, ok = urlVars["threadKey"] if !ok { @@ -34,13 +26,13 @@ func MessageThread(w http.ResponseWriter, r *http.Request) { return } - messageThread, err = Database.GetMessageThreadById(threadKey, userData) + conversationDetail, err = Database.GetConversationDetailById(threadKey) if !ok { http.Error(w, "Not Found", http.StatusNotFound) return } - returnJson, err = json.MarshalIndent(messageThread, "", " ") + returnJson, err = json.MarshalIndent(conversationDetail, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) return diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index a362154..d4c2cdb 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -60,11 +60,17 @@ func InitApiEndpoints(router *mux.Router) { authApi.Use(authenticationMiddleware) // Define routes for friends and friend requests - authApi.HandleFunc("/friend", Friends.CreateFriendRequest).Methods("POST") + authApi.HandleFunc("/friend_requests", Friends.EncryptedFriendRequestList).Methods("GET") + authApi.HandleFunc("/friend_request", Friends.CreateFriendRequest).Methods("POST") + authApi.HandleFunc("/friends", Friends.EncryptedFriendList).Methods("GET") - authApi.HandleFunc("/friend/{userID}", Friends.Friend).Methods("GET") - authApi.HandleFunc("/friend/{userID}/request", Friends.FriendRequest).Methods("POST") + + authApi.HandleFunc("/conversations", Messages.EncryptedConversationList).Methods("GET") + authApi.HandleFunc("/conversation_details", Messages.EncryptedConversationDetailsList).Methods("GET") + + // authApi.HandleFunc("/user/{userID}", Friends.Friend).Methods("GET") + // authApi.HandleFunc("/user/{userID}/request", Friends.FriendRequest).Methods("POST") // Define routes for messages - authApi.HandleFunc("/messages/{threadKey}", Messages.MessageThread).Methods("GET") + authApi.HandleFunc("/messages/{threadKey}", Messages.ConversationDetail).Methods("GET") } diff --git a/Backend/Database/ConversationDetails.go b/Backend/Database/ConversationDetails.go new file mode 100644 index 0000000..144e28c --- /dev/null +++ b/Backend/Database/ConversationDetails.go @@ -0,0 +1,55 @@ +package Database + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +func GetConversationDetailById(id string) (Models.ConversationDetail, error) { + var ( + messageThread Models.ConversationDetail + err error + ) + + err = DB.Preload(clause.Associations). + Where("id = ?", id). + First(&messageThread). + Error + + return messageThread, err +} + +func GetConversationDetailsByIds(id []string) ([]Models.ConversationDetail, error) { + var ( + messageThread []Models.ConversationDetail + err error + ) + + err = DB.Preload(clause.Associations). + Where("id = ?", id). + First(&messageThread). + Error + + return messageThread, err +} + +func CreateConversationDetail(messageThread *Models.ConversationDetail) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(messageThread). + Error +} + +func UpdateConversationDetail(messageThread *Models.ConversationDetail) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Where("id = ?", messageThread.ID). + Updates(messageThread). + Error +} + +func DeleteConversationDetail(messageThread *Models.ConversationDetail) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Delete(messageThread). + Error +} diff --git a/Backend/Database/FriendRequests.go b/Backend/Database/FriendRequests.go new file mode 100644 index 0000000..dec6860 --- /dev/null +++ b/Backend/Database/FriendRequests.go @@ -0,0 +1,47 @@ +package Database + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +func GetFriendRequestById(id string) (Models.FriendRequest, error) { + var ( + friendRequest Models.FriendRequest + err error + ) + + err = DB.Preload(clause.Associations). + First(&friendRequest, "id = ?", id). + Error + + return friendRequest, err +} + +func GetFriendRequestsByUserId(userID string) ([]Models.FriendRequest, error) { + var ( + friends []Models.FriendRequest + err error + ) + + err = DB.Model(Models.FriendRequest{}). + Where("user_id = ?", userID). + Find(&friends). + Error + + return friends, err +} + +func CreateFriendRequest(FriendRequest *Models.FriendRequest) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(FriendRequest). + Error +} + +func DeleteFriendRequest(FriendRequest *Models.FriendRequest) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Delete(FriendRequest). + Error +} diff --git a/Backend/Database/Friends.go b/Backend/Database/Friends.go index d82ccab..102e657 100644 --- a/Backend/Database/Friends.go +++ b/Backend/Database/Friends.go @@ -9,39 +9,66 @@ import ( func GetFriendById(id string) (Models.Friend, error) { var ( - friend Models.Friend - err error + userData Models.Friend + err error ) err = DB.Preload(clause.Associations). - First(&friend, "id = ?", id). + First(&userData, "id = ?", id). Error - return friend, err + return userData, err } -func GetFriendsByUserId(userID string) ([]Models.Friend, error) { +func GetFriendsByIds(ids []string) ([]Models.Friend, error) { var ( - friends []Models.Friend - err error + userData []Models.Friend + err error ) - err = DB.Model(Models.Friend{}). - Where("user_id = ?", userID). - Find(&friends). + err = DB.Preload(clause.Associations). + Find(&userData, ids). Error - return friends, err + return userData, err } -func CreateFriendRequest(friend *Models.Friend) error { - return DB.Session(&gorm.Session{FullSaveAssociations: true}). - Create(friend). +func CreateFriend(userData *Models.Friend) error { + var ( + err error + ) + + err = DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(userData). Error + + return err +} + +func UpdateFriend(id string, userData *Models.Friend) error { + var ( + err error + ) + err = DB.Model(&userData). + Omit("id"). + Where("id = ?", id). + Updates(userData). + Error + + if err != nil { + return err + } + + err = DB.Model(Models.Friend{}). + Where("id = ?", id). + First(userData). + Error + + return err } -func DeleteFriend(friend *Models.Friend) error { +func DeleteFriend(userData *Models.Friend) error { return DB.Session(&gorm.Session{FullSaveAssociations: true}). - Delete(friend). + Delete(userData). Error } diff --git a/Backend/Database/Init.go b/Backend/Database/Init.go index 12f90ae..f8537d4 100644 --- a/Backend/Database/Init.go +++ b/Backend/Database/Init.go @@ -18,12 +18,14 @@ var ( func GetModels() []interface{} { return []interface{}{ + &Models.Session{}, &Models.User{}, &Models.Friend{}, + &Models.FriendRequest{}, &Models.MessageData{}, &Models.Message{}, - &Models.MessageThread{}, - &Models.MessageThreadUser{}, + &Models.ConversationDetail{}, + &Models.UserConversation{}, } } diff --git a/Backend/Database/MessageThreadUsers.go b/Backend/Database/MessageThreadUsers.go deleted file mode 100644 index 842bc15..0000000 --- a/Backend/Database/MessageThreadUsers.go +++ /dev/null @@ -1,39 +0,0 @@ -package Database - -import ( - "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" - - "gorm.io/gorm" - "gorm.io/gorm/clause" -) - -func GetMessageThreadUserById(id string) (Models.MessageThreadUser, error) { - var ( - message Models.MessageThreadUser - err error - ) - - err = DB.Preload(clause.Associations). - First(&message, "id = ?", id). - Error - - return message, err -} - -func CreateMessageThreadUser(messageThreadUser *Models.MessageThreadUser) error { - var ( - err error - ) - - err = DB.Session(&gorm.Session{FullSaveAssociations: true}). - Create(messageThreadUser). - Error - - return err -} - -func DeleteMessageThreadUser(messageThreadUser *Models.MessageThreadUser) error { - return DB.Session(&gorm.Session{FullSaveAssociations: true}). - Delete(messageThreadUser). - Error -} diff --git a/Backend/Database/MessageThreads.go b/Backend/Database/MessageThreads.go deleted file mode 100644 index be3ffc1..0000000 --- a/Backend/Database/MessageThreads.go +++ /dev/null @@ -1,42 +0,0 @@ -package Database - -import ( - "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" - - "gorm.io/gorm" - "gorm.io/gorm/clause" -) - -func GetMessageThreadById(id string, user Models.User) (Models.MessageThread, error) { - var ( - messageThread Models.MessageThread - err error - ) - - err = DB.Preload(clause.Associations). - Where("id = ?", id). - Where("user_id = ?", user.ID). - First(&messageThread). - Error - - return messageThread, err -} - -func CreateMessageThread(messageThread *Models.MessageThread) error { - return DB.Session(&gorm.Session{FullSaveAssociations: true}). - Create(messageThread). - Error -} - -func UpdateMessageThread(messageThread *Models.MessageThread) error { - return DB.Session(&gorm.Session{FullSaveAssociations: true}). - Where("id = ?", messageThread.ID). - Updates(messageThread). - Error -} - -func DeleteMessageThread(messageThread *Models.MessageThread) error { - return DB.Session(&gorm.Session{FullSaveAssociations: true}). - Delete(messageThread). - Error -} diff --git a/Backend/Database/Seeder/FriendSeeder.go b/Backend/Database/Seeder/FriendSeeder.go index bcacf9d..033b7a6 100644 --- a/Backend/Database/Seeder/FriendSeeder.go +++ b/Backend/Database/Seeder/FriendSeeder.go @@ -8,30 +8,43 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" ) -func seedFriend(user, friendUser Models.User) error { +func seedFriend(userRequestTo, userRequestFrom Models.User) error { var ( - friend Models.Friend - err error + friendRequest Models.FriendRequest + decodedID []byte + id []byte + decodedSymKey []byte + symKey []byte + err error ) - friend = Models.Friend{ - UserID: user.ID, - FriendID: base64.StdEncoding.EncodeToString(encryptWithPublicKey([]byte(friendUser.ID.String()), decodedPublicKey)), - AcceptedAt: time.Now(), + decodedID, err = base64.StdEncoding.DecodeString(userRequestFrom.FriendID) + if err != nil { + return err + } + id, err = decryptWithPrivateKey(decodedID, decodedPrivateKey) + if err != nil { + return err } - err = Database.CreateFriendRequest(&friend) + decodedSymKey, err = base64.StdEncoding.DecodeString(userRequestFrom.FriendSymmetricKey) if err != nil { return err } + symKey, err = decryptWithPrivateKey(decodedSymKey, decodedPrivateKey) - friend = Models.Friend{ - UserID: friendUser.ID, - FriendID: base64.StdEncoding.EncodeToString(encryptWithPublicKey([]byte(user.ID.String()), decodedPublicKey)), + friendRequest = Models.FriendRequest{ + UserID: userRequestTo.ID, AcceptedAt: time.Now(), + FriendID: base64.StdEncoding.EncodeToString( + encryptWithPublicKey(id, decodedPublicKey), + ), + SymmetricKey: base64.StdEncoding.EncodeToString( + encryptWithPublicKey(symKey, decodedPublicKey), + ), } - return Database.CreateFriendRequest(&friend) + return Database.CreateFriendRequest(&friendRequest) } func SeedFriends() { @@ -53,6 +66,14 @@ func SeedFriends() { } err = seedFriend(primaryUser, secondaryUser) + if err != nil { + panic(err) + } + + err = seedFriend(secondaryUser, primaryUser) + if err != nil { + panic(err) + } for i = 0; i <= 3; i++ { secondaryUser, err = Database.GetUserByUsername(userNames[i]) @@ -64,5 +85,10 @@ func SeedFriends() { if err != nil { panic(err) } + + err = seedFriend(secondaryUser, primaryUser) + if err != nil { + panic(err) + } } } diff --git a/Backend/Database/Seeder/MessageSeeder.go b/Backend/Database/Seeder/MessageSeeder.go index 29de572..06cd78e 100644 --- a/Backend/Database/Seeder/MessageSeeder.go +++ b/Backend/Database/Seeder/MessageSeeder.go @@ -1,15 +1,8 @@ package Seeder import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "crypto/rsa" - "crypto/sha256" - "encoding/pem" + "encoding/base64" "fmt" - "hash" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" @@ -17,108 +10,49 @@ import ( "github.com/gofrs/uuid" ) -// EncryptWithPublicKey encrypts data with public key -func encryptWithPublicKey(msg []byte, pub *rsa.PublicKey) []byte { +func seedMessage( + primaryUser Models.User, + primaryUserThreadKey, secondaryUserThreadKey string, + thread Models.ConversationDetail, + i int, +) error { var ( - hash hash.Hash + message Models.Message + messageData Models.MessageData + key aesKey + plaintext string + dataCiphertext []byte + senderIdCiphertext []byte + err error ) - hash = sha256.New() - ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pub, msg, nil) + key, err = generateAesKey() if err != nil { panic(err) } - return ciphertext -} -func PKCS5Padding(ciphertext []byte, blockSize int, after int) []byte { - var ( - padding int - padtext []byte - ) - padding = (blockSize - len(ciphertext)%blockSize) - padtext = bytes.Repeat([]byte{byte(padding)}, padding) - return append(ciphertext, padtext...) -} - -func generateAesKey() (*pem.Block, cipher.BlockMode) { - var ( - pemBlock *pem.Block - block cipher.Block - - bKey []byte - bIV []byte - - err error - ) + plaintext = "Test Message" - bKey = make([]byte, 32) - _, err = rand.Read(bKey) - if err != nil { - panic(err) - } - bIV = make([]byte, 16) - _, err = rand.Read(bIV) + dataCiphertext, err = key.aesEncrypt([]byte(plaintext)) if err != nil { panic(err) } - pemBlock = &pem.Block{ - Type: "AES KEY", - Bytes: bKey, - } - - block, err = aes.NewCipher(bKey) + senderIdCiphertext, err = key.aesEncrypt(primaryUser.ID.Bytes()) if err != nil { panic(err) } - return pemBlock, cipher.NewCBCEncrypter(block, bIV) -} - -func seedMessage( - primaryUser Models.User, - primaryUserThreadKey, secondaryUserThreadKey string, - thread Models.MessageThread, - i int, -) error { - var ( - message Models.Message - messageData Models.MessageData - - messagePemBlock *pem.Block - messageMode cipher.BlockMode - - plaintext string - dataCiphertext []byte - senderIdCiphertext []byte - - bPlaintext []byte - bSenderIdPlaintext []byte - - err error - ) - - plaintext = "Test Message" - bPlaintext = PKCS5Padding([]byte(plaintext), aes.BlockSize, len(plaintext)) - bSenderIdPlaintext = PKCS5Padding(primaryUser.ID.Bytes(), aes.BlockSize, len(primaryUser.ID.Bytes())) - - dataCiphertext = make([]byte, len(bPlaintext)) - senderIdCiphertext = make([]byte, len(bSenderIdPlaintext)) - - messagePemBlock, messageMode = generateAesKey() - - messageMode.CryptBlocks(dataCiphertext, bPlaintext) - messageMode.CryptBlocks(senderIdCiphertext, bSenderIdPlaintext) - messageData = Models.MessageData{ - Data: dataCiphertext, - SenderID: senderIdCiphertext, + Data: base64.StdEncoding.EncodeToString(dataCiphertext), + SenderID: base64.StdEncoding.EncodeToString(senderIdCiphertext), } message = Models.Message{ - MessageData: messageData, - SymmetricKey: encryptWithPublicKey(pem.EncodeToMemory(messagePemBlock), decodedPublicKey), + MessageData: messageData, + SymmetricKey: base64.StdEncoding.EncodeToString( + encryptWithPublicKey(key.Key, decodedPublicKey), + ), MessageThreadKey: primaryUserThreadKey, } @@ -130,8 +64,10 @@ func seedMessage( // The symmetric key would be encrypted with secondary users public key in production // But due to using the same pub/priv key pair for all users, we will just duplicate it message = Models.Message{ - MessageDataID: message.MessageDataID, - SymmetricKey: encryptWithPublicKey(pem.EncodeToMemory(messagePemBlock), decodedPublicKey), + MessageDataID: message.MessageDataID, + SymmetricKey: base64.StdEncoding.EncodeToString( + encryptWithPublicKey(key.Key, decodedPublicKey), + ), MessageThreadKey: secondaryUserThreadKey, } @@ -143,107 +79,96 @@ func seedMessage( return err } -func seedMessageThread(threadPemBlock *pem.Block, threadMode cipher.BlockMode) (Models.MessageThread, error) { +func seedConversationDetail(key aesKey) (Models.ConversationDetail, error) { var ( - messageThread Models.MessageThread - + messageThread Models.ConversationDetail name string - bNamePlaintext []byte nameCiphertext []byte - - err error + err error ) name = "Test Conversation" - bNamePlaintext = PKCS5Padding([]byte(name), aes.BlockSize, len(name)) - nameCiphertext = make([]byte, len(bNamePlaintext)) - - threadMode.CryptBlocks(nameCiphertext, bNamePlaintext) + nameCiphertext, err = key.aesEncrypt([]byte(name)) + if err != nil { + panic(err) + } - messageThread = Models.MessageThread{ - Name: nameCiphertext, + messageThread = Models.ConversationDetail{ + Name: base64.StdEncoding.EncodeToString(nameCiphertext), } - err = Database.CreateMessageThread(&messageThread) + err = Database.CreateConversationDetail(&messageThread) return messageThread, err } -func seedUpdateMessageThreadUsers( +func seedUpdateUserConversation( userJson string, - threadPemBlock *pem.Block, - threadMode cipher.BlockMode, - messageThread Models.MessageThread, -) (Models.MessageThread, error) { + key aesKey, + messageThread Models.ConversationDetail, +) (Models.ConversationDetail, error) { var ( - bUsersPlaintext []byte usersCiphertext []byte err error ) - bUsersPlaintext = PKCS5Padding([]byte(userJson), aes.BlockSize, len(userJson)) - usersCiphertext = make([]byte, len(bUsersPlaintext)) - - threadMode.CryptBlocks(usersCiphertext, bUsersPlaintext) + usersCiphertext, err = key.aesEncrypt([]byte(userJson)) + if err != nil { + return messageThread, err + } - messageThread.Users = usersCiphertext - err = Database.UpdateMessageThread(&messageThread) + messageThread.Users = base64.StdEncoding.EncodeToString(usersCiphertext) + err = Database.UpdateConversationDetail(&messageThread) return messageThread, err } -func seedMessageThreadUser( +func seedUserConversation( user Models.User, threadID uuid.UUID, messageThreadKey string, - threadPemBlock *pem.Block, - threadMode cipher.BlockMode, -) (Models.MessageThreadUser, error) { + key aesKey, +) (Models.UserConversation, error) { var ( - messageThreadUser Models.MessageThreadUser - - bThreadIdPlaintext []byte + messageThreadUser Models.UserConversation threadIdCiphertext []byte - - bKeyPlaintext []byte - keyCiphertext []byte - - bAdminPlaintext []byte - adminCiphertext []byte - - err error + keyCiphertext []byte + adminCiphertext []byte + err error ) - bThreadIdPlaintext = PKCS5Padding(threadID.Bytes(), aes.BlockSize, len(threadID.String())) - threadIdCiphertext = make([]byte, len(bThreadIdPlaintext)) - - bKeyPlaintext = PKCS5Padding([]byte(messageThreadKey), aes.BlockSize, len(messageThreadKey)) - keyCiphertext = make([]byte, len(bKeyPlaintext)) + threadIdCiphertext, err = key.aesEncrypt([]byte(threadID.String())) + if err != nil { + return messageThreadUser, err + } - bAdminPlaintext = PKCS5Padding([]byte("true"), aes.BlockSize, len("true")) - adminCiphertext = make([]byte, len(bAdminPlaintext)) + keyCiphertext, err = key.aesEncrypt([]byte(messageThreadKey)) + if err != nil { + return messageThreadUser, err + } - threadMode.CryptBlocks(threadIdCiphertext, bThreadIdPlaintext) - threadMode.CryptBlocks(keyCiphertext, bKeyPlaintext) - threadMode.CryptBlocks(adminCiphertext, bAdminPlaintext) + adminCiphertext, err = key.aesEncrypt([]byte("true")) + if err != nil { + return messageThreadUser, err + } - messageThreadUser = Models.MessageThreadUser{ - UserID: user.ID, - MessageThreadID: threadIdCiphertext, - MessageThreadKey: keyCiphertext, - Admin: adminCiphertext, - SymmetricKey: encryptWithPublicKey(pem.EncodeToMemory(threadPemBlock), decodedPublicKey), + messageThreadUser = Models.UserConversation{ + UserID: user.ID, + ConversationDetailID: base64.StdEncoding.EncodeToString(threadIdCiphertext), + MessageThreadKey: base64.StdEncoding.EncodeToString(keyCiphertext), + Admin: base64.StdEncoding.EncodeToString(adminCiphertext), + SymmetricKey: base64.StdEncoding.EncodeToString( + encryptWithPublicKey(key.Key, decodedPublicKey), + ), } - err = Database.CreateMessageThreadUser(&messageThreadUser) + err = Database.CreateUserConversation(&messageThreadUser) return messageThreadUser, err } func SeedMessages() { var ( - messageThread Models.MessageThread - threadPemBlock *pem.Block - threadMode cipher.BlockMode - + messageThread Models.ConversationDetail + key aesKey primaryUser Models.User primaryUserThreadKey string secondaryUser Models.User @@ -251,13 +176,13 @@ func SeedMessages() { userJson string - thread Models.MessageThread + thread Models.ConversationDetail i int err error ) - threadPemBlock, threadMode = generateAesKey() - messageThread, err = seedMessageThread(threadPemBlock, threadMode) + key, err = generateAesKey() + messageThread, err = seedConversationDetail(key) primaryUserThreadKey = Util.RandomString(32) secondaryUserThreadKey = Util.RandomString(32) @@ -266,12 +191,11 @@ func SeedMessages() { panic(err) } - _, err = seedMessageThreadUser( + _, err = seedUserConversation( primaryUser, messageThread.ID, primaryUserThreadKey, - threadPemBlock, - threadMode, + key, ) secondaryUser, err = Database.GetUserByUsername("testUser2") @@ -279,12 +203,11 @@ func SeedMessages() { panic(err) } - _, err = seedMessageThreadUser( + _, err = seedUserConversation( secondaryUser, messageThread.ID, secondaryUserThreadKey, - threadPemBlock, - threadMode, + key, ) userJson = fmt.Sprintf( @@ -308,10 +231,9 @@ func SeedMessages() { secondaryUser.Username, ) - messageThread, err = seedUpdateMessageThreadUsers( + messageThread, err = seedUpdateUserConversation( userJson, - threadPemBlock, - threadMode, + key, messageThread, ) diff --git a/Backend/Database/Seeder/Seed.go b/Backend/Database/Seeder/Seed.go index 28825f4..7e9a373 100644 --- a/Backend/Database/Seeder/Seed.go +++ b/Backend/Database/Seeder/Seed.go @@ -1,9 +1,7 @@ package Seeder import ( - "crypto/rand" "crypto/rsa" - "crypto/sha256" "crypto/x509" "encoding/pem" "errors" @@ -56,20 +54,10 @@ ZQIDAQAB ) var ( - decodedPublicKey *rsa.PublicKey - // decodedPrivateKey *rsa.PrivateKey + decodedPublicKey *rsa.PublicKey + decodedPrivateKey *rsa.PrivateKey ) -// DecryptWithPrivateKey decrypts data with private key -func decryptWithPrivateKey(ciphertext []byte, priv *rsa.PrivateKey) []byte { - hash := sha256.New() - plaintext, err := rsa.DecryptOAEP(hash, rand.Reader, priv, ciphertext, nil) - if err != nil { - panic(err) - } - return plaintext -} - func Seed() { var ( block *pem.Block @@ -88,6 +76,16 @@ func Seed() { panic(errors.New("Invalid decodedPublicKey")) } + block, _ = pem.Decode([]byte(privateKey)) + decKey, err = x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + panic(err) + } + decodedPrivateKey, ok = decKey.(*rsa.PrivateKey) + if !ok { + panic(errors.New("Invalid decodedPrivateKey")) + } + log.Println("Seeding users...") SeedUsers() diff --git a/Backend/Database/Seeder/UserSeeder.go b/Backend/Database/Seeder/UserSeeder.go index fd7cc7e..b9e12e6 100644 --- a/Backend/Database/Seeder/UserSeeder.go +++ b/Backend/Database/Seeder/UserSeeder.go @@ -1,6 +1,8 @@ package Seeder import ( + "encoding/base64" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" @@ -22,9 +24,12 @@ var userNames = []string{ func createUser(username string) (Models.User, error) { var ( - userData Models.User - password string - err error + userData Models.User + key aesKey + publicUserData Models.Friend + password string + usernameCiphertext []byte + err error ) password, err = Auth.HashPassword("password") @@ -32,11 +37,40 @@ func createUser(username string) (Models.User, error) { return Models.User{}, err } + key, err = generateAesKey() + if err != nil { + return Models.User{}, err + } + + usernameCiphertext, err = key.aesEncrypt([]byte(username)) + if err != nil { + return Models.User{}, err + } + + publicUserData = Models.Friend{ + Username: base64.StdEncoding.EncodeToString(usernameCiphertext), + AsymmetricPublicKey: base64.StdEncoding.EncodeToString([]byte(publicKey)), + } + + err = Database.CreateFriend(&publicUserData) + if err != nil { + return userData, err + } + userData = Models.User{ Username: username, Password: password, AsymmetricPrivateKey: encryptedPrivateKey, AsymmetricPublicKey: publicKey, + FriendID: base64.StdEncoding.EncodeToString( + encryptWithPublicKey( + []byte(publicUserData.ID.String()), + decodedPublicKey, + ), + ), + FriendSymmetricKey: base64.StdEncoding.EncodeToString( + encryptWithPublicKey(key.Key, decodedPublicKey), + ), } err = Database.CreateUser(&userData) diff --git a/Backend/Database/Seeder/encryption.go b/Backend/Database/Seeder/encryption.go new file mode 100644 index 0000000..a116134 --- /dev/null +++ b/Backend/Database/Seeder/encryption.go @@ -0,0 +1,188 @@ +package Seeder + +// THIS FILE IS ONLY USED FOR SEEDING DATA DURING DEVELOPMENT + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/hmac" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "fmt" + "hash" + + "golang.org/x/crypto/pbkdf2" +) + +type aesKey struct { + Key []byte + Iv []byte +} + +func (key aesKey) encode() string { + return base64.StdEncoding.EncodeToString(key.Key) +} + +// Appends padding. +func pkcs7Padding(data []byte, blocklen int) ([]byte, error) { + var ( + padlen int = 1 + pad []byte + ) + if blocklen <= 0 { + return nil, fmt.Errorf("invalid blocklen %d", blocklen) + } + + for ((len(data) + padlen) % blocklen) != 0 { + padlen = padlen + 1 + } + + pad = bytes.Repeat([]byte{byte(padlen)}, padlen) + return append(data, pad...), nil +} + +// pkcs7strip remove pkcs7 padding +func pkcs7strip(data []byte, blockSize int) ([]byte, error) { + var ( + length int + padLen int + ref []byte + ) + + length = len(data) + if length == 0 { + return nil, fmt.Errorf("pkcs7: Data is empty") + } + + if (length % blockSize) != 0 { + return nil, fmt.Errorf("pkcs7: Data is not block-aligned") + } + + padLen = int(data[length-1]) + ref = bytes.Repeat([]byte{byte(padLen)}, padLen) + + if padLen > blockSize || padLen == 0 || !bytes.HasSuffix(data, ref) { + return nil, fmt.Errorf("pkcs7: Invalid padding") + } + + return data[:length-padLen], nil +} + +func generateAesKey() (aesKey, error) { + var ( + saltBytes []byte = []byte{} + password []byte + seed []byte + iv []byte + err error + ) + + password = make([]byte, 64) + _, err = rand.Read(password) + if err != nil { + return aesKey{}, err + } + + seed = make([]byte, 64) + _, err = rand.Read(seed) + if err != nil { + return aesKey{}, err + } + + iv = make([]byte, 16) + _, err = rand.Read(iv) + if err != nil { + return aesKey{}, err + } + + return aesKey{ + Key: pbkdf2.Key( + password, + saltBytes, + 1000, + 32, + func() hash.Hash { return hmac.New(sha256.New, seed) }, + ), + Iv: iv, + }, nil +} + +func (key aesKey) aesEncrypt(plaintext []byte) ([]byte, error) { + var ( + bPlaintext []byte + ciphertext []byte + block cipher.Block + err error + ) + + bPlaintext, err = pkcs7Padding(plaintext, 16) + + block, err = aes.NewCipher(key.Key) + if err != nil { + return []byte{}, err + } + + ciphertext = make([]byte, len(bPlaintext)) + mode := cipher.NewCBCEncrypter(block, key.Iv) + mode.CryptBlocks(ciphertext, bPlaintext) + + ciphertext = append(key.Iv, ciphertext...) + + return ciphertext, nil +} + +func (key aesKey) aesDecrypt(ciphertext []byte) ([]byte, error) { + var ( + plaintext []byte + iv []byte + block cipher.Block + err error + ) + + iv = ciphertext[:aes.BlockSize] + plaintext = ciphertext[aes.BlockSize:] + + block, err = aes.NewCipher(key.Key) + if err != nil { + return []byte{}, err + } + + decMode := cipher.NewCBCDecrypter(block, iv) + decMode.CryptBlocks(plaintext, plaintext) + + return plaintext, nil +} + +// EncryptWithPublicKey encrypts data with public key +func encryptWithPublicKey(msg []byte, pub *rsa.PublicKey) []byte { + var ( + hash hash.Hash + ) + + hash = sha256.New() + ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pub, msg, nil) + if err != nil { + panic(err) + } + return ciphertext +} + +// DecryptWithPrivateKey decrypts data with private key +func decryptWithPrivateKey(ciphertext []byte, priv *rsa.PrivateKey) ([]byte, error) { + var ( + hash hash.Hash + plaintext []byte + err error + ) + + hash = sha256.New() + + plaintext, err = rsa.DecryptOAEP(hash, rand.Reader, priv, ciphertext, nil) + if err != nil { + return plaintext, err + } + return plaintext, nil +} diff --git a/Backend/Database/Sessions.go b/Backend/Database/Sessions.go new file mode 100644 index 0000000..1f125df --- /dev/null +++ b/Backend/Database/Sessions.go @@ -0,0 +1,38 @@ +package Database + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/gorm/clause" +) + +func GetSessionById(id string) (Models.Session, error) { + var ( + session Models.Session + err error + ) + + err = DB.Preload(clause.Associations). + First(&session, "id = ?", id). + Error + + return session, err +} + +func CreateSession(session *Models.Session) error { + var ( + err error + ) + + err = DB.Create(session).Error + + return err +} + +func DeleteSession(session *Models.Session) error { + return DB.Delete(session).Error +} + +func DeleteSessionById(id string) error { + return DB.Delete(&Models.Session{}, id).Error +} diff --git a/Backend/Database/UserConversations.go b/Backend/Database/UserConversations.go new file mode 100644 index 0000000..8e5490b --- /dev/null +++ b/Backend/Database/UserConversations.go @@ -0,0 +1,49 @@ +package Database + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/gorm" +) + +func GetUserConversationById(id string) (Models.UserConversation, error) { + var ( + message Models.UserConversation + err error + ) + + err = DB.First(&message, "id = ?", id). + Error + + return message, err +} + +func GetUserConversationsByUserId(id string) ([]Models.UserConversation, error) { + var ( + conversations []Models.UserConversation + err error + ) + + err = DB.Find(&conversations, "user_id = ?", id). + Error + + return conversations, err +} + +func CreateUserConversation(messageThreadUser *Models.UserConversation) error { + var ( + err error + ) + + err = DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(messageThreadUser). + Error + + return err +} + +func DeleteUserConversation(messageThreadUser *Models.UserConversation) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Delete(messageThreadUser). + Error +} diff --git a/Backend/Models/Friends.go b/Backend/Models/Friends.go index b435223..5022d9b 100644 --- a/Backend/Models/Friends.go +++ b/Backend/Models/Friends.go @@ -6,11 +6,19 @@ import ( "github.com/gofrs/uuid" ) -// Set with User being the requestee, and FriendID being the requester +// TODO: Add profile picture type Friend struct { Base - UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` - User User `json:"user"` - FriendID string `gorm:"not null" json:"friend_id"` // Stored encrypted - AcceptedAt time.Time `json:"accepted_at"` + Username string `gorm:"not null" json:"username"` // Stored encrypted + AsymmetricPublicKey string `gorm:"not null" json:"asymmetric_public_key"` // Stored encrypted +} + +// Set with Friend being the requestee, and RequestFromID being the requester +type FriendRequest struct { + Base + UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` + User User `json:"user"` + FriendID string `gorm:"not null" json:"friend_id"` // Stored encrypted + SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted + AcceptedAt time.Time `json:"accepted_at"` } diff --git a/Backend/Models/Messages.go b/Backend/Models/Messages.go index 6e1893e..6c3d5a3 100644 --- a/Backend/Models/Messages.go +++ b/Backend/Models/Messages.go @@ -2,32 +2,34 @@ package Models import "github.com/gofrs/uuid" +// TODO: Add support for images type MessageData struct { Base - Data []byte `gorm:"not null" json:"data"` // Stored encrypted - SenderID []byte `gorm:"not null" json:"sender_id"` + Data string `gorm:"not null" json:"data"` // Stored encrypted + SenderID string `gorm:"not null" json:"sender_id"` } type Message struct { Base MessageDataID uuid.UUID `json:"-"` MessageData MessageData `json:"message_data"` - SymmetricKey []byte `gorm:"not null" json:"symmetric_key"` // Stored encrypted + SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted MessageThreadKey string `gorm:"not null" json:"message_thread_key"` } -type MessageThread struct { +// TODO: Rename to ConversationDetails +type ConversationDetail struct { Base - Name []byte `gorm:"not null" json:"name"` - Users []byte `json:"users"` + Name string `gorm:"not null" json:"name"` + Users string `json:"users"` // Stored as encrypted JSON } -type MessageThreadUser struct { +type UserConversation struct { Base - UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` - User User `json:"user"` - MessageThreadID []byte `gorm:"not null" json:"message_thread_link_id"` - MessageThreadKey []byte `gorm:"not null" json:"message_thread_key"` - Admin []byte `gorm:"not null" json:"admin"` // Bool if user is admin of thread, stored encrypted - SymmetricKey []byte `gorm:"not null" json:"symmetric_key"` // Stored encrypted + UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` + User User `json:"user"` + ConversationDetailID string `gorm:"not null" json:"conversation_detail_id"` // Stored encrypted + MessageThreadKey string `gorm:"not null" json:"message_thread_key"` // Stored encrypted + Admin string `gorm:"not null" json:"admin"` // Bool if user is admin of thread, stored encrypted + SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted } diff --git a/Backend/Models/Sessions.go b/Backend/Models/Sessions.go new file mode 100644 index 0000000..1f2e215 --- /dev/null +++ b/Backend/Models/Sessions.go @@ -0,0 +1,18 @@ +package Models + +import ( + "time" + + "github.com/gofrs/uuid" +) + +func (s Session) IsExpired() bool { + return s.Expiry.Before(time.Now()) +} + +type Session struct { + Base + UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;"` + User User + Expiry time.Time +} diff --git a/Backend/Models/Users.go b/Backend/Models/Users.go index 1c688c3..0525b52 100644 --- a/Backend/Models/Users.go +++ b/Backend/Models/Users.go @@ -20,4 +20,6 @@ type User struct { ConfirmPassword string `gorm:"-" json:"confirm_password"` AsymmetricPrivateKey string `gorm:"not null" json:"asymmetric_private_key"` // Stored encrypted AsymmetricPublicKey string `gorm:"not null" json:"asymmetric_public_key"` + FriendID string `gorm:"not null" json:"public_user_id"` // Stored encrypted + FriendSymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted } diff --git a/mobile/lib/components/custom_circle_avatar.dart b/mobile/lib/components/custom_circle_avatar.dart new file mode 100644 index 0000000..8492623 --- /dev/null +++ b/mobile/lib/components/custom_circle_avatar.dart @@ -0,0 +1,39 @@ +import 'package:flutter/material.dart'; + +class CustomCircleAvatar extends StatefulWidget { + final String initials; + final String? imagePath; + + const CustomCircleAvatar({ + Key? key, + required this.initials, + this.imagePath, + }) : super(key: key); + + @override + _CustomCircleAvatarState createState() => _CustomCircleAvatarState(); +} + +class _CustomCircleAvatarState extends State{ + + bool _checkLoading = true; + + @override + void initState() { + super.initState(); + if (widget.imagePath != null) { + _checkLoading = false; + } + } + + @override + Widget build(BuildContext context) { + return _checkLoading == true ? + CircleAvatar( + backgroundColor: Colors.grey[300], + child: Text(widget.initials) + ) : CircleAvatar( + backgroundImage: AssetImage(widget.imagePath!) + ); + } +} diff --git a/mobile/lib/main.dart b/mobile/lib/main.dart index 8bad991..0bd22e7 100644 --- a/mobile/lib/main.dart +++ b/mobile/lib/main.dart @@ -1,10 +1,12 @@ import 'package:flutter/material.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; import '/views/main/home.dart'; import '/views/authentication/unauthenticated_landing.dart'; import '/views/authentication/login.dart'; import '/views/authentication/signup.dart'; -void main() { +void main() async { + await dotenv.load(fileName: ".env"); runApp(const MyApp()); } diff --git a/mobile/lib/models/conversations.dart b/mobile/lib/models/conversations.dart index 89a5373..8c4b996 100644 --- a/mobile/lib/models/conversations.dart +++ b/mobile/lib/models/conversations.dart @@ -1,30 +1,116 @@ -const messageTypeSender = 'sender'; -const messageTypeReceiver = 'receiver'; +import 'dart:convert'; +import 'package:pointycastle/export.dart'; +import '/utils/encryption/crypto_utils.dart'; +import '/utils/encryption/aes_helper.dart'; +import '/utils/storage/database.dart'; -class Message { + +Conversation findConversationByDetailId(List conversations, String id) { + for (var conversation in conversations) { + if (conversation.conversationDetailId == id) { + return conversation; + } + } + // Or return `null`. + throw ArgumentError.value(id, "id", "No element with that id"); +} + +class Conversation { String id; - String conversationId; + String userId; + String conversationDetailId; + String messageThreadKey; String symmetricKey; - String data; - String messageType; - String? decryptedData; - Message({ + bool admin; + String name; + String? users; + + Conversation({ required this.id, - required this.conversationId, + required this.userId, + required this.conversationDetailId, + required this.messageThreadKey, required this.symmetricKey, - required this.data, - required this.messageType, - this.decryptedData, + required this.admin, + required this.name, + this.users, }); + + + factory Conversation.fromJson(Map json, RSAPrivateKey privKey) { + var symmetricKeyDecrypted = CryptoUtils.rsaDecrypt( + base64.decode(json['symmetric_key']), + privKey, + ); + + var detailId = AesHelper.aesDecrypt( + symmetricKeyDecrypted, + base64.decode(json['conversation_detail_id']), + ); + + var threadKey = AesHelper.aesDecrypt( + symmetricKeyDecrypted, + base64.decode(json['message_thread_key']), + ); + + var admin = AesHelper.aesDecrypt( + symmetricKeyDecrypted, + base64.decode(json['admin']), + ); + + return Conversation( + id: json['id'], + userId: json['user_id'], + conversationDetailId: detailId, + messageThreadKey: threadKey, + symmetricKey: base64.encode(symmetricKeyDecrypted), + admin: admin == 'true', + name: 'Unknown', + ); + } + + @override + String toString() { + return ''' + + +id: $id +userId: $userId +name: $name +admin: $admin'''; + } + + Map toMap() { + return { + 'id': id, + 'user_id': userId, + 'conversation_detail_id': conversationDetailId, + 'message_thread_key': messageThreadKey, + 'symmetric_key': symmetricKey, + 'admin': admin ? 1 : 0, + 'name': name, + 'users': users, + }; + } } -class Conversation { - String id; - String friendId; - String recentMessageId; - Conversation({ - required this.id, - required this.friendId, - required this.recentMessageId, + +// A method that retrieves all the dogs from the dogs table. +Future> getConversations() async { + final db = await getDatabaseConnection(); + + final List> maps = await db.query('conversations'); + + return List.generate(maps.length, (i) { + return Conversation( + id: maps[i]['id'], + userId: maps[i]['user_id'], + conversationDetailId: maps[i]['conversation_detail_id'], + messageThreadKey: maps[i]['message_thread_key'], + symmetricKey: maps[i]['symmetric_key'], + admin: maps[i]['admin'] == 1, + name: maps[i]['name'], + users: maps[i]['users'], + ); }); } diff --git a/mobile/lib/models/friends.dart b/mobile/lib/models/friends.dart index 8afdcb4..0fcb23c 100644 --- a/mobile/lib/models/friends.dart +++ b/mobile/lib/models/friends.dart @@ -1,32 +1,57 @@ import 'dart:convert'; import "package:pointycastle/export.dart"; import '/utils/encryption/crypto_utils.dart'; +import '/utils/storage/database.dart'; + +Friend findFriendByFriendId(List friends, String id) { + for (var friend in friends) { + if (friend.friendIdDecrypted == id) { + return friend; + } + } + // Or return `null`. + throw ArgumentError.value(id, "id", "No element with that id"); +} class Friend{ String id; String userId; + String? username; String friendId; String friendIdDecrypted; + String friendSymmetricKey; + String friendSymmetricKeyDecrypted; String acceptedAt; Friend({ required this.id, required this.userId, required this.friendId, required this.friendIdDecrypted, + required this.friendSymmetricKey, + required this.friendSymmetricKeyDecrypted, required this.acceptedAt, + this.username }); factory Friend.fromJson(Map json, RSAPrivateKey privKey) { + // TODO: Remove encrypted entries var friendIdDecrypted = CryptoUtils.rsaDecrypt( base64.decode(json['friend_id']), privKey, ); + var friendSymmetricKeyDecrypted = CryptoUtils.rsaDecrypt( + base64.decode(json['symmetric_key']), + privKey, + ); + return Friend( id: json['id'], userId: json['user_id'], friendId: json['friend_id'], friendIdDecrypted: String.fromCharCodes(friendIdDecrypted), + friendSymmetricKey: json['symmetric_key'], + friendSymmetricKeyDecrypted: base64.encode(friendSymmetricKeyDecrypted), acceptedAt: json['accepted_at'], ); } @@ -34,21 +59,46 @@ class Friend{ @override String toString() { return ''' + + id: $id -userId: $userId, -friendId: $friendId, -friendIdDecrypted: $friendIdDecrypted, -accepted_at: $acceptedAt, -'''; +userId: $userId +username: $username +friendIdDecrypted: $friendIdDecrypted +accepted_at: $acceptedAt'''; } Map toMap() { return { 'id': id, 'user_id': userId, + 'username': username, 'friend_id': friendId, 'friend_id_decrypted': friendIdDecrypted, + 'symmetric_key': friendSymmetricKey, + 'symmetric_key_decrypted': friendSymmetricKeyDecrypted, 'accepted_at': acceptedAt, }; } } + + +// A method that retrieves all the dogs from the dogs table. +Future> getFriends() async { + final db = await getDatabaseConnection(); + + final List> maps = await db.query('friends'); + + return List.generate(maps.length, (i) { + return Friend( + id: maps[i]['id'], + userId: maps[i]['user_id'], + friendId: maps[i]['friend_id'], + friendIdDecrypted: maps[i]['friend_id_decrypted'], + friendSymmetricKey: maps[i]['symmetric_key'], + friendSymmetricKeyDecrypted: maps[i]['symmetric_key_decrypted'], + acceptedAt: maps[i]['accepted_at'], + username: maps[i]['username'], + ); + }); +} diff --git a/mobile/lib/models/messages.dart b/mobile/lib/models/messages.dart new file mode 100644 index 0000000..26cb0f4 --- /dev/null +++ b/mobile/lib/models/messages.dart @@ -0,0 +1,20 @@ + +const messageTypeSender = 'sender'; +const messageTypeReceiver = 'receiver'; + +class Message { + String id; + String symmetricKey; + String messageThreadKey; + String data; + String senderId; + String senderUsername; + Message({ + required this.id, + required this.symmetricKey, + required this.messageThreadKey, + required this.data, + required this.senderId, + required this.senderUsername, + }); +} diff --git a/mobile/lib/utils/encryption/aes_helper.dart b/mobile/lib/utils/encryption/aes_helper.dart index 04f2ece..adad897 100644 --- a/mobile/lib/utils/encryption/aes_helper.dart +++ b/mobile/lib/utils/encryption/aes_helper.dart @@ -60,9 +60,16 @@ class AesHelper { return Uint8List(len)..setRange(0, len, src); } - static String aesEncrypt(String password, Uint8List plaintext, + static String aesEncrypt(dynamic password, Uint8List plaintext, {String mode = cbcMode}) { - Uint8List derivedKey = deriveKey(password); + + Uint8List derivedKey; + if (password is String) { + derivedKey = deriveKey(password); + } else { + derivedKey = password; + } + KeyParameter keyParam = KeyParameter(derivedKey); BlockCipher aes = AESEngine(); @@ -93,9 +100,16 @@ class AesHelper { return base64.encode(cipherIvBytes); } - static String aesDecrypt(String password, Uint8List ciphertext, + static String aesDecrypt(dynamic password, Uint8List ciphertext, {String mode = cbcMode}) { - Uint8List derivedKey = deriveKey(password); + + Uint8List derivedKey; + if (password is String) { + derivedKey = deriveKey(password); + } else { + derivedKey = password; + } + KeyParameter keyParam = KeyParameter(derivedKey); BlockCipher aes = AESEngine(); diff --git a/mobile/lib/utils/storage/conversations.dart b/mobile/lib/utils/storage/conversations.dart new file mode 100644 index 0000000..b2c5266 --- /dev/null +++ b/mobile/lib/utils/storage/conversations.dart @@ -0,0 +1,79 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:pointycastle/export.dart'; +import 'package:sqflite/sqflite.dart'; +import '/models/conversations.dart'; +import '/utils/storage/database.dart'; +import '/utils/storage/session_cookie.dart'; +import '/utils/storage/encryption_keys.dart'; +import '/utils/encryption/aes_helper.dart'; + +Future updateConversations() async { + RSAPrivateKey privKey = await getPrivateKey(); + + var resp = await http.get( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), + headers: { + 'cookie': await getSessionCookie(), + } + ); + + if (resp.statusCode != 200) { + throw Exception(resp.body); + } + + List conversations = []; + List conversationsDetailIds = []; + + List conversationsJson = jsonDecode(resp.body); + + for (var i = 0; i < conversationsJson.length; i++) { + Conversation conversation = Conversation.fromJson( + conversationsJson[i] as Map, + privKey, + ); + conversations.add(conversation); + conversationsDetailIds.add(conversation.conversationDetailId); + } + + Map params = {}; + params['conversation_detail_ids'] = conversationsDetailIds.join(','); + var uri = Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversation_details'); + uri = uri.replace(queryParameters: params); + + resp = await http.get( + uri, + headers: { + 'cookie': await getSessionCookie(), + } + ); + + if (resp.statusCode != 200) { + throw Exception(resp.body); + } + + final db = await getDatabaseConnection(); + + List conversationsDetailsJson = jsonDecode(resp.body); + for (var i = 0; i < conversationsDetailsJson.length; i++) { + var conversationDetailJson = conversationsDetailsJson[i] as Map; + var conversation = findConversationByDetailId(conversations, conversationDetailJson['id']); + + conversation.name = AesHelper.aesDecrypt( + base64.decode(conversation.symmetricKey), + base64.decode(conversationDetailJson['name']), + ); + + conversation.users = AesHelper.aesDecrypt( + base64.decode(conversation.symmetricKey), + base64.decode(conversationDetailJson['users']), + ); + + await db.insert( + 'conversations', + conversation.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } +} diff --git a/mobile/lib/utils/storage/database.dart b/mobile/lib/utils/storage/database.dart index 0b306c4..3de37f6 100644 --- a/mobile/lib/utils/storage/database.dart +++ b/mobile/lib/utils/storage/database.dart @@ -6,29 +6,44 @@ import 'package:sqflite/sqflite.dart'; Future getDatabaseConnection() async { WidgetsFlutterBinding.ensureInitialized(); + final path = join(await getDatabasesPath(), 'envelope.db'); + final database = openDatabase( - // Set the path to the database. Note: Using the `join` function from the - // `path` package is best practice to ensure the path is correctly - // constructed for each platform. - join(await getDatabasesPath(), 'envelope.db'), - // When the database is first created, create a table to store dogs. - onCreate: (db, version) { - // Run the CREATE TABLE statement on the database. - return db.execute( - ''' - CREATE TABLE IF NOT EXISTS friends( - id BLOB PRIMARY KEY, - user_id BLOB, - friend_id BLOB, - friend_id_decrypted BLOB, - accepted_at TEXT - ); - ''', - ); - }, - // Set the version. This executes the onCreate function and provides a - // path to perform database upgrades and downgrades. - version: 1, + path, + // TODO: remove friend_id_decrypted and symmetric_key_decrypted + onCreate: (db, version) async { + await db.execute( + ''' + CREATE TABLE IF NOT EXISTS friends( + id TEXT PRIMARY KEY, + user_id TEXT, + username TEXT, + friend_id TEXT, + friend_id_decrypted TEXT, + symmetric_key TEXT, + symmetric_key_decrypted TEXT, + accepted_at TEXT + ); + '''); + + // TODO: Change users to use its own table, as it is a json blob + await db.execute( + ''' + CREATE TABLE IF NOT EXISTS conversations( + id TEXT PRIMARY KEY, + user_id TEXT, + conversation_detail_id TEXT, + message_thread_key TEXT, + symmetric_key TEXT, + admin INTEGER, + name TEXT, + users TEXT + ); + '''); + }, + // Set the version. This executes the onCreate function and provides a + // path to perform database upgrades and downgrades. + version: 1, ); return database; diff --git a/mobile/lib/utils/storage/friends.dart b/mobile/lib/utils/storage/friends.dart index 3e564ae..b0374a2 100644 --- a/mobile/lib/utils/storage/friends.dart +++ b/mobile/lib/utils/storage/friends.dart @@ -1,16 +1,19 @@ -// import 'package:sqflite/sqflite.dart'; -import 'package:http/http.dart' as http; import 'dart:convert'; -import "package:pointycastle/export.dart"; +import 'package:http/http.dart' as http; +import 'package:pointycastle/export.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; import '/models/friends.dart'; +import '/utils/storage/database.dart'; import '/utils/storage/encryption_keys.dart'; import '/utils/storage/session_cookie.dart'; +import '/utils/encryption/aes_helper.dart'; -void getFriends() async { +Future updateFriends() async { RSAPrivateKey privKey = await getPrivateKey(); - final resp = await http.get( - Uri.parse('http://192.168.1.5:8080/api/v1/auth/friends'), + var resp = await http.get( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friend_requests'), headers: { 'cookie': await getSessionCookie(), } @@ -19,20 +22,56 @@ void getFriends() async { if (resp.statusCode != 200) { throw Exception(resp.body); } - + List friends = []; + List friendIds = []; - List friendsJson = jsonDecode(resp.body); + List friendsRequestJson = jsonDecode(resp.body); - for (var i = 0; i < friendsJson.length; i++) { + for (var i = 0; i < friendsRequestJson.length; i++) { friends.add( Friend.fromJson( - friendsJson[i] as Map, + friendsRequestJson[i] as Map, privKey, ) ); + + friendIds.add(friends[i].friendIdDecrypted); + } + + Map params = {}; + params['friend_ids'] = friendIds.join(','); + var uri = Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friends'); + uri = uri.replace(queryParameters: params); + + resp = await http.get( + uri, + headers: { + 'cookie': await getSessionCookie(), + } + ); + + if (resp.statusCode != 200) { + throw Exception(resp.body); } - print(friends); + final db = await getDatabaseConnection(); + + List friendsJson = jsonDecode(resp.body); + for (var i = 0; i < friendsJson.length; i++) { + var friendJson = friendsJson[i] as Map; + var friend = findFriendByFriendId(friends, friendJson['id']); + + friend.username = AesHelper.aesDecrypt( + base64.decode(friend.friendSymmetricKeyDecrypted), + base64.decode(friendJson['username']), + ); + + await db.insert( + 'friends', + friend.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } } diff --git a/mobile/lib/views/authentication/login.dart b/mobile/lib/views/authentication/login.dart index 806729b..29075d1 100644 --- a/mobile/lib/views/authentication/login.dart +++ b/mobile/lib/views/authentication/login.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; import '/utils/encryption/crypto_utils.dart'; import '/utils/encryption/aes_helper.dart'; import '/utils/storage/encryption_keys.dart'; @@ -32,7 +33,7 @@ class LoginResponse { Future login(context, String username, String password) async { final resp = await http.post( - Uri.parse('http://192.168.1.5:8080/api/v1/login'), + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/login'), headers: { 'Content-Type': 'application/json; charset=UTF-8', }, @@ -117,7 +118,7 @@ class _LoginWidgetState extends State { minimumSize: const Size.fromHeight(50), padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), textStyle: const TextStyle( - fontSize: 20, + fontSize: 20, fontWeight: FontWeight.bold, color: Colors.red, ), diff --git a/mobile/lib/views/main/conversation_detail.dart b/mobile/lib/views/main/conversation_detail.dart index 8732f80..4ed7182 100644 --- a/mobile/lib/views/main/conversation_detail.dart +++ b/mobile/lib/views/main/conversation_detail.dart @@ -1,50 +1,21 @@ import 'package:flutter/material.dart'; import '/models/conversations.dart'; +import '/models/messages.dart'; class ConversationDetail extends StatefulWidget{ - const ConversationDetail({Key? key}) : super(key: key); + final Conversation conversation; + const ConversationDetail({ + Key? key, + required this.conversation, + }) : super(key: key); - @override - _ConversationDetailState createState() => _ConversationDetailState(); + @override + _ConversationDetailState createState() => _ConversationDetailState(); } class _ConversationDetailState extends State { - Conversation conversation = Conversation( - id: '777', - friendId: 'abc', - recentMessageId: '111', - ); - - List messages = [ - Message( - id: '444', - conversationId: '777', - symmetricKey: '', - data: 'This is a message', - messageType: messageTypeSender, - ), - Message( - id: '444', - conversationId: '777', - symmetricKey: '', - data: 'This is a message', - messageType: messageTypeReceiver, - ), - Message( - id: '444', - conversationId: '777', - symmetricKey: '', - data: 'This is a message', - messageType: messageTypeSender - ), - Message( - id: '444', - conversationId: '777', - symmetricKey: '', - data: 'This is a message', - messageType: messageTypeReceiver, - ), - ]; + List messages = [ + ]; @override Widget build(BuildContext context) { @@ -69,8 +40,13 @@ class _ConversationDetailState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, - children: const [ - Text("Kriss Benwat",style: TextStyle( fontSize: 16 ,fontWeight: FontWeight.w600),), + children: [ + Text( + widget.conversation.name, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600), + ), ], ), ), @@ -91,11 +67,13 @@ class _ConversationDetailState extends State { return Container( padding: const EdgeInsets.only(left: 14,right: 14,top: 10,bottom: 10), child: Align( - alignment: (messages[index].messageType == messageTypeReceiver ? Alignment.topLeft:Alignment.topRight), + // alignment: (messages[index].messageType == messageTypeReceiver ? Alignment.topLeft:Alignment.topRight), + alignment: Alignment.topLeft, // TODO: compare senderId to current user id child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), - color: (messages[index].messageType == messageTypeReceiver ? Colors.grey.shade200:Colors.blue[200]), + // color: (messages[index].messageType == messageTypeReceiver ? Colors.grey.shade200:Colors.blue[200]), + color: (true ? Colors.grey.shade200:Colors.blue[200]), ), padding: const EdgeInsets.all(16), child: Text(messages[index].data, style: const TextStyle(fontSize: 15)), diff --git a/mobile/lib/views/main/conversation_list.dart b/mobile/lib/views/main/conversation_list.dart index b47e678..5a5ca08 100644 --- a/mobile/lib/views/main/conversation_list.dart +++ b/mobile/lib/views/main/conversation_list.dart @@ -10,41 +10,35 @@ class ConversationList extends StatefulWidget { } class _ConversationListState extends State { - List messages = [ - Message( - id: '123', - conversationId: 'xyz', - data: '', - symmetricKey: '', - messageType: 'reciever', - ), - ]; + List conversations = []; - List friends = [ - Conversation( - id: 'xyz', - friendId: 'abc', - recentMessageId: '123', - ), - ]; + @override + void initState() { + super.initState(); + fetchConversations(); + } + + void fetchConversations() async { + conversations = await getConversations(); + setState(() {}); + } Widget list() { - if (friends.isEmpty) { + if (conversations.isEmpty) { return const Center( child: Text('No Conversations'), ); } return ListView.builder( - itemCount: friends.length, + itemCount: conversations.length, shrinkWrap: true, padding: const EdgeInsets.only(top: 16), physics: const NeverScrollableScrollPhysics(), itemBuilder: (context, i) { return ConversationListItem( - id: friends[i].id, - username: 'Test', + conversation: conversations[i], ); }, ); diff --git a/mobile/lib/views/main/conversation_list_item.dart b/mobile/lib/views/main/conversation_list_item.dart index e8b6c23..78b1d55 100644 --- a/mobile/lib/views/main/conversation_list_item.dart +++ b/mobile/lib/views/main/conversation_list_item.dart @@ -1,60 +1,66 @@ +import 'package:Envelope/components/custom_circle_avatar.dart'; +import 'package:Envelope/models/conversations.dart'; import 'package:flutter/material.dart'; import '/views/main/conversation_detail.dart'; class ConversationListItem extends StatefulWidget{ - final String id; - final String username; - const ConversationListItem({ - Key? key, - required this.id, - required this.username, - }) : super(key: key); + final Conversation conversation; + const ConversationListItem({ + Key? key, + required this.conversation, + }) : super(key: key); - @override - _ConversationListItemState createState() => _ConversationListItemState(); + @override + _ConversationListItemState createState() => _ConversationListItemState(); } class _ConversationListItemState extends State { - @override - Widget build(BuildContext context) { - return GestureDetector( - onTap: () { - Navigator.push(context, MaterialPageRoute(builder: (context){ - return ConversationDetail(); - })); - }, - child: Container( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), - child: Row( - children: [ - Expanded( - child: Row( - children: [ - // CircleAvatar( - // backgroundImage: NetworkImage(widget.imageUrl), - // maxRadius: 30, - // ), - //const SizedBox(width: 16), - Expanded( - child: Container( - color: Colors.transparent, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(widget.username, style: const TextStyle(fontSize: 16)), - const SizedBox(height: 6), - //Text(widget.messageText,style: TextStyle(fontSize: 13,color: Colors.grey.shade600, fontWeight: widget.isMessageRead?FontWeight.bold:FontWeight.normal),), - const Divider(), - ], - ), - ), - ), - ], - ), - ), - ], - ), - ), + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: () { + Navigator.push(context, MaterialPageRoute(builder: (context){ + return ConversationDetail( + conversation: widget.conversation, + ); + })); + }, + child: Container( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CustomCircleAvatar( + initials: widget.conversation.name[0].toUpperCase(), + imagePath: null, + ), + const SizedBox(width: 16), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: Container( + color: Colors.transparent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.conversation.name, + style: const TextStyle(fontSize: 16) + ), + //Text(widget.messageText,style: TextStyle(fontSize: 13,color: Colors.grey.shade600, fontWeight: widget.isMessageRead?FontWeight.bold:FontWeight.normal),), + ], + ), + ), + ), + ), + ], + ), + ), + ], + ), + ), ); - } + } } diff --git a/mobile/lib/views/main/friend_list.dart b/mobile/lib/views/main/friend_list.dart index 9299cb0..2437672 100644 --- a/mobile/lib/views/main/friend_list.dart +++ b/mobile/lib/views/main/friend_list.dart @@ -1,7 +1,6 @@ import 'package:flutter/material.dart'; import '/models/friends.dart'; import '/views/main/friend_list_item.dart'; -import '/utils/storage/friends.dart'; class FriendList extends StatefulWidget { const FriendList({Key? key}) : super(key: key); @@ -15,10 +14,14 @@ class _FriendListState extends State { @override void initState() { - getFriends(); super.initState(); + fetchFriends(); } + void fetchFriends() async { + friends = await getFriends(); + setState(() {}); + } Widget list() { @@ -36,7 +39,7 @@ class _FriendListState extends State { itemBuilder: (context, i) { return FriendListItem( id: friends[i].id, - username: 'test', + username: friends[i].username!, ); }, ); diff --git a/mobile/lib/views/main/friend_list_item.dart b/mobile/lib/views/main/friend_list_item.dart index 42c5215..6fbc26b 100644 --- a/mobile/lib/views/main/friend_list_item.dart +++ b/mobile/lib/views/main/friend_list_item.dart @@ -1,56 +1,67 @@ +import 'package:Envelope/components/custom_circle_avatar.dart'; import 'package:flutter/material.dart'; class FriendListItem extends StatefulWidget{ - final String id; - final String username; - const FriendListItem({ - Key? key, - required this.id, - required this.username, - }) : super(key: key); + final String id; + final String username; + final String? imagePath; + const FriendListItem({ + Key? key, + required this.id, + required this.username, + this.imagePath, + }) : super(key: key); - @override - _FriendListItemState createState() => _FriendListItemState(); + @override + _FriendListItemState createState() => _FriendListItemState(); } class _FriendListItemState extends State { - @override - Widget build(BuildContext context) { - return GestureDetector( - onTap: (){ - }, - child: Container( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), - child: Row( - children: [ - Expanded( - child: Row( - children: [ - // CircleAvatar( - // backgroundImage: NetworkImage(widget.imageUrl), - // maxRadius: 30, - // ), - //const SizedBox(width: 16), - Expanded( - child: Container( - color: Colors.transparent, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(widget.username, style: const TextStyle(fontSize: 16)), - const SizedBox(height: 6), - //Text(widget.messageText,style: TextStyle(fontSize: 13,color: Colors.grey.shade600, fontWeight: widget.isMessageRead?FontWeight.bold:FontWeight.normal),), - const Divider(), - ], - ), - ), - ), - ], - ), - ), - ], - ), - ), + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: (){ + }, + child: Container( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CustomCircleAvatar( + initials: widget.username[0].toUpperCase(), + imagePath: widget.imagePath, + ), + const SizedBox(width: 16), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: Container( + color: Colors.transparent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(widget.username, style: const TextStyle(fontSize: 16)), + // Text( + // widget.messageText, + // style: TextStyle(fontSize: 13, + // color: Colors.grey.shade600, + // fontWeight: widget.isMessageRead?FontWeight.bold:FontWeight.normal + // ), + // ), + ], + ), + ), + ), + ), + ], + ), + ), + ], + ), + ), ); - } + } } diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index 85b3ecc..fcf9900 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -3,71 +3,80 @@ import 'package:shared_preferences/shared_preferences.dart'; import '/views/main/conversation_list.dart'; import '/views/main/friend_list.dart'; import '/views/main/profile.dart'; +import '/utils/storage/friends.dart'; +import '/utils/storage/conversations.dart'; class Home extends StatefulWidget { - const Home({Key? key}) : super(key: key); + const Home({Key? key}) : super(key: key); - @override - State createState() => _HomeState(); + @override + State createState() => _HomeState(); } class _HomeState extends State { - @override - void initState() { - checkLogin(); - super.initState(); - } + @override + void initState() { + super.initState(); + updateData(); + } + + void updateData() async { + await checkLogin(); + await updateFriends(); + await updateConversations(); + } - Future checkLogin() async { - SharedPreferences preferences = await SharedPreferences.getInstance(); - if (preferences.getBool('islogin') != true) { - Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); - } + // TODO: Do server GET check here + Future checkLogin() async { + SharedPreferences preferences = await SharedPreferences.getInstance(); + if (preferences.getBool('islogin') != true) { + Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); } + } - int _selectedIndex = 0; - static const List _widgetOptions = [ - ConversationList(), - FriendList(), - Profile(), - ]; + int _selectedIndex = 0; + static const List _widgetOptions = [ + ConversationList(), + FriendList(), + Profile(), + ]; - void _onItemTapped(int index) { - setState(() { - _selectedIndex = index; - }); - } + void _onItemTapped(int index) { + setState(() { + _selectedIndex = index; + }); + } - @override - Widget build(BuildContext context) { - return WillPopScope( - onWillPop: () async => false, - child: Scaffold( - body: _widgetOptions.elementAt(_selectedIndex), - bottomNavigationBar: BottomNavigationBar( - currentIndex: _selectedIndex, - onTap: _onItemTapped, - selectedItemColor: Colors.red, - unselectedItemColor: Colors.grey.shade600, - selectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600), - unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600), - type: BottomNavigationBarType.fixed, - items: const [ - BottomNavigationBarItem( - icon: Icon(Icons.message), - label: "Chats", - ), - BottomNavigationBarItem( - icon: Icon(Icons.group_work), - label: "Friends", - ), - BottomNavigationBarItem( - icon: Icon(Icons.account_box), - label: "Profile", - ), - ], - ), - ), - ); - } + @override + Widget build(BuildContext context) { + return WillPopScope( + onWillPop: () async => false, + child: Scaffold( + body: _widgetOptions.elementAt(_selectedIndex), + bottomNavigationBar: BottomNavigationBar( + currentIndex: _selectedIndex, + onTap: _onItemTapped, + selectedItemColor: Colors.red, + unselectedItemColor: Colors.grey.shade600, + selectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600), + unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600), + type: BottomNavigationBarType.fixed, + items: const [ + BottomNavigationBarItem( + icon: Icon(Icons.message), + label: "Chats", + ), + BottomNavigationBarItem( + icon: Icon(Icons.group_work), + label: "Friends", + ), + BottomNavigationBarItem( + icon: Icon(Icons.account_box), + label: "Profile", + ), + ], + ), + ), + ); + } } diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock index e09490d..c7d9286 100644 --- a/mobile/pubspec.lock +++ b/mobile/pubspec.lock @@ -90,6 +90,13 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_dotenv: + dependency: "direct main" + description: + name: flutter_dotenv + url: "https://pub.dartlang.org" + source: hosted + version: "5.0.2" flutter_lints: dependency: "direct dev" description: diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml index 86d417a..9dffd90 100644 --- a/mobile/pubspec.yaml +++ b/mobile/pubspec.yaml @@ -19,6 +19,7 @@ dependencies: shared_preferences: ^2.0.15 sqflite: ^2.0.2 path: 1.8.1 + flutter_dotenv: ^5.0.2 dev_dependencies: flutter_test: @@ -27,6 +28,9 @@ dev_dependencies: flutter_lints: ^1.0.0 flutter: - uses-material-design: true + assets: + - .env + + -- 2.17.1 From d8535fdfc7248e0000348ab70011ac1fb262ed99 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Sun, 26 Jun 2022 19:21:42 +0930 Subject: [PATCH 08/24] Message conversations syncing to device --- Backend/Api/Auth/Login.go | 14 +- Backend/Api/Messages/MessageThread.go | 19 +- Backend/Api/Routes.go | 2 +- Backend/Database/Messages.go | 13 + Backend/Database/Seeder/MessageSeeder.go | 12 +- Backend/Models/Messages.go | 7 +- mobile/lib/models/conversations.dart | 1 - mobile/lib/models/friends.dart | 170 +++++---- mobile/lib/models/messages.dart | 116 +++++- mobile/lib/utils/storage/database.dart | 21 +- mobile/lib/utils/storage/friends.dart | 4 +- mobile/lib/utils/storage/messages.dart | 76 ++++ mobile/lib/views/authentication/login.dart | 349 +++++++++--------- .../unauthenticated_landing.dart | 142 +++---- .../lib/views/main/conversation_detail.dart | 259 ++++++++----- mobile/lib/views/main/conversation_list.dart | 1 + .../views/main/conversation_list_item.dart | 1 + mobile/lib/views/main/home.dart | 2 + mobile/lib/views/main/profile.dart | 2 + 19 files changed, 751 insertions(+), 460 deletions(-) create mode 100644 mobile/lib/utils/storage/messages.dart diff --git a/Backend/Api/Auth/Login.go b/Backend/Api/Auth/Login.go index 39c374f..b91d133 100644 --- a/Backend/Api/Auth/Login.go +++ b/Backend/Api/Auth/Login.go @@ -19,9 +19,10 @@ type loginResponse struct { Message string `json:"message"` AsymmetricPublicKey string `json:"asymmetric_public_key"` AsymmetricPrivateKey string `json:"asymmetric_private_key"` + UserID string `json:"user_id"` } -func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey string) { +func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey string, userId string) { var ( status string = "error" returnJson []byte @@ -36,6 +37,7 @@ func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey Message: message, AsymmetricPublicKey: pubKey, AsymmetricPrivateKey: privKey, + UserID: userId, }, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) @@ -59,21 +61,22 @@ func Login(w http.ResponseWriter, r *http.Request) { err = json.NewDecoder(r.Body).Decode(&creds) if err != nil { - makeLoginResponse(w, http.StatusInternalServerError, "An error occurred", "", "") + makeLoginResponse(w, http.StatusInternalServerError, "An error occurred", "", "", "") return } userData, err = Database.GetUserByUsername(creds.Username) if err != nil { - makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "") + makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", "") return } if !CheckPasswordHash(creds.Password, userData.Password) { - makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "") + makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", "") return } + // TODO: Revisit before production expiresAt = time.Now().Add(12 * time.Hour) session = Models.Session{ @@ -83,7 +86,7 @@ func Login(w http.ResponseWriter, r *http.Request) { err = Database.CreateSession(&session) if err != nil { - makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "") + makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", "") return } @@ -99,5 +102,6 @@ func Login(w http.ResponseWriter, r *http.Request) { "Successfully logged in", userData.AsymmetricPublicKey, userData.AsymmetricPrivateKey, + userData.ID.String(), ) } diff --git a/Backend/Api/Messages/MessageThread.go b/Backend/Api/Messages/MessageThread.go index 3fef1d3..7eb3b27 100644 --- a/Backend/Api/Messages/MessageThread.go +++ b/Backend/Api/Messages/MessageThread.go @@ -6,17 +6,18 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + "github.com/gorilla/mux" ) -func ConversationDetail(w http.ResponseWriter, r *http.Request) { +func Messages(w http.ResponseWriter, r *http.Request) { var ( - conversationDetail Models.ConversationDetail - urlVars map[string]string - threadKey string - returnJson []byte - ok bool - err error + messages []Models.Message + urlVars map[string]string + threadKey string + returnJson []byte + ok bool + err error ) urlVars = mux.Vars(r) @@ -26,13 +27,13 @@ func ConversationDetail(w http.ResponseWriter, r *http.Request) { return } - conversationDetail, err = Database.GetConversationDetailById(threadKey) + messages, err = Database.GetMessagesByThreadKey(threadKey) if !ok { http.Error(w, "Not Found", http.StatusNotFound) return } - returnJson, err = json.MarshalIndent(conversationDetail, "", " ") + returnJson, err = json.MarshalIndent(messages, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) return diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index d4c2cdb..651578e 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -72,5 +72,5 @@ func InitApiEndpoints(router *mux.Router) { // authApi.HandleFunc("/user/{userID}/request", Friends.FriendRequest).Methods("POST") // Define routes for messages - authApi.HandleFunc("/messages/{threadKey}", Messages.ConversationDetail).Methods("GET") + authApi.HandleFunc("/messages/{threadKey}", Messages.Messages).Methods("GET") } diff --git a/Backend/Database/Messages.go b/Backend/Database/Messages.go index 866cc40..4c1c352 100644 --- a/Backend/Database/Messages.go +++ b/Backend/Database/Messages.go @@ -20,6 +20,19 @@ func GetMessageById(id string) (Models.Message, error) { return message, err } +func GetMessagesByThreadKey(threadKey string) ([]Models.Message, error) { + var ( + messages []Models.Message + err error + ) + + err = DB.Preload(clause.Associations). + Find(&messages, "message_thread_key = ?", threadKey). + Error + + return messages, err +} + func CreateMessage(message *Models.Message) error { var ( err error diff --git a/Backend/Database/Seeder/MessageSeeder.go b/Backend/Database/Seeder/MessageSeeder.go index 06cd78e..aba744a 100644 --- a/Backend/Database/Seeder/MessageSeeder.go +++ b/Backend/Database/Seeder/MessageSeeder.go @@ -11,7 +11,7 @@ import ( ) func seedMessage( - primaryUser Models.User, + primaryUser, secondaryUser Models.User, primaryUserThreadKey, secondaryUserThreadKey string, thread Models.ConversationDetail, i int, @@ -38,11 +38,18 @@ func seedMessage( panic(err) } - senderIdCiphertext, err = key.aesEncrypt(primaryUser.ID.Bytes()) + senderIdCiphertext, err = key.aesEncrypt([]byte(primaryUser.ID.String())) if err != nil { panic(err) } + if i%2 == 0 { + senderIdCiphertext, err = key.aesEncrypt([]byte(secondaryUser.ID.String())) + if err != nil { + panic(err) + } + } + messageData = Models.MessageData{ Data: base64.StdEncoding.EncodeToString(dataCiphertext), SenderID: base64.StdEncoding.EncodeToString(senderIdCiphertext), @@ -240,6 +247,7 @@ func SeedMessages() { for i = 0; i <= 20; i++ { err = seedMessage( primaryUser, + secondaryUser, primaryUserThreadKey, secondaryUserThreadKey, thread, diff --git a/Backend/Models/Messages.go b/Backend/Models/Messages.go index 6c3d5a3..d9f309c 100644 --- a/Backend/Models/Messages.go +++ b/Backend/Models/Messages.go @@ -1,6 +1,10 @@ package Models -import "github.com/gofrs/uuid" +import ( + "time" + + "github.com/gofrs/uuid" +) // TODO: Add support for images type MessageData struct { @@ -15,6 +19,7 @@ type Message struct { MessageData MessageData `json:"message_data"` SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted MessageThreadKey string `gorm:"not null" json:"message_thread_key"` + CreatedAt time.Time `gorm:"not null" json:"created_at"` } // TODO: Rename to ConversationDetails diff --git a/mobile/lib/models/conversations.dart b/mobile/lib/models/conversations.dart index 8c4b996..2963b6b 100644 --- a/mobile/lib/models/conversations.dart +++ b/mobile/lib/models/conversations.dart @@ -4,7 +4,6 @@ import '/utils/encryption/crypto_utils.dart'; import '/utils/encryption/aes_helper.dart'; import '/utils/storage/database.dart'; - Conversation findConversationByDetailId(List conversations, String id) { for (var conversation in conversations) { if (conversation.conversationDetailId == id) { diff --git a/mobile/lib/models/friends.dart b/mobile/lib/models/friends.dart index 0fcb23c..3bd1b1e 100644 --- a/mobile/lib/models/friends.dart +++ b/mobile/lib/models/friends.dart @@ -4,101 +4,117 @@ import '/utils/encryption/crypto_utils.dart'; import '/utils/storage/database.dart'; Friend findFriendByFriendId(List friends, String id) { - for (var friend in friends) { - if (friend.friendIdDecrypted == id) { - return friend; - } + for (var friend in friends) { + if (friend.friendId == id) { + return friend; } + } // Or return `null`. throw ArgumentError.value(id, "id", "No element with that id"); } class Friend{ - String id; - String userId; - String? username; - String friendId; - String friendIdDecrypted; - String friendSymmetricKey; - String friendSymmetricKeyDecrypted; - String acceptedAt; - Friend({ - required this.id, - required this.userId, - required this.friendId, - required this.friendIdDecrypted, - required this.friendSymmetricKey, - required this.friendSymmetricKeyDecrypted, - required this.acceptedAt, - this.username - }); + String id; + String userId; + String? username; + String friendId; + String friendSymmetricKey; + String acceptedAt; + Friend({ + required this.id, + required this.userId, + required this.friendId, + required this.friendSymmetricKey, + required this.acceptedAt, + this.username + }); - factory Friend.fromJson(Map json, RSAPrivateKey privKey) { - // TODO: Remove encrypted entries - var friendIdDecrypted = CryptoUtils.rsaDecrypt( - base64.decode(json['friend_id']), - privKey, - ); + factory Friend.fromJson(Map json, RSAPrivateKey privKey) { + var friendIdDecrypted = CryptoUtils.rsaDecrypt( + base64.decode(json['friend_id']), + privKey, + ); - var friendSymmetricKeyDecrypted = CryptoUtils.rsaDecrypt( - base64.decode(json['symmetric_key']), - privKey, - ); + var friendSymmetricKeyDecrypted = CryptoUtils.rsaDecrypt( + base64.decode(json['symmetric_key']), + privKey, + ); - return Friend( - id: json['id'], - userId: json['user_id'], - friendId: json['friend_id'], - friendIdDecrypted: String.fromCharCodes(friendIdDecrypted), - friendSymmetricKey: json['symmetric_key'], - friendSymmetricKeyDecrypted: base64.encode(friendSymmetricKeyDecrypted), - acceptedAt: json['accepted_at'], - ); - } + return Friend( + id: json['id'], + userId: json['user_id'], + friendId: String.fromCharCodes(friendIdDecrypted), + friendSymmetricKey: base64.encode(friendSymmetricKeyDecrypted), + acceptedAt: json['accepted_at'], + ); + } - @override - String toString() { - return ''' + @override + String toString() { + return ''' -id: $id -userId: $userId -username: $username -friendIdDecrypted: $friendIdDecrypted -accepted_at: $acceptedAt'''; - } + id: $id + userId: $userId + username: $username + friendId: $friendId + accepted_at: $acceptedAt'''; + } - Map toMap() { - return { - 'id': id, - 'user_id': userId, - 'username': username, - 'friend_id': friendId, - 'friend_id_decrypted': friendIdDecrypted, - 'symmetric_key': friendSymmetricKey, - 'symmetric_key_decrypted': friendSymmetricKeyDecrypted, - 'accepted_at': acceptedAt, - }; - } + Map toMap() { + return { + 'id': id, + 'user_id': userId, + 'username': username, + 'friend_id': friendId, + 'symmetric_key': friendSymmetricKey, + 'accepted_at': acceptedAt, + }; + } } // A method that retrieves all the dogs from the dogs table. Future> getFriends() async { - final db = await getDatabaseConnection(); + final db = await getDatabaseConnection(); - final List> maps = await db.query('friends'); + final List> maps = await db.query('friends'); - return List.generate(maps.length, (i) { - return Friend( - id: maps[i]['id'], - userId: maps[i]['user_id'], - friendId: maps[i]['friend_id'], - friendIdDecrypted: maps[i]['friend_id_decrypted'], - friendSymmetricKey: maps[i]['symmetric_key'], - friendSymmetricKeyDecrypted: maps[i]['symmetric_key_decrypted'], - acceptedAt: maps[i]['accepted_at'], - username: maps[i]['username'], - ); - }); + return List.generate(maps.length, (i) { + return Friend( + id: maps[i]['id'], + userId: maps[i]['user_id'], + friendId: maps[i]['friend_id'], + friendSymmetricKey: maps[i]['symmetric_key'], + acceptedAt: maps[i]['accepted_at'], + username: maps[i]['username'], + ); + }); } + +// Future getFriendByUserId(String userId) async { +// final db = await getDatabaseConnection(); +// +// List whereArguments = [userId]; +// +// final List> maps = await db.query( +// 'friends', +// where: 'friend_id = ?', +// whereArgs: whereArguments, +// ); +// +// print(userId); +// +// if (maps.length != 1) { +// throw ArgumentError('Invalid user id'); +// } +// +// return Friend( +// id: maps[0]['id'], +// userId: maps[0]['user_id'], +// friendId: maps[0]['friend_id'], +// friendSymmetricKey: maps[0]['symmetric_key'], +// acceptedAt: maps[0]['accepted_at'], +// username: maps[0]['username'], +// ); +// } diff --git a/mobile/lib/models/messages.dart b/mobile/lib/models/messages.dart index 26cb0f4..4fc3728 100644 --- a/mobile/lib/models/messages.dart +++ b/mobile/lib/models/messages.dart @@ -1,20 +1,108 @@ +import 'dart:convert'; +import 'package:pointycastle/export.dart'; +import '/utils/encryption/crypto_utils.dart'; +import '/utils/encryption/aes_helper.dart'; +import '/utils/storage/database.dart'; +import '/models/friends.dart'; const messageTypeSender = 'sender'; const messageTypeReceiver = 'receiver'; class Message { - String id; - String symmetricKey; - String messageThreadKey; - String data; - String senderId; - String senderUsername; - Message({ - required this.id, - required this.symmetricKey, - required this.messageThreadKey, - required this.data, - required this.senderId, - required this.senderUsername, - }); + String id; + String symmetricKey; + String messageThreadKey; + String data; + String senderId; + String senderUsername; + String createdAt; + Message({ + required this.id, + required this.symmetricKey, + required this.messageThreadKey, + required this.data, + required this.senderId, + required this.senderUsername, + required this.createdAt, + }); + + + factory Message.fromJson(Map json, RSAPrivateKey privKey) { + var symmetricKey = CryptoUtils.rsaDecrypt( + base64.decode(json['symmetric_key']), + privKey, + ); + + var data = AesHelper.aesDecrypt( + symmetricKey, + base64.decode(json['message_data']['data']), + ); + + var senderId = AesHelper.aesDecrypt( + symmetricKey, + base64.decode(json['message_data']['sender_id']), + ); + + return Message( + id: json['id'], + messageThreadKey: json['message_thread_key'], + symmetricKey: base64.encode(symmetricKey), + data: data, + senderId: senderId, + senderUsername: 'Unknown', // TODO + createdAt: json['created_at'], + ); + } + + @override + String toString() { + return ''' + + + id: $id + data: $data + senderId: $senderId + senderUsername: $senderUsername + createdAt: $createdAt +'''; + } + + Map toMap() { + return { + 'id': id, + 'message_thread_key': messageThreadKey, + 'symmetric_key': symmetricKey, + 'data': data, + 'sender_id': senderId, + 'sender_username': senderUsername, + 'created_at': createdAt, + }; + } + +} + +Future> getMessagesForThread(String messageThreadKey) async { + final db = await getDatabaseConnection(); + + List whereArguments = [messageThreadKey]; + + final List> maps = await db.query( + 'messages', + where: 'message_thread_key = ?', + whereArgs: whereArguments, + orderBy: 'created_at DESC', + ); + + return List.generate(maps.length, (i) { + return Message( + id: maps[i]['id'], + messageThreadKey: maps[i]['message_thread_key'], + symmetricKey: maps[i]['symmetric_key'], + data: maps[i]['data'], + senderId: maps[i]['sender_id'], + senderUsername: maps[i]['sender_username'], + createdAt: maps[i]['created_at'], + ); + }); + } diff --git a/mobile/lib/utils/storage/database.dart b/mobile/lib/utils/storage/database.dart index 3de37f6..3be45e7 100644 --- a/mobile/lib/utils/storage/database.dart +++ b/mobile/lib/utils/storage/database.dart @@ -3,6 +3,11 @@ import 'package:flutter/widgets.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; +Future deleteDb() async { + final path = join(await getDatabasesPath(), 'envelope.db'); + deleteDatabase(path); +} + Future getDatabaseConnection() async { WidgetsFlutterBinding.ensureInitialized(); @@ -10,7 +15,6 @@ Future getDatabaseConnection() async { final database = openDatabase( path, - // TODO: remove friend_id_decrypted and symmetric_key_decrypted onCreate: (db, version) async { await db.execute( ''' @@ -19,9 +23,7 @@ Future getDatabaseConnection() async { user_id TEXT, username TEXT, friend_id TEXT, - friend_id_decrypted TEXT, symmetric_key TEXT, - symmetric_key_decrypted TEXT, accepted_at TEXT ); '''); @@ -40,6 +42,19 @@ Future getDatabaseConnection() async { users TEXT ); '''); + + await db.execute( + ''' + CREATE TABLE IF NOT EXISTS messages( + id TEXT PRIMARY KEY, + message_thread_key TEXT, + symmetric_key TEXT, + data TEXT, + sender_id TEXT, + sender_username TEXT, + created_at TEXT + ); + '''); }, // Set the version. This executes the onCreate function and provides a // path to perform database upgrades and downgrades. diff --git a/mobile/lib/utils/storage/friends.dart b/mobile/lib/utils/storage/friends.dart index b0374a2..529bbcf 100644 --- a/mobile/lib/utils/storage/friends.dart +++ b/mobile/lib/utils/storage/friends.dart @@ -36,7 +36,7 @@ Future updateFriends() async { ) ); - friendIds.add(friends[i].friendIdDecrypted); + friendIds.add(friends[i].friendId); } Map params = {}; @@ -63,7 +63,7 @@ Future updateFriends() async { var friend = findFriendByFriendId(friends, friendJson['id']); friend.username = AesHelper.aesDecrypt( - base64.decode(friend.friendSymmetricKeyDecrypted), + base64.decode(friend.friendSymmetricKey), base64.decode(friendJson['username']), ); diff --git a/mobile/lib/utils/storage/messages.dart b/mobile/lib/utils/storage/messages.dart new file mode 100644 index 0000000..c2fb659 --- /dev/null +++ b/mobile/lib/utils/storage/messages.dart @@ -0,0 +1,76 @@ +import 'dart:convert'; +import 'package:Envelope/models/messages.dart'; +import 'package:http/http.dart' as http; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:pointycastle/export.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:Envelope/models/conversations.dart'; +import '/utils/storage/session_cookie.dart'; +import '/utils/storage/encryption_keys.dart'; +import '/utils/storage/database.dart'; +import '/models/conversations.dart'; + +// TODO: Move this to table +Map> _mapUsers(String users) { + List usersJson = jsonDecode(users); + + Map> mapped = {}; + + for (var i = 0; i < usersJson.length; i++) { + mapped[usersJson[i]['id']] = { + 'username': usersJson[i]['username'], + 'admin': usersJson[i]['admin'], + }; + } + + return mapped; +} + +Future updateMessageThread(Conversation conversation, {RSAPrivateKey? privKey}) async { + privKey ??= await getPrivateKey(); + + var resp = await http.get( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/messages/${conversation.messageThreadKey}'), + headers: { + 'cookie': await getSessionCookie(), + } + ); + + if (resp.statusCode != 200) { + throw Exception(resp.body); + } + + var mapped = _mapUsers(conversation.users!); + + List messageThreadJson = jsonDecode(resp.body); + + final db = await getDatabaseConnection(); + + for (var i = 0; i < messageThreadJson.length; i++) { + Message message = Message.fromJson( + messageThreadJson[i] as Map, + privKey, + ); + + // TODO: Fix this + message.senderUsername = mapped[message.senderId]!['username']!; + + await db.insert( + 'messages', + message.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + + } +} + +Future updateMessageThreads({List? conversations}) async { + RSAPrivateKey privKey = await getPrivateKey(); + + conversations ??= await getConversations(); + + for (var i = 0; i < conversations.length; i++) { + await updateMessageThread(conversations[i], privKey: privKey); + } +} + diff --git a/mobile/lib/views/authentication/login.dart b/mobile/lib/views/authentication/login.dart index 29075d1..b702f11 100644 --- a/mobile/lib/views/authentication/login.dart +++ b/mobile/lib/views/authentication/login.dart @@ -9,198 +9,201 @@ import '/utils/storage/encryption_keys.dart'; import '/utils/storage/session_cookie.dart'; class LoginResponse { - final String status; - final String message; - final String asymmetricPublicKey; - final String asymmetricPrivateKey; - - const LoginResponse({ - required this.status, - required this.message, - required this.asymmetricPublicKey, - required this.asymmetricPrivateKey, - }); - - factory LoginResponse.fromJson(Map json) { - return LoginResponse( - status: json['status'], - message: json['message'], - asymmetricPublicKey: json['asymmetric_public_key'], - asymmetricPrivateKey: json['asymmetric_private_key'], - ); - } + final String status; + final String message; + final String asymmetricPublicKey; + final String asymmetricPrivateKey; + final String userId; + + const LoginResponse({ + required this.status, + required this.message, + required this.asymmetricPublicKey, + required this.asymmetricPrivateKey, + required this.userId, + }); + + factory LoginResponse.fromJson(Map json) { + return LoginResponse( + status: json['status'], + message: json['message'], + asymmetricPublicKey: json['asymmetric_public_key'], + asymmetricPrivateKey: json['asymmetric_private_key'], + userId: json['user_id'], + ); + } } Future login(context, String username, String password) async { - final resp = await http.post( - Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/login'), - headers: { - 'Content-Type': 'application/json; charset=UTF-8', - }, - body: jsonEncode({ - 'username': username, - 'password': password, - }), - ); + final resp = await http.post( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/login'), + headers: { + 'Content-Type': 'application/json; charset=UTF-8', + }, + body: jsonEncode({ + 'username': username, + 'password': password, + }), + ); - if (resp.statusCode != 200) { - throw Exception(resp.body); - } + if (resp.statusCode != 200) { + throw Exception(resp.body); + } - String? rawCookie = resp.headers['set-cookie']; - if (rawCookie != null) { - int index = rawCookie.indexOf(';'); - setSessionCookie((index == -1) ? rawCookie : rawCookie.substring(0, index)); - } + String? rawCookie = resp.headers['set-cookie']; + if (rawCookie != null) { + int index = rawCookie.indexOf(';'); + setSessionCookie((index == -1) ? rawCookie : rawCookie.substring(0, index)); + } - LoginResponse response = LoginResponse.fromJson(jsonDecode(resp.body)); + LoginResponse response = LoginResponse.fromJson(jsonDecode(resp.body)); - var rsaPrivPem = AesHelper.aesDecrypt(password, base64.decode(response.asymmetricPrivateKey)); + var rsaPrivPem = AesHelper.aesDecrypt(password, base64.decode(response.asymmetricPrivateKey)); - debugPrint(rsaPrivPem); + debugPrint(rsaPrivPem); - var rsaPriv = CryptoUtils.rsaPrivateKeyFromPem(rsaPrivPem); - setPrivateKey(rsaPriv); + var rsaPriv = CryptoUtils.rsaPrivateKeyFromPem(rsaPrivPem); + setPrivateKey(rsaPriv); - final preferences = await SharedPreferences.getInstance(); - preferences.setBool('islogin', true); + final preferences = await SharedPreferences.getInstance(); + preferences.setBool('islogin', true); + preferences.setString('userId', response.userId); - return response; + return response; } class Login extends StatelessWidget { - const Login({Key? key}) : super(key: key); - - static const String _title = 'Envelope'; - - @override - Widget build(BuildContext context) { - return Scaffold( - backgroundColor: Colors.cyan, - appBar: AppBar( - title: null, - automaticallyImplyLeading: true, - //`true` if you want Flutter to automatically add Back Button when needed, - //or `false` if you want to force your own back button every where - leading: IconButton(icon: const Icon(Icons.arrow_back), - onPressed:() => { - Navigator.pop(context) - } - ) - ), - body: const SafeArea( - child: LoginWidget(), - ), - ); - } + const Login({Key? key}) : super(key: key); + + static const String _title = 'Envelope'; + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.cyan, + appBar: AppBar( + title: null, + automaticallyImplyLeading: true, + //`true` if you want Flutter to automatically add Back Button when needed, + //or `false` if you want to force your own back button every where + leading: IconButton(icon: const Icon(Icons.arrow_back), + onPressed:() => { + Navigator.pop(context) + } + ) + ), + body: const SafeArea( + child: LoginWidget(), + ), + ); + } } class LoginWidget extends StatefulWidget { - const LoginWidget({Key? key}) : super(key: key); + const LoginWidget({Key? key}) : super(key: key); - @override - State createState() => _LoginWidgetState(); + @override + State createState() => _LoginWidgetState(); } class _LoginWidgetState extends State { - final _formKey = GlobalKey(); - - TextEditingController usernameController = TextEditingController(); - TextEditingController passwordController = TextEditingController(); - - @override - Widget build(BuildContext context) { - const TextStyle _inputTextStyle = TextStyle(fontSize: 18, color: Colors.black); - - final ButtonStyle _buttonStyle = ElevatedButton.styleFrom( - primary: Colors.white, - onPrimary: Colors.cyan, - minimumSize: const Size.fromHeight(50), - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), - textStyle: const TextStyle( - fontSize: 20, - fontWeight: FontWeight.bold, - color: Colors.red, - ), - ); - - return Center( - child: Form( - key: _formKey, - child: Center( - child: Padding( - padding: const EdgeInsets.all(15), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - const Text('Login', style: TextStyle(fontSize: 35, color: Colors.white),), - const SizedBox(height: 30), - TextFormField( - controller: usernameController, - decoration: const InputDecoration( - hintText: 'Username', - ), - style: _inputTextStyle, - // The validator receives the text that the user has entered. - validator: (value) { - if (value == null || value.isEmpty) { - return 'Create a username'; - } - return null; - }, - ), - const SizedBox(height: 5), - TextFormField( - controller: passwordController, - obscureText: true, - enableSuggestions: false, - autocorrect: false, - decoration: const InputDecoration( - hintText: 'Password', - ), - style: _inputTextStyle, - // The validator receives the text that the user has entered. - validator: (value) { - if (value == null || value.isEmpty) { - return 'Enter a password'; - } - return null; - }, - ), - const SizedBox(height: 5), - ElevatedButton( - style: _buttonStyle, - onPressed: () { - if (_formKey.currentState!.validate()) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Processing Data')), - ); - - login( - context, - usernameController.text, - passwordController.text, - ).then((value) { - Navigator. - pushNamedAndRemoveUntil( - context, - '/home', - ModalRoute.withName('/home'), - ); - }).catchError((error) { - print(error); // TODO: Show error on interface - }); - } - }, - child: const Text('Submit'), - ), - ], - ) - ) - ) - - ) - ); - } + final _formKey = GlobalKey(); + + TextEditingController usernameController = TextEditingController(); + TextEditingController passwordController = TextEditingController(); + + @override + Widget build(BuildContext context) { + const TextStyle _inputTextStyle = TextStyle(fontSize: 18, color: Colors.black); + + final ButtonStyle _buttonStyle = ElevatedButton.styleFrom( + primary: Colors.white, + onPrimary: Colors.cyan, + minimumSize: const Size.fromHeight(50), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + textStyle: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Colors.red, + ), + ); + + return Center( + child: Form( + key: _formKey, + child: Center( + child: Padding( + padding: const EdgeInsets.all(15), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + const Text('Login', style: TextStyle(fontSize: 35, color: Colors.white),), + const SizedBox(height: 30), + TextFormField( + controller: usernameController, + decoration: const InputDecoration( + hintText: 'Username', + ), + style: _inputTextStyle, + // The validator receives the text that the user has entered. + validator: (value) { + if (value == null || value.isEmpty) { + return 'Create a username'; + } + return null; + }, + ), + const SizedBox(height: 5), + TextFormField( + controller: passwordController, + obscureText: true, + enableSuggestions: false, + autocorrect: false, + decoration: const InputDecoration( + hintText: 'Password', + ), + style: _inputTextStyle, + // The validator receives the text that the user has entered. + validator: (value) { + if (value == null || value.isEmpty) { + return 'Enter a password'; + } + return null; + }, + ), + const SizedBox(height: 5), + ElevatedButton( + style: _buttonStyle, + onPressed: () { + if (_formKey.currentState!.validate()) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Processing Data')), + ); + + login( + context, + usernameController.text, + passwordController.text, + ).then((value) { + Navigator. + pushNamedAndRemoveUntil( + context, + '/home', + ModalRoute.withName('/home'), + ); + }).catchError((error) { + print(error); // TODO: Show error on interface + }); + } + }, + child: const Text('Submit'), + ), + ], + ) + ) + ) + ) + ); + } } diff --git a/mobile/lib/views/authentication/unauthenticated_landing.dart b/mobile/lib/views/authentication/unauthenticated_landing.dart index e17a06f..1bb6c31 100644 --- a/mobile/lib/views/authentication/unauthenticated_landing.dart +++ b/mobile/lib/views/authentication/unauthenticated_landing.dart @@ -4,82 +4,82 @@ import './login.dart'; import './signup.dart'; class UnauthenticatedLandingWidget extends StatefulWidget { - const UnauthenticatedLandingWidget({Key? key}) : super(key: key); + const UnauthenticatedLandingWidget({Key? key}) : super(key: key); - @override - State createState() => _UnauthenticatedLandingWidgetState(); + @override + State createState() => _UnauthenticatedLandingWidgetState(); } class _UnauthenticatedLandingWidgetState extends State { - @override - Widget build(BuildContext context) { - final ButtonStyle buttonStyle = ElevatedButton.styleFrom( - primary: Colors.white, - onPrimary: Colors.cyan, - minimumSize: const Size.fromHeight(50), - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), - textStyle: const TextStyle( - fontSize: 20, - fontWeight: FontWeight.bold, - color: Colors.red, - ), - ); + @override + Widget build(BuildContext context) { + final ButtonStyle buttonStyle = ElevatedButton.styleFrom( + primary: Colors.white, + onPrimary: Colors.cyan, + minimumSize: const Size.fromHeight(50), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + textStyle: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Colors.red, + ), + ); - return WillPopScope( - onWillPop: () async => false, - child: Scaffold( - backgroundColor: Colors.cyan, - body: SafeArea( - child: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Center( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: const [ - FaIcon(FontAwesomeIcons.envelope, color: Colors.white, size: 40), - SizedBox(width: 15), - Text('Envelope', style: TextStyle(fontSize: 40, color: Colors.white),) - ] - ), - ), - const SizedBox(height: 10), - Padding( - padding: const EdgeInsets.all(15), - child: Column ( - children: [ - ElevatedButton( - child: const Text('Login'), - onPressed: () => { - Navigator.of(context).push( - MaterialPageRoute(builder: (context) => const Login()), - ), - }, + return WillPopScope( + onWillPop: () async => false, + child: Scaffold( + backgroundColor: Colors.cyan, + body: SafeArea( + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Center( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: const [ + FaIcon(FontAwesomeIcons.envelope, color: Colors.white, size: 40), + SizedBox(width: 15), + Text('Envelope', style: TextStyle(fontSize: 40, color: Colors.white),) + ] + ), + ), + const SizedBox(height: 10), + Padding( + padding: const EdgeInsets.all(15), + child: Column ( + children: [ + ElevatedButton( + child: const Text('Login'), + onPressed: () => { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => const Login()), + ), + }, - style: buttonStyle, - ), - const SizedBox(height: 20), - ElevatedButton( - child: const Text('Sign Up'), - onPressed: () => { - Navigator.of(context).push( - MaterialPageRoute(builder: (context) => const Signup()), - ), - }, - style: buttonStyle, - ), - ] - ), - ), - ], - ), - ), - ), - ), - ); - } + style: buttonStyle, + ), + const SizedBox(height: 20), + ElevatedButton( + child: const Text('Sign Up'), + onPressed: () => { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => const Signup()), + ), + }, + style: buttonStyle, + ), + ] + ), + ), + ], + ), + ), + ), + ), + ); + } } diff --git a/mobile/lib/views/main/conversation_detail.dart b/mobile/lib/views/main/conversation_detail.dart index 4ed7182..aaa158e 100644 --- a/mobile/lib/views/main/conversation_detail.dart +++ b/mobile/lib/views/main/conversation_detail.dart @@ -1,7 +1,27 @@ import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import '/models/conversations.dart'; import '/models/messages.dart'; +String convertToAgo(String input){ + DateTime time = DateTime.parse(input); + Duration diff = DateTime.now().difference(time); + + if(diff.inDays >= 1){ + return '${diff.inDays} day${diff.inDays == 1 ? "" : "s"} ago'; + } + if(diff.inHours >= 1){ + return '${diff.inHours} hour${diff.inHours == 1 ? "" : "s"} ago'; + } + if(diff.inMinutes >= 1){ + return '${diff.inMinutes} minute${diff.inMinutes == 1 ? "" : "s"} ago'; + } + if (diff.inSeconds >= 1){ + return '${diff.inSeconds} second${diff.inSeconds == 1 ? "" : "s"} ago'; + } + return 'just now'; +} + class ConversationDetail extends StatefulWidget{ final Conversation conversation; const ConversationDetail({ @@ -11,130 +31,167 @@ class ConversationDetail extends StatefulWidget{ @override _ConversationDetailState createState() => _ConversationDetailState(); + } class _ConversationDetailState extends State { - List messages = [ - ]; + List messages = []; + String userId = ''; + + @override + void initState() { + super.initState(); + fetchMessages(); + } + + void fetchMessages() async { + final preferences = await SharedPreferences.getInstance(); + userId = preferences.getString('userId')!; + messages = await getMessagesForThread(widget.conversation.messageThreadKey); + setState(() {}); + } @override Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - elevation: 0, - automaticallyImplyLeading: false, - backgroundColor: Colors.white, - flexibleSpace: SafeArea( - child: Container( - padding: const EdgeInsets.only(right: 16), - child: Row( - children: [ - IconButton( - onPressed: (){ - Navigator.pop(context); - }, - icon: const Icon(Icons.arrow_back,color: Colors.black,), - ), - const SizedBox(width: 2,), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - widget.conversation.name, - style: const TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600), - ), - ], - ), - ), - const Icon(Icons.settings,color: Colors.black54,), - ], - ), - ), + return Scaffold( + appBar: AppBar( + elevation: 0, + automaticallyImplyLeading: false, + backgroundColor: Colors.white, + flexibleSpace: SafeArea( + child: Container( + padding: const EdgeInsets.only(right: 16), + child: Row( + children: [ + IconButton( + onPressed: (){ + Navigator.pop(context); + }, + icon: const Icon(Icons.arrow_back,color: Colors.black,), + ), + const SizedBox(width: 2,), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + widget.conversation.name, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600), + ), + ], + ), + ), + const Icon(Icons.settings,color: Colors.black54,), + ], ), - ), - body: Stack( - children: [ - ListView.builder( - itemCount: messages.length, - shrinkWrap: true, - padding: const EdgeInsets.only(top: 10,bottom: 10), - physics: const NeverScrollableScrollPhysics(), - itemBuilder: (context, index) { - return Container( - padding: const EdgeInsets.only(left: 14,right: 14,top: 10,bottom: 10), - child: Align( - // alignment: (messages[index].messageType == messageTypeReceiver ? Alignment.topLeft:Alignment.topRight), - alignment: Alignment.topLeft, // TODO: compare senderId to current user id - child: Container( - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(20), - // color: (messages[index].messageType == messageTypeReceiver ? Colors.grey.shade200:Colors.blue[200]), - color: (true ? Colors.grey.shade200:Colors.blue[200]), - ), - padding: const EdgeInsets.all(16), - child: Text(messages[index].data, style: const TextStyle(fontSize: 15)), + ), + ), + ), + body: Stack( + children: [ + ListView.builder( + itemCount: messages.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 10,bottom: 10), + reverse: true, + itemBuilder: (context, index) { + return Container( + padding: const EdgeInsets.only(left: 14,right: 14,top: 0,bottom: 0), + child: Align( + alignment: ( + messages[index].senderId == userId ? + Alignment.topLeft: + Alignment.topRight + ), + child: Column( + crossAxisAlignment: messages[index].senderId == userId ? + CrossAxisAlignment.start : + CrossAxisAlignment.end, + children: [ + Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + color: ( + messages[index].senderId == userId ? + Colors.grey.shade200 : + Colors.blue[200] ), + ), + padding: const EdgeInsets.all(12), + child: Text(messages[index].data, style: const TextStyle(fontSize: 15)), + ), + messages[index].senderId != userId ? + Text(messages[index].senderUsername) : + const SizedBox.shrink(), + Text( + convertToAgo(messages[index].createdAt), + textAlign: TextAlign.left, + style: TextStyle( + fontSize: 12, + color: Colors.grey[500], + ), ), - ); - }, - ), - Align( - alignment: Alignment.bottomLeft, - child: ConstrainedBox( - constraints: const BoxConstraints( - maxHeight: 200.0, + ] + ) ), - child: Container( - padding: const EdgeInsets.only(left: 10,bottom: 10,top: 10), - // height: 60, - width: double.infinity, - color: Colors.white, - child: Row( - children: [ + ); + }, + ), + Align( + alignment: Alignment.bottomLeft, + child: ConstrainedBox( + constraints: const BoxConstraints( + maxHeight: 200.0, + ), + child: Container( + padding: const EdgeInsets.only(left: 10,bottom: 10,top: 10), + // height: 60, + width: double.infinity, + color: Colors.white, + child: Row( + children: [ GestureDetector( - onTap: (){ - }, - child: Container( - height: 30, - width: 30, - decoration: BoxDecoration( - color: Colors.lightBlue, - borderRadius: BorderRadius.circular(30), - ), - child: const Icon(Icons.add, color: Colors.white, size: 20, ), + onTap: (){ + }, + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + color: Colors.lightBlue, + borderRadius: BorderRadius.circular(30), ), + child: const Icon(Icons.add, color: Colors.white, size: 20, ), + ), ), const SizedBox(width: 15,), const Expanded( - child: TextField( - decoration: InputDecoration( - hintText: "Write message...", - hintStyle: TextStyle(color: Colors.black54), - border: InputBorder.none, - ), - maxLines: null, + child: TextField( + decoration: InputDecoration( + hintText: "Write message...", + hintStyle: TextStyle(color: Colors.black54), + border: InputBorder.none, ), + maxLines: null, + ), ), const SizedBox(width: 15,), FloatingActionButton( - onPressed: () { - }, - child: const Icon(Icons.send,color: Colors.white,size: 18,), - backgroundColor: Colors.blue, - elevation: 0, + onPressed: () { + }, + child: const Icon(Icons.send,color: Colors.white,size: 18,), + backgroundColor: Colors.blue, + elevation: 0, ), ], - + ), ), ), - ), - ), - ], + ), + ], ), - ); + ); } } diff --git a/mobile/lib/views/main/conversation_list.dart b/mobile/lib/views/main/conversation_list.dart index 5a5ca08..7ff74b6 100644 --- a/mobile/lib/views/main/conversation_list.dart +++ b/mobile/lib/views/main/conversation_list.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import '/models/conversations.dart'; import '/views/main/conversation_list_item.dart'; +import '/utils/storage/messages.dart'; class ConversationList extends StatefulWidget { const ConversationList({Key? key}) : super(key: key); diff --git a/mobile/lib/views/main/conversation_list_item.dart b/mobile/lib/views/main/conversation_list_item.dart index 78b1d55..ecfc157 100644 --- a/mobile/lib/views/main/conversation_list_item.dart +++ b/mobile/lib/views/main/conversation_list_item.dart @@ -15,6 +15,7 @@ class ConversationListItem extends StatefulWidget{ } class _ConversationListItemState extends State { + @override Widget build(BuildContext context) { return GestureDetector( diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index fcf9900..7d4e6e9 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -5,6 +5,7 @@ import '/views/main/friend_list.dart'; import '/views/main/profile.dart'; import '/utils/storage/friends.dart'; import '/utils/storage/conversations.dart'; +import '/utils/storage/messages.dart'; class Home extends StatefulWidget { const Home({Key? key}) : super(key: key); @@ -24,6 +25,7 @@ class _HomeState extends State { await checkLogin(); await updateFriends(); await updateConversations(); + await updateMessageThreads(); } // TODO: Do server GET check here diff --git a/mobile/lib/views/main/profile.dart b/mobile/lib/views/main/profile.dart index 488d1b6..64d65ff 100644 --- a/mobile/lib/views/main/profile.dart +++ b/mobile/lib/views/main/profile.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '/utils/storage/encryption_keys.dart'; +import '/utils/storage/database.dart'; class Profile extends StatefulWidget { const Profile({Key? key}) : super(key: key); @@ -34,6 +35,7 @@ class _ProfileState extends State { ), child: GestureDetector( onTap: () async { + deleteDb(); final preferences = await SharedPreferences.getInstance(); preferences.setBool('islogin', false); preferences.remove(rsaPrivateKeyName); -- 2.17.1 From a6f54d5ef8a7d798a8bba6ea14224e0fa5803de7 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Sat, 2 Jul 2022 15:20:09 +0930 Subject: [PATCH 09/24] Finish sending messages --- Backend/Api/Auth/Login.go | 16 +- Backend/Api/Messages/CreateMessage.go | 28 ++- Backend/Api/Routes.go | 4 +- Backend/Database/MessageData.go | 39 ++++ Backend/Database/Messages.go | 18 +- Backend/Database/Seeder/MessageSeeder.go | 143 +++++++----- Backend/Database/Seeder/UserSeeder.go | 2 +- Backend/Models/Base.go | 4 + Backend/Models/Messages.go | 21 +- mobile/lib/models/conversation_users.dart | 104 +++++++++ mobile/lib/models/conversations.dart | 14 -- mobile/lib/models/friends.dart | 61 ++--- mobile/lib/models/messages.dart | 117 ++++++++-- mobile/lib/utils/storage/conversations.dart | 26 ++- mobile/lib/utils/storage/database.dart | 18 +- mobile/lib/utils/storage/friends.dart | 2 + mobile/lib/utils/storage/messages.dart | 146 +++++++----- mobile/lib/utils/strings.dart | 8 + mobile/lib/views/authentication/login.dart | 9 +- mobile/lib/views/authentication/signup.dart | 10 +- .../lib/views/main/conversation_detail.dart | 53 +++-- mobile/lib/views/main/conversation_list.dart | 209 ++++++++++-------- mobile/lib/views/main/friend_list.dart | 207 +++++++++-------- mobile/lib/views/main/home.dart | 58 ++++- mobile/pubspec.lock | 21 ++ mobile/pubspec.yaml | 2 + 26 files changed, 907 insertions(+), 433 deletions(-) create mode 100644 Backend/Database/MessageData.go create mode 100644 mobile/lib/models/conversation_users.dart create mode 100644 mobile/lib/utils/strings.dart diff --git a/Backend/Api/Auth/Login.go b/Backend/Api/Auth/Login.go index b91d133..15c42a7 100644 --- a/Backend/Api/Auth/Login.go +++ b/Backend/Api/Auth/Login.go @@ -20,9 +20,10 @@ type loginResponse struct { AsymmetricPublicKey string `json:"asymmetric_public_key"` AsymmetricPrivateKey string `json:"asymmetric_private_key"` UserID string `json:"user_id"` + Username string `json:"username"` } -func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey string, userId string) { +func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey string, user Models.User) { var ( status string = "error" returnJson []byte @@ -37,7 +38,8 @@ func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey Message: message, AsymmetricPublicKey: pubKey, AsymmetricPrivateKey: privKey, - UserID: userId, + UserID: user.ID.String(), + Username: user.Username, }, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) @@ -61,18 +63,18 @@ func Login(w http.ResponseWriter, r *http.Request) { err = json.NewDecoder(r.Body).Decode(&creds) if err != nil { - makeLoginResponse(w, http.StatusInternalServerError, "An error occurred", "", "", "") + makeLoginResponse(w, http.StatusInternalServerError, "An error occurred", "", "", userData) return } userData, err = Database.GetUserByUsername(creds.Username) if err != nil { - makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", "") + makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", userData) return } if !CheckPasswordHash(creds.Password, userData.Password) { - makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", "") + makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", userData) return } @@ -86,7 +88,7 @@ func Login(w http.ResponseWriter, r *http.Request) { err = Database.CreateSession(&session) if err != nil { - makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", "") + makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", userData) return } @@ -102,6 +104,6 @@ func Login(w http.ResponseWriter, r *http.Request) { "Successfully logged in", userData.AsymmetricPublicKey, userData.AsymmetricPrivateKey, - userData.ID.String(), + userData, ) } diff --git a/Backend/Api/Messages/CreateMessage.go b/Backend/Api/Messages/CreateMessage.go index d73977c..c233fc8 100644 --- a/Backend/Api/Messages/CreateMessage.go +++ b/Backend/Api/Messages/CreateMessage.go @@ -2,22 +2,40 @@ package Messages import ( "encoding/json" - "fmt" "net/http" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" ) +type RawMessageData struct { + MessageData Models.MessageData `json:"message_data"` + Messages []Models.Message `json:"message"` +} + func CreateMessage(w http.ResponseWriter, r *http.Request) { var ( - message Models.Message - err error + rawMessageData RawMessageData + err error ) - err = json.NewDecoder(r.Body).Decode(&message) + err = json.NewDecoder(r.Body).Decode(&rawMessageData) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + err = Database.CreateMessageData(&rawMessageData.MessageData) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + err = Database.CreateMessages(&rawMessageData.Messages) if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) return } - fmt.Println(message) + w.WriteHeader(http.StatusOK) } diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index 651578e..7d528ed 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -68,9 +68,7 @@ func InitApiEndpoints(router *mux.Router) { authApi.HandleFunc("/conversations", Messages.EncryptedConversationList).Methods("GET") authApi.HandleFunc("/conversation_details", Messages.EncryptedConversationDetailsList).Methods("GET") - // authApi.HandleFunc("/user/{userID}", Friends.Friend).Methods("GET") - // authApi.HandleFunc("/user/{userID}/request", Friends.FriendRequest).Methods("POST") - // Define routes for messages + authApi.HandleFunc("/message", Messages.CreateMessage).Methods("POST") authApi.HandleFunc("/messages/{threadKey}", Messages.Messages).Methods("GET") } diff --git a/Backend/Database/MessageData.go b/Backend/Database/MessageData.go new file mode 100644 index 0000000..80c6515 --- /dev/null +++ b/Backend/Database/MessageData.go @@ -0,0 +1,39 @@ +package Database + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +func GetMessageDataById(id string) (Models.MessageData, error) { + var ( + messageData Models.MessageData + err error + ) + + err = DB.Preload(clause.Associations). + First(&messageData, "id = ?", id). + Error + + return messageData, err +} + +func CreateMessageData(messageData *Models.MessageData) error { + var ( + err error + ) + + err = DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(messageData). + Error + + return err +} + +func DeleteMessageData(messageData *Models.MessageData) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Delete(messageData). + Error +} diff --git a/Backend/Database/Messages.go b/Backend/Database/Messages.go index 4c1c352..0affa34 100644 --- a/Backend/Database/Messages.go +++ b/Backend/Database/Messages.go @@ -20,14 +20,14 @@ func GetMessageById(id string) (Models.Message, error) { return message, err } -func GetMessagesByThreadKey(threadKey string) ([]Models.Message, error) { +func GetMessagesByThreadKey(associationKey string) ([]Models.Message, error) { var ( messages []Models.Message err error ) - err = DB.Preload(clause.Associations). - Find(&messages, "message_thread_key = ?", threadKey). + err = DB.Preload("MessageData"). + Find(&messages, "association_key = ?", associationKey). Error return messages, err @@ -45,6 +45,18 @@ func CreateMessage(message *Models.Message) error { return err } +func CreateMessages(messages *[]Models.Message) error { + var ( + err error + ) + + err = DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(messages). + Error + + return err +} + func DeleteMessage(message *Models.Message) error { return DB.Session(&gorm.Session{FullSaveAssociations: true}). Delete(message). diff --git a/Backend/Database/Seeder/MessageSeeder.go b/Backend/Database/Seeder/MessageSeeder.go index aba744a..2139eb1 100644 --- a/Backend/Database/Seeder/MessageSeeder.go +++ b/Backend/Database/Seeder/MessageSeeder.go @@ -7,60 +7,93 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Util" + "github.com/gofrs/uuid" ) func seedMessage( primaryUser, secondaryUser Models.User, - primaryUserThreadKey, secondaryUserThreadKey string, - thread Models.ConversationDetail, + primaryUserAssociationKey, secondaryUserAssociationKey string, i int, ) error { var ( message Models.Message messageData Models.MessageData - key aesKey + key, userKey aesKey + keyCiphertext []byte plaintext string dataCiphertext []byte senderIdCiphertext []byte + friendId []byte err error ) - key, err = generateAesKey() + plaintext = "Test Message" + + userKey, err = generateAesKey() if err != nil { panic(err) } - plaintext = "Test Message" + key, err = generateAesKey() + if err != nil { + panic(err) + } dataCiphertext, err = key.aesEncrypt([]byte(plaintext)) if err != nil { panic(err) } - senderIdCiphertext, err = key.aesEncrypt([]byte(primaryUser.ID.String())) + friendId, err = base64.StdEncoding.DecodeString(primaryUser.FriendID) + if err != nil { + panic(err) + } + friendId, err = decryptWithPrivateKey(friendId, decodedPrivateKey) + if err != nil { + panic(err) + } + + senderIdCiphertext, err = key.aesEncrypt(friendId) if err != nil { panic(err) } if i%2 == 0 { - senderIdCiphertext, err = key.aesEncrypt([]byte(secondaryUser.ID.String())) + friendId, err = base64.StdEncoding.DecodeString(secondaryUser.FriendID) + if err != nil { + panic(err) + } + friendId, err = decryptWithPrivateKey(friendId, decodedPrivateKey) + if err != nil { + panic(err) + } + + senderIdCiphertext, err = key.aesEncrypt(friendId) if err != nil { panic(err) } } + keyCiphertext, err = userKey.aesEncrypt( + []byte(base64.StdEncoding.EncodeToString(key.Key)), + ) + if err != nil { + panic(err) + } + messageData = Models.MessageData{ - Data: base64.StdEncoding.EncodeToString(dataCiphertext), - SenderID: base64.StdEncoding.EncodeToString(senderIdCiphertext), + Data: base64.StdEncoding.EncodeToString(dataCiphertext), + SenderID: base64.StdEncoding.EncodeToString(senderIdCiphertext), + SymmetricKey: base64.StdEncoding.EncodeToString(keyCiphertext), } message = Models.Message{ MessageData: messageData, SymmetricKey: base64.StdEncoding.EncodeToString( - encryptWithPublicKey(key.Key, decodedPublicKey), + encryptWithPublicKey(userKey.Key, decodedPublicKey), ), - MessageThreadKey: primaryUserThreadKey, + AssociationKey: primaryUserAssociationKey, } err = Database.CreateMessage(&message) @@ -68,22 +101,15 @@ func seedMessage( return err } - // The symmetric key would be encrypted with secondary users public key in production - // But due to using the same pub/priv key pair for all users, we will just duplicate it message = Models.Message{ - MessageDataID: message.MessageDataID, + MessageData: messageData, SymmetricKey: base64.StdEncoding.EncodeToString( - encryptWithPublicKey(key.Key, decodedPublicKey), + encryptWithPublicKey(userKey.Key, decodedPublicKey), ), - MessageThreadKey: secondaryUserThreadKey, - } - - err = Database.CreateMessage(&message) - if err != nil { - return err + AssociationKey: secondaryUserAssociationKey, } - return err + return Database.CreateMessage(&message) } func seedConversationDetail(key aesKey) (Models.ConversationDetail, error) { @@ -132,13 +158,11 @@ func seedUpdateUserConversation( func seedUserConversation( user Models.User, threadID uuid.UUID, - messageThreadKey string, key aesKey, ) (Models.UserConversation, error) { var ( messageThreadUser Models.UserConversation threadIdCiphertext []byte - keyCiphertext []byte adminCiphertext []byte err error ) @@ -148,11 +172,6 @@ func seedUserConversation( return messageThreadUser, err } - keyCiphertext, err = key.aesEncrypt([]byte(messageThreadKey)) - if err != nil { - return messageThreadUser, err - } - adminCiphertext, err = key.aesEncrypt([]byte("true")) if err != nil { return messageThreadUser, err @@ -161,7 +180,6 @@ func seedUserConversation( messageThreadUser = Models.UserConversation{ UserID: user.ID, ConversationDetailID: base64.StdEncoding.EncodeToString(threadIdCiphertext), - MessageThreadKey: base64.StdEncoding.EncodeToString(keyCiphertext), Admin: base64.StdEncoding.EncodeToString(adminCiphertext), SymmetricKey: base64.StdEncoding.EncodeToString( encryptWithPublicKey(key.Key, decodedPublicKey), @@ -174,24 +192,24 @@ func seedUserConversation( func SeedMessages() { var ( - messageThread Models.ConversationDetail - key aesKey - primaryUser Models.User - primaryUserThreadKey string - secondaryUser Models.User - secondaryUserThreadKey string - - userJson string - - thread Models.ConversationDetail - i int - err error + messageThread Models.ConversationDetail + key aesKey + primaryUser Models.User + primaryUserAssociationKey string + secondaryUser Models.User + secondaryUserAssociationKey string + primaryUserFriendId []byte + secondaryUserFriendId []byte + userJson string + i int + err error ) key, err = generateAesKey() messageThread, err = seedConversationDetail(key) - primaryUserThreadKey = Util.RandomString(32) - secondaryUserThreadKey = Util.RandomString(32) + + primaryUserAssociationKey = Util.RandomString(32) + secondaryUserAssociationKey = Util.RandomString(32) primaryUser, err = Database.GetUserByUsername("testUser") if err != nil { @@ -201,7 +219,6 @@ func SeedMessages() { _, err = seedUserConversation( primaryUser, messageThread.ID, - primaryUserThreadKey, key, ) @@ -213,29 +230,50 @@ func SeedMessages() { _, err = seedUserConversation( secondaryUser, messageThread.ID, - secondaryUserThreadKey, key, ) + primaryUserFriendId, err = base64.StdEncoding.DecodeString(primaryUser.FriendID) + if err != nil { + panic(err) + } + primaryUserFriendId, err = decryptWithPrivateKey(primaryUserFriendId, decodedPrivateKey) + if err != nil { + panic(err) + } + + secondaryUserFriendId, err = base64.StdEncoding.DecodeString(secondaryUser.FriendID) + if err != nil { + panic(err) + } + secondaryUserFriendId, err = decryptWithPrivateKey(secondaryUserFriendId, decodedPrivateKey) + if err != nil { + panic(err) + } + userJson = fmt.Sprintf( ` [ { "id": "%s", "username": "%s", - "admin": "true" + "admin": "true", + "association_key": "%s" }, { "id": "%s", "username": "%s", - "admin": "true" + "admin": "true", + "association_key": "%s" } ] `, - primaryUser.ID.String(), + string(primaryUserFriendId), primaryUser.Username, - secondaryUser.ID.String(), + primaryUserAssociationKey, + string(secondaryUserFriendId), secondaryUser.Username, + secondaryUserAssociationKey, ) messageThread, err = seedUpdateUserConversation( @@ -248,9 +286,8 @@ func SeedMessages() { err = seedMessage( primaryUser, secondaryUser, - primaryUserThreadKey, - secondaryUserThreadKey, - thread, + primaryUserAssociationKey, + secondaryUserAssociationKey, i, ) if err != nil { diff --git a/Backend/Database/Seeder/UserSeeder.go b/Backend/Database/Seeder/UserSeeder.go index b9e12e6..69cd543 100644 --- a/Backend/Database/Seeder/UserSeeder.go +++ b/Backend/Database/Seeder/UserSeeder.go @@ -49,7 +49,7 @@ func createUser(username string) (Models.User, error) { publicUserData = Models.Friend{ Username: base64.StdEncoding.EncodeToString(usernameCiphertext), - AsymmetricPublicKey: base64.StdEncoding.EncodeToString([]byte(publicKey)), + AsymmetricPublicKey: publicKey, } err = Database.CreateFriend(&publicUserData) diff --git a/Backend/Models/Base.go b/Backend/Models/Base.go index 2fdcd07..797bccc 100644 --- a/Backend/Models/Base.go +++ b/Backend/Models/Base.go @@ -17,6 +17,10 @@ func (base *Base) BeforeCreate(tx *gorm.DB) error { err error ) + if !base.ID.IsNil() { + return nil + } + id, err = uuid.NewV4() if err != nil { return err diff --git a/Backend/Models/Messages.go b/Backend/Models/Messages.go index d9f309c..fed8909 100644 --- a/Backend/Models/Messages.go +++ b/Backend/Models/Messages.go @@ -9,24 +9,24 @@ import ( // TODO: Add support for images type MessageData struct { Base - Data string `gorm:"not null" json:"data"` // Stored encrypted - SenderID string `gorm:"not null" json:"sender_id"` + Data string `gorm:"not null" json:"data"` // Stored encrypted + SenderID string `gorm:"not null" json:"sender_id"` // Stored encrypted + SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted } type Message struct { Base - MessageDataID uuid.UUID `json:"-"` - MessageData MessageData `json:"message_data"` - SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted - MessageThreadKey string `gorm:"not null" json:"message_thread_key"` - CreatedAt time.Time `gorm:"not null" json:"created_at"` + MessageDataID uuid.UUID `json:"message_data_id"` + MessageData MessageData `json:"message_data"` + SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted + AssociationKey string `gorm:"not null" json:"association_key"` // TODO: This links all encrypted messages for a user in a thread together. Find a way to fix this + CreatedAt time.Time `gorm:"not null" json:"created_at"` } -// TODO: Rename to ConversationDetails type ConversationDetail struct { Base - Name string `gorm:"not null" json:"name"` - Users string `json:"users"` // Stored as encrypted JSON + Name string `gorm:"not null" json:"name"` // Stored encrypted + Users string `json:"users"` // Stored as encrypted JSON } type UserConversation struct { @@ -34,7 +34,6 @@ type UserConversation struct { UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` User User `json:"user"` ConversationDetailID string `gorm:"not null" json:"conversation_detail_id"` // Stored encrypted - MessageThreadKey string `gorm:"not null" json:"message_thread_key"` // Stored encrypted Admin string `gorm:"not null" json:"admin"` // Bool if user is admin of thread, stored encrypted SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted } diff --git a/mobile/lib/models/conversation_users.dart b/mobile/lib/models/conversation_users.dart new file mode 100644 index 0000000..6c94a0d --- /dev/null +++ b/mobile/lib/models/conversation_users.dart @@ -0,0 +1,104 @@ +import '/utils/storage/database.dart'; +import '/models/conversations.dart'; + +class ConversationUser{ + String id; + String conversationId; + String username; + String associationKey; + String admin; + ConversationUser({ + required this.id, + required this.conversationId, + required this.username, + required this.associationKey, + required this.admin, + }); + + factory ConversationUser.fromJson(Map json, String conversationId) { + return ConversationUser( + id: json['id'], + conversationId: conversationId, + username: json['username'], + associationKey: json['association_key'], + admin: json['admin'], + ); + } + + Map toMap() { + return { + 'id': id, + 'conversation_id': conversationId, + 'username': username, + 'association_key': associationKey, + 'admin': admin, + }; + } +} + +// A method that retrieves all the dogs from the dogs table. +Future> getConversationUsers(Conversation conversation) async { + final db = await getDatabaseConnection(); + + final List> maps = await db.query( + 'conversation_users', + where: 'conversation_id = ?', + whereArgs: [conversation.id], + ); + + return List.generate(maps.length, (i) { + return ConversationUser( + id: maps[i]['id'], + conversationId: maps[i]['conversation_id'], + username: maps[i]['username'], + associationKey: maps[i]['association_key'], + admin: maps[i]['admin'], + ); + }); +} + +Future getConversationUserById(Conversation conversation, String id) async { + final db = await getDatabaseConnection(); + + final List> maps = await db.query( + 'conversation_users', + where: 'conversation_id = ? AND id = ?', + whereArgs: [conversation.id, id], + ); + + if (maps.length != 1) { + throw ArgumentError('Invalid conversation_id or id'); + } + + return ConversationUser( + id: maps[0]['id'], + conversationId: maps[0]['conversation_id'], + username: maps[0]['username'], + associationKey: maps[0]['association_key'], + admin: maps[0]['admin'], + ); + +} + +Future getConversationUserByUsername(Conversation conversation, String username) async { + final db = await getDatabaseConnection(); + + final List> maps = await db.query( + 'conversation_users', + where: 'conversation_id = ? AND username = ?', + whereArgs: [conversation.id, username], + ); + + if (maps.length != 1) { + throw ArgumentError('Invalid conversation_id or username'); + } + + return ConversationUser( + id: maps[0]['id'], + conversationId: maps[0]['conversation_id'], + username: maps[0]['username'], + associationKey: maps[0]['association_key'], + admin: maps[0]['admin'], + ); + +} diff --git a/mobile/lib/models/conversations.dart b/mobile/lib/models/conversations.dart index 2963b6b..ac18d89 100644 --- a/mobile/lib/models/conversations.dart +++ b/mobile/lib/models/conversations.dart @@ -18,21 +18,17 @@ class Conversation { String id; String userId; String conversationDetailId; - String messageThreadKey; String symmetricKey; bool admin; String name; - String? users; Conversation({ required this.id, required this.userId, required this.conversationDetailId, - required this.messageThreadKey, required this.symmetricKey, required this.admin, required this.name, - this.users, }); @@ -47,11 +43,6 @@ class Conversation { base64.decode(json['conversation_detail_id']), ); - var threadKey = AesHelper.aesDecrypt( - symmetricKeyDecrypted, - base64.decode(json['message_thread_key']), - ); - var admin = AesHelper.aesDecrypt( symmetricKeyDecrypted, base64.decode(json['admin']), @@ -61,7 +52,6 @@ class Conversation { id: json['id'], userId: json['user_id'], conversationDetailId: detailId, - messageThreadKey: threadKey, symmetricKey: base64.encode(symmetricKeyDecrypted), admin: admin == 'true', name: 'Unknown', @@ -84,11 +74,9 @@ admin: $admin'''; 'id': id, 'user_id': userId, 'conversation_detail_id': conversationDetailId, - 'message_thread_key': messageThreadKey, 'symmetric_key': symmetricKey, 'admin': admin ? 1 : 0, 'name': name, - 'users': users, }; } } @@ -105,11 +93,9 @@ Future> getConversations() async { id: maps[i]['id'], userId: maps[i]['user_id'], conversationDetailId: maps[i]['conversation_detail_id'], - messageThreadKey: maps[i]['message_thread_key'], symmetricKey: maps[i]['symmetric_key'], admin: maps[i]['admin'] == 1, name: maps[i]['name'], - users: maps[i]['users'], ); }); } diff --git a/mobile/lib/models/friends.dart b/mobile/lib/models/friends.dart index 3bd1b1e..0b94b4a 100644 --- a/mobile/lib/models/friends.dart +++ b/mobile/lib/models/friends.dart @@ -16,17 +16,19 @@ Friend findFriendByFriendId(List friends, String id) { class Friend{ String id; String userId; - String? username; + String username; String friendId; String friendSymmetricKey; + String asymmetricPublicKey; String acceptedAt; Friend({ required this.id, required this.userId, + required this.username, required this.friendId, required this.friendSymmetricKey, + required this.asymmetricPublicKey, required this.acceptedAt, - this.username }); factory Friend.fromJson(Map json, RSAPrivateKey privKey) { @@ -43,8 +45,10 @@ class Friend{ return Friend( id: json['id'], userId: json['user_id'], + username: '', friendId: String.fromCharCodes(friendIdDecrypted), friendSymmetricKey: base64.encode(friendSymmetricKeyDecrypted), + asymmetricPublicKey: '', acceptedAt: json['accepted_at'], ); } @@ -68,6 +72,7 @@ class Friend{ 'username': username, 'friend_id': friendId, 'symmetric_key': friendSymmetricKey, + 'asymmetric_public_key': asymmetricPublicKey, 'accepted_at': acceptedAt, }; } @@ -86,35 +91,35 @@ Future> getFriends() async { userId: maps[i]['user_id'], friendId: maps[i]['friend_id'], friendSymmetricKey: maps[i]['symmetric_key'], + asymmetricPublicKey: maps[i]['asymmetric_public_key'], acceptedAt: maps[i]['accepted_at'], username: maps[i]['username'], ); }); } -// Future getFriendByUserId(String userId) async { -// final db = await getDatabaseConnection(); -// -// List whereArguments = [userId]; -// -// final List> maps = await db.query( -// 'friends', -// where: 'friend_id = ?', -// whereArgs: whereArguments, -// ); -// -// print(userId); -// -// if (maps.length != 1) { -// throw ArgumentError('Invalid user id'); -// } -// -// return Friend( -// id: maps[0]['id'], -// userId: maps[0]['user_id'], -// friendId: maps[0]['friend_id'], -// friendSymmetricKey: maps[0]['symmetric_key'], -// acceptedAt: maps[0]['accepted_at'], -// username: maps[0]['username'], -// ); -// } +Future getFriendByFriendId(String userId) async { + final db = await getDatabaseConnection(); + + List whereArguments = [userId]; + + final List> maps = await db.query( + 'friends', + where: 'friend_id = ?', + whereArgs: whereArguments, + ); + + if (maps.length != 1) { + throw ArgumentError('Invalid user id'); + } + + return Friend( + id: maps[0]['id'], + userId: maps[0]['user_id'], + friendId: maps[0]['friend_id'], + friendSymmetricKey: maps[0]['symmetric_key'], + asymmetricPublicKey: maps[0]['asymmetric_public_key'], + acceptedAt: maps[0]['accepted_at'], + username: maps[0]['username'], + ); +} diff --git a/mobile/lib/models/messages.dart b/mobile/lib/models/messages.dart index 4fc3728..0cb0bef 100644 --- a/mobile/lib/models/messages.dart +++ b/mobile/lib/models/messages.dart @@ -1,8 +1,14 @@ import 'dart:convert'; +import 'dart:typed_data'; +import 'package:uuid/uuid.dart'; +import 'package:Envelope/models/conversation_users.dart'; +import 'package:Envelope/models/conversations.dart'; import 'package:pointycastle/export.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import '/utils/encryption/crypto_utils.dart'; import '/utils/encryption/aes_helper.dart'; import '/utils/storage/database.dart'; +import '/utils/strings.dart'; import '/models/friends.dart'; const messageTypeSender = 'sender'; @@ -11,49 +17,116 @@ const messageTypeReceiver = 'receiver'; class Message { String id; String symmetricKey; - String messageThreadKey; + String userSymmetricKey; String data; String senderId; String senderUsername; + String associationKey; String createdAt; Message({ required this.id, required this.symmetricKey, - required this.messageThreadKey, + required this.userSymmetricKey, required this.data, required this.senderId, required this.senderUsername, + required this.associationKey, required this.createdAt, }); factory Message.fromJson(Map json, RSAPrivateKey privKey) { - var symmetricKey = CryptoUtils.rsaDecrypt( + var userSymmetricKey = CryptoUtils.rsaDecrypt( base64.decode(json['symmetric_key']), privKey, ); - var data = AesHelper.aesDecrypt( - symmetricKey, - base64.decode(json['message_data']['data']), + var symmetricKey = AesHelper.aesDecrypt( + userSymmetricKey, + base64.decode(json['message_data']['symmetric_key']), ); var senderId = AesHelper.aesDecrypt( - symmetricKey, + base64.decode(symmetricKey), base64.decode(json['message_data']['sender_id']), ); + var data = AesHelper.aesDecrypt( + base64.decode(symmetricKey), + base64.decode(json['message_data']['data']), + ); + return Message( id: json['id'], - messageThreadKey: json['message_thread_key'], - symmetricKey: base64.encode(symmetricKey), + symmetricKey: symmetricKey, + userSymmetricKey: base64.encode(userSymmetricKey), data: data, senderId: senderId, - senderUsername: 'Unknown', // TODO + senderUsername: 'Unknown', + associationKey: json['association_key'], createdAt: json['created_at'], ); } + Future toJson(Conversation conversation, String messageDataId) async { + final preferences = await SharedPreferences.getInstance(); + RSAPublicKey publicKey = CryptoUtils.rsaPublicKeyFromPem(preferences.getString('asymmetricPublicKey')!); + + final userSymmetricKey = AesHelper.deriveKey(generateRandomString(32)); + final symmetricKey = AesHelper.deriveKey(generateRandomString(32)); + + List> messages = []; + + String id = ''; + + List conversationUsers = await getConversationUsers(conversation); + + for (var i = 0; i < conversationUsers.length; i++) { + ConversationUser user = conversationUsers[i]; + if (preferences.getString('username') == user.username) { + id = user.id; + + messages.add({ + 'message_data_id': messageDataId, + 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt( + userSymmetricKey, + publicKey, + )), + 'association_key': user.associationKey, + }); + + continue; + } + + Friend friend = await getFriendByFriendId(user.id); + RSAPublicKey friendPublicKey = CryptoUtils.rsaPublicKeyFromPem(friend.asymmetricPublicKey); + + messages.add({ + 'message_data_id': messageDataId, + 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt( + userSymmetricKey, + friendPublicKey, + )), + 'association_key': user.associationKey, + }); + } + + Map messageData = { + 'id': messageDataId, + 'data': AesHelper.aesEncrypt(symmetricKey, Uint8List.fromList(data.codeUnits)), + 'sender_id': AesHelper.aesEncrypt(symmetricKey, Uint8List.fromList(id.codeUnits)), + 'symmetric_key': AesHelper.aesEncrypt( + userSymmetricKey, + Uint8List.fromList(base64.encode(symmetricKey).codeUnits), + ), + }; + + return jsonEncode({ + 'message_data': messageData, + 'message': messages, + }); + } + @override String toString() { return ''' @@ -63,6 +136,7 @@ class Message { data: $data senderId: $senderId senderUsername: $senderUsername + associationKey: $associationKey createdAt: $createdAt '''; } @@ -70,37 +144,40 @@ class Message { Map toMap() { return { 'id': id, - 'message_thread_key': messageThreadKey, 'symmetric_key': symmetricKey, + 'user_symmetric_key': userSymmetricKey, 'data': data, 'sender_id': senderId, 'sender_username': senderUsername, + 'association_key': associationKey, 'created_at': createdAt, }; } } -Future> getMessagesForThread(String messageThreadKey) async { +Future> getMessagesForThread(Conversation conversation) async { final db = await getDatabaseConnection(); - List whereArguments = [messageThreadKey]; - - final List> maps = await db.query( - 'messages', - where: 'message_thread_key = ?', - whereArgs: whereArguments, - orderBy: 'created_at DESC', + final List> maps = await db.rawQuery( + ''' + SELECT * FROM messages WHERE association_key IN ( + SELECT association_key FROM conversation_users WHERE conversation_id = ? + ) + ORDER BY created_at DESC; + ''', + [conversation.id] ); return List.generate(maps.length, (i) { return Message( id: maps[i]['id'], - messageThreadKey: maps[i]['message_thread_key'], symmetricKey: maps[i]['symmetric_key'], + userSymmetricKey: maps[i]['user_symmetric_key'], data: maps[i]['data'], senderId: maps[i]['sender_id'], senderUsername: maps[i]['sender_username'], + associationKey: maps[i]['association_key'], createdAt: maps[i]['created_at'], ); }); diff --git a/mobile/lib/utils/storage/conversations.dart b/mobile/lib/utils/storage/conversations.dart index b2c5266..749bd67 100644 --- a/mobile/lib/utils/storage/conversations.dart +++ b/mobile/lib/utils/storage/conversations.dart @@ -4,6 +4,7 @@ import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:pointycastle/export.dart'; import 'package:sqflite/sqflite.dart'; import '/models/conversations.dart'; +import '/models/conversation_users.dart'; import '/utils/storage/database.dart'; import '/utils/storage/session_cookie.dart'; import '/utils/storage/encryption_keys.dart'; @@ -65,15 +66,30 @@ Future updateConversations() async { base64.decode(conversationDetailJson['name']), ); - conversation.users = AesHelper.aesDecrypt( - base64.decode(conversation.symmetricKey), - base64.decode(conversationDetailJson['users']), - ); - await db.insert( 'conversations', conversation.toMap(), conflictAlgorithm: ConflictAlgorithm.replace, ); + + List usersData = json.decode( + AesHelper.aesDecrypt( + base64.decode(conversation.symmetricKey), + base64.decode(conversationDetailJson['users']), + ) + ); + + for (var i = 0; i < usersData.length; i++) { + ConversationUser conversationUser = ConversationUser.fromJson( + usersData[i] as Map, + conversation.id, + ); + + await db.insert( + 'conversation_users', + conversationUser.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } } } diff --git a/mobile/lib/utils/storage/database.dart b/mobile/lib/utils/storage/database.dart index 3be45e7..41419e5 100644 --- a/mobile/lib/utils/storage/database.dart +++ b/mobile/lib/utils/storage/database.dart @@ -24,6 +24,7 @@ Future getDatabaseConnection() async { username TEXT, friend_id TEXT, symmetric_key TEXT, + asymmetric_public_key TEXT, accepted_at TEXT ); '''); @@ -35,7 +36,6 @@ Future getDatabaseConnection() async { id TEXT PRIMARY KEY, user_id TEXT, conversation_detail_id TEXT, - message_thread_key TEXT, symmetric_key TEXT, admin INTEGER, name TEXT, @@ -43,18 +43,32 @@ Future getDatabaseConnection() async { ); '''); + await db.execute( + ''' + CREATE TABLE IF NOT EXISTS conversation_users( + id TEXT PRIMARY KEY, + conversation_id TEXT, + username TEXT, + data TEXT, + association_key TEXT, + admin TEXT + ); + '''); + await db.execute( ''' CREATE TABLE IF NOT EXISTS messages( id TEXT PRIMARY KEY, - message_thread_key TEXT, symmetric_key TEXT, + user_symmetric_key TEXT, data TEXT, sender_id TEXT, sender_username TEXT, + association_key TEXT, created_at TEXT ); '''); + }, // Set the version. This executes the onCreate function and provides a // path to perform database upgrades and downgrades. diff --git a/mobile/lib/utils/storage/friends.dart b/mobile/lib/utils/storage/friends.dart index 529bbcf..a4fc827 100644 --- a/mobile/lib/utils/storage/friends.dart +++ b/mobile/lib/utils/storage/friends.dart @@ -67,6 +67,8 @@ Future updateFriends() async { base64.decode(friendJson['username']), ); + friend.asymmetricPublicKey = friendJson['asymmetric_public_key']; + await db.insert( 'friends', friend.toMap(), diff --git a/mobile/lib/utils/storage/messages.dart b/mobile/lib/utils/storage/messages.dart index c2fb659..33c13e6 100644 --- a/mobile/lib/utils/storage/messages.dart +++ b/mobile/lib/utils/storage/messages.dart @@ -1,76 +1,112 @@ import 'dart:convert'; -import 'package:Envelope/models/messages.dart'; +import 'package:uuid/uuid.dart'; +import 'package:Envelope/models/conversation_users.dart'; +import 'package:intl/intl.dart'; import 'package:http/http.dart' as http; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:pointycastle/export.dart'; import 'package:sqflite/sqflite.dart'; -import 'package:Envelope/models/conversations.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import '/utils/storage/session_cookie.dart'; import '/utils/storage/encryption_keys.dart'; import '/utils/storage/database.dart'; import '/models/conversations.dart'; - -// TODO: Move this to table -Map> _mapUsers(String users) { - List usersJson = jsonDecode(users); - - Map> mapped = {}; - - for (var i = 0; i < usersJson.length; i++) { - mapped[usersJson[i]['id']] = { - 'username': usersJson[i]['username'], - 'admin': usersJson[i]['admin'], - }; - } - - return mapped; -} +import '/models/messages.dart'; Future updateMessageThread(Conversation conversation, {RSAPrivateKey? privKey}) async { - privKey ??= await getPrivateKey(); - - var resp = await http.get( - Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/messages/${conversation.messageThreadKey}'), - headers: { - 'cookie': await getSessionCookie(), - } + privKey ??= await getPrivateKey(); + final preferences = await SharedPreferences.getInstance(); + String username = preferences.getString('username')!; + ConversationUser currentUser = await getConversationUserByUsername(conversation, username); + + var resp = await http.get( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/messages/${currentUser.associationKey}'), + headers: { + 'cookie': await getSessionCookie(), + } + ); + + if (resp.statusCode != 200) { + throw Exception(resp.body); + } + + List messageThreadJson = jsonDecode(resp.body); + + final db = await getDatabaseConnection(); + + for (var i = 0; i < messageThreadJson.length; i++) { + Message message = Message.fromJson( + messageThreadJson[i] as Map, + privKey, ); - if (resp.statusCode != 200) { - throw Exception(resp.body); - } - - var mapped = _mapUsers(conversation.users!); + ConversationUser messageUser = await getConversationUserById(conversation, message.senderId); + message.senderUsername = messageUser.username; - List messageThreadJson = jsonDecode(resp.body); - - final db = await getDatabaseConnection(); - - for (var i = 0; i < messageThreadJson.length; i++) { - Message message = Message.fromJson( - messageThreadJson[i] as Map, - privKey, - ); - - // TODO: Fix this - message.senderUsername = mapped[message.senderId]!['username']!; - - await db.insert( - 'messages', - message.toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, - ); - - } + await db.insert( + 'messages', + message.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } } Future updateMessageThreads({List? conversations}) async { - RSAPrivateKey privKey = await getPrivateKey(); + RSAPrivateKey privKey = await getPrivateKey(); - conversations ??= await getConversations(); + conversations ??= await getConversations(); - for (var i = 0; i < conversations.length; i++) { - await updateMessageThread(conversations[i], privKey: privKey); - } + for (var i = 0; i < conversations.length; i++) { + await updateMessageThread(conversations[i], privKey: privKey); + } } +Future sendMessage(Conversation conversation, String data) async { + final preferences = await SharedPreferences.getInstance(); + final userId = preferences.getString('userId'); + final username = preferences.getString('username'); + if (userId == null || username == null) { + throw Exception('Invalid user id'); + } + + var uuid = const Uuid(); + final String messageDataId = uuid.v4(); + + ConversationUser currentUser = await getConversationUserByUsername(conversation, username); + + + Message message = Message( + id: messageDataId, + symmetricKey: '', + userSymmetricKey: '', + senderId: userId, + senderUsername: username, + data: data, + createdAt: DateTime.now().toIso8601String(), + associationKey: currentUser.associationKey, + ); + + final db = await getDatabaseConnection(); + + print(await db.query('messages')); + + await db.insert( + 'messages', + message.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + + String messageJson = await message.toJson(conversation, messageDataId); + + final resp = await http.post( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/message'), + headers: { + 'Content-Type': 'application/json; charset=UTF-8', + 'cookie': await getSessionCookie(), + }, + body: messageJson, + ); + + // TODO: If statusCode not successfull, mark as needing resend + print(resp.statusCode); +} diff --git a/mobile/lib/utils/strings.dart b/mobile/lib/utils/strings.dart new file mode 100644 index 0000000..1c8b117 --- /dev/null +++ b/mobile/lib/utils/strings.dart @@ -0,0 +1,8 @@ +import 'dart:math'; + +String generateRandomString(int len) { + var r = Random(); + const _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890'; + return List.generate(len, (index) => _chars[r.nextInt(_chars.length)]).join(); +} + diff --git a/mobile/lib/views/authentication/login.dart b/mobile/lib/views/authentication/login.dart index b702f11..9802423 100644 --- a/mobile/lib/views/authentication/login.dart +++ b/mobile/lib/views/authentication/login.dart @@ -14,6 +14,7 @@ class LoginResponse { final String asymmetricPublicKey; final String asymmetricPrivateKey; final String userId; + final String username; const LoginResponse({ required this.status, @@ -21,6 +22,7 @@ class LoginResponse { required this.asymmetricPublicKey, required this.asymmetricPrivateKey, required this.userId, + required this.username, }); factory LoginResponse.fromJson(Map json) { @@ -30,6 +32,7 @@ class LoginResponse { asymmetricPublicKey: json['asymmetric_public_key'], asymmetricPrivateKey: json['asymmetric_private_key'], userId: json['user_id'], + username: json['username'], ); } } @@ -60,14 +63,14 @@ Future login(context, String username, String password) async { var rsaPrivPem = AesHelper.aesDecrypt(password, base64.decode(response.asymmetricPrivateKey)); - debugPrint(rsaPrivPem); - var rsaPriv = CryptoUtils.rsaPrivateKeyFromPem(rsaPrivPem); setPrivateKey(rsaPriv); final preferences = await SharedPreferences.getInstance(); preferences.setBool('islogin', true); preferences.setString('userId', response.userId); + preferences.setString('username', response.username); + preferences.setString('asymmetricPublicKey', response.asymmetricPublicKey); return response; } @@ -75,8 +78,6 @@ Future login(context, String username, String password) async { class Login extends StatelessWidget { const Login({Key? key}) : super(key: key); - static const String _title = 'Envelope'; - @override Widget build(BuildContext context) { return Scaffold( diff --git a/mobile/lib/views/authentication/signup.dart b/mobile/lib/views/authentication/signup.dart index d179a21..74425c3 100644 --- a/mobile/lib/views/authentication/signup.dart +++ b/mobile/lib/views/authentication/signup.dart @@ -47,25 +47,19 @@ Future signUp(context, String username, String password, String 'asymmetric_private_key': encRsaPriv, }), ); - + SignupResponse response = SignupResponse.fromJson(jsonDecode(resp.body)); if (resp.statusCode != 201) { throw Exception(response.message); } - debugPrint(rsaPubPem); - debugPrint(rsaPrivPem); - debugPrint(resp.body); - return response; } class Signup extends StatelessWidget { const Signup({Key? key}) : super(key: key); - static const String _title = 'Envelope'; - @override Widget build(BuildContext context) { return Scaffold( @@ -113,7 +107,7 @@ class _SignupWidgetState extends State { minimumSize: const Size.fromHeight(50), padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), textStyle: const TextStyle( - fontSize: 20, + fontSize: 20, fontWeight: FontWeight.bold, color: Colors.red, ), diff --git a/mobile/lib/views/main/conversation_detail.dart b/mobile/lib/views/main/conversation_detail.dart index aaa158e..c3f0bb4 100644 --- a/mobile/lib/views/main/conversation_detail.dart +++ b/mobile/lib/views/main/conversation_detail.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '/models/conversations.dart'; import '/models/messages.dart'; +import '/utils/storage/messages.dart'; String convertToAgo(String input){ DateTime time = DateTime.parse(input); @@ -36,7 +37,9 @@ class ConversationDetail extends StatefulWidget{ class _ConversationDetailState extends State { List messages = []; - String userId = ''; + String username = ''; + + TextEditingController msgController = TextEditingController(); @override void initState() { @@ -44,10 +47,10 @@ class _ConversationDetailState extends State { fetchMessages(); } - void fetchMessages() async { + Future fetchMessages() async { final preferences = await SharedPreferences.getInstance(); - userId = preferences.getString('userId')!; - messages = await getMessagesForThread(widget.conversation.messageThreadKey); + username = preferences.getString('username')!; + messages = await getMessagesForThread(widget.conversation); setState(() {}); } @@ -84,7 +87,7 @@ class _ConversationDetailState extends State { ], ), ), - const Icon(Icons.settings,color: Colors.black54,), + const Icon(Icons.settings,color: Colors.black54), ], ), ), @@ -95,35 +98,35 @@ class _ConversationDetailState extends State { ListView.builder( itemCount: messages.length, shrinkWrap: true, - padding: const EdgeInsets.only(top: 10,bottom: 10), + padding: const EdgeInsets.only(top: 10,bottom: 90), reverse: true, itemBuilder: (context, index) { return Container( padding: const EdgeInsets.only(left: 14,right: 14,top: 0,bottom: 0), child: Align( alignment: ( - messages[index].senderId == userId ? - Alignment.topLeft: - Alignment.topRight + messages[index].senderUsername == username ? + Alignment.topRight : + Alignment.topLeft ), child: Column( - crossAxisAlignment: messages[index].senderId == userId ? - CrossAxisAlignment.start : - CrossAxisAlignment.end, + crossAxisAlignment: messages[index].senderUsername == username ? + CrossAxisAlignment.end : + CrossAxisAlignment.start, children: [ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: ( - messages[index].senderId == userId ? - Colors.grey.shade200 : - Colors.blue[200] + messages[index].senderUsername == username ? + Colors.blue[200] : + Colors.grey.shade200 ), ), padding: const EdgeInsets.all(12), child: Text(messages[index].data, style: const TextStyle(fontSize: 15)), ), - messages[index].senderId != userId ? + messages[index].senderUsername != username ? Text(messages[index].senderUsername) : const SizedBox.shrink(), Text( @@ -167,24 +170,32 @@ class _ConversationDetailState extends State { ), ), const SizedBox(width: 15,), - const Expanded( + Expanded( child: TextField( - decoration: InputDecoration( + decoration: const InputDecoration( hintText: "Write message...", hintStyle: TextStyle(color: Colors.black54), border: InputBorder.none, ), maxLines: null, + controller: msgController, ), ), - const SizedBox(width: 15,), + const SizedBox(width: 15), FloatingActionButton( - onPressed: () { + onPressed: () async { + if (msgController.text == '') { + return; + } + await sendMessage(widget.conversation, msgController.text); + messages = await getMessagesForThread(widget.conversation); + setState(() {}); + msgController.text = ''; }, child: const Icon(Icons.send,color: Colors.white,size: 18,), backgroundColor: Colors.blue, - elevation: 0, ), + const SizedBox(width: 10), ], ), ), diff --git a/mobile/lib/views/main/conversation_list.dart b/mobile/lib/views/main/conversation_list.dart index 7ff74b6..1636f4f 100644 --- a/mobile/lib/views/main/conversation_list.dart +++ b/mobile/lib/views/main/conversation_list.dart @@ -1,110 +1,133 @@ import 'package:flutter/material.dart'; import '/models/conversations.dart'; import '/views/main/conversation_list_item.dart'; -import '/utils/storage/messages.dart'; class ConversationList extends StatefulWidget { - const ConversationList({Key? key}) : super(key: key); + final List conversations; + const ConversationList({ + Key? key, + required this.conversations, + }) : super(key: key); - @override - State createState() => _ConversationListState(); + @override + State createState() => _ConversationListState(); } class _ConversationListState extends State { - List conversations = []; + List conversations = []; - @override - void initState() { - super.initState(); - fetchConversations(); - } - - void fetchConversations() async { - conversations = await getConversations(); - setState(() {}); - } + @override + void initState() { + super.initState(); + conversations.addAll(widget.conversations); + setState(() {}); + } - Widget list() { + void filterSearchResults(String query) { + List dummySearchList = []; + dummySearchList.addAll(widget.conversations); - if (conversations.isEmpty) { - return const Center( - child: Text('No Conversations'), - ); + if(query.isNotEmpty) { + List dummyListData = []; + dummySearchList.forEach((item) { + if (item.name.toLowerCase().contains(query)) { + dummyListData.add(item); } - - return ListView.builder( - itemCount: conversations.length, - shrinkWrap: true, - padding: const EdgeInsets.only(top: 16), - physics: const NeverScrollableScrollPhysics(), - itemBuilder: (context, i) { - return ConversationListItem( - conversation: conversations[i], - ); - }, - ); + }); + setState(() { + conversations.clear(); + conversations.addAll(dummyListData); + }); + return; } - @override - Widget build(BuildContext context) { - return Scaffold( - body: SingleChildScrollView( - physics: const BouncingScrollPhysics(), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SafeArea( - child: Padding( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Text("Conversations",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), - Container( - padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), - height: 30, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(30), - color: Colors.pink[50], - ), - child: Row( - children: const [ - Icon(Icons.add,color: Colors.pink,size: 20,), - SizedBox(width: 2,), - Text("Add",style: TextStyle(fontSize: 14,fontWeight: FontWeight.bold),), - ], - ), - ) - ], - ), - ), - ), - Padding( - padding: const EdgeInsets.only(top: 16,left: 16,right: 16), - child: TextField( - decoration: InputDecoration( - hintText: "Search...", - hintStyle: TextStyle(color: Colors.grey.shade600), - prefixIcon: Icon(Icons.search,color: Colors.grey.shade600, size: 20,), - filled: true, - fillColor: Colors.grey.shade100, - contentPadding: const EdgeInsets.all(8), - enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(20), - borderSide: BorderSide( - color: Colors.grey.shade100 - ) - ), - ), - ), - ), - Padding( - padding: const EdgeInsets.only(top: 16,left: 16,right: 16), - child: list(), - ), - ], - ), - ), - ); + setState(() { + conversations.clear(); + conversations.addAll(widget.conversations); + }); + } + + Widget list() { + if (conversations.isEmpty) { + return const Center( + child: Text('No Conversations'), + ); } + + return ListView.builder( + itemCount: conversations.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 16), + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, i) { + return ConversationListItem( + conversation: conversations[i], + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SafeArea( + child: Padding( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text("Conversations",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), + Container( + padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), + height: 30, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(30), + color: Colors.pink[50], + ), + child: Row( + children: const [ + Icon(Icons.add,color: Colors.pink,size: 20,), + SizedBox(width: 2,), + Text("Add",style: TextStyle(fontSize: 14,fontWeight: FontWeight.bold),), + ], + ), + ) + ], + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: TextField( + decoration: InputDecoration( + hintText: "Search...", + hintStyle: TextStyle(color: Colors.grey.shade600), + prefixIcon: Icon(Icons.search,color: Colors.grey.shade600, size: 20,), + filled: true, + fillColor: Colors.grey.shade100, + contentPadding: const EdgeInsets.all(8), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(20), + borderSide: BorderSide( + color: Colors.grey.shade100 + ) + ), + ), + onChanged: (value) => filterSearchResults(value.toLowerCase()) + ), + ), + Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: list(), + ), + ], + ), + ), + ); + } } diff --git a/mobile/lib/views/main/friend_list.dart b/mobile/lib/views/main/friend_list.dart index 2437672..719c57c 100644 --- a/mobile/lib/views/main/friend_list.dart +++ b/mobile/lib/views/main/friend_list.dart @@ -3,108 +3,133 @@ import '/models/friends.dart'; import '/views/main/friend_list_item.dart'; class FriendList extends StatefulWidget { - const FriendList({Key? key}) : super(key: key); + final List friends; + const FriendList({ + Key? key, + required this.friends, + }) : super(key: key); - @override - State createState() => _FriendListState(); + @override + State createState() => _FriendListState(); } class _FriendListState extends State { - List friends = []; + List friends = []; + List friendsDuplicate = []; - @override - void initState() { - super.initState(); - fetchFriends(); - } - - void fetchFriends() async { - friends = await getFriends(); - setState(() {}); - } + @override + void initState() { + super.initState(); + friends.addAll(widget.friends); + setState(() {}); + } - Widget list() { + void filterSearchResults(String query) { + List dummySearchList = []; + dummySearchList.addAll(widget.friends); - if (friends.isEmpty) { - return const Center( - child: Text('No Friends'), - ); + if(query.isNotEmpty) { + List dummyListData = []; + dummySearchList.forEach((item) { + if(item.username.toLowerCase().contains(query)) { + dummyListData.add(item); } + }); + setState(() { + friends.clear(); + friends.addAll(dummyListData); + }); + return; + } - return ListView.builder( - itemCount: friends.length, - shrinkWrap: true, - padding: const EdgeInsets.only(top: 16), - physics: const NeverScrollableScrollPhysics(), - itemBuilder: (context, i) { - return FriendListItem( - id: friends[i].id, - username: friends[i].username!, - ); - }, - ); + setState(() { + friends.clear(); + friends.addAll(widget.friends); + }); + } + + Widget list() { + if (friends.isEmpty) { + return const Center( + child: Text('No Friends'), + ); } - @override - Widget build(BuildContext context) { - return Scaffold( - body: SingleChildScrollView( - physics: const BouncingScrollPhysics(), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SafeArea( - child: Padding( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Text("Friends",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), - Container( - padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), - height: 30, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(30), - color: Colors.pink[50], - ), - child: Row( - children: const [ - Icon(Icons.add,color: Colors.pink,size: 20,), - SizedBox(width: 2,), - Text("Add",style: TextStyle(fontSize: 14,fontWeight: FontWeight.bold),), - ], - ), - ) - ], - ), - ), - ), - Padding( - padding: const EdgeInsets.only(top: 16,left: 16,right: 16), - child: TextField( - decoration: InputDecoration( - hintText: "Search...", - hintStyle: TextStyle(color: Colors.grey.shade600), - prefixIcon: Icon(Icons.search,color: Colors.grey.shade600, size: 20,), - filled: true, - fillColor: Colors.grey.shade100, - contentPadding: const EdgeInsets.all(8), - enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(20), - borderSide: BorderSide( - color: Colors.grey.shade100 - ) - ), - ), - ), - ), - Padding( - padding: const EdgeInsets.only(top: 16,left: 16,right: 16), - child: list(), - ), - ], + return ListView.builder( + itemCount: friends.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 16), + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, i) { + return FriendListItem( + id: friends[i].id, + username: friends[i].username, + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SafeArea( + child: Padding( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text("Friends",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), + Container( + padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), + height: 30, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(30), + color: Colors.pink[50], + ), + child: Row( + children: const [ + Icon(Icons.add,color: Colors.pink,size: 20,), + SizedBox(width: 2,), + Text("Add",style: TextStyle(fontSize: 14,fontWeight: FontWeight.bold),), + ], + ), + ) + ], + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: TextField( + decoration: InputDecoration( + hintText: "Search...", + hintStyle: TextStyle(color: Colors.grey.shade600), + prefixIcon: Icon(Icons.search,color: Colors.grey.shade600, size: 20,), + filled: true, + fillColor: Colors.grey.shade100, + contentPadding: const EdgeInsets.all(8), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(20), + borderSide: BorderSide( + color: Colors.grey.shade100 + ) + ), ), + onChanged: (value) => filterSearchResults(value.toLowerCase()) ), - ); - } + ), + Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: list(), + ), + ], + ), + ), + ); + } } diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index 7d4e6e9..06c6295 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -6,6 +6,8 @@ import '/views/main/profile.dart'; import '/utils/storage/friends.dart'; import '/utils/storage/conversations.dart'; import '/utils/storage/messages.dart'; +import '/models/conversations.dart'; +import '/models/friends.dart'; class Home extends StatefulWidget { const Home({Key? key}) : super(key: key); @@ -15,6 +17,17 @@ class Home extends StatefulWidget { } class _HomeState extends State { + List conversations = []; + List friends = []; + + bool isLoading = true; + int _selectedIndex = 0; + List _widgetOptions = [ + const ConversationList(conversations: []), + const FriendList(friends: []), + const Profile(), + ]; + @override void initState() { super.initState(); @@ -26,6 +39,18 @@ class _HomeState extends State { await updateFriends(); await updateConversations(); await updateMessageThreads(); + + conversations = await getConversations(); + friends = await getFriends(); + + setState(() { + _widgetOptions = [ + ConversationList(conversations: conversations), + FriendList(friends: friends), + const Profile(), + ]; + isLoading = false; + }); } // TODO: Do server GET check here @@ -36,26 +61,41 @@ class _HomeState extends State { } } - int _selectedIndex = 0; - static const List _widgetOptions = [ - ConversationList(), - FriendList(), - Profile(), - ]; - void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } + Widget loading() { + return Stack( + children: [ + const Opacity( + opacity: 0.1, + child: ModalBarrier(dismissible: false, color: Colors.black), + ), + Center( + child: Column( + mainAxisSize: MainAxisSize.max, + mainAxisAlignment: MainAxisAlignment.center, + children: const [ + CircularProgressIndicator(), + SizedBox(height: 25), + Text("Loading..."), + ], + ) + ), + ] + ); + } + @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async => false, child: Scaffold( - body: _widgetOptions.elementAt(_selectedIndex), - bottomNavigationBar: BottomNavigationBar( + body: isLoading ? loading() : _widgetOptions.elementAt(_selectedIndex), + bottomNavigationBar: isLoading ? const SizedBox.shrink() : BottomNavigationBar( currentIndex: _selectedIndex, onTap: _onItemTapped, selectedItemColor: Colors.red, diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock index c7d9286..0f77a70 100644 --- a/mobile/pubspec.lock +++ b/mobile/pubspec.lock @@ -57,6 +57,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "3.0.1" + crypto: + dependency: transitive + description: + name: crypto + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.2" cupertino_icons: dependency: "direct main" description: @@ -135,6 +142,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "4.0.1" + intl: + dependency: "direct main" + description: + name: intl + url: "https://pub.dartlang.org" + source: hosted + version: "0.17.0" js: dependency: transitive description: @@ -357,6 +371,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.3.0" + uuid: + dependency: "direct main" + description: + name: uuid + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.6" vector_math: dependency: transitive description: diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml index 9dffd90..ded0ef6 100644 --- a/mobile/pubspec.yaml +++ b/mobile/pubspec.yaml @@ -20,6 +20,8 @@ dependencies: sqflite: ^2.0.2 path: 1.8.1 flutter_dotenv: ^5.0.2 + intl: ^0.17.0 + uuid: ^3.0.6 dev_dependencies: flutter_test: -- 2.17.1 From 66810ac55ef51349e20fca8376df8f8f50d0baaa Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Mon, 4 Jul 2022 07:38:16 +0930 Subject: [PATCH 10/24] Fix login check on initial load, add failed to send message --- Backend/Api/Auth/Check.go | 9 ++ Backend/Api/Routes.go | 2 + mobile/lib/models/messages.dart | 6 +- mobile/lib/utils/storage/conversations.dart | 96 ++++++++++--------- mobile/lib/utils/storage/database.dart | 3 +- mobile/lib/utils/storage/friends.dart | 67 +++++++------ mobile/lib/utils/storage/messages.dart | 58 +++++++---- mobile/lib/views/authentication/login.dart | 2 +- .../lib/views/main/conversation_detail.dart | 32 ++++++- mobile/lib/views/main/home.dart | 43 ++++++++- mobile/lib/views/main/profile.dart | 4 +- 11 files changed, 213 insertions(+), 109 deletions(-) create mode 100644 Backend/Api/Auth/Check.go diff --git a/Backend/Api/Auth/Check.go b/Backend/Api/Auth/Check.go new file mode 100644 index 0000000..e503183 --- /dev/null +++ b/Backend/Api/Auth/Check.go @@ -0,0 +1,9 @@ +package Auth + +import ( + "net/http" +) + +func Check(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) +} diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index 7d528ed..5aee439 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -59,6 +59,8 @@ func InitApiEndpoints(router *mux.Router) { authApi = api.PathPrefix("/auth/").Subrouter() authApi.Use(authenticationMiddleware) + authApi.HandleFunc("/check", Auth.Check).Methods("GET") + // Define routes for friends and friend requests authApi.HandleFunc("/friend_requests", Friends.EncryptedFriendRequestList).Methods("GET") authApi.HandleFunc("/friend_request", Friends.CreateFriendRequest).Methods("POST") diff --git a/mobile/lib/models/messages.dart b/mobile/lib/models/messages.dart index 0cb0bef..ae0edac 100644 --- a/mobile/lib/models/messages.dart +++ b/mobile/lib/models/messages.dart @@ -1,6 +1,5 @@ import 'dart:convert'; import 'dart:typed_data'; -import 'package:uuid/uuid.dart'; import 'package:Envelope/models/conversation_users.dart'; import 'package:Envelope/models/conversations.dart'; import 'package:pointycastle/export.dart'; @@ -23,6 +22,7 @@ class Message { String senderUsername; String associationKey; String createdAt; + bool failedToSend; Message({ required this.id, required this.symmetricKey, @@ -32,6 +32,7 @@ class Message { required this.senderUsername, required this.associationKey, required this.createdAt, + required this.failedToSend, }); @@ -65,6 +66,7 @@ class Message { senderUsername: 'Unknown', associationKey: json['association_key'], createdAt: json['created_at'], + failedToSend: false, ); } @@ -151,6 +153,7 @@ class Message { 'sender_username': senderUsername, 'association_key': associationKey, 'created_at': createdAt, + 'failed_to_send': failedToSend ? 1 : 0, }; } @@ -179,6 +182,7 @@ Future> getMessagesForThread(Conversation conversation) async { senderUsername: maps[i]['sender_username'], associationKey: maps[i]['association_key'], createdAt: maps[i]['created_at'], + failedToSend: maps[i]['failed_to_send'] == 1, ); }); diff --git a/mobile/lib/utils/storage/conversations.dart b/mobile/lib/utils/storage/conversations.dart index 749bd67..fa4564e 100644 --- a/mobile/lib/utils/storage/conversations.dart +++ b/mobile/lib/utils/storage/conversations.dart @@ -13,63 +13,64 @@ import '/utils/encryption/aes_helper.dart'; Future updateConversations() async { RSAPrivateKey privKey = await getPrivateKey(); - var resp = await http.get( - Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), - headers: { - 'cookie': await getSessionCookie(), - } - ); - - if (resp.statusCode != 200) { + try { + var resp = await http.get( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), + headers: { + 'cookie': await getSessionCookie(), + } + ); + + if (resp.statusCode != 200) { throw Exception(resp.body); - } + } - List conversations = []; - List conversationsDetailIds = []; + List conversations = []; + List conversationsDetailIds = []; - List conversationsJson = jsonDecode(resp.body); + List conversationsJson = jsonDecode(resp.body); - for (var i = 0; i < conversationsJson.length; i++) { + for (var i = 0; i < conversationsJson.length; i++) { Conversation conversation = Conversation.fromJson( - conversationsJson[i] as Map, - privKey, + conversationsJson[i] as Map, + privKey, ); conversations.add(conversation); conversationsDetailIds.add(conversation.conversationDetailId); - } + } - Map params = {}; - params['conversation_detail_ids'] = conversationsDetailIds.join(','); - var uri = Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversation_details'); - uri = uri.replace(queryParameters: params); + Map params = {}; + params['conversation_detail_ids'] = conversationsDetailIds.join(','); + var uri = Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversation_details'); + uri = uri.replace(queryParameters: params); - resp = await http.get( - uri, - headers: { - 'cookie': await getSessionCookie(), - } - ); + resp = await http.get( + uri, + headers: { + 'cookie': await getSessionCookie(), + } + ); - if (resp.statusCode != 200) { + if (resp.statusCode != 200) { throw Exception(resp.body); - } + } - final db = await getDatabaseConnection(); + final db = await getDatabaseConnection(); - List conversationsDetailsJson = jsonDecode(resp.body); - for (var i = 0; i < conversationsDetailsJson.length; i++) { + List conversationsDetailsJson = jsonDecode(resp.body); + for (var i = 0; i < conversationsDetailsJson.length; i++) { var conversationDetailJson = conversationsDetailsJson[i] as Map; var conversation = findConversationByDetailId(conversations, conversationDetailJson['id']); conversation.name = AesHelper.aesDecrypt( - base64.decode(conversation.symmetricKey), - base64.decode(conversationDetailJson['name']), + base64.decode(conversation.symmetricKey), + base64.decode(conversationDetailJson['name']), ); await db.insert( - 'conversations', - conversation.toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, + 'conversations', + conversation.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, ); List usersData = json.decode( @@ -80,16 +81,19 @@ Future updateConversations() async { ); for (var i = 0; i < usersData.length; i++) { - ConversationUser conversationUser = ConversationUser.fromJson( - usersData[i] as Map, - conversation.id, - ); - - await db.insert( - 'conversation_users', - conversationUser.toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, - ); + ConversationUser conversationUser = ConversationUser.fromJson( + usersData[i] as Map, + conversation.id, + ); + + await db.insert( + 'conversation_users', + conversationUser.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); } + } + } catch (SocketException) { + return; } } diff --git a/mobile/lib/utils/storage/database.dart b/mobile/lib/utils/storage/database.dart index 41419e5..86e2a31 100644 --- a/mobile/lib/utils/storage/database.dart +++ b/mobile/lib/utils/storage/database.dart @@ -65,7 +65,8 @@ Future getDatabaseConnection() async { sender_id TEXT, sender_username TEXT, association_key TEXT, - created_at TEXT + created_at TEXT, + failed_to_send INTEGER ); '''); diff --git a/mobile/lib/utils/storage/friends.dart b/mobile/lib/utils/storage/friends.dart index a4fc827..f3347cb 100644 --- a/mobile/lib/utils/storage/friends.dart +++ b/mobile/lib/utils/storage/friends.dart @@ -10,17 +10,18 @@ import '/utils/storage/session_cookie.dart'; import '/utils/encryption/aes_helper.dart'; Future updateFriends() async { - RSAPrivateKey privKey = await getPrivateKey(); + RSAPrivateKey privKey = await getPrivateKey(); + try { var resp = await http.get( - Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friend_requests'), - headers: { - 'cookie': await getSessionCookie(), - } + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friend_requests'), + headers: { + 'cookie': await getSessionCookie(), + } ); if (resp.statusCode != 200) { - throw Exception(resp.body); + throw Exception(resp.body); } List friends = []; @@ -29,14 +30,14 @@ Future updateFriends() async { List friendsRequestJson = jsonDecode(resp.body); for (var i = 0; i < friendsRequestJson.length; i++) { - friends.add( - Friend.fromJson( - friendsRequestJson[i] as Map, - privKey, - ) - ); - - friendIds.add(friends[i].friendId); + friends.add( + Friend.fromJson( + friendsRequestJson[i] as Map, + privKey, + ) + ); + + friendIds.add(friends[i].friendId); } Map params = {}; @@ -45,35 +46,39 @@ Future updateFriends() async { uri = uri.replace(queryParameters: params); resp = await http.get( - uri, - headers: { - 'cookie': await getSessionCookie(), - } + uri, + headers: { + 'cookie': await getSessionCookie(), + } ); if (resp.statusCode != 200) { - throw Exception(resp.body); + throw Exception(resp.body); } final db = await getDatabaseConnection(); List friendsJson = jsonDecode(resp.body); for (var i = 0; i < friendsJson.length; i++) { - var friendJson = friendsJson[i] as Map; - var friend = findFriendByFriendId(friends, friendJson['id']); + var friendJson = friendsJson[i] as Map; + var friend = findFriendByFriendId(friends, friendJson['id']); - friend.username = AesHelper.aesDecrypt( - base64.decode(friend.friendSymmetricKey), - base64.decode(friendJson['username']), - ); + friend.username = AesHelper.aesDecrypt( + base64.decode(friend.friendSymmetricKey), + base64.decode(friendJson['username']), + ); - friend.asymmetricPublicKey = friendJson['asymmetric_public_key']; + friend.asymmetricPublicKey = friendJson['asymmetric_public_key']; - await db.insert( - 'friends', - friend.toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, - ); + await db.insert( + 'friends', + friend.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); } + + } catch (SocketException) { + return; + } } diff --git a/mobile/lib/utils/storage/messages.dart b/mobile/lib/utils/storage/messages.dart index 33c13e6..ea9457f 100644 --- a/mobile/lib/utils/storage/messages.dart +++ b/mobile/lib/utils/storage/messages.dart @@ -52,12 +52,16 @@ Future updateMessageThread(Conversation conversation, {RSAPrivateKey? priv } Future updateMessageThreads({List? conversations}) async { - RSAPrivateKey privKey = await getPrivateKey(); + try { + RSAPrivateKey privKey = await getPrivateKey(); - conversations ??= await getConversations(); + conversations ??= await getConversations(); - for (var i = 0; i < conversations.length; i++) { - await updateMessageThread(conversations[i], privKey: privKey); + for (var i = 0; i < conversations.length; i++) { + await updateMessageThread(conversations[i], privKey: privKey); + } + } catch(SocketException) { + return; } } @@ -74,7 +78,6 @@ Future sendMessage(Conversation conversation, String data) async { ConversationUser currentUser = await getConversationUserByUsername(conversation, username); - Message message = Message( id: messageDataId, symmetricKey: '', @@ -82,31 +85,44 @@ Future sendMessage(Conversation conversation, String data) async { senderId: userId, senderUsername: username, data: data, - createdAt: DateTime.now().toIso8601String(), associationKey: currentUser.associationKey, + createdAt: DateTime.now().toIso8601String(), + failedToSend: false, ); final db = await getDatabaseConnection(); - print(await db.query('messages')); - await db.insert( 'messages', message.toMap(), conflictAlgorithm: ConflictAlgorithm.replace, ); - String messageJson = await message.toJson(conversation, messageDataId); - - final resp = await http.post( - Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/message'), - headers: { - 'Content-Type': 'application/json; charset=UTF-8', - 'cookie': await getSessionCookie(), - }, - body: messageJson, - ); - - // TODO: If statusCode not successfull, mark as needing resend - print(resp.statusCode); + String sessionCookie = await getSessionCookie(); + + message.toJson(conversation, messageDataId) + .then((messageJson) { + return http.post( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/message'), + headers: { + 'Content-Type': 'application/json; charset=UTF-8', + 'cookie': sessionCookie, + }, + body: messageJson, + ); + }) + .then((resp) { + if (resp.statusCode != 200) { + throw Exception('Unable to send message'); + } + }) + .catchError((exception) { + message.failedToSend = true; + db.update( + 'messages', + message.toMap(), + where: 'id = ?', + whereArgs: [message.id], + ); + }); } diff --git a/mobile/lib/views/authentication/login.dart b/mobile/lib/views/authentication/login.dart index 9802423..7c60879 100644 --- a/mobile/lib/views/authentication/login.dart +++ b/mobile/lib/views/authentication/login.dart @@ -67,7 +67,7 @@ Future login(context, String username, String password) async { setPrivateKey(rsaPriv); final preferences = await SharedPreferences.getInstance(); - preferences.setBool('islogin', true); + preferences.setString('logged_in_at', (DateTime.now()).toIso8601String()); preferences.setString('userId', response.userId); preferences.setString('username', response.username); preferences.setString('asymmetricPublicKey', response.asymmetricPublicKey); diff --git a/mobile/lib/views/main/conversation_detail.dart b/mobile/lib/views/main/conversation_detail.dart index c3f0bb4..f00e84e 100644 --- a/mobile/lib/views/main/conversation_detail.dart +++ b/mobile/lib/views/main/conversation_detail.dart @@ -54,6 +54,32 @@ class _ConversationDetailState extends State { setState(() {}); } + Widget usernameOrFailedToSend(int index) { + if (messages[index].senderUsername != username) { + return Text(messages[index].senderUsername); + } + + if (messages[index].failedToSend) { + return Row( + mainAxisAlignment: MainAxisAlignment.end, + children: const [ + Icon( + Icons.warning_rounded, + color: Colors.red, + size: 20, + ), + Text( + 'Failed to send', + style: TextStyle(color: Colors.red, fontSize: 12), + textAlign: TextAlign.right, + ), + ], + ); + } + + return const SizedBox.shrink(); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -102,7 +128,7 @@ class _ConversationDetailState extends State { reverse: true, itemBuilder: (context, index) { return Container( - padding: const EdgeInsets.only(left: 14,right: 14,top: 0,bottom: 0), + padding: const EdgeInsets.only(left: 14,right: 14,top: 0,bottom: 10), child: Align( alignment: ( messages[index].senderUsername == username ? @@ -126,9 +152,7 @@ class _ConversationDetailState extends State { padding: const EdgeInsets.all(12), child: Text(messages[index].data, style: const TextStyle(fontSize: 15)), ), - messages[index].senderUsername != username ? - Text(messages[index].senderUsername) : - const SizedBox.shrink(), + usernameOrFailedToSend(index), Text( convertToAgo(messages[index].createdAt), textAlign: TextAlign.left, diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index 06c6295..f7a0d6d 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -1,11 +1,14 @@ import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:http/http.dart' as http; +import 'package:flutter_dotenv/flutter_dotenv.dart'; import '/views/main/conversation_list.dart'; import '/views/main/friend_list.dart'; import '/views/main/profile.dart'; import '/utils/storage/friends.dart'; import '/utils/storage/conversations.dart'; import '/utils/storage/messages.dart'; +import '/utils/storage/session_cookie.dart'; import '/models/conversations.dart'; import '/models/friends.dart'; @@ -53,12 +56,46 @@ class _HomeState extends State { }); } - // TODO: Do server GET check here - Future checkLogin() async { + Future checkLogin() async { SharedPreferences preferences = await SharedPreferences.getInstance(); - if (preferences.getBool('islogin') != true) { + + var loggedInTime = preferences.getString('logged_in_at'); + if (loggedInTime == null) { + preferences.remove('logged_in_at'); + preferences.remove('username'); + preferences.remove('userId'); + preferences.remove('asymmetricPublicKey'); Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); + return; + } + + DateTime loggedInAt = DateTime.parse(loggedInTime); + bool isAfter = loggedInAt.isAfter((DateTime.now()).add(const Duration(hours: 12))); + int statusCode = 200; + + try { + var resp = await http.get( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/check'), + headers: { + 'cookie': await getSessionCookie(), + } + ); + statusCode = resp.statusCode; + } catch(SocketException) { + if (!isAfter) { + return; + } } + + if (!isAfter && statusCode == 200) { + return; + } + + preferences.remove('logged_in_at'); + preferences.remove('username'); + preferences.remove('userId'); + preferences.remove('asymmetricPublicKey'); + Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); } void _onItemTapped(int index) { diff --git a/mobile/lib/views/main/profile.dart b/mobile/lib/views/main/profile.dart index 64d65ff..ccc84d5 100644 --- a/mobile/lib/views/main/profile.dart +++ b/mobile/lib/views/main/profile.dart @@ -37,7 +37,9 @@ class _ProfileState extends State { onTap: () async { deleteDb(); final preferences = await SharedPreferences.getInstance(); - preferences.setBool('islogin', false); + preferences.remove('logged_in_at'); + preferences.remove('username'); + preferences.remove('userId'); preferences.remove(rsaPrivateKeyName); Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); }, -- 2.17.1 From 0dac8e86ae0eef3983713c0c9a77721baab35861 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Wed, 6 Jul 2022 21:03:49 +0930 Subject: [PATCH 11/24] Code clean up and organisation of colors and profile storage --- Backend/Database/Seeder/FriendSeeder.go | 2 +- Backend/Database/Seeder/MessageSeeder.go | 4 +- Backend/Database/Seeder/UserSeeder.go | 2 +- .../lib/components/custom_circle_avatar.dart | 64 ++- mobile/lib/main.dart | 124 ++++-- mobile/lib/models/conversation_users.dart | 13 +- mobile/lib/models/my_profile.dart | 94 ++++ mobile/lib/utils/storage/database.dart | 2 +- mobile/lib/views/authentication/login.dart | 87 ++-- mobile/lib/views/authentication/signup.dart | 402 +++++++++--------- .../unauthenticated_landing.dart | 33 +- .../lib/views/main/conversation_detail.dart | 140 ++++-- mobile/lib/views/main/conversation_list.dart | 36 +- .../lib/views/main/conversation_settings.dart | 124 ++++++ .../conversation_settings_user_list_item.dart | 105 +++++ mobile/lib/views/main/friend_list.dart | 37 +- mobile/lib/views/main/friend_list_item.dart | 72 ++-- mobile/lib/views/main/home.dart | 53 +-- mobile/lib/views/main/profile.dart | 125 +++--- 19 files changed, 1016 insertions(+), 503 deletions(-) create mode 100644 mobile/lib/models/my_profile.dart create mode 100644 mobile/lib/views/main/conversation_settings.dart create mode 100644 mobile/lib/views/main/conversation_settings_user_list_item.dart diff --git a/Backend/Database/Seeder/FriendSeeder.go b/Backend/Database/Seeder/FriendSeeder.go index 033b7a6..5d79da2 100644 --- a/Backend/Database/Seeder/FriendSeeder.go +++ b/Backend/Database/Seeder/FriendSeeder.go @@ -60,7 +60,7 @@ func SeedFriends() { panic(err) } - secondaryUser, err = Database.GetUserByUsername("testUser2") + secondaryUser, err = Database.GetUserByUsername("ATestUser2") if err != nil { panic(err) } diff --git a/Backend/Database/Seeder/MessageSeeder.go b/Backend/Database/Seeder/MessageSeeder.go index 2139eb1..a725c5f 100644 --- a/Backend/Database/Seeder/MessageSeeder.go +++ b/Backend/Database/Seeder/MessageSeeder.go @@ -222,7 +222,7 @@ func SeedMessages() { key, ) - secondaryUser, err = Database.GetUserByUsername("testUser2") + secondaryUser, err = Database.GetUserByUsername("ATestUser2") if err != nil { panic(err) } @@ -263,7 +263,7 @@ func SeedMessages() { { "id": "%s", "username": "%s", - "admin": "true", + "admin": "false", "association_key": "%s" } ] diff --git a/Backend/Database/Seeder/UserSeeder.go b/Backend/Database/Seeder/UserSeeder.go index 69cd543..3c99c9c 100644 --- a/Backend/Database/Seeder/UserSeeder.go +++ b/Backend/Database/Seeder/UserSeeder.go @@ -88,7 +88,7 @@ func SeedUsers() { if err != nil { panic(err) } - _, err = createUser("testUser2") + _, err = createUser("ATestUser2") if err != nil { panic(err) } diff --git a/mobile/lib/components/custom_circle_avatar.dart b/mobile/lib/components/custom_circle_avatar.dart index 8492623..bf7d1b8 100644 --- a/mobile/lib/components/custom_circle_avatar.dart +++ b/mobile/lib/components/custom_circle_avatar.dart @@ -1,13 +1,23 @@ import 'package:flutter/material.dart'; +enum AvatarTypes { + initials, + icon, + image, +} + class CustomCircleAvatar extends StatefulWidget { - final String initials; + final String? initials; + final Icon? icon; final String? imagePath; + final double radius; const CustomCircleAvatar({ Key? key, - required this.initials, + this.initials, + this.icon, this.imagePath, + this.radius = 20, }) : super(key: key); @override @@ -15,25 +25,55 @@ class CustomCircleAvatar extends StatefulWidget { } class _CustomCircleAvatarState extends State{ - - bool _checkLoading = true; + AvatarTypes type = AvatarTypes.image; @override void initState() { super.initState(); + if (widget.imagePath != null) { - _checkLoading = false; + type = AvatarTypes.image; + return; } + + if (widget.icon != null) { + type = AvatarTypes.icon; + return; + } + + if (widget.initials != null) { + type = AvatarTypes.initials; + return; + } + + throw ArgumentError('Invalid arguments passed to CustomCircleAvatar'); + } + + Widget avatar() { + if (type == AvatarTypes.initials) { + return CircleAvatar( + backgroundColor: Colors.grey[300], + child: Text(widget.initials!), + radius: widget.radius, + ); + } + + if (type == AvatarTypes.icon) { + return CircleAvatar( + backgroundColor: Colors.grey[300], + child: widget.icon, + radius: widget.radius, + ); + } + + return CircleAvatar( + backgroundImage: AssetImage(widget.imagePath!), + radius: widget.radius, + ); } @override Widget build(BuildContext context) { - return _checkLoading == true ? - CircleAvatar( - backgroundColor: Colors.grey[300], - child: Text(widget.initials) - ) : CircleAvatar( - backgroundImage: AssetImage(widget.imagePath!) - ); + return avatar(); } } diff --git a/mobile/lib/main.dart b/mobile/lib/main.dart index 0bd22e7..7890c86 100644 --- a/mobile/lib/main.dart +++ b/mobile/lib/main.dart @@ -6,49 +6,97 @@ import '/views/authentication/login.dart'; import '/views/authentication/signup.dart'; void main() async { - await dotenv.load(fileName: ".env"); - runApp(const MyApp()); + await dotenv.load(fileName: ".env"); + runApp(const MyApp()); } class MyApp extends StatelessWidget { - const MyApp({Key? key}) : super(key: key); + const MyApp({Key? key}) : super(key: key); - static const String _title = 'Envelope'; + static const String _title = 'Envelope'; - @override - Widget build(BuildContext context) { - return MaterialApp( - title: _title, - routes: { - '/home': (context) => const Home(), - '/landing': (context) => const UnauthenticatedLandingWidget(), - '/login': (context) => const Login(), - '/signup': (context) => const Signup(), - }, - home: const Scaffold( - backgroundColor: Colors.cyan, - body: SafeArea( - child: Home(), - ) + @override + Widget build(BuildContext context) { + return MaterialApp( + title: _title, + routes: { + '/home': (context) => const Home(), + '/landing': (context) => const UnauthenticatedLandingWidget(), + '/login': (context) => const Login(), + '/signup': (context) => const Signup(), + }, + home: const Scaffold( + body: SafeArea( + child: Home(), + ) + ), + theme: ThemeData( + brightness: Brightness.light, + primaryColor: Colors.red, + appBarTheme: const AppBarTheme( + backgroundColor: Colors.cyan, + elevation: 0, + ), + inputDecorationTheme: const InputDecorationTheme( + labelStyle: TextStyle( + color: Colors.white, + fontSize: 30, ), - theme: ThemeData( - appBarTheme: const AppBarTheme( - backgroundColor: Colors.cyan, - elevation: 0, - ), - inputDecorationTheme: const InputDecorationTheme( - border: OutlineInputBorder(), - focusedBorder: OutlineInputBorder(), - labelStyle: TextStyle( - color: Colors.white, - fontSize: 30, - ), - filled: true, - fillColor: Colors.white, - ), + filled: false, + ), + ), + darkTheme: ThemeData( + brightness: Brightness.dark, + primaryColor: Colors.orange.shade900, + backgroundColor: Colors.grey.shade900, + colorScheme: ColorScheme( + brightness: Brightness.dark, + primary: Colors.orange.shade900, + onPrimary: Colors.white, + secondary: Colors.blue.shade400, + onSecondary: Colors.white, + tertiary: Colors.grey.shade600, + onTertiary: Colors.black, + error: Colors.red, + onError: Colors.yellow, + background: Colors.grey.shade900, + onBackground: Colors.white, + surface: Colors.grey.shade700, + onSurface: Colors.white, + ), + hintColor: Colors.grey.shade500, + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: Colors.grey.shade800, + hintStyle: TextStyle( + color: Colors.grey.shade500, + ), + iconColor: Colors.grey.shade500, + contentPadding: const EdgeInsets.all(8), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(15), + borderSide: const BorderSide( + color: Colors.transparent, + ) + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(15), + borderSide: const BorderSide( + color: Colors.transparent, + ) + ), - ), - - ); - } + ), + appBarTheme: AppBarTheme( + color: Colors.grey.shade800, + iconTheme: IconThemeData( + color: Colors.grey.shade400 + ), + toolbarTextStyle: TextStyle( + color: Colors.grey.shade400 + ), + ), + ), + ); + } } diff --git a/mobile/lib/models/conversation_users.dart b/mobile/lib/models/conversation_users.dart index 6c94a0d..e0e000d 100644 --- a/mobile/lib/models/conversation_users.dart +++ b/mobile/lib/models/conversation_users.dart @@ -6,7 +6,7 @@ class ConversationUser{ String conversationId; String username; String associationKey; - String admin; + bool admin; ConversationUser({ required this.id, required this.conversationId, @@ -21,7 +21,7 @@ class ConversationUser{ conversationId: conversationId, username: json['username'], associationKey: json['association_key'], - admin: json['admin'], + admin: json['admin'] == 'true', ); } @@ -31,7 +31,7 @@ class ConversationUser{ 'conversation_id': conversationId, 'username': username, 'association_key': associationKey, - 'admin': admin, + 'admin': admin ? 1 : 0, }; } } @@ -44,6 +44,7 @@ Future> getConversationUsers(Conversation conversation) a 'conversation_users', where: 'conversation_id = ?', whereArgs: [conversation.id], + orderBy: 'admin', ); return List.generate(maps.length, (i) { @@ -52,7 +53,7 @@ Future> getConversationUsers(Conversation conversation) a conversationId: maps[i]['conversation_id'], username: maps[i]['username'], associationKey: maps[i]['association_key'], - admin: maps[i]['admin'], + admin: maps[i]['admin'] == 1, ); }); } @@ -75,7 +76,7 @@ Future getConversationUserById(Conversation conversation, Stri conversationId: maps[0]['conversation_id'], username: maps[0]['username'], associationKey: maps[0]['association_key'], - admin: maps[0]['admin'], + admin: maps[0]['admin'] == 1, ); } @@ -98,7 +99,7 @@ Future getConversationUserByUsername(Conversation conversation conversationId: maps[0]['conversation_id'], username: maps[0]['username'], associationKey: maps[0]['association_key'], - admin: maps[0]['admin'], + admin: maps[0]['admin'] == 1, ); } diff --git a/mobile/lib/models/my_profile.dart b/mobile/lib/models/my_profile.dart new file mode 100644 index 0000000..c584018 --- /dev/null +++ b/mobile/lib/models/my_profile.dart @@ -0,0 +1,94 @@ +import 'dart:convert'; +import 'package:Envelope/utils/encryption/aes_helper.dart'; +import 'package:Envelope/utils/encryption/crypto_utils.dart'; +import 'package:pointycastle/impl.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class MyProfile { + String id; + String username; + RSAPrivateKey privateKey; + RSAPublicKey publicKey; + DateTime loggedInAt; + + MyProfile({ + required this.id, + required this.username, + required this.privateKey, + required this.publicKey, + required this.loggedInAt, + }); + + factory MyProfile._fromJson(Map json) { + DateTime loggedInAt = DateTime.now(); + if (json.containsKey('logged_in_at')) { + loggedInAt = DateTime.parse(json['logged_in_at']); + } + + return MyProfile( + id: json['user_id'], + username: json['username'], + privateKey: CryptoUtils.rsaPrivateKeyFromPem(json['asymmetric_private_key']), + publicKey: CryptoUtils.rsaPublicKeyFromPem(json['asymmetric_public_key']), + loggedInAt: loggedInAt, + ); + } + + @override + String toString() { + return ''' + user_id: $id + username: $username + logged_in_at: $loggedInAt + public_key: $publicKey + private_key: $privateKey + '''; + } + + String toJson() { + return jsonEncode({ + 'user_id': id, + 'username': username, + 'asymmetric_private_key': CryptoUtils.encodeRSAPrivateKeyToPem(privateKey), + 'asymmetric_public_key': CryptoUtils.encodeRSAPublicKeyToPem(publicKey), + 'logged_in_at': loggedInAt.toIso8601String(), + }); + } + + static Future login(Map json, String password) async { + json['asymmetric_private_key'] = AesHelper.aesDecrypt( + password, + base64.decode(json['asymmetric_private_key']) + ); + MyProfile profile = MyProfile._fromJson(json); + final preferences = await SharedPreferences.getInstance(); + print(profile.toJson()); + preferences.setString('profile', profile.toJson()); + return profile; + } + + static Future logout() async { + final preferences = await SharedPreferences.getInstance(); + preferences.remove('profile'); + } + + static Future getProfile() async { + final preferences = await SharedPreferences.getInstance(); + String? profileJson = preferences.getString('profile'); + if (profileJson == null) { + throw Exception('No profile'); + } + return MyProfile._fromJson(json.decode(profileJson)); + } + + static Future isLoggedIn() async { + MyProfile profile = await MyProfile.getProfile(); + return profile.loggedInAt.isBefore((DateTime.now()).add(const Duration(hours: 12))); + } + + Future getPrivateKey() async { + MyProfile profile = await MyProfile.getProfile(); + return profile.privateKey; + } +} + diff --git a/mobile/lib/utils/storage/database.dart b/mobile/lib/utils/storage/database.dart index 86e2a31..162a5c5 100644 --- a/mobile/lib/utils/storage/database.dart +++ b/mobile/lib/utils/storage/database.dart @@ -51,7 +51,7 @@ Future getDatabaseConnection() async { username TEXT, data TEXT, association_key TEXT, - admin TEXT + admin INTEGER ); '''); diff --git a/mobile/lib/views/authentication/login.dart b/mobile/lib/views/authentication/login.dart index 7c60879..c1c7fb7 100644 --- a/mobile/lib/views/authentication/login.dart +++ b/mobile/lib/views/authentication/login.dart @@ -1,11 +1,8 @@ import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import '/utils/encryption/crypto_utils.dart'; -import '/utils/encryption/aes_helper.dart'; -import '/utils/storage/encryption_keys.dart'; +import '/models/my_profile.dart'; import '/utils/storage/session_cookie.dart'; class LoginResponse { @@ -37,7 +34,7 @@ class LoginResponse { } } -Future login(context, String username, String password) async { +Future login(context, String username, String password) async { final resp = await http.post( Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/login'), headers: { @@ -59,20 +56,7 @@ Future login(context, String username, String password) async { setSessionCookie((index == -1) ? rawCookie : rawCookie.substring(0, index)); } - LoginResponse response = LoginResponse.fromJson(jsonDecode(resp.body)); - - var rsaPrivPem = AesHelper.aesDecrypt(password, base64.decode(response.asymmetricPrivateKey)); - - var rsaPriv = CryptoUtils.rsaPrivateKeyFromPem(rsaPrivPem); - setPrivateKey(rsaPriv); - - final preferences = await SharedPreferences.getInstance(); - preferences.setString('logged_in_at', (DateTime.now()).toIso8601String()); - preferences.setString('userId', response.userId); - preferences.setString('username', response.username); - preferences.setString('asymmetricPublicKey', response.asymmetricPublicKey); - - return response; + return await MyProfile.login(json.decode(resp.body), password); } class Login extends StatelessWidget { @@ -81,17 +65,16 @@ class Login extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: Colors.cyan, appBar: AppBar( title: null, automaticallyImplyLeading: true, - //`true` if you want Flutter to automatically add Back Button when needed, - //or `false` if you want to force your own back button every where leading: IconButton(icon: const Icon(Icons.arrow_back), onPressed:() => { Navigator.pop(context) } - ) + ), + backgroundColor: Colors.transparent, + shadowColor: Colors.transparent, ), body: const SafeArea( child: LoginWidget(), @@ -115,17 +98,26 @@ class _LoginWidgetState extends State { @override Widget build(BuildContext context) { - const TextStyle _inputTextStyle = TextStyle(fontSize: 18, color: Colors.black); + const TextStyle inputTextStyle = TextStyle( + fontSize: 18, + ); - final ButtonStyle _buttonStyle = ElevatedButton.styleFrom( - primary: Colors.white, - onPrimary: Colors.cyan, + final OutlineInputBorder inputBorderStyle = OutlineInputBorder( + borderRadius: BorderRadius.circular(5), + borderSide: const BorderSide( + color: Colors.transparent, + ) + ); + + final ButtonStyle buttonStyle = ElevatedButton.styleFrom( + primary: Theme.of(context).colorScheme.surface, + onPrimary: Theme.of(context).colorScheme.onSurface, minimumSize: const Size.fromHeight(50), padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), - textStyle: const TextStyle( + textStyle: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, - color: Colors.red, + color: Theme.of(context).colorScheme.error, ), ); @@ -134,37 +126,52 @@ class _LoginWidgetState extends State { key: _formKey, child: Center( child: Padding( - padding: const EdgeInsets.all(15), + padding: const EdgeInsets.only( + left: 20, + right: 20, + top: 0, + bottom: 80, + ), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ - const Text('Login', style: TextStyle(fontSize: 35, color: Colors.white),), + Text( + 'Login', + style: TextStyle( + fontSize: 35, + color: Theme.of(context).colorScheme.onBackground, + ), + ), const SizedBox(height: 30), TextFormField( controller: usernameController, - decoration: const InputDecoration( + decoration: InputDecoration( hintText: 'Username', + enabledBorder: inputBorderStyle, + focusedBorder: inputBorderStyle, ), - style: _inputTextStyle, + style: inputTextStyle, // The validator receives the text that the user has entered. validator: (value) { if (value == null || value.isEmpty) { - return 'Create a username'; + return 'Enter a username'; } return null; }, ), - const SizedBox(height: 5), + const SizedBox(height: 10), TextFormField( controller: passwordController, obscureText: true, enableSuggestions: false, autocorrect: false, - decoration: const InputDecoration( + decoration: InputDecoration( hintText: 'Password', + enabledBorder: inputBorderStyle, + focusedBorder: inputBorderStyle, ), - style: _inputTextStyle, + style: inputTextStyle, // The validator receives the text that the user has entered. validator: (value) { if (value == null || value.isEmpty) { @@ -173,9 +180,9 @@ class _LoginWidgetState extends State { return null; }, ), - const SizedBox(height: 5), + const SizedBox(height: 15), ElevatedButton( - style: _buttonStyle, + style: buttonStyle, onPressed: () { if (_formKey.currentState!.validate()) { ScaffoldMessenger.of(context).showSnackBar( @@ -186,7 +193,7 @@ class _LoginWidgetState extends State { context, usernameController.text, passwordController.text, - ).then((value) { + ).then((val) { Navigator. pushNamedAndRemoveUntil( context, diff --git a/mobile/lib/views/authentication/signup.dart b/mobile/lib/views/authentication/signup.dart index 74425c3..0847bf7 100644 --- a/mobile/lib/views/authentication/signup.dart +++ b/mobile/lib/views/authentication/signup.dart @@ -2,211 +2,233 @@ import 'dart:typed_data'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; -import 'package:shared_preferences/shared_preferences.dart'; - import '/utils/encryption/aes_helper.dart'; -import '/utils/storage/encryption_keys.dart'; import '/utils/encryption/crypto_utils.dart'; class SignupResponse { - final String status; - final String message; - - const SignupResponse({ - required this.status, - required this.message, - }); - - factory SignupResponse.fromJson(Map json) { - return SignupResponse( - status: json['status'], - message: json['message'], - ); - } + final String status; + final String message; + + const SignupResponse({ + required this.status, + required this.message, + }); + + factory SignupResponse.fromJson(Map json) { + return SignupResponse( + status: json['status'], + message: json['message'], + ); + } } Future signUp(context, String username, String password, String confirmPassword) async { - var keyPair = CryptoUtils.generateRSAKeyPair(); - - var rsaPubPem = CryptoUtils.encodeRSAPublicKeyToPem(keyPair.publicKey); - var rsaPrivPem = CryptoUtils.encodeRSAPrivateKeyToPem(keyPair.privateKey); - - var encRsaPriv = AesHelper.aesEncrypt(password, Uint8List.fromList(rsaPrivPem.codeUnits)); - - // TODO: Check for timeout here - final resp = await http.post( - Uri.parse('http://192.168.1.5:8080/api/v1/signup'), - headers: { - 'Content-Type': 'application/json; charset=UTF-8', - }, - body: jsonEncode({ - 'username': username, - 'password': password, - 'confirm_password': confirmPassword, - 'asymmetric_public_key': rsaPubPem, - 'asymmetric_private_key': encRsaPriv, - }), - ); - - SignupResponse response = SignupResponse.fromJson(jsonDecode(resp.body)); - - if (resp.statusCode != 201) { - throw Exception(response.message); - } - - return response; + var keyPair = CryptoUtils.generateRSAKeyPair(); + + var rsaPubPem = CryptoUtils.encodeRSAPublicKeyToPem(keyPair.publicKey); + var rsaPrivPem = CryptoUtils.encodeRSAPrivateKeyToPem(keyPair.privateKey); + + var encRsaPriv = AesHelper.aesEncrypt(password, Uint8List.fromList(rsaPrivPem.codeUnits)); + + // TODO: Check for timeout here + final resp = await http.post( + Uri.parse('http://192.168.1.5:8080/api/v1/signup'), + headers: { + 'Content-Type': 'application/json; charset=UTF-8', + }, + body: jsonEncode({ + 'username': username, + 'password': password, + 'confirm_password': confirmPassword, + 'asymmetric_public_key': rsaPubPem, + 'asymmetric_private_key': encRsaPriv, + }), + ); + + SignupResponse response = SignupResponse.fromJson(jsonDecode(resp.body)); + + if (resp.statusCode != 201) { + throw Exception(response.message); + } + + return response; } class Signup extends StatelessWidget { - const Signup({Key? key}) : super(key: key); - - @override - Widget build(BuildContext context) { - return Scaffold( - backgroundColor: Colors.cyan, - appBar: AppBar( - title: null, - automaticallyImplyLeading: true, - //`true` if you want Flutter to automatically add Back Button when needed, - //or `false` if you want to force your own back button every where - leading: IconButton(icon: const Icon(Icons.arrow_back), - //onPressed:() => Navigator.pop(context, false), - onPressed:() => { - Navigator.pop(context) - } - ) - ), - body: const SafeArea( - child: SignupWidget(), - ) - ); - } + const Signup({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: null, + automaticallyImplyLeading: true, + //`true` if you want Flutter to automatically add Back Button when needed, + //or `false` if you want to force your own back button every where + leading: IconButton(icon: const Icon(Icons.arrow_back), + onPressed:() => { + Navigator.pop(context) + } + ), + backgroundColor: Colors.transparent, + shadowColor: Colors.transparent, + ), + body: const SafeArea( + child: SignupWidget(), + ) + ); + } } class SignupWidget extends StatefulWidget { - const SignupWidget({Key? key}) : super(key: key); + const SignupWidget({Key? key}) : super(key: key); - @override - State createState() => _SignupWidgetState(); + @override + State createState() => _SignupWidgetState(); } class _SignupWidgetState extends State { - final _formKey = GlobalKey(); - - TextEditingController usernameController = TextEditingController(); - TextEditingController passwordController = TextEditingController(); - TextEditingController passwordConfirmController = TextEditingController(); - - @override - Widget build(BuildContext context) { - const TextStyle _inputTextStyle = TextStyle(fontSize: 18, color: Colors.black); - - final ButtonStyle _buttonStyle = ElevatedButton.styleFrom( - primary: Colors.white, - onPrimary: Colors.cyan, - minimumSize: const Size.fromHeight(50), - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), - textStyle: const TextStyle( - fontSize: 20, - fontWeight: FontWeight.bold, - color: Colors.red, - ), - ); - - return Center( - child: Form( - key: _formKey, - child: Center( - child: Padding( - padding: const EdgeInsets.all(15), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - const Text('Sign Up', style: TextStyle(fontSize: 35, color: Colors.white),), - const SizedBox(height: 30), - TextFormField( - controller: usernameController, - decoration: const InputDecoration( - hintText: 'Username', - ), - style: _inputTextStyle, - // The validator receives the text that the user has entered. - validator: (value) { - if (value == null || value.isEmpty) { - return 'Create a username'; - } - return null; - }, - ), - const SizedBox(height: 5), - TextFormField( - controller: passwordController, - obscureText: true, - enableSuggestions: false, - autocorrect: false, - decoration: const InputDecoration( - hintText: 'Password', - ), - style: _inputTextStyle, - // The validator receives the text that the user has entered. - validator: (value) { - if (value == null || value.isEmpty) { - return 'Enter a password'; - } - return null; - }, - ), - const SizedBox(height: 5), - TextFormField( - controller: passwordConfirmController, - obscureText: true, - enableSuggestions: false, - autocorrect: false, - decoration: const InputDecoration( - hintText: 'Password', - ), - style: _inputTextStyle, - // The validator receives the text that the user has entered. - validator: (value) { - if (value == null || value.isEmpty) { - return 'Confirm your password'; - } - if (value != passwordController.text) { - return 'Passwords do not match'; - } - return null; - }, - ), - const SizedBox(height: 5), - ElevatedButton( - style: _buttonStyle, - onPressed: () { - if (_formKey.currentState!.validate()) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Processing Data')), - ); - - signUp( - context, - usernameController.text, - passwordController.text, - passwordConfirmController.text - ).then((value) { - Navigator.of(context).popUntil((route) => route.isFirst); - }).catchError((error) { - print(error); // TODO: Show error on interface - }); - } - }, - child: const Text('Submit'), - ), - ], - ) - ) - ) - - ) - ); - } + final _formKey = GlobalKey(); + + TextEditingController usernameController = TextEditingController(); + TextEditingController passwordController = TextEditingController(); + TextEditingController passwordConfirmController = TextEditingController(); + + @override + Widget build(BuildContext context) { + const TextStyle inputTextStyle = TextStyle( + fontSize: 18, + ); + + final OutlineInputBorder inputBorderStyle = OutlineInputBorder( + borderRadius: BorderRadius.circular(5), + borderSide: const BorderSide( + color: Colors.transparent, + ) + ); + + final ButtonStyle buttonStyle = ElevatedButton.styleFrom( + primary: Theme.of(context).colorScheme.surface, + onPrimary: Theme.of(context).colorScheme.onSurface, + minimumSize: const Size.fromHeight(50), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + textStyle: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.error, + ), + ); + + return Center( + child: Form( + key: _formKey, + child: Center( + child: Padding( + padding: const EdgeInsets.only( + left: 20, + right: 20, + top: 0, + bottom: 100, + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + 'Sign Up', + style: TextStyle( + fontSize: 35, + color: Theme.of(context).colorScheme.onBackground, + ), + ), + const SizedBox(height: 30), + TextFormField( + controller: usernameController, + decoration: InputDecoration( + hintText: 'Username', + enabledBorder: inputBorderStyle, + focusedBorder: inputBorderStyle, + ), + style: inputTextStyle, + // The validator receives the text that the user has entered. + validator: (value) { + if (value == null || value.isEmpty) { + return 'Create a username'; + } + return null; + }, + ), + const SizedBox(height: 10), + TextFormField( + controller: passwordController, + obscureText: true, + enableSuggestions: false, + autocorrect: false, + decoration: InputDecoration( + hintText: 'Password', + enabledBorder: inputBorderStyle, + focusedBorder: inputBorderStyle, + ), + style: inputTextStyle, + // The validator receives the text that the user has entered. + validator: (value) { + if (value == null || value.isEmpty) { + return 'Enter a password'; + } + return null; + }, + ), + const SizedBox(height: 10), + TextFormField( + controller: passwordConfirmController, + obscureText: true, + enableSuggestions: false, + autocorrect: false, + decoration: InputDecoration( + hintText: 'Password', + enabledBorder: inputBorderStyle, + focusedBorder: inputBorderStyle, + ), + style: inputTextStyle, + // The validator receives the text that the user has entered. + validator: (value) { + if (value == null || value.isEmpty) { + return 'Confirm your password'; + } + if (value != passwordController.text) { + return 'Passwords do not match'; + } + return null; + }, + ), + const SizedBox(height: 15), + ElevatedButton( + style: buttonStyle, + onPressed: () { + if (_formKey.currentState!.validate()) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Processing Data')), + ); + + signUp( + context, + usernameController.text, + passwordController.text, + passwordConfirmController.text + ).then((value) { + Navigator.of(context).popUntil((route) => route.isFirst); + }).catchError((error) { + print(error); // TODO: Show error on interface + }); + } + }, + child: const Text('Submit'), + ), + ], + ) + ) + ) + ) + ); + } } diff --git a/mobile/lib/views/authentication/unauthenticated_landing.dart b/mobile/lib/views/authentication/unauthenticated_landing.dart index 1bb6c31..adbdd19 100644 --- a/mobile/lib/views/authentication/unauthenticated_landing.dart +++ b/mobile/lib/views/authentication/unauthenticated_landing.dart @@ -15,21 +15,19 @@ class _UnauthenticatedLandingWidgetState extends State false, child: Scaffold( - backgroundColor: Colors.cyan, body: SafeArea( child: Center( child: Column( @@ -40,16 +38,31 @@ class _UnauthenticatedLandingWidgetState extends State { Widget usernameOrFailedToSend(int index) { if (messages[index].senderUsername != username) { - return Text(messages[index].senderUsername); + return Text( + messages[index].senderUsername, + style: TextStyle( + fontSize: 12, + color: Colors.grey[300], + ), + ); } if (messages[index].failedToSend) { @@ -86,7 +93,6 @@ class _ConversationDetailState extends State { appBar: AppBar( elevation: 0, automaticallyImplyLeading: false, - backgroundColor: Colors.white, flexibleSpace: SafeArea( child: Container( padding: const EdgeInsets.only(right: 16), @@ -96,7 +102,10 @@ class _ConversationDetailState extends State { onPressed: (){ Navigator.pop(context); }, - icon: const Icon(Icons.arrow_back,color: Colors.black,), + icon: Icon( + Icons.arrow_back, + color: Theme.of(context).appBarTheme.iconTheme?.color, + ), ), const SizedBox(width: 2,), Expanded( @@ -106,14 +115,26 @@ class _ConversationDetailState extends State { children: [ Text( widget.conversation.name, - style: const TextStyle( + style: TextStyle( fontSize: 16, - fontWeight: FontWeight.w600), + fontWeight: FontWeight.w600, + color: Theme.of(context).appBarTheme.toolbarTextStyle?.color + ), ), ], ), ), - const Icon(Icons.settings,color: Colors.black54), + IconButton( + onPressed: (){ + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ConversationSettings(conversation: widget.conversation)), + ); + }, + icon: Icon( + Icons.settings, + color: Theme.of(context).appBarTheme.iconTheme?.color, + ), + ), ], ), ), @@ -128,7 +149,7 @@ class _ConversationDetailState extends State { reverse: true, itemBuilder: (context, index) { return Container( - padding: const EdgeInsets.only(left: 14,right: 14,top: 0,bottom: 10), + padding: const EdgeInsets.only(left: 14,right: 14,top: 0,bottom: 0), child: Align( alignment: ( messages[index].senderUsername == username ? @@ -145,23 +166,54 @@ class _ConversationDetailState extends State { borderRadius: BorderRadius.circular(20), color: ( messages[index].senderUsername == username ? - Colors.blue[200] : - Colors.grey.shade200 + Theme.of(context).colorScheme.primary : + Theme.of(context).colorScheme.tertiary ), ), padding: const EdgeInsets.all(12), - child: Text(messages[index].data, style: const TextStyle(fontSize: 15)), + child: Text( + messages[index].data, + style: TextStyle( + fontSize: 15, + color: messages[index].senderUsername == username ? + Theme.of(context).colorScheme.onPrimary : + Theme.of(context).colorScheme.onTertiary, + ) + ), ), - usernameOrFailedToSend(index), - Text( - convertToAgo(messages[index].createdAt), - textAlign: TextAlign.left, - style: TextStyle( - fontSize: 12, - color: Colors.grey[500], + const SizedBox(height: 1.5), + Row( + mainAxisAlignment: messages[index].senderUsername == username ? + MainAxisAlignment.end : + MainAxisAlignment.start, + children: [ + const SizedBox(width: 10), + usernameOrFailedToSend(index), + ], + ), + const SizedBox(height: 1.5), + Row( + mainAxisAlignment: messages[index].senderUsername == username ? + MainAxisAlignment.end : + MainAxisAlignment.start, + children: [ + const SizedBox(width: 10), + Text( + convertToAgo(messages[index].createdAt), + textAlign: messages[index].senderUsername == username ? + TextAlign.left : + TextAlign.right, + style: TextStyle( + fontSize: 12, + color: Colors.grey[500], + ), + ), + ], ), - ), - ] + index != 0 ? + const SizedBox(height: 20) : + const SizedBox.shrink(), + ], ) ), ); @@ -177,7 +229,7 @@ class _ConversationDetailState extends State { padding: const EdgeInsets.only(left: 10,bottom: 10,top: 10), // height: 60, width: double.infinity, - color: Colors.white, + color: Theme.of(context).backgroundColor, child: Row( children: [ GestureDetector( @@ -187,18 +239,24 @@ class _ConversationDetailState extends State { height: 30, width: 30, decoration: BoxDecoration( - color: Colors.lightBlue, + color: Theme.of(context).primaryColor, borderRadius: BorderRadius.circular(30), ), - child: const Icon(Icons.add, color: Colors.white, size: 20, ), + child: Icon( + Icons.add, + color: Theme.of(context).colorScheme.onPrimary, + size: 20 + ), ), ), const SizedBox(width: 15,), Expanded( child: TextField( - decoration: const InputDecoration( + decoration: InputDecoration( hintText: "Write message...", - hintStyle: TextStyle(color: Colors.black54), + hintStyle: TextStyle( + color: Theme.of(context).hintColor, + ), border: InputBorder.none, ), maxLines: null, @@ -206,18 +264,28 @@ class _ConversationDetailState extends State { ), ), const SizedBox(width: 15), - FloatingActionButton( - onPressed: () async { - if (msgController.text == '') { - return; - } - await sendMessage(widget.conversation, msgController.text); - messages = await getMessagesForThread(widget.conversation); - setState(() {}); - msgController.text = ''; - }, - child: const Icon(Icons.send,color: Colors.white,size: 18,), - backgroundColor: Colors.blue, + Container( + width: 45, + height: 45, + child: FittedBox( + child: FloatingActionButton( + onPressed: () async { + if (msgController.text == '') { + return; + } + await sendMessage(widget.conversation, msgController.text); + messages = await getMessagesForThread(widget.conversation); + setState(() {}); + msgController.text = ''; + }, + child: Icon( + Icons.send, + color: Theme.of(context).colorScheme.onPrimary, + size: 22 + ), + backgroundColor: Theme.of(context).primaryColor, + ), + ), ), const SizedBox(width: 10), ], diff --git a/mobile/lib/views/main/conversation_list.dart b/mobile/lib/views/main/conversation_list.dart index 1636f4f..8ba20f7 100644 --- a/mobile/lib/views/main/conversation_list.dart +++ b/mobile/lib/views/main/conversation_list.dart @@ -80,23 +80,8 @@ class _ConversationListState extends State { padding: const EdgeInsets.only(left: 16,right: 16,top: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Text("Conversations",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), - Container( - padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), - height: 30, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(30), - color: Colors.pink[50], - ), - child: Row( - children: const [ - Icon(Icons.add,color: Colors.pink,size: 20,), - SizedBox(width: 2,), - Text("Add",style: TextStyle(fontSize: 14,fontWeight: FontWeight.bold),), - ], - ), - ) + children: const [ + Text("Conversations",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), ], ), ), @@ -104,20 +89,13 @@ class _ConversationListState extends State { Padding( padding: const EdgeInsets.only(top: 16,left: 16,right: 16), child: TextField( - decoration: InputDecoration( + decoration: const InputDecoration( hintText: "Search...", - hintStyle: TextStyle(color: Colors.grey.shade600), - prefixIcon: Icon(Icons.search,color: Colors.grey.shade600, size: 20,), - filled: true, - fillColor: Colors.grey.shade100, - contentPadding: const EdgeInsets.all(8), - enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(20), - borderSide: BorderSide( - color: Colors.grey.shade100 - ) + prefixIcon: Icon( + Icons.search, + size: 20 ), - ), + ), onChanged: (value) => filterSearchResults(value.toLowerCase()) ), ), diff --git a/mobile/lib/views/main/conversation_settings.dart b/mobile/lib/views/main/conversation_settings.dart new file mode 100644 index 0000000..c4e04c5 --- /dev/null +++ b/mobile/lib/views/main/conversation_settings.dart @@ -0,0 +1,124 @@ +import 'package:Envelope/models/conversation_users.dart'; +import 'package:flutter/material.dart'; +import '/views/main/conversation_settings_user_list_item.dart'; +import '/models/conversations.dart'; +import 'package:Envelope/components/custom_circle_avatar.dart'; + +class ConversationSettings extends StatefulWidget { + final Conversation conversation; + const ConversationSettings({ + Key? key, + required this.conversation, + }) : super(key: key); + + @override + State createState() => _ConversationSettingsState(); +} + +class _ConversationSettingsState extends State { + final _formKey = GlobalKey(); + + List users = []; + + TextEditingController nameController = TextEditingController(); + + @override + void initState() { + nameController.text = widget.conversation.name; + super.initState(); + getUsers(); + } + + Future getUsers() async { + users = await getConversationUsers(widget.conversation); + setState(() {}); + } + + Widget conversationName() { + return Row( + children: [ + const CustomCircleAvatar( + icon: Icon(Icons.people, size: 40), + imagePath: null, // TODO: Add image here + radius: 30, + ), + const SizedBox(width: 10), + Text( + widget.conversation.name, + style: const TextStyle( + fontSize: 25, + fontWeight: FontWeight.w500, + ), + ), + ], + ); + } + + Widget usersList() { + return ListView.builder( + itemCount: users.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 16), + itemBuilder: (context, i) { + return ConversationSettingsUserListItem( + user: users[i], + isAdmin: widget.conversation.admin, + ); + } + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + elevation: 0, + automaticallyImplyLeading: false, + flexibleSpace: SafeArea( + child: Container( + padding: const EdgeInsets.only(right: 16), + child: Row( + children: [ + IconButton( + onPressed: (){ + Navigator.pop(context); + }, + icon: const Icon(Icons.arrow_back), + ), + const SizedBox(width: 2,), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + widget.conversation.name + " Settings", + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600 + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + body: Padding( + padding: const EdgeInsets.all(15), + child: Column( + children: [ + const SizedBox(height: 30), + conversationName(), + const SizedBox(height: 10), + const Text('Users', style: TextStyle(fontSize: 20)), + usersList(), + ], + ), + ), + ); + } +} + diff --git a/mobile/lib/views/main/conversation_settings_user_list_item.dart b/mobile/lib/views/main/conversation_settings_user_list_item.dart new file mode 100644 index 0000000..590fc06 --- /dev/null +++ b/mobile/lib/views/main/conversation_settings_user_list_item.dart @@ -0,0 +1,105 @@ +import 'package:flutter/material.dart'; +import 'package:Envelope/models/conversation_users.dart'; +import 'package:Envelope/components/custom_circle_avatar.dart'; + +class ConversationSettingsUserListItem extends StatefulWidget{ + final ConversationUser user; + final bool isAdmin; + const ConversationSettingsUserListItem({ + Key? key, + required this.user, + required this.isAdmin, + }) : super(key: key); + + @override + _ConversationSettingsUserListItemState createState() => _ConversationSettingsUserListItemState(); +} + +class _ConversationSettingsUserListItemState extends State { + + Widget admin() { + if (widget.user.admin) { + return const SizedBox.shrink(); + } + + return Row( + children: const [ + SizedBox(width: 5), + Icon(Icons.circle, size: 6), + SizedBox(width: 5), + Text( + 'Admin', + style: TextStyle( + fontSize: 14, + ), + ), + ] + ); + } + + Widget adminUserActions() { + if (!widget.isAdmin) { + return const SizedBox.shrink(); + } + + return Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + IconButton(icon: const Icon(Icons.cancel), + padding: const EdgeInsets.all(0), + onPressed:() => { + print('Cancel') + } + ), + IconButton(icon: const Icon(Icons.admin_panel_settings), + padding: const EdgeInsets.all(0), + onPressed:() => { + print('Admin') + } + ) + ], + ); + } + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), + child: Row( + children: [ + Expanded( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + CustomCircleAvatar( + initials: widget.user.username[0].toUpperCase(), + imagePath: null, // TODO: Add image here + radius: 15, + ), + const SizedBox(width: 16), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: Container( + color: Colors.transparent, + child: Row( + children: [ + Text( + widget.user.username, + style: const TextStyle(fontSize: 16) + ), + admin(), + ], + ), + ), + ), + ), + ], + ), + ), + adminUserActions(), + ], + ), + ); + } +} diff --git a/mobile/lib/views/main/friend_list.dart b/mobile/lib/views/main/friend_list.dart index 719c57c..f331659 100644 --- a/mobile/lib/views/main/friend_list.dart +++ b/mobile/lib/views/main/friend_list.dart @@ -88,14 +88,24 @@ class _FriendListState extends State { padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), height: 30, decoration: BoxDecoration( - borderRadius: BorderRadius.circular(30), - color: Colors.pink[50], + borderRadius: BorderRadius.circular(20), + color: Theme.of(context).colorScheme.tertiary ), child: Row( - children: const [ - Icon(Icons.add,color: Colors.pink,size: 20,), - SizedBox(width: 2,), - Text("Add",style: TextStyle(fontSize: 14,fontWeight: FontWeight.bold),), + children: [ + Icon( + Icons.add, + color: Theme.of(context).primaryColor, + size: 20 + ), + const SizedBox(width: 2,), + const Text( + "Add", + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold + ) + ), ], ), ) @@ -106,18 +116,11 @@ class _FriendListState extends State { Padding( padding: const EdgeInsets.only(top: 16,left: 16,right: 16), child: TextField( - decoration: InputDecoration( + decoration: const InputDecoration( hintText: "Search...", - hintStyle: TextStyle(color: Colors.grey.shade600), - prefixIcon: Icon(Icons.search,color: Colors.grey.shade600, size: 20,), - filled: true, - fillColor: Colors.grey.shade100, - contentPadding: const EdgeInsets.all(8), - enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(20), - borderSide: BorderSide( - color: Colors.grey.shade100 - ) + prefixIcon: Icon( + Icons.search, + size: 20 ), ), onChanged: (value) => filterSearchResults(value.toLowerCase()) diff --git a/mobile/lib/views/main/friend_list_item.dart b/mobile/lib/views/main/friend_list_item.dart index 6fbc26b..3dece66 100644 --- a/mobile/lib/views/main/friend_list_item.dart +++ b/mobile/lib/views/main/friend_list_item.dart @@ -24,44 +24,44 @@ class _FriendListItemState extends State { onTap: (){ }, child: Container( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), - child: Row( - children: [ - Expanded( - child: Row( - children: [ - CustomCircleAvatar( - initials: widget.username[0].toUpperCase(), - imagePath: widget.imagePath, - ), - const SizedBox(width: 16), - Expanded( - child: Align( - alignment: Alignment.centerLeft, - child: Container( - color: Colors.transparent, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(widget.username, style: const TextStyle(fontSize: 16)), - // Text( - // widget.messageText, - // style: TextStyle(fontSize: 13, - // color: Colors.grey.shade600, - // fontWeight: widget.isMessageRead?FontWeight.bold:FontWeight.normal - // ), - // ), - ], - ), - ), + padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CustomCircleAvatar( + initials: widget.username[0].toUpperCase(), + imagePath: widget.imagePath, + ), + const SizedBox(width: 16), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: Container( + color: Colors.transparent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(widget.username, style: const TextStyle(fontSize: 16)), + // Text( + // widget.messageText, + // style: TextStyle(fontSize: 13, + // color: Colors.grey.shade600, + // fontWeight: widget.isMessageRead?FontWeight.bold:FontWeight.normal + // ), + // ), + ], ), ), - ], - ), - ), - ], + ), + ), + ], + ), ), - ), - ); + ], + ), + ), + ); } } diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index f7a0d6d..768ef48 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -11,6 +11,7 @@ import '/utils/storage/messages.dart'; import '/utils/storage/session_cookie.dart'; import '/models/conversations.dart'; import '/models/friends.dart'; +import '/models/my_profile.dart'; class Home extends StatefulWidget { const Home({Key? key}) : super(key: key); @@ -33,12 +34,14 @@ class _HomeState extends State { @override void initState() { - super.initState(); updateData(); + super.initState(); } void updateData() async { - await checkLogin(); + if (!await checkLogin()) { + return; + } await updateFriends(); await updateConversations(); await updateMessageThreads(); @@ -56,23 +59,23 @@ class _HomeState extends State { }); } - Future checkLogin() async { - SharedPreferences preferences = await SharedPreferences.getInstance(); + Future checkLogin() async { + bool isLoggedIn = false; - var loggedInTime = preferences.getString('logged_in_at'); - if (loggedInTime == null) { - preferences.remove('logged_in_at'); - preferences.remove('username'); - preferences.remove('userId'); - preferences.remove('asymmetricPublicKey'); + try { + isLoggedIn = await MyProfile.isLoggedIn(); + } catch (Exception) { Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); - return; + return false; } - DateTime loggedInAt = DateTime.parse(loggedInTime); - bool isAfter = loggedInAt.isAfter((DateTime.now()).add(const Duration(hours: 12))); - int statusCode = 200; + if (!isLoggedIn) { + await MyProfile.logout(); + Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); + return false; + } + int statusCode = 200; try { var resp = await http.get( Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/check'), @@ -82,20 +85,18 @@ class _HomeState extends State { ); statusCode = resp.statusCode; } catch(SocketException) { - if (!isAfter) { - return; + if (await MyProfile.isLoggedIn()) { + return true; } } - if (!isAfter && statusCode == 200) { - return; + if (isLoggedIn && statusCode == 200) { + return true; } - preferences.remove('logged_in_at'); - preferences.remove('username'); - preferences.remove('userId'); - preferences.remove('asymmetricPublicKey'); + MyProfile.logout(); Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); + return false; } void _onItemTapped(int index) { @@ -130,13 +131,13 @@ class _HomeState extends State { Widget build(BuildContext context) { return WillPopScope( onWillPop: () async => false, - child: Scaffold( - body: isLoading ? loading() : _widgetOptions.elementAt(_selectedIndex), + child: isLoading ? loading() : Scaffold( + body: _widgetOptions.elementAt(_selectedIndex), bottomNavigationBar: isLoading ? const SizedBox.shrink() : BottomNavigationBar( currentIndex: _selectedIndex, onTap: _onItemTapped, - selectedItemColor: Colors.red, - unselectedItemColor: Colors.grey.shade600, + selectedItemColor: Theme.of(context).primaryColor, + unselectedItemColor: Theme.of(context).hintColor, selectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600), unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600), type: BottomNavigationBarType.fixed, diff --git a/mobile/lib/views/main/profile.dart b/mobile/lib/views/main/profile.dart index ccc84d5..9222403 100644 --- a/mobile/lib/views/main/profile.dart +++ b/mobile/lib/views/main/profile.dart @@ -1,68 +1,77 @@ import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import '/utils/storage/encryption_keys.dart'; import '/utils/storage/database.dart'; +import '/models/my_profile.dart'; class Profile extends StatefulWidget { - const Profile({Key? key}) : super(key: key); + const Profile({Key? key}) : super(key: key); - @override - State createState() => _ProfileState(); + @override + State createState() => _ProfileState(); } class _ProfileState extends State { - @override - Widget build(BuildContext context) { - return Scaffold( - body: SingleChildScrollView( - physics: const BouncingScrollPhysics(), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SafeArea( - child: Padding( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Text("Profile",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), - Container( - padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), - height: 30, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(30), - color: Colors.pink[50], - ), - child: GestureDetector( - onTap: () async { - deleteDb(); - final preferences = await SharedPreferences.getInstance(); - preferences.remove('logged_in_at'); - preferences.remove('username'); - preferences.remove('userId'); - preferences.remove(rsaPrivateKeyName); - Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); - }, - child: Row( - children: const [ - Icon(Icons.logout, color: Colors.pink, size: 20,), - SizedBox(width: 2,), - Text("Logout",style: TextStyle(fontSize: 14,fontWeight: FontWeight.bold),), - ], - ), - ), - ) - ], - ), - ), - ), - const Padding( - padding: EdgeInsets.only(top: 16,left: 16,right: 16), - child: Text('Test'), - ), - ], - ), - ), - ); + @override + Widget build(BuildContext context) { + return Scaffold( + body: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SafeArea( + child: Padding( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text("Profile",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), + Container( + padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), + height: 30, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(30), + color: Theme.of(context).colorScheme.tertiary + ), + child: GestureDetector( + onTap: () { + deleteDb(); + MyProfile.logout(); + Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); + }, + child: Row( + children: [ + Icon( + Icons.logout, + color: Theme.of(context).primaryColor, + size: 20 + ), + const SizedBox(width: 2,), + const Text( + 'Logout', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold + ) + ), + ], + ), + ), + ) + ], + ), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: Row( + children: const [ + Text('FUCK'), + ], + ) + ), + ], + ), + ), + ); } } -- 2.17.1 From 283054bfd58dfef6f9f98bf7c7104fce6b026f2d Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Sat, 9 Jul 2022 15:44:54 +0930 Subject: [PATCH 12/24] Update the conversation settings and profile page --- mobile/lib/models/my_profile.dart | 35 ++-- .../lib/views/main/conversation_settings.dart | 119 ++++++++++++- .../conversation_settings_user_list_item.dart | 64 +++++-- mobile/lib/views/main/home.dart | 14 +- mobile/lib/views/main/profile.dart | 160 ++++++++++++++---- mobile/pubspec.lock | 14 ++ mobile/pubspec.yaml | 1 + 7 files changed, 333 insertions(+), 74 deletions(-) diff --git a/mobile/lib/models/my_profile.dart b/mobile/lib/models/my_profile.dart index c584018..4e95cdb 100644 --- a/mobile/lib/models/my_profile.dart +++ b/mobile/lib/models/my_profile.dart @@ -7,16 +7,16 @@ import 'package:shared_preferences/shared_preferences.dart'; class MyProfile { String id; String username; - RSAPrivateKey privateKey; - RSAPublicKey publicKey; - DateTime loggedInAt; + RSAPrivateKey? privateKey; + RSAPublicKey? publicKey; + DateTime? loggedInAt; MyProfile({ required this.id, required this.username, - required this.privateKey, - required this.publicKey, - required this.loggedInAt, + this.privateKey, + this.publicKey, + this.loggedInAt, }); factory MyProfile._fromJson(Map json) { @@ -49,9 +49,13 @@ class MyProfile { return jsonEncode({ 'user_id': id, 'username': username, - 'asymmetric_private_key': CryptoUtils.encodeRSAPrivateKeyToPem(privateKey), - 'asymmetric_public_key': CryptoUtils.encodeRSAPublicKeyToPem(publicKey), - 'logged_in_at': loggedInAt.toIso8601String(), + 'asymmetric_private_key': privateKey != null ? + CryptoUtils.encodeRSAPrivateKeyToPem(privateKey!) : + null, + 'asymmetric_public_key': publicKey != null ? + CryptoUtils.encodeRSAPublicKeyToPem(publicKey!) : + null, + 'logged_in_at': loggedInAt?.toIso8601String(), }); } @@ -62,7 +66,6 @@ class MyProfile { ); MyProfile profile = MyProfile._fromJson(json); final preferences = await SharedPreferences.getInstance(); - print(profile.toJson()); preferences.setString('profile', profile.toJson()); return profile; } @@ -83,12 +86,20 @@ class MyProfile { static Future isLoggedIn() async { MyProfile profile = await MyProfile.getProfile(); - return profile.loggedInAt.isBefore((DateTime.now()).add(const Duration(hours: 12))); + if (profile.loggedInAt == null) { + return false; + } + return profile.loggedInAt!.isBefore( + (DateTime.now()).add(const Duration(hours: 12)) + ); } Future getPrivateKey() async { MyProfile profile = await MyProfile.getProfile(); - return profile.privateKey; + if (profile.privateKey == null) { + throw Exception('Could not get privateKey'); + } + return profile.privateKey!; } } diff --git a/mobile/lib/views/main/conversation_settings.dart b/mobile/lib/views/main/conversation_settings.dart index c4e04c5..caf917d 100644 --- a/mobile/lib/views/main/conversation_settings.dart +++ b/mobile/lib/views/main/conversation_settings.dart @@ -1,4 +1,5 @@ import 'package:Envelope/models/conversation_users.dart'; +import 'package:Envelope/models/my_profile.dart'; import 'package:flutter/material.dart'; import '/views/main/conversation_settings_user_list_item.dart'; import '/models/conversations.dart'; @@ -16,9 +17,8 @@ class ConversationSettings extends StatefulWidget { } class _ConversationSettingsState extends State { - final _formKey = GlobalKey(); - List users = []; + MyProfile? profile; TextEditingController nameController = TextEditingController(); @@ -31,6 +31,7 @@ class _ConversationSettingsState extends State { Future getUsers() async { users = await getConversationUsers(widget.conversation); + profile = await MyProfile.getProfile(); setState(() {}); } @@ -50,7 +51,101 @@ class _ConversationSettingsState extends State { fontWeight: FontWeight.w500, ), ), - ], + widget.conversation.admin ? IconButton( + iconSize: 20, + icon: const Icon(Icons.edit), + padding: const EdgeInsets.all(5.0), + splashRadius: 25, + onPressed: () { + // TODO: Redirect to edit screen + }, + ) : const SizedBox.shrink(), + ], + ); + } + + Widget sectionTitle(String title) { + return Align( + alignment: Alignment.centerLeft, + child: Container( + padding: const EdgeInsets.only(left: 12), + child: Text( + title, + style: const TextStyle(fontSize: 20), + ), + ), + ); + } + + Widget settings() { + return Align( + alignment: Alignment.centerLeft, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const SizedBox(height: 5), + TextButton.icon( + label: const Text( + 'Disappearing Messages', + style: TextStyle(fontSize: 16) + ), + icon: const Icon(Icons.timer), + style: ButtonStyle( + alignment: Alignment.centerLeft, + foregroundColor: MaterialStateProperty.resolveWith( + (Set states) { + return Theme.of(context).colorScheme.onBackground; + }, + ) + ), + onPressed: () { + print('Disappearing Messages'); + } + ), + TextButton.icon( + label: const Text( + 'Permissions', + style: TextStyle(fontSize: 16) + ), + icon: const Icon(Icons.lock), + style: ButtonStyle( + alignment: Alignment.centerLeft, + foregroundColor: MaterialStateProperty.resolveWith( + (Set states) { + return Theme.of(context).colorScheme.onBackground; + }, + ) + ), + onPressed: () { + print('Permissions'); + } + ), + ], + ), + ); + } + + Widget myAccess() { + return Align( + alignment: Alignment.centerLeft, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + TextButton.icon( + label: const Text( + 'Leave Conversation', + style: TextStyle(fontSize: 16) + ), + icon: const Icon(Icons.exit_to_app), + style: const ButtonStyle( + alignment: Alignment.centerLeft, + ), + onPressed: () { + print('Leave Group'); + } + ), + ], + ), ); } @@ -58,11 +153,12 @@ class _ConversationSettingsState extends State { return ListView.builder( itemCount: users.length, shrinkWrap: true, - padding: const EdgeInsets.only(top: 16), + padding: const EdgeInsets.only(top: 5, bottom: 0), itemBuilder: (context, i) { return ConversationSettingsUserListItem( user: users[i], isAdmin: widget.conversation.admin, + profile: profile!, // TODO: Fix this ); } ); @@ -112,9 +208,20 @@ class _ConversationSettingsState extends State { children: [ const SizedBox(height: 30), conversationName(), - const SizedBox(height: 10), - const Text('Users', style: TextStyle(fontSize: 20)), + const SizedBox(height: 25), + widget.conversation.admin ? + sectionTitle('Settings') : + const SizedBox.shrink(), + widget.conversation.admin ? + settings() : + const SizedBox.shrink(), + widget.conversation.admin ? + const SizedBox(height: 25) : + const SizedBox.shrink(), + sectionTitle('Members'), usersList(), + const SizedBox(height: 25), + myAccess(), ], ), ), diff --git a/mobile/lib/views/main/conversation_settings_user_list_item.dart b/mobile/lib/views/main/conversation_settings_user_list_item.dart index 590fc06..b261aad 100644 --- a/mobile/lib/views/main/conversation_settings_user_list_item.dart +++ b/mobile/lib/views/main/conversation_settings_user_list_item.dart @@ -1,3 +1,4 @@ +import 'package:Envelope/models/my_profile.dart'; import 'package:flutter/material.dart'; import 'package:Envelope/models/conversation_users.dart'; import 'package:Envelope/components/custom_circle_avatar.dart'; @@ -5,10 +6,12 @@ import 'package:Envelope/components/custom_circle_avatar.dart'; class ConversationSettingsUserListItem extends StatefulWidget{ final ConversationUser user; final bool isAdmin; + final MyProfile profile; const ConversationSettingsUserListItem({ Key? key, required this.user, required this.isAdmin, + required this.profile, }) : super(key: key); @override @@ -18,7 +21,7 @@ class ConversationSettingsUserListItem extends StatefulWidget{ class _ConversationSettingsUserListItemState extends State { Widget admin() { - if (widget.user.admin) { + if (!widget.user.admin) { return const SizedBox.shrink(); } @@ -38,33 +41,60 @@ class _ConversationSettingsUserListItemState extends State [ - IconButton(icon: const Icon(Icons.cancel), - padding: const EdgeInsets.all(0), - onPressed:() => { - print('Cancel') - } + return PopupMenuButton( + itemBuilder: (context) => [ + PopupMenuItem( + value: 'admin', + // row with 2 children + child: Row( + children: const [ + Icon(Icons.admin_panel_settings), + SizedBox( + width: 10, + ), + Text('Promote to Admin') + ], + ), + ), + PopupMenuItem( + value: 'remove', + // row with 2 children + child: Row( + children: const [ + Icon(Icons.cancel), + SizedBox( + width: 10, + ), + Text('Remove from chat') + ], + ), ), - IconButton(icon: const Icon(Icons.admin_panel_settings), - padding: const EdgeInsets.all(0), - onPressed:() => { - print('Admin') - } - ) ], + offset: const Offset(0, 50), + elevation: 2, + // on selected we show the dialog box + onSelected: (String value) { + // if value 1 show dialog + if (value == 'admin') { + print('admin'); + return; + // if value 2 show dialog + } + if (value == 'remove') { + print('remove'); + } + }, ); } @override Widget build(BuildContext context) { return Container( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), + padding: const EdgeInsets.only(left: 12,right: 5,top: 0,bottom: 0), child: Row( children: [ Expanded( diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index 768ef48..85f4874 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -23,13 +23,22 @@ class Home extends StatefulWidget { class _HomeState extends State { List conversations = []; List friends = []; + MyProfile profile = MyProfile( + id: '', + username: '', + ); bool isLoading = true; int _selectedIndex = 0; List _widgetOptions = [ const ConversationList(conversations: []), const FriendList(friends: []), - const Profile(), + Profile( + profile: MyProfile( + id: '', + username: '', + ) + ), ]; @override @@ -48,12 +57,13 @@ class _HomeState extends State { conversations = await getConversations(); friends = await getFriends(); + profile = await MyProfile.getProfile(); setState(() { _widgetOptions = [ ConversationList(conversations: conversations), FriendList(friends: friends), - const Profile(), + Profile(profile: profile), ]; isLoading = false; }); diff --git a/mobile/lib/views/main/profile.dart b/mobile/lib/views/main/profile.dart index 9222403..f064ef3 100644 --- a/mobile/lib/views/main/profile.dart +++ b/mobile/lib/views/main/profile.dart @@ -1,15 +1,120 @@ import 'package:flutter/material.dart'; +import 'package:qr_flutter/qr_flutter.dart'; import '/utils/storage/database.dart'; import '/models/my_profile.dart'; +import '/components/custom_circle_avatar.dart'; class Profile extends StatefulWidget { - const Profile({Key? key}) : super(key: key); + final MyProfile profile; + const Profile({ + Key? key, + required this.profile, + }) : super(key: key); @override State createState() => _ProfileState(); } class _ProfileState extends State { + Widget usernameHeading() { + return Row( + children: [ + const CustomCircleAvatar( + icon: Icon(Icons.person, size: 40), + imagePath: null, // TODO: Add image here + radius: 30, + ), + const SizedBox(width: 20), + Text( + widget.profile.username, + style: const TextStyle( + fontSize: 25, + fontWeight: FontWeight.w500, + ), + ), + // widget.conversation.admin ? IconButton( + // iconSize: 20, + // icon: const Icon(Icons.edit), + // padding: const EdgeInsets.all(5.0), + // splashRadius: 25, + // onPressed: () { + // // TODO: Redirect to edit screen + // }, + // ) : const SizedBox.shrink(), + ], + ); + } + + Widget _profileQrCode() { + return Container( + child: QrImage( + data: 'This is a simple QR code', + version: QrVersions.auto, + size: 130, + gapless: true, + ), + width: 130, + height: 130, + color: Theme.of(context).colorScheme.onPrimary, + ); + } + + Widget settings() { + return Align( + alignment: Alignment.centerLeft, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const SizedBox(height: 5), + TextButton.icon( + label: const Text( + 'Disappearing Messages', + style: TextStyle(fontSize: 16) + ), + icon: const Icon(Icons.timer), + style: ButtonStyle( + alignment: Alignment.centerLeft, + foregroundColor: MaterialStateProperty.resolveWith( + (Set states) { + return Theme.of(context).colorScheme.onBackground; + }, + ) + ), + onPressed: () { + print('Disappearing Messages'); + } + ), + ], + ), + ); + } + + Widget logout() { + return Align( + alignment: Alignment.centerLeft, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + TextButton.icon( + label: const Text( + 'Logout', + style: TextStyle(fontSize: 16) + ), + icon: const Icon(Icons.exit_to_app), + style: const ButtonStyle( + alignment: Alignment.centerLeft, + ), + onPressed: () { + deleteDb(); + MyProfile.logout(); + Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); + } + ), + ], + ), + ); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -23,49 +128,30 @@ class _ProfileState extends State { padding: const EdgeInsets.only(left: 16,right: 16,top: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Text("Profile",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), - Container( - padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), - height: 30, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(30), - color: Theme.of(context).colorScheme.tertiary - ), - child: GestureDetector( - onTap: () { - deleteDb(); - MyProfile.logout(); - Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); - }, - child: Row( - children: [ - Icon( - Icons.logout, - color: Theme.of(context).primaryColor, - size: 20 - ), - const SizedBox(width: 2,), - const Text( - 'Logout', - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold - ) - ), - ], - ), + children: const [ + Text( + 'Profile', + style: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold, ), - ) + ), ], ), ), ), Padding( padding: const EdgeInsets.only(top: 16,left: 16,right: 16), - child: Row( - children: const [ - Text('FUCK'), + child: Column( + children: [ + const SizedBox(height: 30), + usernameHeading(), + const SizedBox(height: 30), + _profileQrCode(), + const SizedBox(height: 30), + settings(), + const SizedBox(height: 30), + logout(), ], ) ), diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock index 0f77a70..cfa6a60 100644 --- a/mobile/pubspec.lock +++ b/mobile/pubspec.lock @@ -240,6 +240,20 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "4.2.4" + qr: + dependency: transitive + description: + name: qr + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + qr_flutter: + dependency: "direct main" + description: + name: qr_flutter + url: "https://pub.dartlang.org" + source: hosted + version: "4.0.0" shared_preferences: dependency: "direct main" description: diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml index ded0ef6..ea62a83 100644 --- a/mobile/pubspec.yaml +++ b/mobile/pubspec.yaml @@ -22,6 +22,7 @@ dependencies: flutter_dotenv: ^5.0.2 intl: ^0.17.0 uuid: ^3.0.6 + qr_flutter: ^4.0.0 dev_dependencies: flutter_test: -- 2.17.1 From 4ca108dafaa1759ff76b8bc058121f85d53414cb Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Wed, 13 Jul 2022 20:33:30 +0930 Subject: [PATCH 13/24] Make local conversation records --- mobile/lib/models/conversations.dart | 226 +++++++++++------- mobile/lib/models/friends.dart | 2 + mobile/lib/models/my_profile.dart | 5 +- mobile/lib/utils/storage/database.dart | 1 - .../unauthenticated_landing.dart | 2 +- .../main/conversation_create_add_users.dart | 170 +++++++++++++ .../conversation_create_add_users_list.dart | 96 ++++++++ .../views/main/conversation_edit_details.dart | 146 +++++++++++ mobile/lib/views/main/conversation_list.dart | 32 ++- .../views/main/conversation_list_item.dart | 1 + mobile/lib/views/main/friend_list.dart | 3 +- mobile/lib/views/main/friend_list_item.dart | 25 +- mobile/lib/views/main/home.dart | 7 +- 13 files changed, 608 insertions(+), 108 deletions(-) create mode 100644 mobile/lib/views/main/conversation_create_add_users.dart create mode 100644 mobile/lib/views/main/conversation_create_add_users_list.dart create mode 100644 mobile/lib/views/main/conversation_edit_details.dart diff --git a/mobile/lib/models/conversations.dart b/mobile/lib/models/conversations.dart index ac18d89..45c4e1e 100644 --- a/mobile/lib/models/conversations.dart +++ b/mobile/lib/models/conversations.dart @@ -1,101 +1,163 @@ import 'dart:convert'; +import 'dart:typed_data'; +import 'package:Envelope/models/conversation_users.dart'; +import 'package:Envelope/models/friends.dart'; +import 'package:Envelope/models/my_profile.dart'; import 'package:pointycastle/export.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:uuid/uuid.dart'; import '/utils/encryption/crypto_utils.dart'; import '/utils/encryption/aes_helper.dart'; import '/utils/storage/database.dart'; +import '/utils/strings.dart'; Conversation findConversationByDetailId(List conversations, String id) { - for (var conversation in conversations) { - if (conversation.conversationDetailId == id) { - return conversation; - } + for (var conversation in conversations) { + if (conversation.conversationDetailId == id) { + return conversation; } + } // Or return `null`. throw ArgumentError.value(id, "id", "No element with that id"); } class Conversation { - String id; - String userId; - String conversationDetailId; - String symmetricKey; - bool admin; - String name; - - Conversation({ - required this.id, - required this.userId, - required this.conversationDetailId, - required this.symmetricKey, - required this.admin, - required this.name, - }); - - - factory Conversation.fromJson(Map json, RSAPrivateKey privKey) { - var symmetricKeyDecrypted = CryptoUtils.rsaDecrypt( - base64.decode(json['symmetric_key']), - privKey, - ); - - var detailId = AesHelper.aesDecrypt( - symmetricKeyDecrypted, - base64.decode(json['conversation_detail_id']), - ); - - var admin = AesHelper.aesDecrypt( - symmetricKeyDecrypted, - base64.decode(json['admin']), - ); - - return Conversation( - id: json['id'], - userId: json['user_id'], - conversationDetailId: detailId, - symmetricKey: base64.encode(symmetricKeyDecrypted), - admin: admin == 'true', - name: 'Unknown', - ); - } - - @override - String toString() { - return ''' - - -id: $id -userId: $userId -name: $name -admin: $admin'''; - } - - Map toMap() { - return { - 'id': id, - 'user_id': userId, - 'conversation_detail_id': conversationDetailId, - 'symmetric_key': symmetricKey, - 'admin': admin ? 1 : 0, - 'name': name, - }; - } + String id; + String userId; + String conversationDetailId; + String symmetricKey; + bool admin; + String name; + + Conversation({ + required this.id, + required this.userId, + required this.conversationDetailId, + required this.symmetricKey, + required this.admin, + required this.name, + }); + + + factory Conversation.fromJson(Map json, RSAPrivateKey privKey) { + var symmetricKeyDecrypted = CryptoUtils.rsaDecrypt( + base64.decode(json['symmetric_key']), + privKey, + ); + + var detailId = AesHelper.aesDecrypt( + symmetricKeyDecrypted, + base64.decode(json['conversation_detail_id']), + ); + + var admin = AesHelper.aesDecrypt( + symmetricKeyDecrypted, + base64.decode(json['admin']), + ); + + return Conversation( + id: json['id'], + userId: json['user_id'], + conversationDetailId: detailId, + symmetricKey: base64.encode(symmetricKeyDecrypted), + admin: admin == 'true', + name: 'Unknown', + ); + } + + @override + String toString() { + return ''' + + + id: $id + userId: $userId + name: $name + admin: $admin'''; + } + + Map toMap() { + return { + 'id': id, + 'user_id': userId, + 'conversation_detail_id': conversationDetailId, + 'symmetric_key': symmetricKey, + 'admin': admin ? 1 : 0, + 'name': name, + }; + } } +Future createConversation(String title, List friends) async { + final db = await getDatabaseConnection(); + + MyProfile profile = await MyProfile.getProfile(); + + var uuid = const Uuid(); + final String conversationId = uuid.v4(); + + Uint8List symmetricKey = AesHelper.deriveKey(generateRandomString(32)); + + String associationKey = generateRandomString(32); + + Conversation conversation = Conversation( + id: conversationId, + userId: profile.id, + conversationDetailId: '', + symmetricKey: base64.encode(symmetricKey), + admin: true, + name: title, + ); + + await db.insert( + 'conversations', + conversation.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + + await db.insert( + 'conversation_users', + ConversationUser( + id: uuid.v4(), + conversationId: conversationId, + username: profile.username, + associationKey: associationKey, + admin: false, + ).toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + + for (Friend friend in friends) { + await db.insert( + 'conversation_users', + ConversationUser( + id: uuid.v4(), + conversationId: conversationId, + username: friend.username, + associationKey: associationKey, + admin: false, + ).toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + return conversation; +} // A method that retrieves all the dogs from the dogs table. Future> getConversations() async { - final db = await getDatabaseConnection(); - - final List> maps = await db.query('conversations'); - - return List.generate(maps.length, (i) { - return Conversation( - id: maps[i]['id'], - userId: maps[i]['user_id'], - conversationDetailId: maps[i]['conversation_detail_id'], - symmetricKey: maps[i]['symmetric_key'], - admin: maps[i]['admin'] == 1, - name: maps[i]['name'], - ); - }); + final db = await getDatabaseConnection(); + + final List> maps = await db.query('conversations'); + + return List.generate(maps.length, (i) { + return Conversation( + id: maps[i]['id'], + userId: maps[i]['user_id'], + conversationDetailId: maps[i]['conversation_detail_id'], + symmetricKey: maps[i]['symmetric_key'], + admin: maps[i]['admin'] == 1, + name: maps[i]['name'], + ); + }); } diff --git a/mobile/lib/models/friends.dart b/mobile/lib/models/friends.dart index 0b94b4a..d387e11 100644 --- a/mobile/lib/models/friends.dart +++ b/mobile/lib/models/friends.dart @@ -21,6 +21,7 @@ class Friend{ String friendSymmetricKey; String asymmetricPublicKey; String acceptedAt; + bool? selected; Friend({ required this.id, required this.userId, @@ -29,6 +30,7 @@ class Friend{ required this.friendSymmetricKey, required this.asymmetricPublicKey, required this.acceptedAt, + this.selected, }); factory Friend.fromJson(Map json, RSAPrivateKey privKey) { diff --git a/mobile/lib/models/my_profile.dart b/mobile/lib/models/my_profile.dart index 4e95cdb..ccd0eae 100644 --- a/mobile/lib/models/my_profile.dart +++ b/mobile/lib/models/my_profile.dart @@ -89,8 +89,9 @@ class MyProfile { if (profile.loggedInAt == null) { return false; } - return profile.loggedInAt!.isBefore( - (DateTime.now()).add(const Duration(hours: 12)) + + return profile.loggedInAt!.add(const Duration(hours: 12)).isAfter( + (DateTime.now()) ); } diff --git a/mobile/lib/utils/storage/database.dart b/mobile/lib/utils/storage/database.dart index 162a5c5..a760960 100644 --- a/mobile/lib/utils/storage/database.dart +++ b/mobile/lib/utils/storage/database.dart @@ -39,7 +39,6 @@ Future getDatabaseConnection() async { symmetric_key TEXT, admin INTEGER, name TEXT, - users TEXT ); '''); diff --git a/mobile/lib/views/authentication/unauthenticated_landing.dart b/mobile/lib/views/authentication/unauthenticated_landing.dart index adbdd19..85748ef 100644 --- a/mobile/lib/views/authentication/unauthenticated_landing.dart +++ b/mobile/lib/views/authentication/unauthenticated_landing.dart @@ -18,7 +18,7 @@ class _UnauthenticatedLandingWidgetState extends State friends; + final String title; + const ConversationAddFriendsList({ + Key? key, + required this.friends, + required this.title, + }) : super(key: key); + + @override + State createState() => _ConversationAddFriendsListState(); +} + +class _ConversationAddFriendsListState extends State { + List friends = []; + List friendsSelected = []; + + @override + void initState() { + super.initState(); + friends.addAll(widget.friends); + setState(() {}); + } + + void filterSearchResults(String query) { + List dummySearchList = []; + dummySearchList.addAll(widget.friends); + + if(query.isNotEmpty) { + List dummyListData = []; + for (Friend friend in dummySearchList) { + if (friend.username.toLowerCase().contains(query)) { + dummyListData.add(friend); + } + } + setState(() { + friends.clear(); + friends.addAll(dummyListData); + }); + return; + } + + setState(() { + friends.clear(); + friends.addAll(widget.friends); + }); + } + + Widget list() { + if (friends.isEmpty) { + return const Center( + child: Text('No Friends'), + ); + } + + return ListView.builder( + itemCount: friends.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 16), + physics: const BouncingScrollPhysics(), + itemBuilder: (context, i) { + return ConversationAddFriendItem( + friend: friends[i], + isSelected: (bool value) { + setState(() { + widget.friends[i].selected = value; + if (value) { + friendsSelected.add(friends[i]); + return; + } + friendsSelected.remove(friends[i]); + }); + } + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + elevation: 0, + automaticallyImplyLeading: false, + flexibleSpace: SafeArea( + child: Container( + padding: const EdgeInsets.only(right: 16), + child: Row( + children: [ + IconButton( + onPressed: (){ + Navigator.pop(context); + }, + icon: const Icon(Icons.arrow_back), + ), + const SizedBox(width: 2,), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + friendsSelected.isEmpty ? + 'Select Friends' : + '${friendsSelected.length} Friends Selected', + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600 + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + body: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 20,left: 16,right: 16), + child: TextField( + decoration: const InputDecoration( + hintText: "Search...", + prefixIcon: Icon( + Icons.search, + size: 20 + ), + ), + onChanged: (value) => filterSearchResults(value.toLowerCase()) + ), + ), + Padding( + padding: const EdgeInsets.only(top: 0,left: 16,right: 16), + child: list(), + ), + ], + ), + floatingActionButton: Padding( + padding: const EdgeInsets.only(right: 10, bottom: 10), + child: FloatingActionButton( + onPressed: () async { + Conversation conversation = await createConversation(widget.title, friendsSelected); + + friendsSelected = []; + Navigator.of(context).popUntil((route) => route.isFirst); + Navigator.push(context, MaterialPageRoute(builder: (context){ + return ConversationDetail( + conversation: conversation, + ); + })); + }, + backgroundColor: Theme.of(context).colorScheme.primary, + child: friendsSelected.isEmpty ? + const Text('Skip') : + const Icon(Icons.add, size: 30), + ), + ), + ); + } +} diff --git a/mobile/lib/views/main/conversation_create_add_users_list.dart b/mobile/lib/views/main/conversation_create_add_users_list.dart new file mode 100644 index 0000000..6c53ac4 --- /dev/null +++ b/mobile/lib/views/main/conversation_create_add_users_list.dart @@ -0,0 +1,96 @@ +import 'package:Envelope/components/custom_circle_avatar.dart'; +import 'package:Envelope/models/friends.dart'; +import 'package:flutter/material.dart'; + +class ConversationAddFriendItem extends StatefulWidget{ + final Friend friend; + final ValueChanged isSelected; + const ConversationAddFriendItem({ + Key? key, + required this.friend, + required this.isSelected, + }) : super(key: key); + + @override + _ConversationAddFriendItemState createState() => _ConversationAddFriendItemState(); +} + +class _ConversationAddFriendItemState extends State { + @override + void initState() { + super.initState(); + } + + @override + Widget build(BuildContext context) { + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () async { + setState(() { + widget.friend.selected = !(widget.friend.selected ?? false); + widget.isSelected(widget.friend.selected ?? false); + }); + }, + child: Container( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CustomCircleAvatar( + initials: widget.friend.username[0].toUpperCase(), + imagePath: null, + ), + const SizedBox(width: 16), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: Container( + color: Colors.transparent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.friend.username, + style: const TextStyle( + fontSize: 16 + ) + ), + ], + ), + ), + ), + ), + (widget.friend.selected ?? false) + ? Align( + alignment: Alignment.centerRight, + child: Icon( + Icons.check_circle, + color: Theme.of(context).colorScheme.primary, + size: 36, + ), + ) + : Padding( + padding: const EdgeInsets.only(right: 3), + child: Container( + width: 30, + height: 30, + decoration: BoxDecoration( + border: Border.all( + color: Theme.of(context).colorScheme.primary, + width: 2, + ), + borderRadius: const BorderRadius.all(Radius.circular(100)) + ), + ) + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/mobile/lib/views/main/conversation_edit_details.dart b/mobile/lib/views/main/conversation_edit_details.dart new file mode 100644 index 0000000..a882913 --- /dev/null +++ b/mobile/lib/views/main/conversation_edit_details.dart @@ -0,0 +1,146 @@ +import 'package:flutter/material.dart'; +import '/components/custom_circle_avatar.dart'; +import '/views/main/conversation_create_add_users.dart'; +import '/models/friends.dart'; +import '/models/conversations.dart'; + +class ConversationEditDetails extends StatefulWidget { + final Conversation? conversation; + final List? friends; + const ConversationEditDetails({ + Key? key, + this.conversation, + this.friends, + }) : super(key: key); + + @override + State createState() => _ConversationEditDetails(); +} + +class _ConversationEditDetails extends State { + final _formKey = GlobalKey(); + + List conversations = []; + + TextEditingController conversationNameController = TextEditingController(); + + @override + Widget build(BuildContext context) { + const TextStyle inputTextStyle = TextStyle( + fontSize: 25, + ); + + final OutlineInputBorder inputBorderStyle = OutlineInputBorder( + borderRadius: BorderRadius.circular(5), + borderSide: const BorderSide( + color: Colors.transparent, + ) + ); + + final ButtonStyle buttonStyle = ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 10), + textStyle: TextStyle( + fontSize: 15, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.error, + ), + ); + + return Scaffold( + appBar: AppBar( + elevation: 0, + automaticallyImplyLeading: false, + flexibleSpace: SafeArea( + child: Container( + padding: const EdgeInsets.only(right: 16), + child: Row( + children: [ + IconButton( + onPressed: (){ + Navigator.pop(context); + }, + icon: const Icon(Icons.arrow_back), + ), + const SizedBox(width: 2,), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + widget.conversation != null ? + widget.conversation!.name + " Settings" : + 'Add Conversation', + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600 + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + body: Center( + child: Padding( + padding: const EdgeInsets.only( + top: 50, + left: 25, + right: 25, + ), + child: Form( + key: _formKey, + child: Column( + children: [ + CustomCircleAvatar( + icon: widget.conversation != null ? + null : // TODO: Add icon here + const Icon(Icons.people, size: 60), + imagePath: null, + radius: 50, + ), + const SizedBox(height: 30), + TextFormField( + controller: conversationNameController, + textAlign: TextAlign.center, + decoration: InputDecoration( + hintText: 'Title', + enabledBorder: inputBorderStyle, + focusedBorder: inputBorderStyle, + ), + style: inputTextStyle, + // The validator receives the text that the user has entered. + validator: (value) { + if (value == null || value.isEmpty) { + return 'Add a title'; + } + return null; + }, + ), + const SizedBox(height: 30), + ElevatedButton( + style: buttonStyle, + onPressed: () { + if (_formKey.currentState!.validate()) { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ConversationAddFriendsList( + friends: widget.friends!, + title: conversationNameController.text, + ) + ) + ); + } + }, + child: const Text('Save'), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/mobile/lib/views/main/conversation_list.dart b/mobile/lib/views/main/conversation_list.dart index 8ba20f7..b827ea6 100644 --- a/mobile/lib/views/main/conversation_list.dart +++ b/mobile/lib/views/main/conversation_list.dart @@ -1,12 +1,16 @@ +import 'package:Envelope/models/friends.dart'; +import 'package:Envelope/views/main/conversation_edit_details.dart'; import 'package:flutter/material.dart'; import '/models/conversations.dart'; import '/views/main/conversation_list_item.dart'; class ConversationList extends StatefulWidget { final List conversations; + final List friends; const ConversationList({ Key? key, required this.conversations, + required this.friends, }) : super(key: key); @override @@ -15,11 +19,13 @@ class ConversationList extends StatefulWidget { class _ConversationListState extends State { List conversations = []; + List friends = []; @override void initState() { super.initState(); conversations.addAll(widget.conversations); + friends.addAll(widget.friends); setState(() {}); } @@ -81,7 +87,13 @@ class _ConversationListState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: const [ - Text("Conversations",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), + Text( + 'Conversations', + style: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold + ) + ), ], ), ), @@ -106,6 +118,24 @@ class _ConversationListState extends State { ], ), ), + floatingActionButton: Padding( + padding: const EdgeInsets.only(right: 10, bottom: 10), + child: FloatingActionButton( + onPressed: () { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ConversationEditDetails( + friends: friends, + )), + ).then(onGoBack); + }, + backgroundColor: Theme.of(context).colorScheme.primary, + child: const Icon(Icons.add, size: 30), + ), + ), ); } + + onGoBack(dynamic value) { + setState(() {}); + } } diff --git a/mobile/lib/views/main/conversation_list_item.dart b/mobile/lib/views/main/conversation_list_item.dart index ecfc157..885400f 100644 --- a/mobile/lib/views/main/conversation_list_item.dart +++ b/mobile/lib/views/main/conversation_list_item.dart @@ -19,6 +19,7 @@ class _ConversationListItemState extends State { @override Widget build(BuildContext context) { return GestureDetector( + behavior: HitTestBehavior.opaque, onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context){ return ConversationDetail( diff --git a/mobile/lib/views/main/friend_list.dart b/mobile/lib/views/main/friend_list.dart index f331659..f1076ef 100644 --- a/mobile/lib/views/main/friend_list.dart +++ b/mobile/lib/views/main/friend_list.dart @@ -62,8 +62,7 @@ class _FriendListState extends State { physics: const NeverScrollableScrollPhysics(), itemBuilder: (context, i) { return FriendListItem( - id: friends[i].id, - username: friends[i].username, + friend: friends[i], ); }, ); diff --git a/mobile/lib/views/main/friend_list_item.dart b/mobile/lib/views/main/friend_list_item.dart index 3dece66..fd13204 100644 --- a/mobile/lib/views/main/friend_list_item.dart +++ b/mobile/lib/views/main/friend_list_item.dart @@ -1,15 +1,12 @@ import 'package:Envelope/components/custom_circle_avatar.dart'; +import 'package:Envelope/models/friends.dart'; import 'package:flutter/material.dart'; class FriendListItem extends StatefulWidget{ - final String id; - final String username; - final String? imagePath; + final Friend friend; const FriendListItem({ Key? key, - required this.id, - required this.username, - this.imagePath, + required this.friend, }) : super(key: key); @override @@ -21,7 +18,8 @@ class _FriendListItemState extends State { @override Widget build(BuildContext context) { return GestureDetector( - onTap: (){ + behavior: HitTestBehavior.opaque, + onTap: () async { }, child: Container( padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), @@ -31,8 +29,8 @@ class _FriendListItemState extends State { child: Row( children: [ CustomCircleAvatar( - initials: widget.username[0].toUpperCase(), - imagePath: widget.imagePath, + initials: widget.friend.username[0].toUpperCase(), + imagePath: null, ), const SizedBox(width: 16), Expanded( @@ -43,14 +41,7 @@ class _FriendListItemState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(widget.username, style: const TextStyle(fontSize: 16)), - // Text( - // widget.messageText, - // style: TextStyle(fontSize: 13, - // color: Colors.grey.shade600, - // fontWeight: widget.isMessageRead?FontWeight.bold:FontWeight.normal - // ), - // ), + Text(widget.friend.username, style: const TextStyle(fontSize: 16)), ], ), ), diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index 85f4874..31a1a36 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -31,7 +31,7 @@ class _HomeState extends State { bool isLoading = true; int _selectedIndex = 0; List _widgetOptions = [ - const ConversationList(conversations: []), + const ConversationList(conversations: [], friends: []), const FriendList(friends: []), Profile( profile: MyProfile( @@ -61,7 +61,10 @@ class _HomeState extends State { setState(() { _widgetOptions = [ - ConversationList(conversations: conversations), + ConversationList( + conversations: conversations, + friends: friends, + ), FriendList(friends: friends), Profile(profile: profile), ]; -- 2.17.1 From b05b90e6d2a9e4c1aac9d0bff8df050b2f563592 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Tue, 19 Jul 2022 20:24:00 +0930 Subject: [PATCH 14/24] Remove friends table due to unnecessary added complexity WIP - Creating conversations --- Backend/Api/Friends/EncryptedFriendsList.go | 38 ---- Backend/Api/Messages/CreateConversation.go | 54 ++++++ Backend/Api/Routes.go | 8 +- Backend/Database/ConversationDetails.go | 2 +- Backend/Database/Friends.go | 74 ------- Backend/Database/Init.go | 11 +- Backend/Database/Seeder/FriendSeeder.go | 36 ++-- Backend/Database/Seeder/MessageSeeder.go | 47 ++--- Backend/Database/Seeder/UserSeeder.go | 40 +--- Backend/Database/UserConversations.go | 20 +- Backend/Models/Friends.go | 20 +- Backend/Models/Users.go | 10 +- mobile/lib/models/conversation_users.dart | 44 ++--- mobile/lib/models/conversations.dart | 183 +++++++++++++----- mobile/lib/models/friends.dart | 58 +++--- mobile/lib/models/my_profile.dart | 11 +- mobile/lib/utils/storage/conversations.dart | 156 ++++++++------- mobile/lib/utils/storage/database.dart | 4 +- mobile/lib/utils/storage/encryption_keys.dart | 27 --- mobile/lib/utils/storage/friends.dart | 60 ++---- mobile/lib/utils/storage/messages.dart | 30 ++- .../main/conversation_create_add_users.dart | 8 +- .../lib/views/main/conversation_detail.dart | 23 ++- mobile/lib/views/main/conversation_list.dart | 8 +- .../views/main/conversation_list_item.dart | 27 ++- mobile/lib/views/main/home.dart | 2 +- mobile/lib/views/main/profile.dart | 15 ++ 27 files changed, 499 insertions(+), 517 deletions(-) create mode 100644 Backend/Api/Messages/CreateConversation.go delete mode 100644 Backend/Database/Friends.go delete mode 100644 mobile/lib/utils/storage/encryption_keys.dart diff --git a/Backend/Api/Friends/EncryptedFriendsList.go b/Backend/Api/Friends/EncryptedFriendsList.go index d9f8d61..441284f 100644 --- a/Backend/Api/Friends/EncryptedFriendsList.go +++ b/Backend/Api/Friends/EncryptedFriendsList.go @@ -3,8 +3,6 @@ package Friends import ( "encoding/json" "net/http" - "net/url" - "strings" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" @@ -40,39 +38,3 @@ func EncryptedFriendRequestList(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write(returnJson) } - -func EncryptedFriendList(w http.ResponseWriter, r *http.Request) { - var ( - friends []Models.Friend - query url.Values - friendIds []string - returnJson []byte - ok bool - err error - ) - - query = r.URL.Query() - friendIds, ok = query["friend_ids"] - if !ok { - http.Error(w, "Invalid Data", http.StatusBadGateway) - return - } - - // TODO: Fix error handling here - friendIds = strings.Split(friendIds[0], ",") - - friends, err = Database.GetFriendsByIds(friendIds) - if err != nil { - http.Error(w, "Error", http.StatusInternalServerError) - return - } - - returnJson, err = json.MarshalIndent(friends, "", " ") - if err != nil { - http.Error(w, "Error", http.StatusInternalServerError) - return - } - - w.WriteHeader(http.StatusOK) - w.Write(returnJson) -} diff --git a/Backend/Api/Messages/CreateConversation.go b/Backend/Api/Messages/CreateConversation.go new file mode 100644 index 0000000..b2dccd9 --- /dev/null +++ b/Backend/Api/Messages/CreateConversation.go @@ -0,0 +1,54 @@ +package Messages + +import ( + "encoding/json" + "net/http" + "github.com/gofrs/uuid" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +type RawConversationData struct { + ID string `json:"id"` + Name string `json:"name"` + Users string `json:"users"` + UserConversations []Models.UserConversation `json:"user_conversations"` +} + +func CreateConversation(w http.ResponseWriter, r *http.Request) { + var ( + rawConversationData RawConversationData + messageThread Models.ConversationDetail + err error + ) + + err = json.NewDecoder(r.Body).Decode(&rawConversationData) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + messageThread = Models.ConversationDetail{ + Base: Models.Base{ + ID: uuid.FromStringOrNil(rawConversationData.ID), + }, + Name: rawConversationData.Name, + Users: rawConversationData.Users, + } + + err = Database.CreateConversationDetail(&messageThread) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + err = Database.CreateUserConversations(&rawConversationData.UserConversations) + if err != nil { + panic(err) + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) +} diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index 5aee439..a37fc15 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -26,9 +26,7 @@ func loggingMiddleware(next http.Handler) http.Handler { func authenticationMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var ( - err error - ) + var err error _, err = Auth.CheckCookie(r) if err != nil { @@ -65,11 +63,11 @@ func InitApiEndpoints(router *mux.Router) { authApi.HandleFunc("/friend_requests", Friends.EncryptedFriendRequestList).Methods("GET") authApi.HandleFunc("/friend_request", Friends.CreateFriendRequest).Methods("POST") - authApi.HandleFunc("/friends", Friends.EncryptedFriendList).Methods("GET") - authApi.HandleFunc("/conversations", Messages.EncryptedConversationList).Methods("GET") authApi.HandleFunc("/conversation_details", Messages.EncryptedConversationDetailsList).Methods("GET") + authApi.HandleFunc("/conversations", Messages.CreateConversation).Methods("POST") + // Define routes for messages authApi.HandleFunc("/message", Messages.CreateMessage).Methods("POST") authApi.HandleFunc("/messages/{threadKey}", Messages.Messages).Methods("GET") diff --git a/Backend/Database/ConversationDetails.go b/Backend/Database/ConversationDetails.go index 144e28c..cd1140d 100644 --- a/Backend/Database/ConversationDetails.go +++ b/Backend/Database/ConversationDetails.go @@ -28,7 +28,7 @@ func GetConversationDetailsByIds(id []string) ([]Models.ConversationDetail, erro ) err = DB.Preload(clause.Associations). - Where("id = ?", id). + Where("id IN ?", id). First(&messageThread). Error diff --git a/Backend/Database/Friends.go b/Backend/Database/Friends.go deleted file mode 100644 index 102e657..0000000 --- a/Backend/Database/Friends.go +++ /dev/null @@ -1,74 +0,0 @@ -package Database - -import ( - "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" - - "gorm.io/gorm" - "gorm.io/gorm/clause" -) - -func GetFriendById(id string) (Models.Friend, error) { - var ( - userData Models.Friend - err error - ) - - err = DB.Preload(clause.Associations). - First(&userData, "id = ?", id). - Error - - return userData, err -} - -func GetFriendsByIds(ids []string) ([]Models.Friend, error) { - var ( - userData []Models.Friend - err error - ) - - err = DB.Preload(clause.Associations). - Find(&userData, ids). - Error - - return userData, err -} - -func CreateFriend(userData *Models.Friend) error { - var ( - err error - ) - - err = DB.Session(&gorm.Session{FullSaveAssociations: true}). - Create(userData). - Error - - return err -} - -func UpdateFriend(id string, userData *Models.Friend) error { - var ( - err error - ) - err = DB.Model(&userData). - Omit("id"). - Where("id = ?", id). - Updates(userData). - Error - - if err != nil { - return err - } - - err = DB.Model(Models.Friend{}). - Where("id = ?", id). - First(userData). - Error - - return err -} - -func DeleteFriend(userData *Models.Friend) error { - return DB.Session(&gorm.Session{FullSaveAssociations: true}). - Delete(userData). - Error -} diff --git a/Backend/Database/Init.go b/Backend/Database/Init.go index f8537d4..6241fdb 100644 --- a/Backend/Database/Init.go +++ b/Backend/Database/Init.go @@ -9,18 +9,17 @@ import ( "gorm.io/gorm" ) -const dbUrl = "postgres://postgres:@localhost:5432/envelope" -const dbTestUrl = "postgres://postgres:@localhost:5432/envelope_test" - -var ( - DB *gorm.DB +const ( + dbUrl = "postgres://postgres:@localhost:5432/envelope" + dbTestUrl = "postgres://postgres:@localhost:5432/envelope_test" ) +var DB *gorm.DB + func GetModels() []interface{} { return []interface{}{ &Models.Session{}, &Models.User{}, - &Models.Friend{}, &Models.FriendRequest{}, &Models.MessageData{}, &Models.Message{}, diff --git a/Backend/Database/Seeder/FriendSeeder.go b/Backend/Database/Seeder/FriendSeeder.go index 5d79da2..7b3f960 100644 --- a/Backend/Database/Seeder/FriendSeeder.go +++ b/Backend/Database/Seeder/FriendSeeder.go @@ -11,36 +11,42 @@ import ( func seedFriend(userRequestTo, userRequestFrom Models.User) error { var ( friendRequest Models.FriendRequest - decodedID []byte - id []byte - decodedSymKey []byte - symKey []byte + symKey aesKey + encPublicKey []byte err error ) - decodedID, err = base64.StdEncoding.DecodeString(userRequestFrom.FriendID) - if err != nil { - return err - } - id, err = decryptWithPrivateKey(decodedID, decodedPrivateKey) + symKey, err = generateAesKey() if err != nil { return err } - decodedSymKey, err = base64.StdEncoding.DecodeString(userRequestFrom.FriendSymmetricKey) + encPublicKey, err = symKey.aesEncrypt([]byte(publicKey)) if err != nil { return err } - symKey, err = decryptWithPrivateKey(decodedSymKey, decodedPrivateKey) friendRequest = Models.FriendRequest{ - UserID: userRequestTo.ID, - AcceptedAt: time.Now(), + UserID: userRequestTo.ID, + UserUsername: userRequestTo.Username, + AcceptedAt: time.Now(), FriendID: base64.StdEncoding.EncodeToString( - encryptWithPublicKey(id, decodedPublicKey), + encryptWithPublicKey( + []byte(userRequestFrom.ID.String()), + decodedPublicKey, + ), + ), + FriendUsername: base64.StdEncoding.EncodeToString( + encryptWithPublicKey( + []byte(userRequestFrom.Username), + decodedPublicKey, + ), + ), + FriendPublicAsymmetricKey: base64.StdEncoding.EncodeToString( + encPublicKey, ), SymmetricKey: base64.StdEncoding.EncodeToString( - encryptWithPublicKey(symKey, decodedPublicKey), + encryptWithPublicKey(symKey.Key, decodedPublicKey), ), } diff --git a/Backend/Database/Seeder/MessageSeeder.go b/Backend/Database/Seeder/MessageSeeder.go index a725c5f..76ec995 100644 --- a/Backend/Database/Seeder/MessageSeeder.go +++ b/Backend/Database/Seeder/MessageSeeder.go @@ -24,7 +24,6 @@ func seedMessage( plaintext string dataCiphertext []byte senderIdCiphertext []byte - friendId []byte err error ) @@ -45,31 +44,13 @@ func seedMessage( panic(err) } - friendId, err = base64.StdEncoding.DecodeString(primaryUser.FriendID) - if err != nil { - panic(err) - } - friendId, err = decryptWithPrivateKey(friendId, decodedPrivateKey) - if err != nil { - panic(err) - } - - senderIdCiphertext, err = key.aesEncrypt(friendId) + senderIdCiphertext, err = key.aesEncrypt([]byte(primaryUser.ID.String())) if err != nil { panic(err) } if i%2 == 0 { - friendId, err = base64.StdEncoding.DecodeString(secondaryUser.FriendID) - if err != nil { - panic(err) - } - friendId, err = decryptWithPrivateKey(friendId, decodedPrivateKey) - if err != nil { - panic(err) - } - - senderIdCiphertext, err = key.aesEncrypt(friendId) + senderIdCiphertext, err = key.aesEncrypt([]byte(secondaryUser.ID.String())) if err != nil { panic(err) } @@ -198,9 +179,8 @@ func SeedMessages() { primaryUserAssociationKey string secondaryUser Models.User secondaryUserAssociationKey string - primaryUserFriendId []byte - secondaryUserFriendId []byte userJson string + id1, id2 uuid.UUID i int err error ) @@ -233,20 +213,11 @@ func SeedMessages() { key, ) - primaryUserFriendId, err = base64.StdEncoding.DecodeString(primaryUser.FriendID) - if err != nil { - panic(err) - } - primaryUserFriendId, err = decryptWithPrivateKey(primaryUserFriendId, decodedPrivateKey) - if err != nil { - panic(err) - } - - secondaryUserFriendId, err = base64.StdEncoding.DecodeString(secondaryUser.FriendID) + id1, err = uuid.NewV4() if err != nil { panic(err) } - secondaryUserFriendId, err = decryptWithPrivateKey(secondaryUserFriendId, decodedPrivateKey) + id2, err = uuid.NewV4() if err != nil { panic(err) } @@ -256,22 +227,26 @@ func SeedMessages() { [ { "id": "%s", + "user_id": "%s", "username": "%s", "admin": "true", "association_key": "%s" }, { "id": "%s", + "user_id": "%s", "username": "%s", "admin": "false", "association_key": "%s" } ] `, - string(primaryUserFriendId), + id1.String(), + primaryUser.ID.String(), primaryUser.Username, primaryUserAssociationKey, - string(secondaryUserFriendId), + id2.String(), + secondaryUser.ID.String(), secondaryUser.Username, secondaryUserAssociationKey, ) diff --git a/Backend/Database/Seeder/UserSeeder.go b/Backend/Database/Seeder/UserSeeder.go index 3c99c9c..ce13b2a 100644 --- a/Backend/Database/Seeder/UserSeeder.go +++ b/Backend/Database/Seeder/UserSeeder.go @@ -1,8 +1,6 @@ package Seeder import ( - "encoding/base64" - "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" @@ -24,12 +22,9 @@ var userNames = []string{ func createUser(username string) (Models.User, error) { var ( - userData Models.User - key aesKey - publicUserData Models.Friend - password string - usernameCiphertext []byte - err error + userData Models.User + password string + err error ) password, err = Auth.HashPassword("password") @@ -37,40 +32,11 @@ func createUser(username string) (Models.User, error) { return Models.User{}, err } - key, err = generateAesKey() - if err != nil { - return Models.User{}, err - } - - usernameCiphertext, err = key.aesEncrypt([]byte(username)) - if err != nil { - return Models.User{}, err - } - - publicUserData = Models.Friend{ - Username: base64.StdEncoding.EncodeToString(usernameCiphertext), - AsymmetricPublicKey: publicKey, - } - - err = Database.CreateFriend(&publicUserData) - if err != nil { - return userData, err - } - userData = Models.User{ Username: username, Password: password, AsymmetricPrivateKey: encryptedPrivateKey, AsymmetricPublicKey: publicKey, - FriendID: base64.StdEncoding.EncodeToString( - encryptWithPublicKey( - []byte(publicUserData.ID.String()), - decodedPublicKey, - ), - ), - FriendSymmetricKey: base64.StdEncoding.EncodeToString( - encryptWithPublicKey(key.Key, decodedPublicKey), - ), } err = Database.CreateUser(&userData) diff --git a/Backend/Database/UserConversations.go b/Backend/Database/UserConversations.go index 8e5490b..3623fda 100644 --- a/Backend/Database/UserConversations.go +++ b/Backend/Database/UserConversations.go @@ -30,20 +30,32 @@ func GetUserConversationsByUserId(id string) ([]Models.UserConversation, error) return conversations, err } -func CreateUserConversation(messageThreadUser *Models.UserConversation) error { +func CreateUserConversation(userConversation *Models.UserConversation) error { var ( err error ) err = DB.Session(&gorm.Session{FullSaveAssociations: true}). - Create(messageThreadUser). + Create(userConversation). Error return err } -func DeleteUserConversation(messageThreadUser *Models.UserConversation) error { +func CreateUserConversations(userConversations *[]Models.UserConversation) error { + var ( + err error + ) + + err = DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(userConversations). + Error + + return err +} + +func DeleteUserConversation(userConversation *Models.UserConversation) error { return DB.Session(&gorm.Session{FullSaveAssociations: true}). - Delete(messageThreadUser). + Delete(userConversation). Error } diff --git a/Backend/Models/Friends.go b/Backend/Models/Friends.go index 5022d9b..183e2dc 100644 --- a/Backend/Models/Friends.go +++ b/Backend/Models/Friends.go @@ -6,19 +6,15 @@ import ( "github.com/gofrs/uuid" ) -// TODO: Add profile picture -type Friend struct { - Base - Username string `gorm:"not null" json:"username"` // Stored encrypted - AsymmetricPublicKey string `gorm:"not null" json:"asymmetric_public_key"` // Stored encrypted -} - // Set with Friend being the requestee, and RequestFromID being the requester type FriendRequest struct { Base - UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` - User User `json:"user"` - FriendID string `gorm:"not null" json:"friend_id"` // Stored encrypted - SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted - AcceptedAt time.Time `json:"accepted_at"` + UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` + User User ` json:"user"` + UserUsername string ` json:"user_username"` + FriendID string `gorm:"not null" json:"friend_id"` // Stored encrypted + FriendUsername string ` json:"friend_username"` + FriendPublicAsymmetricKey string ` json:"asymmetric_public_key"` + SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted + AcceptedAt time.Time ` json:"accepted_at"` } diff --git a/Backend/Models/Users.go b/Backend/Models/Users.go index 0525b52..4727e26 100644 --- a/Backend/Models/Users.go +++ b/Backend/Models/Users.go @@ -16,10 +16,8 @@ func (u *User) BeforeUpdate(tx *gorm.DB) (err error) { type User struct { Base Username string `gorm:"not null;unique" json:"username"` - Password string `gorm:"not null" json:"password"` - ConfirmPassword string `gorm:"-" json:"confirm_password"` - AsymmetricPrivateKey string `gorm:"not null" json:"asymmetric_private_key"` // Stored encrypted - AsymmetricPublicKey string `gorm:"not null" json:"asymmetric_public_key"` - FriendID string `gorm:"not null" json:"public_user_id"` // Stored encrypted - FriendSymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted + Password string `gorm:"not null" json:"password"` + ConfirmPassword string `gorm:"-" json:"confirm_password"` + AsymmetricPrivateKey string `gorm:"not null" json:"asymmetric_private_key"` // Stored encrypted + AsymmetricPublicKey string `gorm:"not null" json:"asymmetric_public_key"` } diff --git a/mobile/lib/models/conversation_users.dart b/mobile/lib/models/conversation_users.dart index e0e000d..34e6e40 100644 --- a/mobile/lib/models/conversation_users.dart +++ b/mobile/lib/models/conversation_users.dart @@ -3,12 +3,14 @@ import '/models/conversations.dart'; class ConversationUser{ String id; + String userId; String conversationId; String username; String associationKey; bool admin; ConversationUser({ required this.id, + required this.userId, required this.conversationId, required this.username, required this.associationKey, @@ -18,6 +20,7 @@ class ConversationUser{ factory ConversationUser.fromJson(Map json, String conversationId) { return ConversationUser( id: json['id'], + userId: json['user_id'], conversationId: conversationId, username: json['username'], associationKey: json['association_key'], @@ -25,9 +28,20 @@ class ConversationUser{ ); } + Map toJson() { + return { + 'id': id, + 'user_id': userId, + 'username': username, + 'associationKey': associationKey, + 'admin': admin ? 'true' : 'false', + }; + } + Map toMap() { return { 'id': id, + 'user_id': userId, 'conversation_id': conversationId, 'username': username, 'association_key': associationKey, @@ -50,6 +64,7 @@ Future> getConversationUsers(Conversation conversation) a return List.generate(maps.length, (i) { return ConversationUser( id: maps[i]['id'], + userId: maps[i]['user_id'], conversationId: maps[i]['conversation_id'], username: maps[i]['username'], associationKey: maps[i]['association_key'], @@ -58,36 +73,14 @@ Future> getConversationUsers(Conversation conversation) a }); } -Future getConversationUserById(Conversation conversation, String id) async { +Future getConversationUser(Conversation conversation, String userId) async { final db = await getDatabaseConnection(); - final List> maps = await db.query( - 'conversation_users', - where: 'conversation_id = ? AND id = ?', - whereArgs: [conversation.id, id], - ); - - if (maps.length != 1) { - throw ArgumentError('Invalid conversation_id or id'); - } - - return ConversationUser( - id: maps[0]['id'], - conversationId: maps[0]['conversation_id'], - username: maps[0]['username'], - associationKey: maps[0]['association_key'], - admin: maps[0]['admin'] == 1, - ); - -} - -Future getConversationUserByUsername(Conversation conversation, String username) async { - final db = await getDatabaseConnection(); final List> maps = await db.query( 'conversation_users', - where: 'conversation_id = ? AND username = ?', - whereArgs: [conversation.id, username], + where: 'conversation_id = ? AND user_id = ?', + whereArgs: [conversation.id, userId], ); if (maps.length != 1) { @@ -96,6 +89,7 @@ Future getConversationUserByUsername(Conversation conversation return ConversationUser( id: maps[0]['id'], + userId: maps[0]['user_id'], conversationId: maps[0]['conversation_id'], username: maps[0]['username'], associationKey: maps[0]['association_key'], diff --git a/mobile/lib/models/conversations.dart b/mobile/lib/models/conversations.dart index 45c4e1e..ed06387 100644 --- a/mobile/lib/models/conversations.dart +++ b/mobile/lib/models/conversations.dart @@ -11,14 +11,10 @@ import '/utils/encryption/aes_helper.dart'; import '/utils/storage/database.dart'; import '/utils/strings.dart'; -Conversation findConversationByDetailId(List conversations, String id) { - for (var conversation in conversations) { - if (conversation.conversationDetailId == id) { - return conversation; - } - } - // Or return `null`. - throw ArgumentError.value(id, "id", "No element with that id"); +enum ConversationStatus { + complete, + pending, + error, } class Conversation { @@ -28,6 +24,7 @@ class Conversation { String symmetricKey; bool admin; String name; + ConversationStatus status; Conversation({ required this.id, @@ -36,35 +33,86 @@ class Conversation { required this.symmetricKey, required this.admin, required this.name, + required this.status, }); factory Conversation.fromJson(Map json, RSAPrivateKey privKey) { var symmetricKeyDecrypted = CryptoUtils.rsaDecrypt( - base64.decode(json['symmetric_key']), - privKey, + base64.decode(json['symmetric_key']), + privKey, ); var detailId = AesHelper.aesDecrypt( - symmetricKeyDecrypted, - base64.decode(json['conversation_detail_id']), + symmetricKeyDecrypted, + base64.decode(json['conversation_detail_id']), ); var admin = AesHelper.aesDecrypt( - symmetricKeyDecrypted, - base64.decode(json['admin']), + symmetricKeyDecrypted, + base64.decode(json['admin']), ); return Conversation( - id: json['id'], - userId: json['user_id'], - conversationDetailId: detailId, - symmetricKey: base64.encode(symmetricKeyDecrypted), - admin: admin == 'true', - name: 'Unknown', + id: json['id'], + userId: json['user_id'], + conversationDetailId: detailId, + symmetricKey: base64.encode(symmetricKeyDecrypted), + admin: admin == 'true', + name: 'Unknown', + status: ConversationStatus.complete, ); } + Future> toJson() async { + MyProfile profile = await MyProfile.getProfile(); + + var symKey = base64.decode(symmetricKey); + + List users = await getConversationUsers(this); + List userConversations = []; + + for (var x in users) { + print(x.toMap()); + } + + for (ConversationUser user in users) { + if (profile.id == user.userId) { + userConversations.add({ + 'id': user.id, + 'user_id': profile.id, + 'conversation_detail_id': AesHelper.aesEncrypt(symKey, Uint8List.fromList(id.codeUnits)), + 'admin': AesHelper.aesEncrypt(symKey, Uint8List.fromList((admin ? 'true' : 'false').codeUnits)), + 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt(symKey, profile.publicKey!)), + }); + + continue; + } + + Friend friend = await getFriendByFriendId(user.userId); + RSAPublicKey pubKey = CryptoUtils.rsaPublicKeyFromPem(friend.asymmetricPublicKey); + + userConversations.add({ + 'id': user.id, + 'user_id': friend.userId, + 'conversation_detail_id': AesHelper.aesEncrypt(symKey, Uint8List.fromList(id.codeUnits)), + 'admin': AesHelper.aesEncrypt(symKey, Uint8List.fromList((admin ? 'true' : 'false').codeUnits)), + 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt(symKey, pubKey)), + }); + } + + for (var x in userConversations) { + print(x); + } + + return { + 'id': id, + 'name': AesHelper.aesEncrypt(symKey, Uint8List.fromList(name.codeUnits)), + 'users': AesHelper.aesEncrypt(symKey, Uint8List.fromList(jsonEncode(users).codeUnits)), + 'user_conversations': userConversations, + }; + } + @override String toString() { return ''' @@ -84,6 +132,7 @@ class Conversation { 'symmetric_key': symmetricKey, 'admin': admin ? 1 : 0, 'name': name, + 'status': status.index, }; } } @@ -107,43 +156,57 @@ Future createConversation(String title, List friends) asyn symmetricKey: base64.encode(symmetricKey), admin: true, name: title, + status: ConversationStatus.pending, ); await db.insert( - 'conversations', - conversation.toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, + 'conversations', + conversation.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, ); await db.insert( - 'conversation_users', - ConversationUser( - id: uuid.v4(), - conversationId: conversationId, - username: profile.username, - associationKey: associationKey, - admin: false, - ).toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, + 'conversation_users', + ConversationUser( + id: uuid.v4(), + userId: profile.id, + conversationId: conversationId, + username: profile.username, + associationKey: associationKey, + admin: true, + ).toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, ); for (Friend friend in friends) { await db.insert( - 'conversation_users', - ConversationUser( - id: uuid.v4(), - conversationId: conversationId, - username: friend.username, - associationKey: associationKey, - admin: false, - ).toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, + 'conversation_users', + ConversationUser( + id: uuid.v4(), + userId: friend.friendId, + conversationId: conversationId, + username: friend.username, + associationKey: associationKey, + admin: false, + ).toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, ); } return conversation; } +Conversation findConversationByDetailId(List conversations, String id) { + for (var conversation in conversations) { + if (conversation.conversationDetailId == id) { + return conversation; + } + } + // Or return `null`. + throw ArgumentError.value(id, "id", "No element with that id"); +} + + // A method that retrieves all the dogs from the dogs table. Future> getConversations() async { final db = await getDatabaseConnection(); @@ -152,12 +215,38 @@ Future> getConversations() async { return List.generate(maps.length, (i) { return Conversation( - id: maps[i]['id'], - userId: maps[i]['user_id'], - conversationDetailId: maps[i]['conversation_detail_id'], - symmetricKey: maps[i]['symmetric_key'], - admin: maps[i]['admin'] == 1, - name: maps[i]['name'], + id: maps[i]['id'], + userId: maps[i]['user_id'], + conversationDetailId: maps[i]['conversation_detail_id'], + symmetricKey: maps[i]['symmetric_key'], + admin: maps[i]['admin'] == 1, + name: maps[i]['name'], + status: ConversationStatus.values[maps[i]['status']], ); }); } + + +Future getConversationById(String id) async { + final db = await getDatabaseConnection(); + + final List> maps = await db.query( + 'conversations', + where: 'id = ?', + whereArgs: [id], + ); + + if (maps.length != 1) { + throw ArgumentError('Invalid user id'); + } + + return Conversation( + id: maps[0]['id'], + userId: maps[0]['user_id'], + conversationDetailId: maps[0]['conversation_detail_id'], + symmetricKey: maps[0]['symmetric_key'], + admin: maps[0]['admin'] == 1, + name: maps[0]['name'], + status: ConversationStatus.values[maps[0]['status']], + ); +} diff --git a/mobile/lib/models/friends.dart b/mobile/lib/models/friends.dart index d387e11..86d1537 100644 --- a/mobile/lib/models/friends.dart +++ b/mobile/lib/models/friends.dart @@ -1,5 +1,7 @@ import 'dart:convert'; +import 'dart:typed_data'; import "package:pointycastle/export.dart"; +import '../utils/encryption/aes_helper.dart'; import '/utils/encryption/crypto_utils.dart'; import '/utils/storage/database.dart'; @@ -34,23 +36,33 @@ class Friend{ }); factory Friend.fromJson(Map json, RSAPrivateKey privKey) { - var friendIdDecrypted = CryptoUtils.rsaDecrypt( + Uint8List friendIdDecrypted = CryptoUtils.rsaDecrypt( base64.decode(json['friend_id']), privKey, ); - var friendSymmetricKeyDecrypted = CryptoUtils.rsaDecrypt( + Uint8List friendUsername = CryptoUtils.rsaDecrypt( + base64.decode(json['friend_username']), + privKey, + ); + + Uint8List friendSymmetricKeyDecrypted = CryptoUtils.rsaDecrypt( base64.decode(json['symmetric_key']), privKey, ); + String asymmetricPublicKey = AesHelper.aesDecrypt( + friendSymmetricKeyDecrypted, + base64.decode(json['asymmetric_public_key']) + ); + return Friend( id: json['id'], userId: json['user_id'], - username: '', + username: String.fromCharCodes(friendUsername), friendId: String.fromCharCodes(friendIdDecrypted), friendSymmetricKey: base64.encode(friendSymmetricKeyDecrypted), - asymmetricPublicKey: '', + asymmetricPublicKey: asymmetricPublicKey, acceptedAt: json['accepted_at'], ); } @@ -101,27 +113,25 @@ Future> getFriends() async { } Future getFriendByFriendId(String userId) async { - final db = await getDatabaseConnection(); - - List whereArguments = [userId]; + final db = await getDatabaseConnection(); - final List> maps = await db.query( - 'friends', - where: 'friend_id = ?', - whereArgs: whereArguments, - ); + final List> maps = await db.query( + 'friends', + where: 'friend_id = ?', + whereArgs: [userId], + ); - if (maps.length != 1) { - throw ArgumentError('Invalid user id'); - } + if (maps.length != 1) { + throw ArgumentError('Invalid user id'); + } - return Friend( - id: maps[0]['id'], - userId: maps[0]['user_id'], - friendId: maps[0]['friend_id'], - friendSymmetricKey: maps[0]['symmetric_key'], - asymmetricPublicKey: maps[0]['asymmetric_public_key'], - acceptedAt: maps[0]['accepted_at'], - username: maps[0]['username'], - ); + return Friend( + id: maps[0]['id'], + userId: maps[0]['user_id'], + friendId: maps[0]['friend_id'], + friendSymmetricKey: maps[0]['symmetric_key'], + asymmetricPublicKey: maps[0]['asymmetric_public_key'], + acceptedAt: maps[0]['accepted_at'], + username: maps[0]['username'], + ); } diff --git a/mobile/lib/models/my_profile.dart b/mobile/lib/models/my_profile.dart index ccd0eae..0c0207f 100644 --- a/mobile/lib/models/my_profile.dart +++ b/mobile/lib/models/my_profile.dart @@ -7,6 +7,7 @@ import 'package:shared_preferences/shared_preferences.dart'; class MyProfile { String id; String username; + String? friendId; RSAPrivateKey? privateKey; RSAPublicKey? publicKey; DateTime? loggedInAt; @@ -14,6 +15,7 @@ class MyProfile { MyProfile({ required this.id, required this.username, + this.friendId, this.privateKey, this.publicKey, this.loggedInAt, @@ -25,11 +27,14 @@ class MyProfile { loggedInAt = DateTime.parse(json['logged_in_at']); } + RSAPrivateKey privateKey = CryptoUtils.rsaPrivateKeyFromPem(json['asymmetric_private_key']); + RSAPublicKey publicKey = CryptoUtils.rsaPublicKeyFromPem(json['asymmetric_public_key']); + return MyProfile( id: json['user_id'], username: json['username'], - privateKey: CryptoUtils.rsaPrivateKeyFromPem(json['asymmetric_private_key']), - publicKey: CryptoUtils.rsaPublicKeyFromPem(json['asymmetric_public_key']), + privateKey: privateKey, + publicKey: publicKey, loggedInAt: loggedInAt, ); } @@ -95,7 +100,7 @@ class MyProfile { ); } - Future getPrivateKey() async { + static Future getPrivateKey() async { MyProfile profile = await MyProfile.getProfile(); if (profile.privateKey == null) { throw Exception('Could not get privateKey'); diff --git a/mobile/lib/utils/storage/conversations.dart b/mobile/lib/utils/storage/conversations.dart index fa4564e..7fd199a 100644 --- a/mobile/lib/utils/storage/conversations.dart +++ b/mobile/lib/utils/storage/conversations.dart @@ -3,97 +3,117 @@ import 'package:http/http.dart' as http; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:pointycastle/export.dart'; import 'package:sqflite/sqflite.dart'; +import '/models/my_profile.dart'; import '/models/conversations.dart'; import '/models/conversation_users.dart'; import '/utils/storage/database.dart'; import '/utils/storage/session_cookie.dart'; -import '/utils/storage/encryption_keys.dart'; import '/utils/encryption/aes_helper.dart'; +// TODO: Refactor this function Future updateConversations() async { - RSAPrivateKey privKey = await getPrivateKey(); - - try { - var resp = await http.get( - Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), - headers: { - 'cookie': await getSessionCookie(), - } - ); + RSAPrivateKey privKey = await MyProfile.getPrivateKey(); - if (resp.statusCode != 200) { - throw Exception(resp.body); + try { + var resp = await http.get( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), + headers: { + 'cookie': await getSessionCookie(), } + ); - List conversations = []; - List conversationsDetailIds = []; - - List conversationsJson = jsonDecode(resp.body); + if (resp.statusCode != 200) { + throw Exception(resp.body); + } - for (var i = 0; i < conversationsJson.length; i++) { - Conversation conversation = Conversation.fromJson( - conversationsJson[i] as Map, - privKey, - ); - conversations.add(conversation); - conversationsDetailIds.add(conversation.conversationDetailId); - } + List conversations = []; + List conversationsDetailIds = []; - Map params = {}; - params['conversation_detail_ids'] = conversationsDetailIds.join(','); - var uri = Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversation_details'); - uri = uri.replace(queryParameters: params); + List conversationsJson = jsonDecode(resp.body); - resp = await http.get( - uri, - headers: { - 'cookie': await getSessionCookie(), - } + for (var i = 0; i < conversationsJson.length; i++) { + Conversation conversation = Conversation.fromJson( + conversationsJson[i] as Map, + privKey, ); + conversations.add(conversation); + conversationsDetailIds.add(conversation.conversationDetailId); + } - if (resp.statusCode != 200) { - throw Exception(resp.body); + Map params = {}; + params['conversation_detail_ids'] = conversationsDetailIds.join(','); + var uri = Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversation_details'); + uri = uri.replace(queryParameters: params); + + resp = await http.get( + uri, + headers: { + 'cookie': await getSessionCookie(), } + ); - final db = await getDatabaseConnection(); + if (resp.statusCode != 200) { + throw Exception(resp.body); + } - List conversationsDetailsJson = jsonDecode(resp.body); - for (var i = 0; i < conversationsDetailsJson.length; i++) { - var conversationDetailJson = conversationsDetailsJson[i] as Map; - var conversation = findConversationByDetailId(conversations, conversationDetailJson['id']); + final db = await getDatabaseConnection(); - conversation.name = AesHelper.aesDecrypt( - base64.decode(conversation.symmetricKey), - base64.decode(conversationDetailJson['name']), - ); + List conversationsDetailsJson = jsonDecode(resp.body); + for (var i = 0; i < conversationsDetailsJson.length; i++) { + var conversationDetailJson = conversationsDetailsJson[i] as Map; + var conversation = findConversationByDetailId(conversations, conversationDetailJson['id']); - await db.insert( - 'conversations', - conversation.toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, - ); + conversation.name = AesHelper.aesDecrypt( + base64.decode(conversation.symmetricKey), + base64.decode(conversationDetailJson['name']), + ); - List usersData = json.decode( - AesHelper.aesDecrypt( - base64.decode(conversation.symmetricKey), - base64.decode(conversationDetailJson['users']), - ) + await db.insert( + 'conversations', + conversation.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + + List usersData = json.decode( + AesHelper.aesDecrypt( + base64.decode(conversation.symmetricKey), + base64.decode(conversationDetailJson['users']), + ) + ); + + for (var i = 0; i < usersData.length; i++) { + ConversationUser conversationUser = ConversationUser.fromJson( + usersData[i] as Map, + conversation.id, ); - for (var i = 0; i < usersData.length; i++) { - ConversationUser conversationUser = ConversationUser.fromJson( - usersData[i] as Map, - conversation.id, - ); - - await db.insert( - 'conversation_users', - conversationUser.toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, - ); - } + await db.insert( + 'conversation_users', + conversationUser.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); } - } catch (SocketException) { - return; } + } catch (SocketException) { + return; + } +} + +Future uploadConversation(Conversation conversation) async { + String sessionCookie = await getSessionCookie(); + + Map conversationJson = await conversation.toJson(); + + print(conversationJson); + + // var x = await http.post( + // Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), + // headers: { + // 'Content-Type': 'application/json; charset=UTF-8', + // 'cookie': sessionCookie, + // }, + // body: jsonEncode(conversationJson), + // ); + + // print(x.statusCode); } diff --git a/mobile/lib/utils/storage/database.dart b/mobile/lib/utils/storage/database.dart index a760960..d2aa0f3 100644 --- a/mobile/lib/utils/storage/database.dart +++ b/mobile/lib/utils/storage/database.dart @@ -39,6 +39,7 @@ Future getDatabaseConnection() async { symmetric_key TEXT, admin INTEGER, name TEXT, + status INTEGER ); '''); @@ -46,6 +47,7 @@ Future getDatabaseConnection() async { ''' CREATE TABLE IF NOT EXISTS conversation_users( id TEXT PRIMARY KEY, + user_id TEXT, conversation_id TEXT, username TEXT, data TEXT, @@ -72,7 +74,7 @@ Future getDatabaseConnection() async { }, // Set the version. This executes the onCreate function and provides a // path to perform database upgrades and downgrades. - version: 1, + version: 2, ); return database; diff --git a/mobile/lib/utils/storage/encryption_keys.dart b/mobile/lib/utils/storage/encryption_keys.dart deleted file mode 100644 index edc2f5c..0000000 --- a/mobile/lib/utils/storage/encryption_keys.dart +++ /dev/null @@ -1,27 +0,0 @@ -import 'package:shared_preferences/shared_preferences.dart'; -import "package:pointycastle/export.dart"; -import '/utils/encryption/crypto_utils.dart'; - -const rsaPrivateKeyName = 'rsaPrivateKey'; - -void setPrivateKey(RSAPrivateKey key) async { - String keyPem = CryptoUtils.encodeRSAPrivateKeyToPem(key); - - final prefs = await SharedPreferences.getInstance(); - prefs.setString(rsaPrivateKeyName, keyPem); -} - -void unsetPrivateKey() async { - final prefs = await SharedPreferences.getInstance(); - await prefs.remove(rsaPrivateKeyName); -} - -Future getPrivateKey() async { - final prefs = await SharedPreferences.getInstance(); - String? keyPem = prefs.getString(rsaPrivateKeyName); - if (keyPem == null) { - throw Exception('No RSA private key set'); - } - - return CryptoUtils.rsaPrivateKeyFromPem(keyPem); -} diff --git a/mobile/lib/utils/storage/friends.dart b/mobile/lib/utils/storage/friends.dart index f3347cb..4da930c 100644 --- a/mobile/lib/utils/storage/friends.dart +++ b/mobile/lib/utils/storage/friends.dart @@ -1,16 +1,17 @@ import 'dart:convert'; + +import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:http/http.dart' as http; import 'package:pointycastle/export.dart'; import 'package:sqflite/sqflite.dart'; -import 'package:flutter_dotenv/flutter_dotenv.dart'; + import '/models/friends.dart'; +import '/models/my_profile.dart'; import '/utils/storage/database.dart'; -import '/utils/storage/encryption_keys.dart'; import '/utils/storage/session_cookie.dart'; -import '/utils/encryption/aes_helper.dart'; Future updateFriends() async { - RSAPrivateKey privKey = await getPrivateKey(); + RSAPrivateKey privKey = await MyProfile.getPrivateKey(); try { var resp = await http.get( @@ -24,59 +25,24 @@ Future updateFriends() async { throw Exception(resp.body); } - List friends = []; - List friendIds = []; + final db = await getDatabaseConnection(); List friendsRequestJson = jsonDecode(resp.body); for (var i = 0; i < friendsRequestJson.length; i++) { - friends.add( - Friend.fromJson( - friendsRequestJson[i] as Map, - privKey, - ) - ); - - friendIds.add(friends[i].friendId); - } - - Map params = {}; - params['friend_ids'] = friendIds.join(','); - var uri = Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friends'); - uri = uri.replace(queryParameters: params); - - resp = await http.get( - uri, - headers: { - 'cookie': await getSessionCookie(), - } - ); - - if (resp.statusCode != 200) { - throw Exception(resp.body); - } - - final db = await getDatabaseConnection(); - - List friendsJson = jsonDecode(resp.body); - for (var i = 0; i < friendsJson.length; i++) { - var friendJson = friendsJson[i] as Map; - var friend = findFriendByFriendId(friends, friendJson['id']); - - friend.username = AesHelper.aesDecrypt( - base64.decode(friend.friendSymmetricKey), - base64.decode(friendJson['username']), + Friend friend = Friend.fromJson( + friendsRequestJson[i] as Map, + privKey, ); - friend.asymmetricPublicKey = friendJson['asymmetric_public_key']; - await db.insert( - 'friends', - friend.toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, + 'friends', + friend.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, ); } + } catch (SocketException) { return; } diff --git a/mobile/lib/utils/storage/messages.dart b/mobile/lib/utils/storage/messages.dart index ea9457f..bc524b3 100644 --- a/mobile/lib/utils/storage/messages.dart +++ b/mobile/lib/utils/storage/messages.dart @@ -1,23 +1,19 @@ import 'dart:convert'; +import 'package:Envelope/models/my_profile.dart'; import 'package:uuid/uuid.dart'; import 'package:Envelope/models/conversation_users.dart'; -import 'package:intl/intl.dart'; import 'package:http/http.dart' as http; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:pointycastle/export.dart'; import 'package:sqflite/sqflite.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '/utils/storage/session_cookie.dart'; -import '/utils/storage/encryption_keys.dart'; import '/utils/storage/database.dart'; import '/models/conversations.dart'; import '/models/messages.dart'; -Future updateMessageThread(Conversation conversation, {RSAPrivateKey? privKey}) async { - privKey ??= await getPrivateKey(); - final preferences = await SharedPreferences.getInstance(); - String username = preferences.getString('username')!; - ConversationUser currentUser = await getConversationUserByUsername(conversation, username); +Future updateMessageThread(Conversation conversation, {MyProfile? profile}) async { + profile ??= await MyProfile.getProfile(); + ConversationUser currentUser = await getConversationUser(conversation, profile.id); var resp = await http.get( Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/messages/${currentUser.associationKey}'), @@ -37,10 +33,10 @@ Future updateMessageThread(Conversation conversation, {RSAPrivateKey? priv for (var i = 0; i < messageThreadJson.length; i++) { Message message = Message.fromJson( messageThreadJson[i] as Map, - privKey, + profile.privateKey!, ); - ConversationUser messageUser = await getConversationUserById(conversation, message.senderId); + ConversationUser messageUser = await getConversationUser(conversation, message.senderId); message.senderUsername = messageUser.username; await db.insert( @@ -52,17 +48,17 @@ Future updateMessageThread(Conversation conversation, {RSAPrivateKey? priv } Future updateMessageThreads({List? conversations}) async { - try { - RSAPrivateKey privKey = await getPrivateKey(); + // try { + MyProfile profile = await MyProfile.getProfile(); conversations ??= await getConversations(); for (var i = 0; i < conversations.length; i++) { - await updateMessageThread(conversations[i], privKey: privKey); + await updateMessageThread(conversations[i], profile: profile); } - } catch(SocketException) { - return; - } + // } catch(SocketException) { + // return; + // } } Future sendMessage(Conversation conversation, String data) async { @@ -76,7 +72,7 @@ Future sendMessage(Conversation conversation, String data) async { var uuid = const Uuid(); final String messageDataId = uuid.v4(); - ConversationUser currentUser = await getConversationUserByUsername(conversation, username); + ConversationUser currentUser = await getConversationUser(conversation, username); Message message = Message( id: messageDataId, diff --git a/mobile/lib/views/main/conversation_create_add_users.dart b/mobile/lib/views/main/conversation_create_add_users.dart index 29ed1ab..7880dc8 100644 --- a/mobile/lib/views/main/conversation_create_add_users.dart +++ b/mobile/lib/views/main/conversation_create_add_users.dart @@ -1,9 +1,9 @@ import 'package:Envelope/models/conversations.dart'; +import 'package:Envelope/utils/storage/conversations.dart'; import 'package:Envelope/views/main/conversation_create_add_users_list.dart'; import 'package:Envelope/views/main/conversation_detail.dart'; import 'package:flutter/material.dart'; import '/models/friends.dart'; -import '/views/main/friend_list_item.dart'; class ConversationAddFriendsList extends StatefulWidget { final List friends; @@ -150,8 +150,12 @@ class _ConversationAddFriendsListState extends State child: FloatingActionButton( onPressed: () async { Conversation conversation = await createConversation(widget.title, friendsSelected); + uploadConversation(conversation); + + setState(() { + friendsSelected = []; + }); - friendsSelected = []; Navigator.of(context).popUntil((route) => route.isFirst); Navigator.push(context, MaterialPageRoute(builder: (context){ return ConversationDetail( diff --git a/mobile/lib/views/main/conversation_detail.dart b/mobile/lib/views/main/conversation_detail.dart index 440c000..02bb964 100644 --- a/mobile/lib/views/main/conversation_detail.dart +++ b/mobile/lib/views/main/conversation_detail.dart @@ -1,6 +1,6 @@ +import 'package:Envelope/models/my_profile.dart'; import 'package:Envelope/views/main/conversation_settings.dart'; import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import '/models/conversations.dart'; import '/models/messages.dart'; import '/utils/storage/messages.dart'; @@ -38,7 +38,7 @@ class ConversationDetail extends StatefulWidget{ class _ConversationDetailState extends State { List messages = []; - String username = ''; + MyProfile profile = MyProfile(id: '', username: ''); TextEditingController msgController = TextEditingController(); @@ -49,14 +49,13 @@ class _ConversationDetailState extends State { } Future fetchMessages() async { - final preferences = await SharedPreferences.getInstance(); - username = preferences.getString('username')!; + profile = await MyProfile.getProfile(); messages = await getMessagesForThread(widget.conversation); setState(() {}); } Widget usernameOrFailedToSend(int index) { - if (messages[index].senderUsername != username) { + if (messages[index].senderUsername != profile.username) { return Text( messages[index].senderUsername, style: TextStyle( @@ -152,12 +151,12 @@ class _ConversationDetailState extends State { padding: const EdgeInsets.only(left: 14,right: 14,top: 0,bottom: 0), child: Align( alignment: ( - messages[index].senderUsername == username ? + messages[index].senderUsername == profile.username ? Alignment.topRight : Alignment.topLeft ), child: Column( - crossAxisAlignment: messages[index].senderUsername == username ? + crossAxisAlignment: messages[index].senderUsername == profile.username ? CrossAxisAlignment.end : CrossAxisAlignment.start, children: [ @@ -165,7 +164,7 @@ class _ConversationDetailState extends State { decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: ( - messages[index].senderUsername == username ? + messages[index].senderUsername == profile.username ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.tertiary ), @@ -175,7 +174,7 @@ class _ConversationDetailState extends State { messages[index].data, style: TextStyle( fontSize: 15, - color: messages[index].senderUsername == username ? + color: messages[index].senderUsername == profile.username ? Theme.of(context).colorScheme.onPrimary : Theme.of(context).colorScheme.onTertiary, ) @@ -183,7 +182,7 @@ class _ConversationDetailState extends State { ), const SizedBox(height: 1.5), Row( - mainAxisAlignment: messages[index].senderUsername == username ? + mainAxisAlignment: messages[index].senderUsername == profile.username ? MainAxisAlignment.end : MainAxisAlignment.start, children: [ @@ -193,14 +192,14 @@ class _ConversationDetailState extends State { ), const SizedBox(height: 1.5), Row( - mainAxisAlignment: messages[index].senderUsername == username ? + mainAxisAlignment: messages[index].senderUsername == profile.username ? MainAxisAlignment.end : MainAxisAlignment.start, children: [ const SizedBox(width: 10), Text( convertToAgo(messages[index].createdAt), - textAlign: messages[index].senderUsername == username ? + textAlign: messages[index].senderUsername == profile.username ? TextAlign.left : TextAlign.right, style: TextStyle( diff --git a/mobile/lib/views/main/conversation_list.dart b/mobile/lib/views/main/conversation_list.dart index b827ea6..7de543c 100644 --- a/mobile/lib/views/main/conversation_list.dart +++ b/mobile/lib/views/main/conversation_list.dart @@ -35,11 +35,11 @@ class _ConversationListState extends State { if(query.isNotEmpty) { List dummyListData = []; - dummySearchList.forEach((item) { + for (Conversation item in dummySearchList) { if (item.name.toLowerCase().contains(query)) { dummyListData.add(item); } - }); + } setState(() { conversations.clear(); conversations.addAll(dummyListData); @@ -135,7 +135,9 @@ class _ConversationListState extends State { ); } - onGoBack(dynamic value) { + onGoBack(dynamic value) async { + conversations = await getConversations(); + friends = await getFriends(); setState(() {}); } } diff --git a/mobile/lib/views/main/conversation_list_item.dart b/mobile/lib/views/main/conversation_list_item.dart index 885400f..b26c0fc 100644 --- a/mobile/lib/views/main/conversation_list_item.dart +++ b/mobile/lib/views/main/conversation_list_item.dart @@ -15,27 +15,37 @@ class ConversationListItem extends StatefulWidget{ } class _ConversationListItemState extends State { + late Conversation conversation; + bool loaded = false; + + @override + void initState() { + super.initState(); + conversation = widget.conversation; + loaded = true; + setState(() {}); + } @override Widget build(BuildContext context) { return GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { - Navigator.push(context, MaterialPageRoute(builder: (context){ + loaded ? Navigator.push(context, MaterialPageRoute(builder: (context){ return ConversationDetail( - conversation: widget.conversation, + conversation: conversation, ); - })); + })).then(onGoBack) : null; }, child: Container( padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), - child: Row( + child: !loaded ? null : Row( children: [ Expanded( child: Row( children: [ CustomCircleAvatar( - initials: widget.conversation.name[0].toUpperCase(), + initials: conversation.name[0].toUpperCase(), imagePath: null, ), const SizedBox(width: 16), @@ -48,7 +58,7 @@ class _ConversationListItemState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - widget.conversation.name, + conversation.name, style: const TextStyle(fontSize: 16) ), //Text(widget.messageText,style: TextStyle(fontSize: 13,color: Colors.grey.shade600, fontWeight: widget.isMessageRead?FontWeight.bold:FontWeight.normal),), @@ -65,4 +75,9 @@ class _ConversationListItemState extends State { ), ); } + + onGoBack(dynamic value) async { + conversation = await getConversationById(widget.conversation.id); + setState(() {}); + } } diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index 31a1a36..cb077d4 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:http/http.dart' as http; import 'package:flutter_dotenv/flutter_dotenv.dart'; import '/views/main/conversation_list.dart'; @@ -51,6 +50,7 @@ class _HomeState extends State { if (!await checkLogin()) { return; } + await updateFriends(); await updateConversations(); await updateMessageThreads(); diff --git a/mobile/lib/views/main/profile.dart b/mobile/lib/views/main/profile.dart index f064ef3..4009961 100644 --- a/mobile/lib/views/main/profile.dart +++ b/mobile/lib/views/main/profile.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:qr_flutter/qr_flutter.dart'; import '/utils/storage/database.dart'; import '/models/my_profile.dart'; @@ -90,6 +91,7 @@ class _ProfileState extends State { } Widget logout() { + bool isTesting = dotenv.env["ENVIRONMENT"] == 'development'; return Align( alignment: Alignment.centerLeft, child: Column( @@ -110,6 +112,19 @@ class _ProfileState extends State { Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); } ), + isTesting ? TextButton.icon( + label: const Text( + 'Delete Database', + style: TextStyle(fontSize: 16) + ), + icon: const Icon(Icons.delete_forever), + style: const ButtonStyle( + alignment: Alignment.centerLeft, + ), + onPressed: () { + deleteDb(); + } + ) : const SizedBox.shrink(), ], ), ); -- 2.17.1 From 9502692958d62b3149546f7fc2518dab818ad8b8 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Tue, 19 Jul 2022 20:33:49 +0930 Subject: [PATCH 15/24] Seperate views into subdirectories --- mobile/lib/models/conversations.dart | 254 +++++++++--------- mobile/lib/utils/storage/messages.dart | 116 ++++---- .../create_add_users.dart} | 131 ++++----- .../create_add_users_list.dart} | 0 .../detail.dart} | 93 +++---- .../edit_details.dart} | 5 +- .../list.dart} | 109 ++++---- .../list_item.dart} | 23 +- .../settings.dart} | 205 +++++++------- .../settings_user_list_item.dart} | 7 +- .../{friend_list.dart => friend/list.dart} | 105 ++++---- .../list_item.dart} | 0 mobile/lib/views/main/home.dart | 141 +++++----- .../lib/views/main/{ => profile}/profile.dart | 0 14 files changed, 601 insertions(+), 588 deletions(-) rename mobile/lib/views/main/{conversation_create_add_users.dart => conversation/create_add_users.dart} (95%) rename mobile/lib/views/main/{conversation_create_add_users_list.dart => conversation/create_add_users_list.dart} (100%) rename mobile/lib/views/main/{conversation_detail.dart => conversation/detail.dart} (99%) rename mobile/lib/views/main/{conversation_edit_details.dart => conversation/edit_details.dart} (98%) rename mobile/lib/views/main/{conversation_list.dart => conversation/list.dart} (97%) rename mobile/lib/views/main/{conversation_list_item.dart => conversation/list_item.dart} (95%) rename mobile/lib/views/main/{conversation_settings.dart => conversation/settings.dart} (97%) rename mobile/lib/views/main/{conversation_settings_user_list_item.dart => conversation/settings_user_list_item.dart} (95%) rename mobile/lib/views/main/{friend_list.dart => friend/list.dart} (99%) rename mobile/lib/views/main/{friend_list_item.dart => friend/list_item.dart} (100%) rename mobile/lib/views/main/{ => profile}/profile.dart (100%) diff --git a/mobile/lib/models/conversations.dart b/mobile/lib/models/conversations.dart index ed06387..3494e48 100644 --- a/mobile/lib/models/conversations.dart +++ b/mobile/lib/models/conversations.dart @@ -1,22 +1,131 @@ import 'dart:convert'; import 'dart:typed_data'; -import 'package:Envelope/models/conversation_users.dart'; -import 'package:Envelope/models/friends.dart'; -import 'package:Envelope/models/my_profile.dart'; + import 'package:pointycastle/export.dart'; import 'package:sqflite/sqflite.dart'; import 'package:uuid/uuid.dart'; -import '/utils/encryption/crypto_utils.dart'; + +import '/models/conversation_users.dart'; +import '/models/friends.dart'; +import '/models/my_profile.dart'; import '/utils/encryption/aes_helper.dart'; +import '/utils/encryption/crypto_utils.dart'; import '/utils/storage/database.dart'; import '/utils/strings.dart'; -enum ConversationStatus { - complete, - pending, - error, +Future createConversation(String title, List friends) async { + final db = await getDatabaseConnection(); + + MyProfile profile = await MyProfile.getProfile(); + + var uuid = const Uuid(); + final String conversationId = uuid.v4(); + + Uint8List symmetricKey = AesHelper.deriveKey(generateRandomString(32)); + + String associationKey = generateRandomString(32); + + Conversation conversation = Conversation( + id: conversationId, + userId: profile.id, + conversationDetailId: '', + symmetricKey: base64.encode(symmetricKey), + admin: true, + name: title, + status: ConversationStatus.pending, + ); + + await db.insert( + 'conversations', + conversation.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + + await db.insert( + 'conversation_users', + ConversationUser( + id: uuid.v4(), + userId: profile.id, + conversationId: conversationId, + username: profile.username, + associationKey: associationKey, + admin: true, + ).toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + + for (Friend friend in friends) { + await db.insert( + 'conversation_users', + ConversationUser( + id: uuid.v4(), + userId: friend.friendId, + conversationId: conversationId, + username: friend.username, + associationKey: associationKey, + admin: false, + ).toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + return conversation; +} + +Conversation findConversationByDetailId(List conversations, String id) { + for (var conversation in conversations) { + if (conversation.conversationDetailId == id) { + return conversation; + } + } + // Or return `null`. + throw ArgumentError.value(id, "id", "No element with that id"); +} + +Future getConversationById(String id) async { + final db = await getDatabaseConnection(); + + final List> maps = await db.query( + 'conversations', + where: 'id = ?', + whereArgs: [id], + ); + + if (maps.length != 1) { + throw ArgumentError('Invalid user id'); + } + + return Conversation( + id: maps[0]['id'], + userId: maps[0]['user_id'], + conversationDetailId: maps[0]['conversation_detail_id'], + symmetricKey: maps[0]['symmetric_key'], + admin: maps[0]['admin'] == 1, + name: maps[0]['name'], + status: ConversationStatus.values[maps[0]['status']], + ); } +// A method that retrieves all the dogs from the dogs table. +Future> getConversations() async { + final db = await getDatabaseConnection(); + + final List> maps = await db.query('conversations'); + + return List.generate(maps.length, (i) { + return Conversation( + id: maps[i]['id'], + userId: maps[i]['user_id'], + conversationDetailId: maps[i]['conversation_detail_id'], + symmetricKey: maps[i]['symmetric_key'], + admin: maps[i]['admin'] == 1, + name: maps[i]['name'], + status: ConversationStatus.values[maps[i]['status']], + ); + }); +} + + class Conversation { String id; String userId; @@ -113,17 +222,6 @@ class Conversation { }; } - @override - String toString() { - return ''' - - - id: $id - userId: $userId - name: $name - admin: $admin'''; - } - Map toMap() { return { 'id': id, @@ -135,118 +233,22 @@ class Conversation { 'status': status.index, }; } -} - -Future createConversation(String title, List friends) async { - final db = await getDatabaseConnection(); - - MyProfile profile = await MyProfile.getProfile(); - - var uuid = const Uuid(); - final String conversationId = uuid.v4(); - - Uint8List symmetricKey = AesHelper.deriveKey(generateRandomString(32)); - - String associationKey = generateRandomString(32); - - Conversation conversation = Conversation( - id: conversationId, - userId: profile.id, - conversationDetailId: '', - symmetricKey: base64.encode(symmetricKey), - admin: true, - name: title, - status: ConversationStatus.pending, - ); - - await db.insert( - 'conversations', - conversation.toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, - ); - await db.insert( - 'conversation_users', - ConversationUser( - id: uuid.v4(), - userId: profile.id, - conversationId: conversationId, - username: profile.username, - associationKey: associationKey, - admin: true, - ).toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, - ); - - for (Friend friend in friends) { - await db.insert( - 'conversation_users', - ConversationUser( - id: uuid.v4(), - userId: friend.friendId, - conversationId: conversationId, - username: friend.username, - associationKey: associationKey, - admin: false, - ).toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, - ); - } + @override + String toString() { + return ''' - return conversation; -} -Conversation findConversationByDetailId(List conversations, String id) { - for (var conversation in conversations) { - if (conversation.conversationDetailId == id) { - return conversation; - } + id: $id + userId: $userId + name: $name + admin: $admin'''; } - // Or return `null`. - throw ArgumentError.value(id, "id", "No element with that id"); -} - - -// A method that retrieves all the dogs from the dogs table. -Future> getConversations() async { - final db = await getDatabaseConnection(); - - final List> maps = await db.query('conversations'); - - return List.generate(maps.length, (i) { - return Conversation( - id: maps[i]['id'], - userId: maps[i]['user_id'], - conversationDetailId: maps[i]['conversation_detail_id'], - symmetricKey: maps[i]['symmetric_key'], - admin: maps[i]['admin'] == 1, - name: maps[i]['name'], - status: ConversationStatus.values[maps[i]['status']], - ); - }); } -Future getConversationById(String id) async { - final db = await getDatabaseConnection(); - - final List> maps = await db.query( - 'conversations', - where: 'id = ?', - whereArgs: [id], - ); - - if (maps.length != 1) { - throw ArgumentError('Invalid user id'); - } - - return Conversation( - id: maps[0]['id'], - userId: maps[0]['user_id'], - conversationDetailId: maps[0]['conversation_detail_id'], - symmetricKey: maps[0]['symmetric_key'], - admin: maps[0]['admin'] == 1, - name: maps[0]['name'], - status: ConversationStatus.values[maps[0]['status']], - ); +enum ConversationStatus { + complete, + pending, + error, } diff --git a/mobile/lib/utils/storage/messages.dart b/mobile/lib/utils/storage/messages.dart index bc524b3..4342e43 100644 --- a/mobile/lib/utils/storage/messages.dart +++ b/mobile/lib/utils/storage/messages.dart @@ -1,65 +1,17 @@ import 'dart:convert'; -import 'package:Envelope/models/my_profile.dart'; -import 'package:uuid/uuid.dart'; -import 'package:Envelope/models/conversation_users.dart'; -import 'package:http/http.dart' as http; + import 'package:flutter_dotenv/flutter_dotenv.dart'; -import 'package:sqflite/sqflite.dart'; +import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; -import '/utils/storage/session_cookie.dart'; -import '/utils/storage/database.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:uuid/uuid.dart'; + +import '/models/conversation_users.dart'; import '/models/conversations.dart'; import '/models/messages.dart'; - -Future updateMessageThread(Conversation conversation, {MyProfile? profile}) async { - profile ??= await MyProfile.getProfile(); - ConversationUser currentUser = await getConversationUser(conversation, profile.id); - - var resp = await http.get( - Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/messages/${currentUser.associationKey}'), - headers: { - 'cookie': await getSessionCookie(), - } - ); - - if (resp.statusCode != 200) { - throw Exception(resp.body); - } - - List messageThreadJson = jsonDecode(resp.body); - - final db = await getDatabaseConnection(); - - for (var i = 0; i < messageThreadJson.length; i++) { - Message message = Message.fromJson( - messageThreadJson[i] as Map, - profile.privateKey!, - ); - - ConversationUser messageUser = await getConversationUser(conversation, message.senderId); - message.senderUsername = messageUser.username; - - await db.insert( - 'messages', - message.toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, - ); - } -} - -Future updateMessageThreads({List? conversations}) async { - // try { - MyProfile profile = await MyProfile.getProfile(); - - conversations ??= await getConversations(); - - for (var i = 0; i < conversations.length; i++) { - await updateMessageThread(conversations[i], profile: profile); - } - // } catch(SocketException) { - // return; - // } -} +import '/models/my_profile.dart'; +import '/utils/storage/database.dart'; +import '/utils/storage/session_cookie.dart'; Future sendMessage(Conversation conversation, String data) async { final preferences = await SharedPreferences.getInstance(); @@ -122,3 +74,53 @@ Future sendMessage(Conversation conversation, String data) async { ); }); } + +Future updateMessageThread(Conversation conversation, {MyProfile? profile}) async { + profile ??= await MyProfile.getProfile(); + ConversationUser currentUser = await getConversationUser(conversation, profile.id); + + var resp = await http.get( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/messages/${currentUser.associationKey}'), + headers: { + 'cookie': await getSessionCookie(), + } + ); + + if (resp.statusCode != 200) { + throw Exception(resp.body); + } + + List messageThreadJson = jsonDecode(resp.body); + + final db = await getDatabaseConnection(); + + for (var i = 0; i < messageThreadJson.length; i++) { + Message message = Message.fromJson( + messageThreadJson[i] as Map, + profile.privateKey!, + ); + + ConversationUser messageUser = await getConversationUser(conversation, message.senderId); + message.senderUsername = messageUser.username; + + await db.insert( + 'messages', + message.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } +} + +Future updateMessageThreads({List? conversations}) async { + // try { + MyProfile profile = await MyProfile.getProfile(); + + conversations ??= await getConversations(); + + for (var i = 0; i < conversations.length; i++) { + await updateMessageThread(conversations[i], profile: profile); + } + // } catch(SocketException) { + // return; + // } +} diff --git a/mobile/lib/views/main/conversation_create_add_users.dart b/mobile/lib/views/main/conversation/create_add_users.dart similarity index 95% rename from mobile/lib/views/main/conversation_create_add_users.dart rename to mobile/lib/views/main/conversation/create_add_users.dart index 7880dc8..4e9ed49 100644 --- a/mobile/lib/views/main/conversation_create_add_users.dart +++ b/mobile/lib/views/main/conversation/create_add_users.dart @@ -1,9 +1,10 @@ -import 'package:Envelope/models/conversations.dart'; -import 'package:Envelope/utils/storage/conversations.dart'; -import 'package:Envelope/views/main/conversation_create_add_users_list.dart'; -import 'package:Envelope/views/main/conversation_detail.dart'; import 'package:flutter/material.dart'; + +import '/models/conversations.dart'; import '/models/friends.dart'; +import '/utils/storage/conversations.dart'; +import '/views/main/conversation/create_add_users_list.dart'; +import '/views/main/conversation/detail.dart'; class ConversationAddFriendsList extends StatefulWidget { final List friends; @@ -22,67 +23,6 @@ class _ConversationAddFriendsListState extends State List friends = []; List friendsSelected = []; - @override - void initState() { - super.initState(); - friends.addAll(widget.friends); - setState(() {}); - } - - void filterSearchResults(String query) { - List dummySearchList = []; - dummySearchList.addAll(widget.friends); - - if(query.isNotEmpty) { - List dummyListData = []; - for (Friend friend in dummySearchList) { - if (friend.username.toLowerCase().contains(query)) { - dummyListData.add(friend); - } - } - setState(() { - friends.clear(); - friends.addAll(dummyListData); - }); - return; - } - - setState(() { - friends.clear(); - friends.addAll(widget.friends); - }); - } - - Widget list() { - if (friends.isEmpty) { - return const Center( - child: Text('No Friends'), - ); - } - - return ListView.builder( - itemCount: friends.length, - shrinkWrap: true, - padding: const EdgeInsets.only(top: 16), - physics: const BouncingScrollPhysics(), - itemBuilder: (context, i) { - return ConversationAddFriendItem( - friend: friends[i], - isSelected: (bool value) { - setState(() { - widget.friends[i].selected = value; - if (value) { - friendsSelected.add(friends[i]); - return; - } - friendsSelected.remove(friends[i]); - }); - } - ); - }, - ); - } - @override Widget build(BuildContext context) { return Scaffold( @@ -171,4 +111,65 @@ class _ConversationAddFriendsListState extends State ), ); } + + void filterSearchResults(String query) { + List dummySearchList = []; + dummySearchList.addAll(widget.friends); + + if(query.isNotEmpty) { + List dummyListData = []; + for (Friend friend in dummySearchList) { + if (friend.username.toLowerCase().contains(query)) { + dummyListData.add(friend); + } + } + setState(() { + friends.clear(); + friends.addAll(dummyListData); + }); + return; + } + + setState(() { + friends.clear(); + friends.addAll(widget.friends); + }); + } + + @override + void initState() { + super.initState(); + friends.addAll(widget.friends); + setState(() {}); + } + + Widget list() { + if (friends.isEmpty) { + return const Center( + child: Text('No Friends'), + ); + } + + return ListView.builder( + itemCount: friends.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 16), + physics: const BouncingScrollPhysics(), + itemBuilder: (context, i) { + return ConversationAddFriendItem( + friend: friends[i], + isSelected: (bool value) { + setState(() { + widget.friends[i].selected = value; + if (value) { + friendsSelected.add(friends[i]); + return; + } + friendsSelected.remove(friends[i]); + }); + } + ); + }, + ); + } } diff --git a/mobile/lib/views/main/conversation_create_add_users_list.dart b/mobile/lib/views/main/conversation/create_add_users_list.dart similarity index 100% rename from mobile/lib/views/main/conversation_create_add_users_list.dart rename to mobile/lib/views/main/conversation/create_add_users_list.dart diff --git a/mobile/lib/views/main/conversation_detail.dart b/mobile/lib/views/main/conversation/detail.dart similarity index 99% rename from mobile/lib/views/main/conversation_detail.dart rename to mobile/lib/views/main/conversation/detail.dart index 02bb964..511b538 100644 --- a/mobile/lib/views/main/conversation_detail.dart +++ b/mobile/lib/views/main/conversation/detail.dart @@ -1,9 +1,10 @@ -import 'package:Envelope/models/my_profile.dart'; -import 'package:Envelope/views/main/conversation_settings.dart'; import 'package:flutter/material.dart'; + import '/models/conversations.dart'; import '/models/messages.dart'; +import '/models/my_profile.dart'; import '/utils/storage/messages.dart'; +import '/views/main/conversation/settings.dart'; String convertToAgo(String input){ DateTime time = DateTime.parse(input); @@ -42,50 +43,6 @@ class _ConversationDetailState extends State { TextEditingController msgController = TextEditingController(); - @override - void initState() { - super.initState(); - fetchMessages(); - } - - Future fetchMessages() async { - profile = await MyProfile.getProfile(); - messages = await getMessagesForThread(widget.conversation); - setState(() {}); - } - - Widget usernameOrFailedToSend(int index) { - if (messages[index].senderUsername != profile.username) { - return Text( - messages[index].senderUsername, - style: TextStyle( - fontSize: 12, - color: Colors.grey[300], - ), - ); - } - - if (messages[index].failedToSend) { - return Row( - mainAxisAlignment: MainAxisAlignment.end, - children: const [ - Icon( - Icons.warning_rounded, - color: Colors.red, - size: 20, - ), - Text( - 'Failed to send', - style: TextStyle(color: Colors.red, fontSize: 12), - textAlign: TextAlign.right, - ), - ], - ); - } - - return const SizedBox.shrink(); - } - @override Widget build(BuildContext context) { return Scaffold( @@ -296,4 +253,48 @@ class _ConversationDetailState extends State { ), ); } + + Future fetchMessages() async { + profile = await MyProfile.getProfile(); + messages = await getMessagesForThread(widget.conversation); + setState(() {}); + } + + @override + void initState() { + super.initState(); + fetchMessages(); + } + + Widget usernameOrFailedToSend(int index) { + if (messages[index].senderUsername != profile.username) { + return Text( + messages[index].senderUsername, + style: TextStyle( + fontSize: 12, + color: Colors.grey[300], + ), + ); + } + + if (messages[index].failedToSend) { + return Row( + mainAxisAlignment: MainAxisAlignment.end, + children: const [ + Icon( + Icons.warning_rounded, + color: Colors.red, + size: 20, + ), + Text( + 'Failed to send', + style: TextStyle(color: Colors.red, fontSize: 12), + textAlign: TextAlign.right, + ), + ], + ); + } + + return const SizedBox.shrink(); + } } diff --git a/mobile/lib/views/main/conversation_edit_details.dart b/mobile/lib/views/main/conversation/edit_details.dart similarity index 98% rename from mobile/lib/views/main/conversation_edit_details.dart rename to mobile/lib/views/main/conversation/edit_details.dart index a882913..be48588 100644 --- a/mobile/lib/views/main/conversation_edit_details.dart +++ b/mobile/lib/views/main/conversation/edit_details.dart @@ -1,8 +1,9 @@ import 'package:flutter/material.dart'; + import '/components/custom_circle_avatar.dart'; -import '/views/main/conversation_create_add_users.dart'; -import '/models/friends.dart'; import '/models/conversations.dart'; +import '/models/friends.dart'; +import '/views/main/conversation/create_add_users.dart'; class ConversationEditDetails extends StatefulWidget { final Conversation? conversation; diff --git a/mobile/lib/views/main/conversation_list.dart b/mobile/lib/views/main/conversation/list.dart similarity index 97% rename from mobile/lib/views/main/conversation_list.dart rename to mobile/lib/views/main/conversation/list.dart index 7de543c..8ec0931 100644 --- a/mobile/lib/views/main/conversation_list.dart +++ b/mobile/lib/views/main/conversation/list.dart @@ -1,8 +1,9 @@ import 'package:Envelope/models/friends.dart'; -import 'package:Envelope/views/main/conversation_edit_details.dart'; import 'package:flutter/material.dart'; + import '/models/conversations.dart'; -import '/views/main/conversation_list_item.dart'; +import '/views/main/conversation/edit_details.dart'; +import '/views/main/conversation/list_item.dart'; class ConversationList extends StatefulWidget { final List conversations; @@ -21,58 +22,6 @@ class _ConversationListState extends State { List conversations = []; List friends = []; - @override - void initState() { - super.initState(); - conversations.addAll(widget.conversations); - friends.addAll(widget.friends); - setState(() {}); - } - - void filterSearchResults(String query) { - List dummySearchList = []; - dummySearchList.addAll(widget.conversations); - - if(query.isNotEmpty) { - List dummyListData = []; - for (Conversation item in dummySearchList) { - if (item.name.toLowerCase().contains(query)) { - dummyListData.add(item); - } - } - setState(() { - conversations.clear(); - conversations.addAll(dummyListData); - }); - return; - } - - setState(() { - conversations.clear(); - conversations.addAll(widget.conversations); - }); - } - - Widget list() { - if (conversations.isEmpty) { - return const Center( - child: Text('No Conversations'), - ); - } - - return ListView.builder( - itemCount: conversations.length, - shrinkWrap: true, - padding: const EdgeInsets.only(top: 16), - physics: const NeverScrollableScrollPhysics(), - itemBuilder: (context, i) { - return ConversationListItem( - conversation: conversations[i], - ); - }, - ); - } - @override Widget build(BuildContext context) { return Scaffold( @@ -135,6 +84,58 @@ class _ConversationListState extends State { ); } + void filterSearchResults(String query) { + List dummySearchList = []; + dummySearchList.addAll(widget.conversations); + + if(query.isNotEmpty) { + List dummyListData = []; + for (Conversation item in dummySearchList) { + if (item.name.toLowerCase().contains(query)) { + dummyListData.add(item); + } + } + setState(() { + conversations.clear(); + conversations.addAll(dummyListData); + }); + return; + } + + setState(() { + conversations.clear(); + conversations.addAll(widget.conversations); + }); + } + + @override + void initState() { + super.initState(); + conversations.addAll(widget.conversations); + friends.addAll(widget.friends); + setState(() {}); + } + + Widget list() { + if (conversations.isEmpty) { + return const Center( + child: Text('No Conversations'), + ); + } + + return ListView.builder( + itemCount: conversations.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 16), + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, i) { + return ConversationListItem( + conversation: conversations[i], + ); + }, + ); + } + onGoBack(dynamic value) async { conversations = await getConversations(); friends = await getFriends(); diff --git a/mobile/lib/views/main/conversation_list_item.dart b/mobile/lib/views/main/conversation/list_item.dart similarity index 95% rename from mobile/lib/views/main/conversation_list_item.dart rename to mobile/lib/views/main/conversation/list_item.dart index b26c0fc..45015e9 100644 --- a/mobile/lib/views/main/conversation_list_item.dart +++ b/mobile/lib/views/main/conversation/list_item.dart @@ -1,7 +1,8 @@ -import 'package:Envelope/components/custom_circle_avatar.dart'; -import 'package:Envelope/models/conversations.dart'; import 'package:flutter/material.dart'; -import '/views/main/conversation_detail.dart'; + +import '/components/custom_circle_avatar.dart'; +import '/models/conversations.dart'; +import '/views/main/conversation/detail.dart'; class ConversationListItem extends StatefulWidget{ final Conversation conversation; @@ -18,14 +19,6 @@ class _ConversationListItemState extends State { late Conversation conversation; bool loaded = false; - @override - void initState() { - super.initState(); - conversation = widget.conversation; - loaded = true; - setState(() {}); - } - @override Widget build(BuildContext context) { return GestureDetector( @@ -76,6 +69,14 @@ class _ConversationListItemState extends State { ); } + @override + void initState() { + super.initState(); + conversation = widget.conversation; + loaded = true; + setState(() {}); + } + onGoBack(dynamic value) async { conversation = await getConversationById(widget.conversation.id); setState(() {}); diff --git a/mobile/lib/views/main/conversation_settings.dart b/mobile/lib/views/main/conversation/settings.dart similarity index 97% rename from mobile/lib/views/main/conversation_settings.dart rename to mobile/lib/views/main/conversation/settings.dart index caf917d..85dbc7e 100644 --- a/mobile/lib/views/main/conversation_settings.dart +++ b/mobile/lib/views/main/conversation/settings.dart @@ -1,9 +1,10 @@ -import 'package:Envelope/models/conversation_users.dart'; -import 'package:Envelope/models/my_profile.dart'; +import 'package:Envelope/components/custom_circle_avatar.dart'; import 'package:flutter/material.dart'; -import '/views/main/conversation_settings_user_list_item.dart'; + +import '/models/conversation_users.dart'; import '/models/conversations.dart'; -import 'package:Envelope/components/custom_circle_avatar.dart'; +import '/models/my_profile.dart'; +import '/views/main/conversation/settings_user_list_item.dart'; class ConversationSettings extends StatefulWidget { final Conversation conversation; @@ -23,16 +24,67 @@ class _ConversationSettingsState extends State { TextEditingController nameController = TextEditingController(); @override - void initState() { - nameController.text = widget.conversation.name; - super.initState(); - getUsers(); - } - - Future getUsers() async { - users = await getConversationUsers(widget.conversation); - profile = await MyProfile.getProfile(); - setState(() {}); + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + elevation: 0, + automaticallyImplyLeading: false, + flexibleSpace: SafeArea( + child: Container( + padding: const EdgeInsets.only(right: 16), + child: Row( + children: [ + IconButton( + onPressed: (){ + Navigator.pop(context); + }, + icon: const Icon(Icons.arrow_back), + ), + const SizedBox(width: 2,), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + widget.conversation.name + " Settings", + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600 + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + body: Padding( + padding: const EdgeInsets.all(15), + child: Column( + children: [ + const SizedBox(height: 30), + conversationName(), + const SizedBox(height: 25), + widget.conversation.admin ? + sectionTitle('Settings') : + const SizedBox.shrink(), + widget.conversation.admin ? + settings() : + const SizedBox.shrink(), + widget.conversation.admin ? + const SizedBox(height: 25) : + const SizedBox.shrink(), + sectionTitle('Members'), + usersList(), + const SizedBox(height: 25), + myAccess(), + ], + ), + ), + ); } Widget conversationName() { @@ -64,6 +116,43 @@ class _ConversationSettingsState extends State { ); } + Future getUsers() async { + users = await getConversationUsers(widget.conversation); + profile = await MyProfile.getProfile(); + setState(() {}); + } + + @override + void initState() { + nameController.text = widget.conversation.name; + super.initState(); + getUsers(); + } + + Widget myAccess() { + return Align( + alignment: Alignment.centerLeft, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + TextButton.icon( + label: const Text( + 'Leave Conversation', + style: TextStyle(fontSize: 16) + ), + icon: const Icon(Icons.exit_to_app), + style: const ButtonStyle( + alignment: Alignment.centerLeft, + ), + onPressed: () { + print('Leave Group'); + } + ), + ], + ), + ); + } + Widget sectionTitle(String title) { return Align( alignment: Alignment.centerLeft, @@ -125,30 +214,6 @@ class _ConversationSettingsState extends State { ); } - Widget myAccess() { - return Align( - alignment: Alignment.centerLeft, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - TextButton.icon( - label: const Text( - 'Leave Conversation', - style: TextStyle(fontSize: 16) - ), - icon: const Icon(Icons.exit_to_app), - style: const ButtonStyle( - alignment: Alignment.centerLeft, - ), - onPressed: () { - print('Leave Group'); - } - ), - ], - ), - ); - } - Widget usersList() { return ListView.builder( itemCount: users.length, @@ -163,69 +228,5 @@ class _ConversationSettingsState extends State { } ); } - - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - elevation: 0, - automaticallyImplyLeading: false, - flexibleSpace: SafeArea( - child: Container( - padding: const EdgeInsets.only(right: 16), - child: Row( - children: [ - IconButton( - onPressed: (){ - Navigator.pop(context); - }, - icon: const Icon(Icons.arrow_back), - ), - const SizedBox(width: 2,), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - widget.conversation.name + " Settings", - style: const TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600 - ), - ), - ], - ), - ), - ], - ), - ), - ), - ), - body: Padding( - padding: const EdgeInsets.all(15), - child: Column( - children: [ - const SizedBox(height: 30), - conversationName(), - const SizedBox(height: 25), - widget.conversation.admin ? - sectionTitle('Settings') : - const SizedBox.shrink(), - widget.conversation.admin ? - settings() : - const SizedBox.shrink(), - widget.conversation.admin ? - const SizedBox(height: 25) : - const SizedBox.shrink(), - sectionTitle('Members'), - usersList(), - const SizedBox(height: 25), - myAccess(), - ], - ), - ), - ); - } } diff --git a/mobile/lib/views/main/conversation_settings_user_list_item.dart b/mobile/lib/views/main/conversation/settings_user_list_item.dart similarity index 95% rename from mobile/lib/views/main/conversation_settings_user_list_item.dart rename to mobile/lib/views/main/conversation/settings_user_list_item.dart index b261aad..7c676a0 100644 --- a/mobile/lib/views/main/conversation_settings_user_list_item.dart +++ b/mobile/lib/views/main/conversation/settings_user_list_item.dart @@ -1,7 +1,8 @@ -import 'package:Envelope/models/my_profile.dart'; import 'package:flutter/material.dart'; -import 'package:Envelope/models/conversation_users.dart'; -import 'package:Envelope/components/custom_circle_avatar.dart'; + +import '/components/custom_circle_avatar.dart'; +import '/models/conversation_users.dart'; +import '/models/my_profile.dart'; class ConversationSettingsUserListItem extends StatefulWidget{ final ConversationUser user; diff --git a/mobile/lib/views/main/friend_list.dart b/mobile/lib/views/main/friend/list.dart similarity index 99% rename from mobile/lib/views/main/friend_list.dart rename to mobile/lib/views/main/friend/list.dart index f1076ef..40b8fd3 100644 --- a/mobile/lib/views/main/friend_list.dart +++ b/mobile/lib/views/main/friend/list.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; + import '/models/friends.dart'; -import '/views/main/friend_list_item.dart'; +import '/views/main/friend/list_item.dart'; class FriendList extends StatefulWidget { final List friends; @@ -17,57 +18,6 @@ class _FriendListState extends State { List friends = []; List friendsDuplicate = []; - @override - void initState() { - super.initState(); - friends.addAll(widget.friends); - setState(() {}); - } - - void filterSearchResults(String query) { - List dummySearchList = []; - dummySearchList.addAll(widget.friends); - - if(query.isNotEmpty) { - List dummyListData = []; - dummySearchList.forEach((item) { - if(item.username.toLowerCase().contains(query)) { - dummyListData.add(item); - } - }); - setState(() { - friends.clear(); - friends.addAll(dummyListData); - }); - return; - } - - setState(() { - friends.clear(); - friends.addAll(widget.friends); - }); - } - - Widget list() { - if (friends.isEmpty) { - return const Center( - child: Text('No Friends'), - ); - } - - return ListView.builder( - itemCount: friends.length, - shrinkWrap: true, - padding: const EdgeInsets.only(top: 16), - physics: const NeverScrollableScrollPhysics(), - itemBuilder: (context, i) { - return FriendListItem( - friend: friends[i], - ); - }, - ); - } - @override Widget build(BuildContext context) { return Scaffold( @@ -134,4 +84,55 @@ class _FriendListState extends State { ), ); } + + void filterSearchResults(String query) { + List dummySearchList = []; + dummySearchList.addAll(widget.friends); + + if(query.isNotEmpty) { + List dummyListData = []; + dummySearchList.forEach((item) { + if(item.username.toLowerCase().contains(query)) { + dummyListData.add(item); + } + }); + setState(() { + friends.clear(); + friends.addAll(dummyListData); + }); + return; + } + + setState(() { + friends.clear(); + friends.addAll(widget.friends); + }); + } + + @override + void initState() { + super.initState(); + friends.addAll(widget.friends); + setState(() {}); + } + + Widget list() { + if (friends.isEmpty) { + return const Center( + child: Text('No Friends'), + ); + } + + return ListView.builder( + itemCount: friends.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 16), + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, i) { + return FriendListItem( + friend: friends[i], + ); + }, + ); + } } diff --git a/mobile/lib/views/main/friend_list_item.dart b/mobile/lib/views/main/friend/list_item.dart similarity index 100% rename from mobile/lib/views/main/friend_list_item.dart rename to mobile/lib/views/main/friend/list_item.dart diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index cb077d4..80f2be5 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -1,16 +1,17 @@ import 'package:flutter/material.dart'; -import 'package:http/http.dart' as http; import 'package:flutter_dotenv/flutter_dotenv.dart'; -import '/views/main/conversation_list.dart'; -import '/views/main/friend_list.dart'; -import '/views/main/profile.dart'; -import '/utils/storage/friends.dart'; -import '/utils/storage/conversations.dart'; -import '/utils/storage/messages.dart'; -import '/utils/storage/session_cookie.dart'; +import 'package:http/http.dart' as http; + import '/models/conversations.dart'; import '/models/friends.dart'; import '/models/my_profile.dart'; +import '/utils/storage/conversations.dart'; +import '/utils/storage/friends.dart'; +import '/utils/storage/messages.dart'; +import '/utils/storage/session_cookie.dart'; +import '/views/main/conversation/list.dart'; +import '/views/main/friend/list.dart'; +import '/views/main/profile/profile.dart'; class Home extends StatefulWidget { const Home({Key? key}) : super(key: key); @@ -41,35 +42,36 @@ class _HomeState extends State { ]; @override - void initState() { - updateData(); - super.initState(); - } - - void updateData() async { - if (!await checkLogin()) { - return; - } - - await updateFriends(); - await updateConversations(); - await updateMessageThreads(); - - conversations = await getConversations(); - friends = await getFriends(); - profile = await MyProfile.getProfile(); - - setState(() { - _widgetOptions = [ - ConversationList( - conversations: conversations, - friends: friends, + Widget build(BuildContext context) { + return WillPopScope( + onWillPop: () async => false, + child: isLoading ? loading() : Scaffold( + body: _widgetOptions.elementAt(_selectedIndex), + bottomNavigationBar: isLoading ? const SizedBox.shrink() : BottomNavigationBar( + currentIndex: _selectedIndex, + onTap: _onItemTapped, + selectedItemColor: Theme.of(context).primaryColor, + unselectedItemColor: Theme.of(context).hintColor, + selectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600), + unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600), + type: BottomNavigationBarType.fixed, + items: const [ + BottomNavigationBarItem( + icon: Icon(Icons.message), + label: "Chats", + ), + BottomNavigationBarItem( + icon: Icon(Icons.group_work), + label: "Friends", + ), + BottomNavigationBarItem( + icon: Icon(Icons.account_box), + label: "Profile", + ), + ], + ), ), - FriendList(friends: friends), - Profile(profile: profile), - ]; - isLoading = false; - }); + ); } Future checkLogin() async { @@ -112,10 +114,10 @@ class _HomeState extends State { return false; } - void _onItemTapped(int index) { - setState(() { - _selectedIndex = index; - }); + @override + void initState() { + updateData(); + super.initState(); } Widget loading() { @@ -140,36 +142,35 @@ class _HomeState extends State { ); } - @override - Widget build(BuildContext context) { - return WillPopScope( - onWillPop: () async => false, - child: isLoading ? loading() : Scaffold( - body: _widgetOptions.elementAt(_selectedIndex), - bottomNavigationBar: isLoading ? const SizedBox.shrink() : BottomNavigationBar( - currentIndex: _selectedIndex, - onTap: _onItemTapped, - selectedItemColor: Theme.of(context).primaryColor, - unselectedItemColor: Theme.of(context).hintColor, - selectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600), - unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600), - type: BottomNavigationBarType.fixed, - items: const [ - BottomNavigationBarItem( - icon: Icon(Icons.message), - label: "Chats", - ), - BottomNavigationBarItem( - icon: Icon(Icons.group_work), - label: "Friends", - ), - BottomNavigationBarItem( - icon: Icon(Icons.account_box), - label: "Profile", - ), - ], - ), + void updateData() async { + if (!await checkLogin()) { + return; + } + + await updateFriends(); + await updateConversations(); + await updateMessageThreads(); + + conversations = await getConversations(); + friends = await getFriends(); + profile = await MyProfile.getProfile(); + + setState(() { + _widgetOptions = [ + ConversationList( + conversations: conversations, + friends: friends, ), - ); + FriendList(friends: friends), + Profile(profile: profile), + ]; + isLoading = false; + }); + } + + void _onItemTapped(int index) { + setState(() { + _selectedIndex = index; + }); } } diff --git a/mobile/lib/views/main/profile.dart b/mobile/lib/views/main/profile/profile.dart similarity index 100% rename from mobile/lib/views/main/profile.dart rename to mobile/lib/views/main/profile/profile.dart -- 2.17.1 From b409ddaac8c0a1646cc55e2dc178b711a3c46168 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Mon, 25 Jul 2022 19:39:27 +0930 Subject: [PATCH 16/24] Fix conversation creation & slight polish on converstation pages --- Backend/Api/Messages/Conversations.go | 1 - Backend/Api/Messages/CreateConversation.go | 11 ++- Backend/Database/ConversationDetails.go | 2 +- Backend/Database/UserConversations.go | 11 +-- mobile/lib/models/conversation_users.dart | 99 +++++++++---------- mobile/lib/models/conversations.dart | 81 ++++++++++----- mobile/lib/utils/storage/conversations.dart | 28 +++--- mobile/lib/utils/storage/database.dart | 7 +- mobile/lib/utils/storage/messages.dart | 14 +-- mobile/lib/utils/time.dart | 19 ++++ .../lib/views/main/conversation/detail.dart | 20 +--- .../views/main/conversation/edit_details.dart | 17 +++- .../views/main/conversation/list_item.dart | 43 +++++++- .../lib/views/main/conversation/settings.dart | 16 ++- .../conversation/settings_user_list_item.dart | 8 +- 15 files changed, 225 insertions(+), 152 deletions(-) create mode 100644 mobile/lib/utils/time.dart diff --git a/Backend/Api/Messages/Conversations.go b/Backend/Api/Messages/Conversations.go index c0beeee..4475790 100644 --- a/Backend/Api/Messages/Conversations.go +++ b/Backend/Api/Messages/Conversations.go @@ -79,5 +79,4 @@ func EncryptedConversationDetailsList(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write(returnJson) - } diff --git a/Backend/Api/Messages/CreateConversation.go b/Backend/Api/Messages/CreateConversation.go index b2dccd9..a806473 100644 --- a/Backend/Api/Messages/CreateConversation.go +++ b/Backend/Api/Messages/CreateConversation.go @@ -2,7 +2,9 @@ package Messages import ( "encoding/json" + "fmt" "net/http" + "github.com/gofrs/uuid" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" @@ -30,9 +32,9 @@ func CreateConversation(w http.ResponseWriter, r *http.Request) { } messageThread = Models.ConversationDetail{ - Base: Models.Base{ - ID: uuid.FromStringOrNil(rawConversationData.ID), - }, + Base: Models.Base{ + ID: uuid.FromStringOrNil(rawConversationData.ID), + }, Name: rawConversationData.Name, Users: rawConversationData.Users, } @@ -43,9 +45,10 @@ func CreateConversation(w http.ResponseWriter, r *http.Request) { return } + fmt.Println(rawConversationData.UserConversations[0]) + err = Database.CreateUserConversations(&rawConversationData.UserConversations) if err != nil { - panic(err) http.Error(w, "Error", http.StatusInternalServerError) return } diff --git a/Backend/Database/ConversationDetails.go b/Backend/Database/ConversationDetails.go index cd1140d..9893022 100644 --- a/Backend/Database/ConversationDetails.go +++ b/Backend/Database/ConversationDetails.go @@ -29,7 +29,7 @@ func GetConversationDetailsByIds(id []string) ([]Models.ConversationDetail, erro err = DB.Preload(clause.Associations). Where("id IN ?", id). - First(&messageThread). + Find(&messageThread). Error return messageThread, err diff --git a/Backend/Database/UserConversations.go b/Backend/Database/UserConversations.go index 3623fda..02fb62d 100644 --- a/Backend/Database/UserConversations.go +++ b/Backend/Database/UserConversations.go @@ -31,9 +31,7 @@ func GetUserConversationsByUserId(id string) ([]Models.UserConversation, error) } func CreateUserConversation(userConversation *Models.UserConversation) error { - var ( - err error - ) + var err error err = DB.Session(&gorm.Session{FullSaveAssociations: true}). Create(userConversation). @@ -43,12 +41,9 @@ func CreateUserConversation(userConversation *Models.UserConversation) error { } func CreateUserConversations(userConversations *[]Models.UserConversation) error { - var ( - err error - ) + var err error - err = DB.Session(&gorm.Session{FullSaveAssociations: true}). - Create(userConversations). + err = DB.Create(userConversations). Error return err diff --git a/mobile/lib/models/conversation_users.dart b/mobile/lib/models/conversation_users.dart index 34e6e40..3417792 100644 --- a/mobile/lib/models/conversation_users.dart +++ b/mobile/lib/models/conversation_users.dart @@ -1,5 +1,52 @@ -import '/utils/storage/database.dart'; import '/models/conversations.dart'; +import '/utils/storage/database.dart'; + +Future getConversationUser(Conversation conversation, String userId) async { + final db = await getDatabaseConnection(); + + final List> maps = await db.query( + 'conversation_users', + where: 'conversation_id = ? AND user_id = ?', + whereArgs: [conversation.id, userId], + ); + + if (maps.length != 1) { + throw ArgumentError('Invalid conversation_id or username'); + } + + return ConversationUser( + id: maps[0]['id'], + userId: maps[0]['user_id'], + conversationId: maps[0]['conversation_id'], + username: maps[0]['username'], + associationKey: maps[0]['association_key'], + admin: maps[0]['admin'] == 1, + ); + +} + +// A method that retrieves all the dogs from the dogs table. +Future> getConversationUsers(Conversation conversation) async { + final db = await getDatabaseConnection(); + + final List> maps = await db.query( + 'conversation_users', + where: 'conversation_id = ?', + whereArgs: [conversation.id], + orderBy: 'admin', + ); + + return List.generate(maps.length, (i) { + return ConversationUser( + id: maps[i]['id'], + userId: maps[i]['user_id'], + conversationId: maps[i]['conversation_id'], + username: maps[i]['username'], + associationKey: maps[i]['association_key'], + admin: maps[i]['admin'] == 1, + ); + }); +} class ConversationUser{ String id; @@ -33,7 +80,7 @@ class ConversationUser{ 'id': id, 'user_id': userId, 'username': username, - 'associationKey': associationKey, + 'association_key': associationKey, 'admin': admin ? 'true' : 'false', }; } @@ -49,51 +96,3 @@ class ConversationUser{ }; } } - -// A method that retrieves all the dogs from the dogs table. -Future> getConversationUsers(Conversation conversation) async { - final db = await getDatabaseConnection(); - - final List> maps = await db.query( - 'conversation_users', - where: 'conversation_id = ?', - whereArgs: [conversation.id], - orderBy: 'admin', - ); - - return List.generate(maps.length, (i) { - return ConversationUser( - id: maps[i]['id'], - userId: maps[i]['user_id'], - conversationId: maps[i]['conversation_id'], - username: maps[i]['username'], - associationKey: maps[i]['association_key'], - admin: maps[i]['admin'] == 1, - ); - }); -} - -Future getConversationUser(Conversation conversation, String userId) async { - final db = await getDatabaseConnection(); - - - final List> maps = await db.query( - 'conversation_users', - where: 'conversation_id = ? AND user_id = ?', - whereArgs: [conversation.id, userId], - ); - - if (maps.length != 1) { - throw ArgumentError('Invalid conversation_id or username'); - } - - return ConversationUser( - id: maps[0]['id'], - userId: maps[0]['user_id'], - conversationId: maps[0]['conversation_id'], - username: maps[0]['username'], - associationKey: maps[0]['association_key'], - admin: maps[0]['admin'] == 1, - ); - -} diff --git a/mobile/lib/models/conversations.dart b/mobile/lib/models/conversations.dart index 3494e48..88adea3 100644 --- a/mobile/lib/models/conversations.dart +++ b/mobile/lib/models/conversations.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'dart:typed_data'; +import 'package:Envelope/models/messages.dart'; import 'package:pointycastle/export.dart'; import 'package:sqflite/sqflite.dart'; import 'package:uuid/uuid.dart'; @@ -20,6 +21,7 @@ Future createConversation(String title, List friends) asyn var uuid = const Uuid(); final String conversationId = uuid.v4(); + final String conversationDetailId = uuid.v4(); Uint8List symmetricKey = AesHelper.deriveKey(generateRandomString(32)); @@ -28,11 +30,12 @@ Future createConversation(String title, List friends) asyn Conversation conversation = Conversation( id: conversationId, userId: profile.id, - conversationDetailId: '', + conversationDetailId: conversationDetailId, symmetricKey: base64.encode(symmetricKey), admin: true, name: title, status: ConversationStatus.pending, + isRead: true, ); await db.insert( @@ -51,7 +54,7 @@ Future createConversation(String title, List friends) asyn associationKey: associationKey, admin: true, ).toMap(), - conflictAlgorithm: ConflictAlgorithm.replace, + conflictAlgorithm: ConflictAlgorithm.fail, ); for (Friend friend in friends) { @@ -103,6 +106,7 @@ Future getConversationById(String id) async { admin: maps[0]['admin'] == 1, name: maps[0]['name'], status: ConversationStatus.values[maps[0]['status']], + isRead: maps[0]['is_read'] == 1, ); } @@ -121,6 +125,7 @@ Future> getConversations() async { admin: maps[i]['admin'] == 1, name: maps[i]['name'], status: ConversationStatus.values[maps[i]['status']], + isRead: maps[i]['is_read'] == 1, ); }); } @@ -134,6 +139,7 @@ class Conversation { bool admin; String name; ConversationStatus status; + bool isRead; Conversation({ required this.id, @@ -143,6 +149,7 @@ class Conversation { required this.admin, required this.name, required this.status, + required this.isRead, }); @@ -170,6 +177,7 @@ class Conversation { admin: admin == 'true', name: 'Unknown', status: ConversationStatus.complete, + isRead: true, ); } @@ -181,41 +189,28 @@ class Conversation { List users = await getConversationUsers(this); List userConversations = []; - for (var x in users) { - print(x.toMap()); - } - for (ConversationUser user in users) { - if (profile.id == user.userId) { - userConversations.add({ - 'id': user.id, - 'user_id': profile.id, - 'conversation_detail_id': AesHelper.aesEncrypt(symKey, Uint8List.fromList(id.codeUnits)), - 'admin': AesHelper.aesEncrypt(symKey, Uint8List.fromList((admin ? 'true' : 'false').codeUnits)), - 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt(symKey, profile.publicKey!)), - }); - - continue; - } - Friend friend = await getFriendByFriendId(user.userId); - RSAPublicKey pubKey = CryptoUtils.rsaPublicKeyFromPem(friend.asymmetricPublicKey); + RSAPublicKey pubKey = profile.publicKey!; + String newId = id; + + if (profile.id != user.userId) { + Friend friend = await getFriendByFriendId(user.userId); + pubKey = CryptoUtils.rsaPublicKeyFromPem(friend.asymmetricPublicKey); + newId = (const Uuid()).v4(); + } userConversations.add({ - 'id': user.id, - 'user_id': friend.userId, - 'conversation_detail_id': AesHelper.aesEncrypt(symKey, Uint8List.fromList(id.codeUnits)), + 'id': newId, + 'user_id': user.userId, + 'conversation_detail_id': AesHelper.aesEncrypt(symKey, Uint8List.fromList(conversationDetailId.codeUnits)), 'admin': AesHelper.aesEncrypt(symKey, Uint8List.fromList((admin ? 'true' : 'false').codeUnits)), 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt(symKey, pubKey)), }); } - for (var x in userConversations) { - print(x); - } - return { - 'id': id, + 'id': conversationDetailId, 'name': AesHelper.aesEncrypt(symKey, Uint8List.fromList(name.codeUnits)), 'users': AesHelper.aesEncrypt(symKey, Uint8List.fromList(jsonEncode(users).codeUnits)), 'user_conversations': userConversations, @@ -231,6 +226,7 @@ class Conversation { 'admin': admin ? 1 : 0, 'name': name, 'status': status.index, + 'is_read': isRead ? 1 : 0, }; } @@ -244,6 +240,37 @@ class Conversation { name: $name admin: $admin'''; } + + Future getRecentMessage() async { + final db = await getDatabaseConnection(); + + final List> maps = await db.rawQuery( + ''' + SELECT * FROM messages WHERE association_key IN ( + SELECT association_key FROM conversation_users WHERE conversation_id = ? + ) + ORDER BY created_at DESC + LIMIT 1; + ''', + [id], + ); + + if (maps.isEmpty) { + return null; + } + + return Message( + id: maps[0]['id'], + symmetricKey: maps[0]['symmetric_key'], + userSymmetricKey: maps[0]['user_symmetric_key'], + data: maps[0]['data'], + senderId: maps[0]['sender_id'], + senderUsername: maps[0]['sender_username'], + associationKey: maps[0]['association_key'], + createdAt: maps[0]['created_at'], + failedToSend: maps[0]['failed_to_send'] == 1, + ); + } } diff --git a/mobile/lib/utils/storage/conversations.dart b/mobile/lib/utils/storage/conversations.dart index 7fd199a..69d5f5c 100644 --- a/mobile/lib/utils/storage/conversations.dart +++ b/mobile/lib/utils/storage/conversations.dart @@ -14,7 +14,7 @@ import '/utils/encryption/aes_helper.dart'; Future updateConversations() async { RSAPrivateKey privKey = await MyProfile.getPrivateKey(); - try { + // try { var resp = await http.get( Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), headers: { @@ -94,9 +94,9 @@ Future updateConversations() async { ); } } - } catch (SocketException) { - return; - } + // } catch (SocketException) { + // return; + // } } Future uploadConversation(Conversation conversation) async { @@ -104,16 +104,14 @@ Future uploadConversation(Conversation conversation) async { Map conversationJson = await conversation.toJson(); - print(conversationJson); + var x = await http.post( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), + headers: { + 'Content-Type': 'application/json; charset=UTF-8', + 'cookie': sessionCookie, + }, + body: jsonEncode(conversationJson), + ); - // var x = await http.post( - // Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), - // headers: { - // 'Content-Type': 'application/json; charset=UTF-8', - // 'cookie': sessionCookie, - // }, - // body: jsonEncode(conversationJson), - // ); - - // print(x.statusCode); + print(x.statusCode); } diff --git a/mobile/lib/utils/storage/database.dart b/mobile/lib/utils/storage/database.dart index d2aa0f3..4466f6d 100644 --- a/mobile/lib/utils/storage/database.dart +++ b/mobile/lib/utils/storage/database.dart @@ -39,7 +39,8 @@ Future getDatabaseConnection() async { symmetric_key TEXT, admin INTEGER, name TEXT, - status INTEGER + status INTEGER, + is_read INTEGER ); '''); @@ -72,9 +73,7 @@ Future getDatabaseConnection() async { '''); }, - // Set the version. This executes the onCreate function and provides a - // path to perform database upgrades and downgrades. - version: 2, + version: 2, ); return database; diff --git a/mobile/lib/utils/storage/messages.dart b/mobile/lib/utils/storage/messages.dart index 4342e43..128c84d 100644 --- a/mobile/lib/utils/storage/messages.dart +++ b/mobile/lib/utils/storage/messages.dart @@ -2,7 +2,6 @@ import 'dart:convert'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:http/http.dart' as http; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:sqflite/sqflite.dart'; import 'package:uuid/uuid.dart'; @@ -14,24 +13,19 @@ import '/utils/storage/database.dart'; import '/utils/storage/session_cookie.dart'; Future sendMessage(Conversation conversation, String data) async { - final preferences = await SharedPreferences.getInstance(); - final userId = preferences.getString('userId'); - final username = preferences.getString('username'); - if (userId == null || username == null) { - throw Exception('Invalid user id'); - } + MyProfile profile = await MyProfile.getProfile(); var uuid = const Uuid(); final String messageDataId = uuid.v4(); - ConversationUser currentUser = await getConversationUser(conversation, username); + ConversationUser currentUser = await getConversationUser(conversation, profile.id); Message message = Message( id: messageDataId, symmetricKey: '', userSymmetricKey: '', - senderId: userId, - senderUsername: username, + senderId: profile.id, + senderUsername: profile.username, data: data, associationKey: currentUser.associationKey, createdAt: DateTime.now().toIso8601String(), diff --git a/mobile/lib/utils/time.dart b/mobile/lib/utils/time.dart new file mode 100644 index 0000000..fb08e74 --- /dev/null +++ b/mobile/lib/utils/time.dart @@ -0,0 +1,19 @@ + +String convertToAgo(String input, { bool short = false }) { + DateTime time = DateTime.parse(input); + Duration diff = DateTime.now().difference(time); + + if(diff.inDays >= 1){ + return '${diff.inDays} day${diff.inDays == 1 ? "" : "s"} ${short ? '': 'ago'}'; + } + if(diff.inHours >= 1){ + return '${diff.inHours} hour${diff.inHours == 1 ? "" : "s"} ${short ? '' : 'ago'}'; + } + if(diff.inMinutes >= 1){ + return '${diff.inMinutes} ${short ? 'min' : 'minute'}${diff.inMinutes == 1 ? "" : "s"} ${short ? '' : 'ago'}'; + } + if (diff.inSeconds >= 1){ + return '${diff.inSeconds} ${short ? '' : 'second'}${diff.inSeconds == 1 ? "" : "s"} ${short ? '' : 'ago'}'; + } + return 'just now'; +} diff --git a/mobile/lib/views/main/conversation/detail.dart b/mobile/lib/views/main/conversation/detail.dart index 511b538..cdee4ac 100644 --- a/mobile/lib/views/main/conversation/detail.dart +++ b/mobile/lib/views/main/conversation/detail.dart @@ -4,27 +4,9 @@ import '/models/conversations.dart'; import '/models/messages.dart'; import '/models/my_profile.dart'; import '/utils/storage/messages.dart'; +import '/utils/time.dart'; import '/views/main/conversation/settings.dart'; -String convertToAgo(String input){ - DateTime time = DateTime.parse(input); - Duration diff = DateTime.now().difference(time); - - if(diff.inDays >= 1){ - return '${diff.inDays} day${diff.inDays == 1 ? "" : "s"} ago'; - } - if(diff.inHours >= 1){ - return '${diff.inHours} hour${diff.inHours == 1 ? "" : "s"} ago'; - } - if(diff.inMinutes >= 1){ - return '${diff.inMinutes} minute${diff.inMinutes == 1 ? "" : "s"} ago'; - } - if (diff.inSeconds >= 1){ - return '${diff.inSeconds} second${diff.inSeconds == 1 ? "" : "s"} ago'; - } - return 'just now'; -} - class ConversationDetail extends StatefulWidget{ final Conversation conversation; const ConversationDetail({ diff --git a/mobile/lib/views/main/conversation/edit_details.dart b/mobile/lib/views/main/conversation/edit_details.dart index be48588..5309579 100644 --- a/mobile/lib/views/main/conversation/edit_details.dart +++ b/mobile/lib/views/main/conversation/edit_details.dart @@ -1,3 +1,4 @@ +import 'package:Envelope/models/conversation_users.dart'; import 'package:flutter/material.dart'; import '/components/custom_circle_avatar.dart'; @@ -8,10 +9,12 @@ import '/views/main/conversation/create_add_users.dart'; class ConversationEditDetails extends StatefulWidget { final Conversation? conversation; final List? friends; + final List? users; const ConversationEditDetails({ Key? key, this.conversation, this.friends, + this.users, }) : super(key: key); @override @@ -25,6 +28,14 @@ class _ConversationEditDetails extends State { TextEditingController conversationNameController = TextEditingController(); + @override + void initState() { + if (widget.conversation != null) { + conversationNameController.text = widget.conversation!.name; + } + super.initState(); + } + @override Widget build(BuildContext context) { const TextStyle inputTextStyle = TextStyle( @@ -96,10 +107,8 @@ class _ConversationEditDetails extends State { key: _formKey, child: Column( children: [ - CustomCircleAvatar( - icon: widget.conversation != null ? - null : // TODO: Add icon here - const Icon(Icons.people, size: 60), + const CustomCircleAvatar( + icon: const Icon(Icons.people, size: 60), imagePath: null, radius: 50, ), diff --git a/mobile/lib/views/main/conversation/list_item.dart b/mobile/lib/views/main/conversation/list_item.dart index 45015e9..defc0da 100644 --- a/mobile/lib/views/main/conversation/list_item.dart +++ b/mobile/lib/views/main/conversation/list_item.dart @@ -1,8 +1,10 @@ import 'package:flutter/material.dart'; +import '/models/messages.dart'; import '/components/custom_circle_avatar.dart'; import '/models/conversations.dart'; import '/views/main/conversation/detail.dart'; +import '/utils/time.dart'; class ConversationListItem extends StatefulWidget{ final Conversation conversation; @@ -17,6 +19,7 @@ class ConversationListItem extends StatefulWidget{ class _ConversationListItemState extends State { late Conversation conversation; + late Message? recentMessage; bool loaded = false; @override @@ -31,7 +34,7 @@ class _ConversationListItemState extends State { })).then(onGoBack) : null; }, child: Container( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), + padding: const EdgeInsets.only(left: 16,right: 0,top: 10,bottom: 10), child: !loaded ? null : Row( children: [ Expanded( @@ -54,13 +57,40 @@ class _ConversationListItemState extends State { conversation.name, style: const TextStyle(fontSize: 16) ), - //Text(widget.messageText,style: TextStyle(fontSize: 13,color: Colors.grey.shade600, fontWeight: widget.isMessageRead?FontWeight.bold:FontWeight.normal),), - ], + recentMessage != null ? + const SizedBox(height: 2) : + const SizedBox.shrink() + , + recentMessage != null ? + Text( + recentMessage!.data, + overflow: TextOverflow.ellipsis, + maxLines: 1, + style: TextStyle( + fontSize: 13, + color: Colors.grey.shade600, + fontWeight: conversation.isRead ? FontWeight.normal : FontWeight.bold, + ), + ) : + const SizedBox.shrink(), + ], ), ), ), ), - ], + recentMessage != null ? + Padding( + padding: const EdgeInsets.only(left: 10), + child: Text( + convertToAgo(recentMessage!.createdAt, short: true), + style: TextStyle( + fontSize: 13, + color: Colors.grey.shade600, + ), + ) + ): + const SizedBox.shrink(), + ], ), ), ], @@ -72,7 +102,12 @@ class _ConversationListItemState extends State { @override void initState() { super.initState(); + getConversationData(); + } + + Future getConversationData() async { conversation = widget.conversation; + recentMessage = await conversation.getRecentMessage(); loaded = true; setState(() {}); } diff --git a/mobile/lib/views/main/conversation/settings.dart b/mobile/lib/views/main/conversation/settings.dart index 85dbc7e..2e8673c 100644 --- a/mobile/lib/views/main/conversation/settings.dart +++ b/mobile/lib/views/main/conversation/settings.dart @@ -1,4 +1,5 @@ import 'package:Envelope/components/custom_circle_avatar.dart'; +import 'package:Envelope/views/main/conversation/edit_details.dart'; import 'package:flutter/material.dart'; import '/models/conversation_users.dart'; @@ -109,7 +110,13 @@ class _ConversationSettingsState extends State { padding: const EdgeInsets.all(5.0), splashRadius: 25, onPressed: () { - // TODO: Redirect to edit screen + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ConversationEditDetails( + users: users, + conversation: widget.conversation, + friends: null, + )), + ).then(onGoBack); }, ) : const SizedBox.shrink(), ], @@ -228,5 +235,12 @@ class _ConversationSettingsState extends State { } ); } + + onGoBack(dynamic value) async { + nameController.text = widget.conversation.name; + super.initState(); + getUsers(); + setState(() {}); + } } diff --git a/mobile/lib/views/main/conversation/settings_user_list_item.dart b/mobile/lib/views/main/conversation/settings_user_list_item.dart index 7c676a0..9657bab 100644 --- a/mobile/lib/views/main/conversation/settings_user_list_item.dart +++ b/mobile/lib/views/main/conversation/settings_user_list_item.dart @@ -43,7 +43,7 @@ class _ConversationSettingsUserListItemState extends State( @@ -75,7 +75,7 @@ class _ConversationSettingsUserListItemState extends State[ Expanded( @@ -104,7 +104,7 @@ class _ConversationSettingsUserListItemState extends State[ CustomCircleAvatar( initials: widget.user.username[0].toUpperCase(), - imagePath: null, // TODO: Add image here + imagePath: null, radius: 15, ), const SizedBox(width: 16), -- 2.17.1 From d7af0a9ac940e8efc06774541fb5d9155e2e9e81 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Tue, 2 Aug 2022 16:11:20 +0930 Subject: [PATCH 17/24] Working conversations and messages --- Backend/Api/Messages/CreateConversation.go | 7 +- Backend/Api/Messages/UpdateConversation.go | 56 +++++ Backend/Api/Routes.go | 1 + Backend/Database/Seeder/MessageSeeder.go | 33 ++- Backend/Database/UserConversations.go | 35 +++ Backend/Models/Messages.go | 19 +- Backend/main.go | 12 +- README.md | 16 +- mobile/lib/models/conversation_users.dart | 154 ++++++------ mobile/lib/models/conversations.dart | 41 +++- mobile/lib/models/messages.dart | 232 +++++++++--------- mobile/lib/utils/storage/conversations.dart | 27 +- mobile/lib/utils/storage/messages.dart | 3 +- .../main/conversation/create_add_users.dart | 16 +- .../views/main/conversation/edit_details.dart | 22 +- mobile/lib/views/main/conversation/list.dart | 26 +- .../lib/views/main/conversation/settings.dart | 107 ++++++-- 17 files changed, 537 insertions(+), 270 deletions(-) create mode 100644 Backend/Api/Messages/UpdateConversation.go diff --git a/Backend/Api/Messages/CreateConversation.go b/Backend/Api/Messages/CreateConversation.go index a806473..505305a 100644 --- a/Backend/Api/Messages/CreateConversation.go +++ b/Backend/Api/Messages/CreateConversation.go @@ -2,7 +2,6 @@ package Messages import ( "encoding/json" - "fmt" "net/http" "github.com/gofrs/uuid" @@ -11,7 +10,7 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" ) -type RawConversationData struct { +type RawCreateConversationData struct { ID string `json:"id"` Name string `json:"name"` Users string `json:"users"` @@ -20,7 +19,7 @@ type RawConversationData struct { func CreateConversation(w http.ResponseWriter, r *http.Request) { var ( - rawConversationData RawConversationData + rawConversationData RawCreateConversationData messageThread Models.ConversationDetail err error ) @@ -45,8 +44,6 @@ func CreateConversation(w http.ResponseWriter, r *http.Request) { return } - fmt.Println(rawConversationData.UserConversations[0]) - err = Database.CreateUserConversations(&rawConversationData.UserConversations) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) diff --git a/Backend/Api/Messages/UpdateConversation.go b/Backend/Api/Messages/UpdateConversation.go new file mode 100644 index 0000000..f1073a2 --- /dev/null +++ b/Backend/Api/Messages/UpdateConversation.go @@ -0,0 +1,56 @@ +package Messages + +import ( + "encoding/json" + "net/http" + + "github.com/gofrs/uuid" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +type RawUpdateConversationData struct { + ID string `json:"id"` + Name string `json:"name"` + Users string `json:"users"` + UserConversations []Models.UserConversation `json:"user_conversations"` +} + +func UpdateConversation(w http.ResponseWriter, r *http.Request) { + var ( + rawConversationData RawCreateConversationData + messageThread Models.ConversationDetail + err error + ) + + err = json.NewDecoder(r.Body).Decode(&rawConversationData) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + messageThread = Models.ConversationDetail{ + Base: Models.Base{ + ID: uuid.FromStringOrNil(rawConversationData.ID), + }, + Name: rawConversationData.Name, + Users: rawConversationData.Users, + } + + err = Database.UpdateConversationDetail(&messageThread) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + if len(rawConversationData.UserConversations) > 0 { + err = Database.UpdateOrCreateUserConversations(&rawConversationData.UserConversations) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + } + + w.WriteHeader(http.StatusOK) +} diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index a37fc15..e1f8df4 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -67,6 +67,7 @@ func InitApiEndpoints(router *mux.Router) { authApi.HandleFunc("/conversation_details", Messages.EncryptedConversationDetailsList).Methods("GET") authApi.HandleFunc("/conversations", Messages.CreateConversation).Methods("POST") + authApi.HandleFunc("/conversations", Messages.UpdateConversation).Methods("PUT") // Define routes for messages authApi.HandleFunc("/message", Messages.CreateMessage).Methods("POST") diff --git a/Backend/Database/Seeder/MessageSeeder.go b/Backend/Database/Seeder/MessageSeeder.go index 76ec995..0aa750f 100644 --- a/Backend/Database/Seeder/MessageSeeder.go +++ b/Backend/Database/Seeder/MessageSeeder.go @@ -6,7 +6,6 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" - "git.tovijaeschke.xyz/tovi/Envelope/Backend/Util" "github.com/gofrs/uuid" ) @@ -176,9 +175,9 @@ func SeedMessages() { messageThread Models.ConversationDetail key aesKey primaryUser Models.User - primaryUserAssociationKey string + primaryUserAssociationKey uuid.UUID secondaryUser Models.User - secondaryUserAssociationKey string + secondaryUserAssociationKey uuid.UUID userJson string id1, id2 uuid.UUID i int @@ -186,10 +185,19 @@ func SeedMessages() { ) key, err = generateAesKey() + if err != nil { + panic(err) + } messageThread, err = seedConversationDetail(key) - primaryUserAssociationKey = Util.RandomString(32) - secondaryUserAssociationKey = Util.RandomString(32) + primaryUserAssociationKey, err = uuid.NewV4() + if err != nil { + panic(err) + } + secondaryUserAssociationKey, err = uuid.NewV4() + if err != nil { + panic(err) + } primaryUser, err = Database.GetUserByUsername("testUser") if err != nil { @@ -201,6 +209,9 @@ func SeedMessages() { messageThread.ID, key, ) + if err != nil { + panic(err) + } secondaryUser, err = Database.GetUserByUsername("ATestUser2") if err != nil { @@ -227,14 +238,14 @@ func SeedMessages() { [ { "id": "%s", - "user_id": "%s", + "user_id": "%s", "username": "%s", "admin": "true", "association_key": "%s" }, { "id": "%s", - "user_id": "%s", + "user_id": "%s", "username": "%s", "admin": "false", "association_key": "%s" @@ -244,11 +255,11 @@ func SeedMessages() { id1.String(), primaryUser.ID.String(), primaryUser.Username, - primaryUserAssociationKey, + primaryUserAssociationKey.String(), id2.String(), secondaryUser.ID.String(), secondaryUser.Username, - secondaryUserAssociationKey, + secondaryUserAssociationKey.String(), ) messageThread, err = seedUpdateUserConversation( @@ -261,8 +272,8 @@ func SeedMessages() { err = seedMessage( primaryUser, secondaryUser, - primaryUserAssociationKey, - secondaryUserAssociationKey, + primaryUserAssociationKey.String(), + secondaryUserAssociationKey.String(), i, ) if err != nil { diff --git a/Backend/Database/UserConversations.go b/Backend/Database/UserConversations.go index 02fb62d..930a98f 100644 --- a/Backend/Database/UserConversations.go +++ b/Backend/Database/UserConversations.go @@ -4,6 +4,7 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" "gorm.io/gorm" + "gorm.io/gorm/clause" ) func GetUserConversationById(id string) (Models.UserConversation, error) { @@ -49,6 +50,40 @@ func CreateUserConversations(userConversations *[]Models.UserConversation) error return err } +func UpdateUserConversation(userConversation *Models.UserConversation) error { + var err error + + err = DB.Model(Models.UserConversation{}). + Updates(userConversation). + Error + + return err +} + +func UpdateUserConversations(userConversations *[]Models.UserConversation) error { + var err error + + err = DB.Model(Models.UserConversation{}). + Updates(userConversations). + Error + + return err +} + +func UpdateOrCreateUserConversations(userConversations *[]Models.UserConversation) error { + var err error + + err = DB.Model(Models.UserConversation{}). + Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: "id"}}, + DoUpdates: clause.AssignmentColumns([]string{"admin"}), + }). + Create(userConversations). + Error + + return err +} + func DeleteUserConversation(userConversation *Models.UserConversation) error { return DB.Session(&gorm.Session{FullSaveAssociations: true}). Delete(userConversation). diff --git a/Backend/Models/Messages.go b/Backend/Models/Messages.go index fed8909..de32fca 100644 --- a/Backend/Models/Messages.go +++ b/Backend/Models/Messages.go @@ -18,22 +18,23 @@ type Message struct { Base MessageDataID uuid.UUID `json:"message_data_id"` MessageData MessageData `json:"message_data"` - SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted - AssociationKey string `gorm:"not null" json:"association_key"` // TODO: This links all encrypted messages for a user in a thread together. Find a way to fix this - CreatedAt time.Time `gorm:"not null" json:"created_at"` + SymmetricKey string `json:"symmetric_key" gorm:"not null"` // Stored encrypted + AssociationKey string `json:"association_key" gorm:"not null"` // TODO: This links all encrypted messages for a user in a thread together. Find a way to fix this + CreatedAt time.Time `json:"created_at" gorm:"not null"` } type ConversationDetail struct { Base - Name string `gorm:"not null" json:"name"` // Stored encrypted - Users string `json:"users"` // Stored as encrypted JSON + Name string `gorm:"not null" json:"name"` // Stored encrypted + Users string ` json:"users"` // Stored as encrypted JSON } type UserConversation struct { Base UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` - User User `json:"user"` - ConversationDetailID string `gorm:"not null" json:"conversation_detail_id"` // Stored encrypted - Admin string `gorm:"not null" json:"admin"` // Bool if user is admin of thread, stored encrypted - SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted + User User ` json:"user"` + ConversationDetailID string `gorm:"not null" json:"conversation_detail_id"` // Stored encrypted + Admin string `gorm:"not null" json:"admin"` // Bool if user is admin of thread, stored encrypted + SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted + // TODO: Add association_key here } diff --git a/Backend/main.go b/Backend/main.go index 2978a6f..00db155 100644 --- a/Backend/main.go +++ b/Backend/main.go @@ -2,6 +2,7 @@ package main import ( "flag" + "fmt" "net/http" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api" @@ -11,9 +12,7 @@ import ( "github.com/gorilla/mux" ) -var ( - seed bool -) +var seed bool func init() { Database.Init() @@ -26,6 +25,7 @@ func init() { func main() { var ( router *mux.Router + err error ) if seed { @@ -37,5 +37,9 @@ func main() { Api.InitApiEndpoints(router) - http.ListenAndServe(":8080", router) + fmt.Println("Listening on port :8080") + err = http.ListenAndServe(":8080", router) + if err != nil { + panic(err) + } } diff --git a/README.md b/README.md index dd411b9..d1cb191 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,17 @@ # Envelope -Encrypted messaging app \ No newline at end of file +Encrypted messaging app + +## TODO + +- Fix adding users to conversations +- Fix users recieving messages +- Fix the admin checks on conversation settings page +- Add admin checks to conversation settings page +- Add admin checks on backend +- Add errors to login / signup page +- Add errors when updating conversations +- Refactor the update conversations function +- Finish the friends list page +- Allow adding friends +- Finish the disappearing messages functionality diff --git a/mobile/lib/models/conversation_users.dart b/mobile/lib/models/conversation_users.dart index 3417792..fe68f58 100644 --- a/mobile/lib/models/conversation_users.dart +++ b/mobile/lib/models/conversation_users.dart @@ -2,97 +2,97 @@ import '/models/conversations.dart'; import '/utils/storage/database.dart'; Future getConversationUser(Conversation conversation, String userId) async { - final db = await getDatabaseConnection(); + final db = await getDatabaseConnection(); - final List> maps = await db.query( - 'conversation_users', - where: 'conversation_id = ? AND user_id = ?', - whereArgs: [conversation.id, userId], - ); + final List> maps = await db.query( + 'conversation_users', + where: 'conversation_id = ? AND user_id = ?', + whereArgs: [conversation.id, userId], + ); - if (maps.length != 1) { - throw ArgumentError('Invalid conversation_id or username'); - } + if (maps.length != 1) { + throw ArgumentError('Invalid conversation_id or username'); + } - return ConversationUser( - id: maps[0]['id'], - userId: maps[0]['user_id'], - conversationId: maps[0]['conversation_id'], - username: maps[0]['username'], - associationKey: maps[0]['association_key'], - admin: maps[0]['admin'] == 1, - ); + return ConversationUser( + id: maps[0]['id'], + userId: maps[0]['user_id'], + conversationId: maps[0]['conversation_id'], + username: maps[0]['username'], + associationKey: maps[0]['association_key'], + admin: maps[0]['admin'] == 1, + ); } // A method that retrieves all the dogs from the dogs table. Future> getConversationUsers(Conversation conversation) async { - final db = await getDatabaseConnection(); + final db = await getDatabaseConnection(); - final List> maps = await db.query( - 'conversation_users', - where: 'conversation_id = ?', - whereArgs: [conversation.id], - orderBy: 'admin', - ); + final List> maps = await db.query( + 'conversation_users', + where: 'conversation_id = ?', + whereArgs: [conversation.id], + orderBy: 'admin', + ); - return List.generate(maps.length, (i) { - return ConversationUser( - id: maps[i]['id'], - userId: maps[i]['user_id'], - conversationId: maps[i]['conversation_id'], - username: maps[i]['username'], - associationKey: maps[i]['association_key'], - admin: maps[i]['admin'] == 1, - ); - }); + return List.generate(maps.length, (i) { + return ConversationUser( + id: maps[i]['id'], + userId: maps[i]['user_id'], + conversationId: maps[i]['conversation_id'], + username: maps[i]['username'], + associationKey: maps[i]['association_key'], + admin: maps[i]['admin'] == 1, + ); + }); } class ConversationUser{ - String id; - String userId; - String conversationId; - String username; - String associationKey; - bool admin; - ConversationUser({ - required this.id, - required this.userId, - required this.conversationId, - required this.username, - required this.associationKey, - required this.admin, - }); + String id; + String userId; + String conversationId; + String username; + String associationKey; + bool admin; + ConversationUser({ + required this.id, + required this.userId, + required this.conversationId, + required this.username, + required this.associationKey, + required this.admin, + }); - factory ConversationUser.fromJson(Map json, String conversationId) { - return ConversationUser( - id: json['id'], - userId: json['user_id'], - conversationId: conversationId, - username: json['username'], - associationKey: json['association_key'], - admin: json['admin'] == 'true', - ); - } + factory ConversationUser.fromJson(Map json, String conversationId) { + return ConversationUser( + id: json['id'], + userId: json['user_id'], + conversationId: conversationId, + username: json['username'], + associationKey: json['association_key'], + admin: json['admin'] == 'true', + ); + } - Map toJson() { - return { - 'id': id, - 'user_id': userId, - 'username': username, - 'association_key': associationKey, - 'admin': admin ? 'true' : 'false', - }; - } + Map toJson() { + return { + 'id': id, + 'user_id': userId, + 'username': username, + 'association_key': associationKey, + 'admin': admin ? 'true' : 'false', + }; + } - Map toMap() { - return { - 'id': id, - 'user_id': userId, - 'conversation_id': conversationId, - 'username': username, - 'association_key': associationKey, - 'admin': admin ? 1 : 0, - }; - } + Map toMap() { + return { + 'id': id, + 'user_id': userId, + 'conversation_id': conversationId, + 'username': username, + 'association_key': associationKey, + 'admin': admin ? 1 : 0, + }; + } } diff --git a/mobile/lib/models/conversations.dart b/mobile/lib/models/conversations.dart index 88adea3..6e656da 100644 --- a/mobile/lib/models/conversations.dart +++ b/mobile/lib/models/conversations.dart @@ -25,8 +25,6 @@ Future createConversation(String title, List friends) asyn Uint8List symmetricKey = AesHelper.deriveKey(generateRandomString(32)); - String associationKey = generateRandomString(32); - Conversation conversation = Conversation( id: conversationId, userId: profile.id, @@ -51,7 +49,7 @@ Future createConversation(String title, List friends) asyn userId: profile.id, conversationId: conversationId, username: profile.username, - associationKey: associationKey, + associationKey: uuid.v4(), admin: true, ).toMap(), conflictAlgorithm: ConflictAlgorithm.fail, @@ -65,7 +63,31 @@ Future createConversation(String title, List friends) asyn userId: friend.friendId, conversationId: conversationId, username: friend.username, - associationKey: associationKey, + associationKey: uuid.v4(), + admin: false, + ).toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + return conversation; +} + + +Future addUsersToConversation(Conversation conversation, List friends) async { + final db = await getDatabaseConnection(); + + var uuid = const Uuid(); + + for (Friend friend in friends) { + await db.insert( + 'conversation_users', + ConversationUser( + id: uuid.v4(), + userId: friend.friendId, + conversationId: conversation.id, + username: friend.username, + associationKey: uuid.v4(), admin: false, ).toMap(), conflictAlgorithm: ConflictAlgorithm.replace, @@ -181,12 +203,21 @@ class Conversation { ); } - Future> toJson() async { + Future> payloadJson({ bool includeUsers = true }) async { MyProfile profile = await MyProfile.getProfile(); var symKey = base64.decode(symmetricKey); List users = await getConversationUsers(this); + + if (!includeUsers) { + return { + 'id': conversationDetailId, + 'name': AesHelper.aesEncrypt(symKey, Uint8List.fromList(name.codeUnits)), + 'users': AesHelper.aesEncrypt(symKey, Uint8List.fromList(jsonEncode(users).codeUnits)), + }; + } + List userConversations = []; for (ConversationUser user in users) { diff --git a/mobile/lib/models/messages.dart b/mobile/lib/models/messages.dart index ae0edac..f19f78c 100644 --- a/mobile/lib/models/messages.dart +++ b/mobile/lib/models/messages.dart @@ -1,17 +1,48 @@ import 'dart:convert'; import 'dart:typed_data'; -import 'package:Envelope/models/conversation_users.dart'; -import 'package:Envelope/models/conversations.dart'; + import 'package:pointycastle/export.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import '/utils/encryption/crypto_utils.dart'; + +import '/models/conversation_users.dart'; +import '/models/conversations.dart'; +import '/models/my_profile.dart'; +import '/models/friends.dart'; import '/utils/encryption/aes_helper.dart'; +import '/utils/encryption/crypto_utils.dart'; import '/utils/storage/database.dart'; import '/utils/strings.dart'; -import '/models/friends.dart'; -const messageTypeSender = 'sender'; const messageTypeReceiver = 'receiver'; +const messageTypeSender = 'sender'; + +Future> getMessagesForThread(Conversation conversation) async { + final db = await getDatabaseConnection(); + + final List> maps = await db.rawQuery( + ''' + SELECT * FROM messages WHERE association_key IN ( + SELECT association_key FROM conversation_users WHERE conversation_id = ? + ) + ORDER BY created_at DESC; + ''', + [conversation.id] + ); + + return List.generate(maps.length, (i) { + return Message( + id: maps[i]['id'], + symmetricKey: maps[i]['symmetric_key'], + userSymmetricKey: maps[i]['user_symmetric_key'], + data: maps[i]['data'], + senderId: maps[i]['sender_id'], + senderUsername: maps[i]['sender_username'], + associationKey: maps[i]['association_key'], + createdAt: maps[i]['created_at'], + failedToSend: maps[i]['failed_to_send'] == 1, + ); + }); + +} class Message { String id; @@ -38,109 +69,99 @@ class Message { factory Message.fromJson(Map json, RSAPrivateKey privKey) { var userSymmetricKey = CryptoUtils.rsaDecrypt( - base64.decode(json['symmetric_key']), - privKey, + base64.decode(json['symmetric_key']), + privKey, ); var symmetricKey = AesHelper.aesDecrypt( - userSymmetricKey, - base64.decode(json['message_data']['symmetric_key']), + userSymmetricKey, + base64.decode(json['message_data']['symmetric_key']), ); var senderId = AesHelper.aesDecrypt( - base64.decode(symmetricKey), - base64.decode(json['message_data']['sender_id']), + base64.decode(symmetricKey), + base64.decode(json['message_data']['sender_id']), ); var data = AesHelper.aesDecrypt( - base64.decode(symmetricKey), - base64.decode(json['message_data']['data']), + base64.decode(symmetricKey), + base64.decode(json['message_data']['data']), ); return Message( - id: json['id'], - symmetricKey: symmetricKey, - userSymmetricKey: base64.encode(userSymmetricKey), - data: data, - senderId: senderId, - senderUsername: 'Unknown', - associationKey: json['association_key'], - createdAt: json['created_at'], - failedToSend: false, + id: json['id'], + symmetricKey: symmetricKey, + userSymmetricKey: base64.encode(userSymmetricKey), + data: data, + senderId: senderId, + senderUsername: 'Unknown', + associationKey: json['association_key'], + createdAt: json['created_at'], + failedToSend: false, ); } Future toJson(Conversation conversation, String messageDataId) async { - final preferences = await SharedPreferences.getInstance(); - RSAPublicKey publicKey = CryptoUtils.rsaPublicKeyFromPem(preferences.getString('asymmetricPublicKey')!); - - final userSymmetricKey = AesHelper.deriveKey(generateRandomString(32)); - final symmetricKey = AesHelper.deriveKey(generateRandomString(32)); - - List> messages = []; - - String id = ''; - - List conversationUsers = await getConversationUsers(conversation); - - for (var i = 0; i < conversationUsers.length; i++) { - ConversationUser user = conversationUsers[i]; - if (preferences.getString('username') == user.username) { - id = user.id; - - messages.add({ - 'message_data_id': messageDataId, - 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt( - userSymmetricKey, - publicKey, - )), - 'association_key': user.associationKey, - }); - - continue; - } - - Friend friend = await getFriendByFriendId(user.id); - RSAPublicKey friendPublicKey = CryptoUtils.rsaPublicKeyFromPem(friend.asymmetricPublicKey); - - messages.add({ - 'message_data_id': messageDataId, - 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt( - userSymmetricKey, - friendPublicKey, - )), - 'association_key': user.associationKey, - }); - } + MyProfile profile = await MyProfile.getProfile(); + if (profile.publicKey == null) { + throw Exception('Could not get profile.publicKey'); + } + RSAPublicKey publicKey = profile.publicKey!; + + final userSymmetricKey = AesHelper.deriveKey(generateRandomString(32)); + final symmetricKey = AesHelper.deriveKey(generateRandomString(32)); + + List> messages = []; + + String id = ''; + + List conversationUsers = await getConversationUsers(conversation); - Map messageData = { - 'id': messageDataId, - 'data': AesHelper.aesEncrypt(symmetricKey, Uint8List.fromList(data.codeUnits)), - 'sender_id': AesHelper.aesEncrypt(symmetricKey, Uint8List.fromList(id.codeUnits)), - 'symmetric_key': AesHelper.aesEncrypt( + for (var i = 0; i < conversationUsers.length; i++) { + ConversationUser user = conversationUsers[i]; + + if (profile.id == user.userId) { + id = user.id; + + messages.add({ + 'message_data_id': messageDataId, + 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt( userSymmetricKey, - Uint8List.fromList(base64.encode(symmetricKey).codeUnits), - ), - }; + publicKey, + )), + 'association_key': user.associationKey, + }); - return jsonEncode({ - 'message_data': messageData, - 'message': messages, - }); - } + continue; + } - @override - String toString() { - return ''' + Friend friend = await getFriendByFriendId(user.userId); + RSAPublicKey friendPublicKey = CryptoUtils.rsaPublicKeyFromPem(friend.asymmetricPublicKey); + + messages.add({ + 'message_data_id': messageDataId, + 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt( + userSymmetricKey, + friendPublicKey, + )), + 'association_key': user.associationKey, + }); + } + Map messageData = { + 'id': messageDataId, + 'data': AesHelper.aesEncrypt(symmetricKey, Uint8List.fromList(data.codeUnits)), + 'sender_id': AesHelper.aesEncrypt(symmetricKey, Uint8List.fromList(senderId.codeUnits)), + 'symmetric_key': AesHelper.aesEncrypt( + userSymmetricKey, + Uint8List.fromList(base64.encode(symmetricKey).codeUnits), + ), + }; - id: $id - data: $data - senderId: $senderId - senderUsername: $senderUsername - associationKey: $associationKey - createdAt: $createdAt -'''; + return jsonEncode({ + 'message_data': messageData, + 'message': messages, + }); } Map toMap() { @@ -157,33 +178,18 @@ class Message { }; } -} - -Future> getMessagesForThread(Conversation conversation) async { - final db = await getDatabaseConnection(); + @override + String toString() { + return ''' - final List> maps = await db.rawQuery( - ''' - SELECT * FROM messages WHERE association_key IN ( - SELECT association_key FROM conversation_users WHERE conversation_id = ? - ) - ORDER BY created_at DESC; - ''', - [conversation.id] - ); - return List.generate(maps.length, (i) { - return Message( - id: maps[i]['id'], - symmetricKey: maps[i]['symmetric_key'], - userSymmetricKey: maps[i]['user_symmetric_key'], - data: maps[i]['data'], - senderId: maps[i]['sender_id'], - senderUsername: maps[i]['sender_username'], - associationKey: maps[i]['association_key'], - createdAt: maps[i]['created_at'], - failedToSend: maps[i]['failed_to_send'] == 1, - ); - }); + id: $id + data: $data + senderId: $senderId + senderUsername: $senderUsername + associationKey: $associationKey + createdAt: $createdAt + '''; + } } diff --git a/mobile/lib/utils/storage/conversations.dart b/mobile/lib/utils/storage/conversations.dart index 69d5f5c..a7fe2c0 100644 --- a/mobile/lib/utils/storage/conversations.dart +++ b/mobile/lib/utils/storage/conversations.dart @@ -31,6 +31,10 @@ Future updateConversations() async { List conversationsJson = jsonDecode(resp.body); + if (conversationsJson.isEmpty) { + return; + } + for (var i = 0; i < conversationsJson.length; i++) { Conversation conversation = Conversation.fromJson( conversationsJson[i] as Map, @@ -102,7 +106,7 @@ Future updateConversations() async { Future uploadConversation(Conversation conversation) async { String sessionCookie = await getSessionCookie(); - Map conversationJson = await conversation.toJson(); + Map conversationJson = await conversation.payloadJson(); var x = await http.post( Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), @@ -113,5 +117,26 @@ Future uploadConversation(Conversation conversation) async { body: jsonEncode(conversationJson), ); + // TODO: Handle errors here + print(x.statusCode); +} + + +Future updateConversation(Conversation conversation, { includeUsers = true } ) async { + String sessionCookie = await getSessionCookie(); + + Map conversationJson = await conversation.payloadJson(includeUsers: includeUsers); + + var x = await http.put( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), + headers: { + 'Content-Type': 'application/json; charset=UTF-8', + 'cookie': sessionCookie, + }, + body: jsonEncode(conversationJson), + ); + + // TODO: Handle errors here print(x.statusCode); } + diff --git a/mobile/lib/utils/storage/messages.dart b/mobile/lib/utils/storage/messages.dart index 128c84d..d5978d8 100644 --- a/mobile/lib/utils/storage/messages.dart +++ b/mobile/lib/utils/storage/messages.dart @@ -24,7 +24,7 @@ Future sendMessage(Conversation conversation, String data) async { id: messageDataId, symmetricKey: '', userSymmetricKey: '', - senderId: profile.id, + senderId: currentUser.userId, senderUsername: profile.username, data: data, associationKey: currentUser.associationKey, @@ -66,6 +66,7 @@ Future sendMessage(Conversation conversation, String data) async { where: 'id = ?', whereArgs: [message.id], ); + throw exception; }); } diff --git a/mobile/lib/views/main/conversation/create_add_users.dart b/mobile/lib/views/main/conversation/create_add_users.dart index 4e9ed49..1b9186f 100644 --- a/mobile/lib/views/main/conversation/create_add_users.dart +++ b/mobile/lib/views/main/conversation/create_add_users.dart @@ -8,11 +8,11 @@ import '/views/main/conversation/detail.dart'; class ConversationAddFriendsList extends StatefulWidget { final List friends; - final String title; + final Function(List friendsSelected) saveCallback; const ConversationAddFriendsList({ Key? key, required this.friends, - required this.title, + required this.saveCallback, }) : super(key: key); @override @@ -88,20 +88,12 @@ class _ConversationAddFriendsListState extends State floatingActionButton: Padding( padding: const EdgeInsets.only(right: 10, bottom: 10), child: FloatingActionButton( - onPressed: () async { - Conversation conversation = await createConversation(widget.title, friendsSelected); - uploadConversation(conversation); + onPressed: () { + widget.saveCallback(friendsSelected); setState(() { friendsSelected = []; }); - - Navigator.of(context).popUntil((route) => route.isFirst); - Navigator.push(context, MaterialPageRoute(builder: (context){ - return ConversationDetail( - conversation: conversation, - ); - })); }, backgroundColor: Theme.of(context).colorScheme.primary, child: friendsSelected.isEmpty ? diff --git a/mobile/lib/views/main/conversation/edit_details.dart b/mobile/lib/views/main/conversation/edit_details.dart index 5309579..a0441b9 100644 --- a/mobile/lib/views/main/conversation/edit_details.dart +++ b/mobile/lib/views/main/conversation/edit_details.dart @@ -1,20 +1,15 @@ -import 'package:Envelope/models/conversation_users.dart'; import 'package:flutter/material.dart'; import '/components/custom_circle_avatar.dart'; import '/models/conversations.dart'; -import '/models/friends.dart'; -import '/views/main/conversation/create_add_users.dart'; class ConversationEditDetails extends StatefulWidget { + final Function(String conversationName) saveCallback; final Conversation? conversation; - final List? friends; - final List? users; const ConversationEditDetails({ Key? key, + required this.saveCallback, this.conversation, - this.friends, - this.users, }) : super(key: key); @override @@ -134,15 +129,12 @@ class _ConversationEditDetails extends State { ElevatedButton( style: buttonStyle, onPressed: () { - if (_formKey.currentState!.validate()) { - Navigator.of(context).push( - MaterialPageRoute(builder: (context) => ConversationAddFriendsList( - friends: widget.friends!, - title: conversationNameController.text, - ) - ) - ); + if (!_formKey.currentState!.validate()) { + // TODO: Show error here + return; } + + widget.saveCallback(conversationNameController.text); }, child: const Text('Save'), ), diff --git a/mobile/lib/views/main/conversation/list.dart b/mobile/lib/views/main/conversation/list.dart index 8ec0931..a41e6cf 100644 --- a/mobile/lib/views/main/conversation/list.dart +++ b/mobile/lib/views/main/conversation/list.dart @@ -1,9 +1,12 @@ import 'package:Envelope/models/friends.dart'; +import 'package:Envelope/utils/storage/conversations.dart'; import 'package:flutter/material.dart'; import '/models/conversations.dart'; import '/views/main/conversation/edit_details.dart'; import '/views/main/conversation/list_item.dart'; +import 'create_add_users.dart'; +import 'detail.dart'; class ConversationList extends StatefulWidget { final List conversations; @@ -73,7 +76,28 @@ class _ConversationListState extends State { onPressed: () { Navigator.of(context).push( MaterialPageRoute(builder: (context) => ConversationEditDetails( - friends: friends, + saveCallback: (String conversationName) { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ConversationAddFriendsList( + friends: friends, + saveCallback: (List friendsSelected) async { + Conversation conversation = await createConversation( + conversationName, + friendsSelected + ); + + uploadConversation(conversation); + + Navigator.of(context).popUntil((route) => route.isFirst); + Navigator.push(context, MaterialPageRoute(builder: (context){ + return ConversationDetail( + conversation: conversation, + ); + })); + }, + )) + ); + }, )), ).then(onGoBack); }, diff --git a/mobile/lib/views/main/conversation/settings.dart b/mobile/lib/views/main/conversation/settings.dart index 2e8673c..cc6991b 100644 --- a/mobile/lib/views/main/conversation/settings.dart +++ b/mobile/lib/views/main/conversation/settings.dart @@ -1,11 +1,15 @@ -import 'package:Envelope/components/custom_circle_avatar.dart'; -import 'package:Envelope/views/main/conversation/edit_details.dart'; +import 'package:Envelope/models/friends.dart'; +import 'package:Envelope/views/main/conversation/create_add_users.dart'; import 'package:flutter/material.dart'; import '/models/conversation_users.dart'; import '/models/conversations.dart'; import '/models/my_profile.dart'; import '/views/main/conversation/settings_user_list_item.dart'; +import '/views/main/conversation/edit_details.dart'; +import '/components/custom_circle_avatar.dart'; +import '/utils/storage/database.dart'; +import '/utils/storage/conversations.dart'; class ConversationSettings extends StatefulWidget { final Conversation conversation; @@ -78,7 +82,7 @@ class _ConversationSettingsState extends State { widget.conversation.admin ? const SizedBox(height: 25) : const SizedBox.shrink(), - sectionTitle('Members'), + sectionTitle('Members', showUsersAdd: true), usersList(), const SizedBox(height: 25), myAccess(), @@ -112,9 +116,22 @@ class _ConversationSettingsState extends State { onPressed: () { Navigator.of(context).push( MaterialPageRoute(builder: (context) => ConversationEditDetails( - users: users, - conversation: widget.conversation, - friends: null, + saveCallback: (String conversationName) async { + widget.conversation.name = conversationName; + + final db = await getDatabaseConnection(); + db.update( + 'conversations', + widget.conversation.toMap(), + where: 'id = ?', + whereArgs: [widget.conversation.id], + ); + + await updateConversation(widget.conversation, includeUsers: true); + setState(() {}); + Navigator.pop(context); + }, + conversation: widget.conversation, )), ).then(onGoBack); }, @@ -160,16 +177,49 @@ class _ConversationSettingsState extends State { ); } - Widget sectionTitle(String title) { + Widget sectionTitle(String title, { bool showUsersAdd = false}) { return Align( - alignment: Alignment.centerLeft, - child: Container( - padding: const EdgeInsets.only(left: 12), - child: Text( - title, - style: const TextStyle(fontSize: 20), + alignment: Alignment.centerLeft, + child: Padding( + padding: const EdgeInsets.only(right: 6), + child: Row( + children: [ + Expanded( + child: Container( + padding: const EdgeInsets.only(left: 12), + child: Text( + title, + style: const TextStyle(fontSize: 20), + ), + ), ), - ), + !showUsersAdd ? + const SizedBox.shrink() : + IconButton( + icon: const Icon(Icons.add), + padding: const EdgeInsets.all(0), + onPressed: () async { + List friends = await unselectedFriends(); + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ConversationAddFriendsList( + friends: friends, + saveCallback: (List selectedFriends) async { + addUsersToConversation( + widget.conversation, + selectedFriends, + ); + + await updateConversation(widget.conversation, includeUsers: true); + await getUsers(); + Navigator.pop(context); + }, + )) + ); + }, + ), + ], + ) + ) ); } @@ -236,9 +286,36 @@ class _ConversationSettingsState extends State { ); } + Future> unselectedFriends() async { + final db = await getDatabaseConnection(); + + List notInArgs = []; + for (var user in users) { + notInArgs.add(user.userId); + } + + final List> maps = await db.query( + 'friends', + where: 'friend_id not in (${List.filled(notInArgs.length, '?').join(',')})', + whereArgs: notInArgs, + orderBy: 'username', + ); + + return List.generate(maps.length, (i) { + return Friend( + id: maps[i]['id'], + userId: maps[i]['user_id'], + friendId: maps[i]['friend_id'], + friendSymmetricKey: maps[i]['symmetric_key'], + asymmetricPublicKey: maps[i]['asymmetric_public_key'], + acceptedAt: maps[i]['accepted_at'], + username: maps[i]['username'], + ); + }); + } + onGoBack(dynamic value) async { nameController.text = widget.conversation.name; - super.initState(); getUsers(); setState(() {}); } -- 2.17.1 From c89dcf10eca66b3173b13d52fd5afb39d5298f9a Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Fri, 5 Aug 2022 18:35:02 +0930 Subject: [PATCH 18/24] Fix messages doubling up due to mismatched ids --- Backend/Api/Messages/CreateConversation.go | 8 +- Backend/Api/Messages/MessageThread.go | 16 +- Backend/Api/Messages/UpdateConversation.go | 8 +- Backend/Database/ConversationDetailUsers.go | 41 ++ Backend/Database/Init.go | 1 + Backend/Database/Messages.go | 10 +- Backend/Database/Seeder/MessageSeeder.go | 158 ++++--- Backend/Models/Conversations.go | 33 ++ Backend/Models/Messages.go | 16 - Backend/main.go | 4 +- README.md | 23 +- mobile/lib/models/conversation_users.dart | 102 +++- mobile/lib/models/conversations.dart | 35 +- mobile/lib/models/friends.dart | 46 +- mobile/lib/models/messages.dart | 14 +- mobile/lib/utils/storage/conversations.dart | 11 +- mobile/lib/utils/storage/database.dart | 5 +- mobile/lib/utils/storage/messages.dart | 6 +- mobile/lib/views/authentication/login.dart | 20 +- mobile/lib/views/authentication/signup.dart | 2 +- .../main/conversation/create_add_users.dart | 185 ++++---- .../lib/views/main/conversation/detail.dart | 444 +++++++++--------- .../lib/views/main/conversation/settings.dart | 372 +++++++-------- mobile/lib/views/main/friend/list.dart | 132 +++--- 24 files changed, 932 insertions(+), 760 deletions(-) create mode 100644 Backend/Database/ConversationDetailUsers.go create mode 100644 Backend/Models/Conversations.go diff --git a/Backend/Api/Messages/CreateConversation.go b/Backend/Api/Messages/CreateConversation.go index 505305a..5241995 100644 --- a/Backend/Api/Messages/CreateConversation.go +++ b/Backend/Api/Messages/CreateConversation.go @@ -11,10 +11,10 @@ import ( ) type RawCreateConversationData struct { - ID string `json:"id"` - Name string `json:"name"` - Users string `json:"users"` - UserConversations []Models.UserConversation `json:"user_conversations"` + ID string `json:"id"` + Name string `json:"name"` + Users []Models.ConversationDetailUser `json:"users"` + UserConversations []Models.UserConversation `json:"user_conversations"` } func CreateConversation(w http.ResponseWriter, r *http.Request) { diff --git a/Backend/Api/Messages/MessageThread.go b/Backend/Api/Messages/MessageThread.go index 7eb3b27..b9c4ee7 100644 --- a/Backend/Api/Messages/MessageThread.go +++ b/Backend/Api/Messages/MessageThread.go @@ -12,22 +12,22 @@ import ( func Messages(w http.ResponseWriter, r *http.Request) { var ( - messages []Models.Message - urlVars map[string]string - threadKey string - returnJson []byte - ok bool - err error + messages []Models.Message + urlVars map[string]string + associationKey string + returnJson []byte + ok bool + err error ) urlVars = mux.Vars(r) - threadKey, ok = urlVars["threadKey"] + associationKey, ok = urlVars["threadKey"] if !ok { http.Error(w, "Not Found", http.StatusNotFound) return } - messages, err = Database.GetMessagesByThreadKey(threadKey) + messages, err = Database.GetMessagesByAssociationKey(associationKey) if !ok { http.Error(w, "Not Found", http.StatusNotFound) return diff --git a/Backend/Api/Messages/UpdateConversation.go b/Backend/Api/Messages/UpdateConversation.go index f1073a2..93b5215 100644 --- a/Backend/Api/Messages/UpdateConversation.go +++ b/Backend/Api/Messages/UpdateConversation.go @@ -11,10 +11,10 @@ import ( ) type RawUpdateConversationData struct { - ID string `json:"id"` - Name string `json:"name"` - Users string `json:"users"` - UserConversations []Models.UserConversation `json:"user_conversations"` + ID string `json:"id"` + Name string `json:"name"` + Users []Models.ConversationDetailUser `json:"users"` + UserConversations []Models.UserConversation `json:"user_conversations"` } func UpdateConversation(w http.ResponseWriter, r *http.Request) { diff --git a/Backend/Database/ConversationDetailUsers.go b/Backend/Database/ConversationDetailUsers.go new file mode 100644 index 0000000..6396acb --- /dev/null +++ b/Backend/Database/ConversationDetailUsers.go @@ -0,0 +1,41 @@ +package Database + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +func GetConversationDetailUserById(id string) (Models.ConversationDetailUser, error) { + var ( + messageThread Models.ConversationDetailUser + err error + ) + + err = DB.Preload(clause.Associations). + Where("id = ?", id). + First(&messageThread). + Error + + return messageThread, err +} + +func CreateConversationDetailUser(messageThread *Models.ConversationDetailUser) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(messageThread). + Error +} + +func UpdateConversationDetailUser(messageThread *Models.ConversationDetailUser) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Where("id = ?", messageThread.ID). + Updates(messageThread). + Error +} + +func DeleteConversationDetailUser(messageThread *Models.ConversationDetailUser) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Delete(messageThread). + Error +} diff --git a/Backend/Database/Init.go b/Backend/Database/Init.go index 6241fdb..4124949 100644 --- a/Backend/Database/Init.go +++ b/Backend/Database/Init.go @@ -24,6 +24,7 @@ func GetModels() []interface{} { &Models.MessageData{}, &Models.Message{}, &Models.ConversationDetail{}, + &Models.ConversationDetailUser{}, &Models.UserConversation{}, } } diff --git a/Backend/Database/Messages.go b/Backend/Database/Messages.go index 0affa34..67cf8d3 100644 --- a/Backend/Database/Messages.go +++ b/Backend/Database/Messages.go @@ -20,7 +20,7 @@ func GetMessageById(id string) (Models.Message, error) { return message, err } -func GetMessagesByThreadKey(associationKey string) ([]Models.Message, error) { +func GetMessagesByAssociationKey(associationKey string) ([]Models.Message, error) { var ( messages []Models.Message err error @@ -34,9 +34,7 @@ func GetMessagesByThreadKey(associationKey string) ([]Models.Message, error) { } func CreateMessage(message *Models.Message) error { - var ( - err error - ) + var err error err = DB.Session(&gorm.Session{FullSaveAssociations: true}). Create(message). @@ -46,9 +44,7 @@ func CreateMessage(message *Models.Message) error { } func CreateMessages(messages *[]Models.Message) error { - var ( - err error - ) + var err error err = DB.Session(&gorm.Session{FullSaveAssociations: true}). Create(messages). diff --git a/Backend/Database/Seeder/MessageSeeder.go b/Backend/Database/Seeder/MessageSeeder.go index 0aa750f..dc9a221 100644 --- a/Backend/Database/Seeder/MessageSeeder.go +++ b/Backend/Database/Seeder/MessageSeeder.go @@ -2,7 +2,6 @@ package Seeder import ( "encoding/base64" - "fmt" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" @@ -115,39 +114,19 @@ func seedConversationDetail(key aesKey) (Models.ConversationDetail, error) { return messageThread, err } -func seedUpdateUserConversation( - userJson string, - key aesKey, - messageThread Models.ConversationDetail, -) (Models.ConversationDetail, error) { - var ( - usersCiphertext []byte - err error - ) - - usersCiphertext, err = key.aesEncrypt([]byte(userJson)) - if err != nil { - return messageThread, err - } - - messageThread.Users = base64.StdEncoding.EncodeToString(usersCiphertext) - err = Database.UpdateConversationDetail(&messageThread) - return messageThread, err -} - func seedUserConversation( user Models.User, threadID uuid.UUID, key aesKey, ) (Models.UserConversation, error) { var ( - messageThreadUser Models.UserConversation - threadIdCiphertext []byte - adminCiphertext []byte - err error + messageThreadUser Models.UserConversation + conversationDetailIDCiphertext []byte + adminCiphertext []byte + err error ) - threadIdCiphertext, err = key.aesEncrypt([]byte(threadID.String())) + conversationDetailIDCiphertext, err = key.aesEncrypt([]byte(threadID.String())) if err != nil { return messageThreadUser, err } @@ -159,7 +138,7 @@ func seedUserConversation( messageThreadUser = Models.UserConversation{ UserID: user.ID, - ConversationDetailID: base64.StdEncoding.EncodeToString(threadIdCiphertext), + ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext), Admin: base64.StdEncoding.EncodeToString(adminCiphertext), SymmetricKey: base64.StdEncoding.EncodeToString( encryptWithPublicKey(key.Key, decodedPublicKey), @@ -170,16 +149,78 @@ func seedUserConversation( return messageThreadUser, err } +func seedConversationDetailUser( + user Models.User, + conversationDetail Models.ConversationDetail, + associationKey uuid.UUID, + admin bool, + key aesKey, +) (Models.ConversationDetailUser, error) { + var ( + conversationDetailUser Models.ConversationDetailUser + + adminString string = "false" + + userIdCiphertext []byte + usernameCiphertext []byte + adminCiphertext []byte + associationKeyCiphertext []byte + publicKeyCiphertext []byte + + err error + ) + + if admin { + adminString = "true" + } + + userIdCiphertext, err = key.aesEncrypt([]byte(user.ID.String())) + if err != nil { + return conversationDetailUser, err + } + + usernameCiphertext, err = key.aesEncrypt([]byte(user.Username)) + if err != nil { + return conversationDetailUser, err + } + + adminCiphertext, err = key.aesEncrypt([]byte(adminString)) + if err != nil { + return conversationDetailUser, err + } + + associationKeyCiphertext, err = key.aesEncrypt([]byte(associationKey.String())) + if err != nil { + return conversationDetailUser, err + } + + publicKeyCiphertext, err = key.aesEncrypt([]byte(user.AsymmetricPublicKey)) + if err != nil { + return conversationDetailUser, err + } + + conversationDetailUser = Models.ConversationDetailUser{ + ConversationDetailID: conversationDetail.ID, + UserID: base64.StdEncoding.EncodeToString(userIdCiphertext), + Username: base64.StdEncoding.EncodeToString(usernameCiphertext), + Admin: base64.StdEncoding.EncodeToString(adminCiphertext), + AssociationKey: base64.StdEncoding.EncodeToString(associationKeyCiphertext), + PublicKey: base64.StdEncoding.EncodeToString(publicKeyCiphertext), + } + + err = Database.CreateConversationDetailUser(&conversationDetailUser) + + return conversationDetailUser, err +} + func SeedMessages() { var ( - messageThread Models.ConversationDetail + conversationDetail Models.ConversationDetail key aesKey primaryUser Models.User primaryUserAssociationKey uuid.UUID secondaryUser Models.User secondaryUserAssociationKey uuid.UUID - userJson string - id1, id2 uuid.UUID i int err error ) @@ -188,7 +229,7 @@ func SeedMessages() { if err != nil { panic(err) } - messageThread, err = seedConversationDetail(key) + conversationDetail, err = seedConversationDetail(key) primaryUserAssociationKey, err = uuid.NewV4() if err != nil { @@ -206,7 +247,7 @@ func SeedMessages() { _, err = seedUserConversation( primaryUser, - messageThread.ID, + conversationDetail.ID, key, ) if err != nil { @@ -220,53 +261,34 @@ func SeedMessages() { _, err = seedUserConversation( secondaryUser, - messageThread.ID, + conversationDetail.ID, key, ) - - id1, err = uuid.NewV4() if err != nil { panic(err) } - id2, err = uuid.NewV4() + + _, err = seedConversationDetailUser( + primaryUser, + conversationDetail, + primaryUserAssociationKey, + true, + key, + ) if err != nil { panic(err) } - userJson = fmt.Sprintf( - ` -[ - { - "id": "%s", - "user_id": "%s", - "username": "%s", - "admin": "true", - "association_key": "%s" - }, - { - "id": "%s", - "user_id": "%s", - "username": "%s", - "admin": "false", - "association_key": "%s" - } -] - `, - id1.String(), - primaryUser.ID.String(), - primaryUser.Username, - primaryUserAssociationKey.String(), - id2.String(), - secondaryUser.ID.String(), - secondaryUser.Username, - secondaryUserAssociationKey.String(), - ) - - messageThread, err = seedUpdateUserConversation( - userJson, + _, err = seedConversationDetailUser( + secondaryUser, + conversationDetail, + secondaryUserAssociationKey, + false, key, - messageThread, ) + if err != nil { + panic(err) + } for i = 0; i <= 20; i++ { err = seedMessage( diff --git a/Backend/Models/Conversations.go b/Backend/Models/Conversations.go new file mode 100644 index 0000000..586ff98 --- /dev/null +++ b/Backend/Models/Conversations.go @@ -0,0 +1,33 @@ +package Models + +import ( + "github.com/gofrs/uuid" +) + +type ConversationDetail struct { + Base + Name string `gorm:"not null" json:"name"` // Stored encrypted + Users []ConversationDetailUser ` json:"users"` +} + +type ConversationDetailUser struct { + Base + ConversationDetailID uuid.UUID `gorm:"not null" json:"conversation_detail_id"` + ConversationDetail ConversationDetail `gorm:"not null" json:"conversation"` + UserID string `gorm:"not null" json:"user_id"` // Stored encrypted + Username string `gorm:"not null" json:"username"` // Stored encrypted + Admin string `gorm:"not null" json:"admin"` // Stored encrypted + AssociationKey string `gorm:"not null" json:"association_key"` // Stored encrypted + PublicKey string `gorm:"not null" json:"public_key"` // Stored encrypted +} + +// Used to link the current user to their conversations +type UserConversation struct { + Base + UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` + User User ` json:"user"` + ConversationDetailID string `gorm:"not null" json:"conversation_detail_id"` // Stored encrypted + Admin string `gorm:"not null" json:"admin"` // Bool if user is admin of thread, stored encrypted + SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted + // TODO: Add association_key here +} diff --git a/Backend/Models/Messages.go b/Backend/Models/Messages.go index de32fca..663d72d 100644 --- a/Backend/Models/Messages.go +++ b/Backend/Models/Messages.go @@ -22,19 +22,3 @@ type Message struct { AssociationKey string `json:"association_key" gorm:"not null"` // TODO: This links all encrypted messages for a user in a thread together. Find a way to fix this CreatedAt time.Time `json:"created_at" gorm:"not null"` } - -type ConversationDetail struct { - Base - Name string `gorm:"not null" json:"name"` // Stored encrypted - Users string ` json:"users"` // Stored as encrypted JSON -} - -type UserConversation struct { - Base - UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` - User User ` json:"user"` - ConversationDetailID string `gorm:"not null" json:"conversation_detail_id"` // Stored encrypted - Admin string `gorm:"not null" json:"admin"` // Bool if user is admin of thread, stored encrypted - SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted - // TODO: Add association_key here -} diff --git a/Backend/main.go b/Backend/main.go index 00db155..634cac0 100644 --- a/Backend/main.go +++ b/Backend/main.go @@ -2,7 +2,7 @@ package main import ( "flag" - "fmt" + "log" "net/http" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api" @@ -37,7 +37,7 @@ func main() { Api.InitApiEndpoints(router) - fmt.Println("Listening on port :8080") + log.Println("Listening on port :8080") err = http.ListenAndServe(":8080", router) if err != nil { panic(err) diff --git a/README.md b/README.md index d1cb191..d52d837 100644 --- a/README.md +++ b/README.md @@ -4,14 +4,15 @@ Encrypted messaging app ## TODO -- Fix adding users to conversations -- Fix users recieving messages -- Fix the admin checks on conversation settings page -- Add admin checks to conversation settings page -- Add admin checks on backend -- Add errors to login / signup page -- Add errors when updating conversations -- Refactor the update conversations function -- Finish the friends list page -- Allow adding friends -- Finish the disappearing messages functionality +[x] Fix adding users to conversations +[x] Fix users recieving messages +[x] Fix the admin checks on conversation settings page +[x] Fix sending messages in a conversation that includes users that are not the current users friend +[x] Add admin checks to conversation settings page +[ ] Add admin checks on backend +[ ] Add errors to login / signup page +[ ] Add errors when updating conversations +[ ] Refactor the update conversations function +[ ] Finish the friends list page +[ ] Allow adding friends +[ ] Finish the disappearing messages functionality diff --git a/mobile/lib/models/conversation_users.dart b/mobile/lib/models/conversation_users.dart index fe68f58..73ab7ac 100644 --- a/mobile/lib/models/conversation_users.dart +++ b/mobile/lib/models/conversation_users.dart @@ -1,3 +1,10 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:Envelope/utils/encryption/aes_helper.dart'; +import 'package:Envelope/utils/encryption/crypto_utils.dart'; +import 'package:pointycastle/impl.dart'; + import '/models/conversations.dart'; import '/utils/storage/database.dart'; @@ -20,6 +27,7 @@ Future getConversationUser(Conversation conversation, String u conversationId: maps[0]['conversation_id'], username: maps[0]['username'], associationKey: maps[0]['association_key'], + publicKey: CryptoUtils.rsaPublicKeyFromPem(maps[0]['asymmetric_public_key']), admin: maps[0]['admin'] == 1, ); @@ -33,19 +41,60 @@ Future> getConversationUsers(Conversation conversation) a 'conversation_users', where: 'conversation_id = ?', whereArgs: [conversation.id], - orderBy: 'admin', + orderBy: 'username', ); - return List.generate(maps.length, (i) { + List conversationUsers = List.generate(maps.length, (i) { return ConversationUser( id: maps[i]['id'], userId: maps[i]['user_id'], conversationId: maps[i]['conversation_id'], username: maps[i]['username'], associationKey: maps[i]['association_key'], + publicKey: CryptoUtils.rsaPublicKeyFromPem(maps[i]['asymmetric_public_key']), admin: maps[i]['admin'] == 1, ); }); + + int index = 0; + List finalConversationUsers = []; + + for (ConversationUser conversationUser in conversationUsers) { + if (!conversationUser.admin) { + finalConversationUsers.add(conversationUser); + continue; + } + + finalConversationUsers.insert(index, conversationUser); + index++; + } + + return finalConversationUsers; +} + +Future>> getEncryptedConversationUsers(Conversation conversation, Uint8List symKey) async { + final db = await getDatabaseConnection(); + + final List> maps = await db.query( + 'conversation_users', + where: 'conversation_id = ?', + whereArgs: [conversation.id], + orderBy: 'username', + ); + + List> conversationUsers = List.generate(maps.length, (i) { + return { + 'id': maps[i]['id'], + 'conversation_id': maps[i]['conversation_id'], + 'user_id': AesHelper.aesEncrypt(symKey, Uint8List.fromList(maps[i]['user_id'].codeUnits)), + 'username': AesHelper.aesEncrypt(symKey, Uint8List.fromList(maps[i]['username'].codeUnits)), + 'association_key': AesHelper.aesEncrypt(symKey, Uint8List.fromList(maps[i]['association_key'].codeUnits)), + 'public_key': AesHelper.aesEncrypt(symKey, Uint8List.fromList(maps[i]['asymmetric_public_key'].codeUnits)), + 'admin': AesHelper.aesEncrypt(symKey, Uint8List.fromList((maps[i]['admin'] == 1 ? 'true' : 'false').codeUnits)), + }; + }); + + return conversationUsers; } class ConversationUser{ @@ -54,6 +103,7 @@ class ConversationUser{ String conversationId; String username; String associationKey; + RSAPublicKey publicKey; bool admin; ConversationUser({ required this.id, @@ -61,17 +111,47 @@ class ConversationUser{ required this.conversationId, required this.username, required this.associationKey, + required this.publicKey, required this.admin, }); - factory ConversationUser.fromJson(Map json, String conversationId) { + factory ConversationUser.fromJson(Map json, Uint8List symmetricKey) { + + String userId = AesHelper.aesDecrypt( + symmetricKey, + base64.decode(json['user_id']), + ); + + String username = AesHelper.aesDecrypt( + symmetricKey, + base64.decode(json['username']), + ); + + String associationKey = AesHelper.aesDecrypt( + symmetricKey, + base64.decode(json['association_key']), + ); + + String admin = AesHelper.aesDecrypt( + symmetricKey, + base64.decode(json['admin']), + ); + + String publicKeyString = AesHelper.aesDecrypt( + symmetricKey, + base64.decode(json['public_key']), + ); + + RSAPublicKey publicKey = CryptoUtils.rsaPublicKeyFromPem(publicKeyString); + return ConversationUser( id: json['id'], - userId: json['user_id'], - conversationId: conversationId, - username: json['username'], - associationKey: json['association_key'], - admin: json['admin'] == 'true', + conversationId: json['conversation_detail_id'], + userId: userId, + username: username, + associationKey: associationKey, + publicKey: publicKey, + admin: admin == 'true', ); } @@ -81,6 +161,7 @@ class ConversationUser{ 'user_id': userId, 'username': username, 'association_key': associationKey, + 'asymmetric_public_key': publicKeyPem(), 'admin': admin ? 'true' : 'false', }; } @@ -92,7 +173,12 @@ class ConversationUser{ 'conversation_id': conversationId, 'username': username, 'association_key': associationKey, + 'asymmetric_public_key': publicKeyPem(), 'admin': admin ? 1 : 0, }; } + + String publicKeyPem() { + return CryptoUtils.encodeRSAPublicKeyToPem(publicKey); + } } diff --git a/mobile/lib/models/conversations.dart b/mobile/lib/models/conversations.dart index 6e656da..6b10460 100644 --- a/mobile/lib/models/conversations.dart +++ b/mobile/lib/models/conversations.dart @@ -21,14 +21,12 @@ Future createConversation(String title, List friends) asyn var uuid = const Uuid(); final String conversationId = uuid.v4(); - final String conversationDetailId = uuid.v4(); Uint8List symmetricKey = AesHelper.deriveKey(generateRandomString(32)); Conversation conversation = Conversation( id: conversationId, userId: profile.id, - conversationDetailId: conversationDetailId, symmetricKey: base64.encode(symmetricKey), admin: true, name: title, @@ -50,6 +48,7 @@ Future createConversation(String title, List friends) asyn conversationId: conversationId, username: profile.username, associationKey: uuid.v4(), + publicKey: profile.publicKey!, admin: true, ).toMap(), conflictAlgorithm: ConflictAlgorithm.fail, @@ -64,6 +63,7 @@ Future createConversation(String title, List friends) asyn conversationId: conversationId, username: friend.username, associationKey: uuid.v4(), + publicKey: friend.publicKey, admin: false, ).toMap(), conflictAlgorithm: ConflictAlgorithm.replace, @@ -88,6 +88,7 @@ Future addUsersToConversation(Conversation conversation, List addUsersToConversation(Conversation conversation, List conversations, String id) { for (var conversation in conversations) { - if (conversation.conversationDetailId == id) { + if (conversation.id == id) { return conversation; } } @@ -123,7 +124,6 @@ Future getConversationById(String id) async { return Conversation( id: maps[0]['id'], userId: maps[0]['user_id'], - conversationDetailId: maps[0]['conversation_detail_id'], symmetricKey: maps[0]['symmetric_key'], admin: maps[0]['admin'] == 1, name: maps[0]['name'], @@ -142,7 +142,6 @@ Future> getConversations() async { return Conversation( id: maps[i]['id'], userId: maps[i]['user_id'], - conversationDetailId: maps[i]['conversation_detail_id'], symmetricKey: maps[i]['symmetric_key'], admin: maps[i]['admin'] == 1, name: maps[i]['name'], @@ -156,7 +155,6 @@ Future> getConversations() async { class Conversation { String id; String userId; - String conversationDetailId; String symmetricKey; bool admin; String name; @@ -166,7 +164,6 @@ class Conversation { Conversation({ required this.id, required this.userId, - required this.conversationDetailId, required this.symmetricKey, required this.admin, required this.name, @@ -181,7 +178,7 @@ class Conversation { privKey, ); - var detailId = AesHelper.aesDecrypt( + var id = AesHelper.aesDecrypt( symmetricKeyDecrypted, base64.decode(json['conversation_detail_id']), ); @@ -192,9 +189,8 @@ class Conversation { ); return Conversation( - id: json['id'], + id: id, userId: json['user_id'], - conversationDetailId: detailId, symmetricKey: base64.encode(symmetricKeyDecrypted), admin: admin == 'true', name: 'Unknown', @@ -208,16 +204,16 @@ class Conversation { var symKey = base64.decode(symmetricKey); - List users = await getConversationUsers(this); - if (!includeUsers) { return { - 'id': conversationDetailId, + 'id': id, 'name': AesHelper.aesEncrypt(symKey, Uint8List.fromList(name.codeUnits)), - 'users': AesHelper.aesEncrypt(symKey, Uint8List.fromList(jsonEncode(users).codeUnits)), + 'users': await getEncryptedConversationUsers(this, symKey), }; } + List users = await getConversationUsers(this); + List userConversations = []; for (ConversationUser user in users) { @@ -227,23 +223,23 @@ class Conversation { if (profile.id != user.userId) { Friend friend = await getFriendByFriendId(user.userId); - pubKey = CryptoUtils.rsaPublicKeyFromPem(friend.asymmetricPublicKey); + pubKey = friend.publicKey; newId = (const Uuid()).v4(); } userConversations.add({ 'id': newId, 'user_id': user.userId, - 'conversation_detail_id': AesHelper.aesEncrypt(symKey, Uint8List.fromList(conversationDetailId.codeUnits)), - 'admin': AesHelper.aesEncrypt(symKey, Uint8List.fromList((admin ? 'true' : 'false').codeUnits)), + 'conversation_detail_id': AesHelper.aesEncrypt(symKey, Uint8List.fromList(id.codeUnits)), + 'admin': AesHelper.aesEncrypt(symKey, Uint8List.fromList((user.admin ? 'true' : 'false').codeUnits)), 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt(symKey, pubKey)), }); } return { - 'id': conversationDetailId, + 'id': id, 'name': AesHelper.aesEncrypt(symKey, Uint8List.fromList(name.codeUnits)), - 'users': AesHelper.aesEncrypt(symKey, Uint8List.fromList(jsonEncode(users).codeUnits)), + 'users': await getEncryptedConversationUsers(this, symKey), 'user_conversations': userConversations, }; } @@ -252,7 +248,6 @@ class Conversation { return { 'id': id, 'user_id': userId, - 'conversation_detail_id': conversationDetailId, 'symmetric_key': symmetricKey, 'admin': admin ? 1 : 0, 'name': name, diff --git a/mobile/lib/models/friends.dart b/mobile/lib/models/friends.dart index 86d1537..5711e3a 100644 --- a/mobile/lib/models/friends.dart +++ b/mobile/lib/models/friends.dart @@ -21,7 +21,7 @@ class Friend{ String username; String friendId; String friendSymmetricKey; - String asymmetricPublicKey; + RSAPublicKey publicKey; String acceptedAt; bool? selected; Friend({ @@ -30,39 +30,41 @@ class Friend{ required this.username, required this.friendId, required this.friendSymmetricKey, - required this.asymmetricPublicKey, + required this.publicKey, required this.acceptedAt, this.selected, }); factory Friend.fromJson(Map json, RSAPrivateKey privKey) { - Uint8List friendIdDecrypted = CryptoUtils.rsaDecrypt( + Uint8List idDecrypted = CryptoUtils.rsaDecrypt( base64.decode(json['friend_id']), privKey, ); - Uint8List friendUsername = CryptoUtils.rsaDecrypt( + Uint8List username = CryptoUtils.rsaDecrypt( base64.decode(json['friend_username']), privKey, ); - Uint8List friendSymmetricKeyDecrypted = CryptoUtils.rsaDecrypt( + Uint8List symmetricKeyDecrypted = CryptoUtils.rsaDecrypt( base64.decode(json['symmetric_key']), privKey, ); - String asymmetricPublicKey = AesHelper.aesDecrypt( - friendSymmetricKeyDecrypted, + String publicKeyString = AesHelper.aesDecrypt( + symmetricKeyDecrypted, base64.decode(json['asymmetric_public_key']) ); + RSAPublicKey publicKey = CryptoUtils.rsaPublicKeyFromPem(publicKeyString); + return Friend( id: json['id'], userId: json['user_id'], - username: String.fromCharCodes(friendUsername), - friendId: String.fromCharCodes(friendIdDecrypted), - friendSymmetricKey: base64.encode(friendSymmetricKeyDecrypted), - asymmetricPublicKey: asymmetricPublicKey, + username: String.fromCharCodes(username), + friendId: String.fromCharCodes(idDecrypted), + friendSymmetricKey: base64.encode(symmetricKeyDecrypted), + publicKey: publicKey, acceptedAt: json['accepted_at'], ); } @@ -86,10 +88,14 @@ class Friend{ 'username': username, 'friend_id': friendId, 'symmetric_key': friendSymmetricKey, - 'asymmetric_public_key': asymmetricPublicKey, + 'asymmetric_public_key': publicKeyPem(), 'accepted_at': acceptedAt, }; } + + String publicKeyPem() { + return CryptoUtils.encodeRSAPublicKeyToPem(publicKey); + } } @@ -105,7 +111,7 @@ Future> getFriends() async { userId: maps[i]['user_id'], friendId: maps[i]['friend_id'], friendSymmetricKey: maps[i]['symmetric_key'], - asymmetricPublicKey: maps[i]['asymmetric_public_key'], + publicKey: CryptoUtils.rsaPublicKeyFromPem(maps[i]['asymmetric_public_key']), acceptedAt: maps[i]['accepted_at'], username: maps[i]['username'], ); @@ -126,12 +132,12 @@ Future getFriendByFriendId(String userId) async { } return Friend( - id: maps[0]['id'], - userId: maps[0]['user_id'], - friendId: maps[0]['friend_id'], - friendSymmetricKey: maps[0]['symmetric_key'], - asymmetricPublicKey: maps[0]['asymmetric_public_key'], - acceptedAt: maps[0]['accepted_at'], - username: maps[0]['username'], + id: maps[0]['id'], + userId: maps[0]['user_id'], + friendId: maps[0]['friend_id'], + friendSymmetricKey: maps[0]['symmetric_key'], + publicKey: CryptoUtils.rsaPublicKeyFromPem(maps[0]['asymmetric_public_key']), + acceptedAt: maps[0]['accepted_at'], + username: maps[0]['username'], ); } diff --git a/mobile/lib/models/messages.dart b/mobile/lib/models/messages.dart index f19f78c..e88594f 100644 --- a/mobile/lib/models/messages.dart +++ b/mobile/lib/models/messages.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'dart:typed_data'; import 'package:pointycastle/export.dart'; +import 'package:uuid/uuid.dart'; import '/models/conversation_users.dart'; import '/models/conversations.dart'; @@ -101,20 +102,20 @@ class Message { ); } - Future toJson(Conversation conversation, String messageDataId) async { + Future payloadJson(Conversation conversation, String messageId) async { MyProfile profile = await MyProfile.getProfile(); if (profile.publicKey == null) { throw Exception('Could not get profile.publicKey'); } + RSAPublicKey publicKey = profile.publicKey!; + final String messageDataId = (const Uuid()).v4(); + final userSymmetricKey = AesHelper.deriveKey(generateRandomString(32)); final symmetricKey = AesHelper.deriveKey(generateRandomString(32)); List> messages = []; - - String id = ''; - List conversationUsers = await getConversationUsers(conversation); for (var i = 0; i < conversationUsers.length; i++) { @@ -124,6 +125,7 @@ class Message { id = user.id; messages.add({ + 'id': messageId, 'message_data_id': messageDataId, 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt( userSymmetricKey, @@ -135,8 +137,8 @@ class Message { continue; } - Friend friend = await getFriendByFriendId(user.userId); - RSAPublicKey friendPublicKey = CryptoUtils.rsaPublicKeyFromPem(friend.asymmetricPublicKey); + ConversationUser conversationUser = await getConversationUser(conversation, user.userId); + RSAPublicKey friendPublicKey = conversationUser.publicKey; messages.add({ 'message_data_id': messageDataId, diff --git a/mobile/lib/utils/storage/conversations.dart b/mobile/lib/utils/storage/conversations.dart index a7fe2c0..b5aa0b9 100644 --- a/mobile/lib/utils/storage/conversations.dart +++ b/mobile/lib/utils/storage/conversations.dart @@ -41,7 +41,7 @@ Future updateConversations() async { privKey, ); conversations.add(conversation); - conversationsDetailIds.add(conversation.conversationDetailId); + conversationsDetailIds.add(conversation.id); } Map params = {}; @@ -78,17 +78,12 @@ Future updateConversations() async { conflictAlgorithm: ConflictAlgorithm.replace, ); - List usersData = json.decode( - AesHelper.aesDecrypt( - base64.decode(conversation.symmetricKey), - base64.decode(conversationDetailJson['users']), - ) - ); + List usersData = conversationDetailJson['users']; for (var i = 0; i < usersData.length; i++) { ConversationUser conversationUser = ConversationUser.fromJson( usersData[i] as Map, - conversation.id, + base64.decode(conversation.symmetricKey), ); await db.insert( diff --git a/mobile/lib/utils/storage/database.dart b/mobile/lib/utils/storage/database.dart index 4466f6d..9814bf8 100644 --- a/mobile/lib/utils/storage/database.dart +++ b/mobile/lib/utils/storage/database.dart @@ -35,7 +35,6 @@ Future getDatabaseConnection() async { CREATE TABLE IF NOT EXISTS conversations( id TEXT PRIMARY KEY, user_id TEXT, - conversation_detail_id TEXT, symmetric_key TEXT, admin INTEGER, name TEXT, @@ -51,9 +50,9 @@ Future getDatabaseConnection() async { user_id TEXT, conversation_id TEXT, username TEXT, - data TEXT, association_key TEXT, - admin INTEGER + admin INTEGER, + asymmetric_public_key TEXT ); '''); diff --git a/mobile/lib/utils/storage/messages.dart b/mobile/lib/utils/storage/messages.dart index d5978d8..b551672 100644 --- a/mobile/lib/utils/storage/messages.dart +++ b/mobile/lib/utils/storage/messages.dart @@ -16,12 +16,12 @@ Future sendMessage(Conversation conversation, String data) async { MyProfile profile = await MyProfile.getProfile(); var uuid = const Uuid(); - final String messageDataId = uuid.v4(); + final String messageId = uuid.v4(); ConversationUser currentUser = await getConversationUser(conversation, profile.id); Message message = Message( - id: messageDataId, + id: messageId, symmetricKey: '', userSymmetricKey: '', senderId: currentUser.userId, @@ -42,7 +42,7 @@ Future sendMessage(Conversation conversation, String data) async { String sessionCookie = await getSessionCookie(); - message.toJson(conversation, messageDataId) + message.payloadJson(conversation, messageId) .then((messageJson) { return http.post( Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/message'), diff --git a/mobile/lib/views/authentication/login.dart b/mobile/lib/views/authentication/login.dart index c1c7fb7..b608703 100644 --- a/mobile/lib/views/authentication/login.dart +++ b/mobile/lib/views/authentication/login.dart @@ -8,28 +8,28 @@ import '/utils/storage/session_cookie.dart'; class LoginResponse { final String status; final String message; - final String asymmetricPublicKey; - final String asymmetricPrivateKey; + final String publicKey; + final String privateKey; final String userId; final String username; const LoginResponse({ required this.status, required this.message, - required this.asymmetricPublicKey, - required this.asymmetricPrivateKey, + required this.publicKey, + required this.privateKey, required this.userId, required this.username, }); factory LoginResponse.fromJson(Map json) { return LoginResponse( - status: json['status'], - message: json['message'], - asymmetricPublicKey: json['asymmetric_public_key'], - asymmetricPrivateKey: json['asymmetric_private_key'], - userId: json['user_id'], - username: json['username'], + status: json['status'], + message: json['message'], + publicKey: json['asymmetric_public_key'], + privateKey: json['asymmetric_private_key'], + userId: json['user_id'], + username: json['username'], ); } } diff --git a/mobile/lib/views/authentication/signup.dart b/mobile/lib/views/authentication/signup.dart index 0847bf7..50ef4f0 100644 --- a/mobile/lib/views/authentication/signup.dart +++ b/mobile/lib/views/authentication/signup.dart @@ -28,7 +28,7 @@ Future signUp(context, String username, String password, String var rsaPubPem = CryptoUtils.encodeRSAPublicKeyToPem(keyPair.publicKey); var rsaPrivPem = CryptoUtils.encodeRSAPrivateKeyToPem(keyPair.privateKey); - var encRsaPriv = AesHelper.aesEncrypt(password, Uint8List.fromList(rsaPrivPem.codeUnits)); + String encRsaPriv = AesHelper.aesEncrypt(password, Uint8List.fromList(rsaPrivPem.codeUnits)); // TODO: Check for timeout here final resp = await http.post( diff --git a/mobile/lib/views/main/conversation/create_add_users.dart b/mobile/lib/views/main/conversation/create_add_users.dart index 1b9186f..e1ddf59 100644 --- a/mobile/lib/views/main/conversation/create_add_users.dart +++ b/mobile/lib/views/main/conversation/create_add_users.dart @@ -1,10 +1,7 @@ import 'package:flutter/material.dart'; -import '/models/conversations.dart'; import '/models/friends.dart'; -import '/utils/storage/conversations.dart'; import '/views/main/conversation/create_add_users_list.dart'; -import '/views/main/conversation/detail.dart'; class ConversationAddFriendsList extends StatefulWidget { final List friends; @@ -26,81 +23,81 @@ class _ConversationAddFriendsListState extends State @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - elevation: 0, - automaticallyImplyLeading: false, - flexibleSpace: SafeArea( - child: Container( - padding: const EdgeInsets.only(right: 16), - child: Row( - children: [ - IconButton( - onPressed: (){ - Navigator.pop(context); - }, - icon: const Icon(Icons.arrow_back), - ), - const SizedBox(width: 2,), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - friendsSelected.isEmpty ? - 'Select Friends' : - '${friendsSelected.length} Friends Selected', - style: const TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600 - ), - ), - ], - ), - ), - ], - ), + appBar: AppBar( + elevation: 0, + automaticallyImplyLeading: false, + flexibleSpace: SafeArea( + child: Container( + padding: const EdgeInsets.only(right: 16), + child: Row( + children: [ + IconButton( + onPressed: (){ + Navigator.pop(context); + }, + icon: const Icon(Icons.arrow_back), ), - ), - ), - body: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.only(top: 20,left: 16,right: 16), - child: TextField( - decoration: const InputDecoration( - hintText: "Search...", - prefixIcon: Icon( - Icons.search, - size: 20 - ), + const SizedBox(width: 2,), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + friendsSelected.isEmpty ? + 'Select Friends' : + '${friendsSelected.length} Friends Selected', + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600 ), - onChanged: (value) => filterSearchResults(value.toLowerCase()) - ), - ), - Padding( - padding: const EdgeInsets.only(top: 0,left: 16,right: 16), - child: list(), + ), + ], + ), ), - ], + ], + ), + ), ), - floatingActionButton: Padding( - padding: const EdgeInsets.only(right: 10, bottom: 10), - child: FloatingActionButton( - onPressed: () { - widget.saveCallback(friendsSelected); - - setState(() { - friendsSelected = []; - }); - }, - backgroundColor: Theme.of(context).colorScheme.primary, - child: friendsSelected.isEmpty ? - const Text('Skip') : - const Icon(Icons.add, size: 30), + ), + body: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 20,left: 16,right: 16), + child: TextField( + decoration: const InputDecoration( + hintText: "Search...", + prefixIcon: Icon( + Icons.search, + size: 20 + ), + ), + onChanged: (value) => filterSearchResults(value.toLowerCase()) ), + ), + Padding( + padding: const EdgeInsets.only(top: 0,left: 16,right: 16), + child: list(), + ), + ], + ), + floatingActionButton: Padding( + padding: const EdgeInsets.only(right: 10, bottom: 10), + child: FloatingActionButton( + onPressed: () { + widget.saveCallback(friendsSelected); + + setState(() { + friendsSelected = []; + }); + }, + backgroundColor: Theme.of(context).colorScheme.primary, + child: friendsSelected.isEmpty ? + const Text('Skip') : + const Icon(Icons.add, size: 30), ), + ), ); } @@ -111,10 +108,10 @@ class _ConversationAddFriendsListState extends State if(query.isNotEmpty) { List dummyListData = []; for (Friend friend in dummySearchList) { - if (friend.username.toLowerCase().contains(query)) { - dummyListData.add(friend); - } + if (friend.username.toLowerCase().contains(query)) { + dummyListData.add(friend); } + } setState(() { friends.clear(); friends.addAll(dummyListData); @@ -138,30 +135,30 @@ class _ConversationAddFriendsListState extends State Widget list() { if (friends.isEmpty) { return const Center( - child: Text('No Friends'), + child: Text('No Friends'), ); } return ListView.builder( - itemCount: friends.length, - shrinkWrap: true, - padding: const EdgeInsets.only(top: 16), - physics: const BouncingScrollPhysics(), - itemBuilder: (context, i) { - return ConversationAddFriendItem( - friend: friends[i], - isSelected: (bool value) { - setState(() { - widget.friends[i].selected = value; - if (value) { - friendsSelected.add(friends[i]); - return; - } - friendsSelected.remove(friends[i]); - }); + itemCount: friends.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 16), + physics: const BouncingScrollPhysics(), + itemBuilder: (context, i) { + return ConversationAddFriendItem( + friend: friends[i], + isSelected: (bool value) { + setState(() { + widget.friends[i].selected = value; + if (value) { + friendsSelected.add(friends[i]); + return; } - ); - }, + friendsSelected.remove(friends[i]); + }); + } + ); + }, ); } } diff --git a/mobile/lib/views/main/conversation/detail.dart b/mobile/lib/views/main/conversation/detail.dart index cdee4ac..922bb66 100644 --- a/mobile/lib/views/main/conversation/detail.dart +++ b/mobile/lib/views/main/conversation/detail.dart @@ -28,212 +28,136 @@ class _ConversationDetailState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - elevation: 0, - automaticallyImplyLeading: false, - flexibleSpace: SafeArea( - child: Container( - padding: const EdgeInsets.only(right: 16), - child: Row( - children: [ - IconButton( - onPressed: (){ - Navigator.pop(context); - }, - icon: Icon( - Icons.arrow_back, - color: Theme.of(context).appBarTheme.iconTheme?.color, - ), - ), - const SizedBox(width: 2,), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - widget.conversation.name, - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - color: Theme.of(context).appBarTheme.toolbarTextStyle?.color - ), - ), - ], - ), - ), - IconButton( - onPressed: (){ - Navigator.of(context).push( - MaterialPageRoute(builder: (context) => ConversationSettings(conversation: widget.conversation)), - ); - }, - icon: Icon( - Icons.settings, - color: Theme.of(context).appBarTheme.iconTheme?.color, - ), - ), - ], - ), - ), + appBar: AppBar( + elevation: 0, + automaticallyImplyLeading: false, + flexibleSpace: SafeArea( + child: Container( + padding: const EdgeInsets.only(right: 16), + child: Row( + children: [ + IconButton( + onPressed: (){ + Navigator.pop(context); + }, + icon: Icon( + Icons.arrow_back, + color: Theme.of(context).appBarTheme.iconTheme?.color, ), ), - body: Stack( + const SizedBox(width: 2,), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, children: [ - ListView.builder( - itemCount: messages.length, - shrinkWrap: true, - padding: const EdgeInsets.only(top: 10,bottom: 90), - reverse: true, - itemBuilder: (context, index) { - return Container( - padding: const EdgeInsets.only(left: 14,right: 14,top: 0,bottom: 0), - child: Align( - alignment: ( - messages[index].senderUsername == profile.username ? - Alignment.topRight : - Alignment.topLeft - ), - child: Column( - crossAxisAlignment: messages[index].senderUsername == profile.username ? - CrossAxisAlignment.end : - CrossAxisAlignment.start, - children: [ - Container( - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(20), - color: ( - messages[index].senderUsername == profile.username ? - Theme.of(context).colorScheme.primary : - Theme.of(context).colorScheme.tertiary - ), - ), - padding: const EdgeInsets.all(12), - child: Text( - messages[index].data, - style: TextStyle( - fontSize: 15, - color: messages[index].senderUsername == profile.username ? - Theme.of(context).colorScheme.onPrimary : - Theme.of(context).colorScheme.onTertiary, - ) - ), - ), - const SizedBox(height: 1.5), - Row( - mainAxisAlignment: messages[index].senderUsername == profile.username ? - MainAxisAlignment.end : - MainAxisAlignment.start, - children: [ - const SizedBox(width: 10), - usernameOrFailedToSend(index), - ], - ), - const SizedBox(height: 1.5), - Row( - mainAxisAlignment: messages[index].senderUsername == profile.username ? - MainAxisAlignment.end : - MainAxisAlignment.start, - children: [ - const SizedBox(width: 10), - Text( - convertToAgo(messages[index].createdAt), - textAlign: messages[index].senderUsername == profile.username ? - TextAlign.left : - TextAlign.right, - style: TextStyle( - fontSize: 12, - color: Colors.grey[500], - ), - ), - ], - ), - index != 0 ? - const SizedBox(height: 20) : - const SizedBox.shrink(), - ], - ) - ), - ); + Text( + widget.conversation.name, + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: Theme.of(context).appBarTheme.toolbarTextStyle?.color + ), + ), + ], + ), + ), + IconButton( + onPressed: (){ + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ConversationSettings(conversation: widget.conversation)), + ); + }, + icon: Icon( + Icons.settings, + color: Theme.of(context).appBarTheme.iconTheme?.color, + ), + ), + ], + ), + ), + ), + ), + body: Stack( + children: [ + messagesView(), + Align( + alignment: Alignment.bottomLeft, + child: ConstrainedBox( + constraints: const BoxConstraints( + maxHeight: 200.0, + ), + child: Container( + padding: const EdgeInsets.only(left: 10,bottom: 10,top: 10), + // height: 60, + width: double.infinity, + color: Theme.of(context).backgroundColor, + child: Row( + children: [ + GestureDetector( + onTap: (){ + }, + child: Container( + height: 30, + width: 30, + decoration: BoxDecoration( + color: Theme.of(context).primaryColor, + borderRadius: BorderRadius.circular(30), + ), + child: Icon( + Icons.add, + color: Theme.of(context).colorScheme.onPrimary, + size: 20 + ), + ), + ), + const SizedBox(width: 15,), + Expanded( + child: TextField( + decoration: InputDecoration( + hintText: "Write message...", + hintStyle: TextStyle( + color: Theme.of(context).hintColor, + ), + border: InputBorder.none, + ), + maxLines: null, + controller: msgController, + ), + ), + const SizedBox(width: 15), + Container( + width: 45, + height: 45, + child: FittedBox( + child: FloatingActionButton( + onPressed: () async { + if (msgController.text == '') { + return; + } + await sendMessage(widget.conversation, msgController.text); + messages = await getMessagesForThread(widget.conversation); + setState(() {}); + msgController.text = ''; }, + child: Icon( + Icons.send, + color: Theme.of(context).colorScheme.onPrimary, + size: 22 ), - Align( - alignment: Alignment.bottomLeft, - child: ConstrainedBox( - constraints: const BoxConstraints( - maxHeight: 200.0, - ), - child: Container( - padding: const EdgeInsets.only(left: 10,bottom: 10,top: 10), - // height: 60, - width: double.infinity, - color: Theme.of(context).backgroundColor, - child: Row( - children: [ - GestureDetector( - onTap: (){ - }, - child: Container( - height: 30, - width: 30, - decoration: BoxDecoration( - color: Theme.of(context).primaryColor, - borderRadius: BorderRadius.circular(30), - ), - child: Icon( - Icons.add, - color: Theme.of(context).colorScheme.onPrimary, - size: 20 - ), - ), - ), - const SizedBox(width: 15,), - Expanded( - child: TextField( - decoration: InputDecoration( - hintText: "Write message...", - hintStyle: TextStyle( - color: Theme.of(context).hintColor, - ), - border: InputBorder.none, - ), - maxLines: null, - controller: msgController, - ), - ), - const SizedBox(width: 15), - Container( - width: 45, - height: 45, - child: FittedBox( - child: FloatingActionButton( - onPressed: () async { - if (msgController.text == '') { - return; - } - await sendMessage(widget.conversation, msgController.text); - messages = await getMessagesForThread(widget.conversation); - setState(() {}); - msgController.text = ''; - }, - child: Icon( - Icons.send, - color: Theme.of(context).colorScheme.onPrimary, - size: 22 - ), - backgroundColor: Theme.of(context).primaryColor, - ), - ), - ), - const SizedBox(width: 10), - ], - ), - ), - ), + backgroundColor: Theme.of(context).primaryColor, + ), ), + ), + const SizedBox(width: 10), ], + ), + ), ), - ); + ), + ], + ), + ); } Future fetchMessages() async { @@ -251,32 +175,118 @@ class _ConversationDetailState extends State { Widget usernameOrFailedToSend(int index) { if (messages[index].senderUsername != profile.username) { return Text( - messages[index].senderUsername, - style: TextStyle( - fontSize: 12, - color: Colors.grey[300], - ), - ); + messages[index].senderUsername, + style: TextStyle( + fontSize: 12, + color: Colors.grey[300], + ), + ); } if (messages[index].failedToSend) { return Row( - mainAxisAlignment: MainAxisAlignment.end, - children: const [ - Icon( - Icons.warning_rounded, - color: Colors.red, - size: 20, - ), - Text( - 'Failed to send', - style: TextStyle(color: Colors.red, fontSize: 12), - textAlign: TextAlign.right, - ), - ], + mainAxisAlignment: MainAxisAlignment.end, + children: const [ + Icon( + Icons.warning_rounded, + color: Colors.red, + size: 20, + ), + Text( + 'Failed to send', + style: TextStyle(color: Colors.red, fontSize: 12), + textAlign: TextAlign.right, + ), + ], ); } return const SizedBox.shrink(); } + + Widget messagesView() { + if (messages.isEmpty) { + return const Center( + child: Text('No Messages'), + ); + } + + return ListView.builder( + itemCount: messages.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 10,bottom: 90), + reverse: true, + itemBuilder: (context, index) { + return Container( + padding: const EdgeInsets.only(left: 14,right: 14,top: 0,bottom: 0), + child: Align( + alignment: ( + messages[index].senderUsername == profile.username ? + Alignment.topRight : + Alignment.topLeft + ), + child: Column( + crossAxisAlignment: messages[index].senderUsername == profile.username ? + CrossAxisAlignment.end : + CrossAxisAlignment.start, + children: [ + Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + color: ( + messages[index].senderUsername == profile.username ? + Theme.of(context).colorScheme.primary : + Theme.of(context).colorScheme.tertiary + ), + ), + padding: const EdgeInsets.all(12), + child: Text( + messages[index].data, + style: TextStyle( + fontSize: 15, + color: messages[index].senderUsername == profile.username ? + Theme.of(context).colorScheme.onPrimary : + Theme.of(context).colorScheme.onTertiary, + ) + ), + ), + const SizedBox(height: 1.5), + Row( + mainAxisAlignment: messages[index].senderUsername == profile.username ? + MainAxisAlignment.end : + MainAxisAlignment.start, + children: [ + const SizedBox(width: 10), + usernameOrFailedToSend(index), + ], + ), + const SizedBox(height: 1.5), + Row( + mainAxisAlignment: messages[index].senderUsername == profile.username ? + MainAxisAlignment.end : + MainAxisAlignment.start, + children: [ + const SizedBox(width: 10), + Text( + convertToAgo(messages[index].createdAt), + textAlign: messages[index].senderUsername == profile.username ? + TextAlign.left : + TextAlign.right, + style: TextStyle( + fontSize: 12, + color: Colors.grey[500], + ), + ), + ], + ), + index != 0 ? + const SizedBox(height: 20) : + const SizedBox.shrink(), + ], + ) + ), + ); + }, + ); + } } diff --git a/mobile/lib/views/main/conversation/settings.dart b/mobile/lib/views/main/conversation/settings.dart index cc6991b..cbc06bf 100644 --- a/mobile/lib/views/main/conversation/settings.dart +++ b/mobile/lib/views/main/conversation/settings.dart @@ -1,4 +1,5 @@ import 'package:Envelope/models/friends.dart'; +import 'package:Envelope/utils/encryption/crypto_utils.dart'; import 'package:Envelope/views/main/conversation/create_add_users.dart'; import 'package:flutter/material.dart'; @@ -31,111 +32,113 @@ class _ConversationSettingsState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - elevation: 0, - automaticallyImplyLeading: false, - flexibleSpace: SafeArea( - child: Container( - padding: const EdgeInsets.only(right: 16), - child: Row( - children: [ - IconButton( - onPressed: (){ - Navigator.pop(context); - }, - icon: const Icon(Icons.arrow_back), - ), - const SizedBox(width: 2,), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - widget.conversation.name + " Settings", - style: const TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600 - ), - ), - ], - ), - ), - ], - ), + appBar: AppBar( + elevation: 0, + automaticallyImplyLeading: false, + flexibleSpace: SafeArea( + child: Container( + padding: const EdgeInsets.only(right: 16), + child: Row( + children: [ + IconButton( + onPressed: (){ + Navigator.pop(context); + }, + icon: const Icon(Icons.arrow_back), ), + const SizedBox(width: 2,), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + widget.conversation.name + " Settings", + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600 + ), + ), + ], + ), + ), + ], + ), ), ), - body: Padding( - padding: const EdgeInsets.all(15), - child: Column( - children: [ - const SizedBox(height: 30), - conversationName(), - const SizedBox(height: 25), - widget.conversation.admin ? - sectionTitle('Settings') : - const SizedBox.shrink(), - widget.conversation.admin ? - settings() : - const SizedBox.shrink(), - widget.conversation.admin ? - const SizedBox(height: 25) : - const SizedBox.shrink(), - sectionTitle('Members', showUsersAdd: true), - usersList(), - const SizedBox(height: 25), - myAccess(), - ], + ), + body: Padding( + padding: const EdgeInsets.all(15), + child: SingleChildScrollView( + child: Column( + children: [ + const SizedBox(height: 30), + conversationName(), + const SizedBox(height: 25), + widget.conversation.admin ? + sectionTitle('Settings') : + const SizedBox.shrink(), + widget.conversation.admin ? + settings() : + const SizedBox.shrink(), + widget.conversation.admin ? + const SizedBox(height: 25) : + const SizedBox.shrink(), + sectionTitle('Members', showUsersAdd: true), + usersList(), + const SizedBox(height: 25), + myAccess(), + ], ), ), + ), ); } Widget conversationName() { return Row( - children: [ - const CustomCircleAvatar( - icon: Icon(Icons.people, size: 40), - imagePath: null, // TODO: Add image here - radius: 30, - ), - const SizedBox(width: 10), - Text( - widget.conversation.name, - style: const TextStyle( - fontSize: 25, - fontWeight: FontWeight.w500, - ), + children: [ + const CustomCircleAvatar( + icon: Icon(Icons.people, size: 40), + imagePath: null, // TODO: Add image here + radius: 30, + ), + const SizedBox(width: 10), + Text( + widget.conversation.name, + style: const TextStyle( + fontSize: 25, + fontWeight: FontWeight.w500, ), - widget.conversation.admin ? IconButton( - iconSize: 20, - icon: const Icon(Icons.edit), - padding: const EdgeInsets.all(5.0), - splashRadius: 25, - onPressed: () { - Navigator.of(context).push( - MaterialPageRoute(builder: (context) => ConversationEditDetails( - saveCallback: (String conversationName) async { - widget.conversation.name = conversationName; + ), + widget.conversation.admin ? IconButton( + iconSize: 20, + icon: const Icon(Icons.edit), + padding: const EdgeInsets.all(5.0), + splashRadius: 25, + onPressed: () { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ConversationEditDetails( + saveCallback: (String conversationName) async { + widget.conversation.name = conversationName; - final db = await getDatabaseConnection(); - db.update( - 'conversations', - widget.conversation.toMap(), - where: 'id = ?', - whereArgs: [widget.conversation.id], - ); + final db = await getDatabaseConnection(); + db.update( + 'conversations', + widget.conversation.toMap(), + where: 'id = ?', + whereArgs: [widget.conversation.id], + ); - await updateConversation(widget.conversation, includeUsers: true); - setState(() {}); - Navigator.pop(context); - }, - conversation: widget.conversation, - )), - ).then(onGoBack); - }, - ) : const SizedBox.shrink(), + await updateConversation(widget.conversation, includeUsers: true); + setState(() {}); + Navigator.pop(context); + }, + conversation: widget.conversation, + )), + ).then(onGoBack); + }, + ) : const SizedBox.shrink(), ], ); } @@ -155,24 +158,24 @@ class _ConversationSettingsState extends State { Widget myAccess() { return Align( - alignment: Alignment.centerLeft, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - TextButton.icon( - label: const Text( - 'Leave Conversation', - style: TextStyle(fontSize: 16) - ), - icon: const Icon(Icons.exit_to_app), - style: const ButtonStyle( - alignment: Alignment.centerLeft, - ), - onPressed: () { - print('Leave Group'); - } + alignment: Alignment.centerLeft, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + TextButton.icon( + label: const Text( + 'Leave Conversation', + style: TextStyle(fontSize: 16) +), +icon: const Icon(Icons.exit_to_app), +style: const ButtonStyle( + alignment: Alignment.centerLeft, ), - ], + onPressed: () { + print('Leave Group'); + } + ), + ], ), ); } @@ -194,29 +197,29 @@ class _ConversationSettingsState extends State { ), ), !showUsersAdd ? - const SizedBox.shrink() : - IconButton( - icon: const Icon(Icons.add), - padding: const EdgeInsets.all(0), - onPressed: () async { - List friends = await unselectedFriends(); - Navigator.of(context).push( - MaterialPageRoute(builder: (context) => ConversationAddFriendsList( - friends: friends, - saveCallback: (List selectedFriends) async { - addUsersToConversation( - widget.conversation, - selectedFriends, - ); + const SizedBox.shrink() : + IconButton( + icon: const Icon(Icons.add), + padding: const EdgeInsets.all(0), + onPressed: () async { + List friends = await unselectedFriends(); + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ConversationAddFriendsList( + friends: friends, + saveCallback: (List selectedFriends) async { + addUsersToConversation( + widget.conversation, + selectedFriends, + ); - await updateConversation(widget.conversation, includeUsers: true); - await getUsers(); - Navigator.pop(context); - }, - )) - ); - }, - ), + await updateConversation(widget.conversation, includeUsers: true); + await getUsers(); + Navigator.pop(context); + }, + )) + ); + }, + ), ], ) ) @@ -225,64 +228,65 @@ class _ConversationSettingsState extends State { Widget settings() { return Align( - alignment: Alignment.centerLeft, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - const SizedBox(height: 5), - TextButton.icon( - label: const Text( - 'Disappearing Messages', - style: TextStyle(fontSize: 16) - ), - icon: const Icon(Icons.timer), - style: ButtonStyle( - alignment: Alignment.centerLeft, - foregroundColor: MaterialStateProperty.resolveWith( - (Set states) { - return Theme.of(context).colorScheme.onBackground; - }, - ) - ), - onPressed: () { - print('Disappearing Messages'); - } + alignment: Alignment.centerLeft, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const SizedBox(height: 5), + TextButton.icon( + label: const Text( + 'Disappearing Messages', + style: TextStyle(fontSize: 16) ), - TextButton.icon( - label: const Text( - 'Permissions', - style: TextStyle(fontSize: 16) - ), - icon: const Icon(Icons.lock), - style: ButtonStyle( - alignment: Alignment.centerLeft, - foregroundColor: MaterialStateProperty.resolveWith( - (Set states) { - return Theme.of(context).colorScheme.onBackground; - }, - ) - ), - onPressed: () { - print('Permissions'); - } + icon: const Icon(Icons.timer), + style: ButtonStyle( + alignment: Alignment.centerLeft, + foregroundColor: MaterialStateProperty.resolveWith( + (Set states) { + return Theme.of(context).colorScheme.onBackground; + }, + ) ), - ], + onPressed: () { + print('Disappearing Messages'); + } + ), + TextButton.icon( + label: const Text( + 'Permissions', + style: TextStyle(fontSize: 16) + ), + icon: const Icon(Icons.lock), + style: ButtonStyle( + alignment: Alignment.centerLeft, +foregroundColor: MaterialStateProperty.resolveWith( +(Set states) { +return Theme.of(context).colorScheme.onBackground; +}, + ) + ), + onPressed: () { + print('Permissions'); + } + ), + ], ), ); } Widget usersList() { return ListView.builder( - itemCount: users.length, - shrinkWrap: true, - padding: const EdgeInsets.only(top: 5, bottom: 0), - itemBuilder: (context, i) { - return ConversationSettingsUserListItem( - user: users[i], - isAdmin: widget.conversation.admin, - profile: profile!, // TODO: Fix this - ); - } + itemCount: users.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 5, bottom: 0), + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, i) { + return ConversationSettingsUserListItem( + user: users[i], + isAdmin: widget.conversation.admin, + profile: profile!, // TODO: Fix this + ); + } ); } @@ -291,8 +295,8 @@ class _ConversationSettingsState extends State { List notInArgs = []; for (var user in users) { - notInArgs.add(user.userId); - } + notInArgs.add(user.userId); + } final List> maps = await db.query( 'friends', @@ -307,7 +311,7 @@ class _ConversationSettingsState extends State { userId: maps[i]['user_id'], friendId: maps[i]['friend_id'], friendSymmetricKey: maps[i]['symmetric_key'], - asymmetricPublicKey: maps[i]['asymmetric_public_key'], + publicKey: CryptoUtils.rsaPublicKeyFromPem(maps[i]['asymmetric_public_key']), acceptedAt: maps[i]['accepted_at'], username: maps[i]['username'], ); diff --git a/mobile/lib/views/main/friend/list.dart b/mobile/lib/views/main/friend/list.dart index 40b8fd3..4e79fb1 100644 --- a/mobile/lib/views/main/friend/list.dart +++ b/mobile/lib/views/main/friend/list.dart @@ -21,65 +21,65 @@ class _FriendListState extends State { @override Widget build(BuildContext context) { return Scaffold( - body: SingleChildScrollView( - physics: const BouncingScrollPhysics(), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SafeArea( - child: Padding( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Text("Friends",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), - Container( - padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), - height: 30, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(20), - color: Theme.of(context).colorScheme.tertiary - ), - child: Row( - children: [ - Icon( - Icons.add, - color: Theme.of(context).primaryColor, - size: 20 - ), - const SizedBox(width: 2,), - const Text( - "Add", - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold - ) - ), - ], - ), - ) - ], + body: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SafeArea( + child: Padding( + padding: const EdgeInsets.only(left: 16,right: 16,top: 10), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text("Friends",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), + Container( + padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), + height: 30, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + color: Theme.of(context).colorScheme.tertiary + ), + child: Row( + children: [ + Icon( + Icons.add, + color: Theme.of(context).primaryColor, + size: 20 ), - ), - ), - Padding( - padding: const EdgeInsets.only(top: 16,left: 16,right: 16), - child: TextField( - decoration: const InputDecoration( - hintText: "Search...", - prefixIcon: Icon( - Icons.search, - size: 20 - ), - ), - onChanged: (value) => filterSearchResults(value.toLowerCase()) - ), + const SizedBox(width: 2,), + const Text( + "Add", + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold + ) + ), + ], + ), + ) + ], ), - Padding( - padding: const EdgeInsets.only(top: 16,left: 16,right: 16), - child: list(), + ), + ), + Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: TextField( + decoration: const InputDecoration( + hintText: "Search...", + prefixIcon: Icon( + Icons.search, + size: 20 + ), ), - ], + onChanged: (value) => filterSearchResults(value.toLowerCase()) + ), + ), + Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: list(), + ), + ], ), ), ); @@ -119,20 +119,20 @@ class _FriendListState extends State { Widget list() { if (friends.isEmpty) { return const Center( - child: Text('No Friends'), + child: Text('No Friends'), ); } return ListView.builder( - itemCount: friends.length, - shrinkWrap: true, - padding: const EdgeInsets.only(top: 16), - physics: const NeverScrollableScrollPhysics(), - itemBuilder: (context, i) { - return FriendListItem( - friend: friends[i], - ); - }, + itemCount: friends.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 16), + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, i) { + return FriendListItem( + friend: friends[i], + ); + }, ); } } -- 2.17.1 From 1f4d26165fac9ff86722114ab5133084c4475660 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Thu, 11 Aug 2022 19:23:58 +0930 Subject: [PATCH 19/24] Accept and reject friend requests Added custom error message for when interactions fail --- Backend/Api/Friends/AcceptFriendRequest.go | 75 ++++++ Backend/Api/Friends/EncryptedFriendsList.go | 9 +- Backend/Api/Friends/Friends.go | 33 +-- Backend/Api/Friends/RejectFriendRequest.go | 44 ++++ Backend/Api/Messages/Conversations.go | 14 +- Backend/Api/Messages/MessageThread.go | 9 +- Backend/Api/Routes.go | 34 +-- Backend/Api/Users/SearchUsers.go | 56 +++++ Backend/Database/FriendRequests.go | 24 +- Backend/Database/Seeder/FriendSeeder.go | 35 ++- Backend/Database/Users.go | 40 ++-- Backend/Models/Friends.go | 19 +- Backend/main.go | 2 +- mobile/analysis_options.yaml | 1 + .../lib/components/custom_expandable_fab.dart | 213 ++++++++++++++++++ mobile/lib/components/custom_title_bar.dart | 72 ++++++ mobile/lib/components/flash_message.dart | 60 +++++ mobile/lib/components/user_search_result.dart | 137 +++++++++++ mobile/lib/data_models/user_search.dart | 20 ++ mobile/lib/main.dart | 8 +- mobile/lib/models/friends.dart | 136 ++++++----- mobile/lib/utils/storage/conversations.dart | 48 ++-- mobile/lib/utils/storage/friends.dart | 9 +- mobile/lib/views/authentication/signup.dart | 41 ++-- .../lib/views/main/conversation/detail.dart | 51 +---- mobile/lib/views/main/conversation/list.dart | 136 ++++++----- .../lib/views/main/conversation/settings.dart | 41 +--- mobile/lib/views/main/friend/add_search.dart | 151 +++++++++++++ mobile/lib/views/main/friend/list.dart | 175 ++++++++------ mobile/lib/views/main/friend/list_item.dart | 64 +++--- .../views/main/friend/request_list_item.dart | 180 +++++++++++++++ mobile/lib/views/main/home.dart | 9 +- mobile/lib/views/main/profile/profile.dart | 68 +++--- 33 files changed, 1509 insertions(+), 505 deletions(-) create mode 100644 Backend/Api/Friends/AcceptFriendRequest.go create mode 100644 Backend/Api/Friends/RejectFriendRequest.go create mode 100644 Backend/Api/Users/SearchUsers.go create mode 100644 mobile/lib/components/custom_expandable_fab.dart create mode 100644 mobile/lib/components/custom_title_bar.dart create mode 100644 mobile/lib/components/flash_message.dart create mode 100644 mobile/lib/components/user_search_result.dart create mode 100644 mobile/lib/data_models/user_search.dart create mode 100644 mobile/lib/views/main/friend/add_search.dart create mode 100644 mobile/lib/views/main/friend/request_list_item.dart diff --git a/Backend/Api/Friends/AcceptFriendRequest.go b/Backend/Api/Friends/AcceptFriendRequest.go new file mode 100644 index 0000000..8ba80d1 --- /dev/null +++ b/Backend/Api/Friends/AcceptFriendRequest.go @@ -0,0 +1,75 @@ +package Friends + +import ( + "encoding/json" + "io/ioutil" + "net/http" + "time" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + "github.com/gorilla/mux" +) + +// AcceptFriendRequest accepts friend requests +func AcceptFriendRequest(w http.ResponseWriter, r *http.Request) { + var ( + oldFriendRequest Models.FriendRequest + newFriendRequest Models.FriendRequest + urlVars map[string]string + friendRequestID string + requestBody []byte + ok bool + err error + ) + + urlVars = mux.Vars(r) + friendRequestID, ok = urlVars["requestID"] + if !ok { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + oldFriendRequest, err = Database.GetFriendRequestByID(friendRequestID) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + oldFriendRequest.AcceptedAt.Time = time.Now() + oldFriendRequest.AcceptedAt.Valid = true + + requestBody, err = ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + err = json.Unmarshal(requestBody, &newFriendRequest) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + err = Database.UpdateFriendRequest(&oldFriendRequest) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + newFriendRequest.AcceptedAt.Time = time.Now() + newFriendRequest.AcceptedAt.Valid = true + + err = Database.CreateFriendRequest(&newFriendRequest) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusNoContent) +} diff --git a/Backend/Api/Friends/EncryptedFriendsList.go b/Backend/Api/Friends/EncryptedFriendsList.go index 441284f..410c75c 100644 --- a/Backend/Api/Friends/EncryptedFriendsList.go +++ b/Backend/Api/Friends/EncryptedFriendsList.go @@ -9,11 +9,12 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" ) +// EncryptedFriendRequestList gets friend request list func EncryptedFriendRequestList(w http.ResponseWriter, r *http.Request) { var ( userSession Models.Session friends []Models.FriendRequest - returnJson []byte + returnJSON []byte err error ) @@ -23,18 +24,18 @@ func EncryptedFriendRequestList(w http.ResponseWriter, r *http.Request) { return } - friends, err = Database.GetFriendRequestsByUserId(userSession.UserID.String()) + friends, err = Database.GetFriendRequestsByUserID(userSession.UserID.String()) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) return } - returnJson, err = json.MarshalIndent(friends, "", " ") + returnJSON, err = json.MarshalIndent(friends, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) - w.Write(returnJson) + w.Write(returnJSON) } diff --git a/Backend/Api/Friends/Friends.go b/Backend/Api/Friends/Friends.go index 050b4d8..07316af 100644 --- a/Backend/Api/Friends/Friends.go +++ b/Backend/Api/Friends/Friends.go @@ -7,37 +7,14 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" - "git.tovijaeschke.xyz/tovi/Envelope/Backend/Util" ) -func Friend(w http.ResponseWriter, r *http.Request) { - var ( - userData Models.User - returnJson []byte - err error - ) - - userData, err = Util.GetUserById(w, r) - if err != nil { - http.Error(w, "Not Found", http.StatusNotFound) - return - } - - returnJson, err = json.MarshalIndent(userData, "", " ") - if err != nil { - http.Error(w, "Error", http.StatusInternalServerError) - return - } - - w.WriteHeader(http.StatusOK) - w.Write(returnJson) -} - +// CreateFriendRequest creates a FriendRequest from post data func CreateFriendRequest(w http.ResponseWriter, r *http.Request) { var ( friendRequest Models.FriendRequest requestBody []byte - returnJson []byte + returnJSON []byte err error ) @@ -51,12 +28,14 @@ func CreateFriendRequest(w http.ResponseWriter, r *http.Request) { panic(err) } + friendRequest.AcceptedAt.Scan(nil) + err = Database.CreateFriendRequest(&friendRequest) if err != nil { panic(err) } - returnJson, err = json.MarshalIndent(friendRequest, "", " ") + returnJSON, err = json.MarshalIndent(friendRequest, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError) @@ -65,5 +44,5 @@ func CreateFriendRequest(w http.ResponseWriter, r *http.Request) { // Return updated json w.WriteHeader(http.StatusOK) - w.Write(returnJson) + w.Write(returnJSON) } diff --git a/Backend/Api/Friends/RejectFriendRequest.go b/Backend/Api/Friends/RejectFriendRequest.go new file mode 100644 index 0000000..b1b2c87 --- /dev/null +++ b/Backend/Api/Friends/RejectFriendRequest.go @@ -0,0 +1,44 @@ +package Friends + +import ( + "net/http" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "github.com/gorilla/mux" +) + +// RejectFriendRequest rejects friend requests +func RejectFriendRequest(w http.ResponseWriter, r *http.Request) { + var ( + friendRequest Models.FriendRequest + urlVars map[string]string + friendRequestID string + ok bool + err error + ) + + urlVars = mux.Vars(r) + friendRequestID, ok = urlVars["requestID"] + if !ok { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + friendRequest, err = Database.GetFriendRequestByID(friendRequestID) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + err = Database.DeleteFriendRequest(&friendRequest) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusNoContent) +} diff --git a/Backend/Api/Messages/Conversations.go b/Backend/Api/Messages/Conversations.go index 4475790..27d1470 100644 --- a/Backend/Api/Messages/Conversations.go +++ b/Backend/Api/Messages/Conversations.go @@ -11,11 +11,12 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" ) +// EncryptedConversationList returns an encrypted list of all Conversations func EncryptedConversationList(w http.ResponseWriter, r *http.Request) { var ( userConversations []Models.UserConversation userSession Models.Session - returnJson []byte + returnJSON []byte err error ) @@ -33,22 +34,23 @@ func EncryptedConversationList(w http.ResponseWriter, r *http.Request) { return } - returnJson, err = json.MarshalIndent(userConversations, "", " ") + returnJSON, err = json.MarshalIndent(userConversations, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) - w.Write(returnJson) + w.Write(returnJSON) } +// EncryptedConversationDetailsList returns an encrypted list of all ConversationDetails func EncryptedConversationDetailsList(w http.ResponseWriter, r *http.Request) { var ( userConversations []Models.ConversationDetail query url.Values conversationIds []string - returnJson []byte + returnJSON []byte ok bool err error ) @@ -71,12 +73,12 @@ func EncryptedConversationDetailsList(w http.ResponseWriter, r *http.Request) { return } - returnJson, err = json.MarshalIndent(userConversations, "", " ") + returnJSON, err = json.MarshalIndent(userConversations, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) - w.Write(returnJson) + w.Write(returnJSON) } diff --git a/Backend/Api/Messages/MessageThread.go b/Backend/Api/Messages/MessageThread.go index b9c4ee7..14fac7c 100644 --- a/Backend/Api/Messages/MessageThread.go +++ b/Backend/Api/Messages/MessageThread.go @@ -10,18 +10,19 @@ import ( "github.com/gorilla/mux" ) +// Messages gets messages by the associationKey func Messages(w http.ResponseWriter, r *http.Request) { var ( messages []Models.Message urlVars map[string]string associationKey string - returnJson []byte + returnJSON []byte ok bool err error ) urlVars = mux.Vars(r) - associationKey, ok = urlVars["threadKey"] + associationKey, ok = urlVars["associationKey"] if !ok { http.Error(w, "Not Found", http.StatusNotFound) return @@ -33,12 +34,12 @@ func Messages(w http.ResponseWriter, r *http.Request) { return } - returnJson, err = json.MarshalIndent(messages, "", " ") + returnJSON, err = json.MarshalIndent(messages, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) - w.Write(returnJson) + w.Write(returnJSON) } diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index e1f8df4..0143f90 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -7,6 +7,7 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Friends" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Messages" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Users" "github.com/gorilla/mux" ) @@ -38,10 +39,11 @@ func authenticationMiddleware(next http.Handler) http.Handler { }) } -func InitApiEndpoints(router *mux.Router) { +// InitAPIEndpoints initializes all API endpoints required by mobile app +func InitAPIEndpoints(router *mux.Router) { var ( api *mux.Router - authApi *mux.Router + authAPI *mux.Router ) log.Println("Initializing API routes...") @@ -54,22 +56,24 @@ func InitApiEndpoints(router *mux.Router) { api.HandleFunc("/login", Auth.Login).Methods("POST") api.HandleFunc("/logout", Auth.Logout).Methods("GET") - authApi = api.PathPrefix("/auth/").Subrouter() - authApi.Use(authenticationMiddleware) + authAPI = api.PathPrefix("/auth/").Subrouter() + authAPI.Use(authenticationMiddleware) - authApi.HandleFunc("/check", Auth.Check).Methods("GET") + authAPI.HandleFunc("/check", Auth.Check).Methods("GET") - // Define routes for friends and friend requests - authApi.HandleFunc("/friend_requests", Friends.EncryptedFriendRequestList).Methods("GET") - authApi.HandleFunc("/friend_request", Friends.CreateFriendRequest).Methods("POST") + authAPI.HandleFunc("/users", Users.SearchUsers).Methods("GET") - authApi.HandleFunc("/conversations", Messages.EncryptedConversationList).Methods("GET") - authApi.HandleFunc("/conversation_details", Messages.EncryptedConversationDetailsList).Methods("GET") + authAPI.HandleFunc("/friend_requests", Friends.EncryptedFriendRequestList).Methods("GET") + authAPI.HandleFunc("/friend_request", Friends.CreateFriendRequest).Methods("POST") + authAPI.HandleFunc("/friend_request/{requestID}", Friends.AcceptFriendRequest).Methods("POST") + authAPI.HandleFunc("/friend_request/{requestID}", Friends.RejectFriendRequest).Methods("DELETE") - authApi.HandleFunc("/conversations", Messages.CreateConversation).Methods("POST") - authApi.HandleFunc("/conversations", Messages.UpdateConversation).Methods("PUT") + authAPI.HandleFunc("/conversations", Messages.EncryptedConversationList).Methods("GET") + authAPI.HandleFunc("/conversation_details", Messages.EncryptedConversationDetailsList).Methods("GET") - // Define routes for messages - authApi.HandleFunc("/message", Messages.CreateMessage).Methods("POST") - authApi.HandleFunc("/messages/{threadKey}", Messages.Messages).Methods("GET") + authAPI.HandleFunc("/conversations", Messages.CreateConversation).Methods("POST") + authAPI.HandleFunc("/conversations", Messages.UpdateConversation).Methods("PUT") + + authAPI.HandleFunc("/message", Messages.CreateMessage).Methods("POST") + authAPI.HandleFunc("/messages/{associationKey}", Messages.Messages).Methods("GET") } diff --git a/Backend/Api/Users/SearchUsers.go b/Backend/Api/Users/SearchUsers.go new file mode 100644 index 0000000..56ecd89 --- /dev/null +++ b/Backend/Api/Users/SearchUsers.go @@ -0,0 +1,56 @@ +package Users + +import ( + "encoding/json" + "net/http" + "net/url" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +// SearchUsers searches a for a user by username +func SearchUsers(w http.ResponseWriter, r *http.Request) { + var ( + user Models.User + query url.Values + rawUsername []string + username string + returnJSON []byte + ok bool + err error + ) + + query = r.URL.Query() + rawUsername, ok = query["username"] + if !ok { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + if len(rawUsername) != 1 { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + username = rawUsername[0] + + user, err = Database.GetUserByUsername(username) + if err != nil { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + user.Password = "" + user.AsymmetricPrivateKey = "" + + returnJSON, err = json.MarshalIndent(user, "", " ") + if err != nil { + panic(err) + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + w.WriteHeader(http.StatusOK) + w.Write(returnJSON) +} diff --git a/Backend/Database/FriendRequests.go b/Backend/Database/FriendRequests.go index dec6860..f6393d5 100644 --- a/Backend/Database/FriendRequests.go +++ b/Backend/Database/FriendRequests.go @@ -7,7 +7,8 @@ import ( "gorm.io/gorm/clause" ) -func GetFriendRequestById(id string) (Models.FriendRequest, error) { +// GetFriendRequestByID gets friend request +func GetFriendRequestByID(id string) (Models.FriendRequest, error) { var ( friendRequest Models.FriendRequest err error @@ -20,7 +21,8 @@ func GetFriendRequestById(id string) (Models.FriendRequest, error) { return friendRequest, err } -func GetFriendRequestsByUserId(userID string) ([]Models.FriendRequest, error) { +// GetFriendRequestsByUserID gets friend request by user id +func GetFriendRequestsByUserID(userID string) ([]Models.FriendRequest, error) { var ( friends []Models.FriendRequest err error @@ -34,14 +36,22 @@ func GetFriendRequestsByUserId(userID string) ([]Models.FriendRequest, error) { return friends, err } -func CreateFriendRequest(FriendRequest *Models.FriendRequest) error { - return DB.Session(&gorm.Session{FullSaveAssociations: true}). - Create(FriendRequest). +// CreateFriendRequest creates friend request +func CreateFriendRequest(friendRequest *Models.FriendRequest) error { + return DB.Create(friendRequest). + Error +} + +// UpdateFriendRequest Updates friend request +func UpdateFriendRequest(friendRequest *Models.FriendRequest) error { + return DB.Where("id = ?", friendRequest.ID). + Updates(friendRequest). Error } -func DeleteFriendRequest(FriendRequest *Models.FriendRequest) error { +// DeleteFriendRequest deletes friend request +func DeleteFriendRequest(friendRequest *Models.FriendRequest) error { return DB.Session(&gorm.Session{FullSaveAssociations: true}). - Delete(FriendRequest). + Delete(friendRequest). Error } diff --git a/Backend/Database/Seeder/FriendSeeder.go b/Backend/Database/Seeder/FriendSeeder.go index 7b3f960..f3b5203 100644 --- a/Backend/Database/Seeder/FriendSeeder.go +++ b/Backend/Database/Seeder/FriendSeeder.go @@ -8,7 +8,7 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" ) -func seedFriend(userRequestTo, userRequestFrom Models.User) error { +func seedFriend(userRequestTo, userRequestFrom Models.User, accepted bool) error { var ( friendRequest Models.FriendRequest symKey aesKey @@ -27,9 +27,7 @@ func seedFriend(userRequestTo, userRequestFrom Models.User) error { } friendRequest = Models.FriendRequest{ - UserID: userRequestTo.ID, - UserUsername: userRequestTo.Username, - AcceptedAt: time.Now(), + UserID: userRequestTo.ID, FriendID: base64.StdEncoding.EncodeToString( encryptWithPublicKey( []byte(userRequestFrom.ID.String()), @@ -50,13 +48,20 @@ func seedFriend(userRequestTo, userRequestFrom Models.User) error { ), } + if accepted { + friendRequest.AcceptedAt.Time = time.Now() + friendRequest.AcceptedAt.Valid = true + } + return Database.CreateFriendRequest(&friendRequest) } +// SeedFriends creates dummy friends for testing/development func SeedFriends() { var ( primaryUser Models.User secondaryUser Models.User + accepted bool i int err error ) @@ -71,30 +76,38 @@ func SeedFriends() { panic(err) } - err = seedFriend(primaryUser, secondaryUser) + err = seedFriend(primaryUser, secondaryUser, true) if err != nil { panic(err) } - err = seedFriend(secondaryUser, primaryUser) + err = seedFriend(secondaryUser, primaryUser, true) if err != nil { panic(err) } - for i = 0; i <= 3; i++ { + accepted = false + + for i = 0; i <= 5; i++ { secondaryUser, err = Database.GetUserByUsername(userNames[i]) if err != nil { panic(err) } - err = seedFriend(primaryUser, secondaryUser) - if err != nil { - panic(err) + if i > 3 { + accepted = true } - err = seedFriend(secondaryUser, primaryUser) + err = seedFriend(primaryUser, secondaryUser, accepted) if err != nil { panic(err) } + + if accepted { + err = seedFriend(secondaryUser, primaryUser, accepted) + if err != nil { + panic(err) + } + } } } diff --git a/Backend/Database/Users.go b/Backend/Database/Users.go index 22e3f90..2df6a73 100644 --- a/Backend/Database/Users.go +++ b/Backend/Database/Users.go @@ -11,28 +11,28 @@ import ( func GetUserById(id string) (Models.User, error) { var ( - userData Models.User - err error + user Models.User + err error ) err = DB.Preload(clause.Associations). - First(&userData, "id = ?", id). + First(&user, "id = ?", id). Error - return userData, err + return user, err } func GetUserByUsername(username string) (Models.User, error) { var ( - userData Models.User - err error + user Models.User + err error ) err = DB.Preload(clause.Associations). - First(&userData, "username = ?", username). + First(&user, "username = ?", username). Error - return userData, err + return user, err } func CheckUniqueUsername(username string) error { @@ -58,26 +58,22 @@ func CheckUniqueUsername(username string) error { return nil } -func CreateUser(userData *Models.User) error { - var ( - err error - ) +func CreateUser(user *Models.User) error { + var err error err = DB.Session(&gorm.Session{FullSaveAssociations: true}). - Create(userData). + Create(user). Error return err } -func UpdateUser(id string, userData *Models.User) error { - var ( - err error - ) - err = DB.Model(&userData). +func UpdateUser(id string, user *Models.User) error { + var err error + err = DB.Model(&user). Omit("id"). Where("id = ?", id). - Updates(userData). + Updates(user). Error if err != nil { @@ -86,14 +82,14 @@ func UpdateUser(id string, userData *Models.User) error { err = DB.Model(Models.User{}). Where("id = ?", id). - First(userData). + First(user). Error return err } -func DeleteUser(userData *Models.User) error { +func DeleteUser(user *Models.User) error { return DB.Session(&gorm.Session{FullSaveAssociations: true}). - Delete(userData). + Delete(user). Error } diff --git a/Backend/Models/Friends.go b/Backend/Models/Friends.go index 183e2dc..967af7d 100644 --- a/Backend/Models/Friends.go +++ b/Backend/Models/Friends.go @@ -1,20 +1,19 @@ package Models import ( - "time" + "database/sql" "github.com/gofrs/uuid" ) -// Set with Friend being the requestee, and RequestFromID being the requester +// FriendRequest Set with Friend being the requestee, and RequestFromID being the requester type FriendRequest struct { Base - UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` - User User ` json:"user"` - UserUsername string ` json:"user_username"` - FriendID string `gorm:"not null" json:"friend_id"` // Stored encrypted - FriendUsername string ` json:"friend_username"` - FriendPublicAsymmetricKey string ` json:"asymmetric_public_key"` - SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted - AcceptedAt time.Time ` json:"accepted_at"` + UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` + User User ` json:"user"` + FriendID string `gorm:"not null" json:"friend_id"` // Stored encrypted + FriendUsername string ` json:"friend_username"` // Stored encrypted + FriendPublicAsymmetricKey string ` json:"asymmetric_public_key"` // Stored encrypted + SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted + AcceptedAt sql.NullTime ` json:"accepted_at"` } diff --git a/Backend/main.go b/Backend/main.go index 634cac0..e9dc701 100644 --- a/Backend/main.go +++ b/Backend/main.go @@ -35,7 +35,7 @@ func main() { router = mux.NewRouter() - Api.InitApiEndpoints(router) + Api.InitAPIEndpoints(router) log.Println("Listening on port :8080") err = http.ListenAndServe(":8080", router) diff --git a/mobile/analysis_options.yaml b/mobile/analysis_options.yaml index 61b6c4d..f630962 100644 --- a/mobile/analysis_options.yaml +++ b/mobile/analysis_options.yaml @@ -24,6 +24,7 @@ linter: rules: # avoid_print: false # Uncomment to disable the `avoid_print` rule # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + prefer_single_quotes: true # Additional information about this file can be found at # https://dart.dev/guides/language/analysis-options diff --git a/mobile/lib/components/custom_expandable_fab.dart b/mobile/lib/components/custom_expandable_fab.dart new file mode 100644 index 0000000..7b27e3c --- /dev/null +++ b/mobile/lib/components/custom_expandable_fab.dart @@ -0,0 +1,213 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + + +class ExpandableFab extends StatefulWidget { + const ExpandableFab({ + Key? key, + this.initialOpen, + required this.distance, + required this.icon, + required this.children, + }) : super(key: key); + + final bool? initialOpen; + final double distance; + final Icon icon; + final List children; + + @override + State createState() => _ExpandableFabState(); +} + +class _ExpandableFabState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _controller; + late final Animation _expandAnimation; + bool _open = false; + + @override + void initState() { + super.initState(); + _open = widget.initialOpen ?? false; + _controller = AnimationController( + value: _open ? 1.0 : 0.0, + duration: const Duration(milliseconds: 250), + vsync: this, + ); + _expandAnimation = CurvedAnimation( + curve: Curves.fastOutSlowIn, + reverseCurve: Curves.easeOutQuad, + parent: _controller, + ); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _toggle() { + setState(() { + _open = !_open; + if (_open) { + _controller.forward(); + } else { + _controller.reverse(); + } + }); + } + + @override + Widget build(BuildContext context) { + return SizedBox.expand( + child: Stack( + alignment: Alignment.bottomRight, + clipBehavior: Clip.none, + children: [ + _buildTapToCloseFab(), + ..._buildExpandingActionButtons(), + _buildTapToOpenFab(), + ], + ), + ); + } + + Widget _buildTapToCloseFab() { + return SizedBox( + width: 56.0, + height: 56.0, + child: Center( + child: Material( + shape: const CircleBorder(), + clipBehavior: Clip.antiAlias, + elevation: 4.0, + child: InkWell( + onTap: _toggle, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Icon( + Icons.close, + color: Theme.of(context).primaryColor, + ), + ), + ), + ), + ), + ); + } + + List _buildExpandingActionButtons() { + final children = []; + final count = widget.children.length; + final step = 60.0 / (count - 1); + for (var i = 0, angleInDegrees = 15.0; + i < count; + i++, angleInDegrees += step) { + children.add( + _ExpandingActionButton( + directionInDegrees: angleInDegrees, + maxDistance: widget.distance, + progress: _expandAnimation, + child: widget.children[i], + ), + ); + } + return children; + } + + Widget _buildTapToOpenFab() { + return IgnorePointer( + ignoring: _open, + child: AnimatedContainer( + transformAlignment: Alignment.center, + transform: Matrix4.diagonal3Values( + _open ? 0.7 : 1.0, + _open ? 0.7 : 1.0, + 1.0, + ), + duration: const Duration(milliseconds: 250), + curve: const Interval(0.0, 0.5, curve: Curves.easeOut), + child: AnimatedOpacity( + opacity: _open ? 0.0 : 1.0, + curve: const Interval(0.25, 1.0, curve: Curves.easeInOut), + duration: const Duration(milliseconds: 250), + child: FloatingActionButton( + onPressed: _toggle, + backgroundColor: Theme.of(context).colorScheme.primary, + child: widget.icon, + ), + ), + ), + ); + } +} + +@immutable +class _ExpandingActionButton extends StatelessWidget { + const _ExpandingActionButton({ + required this.directionInDegrees, + required this.maxDistance, + required this.progress, + required this.child, + }); + + final double directionInDegrees; + final double maxDistance; + final Animation progress; + final Widget child; + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: progress, + builder: (context, child) { + final offset = Offset.fromDirection( + directionInDegrees * (math.pi / 180.0), + progress.value * maxDistance, + ); + return Positioned( + right: 4.0 + offset.dx, + bottom: 4.0 + offset.dy, + child: Transform.rotate( + angle: (1.0 - progress.value) * math.pi / 2, + child: child!, + ), + ); + }, + child: FadeTransition( + opacity: progress, + child: child, + ), + ); + } +} + +class ActionButton extends StatelessWidget { + const ActionButton({ + Key? key, + this.onPressed, + required this.icon, + }) : super(key: key); + + final VoidCallback? onPressed; + final Widget icon; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Material( + shape: const CircleBorder(), + clipBehavior: Clip.antiAlias, + color: theme.colorScheme.secondary, + elevation: 4.0, + child: IconButton( + onPressed: onPressed, + icon: icon, + color: theme.colorScheme.onSecondary, + ), + ); + } +} diff --git a/mobile/lib/components/custom_title_bar.dart b/mobile/lib/components/custom_title_bar.dart new file mode 100644 index 0000000..527b1d2 --- /dev/null +++ b/mobile/lib/components/custom_title_bar.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; + +@immutable +class CustomTitleBar extends StatelessWidget with PreferredSizeWidget { + const CustomTitleBar({ + Key? key, + required this.title, + required this.showBack, + this.rightHandButton, + this.backgroundColor, + }) : super(key: key); + + final Text title; + final bool showBack; + final IconButton? rightHandButton; + final Color? backgroundColor; + + @override + Size get preferredSize => const Size.fromHeight(kToolbarHeight); + + @override + Widget build(BuildContext context) { + return AppBar( + elevation: 0, + automaticallyImplyLeading: false, + backgroundColor: + backgroundColor != null ? + backgroundColor! : + Theme.of(context).appBarTheme.backgroundColor, + flexibleSpace: SafeArea( + child: Container( + padding: const EdgeInsets.only(right: 16), + child: Row( + children: [ + showBack ? + _backButton(context) : + const SizedBox.shrink(), + showBack ? + const SizedBox(width: 2,) : + const SizedBox(width: 15), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + title, + ], + ), + ), + rightHandButton != null ? + rightHandButton! : + const SizedBox.shrink(), + ], + ), + ), + ), + ); + } + + Widget _backButton(BuildContext context) { + return IconButton( + onPressed: (){ + Navigator.pop(context); + }, + icon: Icon( + Icons.arrow_back, + color: Theme.of(context).appBarTheme.iconTheme?.color, + ), + ); + } +} + diff --git a/mobile/lib/components/flash_message.dart b/mobile/lib/components/flash_message.dart new file mode 100644 index 0000000..df5eb8f --- /dev/null +++ b/mobile/lib/components/flash_message.dart @@ -0,0 +1,60 @@ +import 'package:flutter/material.dart'; + +class FlashMessage extends StatelessWidget { + const FlashMessage({ + Key? key, + required this.message, + }) : super(key: key); + + final String message; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Stack( + clipBehavior: Clip.none, + children: [ + Container( + padding: const EdgeInsets.all(16), + height: 90, + decoration: BoxDecoration( + borderRadius: const BorderRadius.all(Radius.circular(20)), + color: theme.colorScheme.onError, + ), + child: Column( + children: [ + Text( + 'Error', + style: TextStyle( + color: theme.colorScheme.error, + fontSize: 18 + ), + ), + Text( + message, + style: TextStyle( + color: theme.colorScheme.error, + fontSize: 14 + ), + ), + ], + ), + ), + ] + ); + } +} + +void showMessage(String message, BuildContext context) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: FlashMessage( + message: message, + ), + behavior: SnackBarBehavior.floating, + backgroundColor: Colors.transparent, + elevation: 0, + ), + ); +} diff --git a/mobile/lib/components/user_search_result.dart b/mobile/lib/components/user_search_result.dart new file mode 100644 index 0000000..4b0155d --- /dev/null +++ b/mobile/lib/components/user_search_result.dart @@ -0,0 +1,137 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:http/http.dart' as http; +import 'package:pointycastle/impl.dart'; + +import '/components/custom_circle_avatar.dart'; +import '/data_models/user_search.dart'; +import '/models/my_profile.dart'; +import '/utils/encryption/aes_helper.dart'; +import '/utils/storage/session_cookie.dart'; +import '/utils/strings.dart'; +import '/utils/encryption/crypto_utils.dart'; + +@immutable +class UserSearchResult extends StatefulWidget { + final UserSearch user; + + const UserSearchResult({ + Key? key, + required this.user, + }) : super(key: key); + + @override + _UserSearchResultState createState() => _UserSearchResultState(); +} + +class _UserSearchResultState extends State{ + bool showFailed = false; + + @override + Widget build(BuildContext context) { + return Center( + child: Padding( + padding: const EdgeInsets.only(top: 30), + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + CustomCircleAvatar( + initials: widget.user.username[0].toUpperCase(), + icon: const Icon(Icons.person, size: 80), + imagePath: null, + radius: 50, + ), + const SizedBox(height: 10), + Text( + widget.user.username, + style: const TextStyle( + fontSize: 35, + ), + ), + const SizedBox(height: 30), + TextButton( + onPressed: sendFriendRequest, + child: Text( + 'Send Friend Request', + style: TextStyle( + color: Theme.of(context).colorScheme.onPrimary, + fontSize: 20, + ), + ), + style: ButtonStyle( + backgroundColor: MaterialStateProperty.all(Theme.of(context).colorScheme.primary), + padding: MaterialStateProperty.all( + const EdgeInsets.only(left: 20, right: 20, top: 8, bottom: 8)), + ), + ), + showFailed ? const SizedBox(height: 20) : const SizedBox.shrink(), + failedMessage(context), + ], + ), + ), + ); + } + + Widget failedMessage(BuildContext context) { + if (!showFailed) { + return const SizedBox.shrink(); + } + + return Text( + 'Failed to send friend request', + style: TextStyle( + color: Theme.of(context).colorScheme.error, + fontSize: 16, + ), + ); + } + + Future sendFriendRequest() async { + MyProfile profile = await MyProfile.getProfile(); + + String publicKeyString = CryptoUtils.encodeRSAPublicKeyToPem(profile.publicKey!); + + RSAPublicKey friendPublicKey = CryptoUtils.rsaPublicKeyFromPem(widget.user.publicKey); + + final symmetricKey = AesHelper.deriveKey(generateRandomString(32)); + + String payloadJson = jsonEncode({ + 'user_id': widget.user.id, + 'friend_id': base64.encode(CryptoUtils.rsaEncrypt( + Uint8List.fromList(profile.id.codeUnits), + friendPublicKey, + )), + 'friend_username': base64.encode(CryptoUtils.rsaEncrypt( + Uint8List.fromList(profile.username.codeUnits), + friendPublicKey, + )), + 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt( + Uint8List.fromList(symmetricKey), + friendPublicKey, + )), + 'asymmetric_public_key': AesHelper.aesEncrypt( + symmetricKey, + Uint8List.fromList(publicKeyString.codeUnits), + ), + }); + + var resp = await http.post( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friend_request'), + headers: { + 'cookie': await getSessionCookie(), + }, + body: payloadJson, + ); + + if (resp.statusCode != 200) { + showFailed = true; + setState(() {}); + return; + } + + Navigator.pop(context); + } +} diff --git a/mobile/lib/data_models/user_search.dart b/mobile/lib/data_models/user_search.dart new file mode 100644 index 0000000..6be8501 --- /dev/null +++ b/mobile/lib/data_models/user_search.dart @@ -0,0 +1,20 @@ + +class UserSearch { + String id; + String username; + String publicKey; + + UserSearch({ + required this.id, + required this.username, + required this.publicKey, + }); + + factory UserSearch.fromJson(Map json) { + return UserSearch( + id: json['id'], + username: json['username'], + publicKey: json['asymmetric_public_key'], + ); + } +} diff --git a/mobile/lib/main.dart b/mobile/lib/main.dart index 7890c86..656c188 100644 --- a/mobile/lib/main.dart +++ b/mobile/lib/main.dart @@ -48,17 +48,17 @@ class MyApp extends StatelessWidget { darkTheme: ThemeData( brightness: Brightness.dark, primaryColor: Colors.orange.shade900, - backgroundColor: Colors.grey.shade900, + backgroundColor: Colors.grey.shade800, colorScheme: ColorScheme( brightness: Brightness.dark, primary: Colors.orange.shade900, onPrimary: Colors.white, - secondary: Colors.blue.shade400, + secondary: Colors.orange.shade900, onSecondary: Colors.white, - tertiary: Colors.grey.shade600, + tertiary: Colors.grey.shade500, onTertiary: Colors.black, error: Colors.red, - onError: Colors.yellow, + onError: Colors.white, background: Colors.grey.shade900, onBackground: Colors.white, surface: Colors.grey.shade700, diff --git a/mobile/lib/models/friends.dart b/mobile/lib/models/friends.dart index 5711e3a..269a8ad 100644 --- a/mobile/lib/models/friends.dart +++ b/mobile/lib/models/friends.dart @@ -1,7 +1,9 @@ import 'dart:convert'; import 'dart:typed_data'; -import "package:pointycastle/export.dart"; -import '../utils/encryption/aes_helper.dart'; + +import 'package:pointycastle/export.dart'; + +import '/utils/encryption/aes_helper.dart'; import '/utils/encryption/crypto_utils.dart'; import '/utils/storage/database.dart'; @@ -12,7 +14,63 @@ Friend findFriendByFriendId(List friends, String id) { } } // Or return `null`. - throw ArgumentError.value(id, "id", "No element with that id"); + throw ArgumentError.value(id, 'id', 'No element with that id'); +} + +Future getFriendByFriendId(String userId) async { + final db = await getDatabaseConnection(); + + final List> maps = await db.query( + 'friends', + where: 'friend_id = ?', + whereArgs: [userId], + ); + + if (maps.length != 1) { + throw ArgumentError('Invalid user id'); + } + + return Friend( + id: maps[0]['id'], + userId: maps[0]['user_id'], + friendId: maps[0]['friend_id'], + friendSymmetricKey: maps[0]['symmetric_key'], + publicKey: CryptoUtils.rsaPublicKeyFromPem(maps[0]['asymmetric_public_key']), + acceptedAt: maps[0]['accepted_at'] != null ? DateTime.parse(maps[0]['accepted_at']) : null, + username: maps[0]['username'], + ); +} + + +Future> getFriends({bool? accepted}) async { + final db = await getDatabaseConnection(); + + String? where; + + if (accepted == true) { + where = 'accepted_at IS NOT NULL'; + } + + if (accepted == false) { + where = 'accepted_at IS NULL'; + } + + final List> maps = await db.query( + 'friends', + where: where, + ); + + return List.generate(maps.length, (i) { + return Friend( + id: maps[i]['id'], + userId: maps[i]['user_id'], + friendId: maps[i]['friend_id'], + friendSymmetricKey: maps[i]['symmetric_key'], + publicKey: CryptoUtils.rsaPublicKeyFromPem(maps[i]['asymmetric_public_key']), + acceptedAt: maps[i]['accepted_at'] != null ? DateTime.parse(maps[i]['accepted_at']) : null, + username: maps[i]['username'], + ); + }); } class Friend{ @@ -22,7 +80,7 @@ class Friend{ String friendId; String friendSymmetricKey; RSAPublicKey publicKey; - String acceptedAt; + DateTime? acceptedAt; bool? selected; Friend({ required this.id, @@ -65,20 +123,14 @@ class Friend{ friendId: String.fromCharCodes(idDecrypted), friendSymmetricKey: base64.encode(symmetricKeyDecrypted), publicKey: publicKey, - acceptedAt: json['accepted_at'], + acceptedAt: json['accepted_at']['Valid'] ? + DateTime.parse(json['accepted_at']['Time']) : + null, ); } - @override - String toString() { - return ''' - - - id: $id - userId: $userId - username: $username - friendId: $friendId - accepted_at: $acceptedAt'''; + String publicKeyPem() { + return CryptoUtils.encodeRSAPublicKeyToPem(publicKey); } Map toMap() { @@ -89,55 +141,19 @@ class Friend{ 'friend_id': friendId, 'symmetric_key': friendSymmetricKey, 'asymmetric_public_key': publicKeyPem(), - 'accepted_at': acceptedAt, + 'accepted_at': acceptedAt?.toIso8601String(), }; } - String publicKeyPem() { - return CryptoUtils.encodeRSAPublicKeyToPem(publicKey); - } -} - - -// A method that retrieves all the dogs from the dogs table. -Future> getFriends() async { - final db = await getDatabaseConnection(); - - final List> maps = await db.query('friends'); - - return List.generate(maps.length, (i) { - return Friend( - id: maps[i]['id'], - userId: maps[i]['user_id'], - friendId: maps[i]['friend_id'], - friendSymmetricKey: maps[i]['symmetric_key'], - publicKey: CryptoUtils.rsaPublicKeyFromPem(maps[i]['asymmetric_public_key']), - acceptedAt: maps[i]['accepted_at'], - username: maps[i]['username'], - ); - }); -} - -Future getFriendByFriendId(String userId) async { - final db = await getDatabaseConnection(); + @override + String toString() { + return ''' - final List> maps = await db.query( - 'friends', - where: 'friend_id = ?', - whereArgs: [userId], - ); - if (maps.length != 1) { - throw ArgumentError('Invalid user id'); + id: $id + userId: $userId + username: $username + friendId: $friendId + accepted_at: $acceptedAt'''; } - - return Friend( - id: maps[0]['id'], - userId: maps[0]['user_id'], - friendId: maps[0]['friend_id'], - friendSymmetricKey: maps[0]['symmetric_key'], - publicKey: CryptoUtils.rsaPublicKeyFromPem(maps[0]['asymmetric_public_key']), - acceptedAt: maps[0]['accepted_at'], - username: maps[0]['username'], - ); } diff --git a/mobile/lib/utils/storage/conversations.dart b/mobile/lib/utils/storage/conversations.dart index b5aa0b9..d5068d4 100644 --- a/mobile/lib/utils/storage/conversations.dart +++ b/mobile/lib/utils/storage/conversations.dart @@ -1,14 +1,34 @@ import 'dart:convert'; -import 'package:http/http.dart' as http; + import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:http/http.dart' as http; import 'package:pointycastle/export.dart'; import 'package:sqflite/sqflite.dart'; -import '/models/my_profile.dart'; -import '/models/conversations.dart'; + import '/models/conversation_users.dart'; +import '/models/conversations.dart'; +import '/models/my_profile.dart'; +import '/utils/encryption/aes_helper.dart'; import '/utils/storage/database.dart'; import '/utils/storage/session_cookie.dart'; -import '/utils/encryption/aes_helper.dart'; + +Future updateConversation(Conversation conversation, { includeUsers = true } ) async { + String sessionCookie = await getSessionCookie(); + + Map conversationJson = await conversation.payloadJson(includeUsers: includeUsers); + + var x = await http.put( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), + headers: { + 'Content-Type': 'application/json; charset=UTF-8', + 'cookie': sessionCookie, + }, + body: jsonEncode(conversationJson), + ); + + // TODO: Handle errors here + print(x.statusCode); +} // TODO: Refactor this function Future updateConversations() async { @@ -98,6 +118,7 @@ Future updateConversations() async { // } } + Future uploadConversation(Conversation conversation) async { String sessionCookie = await getSessionCookie(); @@ -116,22 +137,3 @@ Future uploadConversation(Conversation conversation) async { print(x.statusCode); } - -Future updateConversation(Conversation conversation, { includeUsers = true } ) async { - String sessionCookie = await getSessionCookie(); - - Map conversationJson = await conversation.payloadJson(includeUsers: includeUsers); - - var x = await http.put( - Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), - headers: { - 'Content-Type': 'application/json; charset=UTF-8', - 'cookie': sessionCookie, - }, - body: jsonEncode(conversationJson), - ); - - // TODO: Handle errors here - print(x.statusCode); -} - diff --git a/mobile/lib/utils/storage/friends.dart b/mobile/lib/utils/storage/friends.dart index 4da930c..9ed41eb 100644 --- a/mobile/lib/utils/storage/friends.dart +++ b/mobile/lib/utils/storage/friends.dart @@ -13,7 +13,7 @@ import '/utils/storage/session_cookie.dart'; Future updateFriends() async { RSAPrivateKey privKey = await MyProfile.getPrivateKey(); - try { + // try { var resp = await http.get( Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friend_requests'), headers: { @@ -42,9 +42,8 @@ Future updateFriends() async { ); } - - } catch (SocketException) { - return; - } + // } catch (SocketException) { + // return; + // } } diff --git a/mobile/lib/views/authentication/signup.dart b/mobile/lib/views/authentication/signup.dart index 50ef4f0..c9d3447 100644 --- a/mobile/lib/views/authentication/signup.dart +++ b/mobile/lib/views/authentication/signup.dart @@ -1,27 +1,13 @@ -import 'dart:typed_data'; import 'dart:convert'; +import 'dart:typed_data'; + import 'package:flutter/material.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:http/http.dart' as http; + import '/utils/encryption/aes_helper.dart'; import '/utils/encryption/crypto_utils.dart'; -class SignupResponse { - final String status; - final String message; - - const SignupResponse({ - required this.status, - required this.message, - }); - - factory SignupResponse.fromJson(Map json) { - return SignupResponse( - status: json['status'], - message: json['message'], - ); - } -} - Future signUp(context, String username, String password, String confirmPassword) async { var keyPair = CryptoUtils.generateRSAKeyPair(); @@ -32,7 +18,7 @@ Future signUp(context, String username, String password, String // TODO: Check for timeout here final resp = await http.post( - Uri.parse('http://192.168.1.5:8080/api/v1/signup'), + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/signup'), headers: { 'Content-Type': 'application/json; charset=UTF-8', }, @@ -80,6 +66,23 @@ class Signup extends StatelessWidget { } } +class SignupResponse { + final String status; + final String message; + + const SignupResponse({ + required this.status, + required this.message, + }); + + factory SignupResponse.fromJson(Map json) { + return SignupResponse( + status: json['status'], + message: json['message'], + ); + } +} + class SignupWidget extends StatefulWidget { const SignupWidget({Key? key}) : super(key: key); diff --git a/mobile/lib/views/main/conversation/detail.dart b/mobile/lib/views/main/conversation/detail.dart index 922bb66..667077f 100644 --- a/mobile/lib/views/main/conversation/detail.dart +++ b/mobile/lib/views/main/conversation/detail.dart @@ -1,3 +1,4 @@ +import 'package:Envelope/components/custom_title_bar.dart'; import 'package:flutter/material.dart'; import '/models/conversations.dart'; @@ -28,41 +29,17 @@ class _ConversationDetailState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - elevation: 0, - automaticallyImplyLeading: false, - flexibleSpace: SafeArea( - child: Container( - padding: const EdgeInsets.only(right: 16), - child: Row( - children: [ - IconButton( - onPressed: (){ - Navigator.pop(context); - }, - icon: Icon( - Icons.arrow_back, - color: Theme.of(context).appBarTheme.iconTheme?.color, - ), - ), - const SizedBox(width: 2,), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - widget.conversation.name, - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - color: Theme.of(context).appBarTheme.toolbarTextStyle?.color - ), - ), - ], - ), - ), - IconButton( + appBar: CustomTitleBar( + title: Text( + widget.conversation.name, + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: Theme.of(context).appBarTheme.toolbarTextStyle?.color + ), + ), + showBack: true, + rightHandButton: IconButton( onPressed: (){ Navigator.of(context).push( MaterialPageRoute(builder: (context) => ConversationSettings(conversation: widget.conversation)), @@ -73,10 +50,6 @@ class _ConversationDetailState extends State { color: Theme.of(context).appBarTheme.iconTheme?.color, ), ), - ], - ), - ), - ), ), body: Stack( children: [ diff --git a/mobile/lib/views/main/conversation/list.dart b/mobile/lib/views/main/conversation/list.dart index a41e6cf..155ae2a 100644 --- a/mobile/lib/views/main/conversation/list.dart +++ b/mobile/lib/views/main/conversation/list.dart @@ -1,3 +1,4 @@ +import 'package:Envelope/components/custom_title_bar.dart'; import 'package:Envelope/models/friends.dart'; import 'package:Envelope/utils/storage/conversations.dart'; import 'package:flutter/material.dart'; @@ -28,83 +29,72 @@ class _ConversationListState extends State { @override Widget build(BuildContext context) { return Scaffold( - body: SingleChildScrollView( - physics: const BouncingScrollPhysics(), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SafeArea( - child: Padding( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: const [ - Text( - 'Conversations', - style: TextStyle( - fontSize: 32, - fontWeight: FontWeight.bold - ) - ), - ], - ), - ), - ), - Padding( - padding: const EdgeInsets.only(top: 16,left: 16,right: 16), - child: TextField( - decoration: const InputDecoration( - hintText: "Search...", - prefixIcon: Icon( - Icons.search, - size: 20 - ), - ), - onChanged: (value) => filterSearchResults(value.toLowerCase()) - ), - ), - Padding( - padding: const EdgeInsets.only(top: 16,left: 16,right: 16), - child: list(), - ), - ], - ), + appBar: const CustomTitleBar( + title: Text( + 'Conversations', + style: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold + ) + ), + showBack: false, + backgroundColor: Colors.transparent, ), - floatingActionButton: Padding( - padding: const EdgeInsets.only(right: 10, bottom: 10), - child: FloatingActionButton( - onPressed: () { - Navigator.of(context).push( - MaterialPageRoute(builder: (context) => ConversationEditDetails( - saveCallback: (String conversationName) { - Navigator.of(context).push( - MaterialPageRoute(builder: (context) => ConversationAddFriendsList( - friends: friends, - saveCallback: (List friendsSelected) async { - Conversation conversation = await createConversation( - conversationName, - friendsSelected - ); + body: Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: SingleChildScrollView( + child: Column( + children: [ + TextField( + decoration: const InputDecoration( + hintText: "Search...", + prefixIcon: Icon( + Icons.search, + size: 20 + ), + ), + onChanged: (value) => filterSearchResults(value.toLowerCase()) + ), + list(), + ], + ), + ), + ), + floatingActionButton: Padding( + padding: const EdgeInsets.only(right: 10, bottom: 10), + child: FloatingActionButton( + onPressed: () { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ConversationEditDetails( + saveCallback: (String conversationName) { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ConversationAddFriendsList( + friends: friends, + saveCallback: (List friendsSelected) async { + Conversation conversation = await createConversation( + conversationName, + friendsSelected + ); - uploadConversation(conversation); + uploadConversation(conversation); - Navigator.of(context).popUntil((route) => route.isFirst); - Navigator.push(context, MaterialPageRoute(builder: (context){ - return ConversationDetail( - conversation: conversation, - ); - })); - }, - )) - ); - }, - )), - ).then(onGoBack); - }, - backgroundColor: Theme.of(context).colorScheme.primary, - child: const Icon(Icons.add, size: 30), - ), + Navigator.of(context).popUntil((route) => route.isFirst); + Navigator.push(context, MaterialPageRoute(builder: (context){ + return ConversationDetail( + conversation: conversation, + ); + })); + }, + )) + ); + }, + )), + ).then(onGoBack); + }, + backgroundColor: Theme.of(context).colorScheme.primary, + child: const Icon(Icons.add, size: 30), ), + ), ); } diff --git a/mobile/lib/views/main/conversation/settings.dart b/mobile/lib/views/main/conversation/settings.dart index cbc06bf..bc291f0 100644 --- a/mobile/lib/views/main/conversation/settings.dart +++ b/mobile/lib/views/main/conversation/settings.dart @@ -1,3 +1,4 @@ +import 'package:Envelope/components/custom_title_bar.dart'; import 'package:Envelope/models/friends.dart'; import 'package:Envelope/utils/encryption/crypto_utils.dart'; import 'package:Envelope/views/main/conversation/create_add_users.dart'; @@ -32,40 +33,16 @@ class _ConversationSettingsState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - elevation: 0, - automaticallyImplyLeading: false, - flexibleSpace: SafeArea( - child: Container( - padding: const EdgeInsets.only(right: 16), - child: Row( - children: [ - IconButton( - onPressed: (){ - Navigator.pop(context); - }, - icon: const Icon(Icons.arrow_back), - ), - const SizedBox(width: 2,), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - widget.conversation.name + " Settings", - style: const TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600 - ), - ), - ], - ), - ), - ], - ), + appBar: CustomTitleBar( + title: Text( + widget.conversation.name + " Settings", + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: Theme.of(context).appBarTheme.toolbarTextStyle?.color ), ), + showBack: true, ), body: Padding( padding: const EdgeInsets.all(15), diff --git a/mobile/lib/views/main/friend/add_search.dart b/mobile/lib/views/main/friend/add_search.dart new file mode 100644 index 0000000..08b09d3 --- /dev/null +++ b/mobile/lib/views/main/friend/add_search.dart @@ -0,0 +1,151 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; +import 'package:flutter_dotenv/flutter_dotenv.dart'; + +import '/utils/storage/session_cookie.dart'; +import '/components/user_search_result.dart'; +import '/data_models/user_search.dart'; + + +class FriendAddSearch extends StatefulWidget { + const FriendAddSearch({ + Key? key, + }) : super(key: key); + + @override + State createState() => _FriendAddSearchState(); +} + +class _FriendAddSearchState extends State { + UserSearch? user; + Text centerMessage = const Text('Search to add friends...'); + + TextEditingController searchController = TextEditingController(); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + elevation: 0, + automaticallyImplyLeading: false, + flexibleSpace: SafeArea( + child: Container( + padding: const EdgeInsets.only(right: 16), + child: Row( + children: [ + IconButton( + onPressed: () { + Navigator.pop(context); + }, + icon: Icon( + Icons.arrow_back, + color: Theme.of(context).appBarTheme.iconTheme?.color, + ), + ), + const SizedBox(width: 2), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + 'Add Friends', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: Theme.of(context).appBarTheme.toolbarTextStyle?.color + ) + ), + ], + ) + ) + ] + ), + ), + ), + ), + body: Stack( + children: [ + Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: TextField( + autofocus: true, + decoration: InputDecoration( + hintText: 'Search...', + prefixIcon: const Icon( + Icons.search, + size: 20 + ), + suffixIcon: Padding( + padding: const EdgeInsets.only(top: 4, bottom: 4, right: 8), + child: OutlinedButton( + style: ButtonStyle( + backgroundColor: MaterialStateProperty.all(Theme.of(context).colorScheme.secondary), + foregroundColor: MaterialStateProperty.all(Theme.of(context).colorScheme.onSecondary), + shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.0))), + elevation: MaterialStateProperty.all(4), + ), + onPressed: searchUsername, + child: const Icon(Icons.search, size: 25), + ), + ), + ), + controller: searchController, + ), + ), + Padding( + padding: const EdgeInsets.only(top: 90), + child: showFriend(), + ), + ], + ), + ); + } + + Widget showFriend() { + if (user == null) { + return Center( + child: centerMessage, + ); + } + + return UserSearchResult( + user: user!, + ); + } + + Future searchUsername() async { + if (searchController.text.isEmpty) { + return; + } + + Map params = {}; + params['username'] = searchController.text; + var uri = Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/users'); + uri = uri.replace(queryParameters: params); + + var resp = await http.get( + uri, + headers: { + 'cookie': await getSessionCookie(), + } + ); + + if (resp.statusCode != 200) { + user = null; + centerMessage = const Text('User not found'); + setState(() {}); + return; + } + + user = UserSearch.fromJson( + jsonDecode(resp.body) + ); + + setState(() {}); + FocusScope.of(context).unfocus(); + searchController.clear(); + } +} diff --git a/mobile/lib/views/main/friend/list.dart b/mobile/lib/views/main/friend/list.dart index 4e79fb1..82aa8be 100644 --- a/mobile/lib/views/main/friend/list.dart +++ b/mobile/lib/views/main/friend/list.dart @@ -1,13 +1,15 @@ +import 'package:Envelope/components/custom_title_bar.dart'; +import 'package:Envelope/views/main/friend/add_search.dart'; +import 'package:Envelope/views/main/friend/request_list_item.dart'; import 'package:flutter/material.dart'; import '/models/friends.dart'; +import '/components/custom_expandable_fab.dart'; import '/views/main/friend/list_item.dart'; class FriendList extends StatefulWidget { - final List friends; const FriendList({ Key? key, - required this.friends, }) : super(key: key); @override @@ -16,86 +18,83 @@ class FriendList extends StatefulWidget { class _FriendListState extends State { List friends = []; + List friendRequests = []; + List friendsDuplicate = []; + List friendRequestsDuplicate = []; @override Widget build(BuildContext context) { return Scaffold( - body: SingleChildScrollView( - physics: const BouncingScrollPhysics(), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SafeArea( - child: Padding( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Text("Friends",style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),), - Container( - padding: const EdgeInsets.only(left: 8,right: 8,top: 2,bottom: 2), - height: 30, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(20), - color: Theme.of(context).colorScheme.tertiary - ), - child: Row( - children: [ - Icon( - Icons.add, - color: Theme.of(context).primaryColor, - size: 20 - ), - const SizedBox(width: 2,), - const Text( - "Add", - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.bold - ) - ), - ], - ), - ) - ], - ), - ), - ), - Padding( - padding: const EdgeInsets.only(top: 16,left: 16,right: 16), - child: TextField( - decoration: const InputDecoration( - hintText: "Search...", - prefixIcon: Icon( - Icons.search, - size: 20 - ), - ), - onChanged: (value) => filterSearchResults(value.toLowerCase()) - ), - ), - Padding( - padding: const EdgeInsets.only(top: 16,left: 16,right: 16), - child: list(), - ), + appBar: const CustomTitleBar( + title: Text( + 'Friends', + style: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold + ) + ), + showBack: false, + backgroundColor: Colors.transparent, + ), + body: Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: SingleChildScrollView( + child: Column( + children: [ + TextField( + decoration: const InputDecoration( + hintText: 'Search...', + prefixIcon: Icon( + Icons.search, + size: 20 + ), + ), + onChanged: (value) => filterSearchResults(value.toLowerCase()) + ), + headingOrNull('Friend Requests'), + friendRequestList(), + headingOrNull('Friends'), + friendList(), ], ), ), + ), + floatingActionButton: Padding( + padding: const EdgeInsets.only(right: 10, bottom: 10), + child: ExpandableFab( + icon: const Icon(Icons.add, size: 30), + distance: 90.0, + children: [ + ActionButton( + onPressed: () {}, + icon: const Icon(Icons.qr_code_2, size: 25), + ), + ActionButton( + onPressed: () { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => const FriendAddSearch()) + );//.then(onGoBack); // TODO + }, + icon: const Icon(Icons.search, size: 25), + ), + ], + ) + ) ); } void filterSearchResults(String query) { List dummySearchList = []; - dummySearchList.addAll(widget.friends); + dummySearchList.addAll(friends); if(query.isNotEmpty) { List dummyListData = []; - dummySearchList.forEach((item) { + for (Friend item in dummySearchList) { if(item.username.toLowerCase().contains(query)) { dummyListData.add(item); } - }); + } setState(() { friends.clear(); friends.addAll(dummyListData); @@ -105,18 +104,62 @@ class _FriendListState extends State { setState(() { friends.clear(); - friends.addAll(widget.friends); + friends.addAll(friends); }); } @override void initState() { super.initState(); - friends.addAll(widget.friends); + initFriends(); + } + + Future initFriends() async { + friends = await getFriends(accepted: true); + friendRequests = await getFriends(accepted: false); setState(() {}); } - Widget list() { + Widget headingOrNull(String heading) { + if (friends.isEmpty || friendRequests.isEmpty) { + return const SizedBox.shrink(); + } + + return Padding( + padding: const EdgeInsets.only(top: 16), + child: Align( + alignment: Alignment.centerLeft, + child: Text( + heading, + style: TextStyle( + fontSize: 16, + color: Theme.of(context).colorScheme.tertiary, + ), + ), + ) + ); + } + + Widget friendRequestList() { + if (friendRequests.isEmpty) { + return const SizedBox.shrink(); + } + + return ListView.builder( + itemCount: friendRequests.length, + shrinkWrap: true, + padding: const EdgeInsets.only(top: 16), + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, i) { + return FriendRequestListItem( + friend: friendRequests[i], + callback: initFriends, + ); + }, + ); + } + + Widget friendList() { if (friends.isEmpty) { return const Center( child: Text('No Friends'), diff --git a/mobile/lib/views/main/friend/list_item.dart b/mobile/lib/views/main/friend/list_item.dart index fd13204..3610ff1 100644 --- a/mobile/lib/views/main/friend/list_item.dart +++ b/mobile/lib/views/main/friend/list_item.dart @@ -18,40 +18,40 @@ class _FriendListItemState extends State { @override Widget build(BuildContext context) { return GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () async { - }, - child: Container( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10,bottom: 10), - child: Row( - children: [ - Expanded( - child: Row( - children: [ - CustomCircleAvatar( - initials: widget.friend.username[0].toUpperCase(), - imagePath: null, - ), - const SizedBox(width: 16), - Expanded( - child: Align( - alignment: Alignment.centerLeft, - child: Container( - color: Colors.transparent, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(widget.friend.username, style: const TextStyle(fontSize: 16)), - ], - ), - ), - ), - ), - ], + behavior: HitTestBehavior.opaque, + onTap: () async { + }, + child: Container( + padding: const EdgeInsets.only(left: 16,right: 16,top: 0,bottom: 20), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CustomCircleAvatar( + initials: widget.friend.username[0].toUpperCase(), + imagePath: null, + ), + const SizedBox(width: 16), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: Container( + color: Colors.transparent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(widget.friend.username, style: const TextStyle(fontSize: 16)), + ], + ), ), + ), ), - ], - ), + ], + ), + ), + ], + ), ), ); } diff --git a/mobile/lib/views/main/friend/request_list_item.dart b/mobile/lib/views/main/friend/request_list_item.dart new file mode 100644 index 0000000..07c7e24 --- /dev/null +++ b/mobile/lib/views/main/friend/request_list_item.dart @@ -0,0 +1,180 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:Envelope/components/flash_message.dart'; +import 'package:Envelope/utils/storage/database.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:http/http.dart' as http; + +import '/components/custom_circle_avatar.dart'; +import '/models/friends.dart'; +import '/utils/storage/session_cookie.dart'; +import '/models/my_profile.dart'; +import '/utils/encryption/aes_helper.dart'; +import '/utils/encryption/crypto_utils.dart'; +import '/utils/strings.dart'; + + +class FriendRequestListItem extends StatefulWidget{ + final Friend friend; + final Function callback; + + const FriendRequestListItem({ + Key? key, + required this.friend, + required this.callback, + }) : super(key: key); + + @override + _FriendRequestListItemState createState() => _FriendRequestListItemState(); +} + +class _FriendRequestListItemState extends State { + + @override + Widget build(BuildContext context) { + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () async { + }, + child: Container( + padding: const EdgeInsets.only(left: 16,right: 10,top: 0,bottom: 20), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + CustomCircleAvatar( + initials: widget.friend.username[0].toUpperCase(), + imagePath: null, + ), + const SizedBox(width: 16), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: Container( + color: Colors.transparent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(widget.friend.username, style: const TextStyle(fontSize: 16)), + ], + ), + ), + ), + ), + SizedBox( + height: 30, + width: 30, + child: IconButton( + onPressed: () { acceptFriendRequest(context); }, + icon: const Icon(Icons.check), + padding: const EdgeInsets.all(0), + splashRadius: 20, + ), + ), + const SizedBox(width: 6), + SizedBox( + height: 30, + width: 30, + child: IconButton( + onPressed: rejectFriendRequest, + icon: const Icon(Icons.cancel), + padding: const EdgeInsets.all(0), + splashRadius: 20, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } + + Future acceptFriendRequest(BuildContext context) async { + MyProfile profile = await MyProfile.getProfile(); + + String publicKeyString = CryptoUtils.encodeRSAPublicKeyToPem(profile.publicKey!); + + final symmetricKey = AesHelper.deriveKey(generateRandomString(32)); + + String payloadJson = jsonEncode({ + 'user_id': widget.friend.userId, + 'friend_id': base64.encode(CryptoUtils.rsaEncrypt( + Uint8List.fromList(profile.id.codeUnits), + widget.friend.publicKey, + )), + 'friend_username': base64.encode(CryptoUtils.rsaEncrypt( + Uint8List.fromList(profile.username.codeUnits), + widget.friend.publicKey, + )), + 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt( + Uint8List.fromList(symmetricKey), + widget.friend.publicKey, + )), + 'asymmetric_public_key': AesHelper.aesEncrypt( + symmetricKey, + Uint8List.fromList(publicKeyString.codeUnits), + ), + }); + + var resp = await http.post( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friend_request/${widget.friend.id}'), + headers: { + 'cookie': await getSessionCookie(), + }, + body: payloadJson, + ); + + if (resp.statusCode != 204) { + showMessage( + 'Failed to accept friend request, please try again later', + context + ); + return; + } + + final db = await getDatabaseConnection(); + + widget.friend.acceptedAt = DateTime.now(); + + await db.update( + 'friends', + widget.friend.toMap(), + where: 'id = ?', + whereArgs: [widget.friend.id], + ); + + widget.callback(); + } + + Future rejectFriendRequest() async { + var resp = await http.delete( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friend_request/${widget.friend.id}'), + headers: { + 'cookie': await getSessionCookie(), + }, + ); + + if (resp.statusCode != 204) { + showMessage( + 'Failed to decline friend request, please try again later', + context + ); + return; + } + + final db = await getDatabaseConnection(); + + await db.delete( + 'friends', + where: 'id = ?', + whereArgs: [widget.friend.id], + ); + + widget.callback(); + } +} diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index 80f2be5..46e5765 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -23,6 +23,7 @@ class Home extends StatefulWidget { class _HomeState extends State { List conversations = []; List friends = []; + List friendRequests = []; MyProfile profile = MyProfile( id: '', username: '', @@ -32,7 +33,7 @@ class _HomeState extends State { int _selectedIndex = 0; List _widgetOptions = [ const ConversationList(conversations: [], friends: []), - const FriendList(friends: []), + const FriendList(), Profile( profile: MyProfile( id: '', @@ -134,7 +135,7 @@ class _HomeState extends State { children: const [ CircularProgressIndicator(), SizedBox(height: 25), - Text("Loading..."), + Text('Loading...'), ], ) ), @@ -152,7 +153,7 @@ class _HomeState extends State { await updateMessageThreads(); conversations = await getConversations(); - friends = await getFriends(); + friends = await getFriends(accepted: true); profile = await MyProfile.getProfile(); setState(() { @@ -161,7 +162,7 @@ class _HomeState extends State { conversations: conversations, friends: friends, ), - FriendList(friends: friends), + const FriendList(), Profile(profile: profile), ]; isLoading = false; diff --git a/mobile/lib/views/main/profile/profile.dart b/mobile/lib/views/main/profile/profile.dart index 4009961..5127da0 100644 --- a/mobile/lib/views/main/profile/profile.dart +++ b/mobile/lib/views/main/profile/profile.dart @@ -1,3 +1,4 @@ +import 'package:Envelope/components/custom_title_bar.dart'; import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:qr_flutter/qr_flutter.dart'; @@ -133,46 +134,31 @@ class _ProfileState extends State { @override Widget build(BuildContext context) { return Scaffold( - body: SingleChildScrollView( - physics: const BouncingScrollPhysics(), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SafeArea( - child: Padding( - padding: const EdgeInsets.only(left: 16,right: 16,top: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: const [ - Text( - 'Profile', - style: TextStyle( - fontSize: 32, - fontWeight: FontWeight.bold, - ), - ), - ], - ), - ), - ), - Padding( - padding: const EdgeInsets.only(top: 16,left: 16,right: 16), - child: Column( - children: [ - const SizedBox(height: 30), - usernameHeading(), - const SizedBox(height: 30), - _profileQrCode(), - const SizedBox(height: 30), - settings(), - const SizedBox(height: 30), - logout(), - ], - ) - ), - ], - ), + appBar: const CustomTitleBar( + title: Text( + 'Profile', + style: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold + ) ), - ); - } + showBack: false, + backgroundColor: Colors.transparent, + ), + body: Padding( + padding: const EdgeInsets.only(top: 16,left: 16,right: 16), + child: Column( + children: [ + usernameHeading(), + const SizedBox(height: 30), + _profileQrCode(), + const SizedBox(height: 30), + settings(), + const SizedBox(height: 30), + logout(), + ], + ) + ), + ); + } } -- 2.17.1 From b2e97646cddb506a15d48debccbd8216ed726070 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Thu, 11 Aug 2022 19:39:01 +0930 Subject: [PATCH 20/24] Fix accepting friend requests Fix "No Friends" flickering on tab change --- mobile/lib/views/main/friend/list.dart | 11 ++++++++++- .../lib/views/main/friend/request_list_item.dart | 2 +- mobile/lib/views/main/home.dart | 14 ++++++++++++-- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/mobile/lib/views/main/friend/list.dart b/mobile/lib/views/main/friend/list.dart index 82aa8be..ded6225 100644 --- a/mobile/lib/views/main/friend/list.dart +++ b/mobile/lib/views/main/friend/list.dart @@ -8,8 +8,15 @@ import '/components/custom_expandable_fab.dart'; import '/views/main/friend/list_item.dart'; class FriendList extends StatefulWidget { + final List friends; + final List friendRequests; + final Function callback; + const FriendList({ Key? key, + required this.friends, + required this.friendRequests, + required this.callback, }) : super(key: key); @override @@ -111,13 +118,15 @@ class _FriendListState extends State { @override void initState() { super.initState(); - initFriends(); + friends.addAll(widget.friends); + friendRequests.addAll(widget.friendRequests); } Future initFriends() async { friends = await getFriends(accepted: true); friendRequests = await getFriends(accepted: false); setState(() {}); + widget.callback(); } Widget headingOrNull(String heading) { diff --git a/mobile/lib/views/main/friend/request_list_item.dart b/mobile/lib/views/main/friend/request_list_item.dart index 07c7e24..21b81b0 100644 --- a/mobile/lib/views/main/friend/request_list_item.dart +++ b/mobile/lib/views/main/friend/request_list_item.dart @@ -102,7 +102,7 @@ class _FriendRequestListItemState extends State { final symmetricKey = AesHelper.deriveKey(generateRandomString(32)); String payloadJson = jsonEncode({ - 'user_id': widget.friend.userId, + 'user_id': widget.friend.friendId, 'friend_id': base64.encode(CryptoUtils.rsaEncrypt( Uint8List.fromList(profile.id.codeUnits), widget.friend.publicKey, diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index 46e5765..e740db0 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -33,7 +33,7 @@ class _HomeState extends State { int _selectedIndex = 0; List _widgetOptions = [ const ConversationList(conversations: [], friends: []), - const FriendList(), + FriendList(friends: const [], friendRequests: const [], callback: () {}), Profile( profile: MyProfile( id: '', @@ -154,6 +154,7 @@ class _HomeState extends State { conversations = await getConversations(); friends = await getFriends(accepted: true); + friendRequests = await getFriends(accepted: false); profile = await MyProfile.getProfile(); setState(() { @@ -162,13 +163,22 @@ class _HomeState extends State { conversations: conversations, friends: friends, ), - const FriendList(), + FriendList( + friends: friends, + friendRequests: friendRequests, + callback: initFriends, + ), Profile(profile: profile), ]; isLoading = false; }); } + Future initFriends() async { + friends = await getFriends(accepted: true); + friendRequests = await getFriends(accepted: false); + } + void _onItemTapped(int index) { setState(() { _selectedIndex = index; -- 2.17.1 From c120552a6afd5ca14a2119742bf9238b5778e762 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Fri, 12 Aug 2022 19:51:15 +0930 Subject: [PATCH 21/24] Open conversation from friend list --- Backend/Database/Seeder/MessageSeeder.go | 36 +++-- Backend/Models/Conversations.go | 10 +- mobile/lib/models/conversation_users.dart | 4 +- mobile/lib/models/conversations.dart | 68 +++++++++- mobile/lib/utils/storage/conversations.dart | 5 + mobile/lib/utils/storage/database.dart | 2 +- .../lib/views/main/conversation/detail.dart | 11 +- mobile/lib/views/main/conversation/list.dart | 3 +- .../views/main/conversation/list_item.dart | 124 +++++++++--------- mobile/lib/views/main/friend/list_item.dart | 22 +++- 10 files changed, 195 insertions(+), 90 deletions(-) diff --git a/Backend/Database/Seeder/MessageSeeder.go b/Backend/Database/Seeder/MessageSeeder.go index dc9a221..0480131 100644 --- a/Backend/Database/Seeder/MessageSeeder.go +++ b/Backend/Database/Seeder/MessageSeeder.go @@ -21,7 +21,7 @@ func seedMessage( keyCiphertext []byte plaintext string dataCiphertext []byte - senderIdCiphertext []byte + senderIDCiphertext []byte err error ) @@ -42,13 +42,13 @@ func seedMessage( panic(err) } - senderIdCiphertext, err = key.aesEncrypt([]byte(primaryUser.ID.String())) + senderIDCiphertext, err = key.aesEncrypt([]byte(primaryUser.ID.String())) if err != nil { panic(err) } if i%2 == 0 { - senderIdCiphertext, err = key.aesEncrypt([]byte(secondaryUser.ID.String())) + senderIDCiphertext, err = key.aesEncrypt([]byte(secondaryUser.ID.String())) if err != nil { panic(err) } @@ -63,7 +63,7 @@ func seedMessage( messageData = Models.MessageData{ Data: base64.StdEncoding.EncodeToString(dataCiphertext), - SenderID: base64.StdEncoding.EncodeToString(senderIdCiphertext), + SenderID: base64.StdEncoding.EncodeToString(senderIDCiphertext), SymmetricKey: base64.StdEncoding.EncodeToString(keyCiphertext), } @@ -93,10 +93,11 @@ func seedMessage( func seedConversationDetail(key aesKey) (Models.ConversationDetail, error) { var ( - messageThread Models.ConversationDetail - name string - nameCiphertext []byte - err error + messageThread Models.ConversationDetail + name string + nameCiphertext []byte + twoUserCiphertext []byte + err error ) name = "Test Conversation" @@ -106,8 +107,14 @@ func seedConversationDetail(key aesKey) (Models.ConversationDetail, error) { panic(err) } + twoUserCiphertext, err = key.aesEncrypt([]byte("false")) + if err != nil { + panic(err) + } + messageThread = Models.ConversationDetail{ - Name: base64.StdEncoding.EncodeToString(nameCiphertext), + Name: base64.StdEncoding.EncodeToString(nameCiphertext), + TwoUser: base64.StdEncoding.EncodeToString(twoUserCiphertext), } err = Database.CreateConversationDetail(&messageThread) @@ -159,14 +166,14 @@ func seedConversationDetailUser( var ( conversationDetailUser Models.ConversationDetailUser - adminString string = "false" - - userIdCiphertext []byte + userIDCiphertext []byte usernameCiphertext []byte adminCiphertext []byte associationKeyCiphertext []byte publicKeyCiphertext []byte + adminString = "false" + err error ) @@ -174,7 +181,7 @@ func seedConversationDetailUser( adminString = "true" } - userIdCiphertext, err = key.aesEncrypt([]byte(user.ID.String())) + userIDCiphertext, err = key.aesEncrypt([]byte(user.ID.String())) if err != nil { return conversationDetailUser, err } @@ -201,7 +208,7 @@ func seedConversationDetailUser( conversationDetailUser = Models.ConversationDetailUser{ ConversationDetailID: conversationDetail.ID, - UserID: base64.StdEncoding.EncodeToString(userIdCiphertext), + UserID: base64.StdEncoding.EncodeToString(userIDCiphertext), Username: base64.StdEncoding.EncodeToString(usernameCiphertext), Admin: base64.StdEncoding.EncodeToString(adminCiphertext), AssociationKey: base64.StdEncoding.EncodeToString(associationKeyCiphertext), @@ -213,6 +220,7 @@ func seedConversationDetailUser( return conversationDetailUser, err } +// SeedMessages seeds messages & conversations for testing func SeedMessages() { var ( conversationDetail Models.ConversationDetail diff --git a/Backend/Models/Conversations.go b/Backend/Models/Conversations.go index 586ff98..fa88987 100644 --- a/Backend/Models/Conversations.go +++ b/Backend/Models/Conversations.go @@ -4,12 +4,15 @@ import ( "github.com/gofrs/uuid" ) +// ConversationDetail stores the name for the conversation type ConversationDetail struct { Base - Name string `gorm:"not null" json:"name"` // Stored encrypted - Users []ConversationDetailUser ` json:"users"` + Name string `gorm:"not null" json:"name"` // Stored encrypted + Users []ConversationDetailUser ` json:"users"` + TwoUser string `gorm:"not null" json:"two_user"` } +// ConversationDetailUser all users associated with a customer type ConversationDetailUser struct { Base ConversationDetailID uuid.UUID `gorm:"not null" json:"conversation_detail_id"` @@ -21,7 +24,7 @@ type ConversationDetailUser struct { PublicKey string `gorm:"not null" json:"public_key"` // Stored encrypted } -// Used to link the current user to their conversations +// UserConversation Used to link the current user to their conversations type UserConversation struct { Base UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"` @@ -29,5 +32,4 @@ type UserConversation struct { ConversationDetailID string `gorm:"not null" json:"conversation_detail_id"` // Stored encrypted Admin string `gorm:"not null" json:"admin"` // Bool if user is admin of thread, stored encrypted SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted - // TODO: Add association_key here } diff --git a/mobile/lib/models/conversation_users.dart b/mobile/lib/models/conversation_users.dart index 73ab7ac..04ca747 100644 --- a/mobile/lib/models/conversation_users.dart +++ b/mobile/lib/models/conversation_users.dart @@ -14,7 +14,7 @@ Future getConversationUser(Conversation conversation, String u final List> maps = await db.query( 'conversation_users', where: 'conversation_id = ? AND user_id = ?', - whereArgs: [conversation.id, userId], + whereArgs: [ conversation.id, userId ], ); if (maps.length != 1) { @@ -40,7 +40,7 @@ Future> getConversationUsers(Conversation conversation) a final List> maps = await db.query( 'conversation_users', where: 'conversation_id = ?', - whereArgs: [conversation.id], + whereArgs: [ conversation.id ], orderBy: 'username', ); diff --git a/mobile/lib/models/conversations.dart b/mobile/lib/models/conversations.dart index 6b10460..69bc423 100644 --- a/mobile/lib/models/conversations.dart +++ b/mobile/lib/models/conversations.dart @@ -14,7 +14,7 @@ import '/utils/encryption/crypto_utils.dart'; import '/utils/storage/database.dart'; import '/utils/strings.dart'; -Future createConversation(String title, List friends) async { +Future createConversation(String title, List friends, bool twoUser) async { final db = await getDatabaseConnection(); MyProfile profile = await MyProfile.getProfile(); @@ -30,6 +30,7 @@ Future createConversation(String title, List friends) asyn symmetricKey: base64.encode(symmetricKey), admin: true, name: title, + twoUser: twoUser, status: ConversationStatus.pending, isRead: true, ); @@ -105,7 +106,7 @@ Conversation findConversationByDetailId(List conversations, String } } // Or return `null`. - throw ArgumentError.value(id, "id", "No element with that id"); + throw ArgumentError.value(id, 'id', 'No element with that id'); } Future getConversationById(String id) async { @@ -127,6 +128,7 @@ Future getConversationById(String id) async { symmetricKey: maps[0]['symmetric_key'], admin: maps[0]['admin'] == 1, name: maps[0]['name'], + twoUser: maps[0]['two_user'] == 1, status: ConversationStatus.values[maps[0]['status']], isRead: maps[0]['is_read'] == 1, ); @@ -145,12 +147,48 @@ Future> getConversations() async { symmetricKey: maps[i]['symmetric_key'], admin: maps[i]['admin'] == 1, name: maps[i]['name'], + twoUser: maps[i]['two_user'] == 1, status: ConversationStatus.values[maps[i]['status']], isRead: maps[i]['is_read'] == 1, ); }); } +Future getTwoUserConversation(String userId) async { + final db = await getDatabaseConnection(); + + MyProfile profile = await MyProfile.getProfile(); + + print(userId); + print(profile.id); + + final List> maps = await db.rawQuery( + ''' + SELECT conversations.* FROM conversations + LEFT JOIN conversation_users ON conversation_users.conversation_id = conversations.id + WHERE conversation_users.user_id = ? + AND conversation_users.user_id != ? + AND conversations.two_user = 1 + ''', + [ userId, profile.id ], + ); + + if (maps.length != 1) { + return null; + } + + return Conversation( + id: maps[0]['id'], + userId: maps[0]['user_id'], + symmetricKey: maps[0]['symmetric_key'], + admin: maps[0]['admin'] == 1, + name: maps[0]['name'], + twoUser: maps[0]['two_user'] == 1, + status: ConversationStatus.values[maps[0]['status']], + isRead: maps[0]['is_read'] == 1, + ); + +} class Conversation { String id; @@ -158,6 +196,7 @@ class Conversation { String symmetricKey; bool admin; String name; + bool twoUser; ConversationStatus status; bool isRead; @@ -167,6 +206,7 @@ class Conversation { required this.symmetricKey, required this.admin, required this.name, + required this.twoUser, required this.status, required this.isRead, }); @@ -194,6 +234,7 @@ class Conversation { symmetricKey: base64.encode(symmetricKeyDecrypted), admin: admin == 'true', name: 'Unknown', + twoUser: false, status: ConversationStatus.complete, isRead: true, ); @@ -251,6 +292,7 @@ class Conversation { 'symmetric_key': symmetricKey, 'admin': admin ? 1 : 0, 'name': name, + 'two_user': twoUser ? 1 : 0, 'status': status.index, 'is_read': isRead ? 1 : 0, }; @@ -297,6 +339,28 @@ class Conversation { failedToSend: maps[0]['failed_to_send'] == 1, ); } + + Future getName() async { + if (!twoUser) { + return name; + } + + MyProfile profile = await MyProfile.getProfile(); + + final db = await getDatabaseConnection(); + + List> maps = await db.query( + 'conversation_users', + where: 'conversation_id = ? AND user_id != ?', + whereArgs: [ id, profile.id ], + ); + + if (maps.length != 1) { + throw ArgumentError('Invalid user id'); + } + + return maps[0]['username']; + } } diff --git a/mobile/lib/utils/storage/conversations.dart b/mobile/lib/utils/storage/conversations.dart index d5068d4..f4722a3 100644 --- a/mobile/lib/utils/storage/conversations.dart +++ b/mobile/lib/utils/storage/conversations.dart @@ -92,6 +92,11 @@ Future updateConversations() async { base64.decode(conversationDetailJson['name']), ); + conversation.twoUser = AesHelper.aesDecrypt( + base64.decode(conversation.symmetricKey), + base64.decode(conversationDetailJson['two_user']), + ) == 'true'; + await db.insert( 'conversations', conversation.toMap(), diff --git a/mobile/lib/utils/storage/database.dart b/mobile/lib/utils/storage/database.dart index 9814bf8..e643f53 100644 --- a/mobile/lib/utils/storage/database.dart +++ b/mobile/lib/utils/storage/database.dart @@ -29,7 +29,6 @@ Future getDatabaseConnection() async { ); '''); - // TODO: Change users to use its own table, as it is a json blob await db.execute( ''' CREATE TABLE IF NOT EXISTS conversations( @@ -38,6 +37,7 @@ Future getDatabaseConnection() async { symmetric_key TEXT, admin INTEGER, name TEXT, + two_user INTEGER, status INTEGER, is_read INTEGER ); diff --git a/mobile/lib/views/main/conversation/detail.dart b/mobile/lib/views/main/conversation/detail.dart index 667077f..039ab16 100644 --- a/mobile/lib/views/main/conversation/detail.dart +++ b/mobile/lib/views/main/conversation/detail.dart @@ -21,6 +21,7 @@ class ConversationDetail extends StatefulWidget{ } class _ConversationDetailState extends State { + String conversationName = ''; List messages = []; MyProfile profile = MyProfile(id: '', username: ''); @@ -31,7 +32,7 @@ class _ConversationDetailState extends State { return Scaffold( appBar: CustomTitleBar( title: Text( - widget.conversation.name, + conversationName, style: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, @@ -42,7 +43,9 @@ class _ConversationDetailState extends State { rightHandButton: IconButton( onPressed: (){ Navigator.of(context).push( - MaterialPageRoute(builder: (context) => ConversationSettings(conversation: widget.conversation)), + MaterialPageRoute(builder: (context) => ConversationSettings( + conversation: widget.conversation + )), ); }, icon: Icon( @@ -51,6 +54,7 @@ class _ConversationDetailState extends State { ), ), ), + body: Stack( children: [ messagesView(), @@ -88,7 +92,7 @@ class _ConversationDetailState extends State { Expanded( child: TextField( decoration: InputDecoration( - hintText: "Write message...", + hintText: 'Write message...', hintStyle: TextStyle( color: Theme.of(context).hintColor, ), @@ -134,6 +138,7 @@ class _ConversationDetailState extends State { } Future fetchMessages() async { + conversationName = await widget.conversation.getName(); profile = await MyProfile.getProfile(); messages = await getMessagesForThread(widget.conversation); setState(() {}); diff --git a/mobile/lib/views/main/conversation/list.dart b/mobile/lib/views/main/conversation/list.dart index 155ae2a..a19887b 100644 --- a/mobile/lib/views/main/conversation/list.dart +++ b/mobile/lib/views/main/conversation/list.dart @@ -73,7 +73,8 @@ class _ConversationListState extends State { saveCallback: (List friendsSelected) async { Conversation conversation = await createConversation( conversationName, - friendsSelected + friendsSelected, + false, ); uploadConversation(conversation); diff --git a/mobile/lib/views/main/conversation/list_item.dart b/mobile/lib/views/main/conversation/list_item.dart index defc0da..5523204 100644 --- a/mobile/lib/views/main/conversation/list_item.dart +++ b/mobile/lib/views/main/conversation/list_item.dart @@ -19,83 +19,84 @@ class ConversationListItem extends StatefulWidget{ class _ConversationListItemState extends State { late Conversation conversation; + late String conversationName; late Message? recentMessage; bool loaded = false; @override Widget build(BuildContext context) { return GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - loaded ? Navigator.push(context, MaterialPageRoute(builder: (context){ - return ConversationDetail( - conversation: conversation, - ); - })).then(onGoBack) : null; - }, - child: Container( - padding: const EdgeInsets.only(left: 16,right: 0,top: 10,bottom: 10), - child: !loaded ? null : Row( + behavior: HitTestBehavior.opaque, + onTap: () { + loaded ? Navigator.push(context, MaterialPageRoute(builder: (context){ + return ConversationDetail( + conversation: conversation, + ); + })).then(onGoBack) : null; + }, + child: Container( + padding: const EdgeInsets.only(left: 16,right: 0,top: 10,bottom: 10), + child: !loaded ? null : Row( + children: [ + Expanded( + child: Row( children: [ + CustomCircleAvatar( + initials: conversationName[0].toUpperCase(), + imagePath: null, + ), + const SizedBox(width: 16), Expanded( - child: Row( + child: Align( + alignment: Alignment.centerLeft, + child: Container( + color: Colors.transparent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - CustomCircleAvatar( - initials: conversation.name[0].toUpperCase(), - imagePath: null, - ), - const SizedBox(width: 16), - Expanded( - child: Align( - alignment: Alignment.centerLeft, - child: Container( - color: Colors.transparent, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - conversation.name, - style: const TextStyle(fontSize: 16) - ), - recentMessage != null ? - const SizedBox(height: 2) : - const SizedBox.shrink() - , - recentMessage != null ? - Text( - recentMessage!.data, - overflow: TextOverflow.ellipsis, - maxLines: 1, - style: TextStyle( - fontSize: 13, - color: Colors.grey.shade600, - fontWeight: conversation.isRead ? FontWeight.normal : FontWeight.bold, - ), - ) : - const SizedBox.shrink(), - ], - ), - ), - ), + Text( + conversationName, + style: const TextStyle(fontSize: 16) ), recentMessage != null ? - Padding( - padding: const EdgeInsets.only(left: 10), - child: Text( - convertToAgo(recentMessage!.createdAt, short: true), - style: TextStyle( - fontSize: 13, - color: Colors.grey.shade600, - ), - ) - ): - const SizedBox.shrink(), - ], + const SizedBox(height: 2) : + const SizedBox.shrink() + , + recentMessage != null ? + Text( + recentMessage!.data, + overflow: TextOverflow.ellipsis, + maxLines: 1, + style: TextStyle( + fontSize: 13, + color: Colors.grey.shade600, + fontWeight: conversation.isRead ? FontWeight.normal : FontWeight.bold, + ), + ) : + const SizedBox.shrink(), + ], ), + ), ), + ), + recentMessage != null ? + Padding( + padding: const EdgeInsets.only(left: 10), + child: Text( + convertToAgo(recentMessage!.createdAt, short: true), + style: TextStyle( + fontSize: 13, + color: Colors.grey.shade600, + ), + ) + ): + const SizedBox.shrink(), ], + ), ), + ], ), + ), ); } @@ -107,6 +108,7 @@ class _ConversationListItemState extends State { Future getConversationData() async { conversation = widget.conversation; + conversationName = await widget.conversation.getName(); recentMessage = await conversation.getRecentMessage(); loaded = true; setState(() {}); diff --git a/mobile/lib/views/main/friend/list_item.dart b/mobile/lib/views/main/friend/list_item.dart index 3610ff1..5f6a4d3 100644 --- a/mobile/lib/views/main/friend/list_item.dart +++ b/mobile/lib/views/main/friend/list_item.dart @@ -1,5 +1,8 @@ import 'package:Envelope/components/custom_circle_avatar.dart'; +import 'package:Envelope/models/conversations.dart'; import 'package:Envelope/models/friends.dart'; +import 'package:Envelope/utils/strings.dart'; +import 'package:Envelope/views/main/conversation/detail.dart'; import 'package:flutter/material.dart'; class FriendListItem extends StatefulWidget{ @@ -19,8 +22,7 @@ class _FriendListItemState extends State { Widget build(BuildContext context) { return GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () async { - }, + onTap: findOrCreateConversation, child: Container( padding: const EdgeInsets.only(left: 16,right: 16,top: 0,bottom: 20), child: Row( @@ -55,4 +57,20 @@ class _FriendListItemState extends State { ), ); } + + Future findOrCreateConversation() async { + Conversation? conversation = await getTwoUserConversation(widget.friend.friendId); + + conversation ??= await createConversation( + generateRandomString(32), + [ widget.friend ], + true, + ); + + Navigator.push(context, MaterialPageRoute(builder: (context){ + return ConversationDetail( + conversation: conversation!, + ); + })); + } } -- 2.17.1 From 2a5f2438251476fca9407e8c40d95b3d3bb163ae Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Sat, 13 Aug 2022 11:26:33 +0930 Subject: [PATCH 22/24] Fix state management on home page, and fix user conversations --- Backend/Api/Messages/CreateConversation.go | 8 ++- Backend/Api/Routes.go | 3 +- mobile/lib/models/conversations.dart | 57 +++++++++---------- mobile/lib/utils/storage/conversations.dart | 37 +++++++++--- .../unauthenticated_landing.dart | 4 +- .../lib/views/main/conversation/detail.dart | 4 +- mobile/lib/views/main/conversation/list.dart | 2 +- .../views/main/conversation/list_item.dart | 6 +- .../lib/views/main/conversation/settings.dart | 6 +- .../conversation/settings_user_list_item.dart | 2 +- mobile/lib/views/main/friend/list_item.dart | 7 ++- mobile/lib/views/main/home.dart | 32 +++++++++-- 12 files changed, 105 insertions(+), 63 deletions(-) diff --git a/Backend/Api/Messages/CreateConversation.go b/Backend/Api/Messages/CreateConversation.go index 5241995..41de38c 100644 --- a/Backend/Api/Messages/CreateConversation.go +++ b/Backend/Api/Messages/CreateConversation.go @@ -10,13 +10,16 @@ import ( "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" ) +// RawCreateConversationData for holding POST payload type RawCreateConversationData struct { ID string `json:"id"` Name string `json:"name"` + TwoUser string `json:"two_user"` Users []Models.ConversationDetailUser `json:"users"` UserConversations []Models.UserConversation `json:"user_conversations"` } +// CreateConversation creates ConversationDetail, ConversationDetailUsers and UserConversations func CreateConversation(w http.ResponseWriter, r *http.Request) { var ( rawConversationData RawCreateConversationData @@ -34,8 +37,9 @@ func CreateConversation(w http.ResponseWriter, r *http.Request) { Base: Models.Base{ ID: uuid.FromStringOrNil(rawConversationData.ID), }, - Name: rawConversationData.Name, - Users: rawConversationData.Users, + Name: rawConversationData.Name, + TwoUser: rawConversationData.TwoUser, + Users: rawConversationData.Users, } err = Database.CreateConversationDetail(&messageThread) diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index 0143f90..c9d76ee 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -70,8 +70,7 @@ func InitAPIEndpoints(router *mux.Router) { authAPI.HandleFunc("/conversations", Messages.EncryptedConversationList).Methods("GET") authAPI.HandleFunc("/conversation_details", Messages.EncryptedConversationDetailsList).Methods("GET") - - authAPI.HandleFunc("/conversations", Messages.CreateConversation).Methods("POST") + authAPI.HandleFunc("/conversations", Messages.reateConversation).Methods("POST") authAPI.HandleFunc("/conversations", Messages.UpdateConversation).Methods("PUT") authAPI.HandleFunc("/message", Messages.CreateMessage).Methods("POST") diff --git a/mobile/lib/models/conversations.dart b/mobile/lib/models/conversations.dart index 69bc423..e7d760d 100644 --- a/mobile/lib/models/conversations.dart +++ b/mobile/lib/models/conversations.dart @@ -34,7 +34,7 @@ Future createConversation(String title, List friends, bool status: ConversationStatus.pending, isRead: true, ); - + await db.insert( 'conversations', conversation.toMap(), @@ -65,12 +65,32 @@ Future createConversation(String title, List friends, bool username: friend.username, associationKey: uuid.v4(), publicKey: friend.publicKey, - admin: false, + admin: twoUser ? true : false, ).toMap(), conflictAlgorithm: ConflictAlgorithm.replace, ); } + if (twoUser) { + List> maps = await db.query( + 'conversation_users', + where: 'conversation_id = ? AND user_id != ?', + whereArgs: [ conversation.id, profile.id ], + ); + + if (maps.length != 1) { + throw ArgumentError('Invalid user id'); + } + + conversation.name = maps[0]['username']; + + await db.insert( + 'conversations', + conversation.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + return conversation; } @@ -138,7 +158,10 @@ Future getConversationById(String id) async { Future> getConversations() async { final db = await getDatabaseConnection(); - final List> maps = await db.query('conversations'); + final List> maps = await db.query( + 'conversations', + orderBy: 'name', + ); return List.generate(maps.length, (i) { return Conversation( @@ -159,9 +182,6 @@ Future getTwoUserConversation(String userId) async { MyProfile profile = await MyProfile.getProfile(); - print(userId); - print(profile.id); - final List> maps = await db.rawQuery( ''' SELECT conversations.* FROM conversations @@ -281,6 +301,7 @@ class Conversation { 'id': id, 'name': AesHelper.aesEncrypt(symKey, Uint8List.fromList(name.codeUnits)), 'users': await getEncryptedConversationUsers(this, symKey), + 'two_user': AesHelper.aesEncrypt(symKey, Uint8List.fromList((twoUser ? 'true' : 'false').codeUnits)), 'user_conversations': userConversations, }; } @@ -320,7 +341,7 @@ class Conversation { ORDER BY created_at DESC LIMIT 1; ''', - [id], + [ id ], ); if (maps.isEmpty) { @@ -339,28 +360,6 @@ class Conversation { failedToSend: maps[0]['failed_to_send'] == 1, ); } - - Future getName() async { - if (!twoUser) { - return name; - } - - MyProfile profile = await MyProfile.getProfile(); - - final db = await getDatabaseConnection(); - - List> maps = await db.query( - 'conversation_users', - where: 'conversation_id = ? AND user_id != ?', - whereArgs: [ id, profile.id ], - ); - - if (maps.length != 1) { - throw ArgumentError('Invalid user id'); - } - - return maps[0]['username']; - } } diff --git a/mobile/lib/utils/storage/conversations.dart b/mobile/lib/utils/storage/conversations.dart index f4722a3..9ed72e5 100644 --- a/mobile/lib/utils/storage/conversations.dart +++ b/mobile/lib/utils/storage/conversations.dart @@ -1,5 +1,7 @@ import 'dart:convert'; +import 'package:Envelope/components/flash_message.dart'; +import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:http/http.dart' as http; import 'package:pointycastle/export.dart'; @@ -87,16 +89,34 @@ Future updateConversations() async { var conversationDetailJson = conversationsDetailsJson[i] as Map; var conversation = findConversationByDetailId(conversations, conversationDetailJson['id']); - conversation.name = AesHelper.aesDecrypt( - base64.decode(conversation.symmetricKey), - base64.decode(conversationDetailJson['name']), - ); - conversation.twoUser = AesHelper.aesDecrypt( base64.decode(conversation.symmetricKey), base64.decode(conversationDetailJson['two_user']), ) == 'true'; + if (conversation.twoUser) { + MyProfile profile = await MyProfile.getProfile(); + + final db = await getDatabaseConnection(); + + List> maps = await db.query( + 'conversation_users', + where: 'conversation_id = ? AND user_id != ?', + whereArgs: [ conversation.id, profile.id ], + ); + + if (maps.length != 1) { + throw ArgumentError('Invalid user id'); + } + + conversation.name = maps[0]['username']; + } else { + conversation.name = AesHelper.aesDecrypt( + base64.decode(conversation.symmetricKey), + base64.decode(conversationDetailJson['name']), + ); + } + await db.insert( 'conversations', conversation.toMap(), @@ -124,7 +144,7 @@ Future updateConversations() async { } -Future uploadConversation(Conversation conversation) async { +Future uploadConversation(Conversation conversation, BuildContext context) async { String sessionCookie = await getSessionCookie(); Map conversationJson = await conversation.payloadJson(); @@ -138,7 +158,8 @@ Future uploadConversation(Conversation conversation) async { body: jsonEncode(conversationJson), ); - // TODO: Handle errors here - print(x.statusCode); + if (x.statusCode != 200) { + showMessage('Failed to create conversation', context); + } } diff --git a/mobile/lib/views/authentication/unauthenticated_landing.dart b/mobile/lib/views/authentication/unauthenticated_landing.dart index 85748ef..6bcd086 100644 --- a/mobile/lib/views/authentication/unauthenticated_landing.dart +++ b/mobile/lib/views/authentication/unauthenticated_landing.dart @@ -18,9 +18,9 @@ class _UnauthenticatedLandingWidgetState extends State { - String conversationName = ''; List messages = []; MyProfile profile = MyProfile(id: '', username: ''); @@ -32,7 +31,7 @@ class _ConversationDetailState extends State { return Scaffold( appBar: CustomTitleBar( title: Text( - conversationName, + widget.conversation.name, style: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, @@ -138,7 +137,6 @@ class _ConversationDetailState extends State { } Future fetchMessages() async { - conversationName = await widget.conversation.getName(); profile = await MyProfile.getProfile(); messages = await getMessagesForThread(widget.conversation); setState(() {}); diff --git a/mobile/lib/views/main/conversation/list.dart b/mobile/lib/views/main/conversation/list.dart index a19887b..cabf6f0 100644 --- a/mobile/lib/views/main/conversation/list.dart +++ b/mobile/lib/views/main/conversation/list.dart @@ -77,7 +77,7 @@ class _ConversationListState extends State { false, ); - uploadConversation(conversation); + uploadConversation(conversation, context); Navigator.of(context).popUntil((route) => route.isFirst); Navigator.push(context, MaterialPageRoute(builder: (context){ diff --git a/mobile/lib/views/main/conversation/list_item.dart b/mobile/lib/views/main/conversation/list_item.dart index 5523204..816b996 100644 --- a/mobile/lib/views/main/conversation/list_item.dart +++ b/mobile/lib/views/main/conversation/list_item.dart @@ -19,7 +19,6 @@ class ConversationListItem extends StatefulWidget{ class _ConversationListItemState extends State { late Conversation conversation; - late String conversationName; late Message? recentMessage; bool loaded = false; @@ -42,7 +41,7 @@ class _ConversationListItemState extends State { child: Row( children: [ CustomCircleAvatar( - initials: conversationName[0].toUpperCase(), + initials: widget.conversation.name[0].toUpperCase(), imagePath: null, ), const SizedBox(width: 16), @@ -55,7 +54,7 @@ class _ConversationListItemState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - conversationName, + widget.conversation.name, style: const TextStyle(fontSize: 16) ), recentMessage != null ? @@ -108,7 +107,6 @@ class _ConversationListItemState extends State { Future getConversationData() async { conversation = widget.conversation; - conversationName = await widget.conversation.getName(); recentMessage = await conversation.getRecentMessage(); loaded = true; setState(() {}); diff --git a/mobile/lib/views/main/conversation/settings.dart b/mobile/lib/views/main/conversation/settings.dart index bc291f0..35939e1 100644 --- a/mobile/lib/views/main/conversation/settings.dart +++ b/mobile/lib/views/main/conversation/settings.dart @@ -35,7 +35,7 @@ class _ConversationSettingsState extends State { return Scaffold( appBar: CustomTitleBar( title: Text( - widget.conversation.name + " Settings", + widget.conversation.name + ' Settings', style: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, @@ -61,7 +61,7 @@ class _ConversationSettingsState extends State { widget.conversation.admin ? const SizedBox(height: 25) : const SizedBox.shrink(), - sectionTitle('Members', showUsersAdd: true), + sectionTitle('Members', showUsersAdd: widget.conversation.admin && !widget.conversation.twoUser), usersList(), const SizedBox(height: 25), myAccess(), @@ -88,7 +88,7 @@ class _ConversationSettingsState extends State { fontWeight: FontWeight.w500, ), ), - widget.conversation.admin ? IconButton( + widget.conversation.admin && !widget.conversation.twoUser ? IconButton( iconSize: 20, icon: const Icon(Icons.edit), padding: const EdgeInsets.all(5.0), diff --git a/mobile/lib/views/main/conversation/settings_user_list_item.dart b/mobile/lib/views/main/conversation/settings_user_list_item.dart index 9657bab..a527e23 100644 --- a/mobile/lib/views/main/conversation/settings_user_list_item.dart +++ b/mobile/lib/views/main/conversation/settings_user_list_item.dart @@ -42,7 +42,7 @@ class _ConversationSettingsUserListItemState extends State { Widget build(BuildContext context) { return GestureDetector( behavior: HitTestBehavior.opaque, - onTap: findOrCreateConversation, + onTap: () { findOrCreateConversation(context); }, child: Container( padding: const EdgeInsets.only(left: 16,right: 16,top: 0,bottom: 20), child: Row( @@ -58,7 +59,7 @@ class _FriendListItemState extends State { ); } - Future findOrCreateConversation() async { + Future findOrCreateConversation(BuildContext context) async { Conversation? conversation = await getTwoUserConversation(widget.friend.friendId); conversation ??= await createConversation( @@ -67,6 +68,8 @@ class _FriendListItemState extends State { true, ); + uploadConversation(conversation, context); + Navigator.push(context, MaterialPageRoute(builder: (context){ return ConversationDetail( conversation: conversation!, diff --git a/mobile/lib/views/main/home.dart b/mobile/lib/views/main/home.dart index e740db0..f6bfb92 100644 --- a/mobile/lib/views/main/home.dart +++ b/mobile/lib/views/main/home.dart @@ -59,15 +59,15 @@ class _HomeState extends State { items: const [ BottomNavigationBarItem( icon: Icon(Icons.message), - label: "Chats", + label: 'Chats', ), BottomNavigationBarItem( icon: Icon(Icons.group_work), - label: "Friends", + label: 'Friends', ), BottomNavigationBarItem( icon: Icon(Icons.account_box), - label: "Profile", + label: 'Profile', ), ], ), @@ -166,7 +166,7 @@ class _HomeState extends State { FriendList( friends: friends, friendRequests: friendRequests, - callback: initFriends, + callback: reinitDatabaseRecords, ), Profile(profile: profile), ]; @@ -174,12 +174,32 @@ class _HomeState extends State { }); } - Future initFriends() async { + Future reinitDatabaseRecords() async { + + conversations = await getConversations(); friends = await getFriends(accepted: true); friendRequests = await getFriends(accepted: false); + profile = await MyProfile.getProfile(); + + setState(() { + _widgetOptions = [ + ConversationList( + conversations: conversations, + friends: friends, + ), + FriendList( + friends: friends, + friendRequests: friendRequests, + callback: reinitDatabaseRecords, + ), + Profile(profile: profile), + ]; + isLoading = false; + }); } - void _onItemTapped(int index) { + void _onItemTapped(int index) async { + await reinitDatabaseRecords(); setState(() { _selectedIndex = index; }); -- 2.17.1 From bfa4f6b422c0b03793d4c5835903fa26b3efb237 Mon Sep 17 00:00:00 2001 From: Tovi Jaeschke-Rogers Date: Sun, 21 Aug 2022 15:29:10 +0930 Subject: [PATCH 23/24] Add friends through scanning qr code --- Backend/Api/Friends/Friends.go | 52 ++++++- Backend/Api/Routes.go | 3 +- Backend/Database/FriendRequests.go | 6 + mobile/android/app/build.gradle | 2 +- mobile/ios/Runner/Info.plist | 4 + mobile/lib/components/qr_reader.dart | 163 ++++++++++++++++++++ mobile/lib/models/friends.dart | 37 ++++- mobile/lib/utils/storage/conversations.dart | 4 +- mobile/lib/views/main/friend/list.dart | 7 +- mobile/pubspec.lock | 9 +- mobile/pubspec.yaml | 1 + mobile/test/pajamasenergy_qr_code.png | Bin 0 -> 13313 bytes mobile/test/qr_payload.json | 1 + 13 files changed, 279 insertions(+), 10 deletions(-) create mode 100644 mobile/lib/components/qr_reader.dart create mode 100644 mobile/test/pajamasenergy_qr_code.png create mode 100644 mobile/test/qr_payload.json diff --git a/Backend/Api/Friends/Friends.go b/Backend/Api/Friends/Friends.go index 07316af..3327e10 100644 --- a/Backend/Api/Friends/Friends.go +++ b/Backend/Api/Friends/Friends.go @@ -4,6 +4,7 @@ import ( "encoding/json" "io/ioutil" "net/http" + "time" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" @@ -20,19 +21,25 @@ func CreateFriendRequest(w http.ResponseWriter, r *http.Request) { requestBody, err = ioutil.ReadAll(r.Body) if err != nil { - panic(err) + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return } err = json.Unmarshal(requestBody, &friendRequest) if err != nil { - panic(err) + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return } friendRequest.AcceptedAt.Scan(nil) err = Database.CreateFriendRequest(&friendRequest) if err != nil { - panic(err) + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return } returnJSON, err = json.MarshalIndent(friendRequest, "", " ") @@ -46,3 +53,42 @@ func CreateFriendRequest(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write(returnJSON) } + +// CreateFriendRequestQrCode creates a FriendRequest from post data from qr code scan +func CreateFriendRequestQrCode(w http.ResponseWriter, r *http.Request) { + var ( + friendRequests []Models.FriendRequest + requestBody []byte + i int + err error + ) + + requestBody, err = ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + err = json.Unmarshal(requestBody, &friendRequests) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + for i = range friendRequests { + friendRequests[i].AcceptedAt.Time = time.Now() + friendRequests[i].AcceptedAt.Valid = true + } + + err = Database.CreateFriendRequests(&friendRequests) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + w.WriteHeader(http.StatusInternalServerError) + return + } + + // Return updated json + w.WriteHeader(http.StatusOK) +} diff --git a/Backend/Api/Routes.go b/Backend/Api/Routes.go index c9d76ee..50f4f01 100644 --- a/Backend/Api/Routes.go +++ b/Backend/Api/Routes.go @@ -65,12 +65,13 @@ func InitAPIEndpoints(router *mux.Router) { authAPI.HandleFunc("/friend_requests", Friends.EncryptedFriendRequestList).Methods("GET") authAPI.HandleFunc("/friend_request", Friends.CreateFriendRequest).Methods("POST") + authAPI.HandleFunc("/friend_request/qr_code", Friends.CreateFriendRequestQrCode).Methods("POST") authAPI.HandleFunc("/friend_request/{requestID}", Friends.AcceptFriendRequest).Methods("POST") authAPI.HandleFunc("/friend_request/{requestID}", Friends.RejectFriendRequest).Methods("DELETE") authAPI.HandleFunc("/conversations", Messages.EncryptedConversationList).Methods("GET") authAPI.HandleFunc("/conversation_details", Messages.EncryptedConversationDetailsList).Methods("GET") - authAPI.HandleFunc("/conversations", Messages.reateConversation).Methods("POST") + authAPI.HandleFunc("/conversations", Messages.CreateConversation).Methods("POST") authAPI.HandleFunc("/conversations", Messages.UpdateConversation).Methods("PUT") authAPI.HandleFunc("/message", Messages.CreateMessage).Methods("POST") diff --git a/Backend/Database/FriendRequests.go b/Backend/Database/FriendRequests.go index f6393d5..0f6e58a 100644 --- a/Backend/Database/FriendRequests.go +++ b/Backend/Database/FriendRequests.go @@ -42,6 +42,12 @@ func CreateFriendRequest(friendRequest *Models.FriendRequest) error { Error } +// CreateFriendRequests creates multiple friend requests +func CreateFriendRequests(friendRequest *[]Models.FriendRequest) error { + return DB.Create(friendRequest). + Error +} + // UpdateFriendRequest Updates friend request func UpdateFriendRequest(friendRequest *Models.FriendRequest) error { return DB.Where("id = ?", friendRequest.ID). diff --git a/mobile/android/app/build.gradle b/mobile/android/app/build.gradle index 5536a1b..df5e935 100644 --- a/mobile/android/app/build.gradle +++ b/mobile/android/app/build.gradle @@ -44,7 +44,7 @@ android { defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.example.mobile" - minSdkVersion flutter.minSdkVersion + minSdkVersion 20 targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName diff --git a/mobile/ios/Runner/Info.plist b/mobile/ios/Runner/Info.plist index 7c170fc..d3ba628 100644 --- a/mobile/ios/Runner/Info.plist +++ b/mobile/ios/Runner/Info.plist @@ -43,5 +43,9 @@ UIViewControllerBasedStatusBarAppearance + io.flutter.embedded_views_preview + + NSCameraUsageDescription + This app needs camera access to scan QR codes diff --git a/mobile/lib/components/qr_reader.dart b/mobile/lib/components/qr_reader.dart new file mode 100644 index 0000000..1ff79ed --- /dev/null +++ b/mobile/lib/components/qr_reader.dart @@ -0,0 +1,163 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:Envelope/utils/storage/session_cookie.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:pointycastle/impl.dart'; +import 'package:qr_code_scanner/qr_code_scanner.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:uuid/uuid.dart'; +import 'package:http/http.dart' as http; + +import '/models/friends.dart'; +import '/models/my_profile.dart'; +import '/utils/encryption/aes_helper.dart'; +import '/utils/encryption/crypto_utils.dart'; +import '/utils/storage/database.dart'; +import '/utils/strings.dart'; +import 'flash_message.dart'; + +class QrReader extends StatefulWidget { + const QrReader({ + Key? key, + }) : super(key: key); + + @override + State createState() => _QrReaderState(); +} + +class _QrReaderState extends State { + final GlobalKey qrKey = GlobalKey(debugLabel: 'QR'); + Barcode? result; + QRViewController? controller; + + // In order to get hot reload to work we need to pause the camera if the platform + // is android, or resume the camera if the platform is iOS. + @override + void reassemble() { + super.reassemble(); + if (Platform.isAndroid) { + controller!.pauseCamera(); + } else if (Platform.isIOS) { + controller!.resumeCamera(); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Column( + children: [ + Expanded( + flex: 5, + child: QRView( + key: qrKey, + onQRViewCreated: _onQRViewCreated, + formatsAllowed: const [BarcodeFormat.qrcode], + overlay: QrScannerOverlayShape(), + ), + ), + ], + ), + ); + } + + void _onQRViewCreated(QRViewController controller) { + this.controller = controller; + controller.scannedDataStream.listen((scanData) { + addFriend(scanData) + .then((dynamic ret) { + if (ret) { + // Delay exit to prevent exit mid way through rendering + Future.delayed(Duration.zero, () { + Navigator.of(context).pop(); + }); + } + }); + }); + } + + @override + void dispose() { + controller?.dispose(); + super.dispose(); + } + + Future addFriend(Barcode scanData) async { + Map friendJson = jsonDecode(scanData.code!); + + RSAPublicKey publicKey = CryptoUtils.rsaPublicKeyFromPem( + String.fromCharCodes( + base64.decode( + friendJson['k'] + ) + ) + ); + + MyProfile profile = await MyProfile.getProfile(); + + var uuid = const Uuid(); + + final symmetricKey1 = AesHelper.deriveKey(generateRandomString(32)); + final symmetricKey2 = AesHelper.deriveKey(generateRandomString(32)); + + Friend request1 = Friend( + id: uuid.v4(), + userId: friendJson['i'], + username: profile.username, + friendId: profile.id, + friendSymmetricKey: base64.encode(symmetricKey1), + publicKey: profile.publicKey!, + acceptedAt: DateTime.now(), + ); + + Friend request2 = Friend( + id: uuid.v4(), + userId: profile.id, + friendId: friendJson['i'], + username: friendJson['u'], + friendSymmetricKey: base64.encode(symmetricKey2), + publicKey: publicKey, + acceptedAt: DateTime.now(), + ); + + String payload = jsonEncode([ + request1.payloadJson(), + request2.payloadJson(), + ]); + + var resp = await http.post( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friend_request/qr_code'), + headers: { + 'Content-Type': 'application/json; charset=UTF-8', + 'cookie': await getSessionCookie(), + }, + body: payload, + ); + + if (resp.statusCode != 200) { + showMessage( + 'Failed to add friend, please try again later', + context + ); + return false; + } + + final db = await getDatabaseConnection(); + + await db.insert( + 'friends', + request1.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + + await db.insert( + 'friends', + request2.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + + return true; + } +} diff --git a/mobile/lib/models/friends.dart b/mobile/lib/models/friends.dart index 269a8ad..c435697 100644 --- a/mobile/lib/models/friends.dart +++ b/mobile/lib/models/friends.dart @@ -129,6 +129,41 @@ class Friend{ ); } + Map payloadJson() { + + Uint8List friendIdEncrypted = CryptoUtils.rsaEncrypt( + Uint8List.fromList(friendId.codeUnits), + publicKey, + ); + + Uint8List usernameEncrypted = CryptoUtils.rsaEncrypt( + Uint8List.fromList(username.codeUnits), + publicKey, + ); + + Uint8List symmetricKeyEncrypted = CryptoUtils.rsaEncrypt( + Uint8List.fromList( + base64.decode(friendSymmetricKey), + ), + publicKey, + ); + + var publicKeyEncrypted = AesHelper.aesEncrypt( + base64.decode(friendSymmetricKey), + Uint8List.fromList(CryptoUtils.encodeRSAPublicKeyToPem(publicKey).codeUnits), + ); + + return { + 'id': id, + 'user_id': userId, + 'friend_id': base64.encode(friendIdEncrypted), + 'friend_username': base64.encode(usernameEncrypted), + 'symmetric_key': base64.encode(symmetricKeyEncrypted), + 'asymmetric_public_key': publicKeyEncrypted, + 'accepted_at': null, + }; + } + String publicKeyPem() { return CryptoUtils.encodeRSAPublicKeyToPem(publicKey); } @@ -139,7 +174,7 @@ class Friend{ 'user_id': userId, 'username': username, 'friend_id': friendId, - 'symmetric_key': friendSymmetricKey, + 'symmetric_key': base64.encode(friendSymmetricKey.codeUnits), 'asymmetric_public_key': publicKeyPem(), 'accepted_at': acceptedAt?.toIso8601String(), }; diff --git a/mobile/lib/utils/storage/conversations.dart b/mobile/lib/utils/storage/conversations.dart index 9ed72e5..fc65477 100644 --- a/mobile/lib/utils/storage/conversations.dart +++ b/mobile/lib/utils/storage/conversations.dart @@ -149,7 +149,7 @@ Future uploadConversation(Conversation conversation, BuildContext context) Map conversationJson = await conversation.payloadJson(); - var x = await http.post( + var resp = await http.post( Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/conversations'), headers: { 'Content-Type': 'application/json; charset=UTF-8', @@ -158,7 +158,7 @@ Future uploadConversation(Conversation conversation, BuildContext context) body: jsonEncode(conversationJson), ); - if (x.statusCode != 200) { + if (resp.statusCode != 200) { showMessage('Failed to create conversation', context); } } diff --git a/mobile/lib/views/main/friend/list.dart b/mobile/lib/views/main/friend/list.dart index ded6225..8f19a61 100644 --- a/mobile/lib/views/main/friend/list.dart +++ b/mobile/lib/views/main/friend/list.dart @@ -1,4 +1,5 @@ import 'package:Envelope/components/custom_title_bar.dart'; +import 'package:Envelope/components/qr_reader.dart'; import 'package:Envelope/views/main/friend/add_search.dart'; import 'package:Envelope/views/main/friend/request_list_item.dart'; import 'package:flutter/material.dart'; @@ -74,7 +75,11 @@ class _FriendListState extends State { distance: 90.0, children: [ ActionButton( - onPressed: () {}, + onPressed: () { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => const QrReader()) + );//.then(onGoBack); // TODO + }, icon: const Icon(Icons.qr_code_2, size: 25), ), ActionButton( diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock index cfa6a60..917ab66 100644 --- a/mobile/pubspec.lock +++ b/mobile/pubspec.lock @@ -247,6 +247,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.1.0" + qr_code_scanner: + dependency: "direct main" + description: + name: qr_code_scanner + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" qr_flutter: dependency: "direct main" description: @@ -414,5 +421,5 @@ packages: source: hosted version: "0.2.0+1" sdks: - dart: ">=2.17.0-0 <3.0.0" + dart: ">=2.17.0 <3.0.0" flutter: ">=2.8.0" diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml index ea62a83..6007c51 100644 --- a/mobile/pubspec.yaml +++ b/mobile/pubspec.yaml @@ -23,6 +23,7 @@ dependencies: intl: ^0.17.0 uuid: ^3.0.6 qr_flutter: ^4.0.0 + qr_code_scanner: ^1.0.1 dev_dependencies: flutter_test: diff --git a/mobile/test/pajamasenergy_qr_code.png b/mobile/test/pajamasenergy_qr_code.png new file mode 100644 index 0000000000000000000000000000000000000000..84584a2f65e7973fe574ea71c028f02da273c96f GIT binary patch literal 13313 zcmb`OeQcHIdBzAn-q`5Xie;4>|MY6 zeqI|*uMdB0ih>Wv=e+Op-p_Sk_jOe;`2@9#cX zxcSVhuRZ_!|FQ42=YRUl^+WpO)z{v8hxdN^(O%yB*I#^%_h$a&Y2G{hqf>n3-4Dm? zYybKG@wNLmPox*Fw4Waz*w;5a@P7a8x|xRLJMCrZ#?@uH4!vJBwyXJD`!5X-zT7{Z ztVthSy*{^htfo1$zjb^heN}%yl)suhm`vq2*WJoYr;q76_cqv@cWZBDuBN-|_g^}o z|L<+el;4S4@q;_3k~g+bmFU8W^mO`Qa*)+bmLwB?tEryJ%I3_>s$6EQR4dDjRgKk5 zJ*mGbx;(i`3r*ywla2aiN4s8W=@;^>mUj~AquZJ@Lx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NIIL!zglSpbbf;D4l^{G-WQJYvE>rUFdQpj~m z(H340hb@76IF!vn{9t-JC#@%{4X;H;YDosI99$$45X ztM<$4+2QA7GHUcmb9TUWWWe{SYgXrJNAPTv9Hxcli_tdFB-0Vr&uol+@?eMH7ovAe zJ=%$F^C!)4GJ_r#g5WIK=}*iC<|qJqZ^!DWZ=*SIXA_UvjurLYi-o&(_(jFa&+|qZ z%jB2);h)<8!;ab5{$c=2`u&R*fy3?<#B-eTXQA_e`B@rK#D;=q&*J`o8A^lM_X=#8 zEE_V{7NNfuP-?aNbor>>RTHX{ak<(8HpX&R3ImTHG8^j_A2RDXhP2dO-g`f-dwC2h>lc7k)>p zCCluo>|a8lNjMZ>74tGCs<_YpS%7*g6-wAGV{KHaVa%Jcs5y=xLHoH Date: Sun, 21 Aug 2022 15:44:49 +0930 Subject: [PATCH 24/24] Remove redunant w.WriteHeader lines after http.Error --- Backend/Api/Auth/Login.go | 1 - Backend/Api/Auth/Signup.go | 1 - Backend/Api/Friends/AcceptFriendRequest.go | 5 ----- Backend/Api/Friends/Friends.go | 7 ------- Backend/Api/Friends/RejectFriendRequest.go | 2 -- 5 files changed, 16 deletions(-) diff --git a/Backend/Api/Auth/Login.go b/Backend/Api/Auth/Login.go index 15c42a7..44f26e7 100644 --- a/Backend/Api/Auth/Login.go +++ b/Backend/Api/Auth/Login.go @@ -43,7 +43,6 @@ func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey }, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } diff --git a/Backend/Api/Auth/Signup.go b/Backend/Api/Auth/Signup.go index 232611f..57509ab 100644 --- a/Backend/Api/Auth/Signup.go +++ b/Backend/Api/Auth/Signup.go @@ -32,7 +32,6 @@ func makeSignupResponse(w http.ResponseWriter, code int, message string) { }, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } diff --git a/Backend/Api/Friends/AcceptFriendRequest.go b/Backend/Api/Friends/AcceptFriendRequest.go index 8ba80d1..adfa0e5 100644 --- a/Backend/Api/Friends/AcceptFriendRequest.go +++ b/Backend/Api/Friends/AcceptFriendRequest.go @@ -33,7 +33,6 @@ func AcceptFriendRequest(w http.ResponseWriter, r *http.Request) { oldFriendRequest, err = Database.GetFriendRequestByID(friendRequestID) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } @@ -43,21 +42,18 @@ func AcceptFriendRequest(w http.ResponseWriter, r *http.Request) { requestBody, err = ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } err = json.Unmarshal(requestBody, &newFriendRequest) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } err = Database.UpdateFriendRequest(&oldFriendRequest) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } @@ -67,7 +63,6 @@ func AcceptFriendRequest(w http.ResponseWriter, r *http.Request) { err = Database.CreateFriendRequest(&newFriendRequest) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } diff --git a/Backend/Api/Friends/Friends.go b/Backend/Api/Friends/Friends.go index 3327e10..a1db196 100644 --- a/Backend/Api/Friends/Friends.go +++ b/Backend/Api/Friends/Friends.go @@ -22,14 +22,12 @@ func CreateFriendRequest(w http.ResponseWriter, r *http.Request) { requestBody, err = ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } err = json.Unmarshal(requestBody, &friendRequest) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } @@ -38,14 +36,12 @@ func CreateFriendRequest(w http.ResponseWriter, r *http.Request) { err = Database.CreateFriendRequest(&friendRequest) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } returnJSON, err = json.MarshalIndent(friendRequest, "", " ") if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } @@ -66,14 +62,12 @@ func CreateFriendRequestQrCode(w http.ResponseWriter, r *http.Request) { requestBody, err = ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } err = json.Unmarshal(requestBody, &friendRequests) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } @@ -85,7 +79,6 @@ func CreateFriendRequestQrCode(w http.ResponseWriter, r *http.Request) { err = Database.CreateFriendRequests(&friendRequests) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } diff --git a/Backend/Api/Friends/RejectFriendRequest.go b/Backend/Api/Friends/RejectFriendRequest.go index b1b2c87..e341858 100644 --- a/Backend/Api/Friends/RejectFriendRequest.go +++ b/Backend/Api/Friends/RejectFriendRequest.go @@ -29,14 +29,12 @@ func RejectFriendRequest(w http.ResponseWriter, r *http.Request) { friendRequest, err = Database.GetFriendRequestByID(friendRequestID) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } err = Database.DeleteFriendRequest(&friendRequest) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) - w.WriteHeader(http.StatusInternalServerError) return } -- 2.17.1