diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f7fec7f --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/mobile/.env 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/Auth/Login.go b/Backend/Api/Auth/Login.go new file mode 100644 index 0000000..44f26e7 --- /dev/null +++ b/Backend/Api/Auth/Login.go @@ -0,0 +1,108 @@ +package Auth + +import ( + "encoding/json" + "net/http" + "time" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +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"` + UserID string `json:"user_id"` + Username string `json:"username"` +} + +func makeLoginResponse(w http.ResponseWriter, code int, message, pubKey, privKey string, user Models.User) { + 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, + UserID: user.ID.String(), + Username: user.Username, + }, "", " ") + if err != nil { + http.Error(w, "Error", 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 + session Models.Session + expiresAt time.Time + err error + ) + + err = json.NewDecoder(r.Body).Decode(&creds) + if err != nil { + 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", "", "", userData) + return + } + + if !CheckPasswordHash(creds.Password, userData.Password) { + makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", userData) + return + } + + // TODO: Revisit before production + expiresAt = time.Now().Add(12 * time.Hour) + + session = Models.Session{ + UserID: userData.ID, + Expiry: expiresAt, + } + + err = Database.CreateSession(&session) + if err != nil { + makeLoginResponse(w, http.StatusUnauthorized, "An error occurred", "", "", userData) + return + } + + http.SetCookie(w, &http.Cookie{ + Name: "session_token", + Value: session.ID.String(), + Expires: expiresAt, + }) + + makeLoginResponse( + w, + http.StatusOK, + "Successfully logged in", + userData.AsymmetricPublicKey, + userData.AsymmetricPrivateKey, + userData, + ) +} diff --git a/Backend/Api/Auth/Logout.go b/Backend/Api/Auth/Logout.go new file mode 100644 index 0000000..486b575 --- /dev/null +++ b/Backend/Api/Auth/Logout.go @@ -0,0 +1,40 @@ +package Auth + +import ( + "log" + "net/http" + "time" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" +) + +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 + + err = Database.DeleteSessionById(sessionToken) + if err != nil { + log.Println("Could not delete session cookie") + } + + http.SetCookie(w, &http.Cookie{ + Name: "session_token", + Value: "", + Expires: time.Now(), + }) +} 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/Session.go b/Backend/Api/Auth/Session.go new file mode 100644 index 0000000..ffcfae2 --- /dev/null +++ b/Backend/Api/Auth/Session.go @@ -0,0 +1,54 @@ +package Auth + +import ( + "errors" + "net/http" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +func CheckCookie(r *http.Request) (Models.Session, error) { + var ( + c *http.Cookie + sessionToken string + userSession Models.Session + 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, 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() { + Database.DeleteSession(&userSession) + return userSession, errors.New("Cookie expired") + } + + return userSession, nil +} + +func CheckCookieCurrentUser(w http.ResponseWriter, r *http.Request) (Models.User, error) { + var ( + session Models.Session + userData Models.User + err error + ) + + session, err = CheckCookie(r) + if err != nil { + return userData, err + } + + return session.User, nil +} diff --git a/Backend/Api/Auth/Signup.go b/Backend/Api/Auth/Signup.go new file mode 100644 index 0000000..57509ab --- /dev/null +++ b/Backend/Api/Auth/Signup.go @@ -0,0 +1,95 @@ +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" +) + +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) + return + } + + // Return updated json + w.WriteHeader(code) + w.Write(returnJson) + +} + +func Signup(w http.ResponseWriter, r *http.Request) { + var ( + userData Models.User + requestBody []byte + err error + ) + + requestBody, err = ioutil.ReadAll(r.Body) + if err != nil { + log.Printf("Error encountered reading POST body: %s\n", err.Error()) + makeSignupResponse(w, http.StatusInternalServerError, "An error occurred") + return + } + + userData, err = JsonSerialization.DeserializeUser(requestBody, []string{ + "id", + }, false) + if err != nil { + log.Printf("Invalid data provided to Signup: %s\n", err.Error()) + makeSignupResponse(w, http.StatusUnprocessableEntity, "Invalid data provided") + return + } + + if userData.Username == "" || + userData.Password == "" || + userData.ConfirmPassword == "" || + len(userData.AsymmetricPrivateKey) == 0 || + len(userData.AsymmetricPublicKey) == 0 { + makeSignupResponse(w, http.StatusUnprocessableEntity, "Invalid data provided") + return + } + + err = Database.CheckUniqueUsername(userData.Username) + if err != nil { + makeSignupResponse(w, http.StatusUnprocessableEntity, "Invalid data provided") + return + } + + userData.Password, err = HashPassword(userData.Password) + if err != nil { + makeSignupResponse(w, http.StatusInternalServerError, "An error occurred") + return + } + + err = Database.CreateUser(&userData) + if err != nil { + makeSignupResponse(w, http.StatusInternalServerError, "An error occurred") + return + } + + makeSignupResponse(w, http.StatusCreated, "Successfully signed up") +} diff --git a/Backend/Api/Friends/AcceptFriendRequest.go b/Backend/Api/Friends/AcceptFriendRequest.go new file mode 100644 index 0000000..adfa0e5 --- /dev/null +++ b/Backend/Api/Friends/AcceptFriendRequest.go @@ -0,0 +1,70 @@ +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) + 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) + return + } + + err = json.Unmarshal(requestBody, &newFriendRequest) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + err = Database.UpdateFriendRequest(&oldFriendRequest) + if err != nil { + http.Error(w, "Error", 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) + return + } + + w.WriteHeader(http.StatusNoContent) +} diff --git a/Backend/Api/Friends/EncryptedFriendsList.go b/Backend/Api/Friends/EncryptedFriendsList.go new file mode 100644 index 0000000..410c75c --- /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" +) + +// EncryptedFriendRequestList gets friend request list +func EncryptedFriendRequestList(w http.ResponseWriter, r *http.Request) { + var ( + userSession Models.Session + friends []Models.FriendRequest + returnJSON []byte + err error + ) + + userSession, err = Auth.CheckCookie(r) + if err != nil { + http.Error(w, "Forbidden", http.StatusUnauthorized) + return + } + + 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) +} diff --git a/Backend/Api/Friends/FriendRequest.go b/Backend/Api/Friends/FriendRequest.go new file mode 100644 index 0000000..126605d --- /dev/null +++ b/Backend/Api/Friends/FriendRequest.go @@ -0,0 +1,60 @@ +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 string + friendRequest Models.FriendRequest + ok bool + 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, ok = requestJson["id"].(string) + if !ok { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + friendRequest = Models.FriendRequest{ + 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..a1db196 --- /dev/null +++ b/Backend/Api/Friends/Friends.go @@ -0,0 +1,87 @@ +package Friends + +import ( + "encoding/json" + "io/ioutil" + "net/http" + "time" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +// CreateFriendRequest creates a FriendRequest from post data +func CreateFriendRequest(w http.ResponseWriter, r *http.Request) { + var ( + friendRequest Models.FriendRequest + requestBody []byte + returnJSON []byte + err error + ) + + requestBody, err = ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + err = json.Unmarshal(requestBody, &friendRequest) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + friendRequest.AcceptedAt.Scan(nil) + + err = Database.CreateFriendRequest(&friendRequest) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + returnJSON, err = json.MarshalIndent(friendRequest, "", " ") + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + // Return updated json + 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) + return + } + + err = json.Unmarshal(requestBody, &friendRequests) + if err != nil { + http.Error(w, "Error", 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) + return + } + + // Return updated json + w.WriteHeader(http.StatusOK) +} diff --git a/Backend/Api/Friends/RejectFriendRequest.go b/Backend/Api/Friends/RejectFriendRequest.go new file mode 100644 index 0000000..e341858 --- /dev/null +++ b/Backend/Api/Friends/RejectFriendRequest.go @@ -0,0 +1,42 @@ +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) + return + } + + err = Database.DeleteFriendRequest(&friendRequest) + if err != nil { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusNoContent) +} 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/Messages/Conversations.go b/Backend/Api/Messages/Conversations.go new file mode 100644 index 0000000..27d1470 --- /dev/null +++ b/Backend/Api/Messages/Conversations.go @@ -0,0 +1,84 @@ +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" +) + +// 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 + 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) +} + +// 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 + 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/CreateConversation.go b/Backend/Api/Messages/CreateConversation.go new file mode 100644 index 0000000..41de38c --- /dev/null +++ b/Backend/Api/Messages/CreateConversation.go @@ -0,0 +1,58 @@ +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" +) + +// 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 + 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, + TwoUser: rawConversationData.TwoUser, + 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 { + http.Error(w, "Error", http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) +} diff --git a/Backend/Api/Messages/CreateMessage.go b/Backend/Api/Messages/CreateMessage.go new file mode 100644 index 0000000..c233fc8 --- /dev/null +++ b/Backend/Api/Messages/CreateMessage.go @@ -0,0 +1,41 @@ +package Messages + +import ( + "encoding/json" + "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 ( + rawMessageData RawMessageData + err error + ) + + 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 + } + + w.WriteHeader(http.StatusOK) +} diff --git a/Backend/Api/Messages/MessageThread.go b/Backend/Api/Messages/MessageThread.go new file mode 100644 index 0000000..14fac7c --- /dev/null +++ b/Backend/Api/Messages/MessageThread.go @@ -0,0 +1,45 @@ +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" +) + +// 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 + ok bool + err error + ) + + urlVars = mux.Vars(r) + associationKey, ok = urlVars["associationKey"] + if !ok { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + messages, err = Database.GetMessagesByAssociationKey(associationKey) + 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/Messages/UpdateConversation.go b/Backend/Api/Messages/UpdateConversation.go new file mode 100644 index 0000000..93b5215 --- /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 []Models.ConversationDetailUser `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 new file mode 100644 index 0000000..50f4f01 --- /dev/null +++ b/Backend/Api/Routes.go @@ -0,0 +1,79 @@ +package Api + +import ( + "log" + "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" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Users" + + "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, Content Length: %d", + 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 err error + + _, err = Auth.CheckCookie(r) + if err != nil { + http.Error(w, "Forbidden", http.StatusUnauthorized) + return + } + + next.ServeHTTP(w, r) + }) +} + +// InitAPIEndpoints initializes all API endpoints required by mobile app +func InitAPIEndpoints(router *mux.Router) { + var ( + 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") + + authAPI = api.PathPrefix("/auth/").Subrouter() + authAPI.Use(authenticationMiddleware) + + authAPI.HandleFunc("/check", Auth.Check).Methods("GET") + + authAPI.HandleFunc("/users", Users.SearchUsers).Methods("GET") + + 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.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/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/ConversationDetails.go b/Backend/Database/ConversationDetails.go new file mode 100644 index 0000000..9893022 --- /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 IN ?", id). + Find(&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..0f6e58a --- /dev/null +++ b/Backend/Database/FriendRequests.go @@ -0,0 +1,63 @@ +package Database + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +// GetFriendRequestByID gets friend request +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 +} + +// GetFriendRequestsByUserID gets friend request by user id +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 +} + +// CreateFriendRequest creates friend request +func CreateFriendRequest(friendRequest *Models.FriendRequest) error { + return DB.Create(friendRequest). + 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). + Updates(friendRequest). + Error +} + +// DeleteFriendRequest deletes friend request +func DeleteFriendRequest(friendRequest *Models.FriendRequest) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Delete(friendRequest). + Error +} diff --git a/Backend/Database/Init.go b/Backend/Database/Init.go new file mode 100644 index 0000000..4124949 --- /dev/null +++ b/Backend/Database/Init.go @@ -0,0 +1,69 @@ +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" + dbTestUrl = "postgres://postgres:@localhost:5432/envelope_test" +) + +var DB *gorm.DB + +func GetModels() []interface{} { + return []interface{}{ + &Models.Session{}, + &Models.User{}, + &Models.FriendRequest{}, + &Models.MessageData{}, + &Models.Message{}, + &Models.ConversationDetail{}, + &Models.ConversationDetailUser{}, + &Models.UserConversation{}, + } +} + +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/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 new file mode 100644 index 0000000..67cf8d3 --- /dev/null +++ b/Backend/Database/Messages.go @@ -0,0 +1,60 @@ +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 GetMessagesByAssociationKey(associationKey string) ([]Models.Message, error) { + var ( + messages []Models.Message + err error + ) + + err = DB.Preload("MessageData"). + Find(&messages, "association_key = ?", associationKey). + 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 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). + Error +} diff --git a/Backend/Database/Seeder/FriendSeeder.go b/Backend/Database/Seeder/FriendSeeder.go new file mode 100644 index 0000000..f3b5203 --- /dev/null +++ b/Backend/Database/Seeder/FriendSeeder.go @@ -0,0 +1,113 @@ +package Seeder + +import ( + "encoding/base64" + "time" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" +) + +func seedFriend(userRequestTo, userRequestFrom Models.User, accepted bool) error { + var ( + friendRequest Models.FriendRequest + symKey aesKey + encPublicKey []byte + err error + ) + + symKey, err = generateAesKey() + if err != nil { + return err + } + + encPublicKey, err = symKey.aesEncrypt([]byte(publicKey)) + if err != nil { + return err + } + + friendRequest = Models.FriendRequest{ + UserID: userRequestTo.ID, + FriendID: base64.StdEncoding.EncodeToString( + 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.Key, decodedPublicKey), + ), + } + + 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 + ) + + primaryUser, err = Database.GetUserByUsername("testUser") + if err != nil { + panic(err) + } + + secondaryUser, err = Database.GetUserByUsername("ATestUser2") + if err != nil { + panic(err) + } + + err = seedFriend(primaryUser, secondaryUser, true) + if err != nil { + panic(err) + } + + err = seedFriend(secondaryUser, primaryUser, true) + if err != nil { + panic(err) + } + + accepted = false + + for i = 0; i <= 5; i++ { + secondaryUser, err = Database.GetUserByUsername(userNames[i]) + if err != nil { + panic(err) + } + + if i > 3 { + accepted = true + } + + 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/Seeder/MessageSeeder.go b/Backend/Database/Seeder/MessageSeeder.go new file mode 100644 index 0000000..0480131 --- /dev/null +++ b/Backend/Database/Seeder/MessageSeeder.go @@ -0,0 +1,313 @@ +package Seeder + +import ( + "encoding/base64" + + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "github.com/gofrs/uuid" +) + +func seedMessage( + primaryUser, secondaryUser Models.User, + primaryUserAssociationKey, secondaryUserAssociationKey string, + i int, +) error { + var ( + message Models.Message + messageData Models.MessageData + key, userKey aesKey + keyCiphertext []byte + plaintext string + dataCiphertext []byte + senderIDCiphertext []byte + err error + ) + + plaintext = "Test Message" + + userKey, err = generateAesKey() + if err != nil { + panic(err) + } + + 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())) + if err != nil { + panic(err) + } + + if i%2 == 0 { + senderIDCiphertext, err = key.aesEncrypt([]byte(secondaryUser.ID.String())) + 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), + SymmetricKey: base64.StdEncoding.EncodeToString(keyCiphertext), + } + + message = Models.Message{ + MessageData: messageData, + SymmetricKey: base64.StdEncoding.EncodeToString( + encryptWithPublicKey(userKey.Key, decodedPublicKey), + ), + AssociationKey: primaryUserAssociationKey, + } + + err = Database.CreateMessage(&message) + if err != nil { + return err + } + + message = Models.Message{ + MessageData: messageData, + SymmetricKey: base64.StdEncoding.EncodeToString( + encryptWithPublicKey(userKey.Key, decodedPublicKey), + ), + AssociationKey: secondaryUserAssociationKey, + } + + return Database.CreateMessage(&message) +} + +func seedConversationDetail(key aesKey) (Models.ConversationDetail, error) { + var ( + messageThread Models.ConversationDetail + name string + nameCiphertext []byte + twoUserCiphertext []byte + err error + ) + + name = "Test Conversation" + + nameCiphertext, err = key.aesEncrypt([]byte(name)) + if err != nil { + panic(err) + } + + twoUserCiphertext, err = key.aesEncrypt([]byte("false")) + if err != nil { + panic(err) + } + + messageThread = Models.ConversationDetail{ + Name: base64.StdEncoding.EncodeToString(nameCiphertext), + TwoUser: base64.StdEncoding.EncodeToString(twoUserCiphertext), + } + + err = Database.CreateConversationDetail(&messageThread) + return messageThread, err +} + +func seedUserConversation( + user Models.User, + threadID uuid.UUID, + key aesKey, +) (Models.UserConversation, error) { + var ( + messageThreadUser Models.UserConversation + conversationDetailIDCiphertext []byte + adminCiphertext []byte + err error + ) + + conversationDetailIDCiphertext, err = key.aesEncrypt([]byte(threadID.String())) + if err != nil { + return messageThreadUser, err + } + + adminCiphertext, err = key.aesEncrypt([]byte("true")) + if err != nil { + return messageThreadUser, err + } + + messageThreadUser = Models.UserConversation{ + UserID: user.ID, + ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext), + Admin: base64.StdEncoding.EncodeToString(adminCiphertext), + SymmetricKey: base64.StdEncoding.EncodeToString( + encryptWithPublicKey(key.Key, decodedPublicKey), + ), + } + + err = Database.CreateUserConversation(&messageThreadUser) + 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 + + userIDCiphertext []byte + usernameCiphertext []byte + adminCiphertext []byte + associationKeyCiphertext []byte + publicKeyCiphertext []byte + + adminString = "false" + + 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 +} + +// SeedMessages seeds messages & conversations for testing +func SeedMessages() { + var ( + conversationDetail Models.ConversationDetail + key aesKey + primaryUser Models.User + primaryUserAssociationKey uuid.UUID + secondaryUser Models.User + secondaryUserAssociationKey uuid.UUID + i int + err error + ) + + key, err = generateAesKey() + if err != nil { + panic(err) + } + conversationDetail, err = seedConversationDetail(key) + + 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 { + panic(err) + } + + _, err = seedUserConversation( + primaryUser, + conversationDetail.ID, + key, + ) + if err != nil { + panic(err) + } + + secondaryUser, err = Database.GetUserByUsername("ATestUser2") + if err != nil { + panic(err) + } + + _, err = seedUserConversation( + secondaryUser, + conversationDetail.ID, + key, + ) + if err != nil { + panic(err) + } + + _, err = seedConversationDetailUser( + primaryUser, + conversationDetail, + primaryUserAssociationKey, + true, + key, + ) + if err != nil { + panic(err) + } + + _, err = seedConversationDetailUser( + secondaryUser, + conversationDetail, + secondaryUserAssociationKey, + false, + key, + ) + if err != nil { + panic(err) + } + + for i = 0; i <= 20; i++ { + err = seedMessage( + primaryUser, + secondaryUser, + primaryUserAssociationKey.String(), + secondaryUserAssociationKey.String(), + 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..7e9a373 --- /dev/null +++ b/Backend/Database/Seeder/Seed.go @@ -0,0 +1,97 @@ +package Seeder + +import ( + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "errors" + "log" +) + +const ( + // Encrypted with "password" + encryptedPrivateKey string = `sPhQsHpXYFqPb7qdmTY7APFwBb4m7meCITujDeKMQFnIjplOVm9ijjXU+YAmGvrX13ukBj8zo9MTVhjJUjJ917pyLhl4w8uyg1jCvplUYtJVXhGA9Wy3NqHMuq3SU3fKdlEM+oR4zYkbAYWp42XvulbcuVBEWiWkvHOrbdKPFpMmd54SL2c/vcWrmjgC7rTlJf2TYICZwRK+6Y0XZi5fSWeU0vg7+rHWKHc5MHHtAdAiL+HCa90c5gfh+hXkT5ojGHOkhT9kdLy3PTPN19EGpdXgZ3WFq1z9CZ6zX7uM091uR0IvgzfwaLx8HJCx7ViWQhioH9LJZgC73RMf/dwzejg2COy4QT/E59RPOczgd779rxiRmphMoR8xJYBFRlkTVmcUO4NcUE50Cc39hXezcekHuV1YQK4BXTrxGX1ceiCXYlKAWS9wHZpog9OldTCPBpw5XAWExh3kRzqdvsdHxHVE+TpAEIjDljAlc3r+FPHYH1zWWk41eQ/zz3Vkx5Zl4dMF9x+uUOspQXVb/4K42e9fMKychNUN5o/JzIwy7xOzgXa6iwf223On/mXKV6FK6Q8lojK7Wc8g7AwfqnN9//HjI14pVqGBJtn5ggL/g4qt0JFl3pV/6n/ZLMG6k8wpsaApLGvsTPqZHcv+C69Z33rZQ4TagXVxpmnWMpPCaR0+Dawn4iAce2UvUtIN2KbJNcTtRQo4z30+BbgmVKHgkR0EHMu4cYjJPYwJ5H8IYcQuFKb7+Cp33FD2Lv54I9uvtVHH9bWcid9K82y68PufJi/0icZ3EyEqZygez9mgJzxXO1b7xZMiosGs82QRv7IIOSzqBPRYv1Lxi3fWkgnOvw4dWFxJnKEI2+KD9K0z+XsgVlm26fdRklQAAf6xOJ1nJXBScbm12FBTWLMjLzHWz/iI9mQ+eGV9AREqrgQjUayXdnCsa0Q9bTTktxBkrJND4NUEDSGklhj9SY+VM0mhgAbkCvSE59vKtcNmCHx2Y+JnbZyKzJ71EaErX9vOpYCneKOjn8phVBJHQHM16QRLGyW4DUfn2CtAvb7Kks56kf/mn9YZDU68zSoLzm9rz7fjS2OUsxwmuv2IRCv/UTGgtfEfCs34qzagADfTNKTou7qkedhoygvuHiN4PzgGnjw1DQMks9PWr44z1gvIV4pEGiqgIuNHDjxKsfgQy0Cp2AV1+FNLWd1zd5t/K2pXR+knDoeHIZ2m6txQMl9I4GIyQ1bQFJWrYXPS8oMjvoH0YYVsHyShBsU2SKlG7nGbuUyoCR1EtRIzHMgP1Dq+Whqdbv67pRvhGVmydkCh0wbD+LJBcp2KJK+EQT9vv6GT5JW0oVHnE5TEXCnEJOW/rMhNMTMSccRmnVdguIE4HZsXx+cmV36jHgEt9bzcsvyWvFFoG4xL+t2UUnztX870vu//XaeVuOEAgehY/KLncrY7lhsQA4puCFIWpPteiCNhU1D8DTKc8V0ZtLT9a31SL1NLhZ+YHiD8Hs5SYdj6FW50E5yYUqPRPkg5mpbh88cRcPdsngCxU8iusNN3MSP07lO0h8zULDqtQsAq9p5o7IFTvWlAjekMy1sKTj3CuH7FuAkMHvwU0odMFeaS9T+8+4OGeprHwogWTzTbPnoOqOP/RC6vGfBvpju5s264hYguT24iXzhDFYk/8JQQe+USIbkQ7wXRw+/9cK8h5cs4LyaxMOx0pXHooxJ01bF8BYgYG4s0RB2gItzMk/L5/XhrOdWxEAdYR27s0dCN58gyvoU6phgQbTqvNTFYAObRcjfKfHu3PrFCYBBAKJ7Nm58C3rz832+ZTGVdQ3490TvO+sCLYKzpgtsqr8KyedG9LKa8wn/wlRD7kYn+J2SrMPY2Q0e4evyJaCAsolp/BQfy9JFtyRDPWTHn+jOHjW8ZN7vswGkRwYlSJSl0UC8mmJyS4lwnO/Vv4wBnDHQEzIycjn3JZAlV5ing0HKqUfW6G07453JXd8oZiMC/kIQjgWkdg34zxBYarVVrHFG5FIH9w7QWY8PCDU/kkcLniT0yD1/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 +) + +func Seed() { + var ( + block *pem.Block + decKey any + ok bool + err error + ) + + block, _ = pem.Decode([]byte(publicKey)) + decKey, err = x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + panic(err) + } + decodedPublicKey, ok = decKey.(*rsa.PublicKey) + if !ok { + 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() + + 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..ce13b2a --- /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("ATestUser2") + if err != nil { + panic(err) + } + + for i = 0; i <= 10; i++ { + _, err = createUser(userNames[i]) + if err != nil { + panic(err) + } + } +} 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..930a98f --- /dev/null +++ b/Backend/Database/UserConversations.go @@ -0,0 +1,91 @@ +package Database + +import ( + "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +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(userConversation *Models.UserConversation) error { + var err error + + err = DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(userConversation). + Error + + return err +} + +func CreateUserConversations(userConversations *[]Models.UserConversation) error { + var err error + + err = DB.Create(userConversations). + 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). + Error +} diff --git a/Backend/Database/Users.go b/Backend/Database/Users.go new file mode 100644 index 0000000..2df6a73 --- /dev/null +++ b/Backend/Database/Users.go @@ -0,0 +1,95 @@ +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 ( + user Models.User + err error + ) + + err = DB.Preload(clause.Associations). + First(&user, "id = ?", id). + Error + + return user, err +} + +func GetUserByUsername(username string) (Models.User, error) { + var ( + user Models.User + err error + ) + + err = DB.Preload(clause.Associations). + First(&user, "username = ?", username). + Error + + return user, 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(user *Models.User) error { + var err error + + err = DB.Session(&gorm.Session{FullSaveAssociations: true}). + Create(user). + Error + + return err +} + +func UpdateUser(id string, user *Models.User) error { + var err error + err = DB.Model(&user). + Omit("id"). + Where("id = ?", id). + Updates(user). + Error + + if err != nil { + return err + } + + err = DB.Model(Models.User{}). + Where("id = ?", id). + First(user). + Error + + return err +} + +func DeleteUser(user *Models.User) error { + return DB.Session(&gorm.Session{FullSaveAssociations: true}). + Delete(user). + Error +} diff --git a/Backend/Models/Base.go b/Backend/Models/Base.go new file mode 100644 index 0000000..797bccc --- /dev/null +++ b/Backend/Models/Base.go @@ -0,0 +1,31 @@ +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 + ) + + if !base.ID.IsNil() { + return nil + } + + id, err = uuid.NewV4() + if err != nil { + return err + } + + base.ID = id + return nil +} diff --git a/Backend/Models/Conversations.go b/Backend/Models/Conversations.go new file mode 100644 index 0000000..fa88987 --- /dev/null +++ b/Backend/Models/Conversations.go @@ -0,0 +1,35 @@ +package Models + +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"` + 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"` + 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 +} + +// 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"` + 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 +} diff --git a/Backend/Models/Friends.go b/Backend/Models/Friends.go new file mode 100644 index 0000000..967af7d --- /dev/null +++ b/Backend/Models/Friends.go @@ -0,0 +1,19 @@ +package Models + +import ( + "database/sql" + + "github.com/gofrs/uuid" +) + +// 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"` + 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/Models/Messages.go b/Backend/Models/Messages.go new file mode 100644 index 0000000..663d72d --- /dev/null +++ b/Backend/Models/Messages.go @@ -0,0 +1,24 @@ +package Models + +import ( + "time" + + "github.com/gofrs/uuid" +) + +// 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"` // Stored encrypted + SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted +} + +type Message struct { + Base + MessageDataID uuid.UUID `json:"message_data_id"` + MessageData MessageData `json:"message_data"` + 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"` +} 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 new file mode 100644 index 0000000..4727e26 --- /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 string `gorm:"not null" json:"asymmetric_private_key"` // Stored encrypted + AsymmetricPublicKey string `gorm:"not null" json:"asymmetric_public_key"` +} 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/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) +} 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 new file mode 100644 index 0000000..127bb75 --- /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 + golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 + 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/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..e9dc701 --- /dev/null +++ b/Backend/main.go @@ -0,0 +1,45 @@ +package main + +import ( + "flag" + "log" + "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() { + var ( + router *mux.Router + err error + ) + + if seed { + Seeder.Seed() + return + } + + router = mux.NewRouter() + + Api.InitAPIEndpoints(router) + + 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 dd411b9..d52d837 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,18 @@ # Envelope -Encrypted messaging app \ No newline at end of file +Encrypted messaging app + +## TODO + +[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/.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..f630962 --- /dev/null +++ b/mobile/analysis_options.yaml @@ -0,0 +1,30 @@ +# 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 + prefer_single_quotes: true + +# 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..df5e935 --- /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 20 + 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..c3bfaaa --- /dev/null +++ b/mobile/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + 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 0000000..db77bb4 Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ 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 0000000..17987b7 Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ 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 0000000..d5f1c8d Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ 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 0000000..4d6372e Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ 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 0000000..dc9ada4 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..28c6bf0 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..2ccbfd9 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ 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 0000000..f091b6b Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cde121 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ 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 0000000..d0ef06e Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..dcdc230 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..2ccbfd9 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ 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 0000000..c8f9ed8 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ 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 0000000..a6d6b86 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ 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 0000000..a6d6b86 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ 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 0000000..75b2d16 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ 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 index 0000000..c4df70d Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..6a84f41 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..d0e1f58 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ 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 0000000..9da19ea Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ 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 0000000..9da19ea Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ 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..d3ba628 --- /dev/null +++ b/mobile/ios/Runner/Info.plist @@ -0,0 +1,51 @@ + + + + + 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 + + io.flutter.embedded_views_preview + + NSCameraUsageDescription + This app needs camera access to scan QR codes + + 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/components/custom_circle_avatar.dart b/mobile/lib/components/custom_circle_avatar.dart new file mode 100644 index 0000000..bf7d1b8 --- /dev/null +++ b/mobile/lib/components/custom_circle_avatar.dart @@ -0,0 +1,79 @@ +import 'package:flutter/material.dart'; + +enum AvatarTypes { + initials, + icon, + image, +} + +class CustomCircleAvatar extends StatefulWidget { + final String? initials; + final Icon? icon; + final String? imagePath; + final double radius; + + const CustomCircleAvatar({ + Key? key, + this.initials, + this.icon, + this.imagePath, + this.radius = 20, + }) : super(key: key); + + @override + _CustomCircleAvatarState createState() => _CustomCircleAvatarState(); +} + +class _CustomCircleAvatarState extends State{ + AvatarTypes type = AvatarTypes.image; + + @override + void initState() { + super.initState(); + + if (widget.imagePath != null) { + 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 avatar(); + } +} 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/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/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 new file mode 100644 index 0000000..656c188 --- /dev/null +++ b/mobile/lib/main.dart @@ -0,0 +1,102 @@ +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() async { + await dotenv.load(fileName: ".env"); + runApp(const MyApp()); +} + +class MyApp extends StatelessWidget { + const MyApp({Key? key}) : super(key: key); + + 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( + 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, + ), + filled: false, + ), + ), + darkTheme: ThemeData( + brightness: Brightness.dark, + primaryColor: Colors.orange.shade900, + backgroundColor: Colors.grey.shade800, + colorScheme: ColorScheme( + brightness: Brightness.dark, + primary: Colors.orange.shade900, + onPrimary: Colors.white, + secondary: Colors.orange.shade900, + onSecondary: Colors.white, + tertiary: Colors.grey.shade500, + onTertiary: Colors.black, + error: Colors.red, + onError: Colors.white, + 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 new file mode 100644 index 0000000..04ca747 --- /dev/null +++ b/mobile/lib/models/conversation_users.dart @@ -0,0 +1,184 @@ +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'; + +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'], + publicKey: CryptoUtils.rsaPublicKeyFromPem(maps[0]['asymmetric_public_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: 'username', + ); + + 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{ + String id; + String userId; + String conversationId; + String username; + String associationKey; + RSAPublicKey publicKey; + bool admin; + ConversationUser({ + required this.id, + required this.userId, + required this.conversationId, + required this.username, + required this.associationKey, + required this.publicKey, + required this.admin, + }); + + 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'], + conversationId: json['conversation_detail_id'], + userId: userId, + username: username, + associationKey: associationKey, + publicKey: publicKey, + admin: admin == 'true', + ); + } + + Map toJson() { + return { + 'id': id, + 'user_id': userId, + 'username': username, + 'association_key': associationKey, + 'asymmetric_public_key': publicKeyPem(), + 'admin': admin ? 'true' : 'false', + }; + } + + Map toMap() { + return { + 'id': id, + 'user_id': userId, + '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 new file mode 100644 index 0000000..e7d760d --- /dev/null +++ b/mobile/lib/models/conversations.dart @@ -0,0 +1,370 @@ +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'; + +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'; + +Future createConversation(String title, List friends, bool twoUser) 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)); + + Conversation conversation = Conversation( + id: conversationId, + userId: profile.id, + symmetricKey: base64.encode(symmetricKey), + admin: true, + name: title, + twoUser: twoUser, + status: ConversationStatus.pending, + isRead: true, + ); + + 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: uuid.v4(), + publicKey: profile.publicKey!, + admin: true, + ).toMap(), + conflictAlgorithm: ConflictAlgorithm.fail, + ); + + for (Friend friend in friends) { + await db.insert( + 'conversation_users', + ConversationUser( + id: uuid.v4(), + userId: friend.friendId, + conversationId: conversationId, + username: friend.username, + associationKey: uuid.v4(), + publicKey: friend.publicKey, + 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; +} + + +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(), + publicKey: friend.publicKey, + admin: false, + ).toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + return conversation; +} + +Conversation findConversationByDetailId(List conversations, String id) { + for (var conversation in conversations) { + if (conversation.id == 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'], + 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, + ); +} + +// 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', + orderBy: 'name', + ); + + return List.generate(maps.length, (i) { + return Conversation( + id: maps[i]['id'], + userId: maps[i]['user_id'], + 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(); + + 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; + String userId; + String symmetricKey; + bool admin; + String name; + bool twoUser; + ConversationStatus status; + bool isRead; + + Conversation({ + required this.id, + required this.userId, + required this.symmetricKey, + required this.admin, + required this.name, + required this.twoUser, + required this.status, + required this.isRead, + }); + + + factory Conversation.fromJson(Map json, RSAPrivateKey privKey) { + var symmetricKeyDecrypted = CryptoUtils.rsaDecrypt( + base64.decode(json['symmetric_key']), + privKey, + ); + + var id = AesHelper.aesDecrypt( + symmetricKeyDecrypted, + base64.decode(json['conversation_detail_id']), + ); + + var admin = AesHelper.aesDecrypt( + symmetricKeyDecrypted, + base64.decode(json['admin']), + ); + + return Conversation( + id: id, + userId: json['user_id'], + symmetricKey: base64.encode(symmetricKeyDecrypted), + admin: admin == 'true', + name: 'Unknown', + twoUser: false, + status: ConversationStatus.complete, + isRead: true, + ); + } + + Future> payloadJson({ bool includeUsers = true }) async { + MyProfile profile = await MyProfile.getProfile(); + + var symKey = base64.decode(symmetricKey); + + if (!includeUsers) { + return { + 'id': id, + 'name': AesHelper.aesEncrypt(symKey, Uint8List.fromList(name.codeUnits)), + 'users': await getEncryptedConversationUsers(this, symKey), + }; + } + + List users = await getConversationUsers(this); + + List userConversations = []; + + for (ConversationUser user in users) { + + RSAPublicKey pubKey = profile.publicKey!; + String newId = id; + + if (profile.id != user.userId) { + Friend friend = await getFriendByFriendId(user.userId); + pubKey = friend.publicKey; + newId = (const Uuid()).v4(); + } + + userConversations.add({ + 'id': newId, + 'user_id': user.userId, + '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': 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, + }; + } + + Map toMap() { + return { + 'id': id, + 'user_id': userId, + 'symmetric_key': symmetricKey, + 'admin': admin ? 1 : 0, + 'name': name, + 'two_user': twoUser ? 1 : 0, + 'status': status.index, + 'is_read': isRead ? 1 : 0, + }; + } + + @override + String toString() { + return ''' + + + id: $id + userId: $userId + 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, + ); + } +} + + +enum ConversationStatus { + complete, + pending, + error, +} diff --git a/mobile/lib/models/friends.dart b/mobile/lib/models/friends.dart new file mode 100644 index 0000000..c435697 --- /dev/null +++ b/mobile/lib/models/friends.dart @@ -0,0 +1,194 @@ +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'; + +Friend findFriendByFriendId(List friends, String id) { + for (var friend in friends) { + if (friend.friendId == id) { + return friend; + } + } + // Or return `null`. + 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{ + String id; + String userId; + String username; + String friendId; + String friendSymmetricKey; + RSAPublicKey publicKey; + DateTime? acceptedAt; + bool? selected; + Friend({ + required this.id, + required this.userId, + required this.username, + required this.friendId, + required this.friendSymmetricKey, + required this.publicKey, + required this.acceptedAt, + this.selected, + }); + + factory Friend.fromJson(Map json, RSAPrivateKey privKey) { + Uint8List idDecrypted = CryptoUtils.rsaDecrypt( + base64.decode(json['friend_id']), + privKey, + ); + + Uint8List username = CryptoUtils.rsaDecrypt( + base64.decode(json['friend_username']), + privKey, + ); + + Uint8List symmetricKeyDecrypted = CryptoUtils.rsaDecrypt( + base64.decode(json['symmetric_key']), + privKey, + ); + + 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(username), + friendId: String.fromCharCodes(idDecrypted), + friendSymmetricKey: base64.encode(symmetricKeyDecrypted), + publicKey: publicKey, + acceptedAt: json['accepted_at']['Valid'] ? + DateTime.parse(json['accepted_at']['Time']) : + null, + ); + } + + 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); + } + + Map toMap() { + return { + 'id': id, + 'user_id': userId, + 'username': username, + 'friend_id': friendId, + 'symmetric_key': base64.encode(friendSymmetricKey.codeUnits), + 'asymmetric_public_key': publicKeyPem(), + 'accepted_at': acceptedAt?.toIso8601String(), + }; + } + + @override + String toString() { + return ''' + + + id: $id + userId: $userId + username: $username + friendId: $friendId + accepted_at: $acceptedAt'''; + } +} diff --git a/mobile/lib/models/messages.dart b/mobile/lib/models/messages.dart new file mode 100644 index 0000000..e88594f --- /dev/null +++ b/mobile/lib/models/messages.dart @@ -0,0 +1,197 @@ +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'; +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'; + +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; + String symmetricKey; + String userSymmetricKey; + String data; + String senderId; + String senderUsername; + String associationKey; + String createdAt; + bool failedToSend; + Message({ + required this.id, + required this.symmetricKey, + required this.userSymmetricKey, + required this.data, + required this.senderId, + required this.senderUsername, + required this.associationKey, + required this.createdAt, + required this.failedToSend, + }); + + + factory Message.fromJson(Map json, RSAPrivateKey privKey) { + var userSymmetricKey = CryptoUtils.rsaDecrypt( + base64.decode(json['symmetric_key']), + privKey, + ); + + var symmetricKey = AesHelper.aesDecrypt( + userSymmetricKey, + base64.decode(json['message_data']['symmetric_key']), + ); + + var senderId = AesHelper.aesDecrypt( + 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'], + symmetricKey: symmetricKey, + userSymmetricKey: base64.encode(userSymmetricKey), + data: data, + senderId: senderId, + senderUsername: 'Unknown', + associationKey: json['association_key'], + createdAt: json['created_at'], + failedToSend: false, + ); + } + + 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 = []; + List conversationUsers = await getConversationUsers(conversation); + + for (var i = 0; i < conversationUsers.length; i++) { + ConversationUser user = conversationUsers[i]; + + if (profile.id == user.userId) { + id = user.id; + + messages.add({ + 'id': messageId, + 'message_data_id': messageDataId, + 'symmetric_key': base64.encode(CryptoUtils.rsaEncrypt( + userSymmetricKey, + publicKey, + )), + 'association_key': user.associationKey, + }); + + continue; + } + + ConversationUser conversationUser = await getConversationUser(conversation, user.userId); + RSAPublicKey friendPublicKey = conversationUser.publicKey; + + 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), + ), + }; + + return jsonEncode({ + 'message_data': messageData, + 'message': messages, + }); + } + + Map toMap() { + return { + 'id': id, + 'symmetric_key': symmetricKey, + 'user_symmetric_key': userSymmetricKey, + 'data': data, + 'sender_id': senderId, + 'sender_username': senderUsername, + 'association_key': associationKey, + 'created_at': createdAt, + 'failed_to_send': failedToSend ? 1 : 0, + }; + } + + @override + String toString() { + return ''' + + + id: $id + data: $data + senderId: $senderId + senderUsername: $senderUsername + associationKey: $associationKey + createdAt: $createdAt + '''; + } + +} diff --git a/mobile/lib/models/my_profile.dart b/mobile/lib/models/my_profile.dart new file mode 100644 index 0000000..0c0207f --- /dev/null +++ b/mobile/lib/models/my_profile.dart @@ -0,0 +1,111 @@ +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; + String? friendId; + RSAPrivateKey? privateKey; + RSAPublicKey? publicKey; + DateTime? loggedInAt; + + MyProfile({ + required this.id, + required this.username, + this.friendId, + this.privateKey, + this.publicKey, + this.loggedInAt, + }); + + factory MyProfile._fromJson(Map json) { + DateTime loggedInAt = DateTime.now(); + if (json.containsKey('logged_in_at')) { + 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: privateKey, + publicKey: publicKey, + 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': privateKey != null ? + CryptoUtils.encodeRSAPrivateKeyToPem(privateKey!) : + null, + 'asymmetric_public_key': publicKey != null ? + CryptoUtils.encodeRSAPublicKeyToPem(publicKey!) : + null, + '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(); + 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(); + if (profile.loggedInAt == null) { + return false; + } + + return profile.loggedInAt!.add(const Duration(hours: 12)).isAfter( + (DateTime.now()) + ); + } + + static Future getPrivateKey() async { + MyProfile profile = await MyProfile.getProfile(); + if (profile.privateKey == null) { + throw Exception('Could not get privateKey'); + } + return profile.privateKey!; + } +} + diff --git a/mobile/lib/utils/encryption/aes_helper.dart b/mobile/lib/utils/encryption/aes_helper.dart new file mode 100644 index 0000000..adad897 --- /dev/null +++ b/mobile/lib/utils/encryption/aes_helper.dart @@ -0,0 +1,152 @@ +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(dynamic password, Uint8List plaintext, + {String mode = cbcMode}) { + + Uint8List derivedKey; + if (password is String) { + derivedKey = deriveKey(password); + } else { + derivedKey = 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(dynamic password, Uint8List ciphertext, + {String mode = cbcMode}) { + + Uint8List derivedKey; + if (password is String) { + derivedKey = deriveKey(password); + } else { + derivedKey = 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/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 new file mode 100644 index 0000000..72e854b --- /dev/null +++ b/mobile/lib/utils/encryption/rsa_key_helper.dart @@ -0,0 +1,260 @@ +import 'dart:convert'; +import 'dart:math'; +import 'dart:typed_data'; +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 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-----', + ]; + 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.zero); + + 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.one); + var exp1 = ASN1Integer(dP); + var dQ = privateKey.privateExponent! % (privateKey.q! - BigInt.one); + 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/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/conversations.dart b/mobile/lib/utils/storage/conversations.dart new file mode 100644 index 0000000..fc65477 --- /dev/null +++ b/mobile/lib/utils/storage/conversations.dart @@ -0,0 +1,165 @@ +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'; +import 'package:sqflite/sqflite.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'; + +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 { + RSAPrivateKey privKey = await MyProfile.getPrivateKey(); + + // 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 conversationsJson = jsonDecode(resp.body); + + if (conversationsJson.isEmpty) { + return; + } + + for (var i = 0; i < conversationsJson.length; i++) { + Conversation conversation = Conversation.fromJson( + conversationsJson[i] as Map, + privKey, + ); + conversations.add(conversation); + conversationsDetailIds.add(conversation.id); + } + + 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.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(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + + List usersData = conversationDetailJson['users']; + + for (var i = 0; i < usersData.length; i++) { + ConversationUser conversationUser = ConversationUser.fromJson( + usersData[i] as Map, + base64.decode(conversation.symmetricKey), + ); + + await db.insert( + 'conversation_users', + conversationUser.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + } + // } catch (SocketException) { + // return; + // } +} + + +Future uploadConversation(Conversation conversation, BuildContext context) async { + String sessionCookie = await getSessionCookie(); + + Map conversationJson = await conversation.payloadJson(); + + var resp = 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), + ); + + if (resp.statusCode != 200) { + showMessage('Failed to create conversation', context); + } +} + diff --git a/mobile/lib/utils/storage/database.dart b/mobile/lib/utils/storage/database.dart new file mode 100644 index 0000000..e643f53 --- /dev/null +++ b/mobile/lib/utils/storage/database.dart @@ -0,0 +1,79 @@ +import 'dart:async'; +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(); + + final path = join(await getDatabasesPath(), 'envelope.db'); + + final database = openDatabase( + path, + 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, + symmetric_key TEXT, + asymmetric_public_key TEXT, + accepted_at TEXT + ); + '''); + + await db.execute( + ''' + CREATE TABLE IF NOT EXISTS conversations( + id TEXT PRIMARY KEY, + user_id TEXT, + symmetric_key TEXT, + admin INTEGER, + name TEXT, + two_user INTEGER, + status INTEGER, + is_read INTEGER + ); + '''); + + await db.execute( + ''' + CREATE TABLE IF NOT EXISTS conversation_users( + id TEXT PRIMARY KEY, + user_id TEXT, + conversation_id TEXT, + username TEXT, + association_key TEXT, + admin INTEGER, + asymmetric_public_key TEXT + ); + '''); + + await db.execute( + ''' + CREATE TABLE IF NOT EXISTS messages( + id TEXT PRIMARY KEY, + symmetric_key TEXT, + user_symmetric_key TEXT, + data TEXT, + sender_id TEXT, + sender_username TEXT, + association_key TEXT, + created_at TEXT, + failed_to_send INTEGER + ); + '''); + + }, + version: 2, + ); + + return database; +} diff --git a/mobile/lib/utils/storage/friends.dart b/mobile/lib/utils/storage/friends.dart new file mode 100644 index 0000000..9ed41eb --- /dev/null +++ b/mobile/lib/utils/storage/friends.dart @@ -0,0 +1,49 @@ +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 '/models/friends.dart'; +import '/models/my_profile.dart'; +import '/utils/storage/database.dart'; +import '/utils/storage/session_cookie.dart'; + +Future updateFriends() async { + RSAPrivateKey privKey = await MyProfile.getPrivateKey(); + + // try { + var resp = await http.get( + Uri.parse('${dotenv.env["SERVER_URL"]}api/v1/auth/friend_requests'), + headers: { + 'cookie': await getSessionCookie(), + } + ); + + if (resp.statusCode != 200) { + throw Exception(resp.body); + } + + final db = await getDatabaseConnection(); + + List friendsRequestJson = jsonDecode(resp.body); + + for (var i = 0; i < friendsRequestJson.length; i++) { + Friend friend = Friend.fromJson( + friendsRequestJson[i] as Map, + privKey, + ); + + 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 new file mode 100644 index 0000000..b551672 --- /dev/null +++ b/mobile/lib/utils/storage/messages.dart @@ -0,0 +1,121 @@ +import 'dart:convert'; + +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:http/http.dart' as http; +import 'package:sqflite/sqflite.dart'; +import 'package:uuid/uuid.dart'; + +import '/models/conversation_users.dart'; +import '/models/conversations.dart'; +import '/models/messages.dart'; +import '/models/my_profile.dart'; +import '/utils/storage/database.dart'; +import '/utils/storage/session_cookie.dart'; + +Future sendMessage(Conversation conversation, String data) async { + MyProfile profile = await MyProfile.getProfile(); + + var uuid = const Uuid(); + final String messageId = uuid.v4(); + + ConversationUser currentUser = await getConversationUser(conversation, profile.id); + + Message message = Message( + id: messageId, + symmetricKey: '', + userSymmetricKey: '', + senderId: currentUser.userId, + senderUsername: profile.username, + data: data, + associationKey: currentUser.associationKey, + createdAt: DateTime.now().toIso8601String(), + failedToSend: false, + ); + + final db = await getDatabaseConnection(); + + await db.insert( + 'messages', + message.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace, + ); + + String sessionCookie = await getSessionCookie(); + + message.payloadJson(conversation, messageId) + .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], + ); + throw exception; + }); +} + +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/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/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/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/authentication/login.dart b/mobile/lib/views/authentication/login.dart new file mode 100644 index 0000000..b608703 --- /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:flutter_dotenv/flutter_dotenv.dart'; +import '/models/my_profile.dart'; +import '/utils/storage/session_cookie.dart'; + +class LoginResponse { + final String status; + final String message; + final String publicKey; + final String privateKey; + final String userId; + final String username; + + const LoginResponse({ + required this.status, + required this.message, + 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'], + publicKey: json['asymmetric_public_key'], + privateKey: json['asymmetric_private_key'], + userId: json['user_id'], + username: json['username'], + ); + } +} + +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, + }), + ); + + 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)); + } + + return await MyProfile.login(json.decode(resp.body), password); +} + +class Login extends StatelessWidget { + const Login({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: null, + automaticallyImplyLeading: true, + leading: IconButton(icon: const Icon(Icons.arrow_back), + onPressed:() => { + Navigator.pop(context) + } + ), + backgroundColor: Colors.transparent, + shadowColor: Colors.transparent, + ), + body: const SafeArea( + child: LoginWidget(), + ), + ); + } +} + +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, + ); + + 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: 80, + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + 'Login', + 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 'Enter 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: 15), + 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((val) { + 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/signup.dart b/mobile/lib/views/authentication/signup.dart new file mode 100644 index 0000000..c9d3447 --- /dev/null +++ b/mobile/lib/views/authentication/signup.dart @@ -0,0 +1,237 @@ +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'; + +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); + + String encRsaPriv = AesHelper.aesEncrypt(password, Uint8List.fromList(rsaPrivPem.codeUnits)); + + // TODO: Check for timeout here + final resp = await http.post( + Uri.parse('${dotenv.env["SERVER_URL"]}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( + 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 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); + + @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, + ); + + 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 new file mode 100644 index 0000000..6bcd086 --- /dev/null +++ b/mobile/lib/views/authentication/unauthenticated_landing.dart @@ -0,0 +1,98 @@ +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: 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( + fontSize: 20, + fontWeight: FontWeight.bold, + ), + ); + + return WillPopScope( + onWillPop: () async => false, + child: Scaffold( + body: SafeArea( + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Center( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + FaIcon( + FontAwesomeIcons.envelope, + color: Theme.of(context).colorScheme.onBackground, + size: 40 + ), + const SizedBox(width: 15), + Text( + 'Envelope', + style: TextStyle( + fontSize: 40, + color: Theme.of(context).colorScheme.onBackground, + ), + ) + ] + ), + ), + const SizedBox(height: 10), + Padding( + padding: const EdgeInsets.only( + top: 15, + bottom: 15, + left: 20, + right: 20, + ), + 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/conversation/create_add_users.dart b/mobile/lib/views/main/conversation/create_add_users.dart new file mode 100644 index 0000000..e1ddf59 --- /dev/null +++ b/mobile/lib/views/main/conversation/create_add_users.dart @@ -0,0 +1,164 @@ +import 'package:flutter/material.dart'; + +import '/models/friends.dart'; +import '/views/main/conversation/create_add_users_list.dart'; + +class ConversationAddFriendsList extends StatefulWidget { + final List friends; + final Function(List friendsSelected) saveCallback; + const ConversationAddFriendsList({ + Key? key, + required this.friends, + required this.saveCallback, + }) : super(key: key); + + @override + State createState() => _ConversationAddFriendsListState(); +} + +class _ConversationAddFriendsListState extends State { + List friends = []; + List friendsSelected = []; + + @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: () { + widget.saveCallback(friendsSelected); + + setState(() { + friendsSelected = []; + }); + }, + backgroundColor: Theme.of(context).colorScheme.primary, + child: friendsSelected.isEmpty ? + const Text('Skip') : + const Icon(Icons.add, size: 30), + ), + ), + ); + } + + 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 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/detail.dart b/mobile/lib/views/main/conversation/detail.dart new file mode 100644 index 0000000..d0bbca2 --- /dev/null +++ b/mobile/lib/views/main/conversation/detail.dart @@ -0,0 +1,268 @@ +import 'package:Envelope/components/custom_title_bar.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 '/utils/time.dart'; +import '/views/main/conversation/settings.dart'; + +class ConversationDetail extends StatefulWidget{ + final Conversation conversation; + const ConversationDetail({ + Key? key, + required this.conversation, + }) : super(key: key); + + @override + _ConversationDetailState createState() => _ConversationDetailState(); + +} + +class _ConversationDetailState extends State { + List messages = []; + MyProfile profile = MyProfile(id: '', username: ''); + + TextEditingController msgController = TextEditingController(); + + @override + Widget build(BuildContext context) { + return Scaffold( + 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 + )), + ); + }, + 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 + ), + backgroundColor: Theme.of(context).primaryColor, + ), + ), + ), + const SizedBox(width: 10), + ], + ), + ), + ), + ), + ], + ), + ); + } + + 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(); + } + + 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/edit_details.dart b/mobile/lib/views/main/conversation/edit_details.dart new file mode 100644 index 0000000..a0441b9 --- /dev/null +++ b/mobile/lib/views/main/conversation/edit_details.dart @@ -0,0 +1,148 @@ +import 'package:flutter/material.dart'; + +import '/components/custom_circle_avatar.dart'; +import '/models/conversations.dart'; + +class ConversationEditDetails extends StatefulWidget { + final Function(String conversationName) saveCallback; + final Conversation? conversation; + const ConversationEditDetails({ + Key? key, + required this.saveCallback, + this.conversation, + }) : super(key: key); + + @override + State createState() => _ConversationEditDetails(); +} + +class _ConversationEditDetails extends State { + final _formKey = GlobalKey(); + + List conversations = []; + + 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( + 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: [ + const CustomCircleAvatar( + icon: 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()) { + // 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 new file mode 100644 index 0000000..cabf6f0 --- /dev/null +++ b/mobile/lib/views/main/conversation/list.dart @@ -0,0 +1,159 @@ +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'; + +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; + final List friends; + const ConversationList({ + Key? key, + required this.conversations, + required this.friends, + }) : super(key: key); + + @override + State createState() => _ConversationListState(); +} + +class _ConversationListState extends State { + List conversations = []; + List friends = []; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: const CustomTitleBar( + title: Text( + 'Conversations', + 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()) + ), + 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, + false, + ); + + uploadConversation(conversation, context); + + 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), + ), + ), + ); + } + + 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(); + setState(() {}); + } +} 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..816b996 --- /dev/null +++ b/mobile/lib/views/main/conversation/list_item.dart @@ -0,0 +1,119 @@ +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; + const ConversationListItem({ + Key? key, + required this.conversation, + }) : super(key: key); + + @override + _ConversationListItemState createState() => _ConversationListItemState(); +} + +class _ConversationListItemState extends State { + late Conversation conversation; + 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( + 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) + ), + 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(), + ], + ), + ), + ], + ), + ), + ); + } + + @override + void initState() { + super.initState(); + getConversationData(); + } + + Future getConversationData() async { + conversation = widget.conversation; + recentMessage = await conversation.getRecentMessage(); + 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 new file mode 100644 index 0000000..35939e1 --- /dev/null +++ b/mobile/lib/views/main/conversation/settings.dart @@ -0,0 +1,304 @@ +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'; +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; + const ConversationSettings({ + Key? key, + required this.conversation, + }) : super(key: key); + + @override + State createState() => _ConversationSettingsState(); +} + +class _ConversationSettingsState extends State { + List users = []; + MyProfile? profile; + + TextEditingController nameController = TextEditingController(); + + @override + Widget build(BuildContext context) { + return Scaffold( + 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), + 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: widget.conversation.admin && !widget.conversation.twoUser), + 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, + ), + ), + widget.conversation.admin && !widget.conversation.twoUser ? 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], + ); + + await updateConversation(widget.conversation, includeUsers: true); + setState(() {}); + Navigator.pop(context); + }, + conversation: widget.conversation, + )), + ).then(onGoBack); + }, + ) : const SizedBox.shrink(), + ], + ); + } + + 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, { bool showUsersAdd = false}) { + return Align( + 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); + }, + )) + ); + }, + ), + ], + ) + ) + ); + } + + 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 usersList() { + return ListView.builder( + 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 + ); + } + ); + } + + 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'], + publicKey: CryptoUtils.rsaPublicKeyFromPem(maps[i]['asymmetric_public_key']), + acceptedAt: maps[i]['accepted_at'], + username: maps[i]['username'], + ); + }); + } + + onGoBack(dynamic value) async { + nameController.text = widget.conversation.name; + 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 new file mode 100644 index 0000000..a527e23 --- /dev/null +++ b/mobile/lib/views/main/conversation/settings_user_list_item.dart @@ -0,0 +1,136 @@ +import 'package:flutter/material.dart'; + +import '/components/custom_circle_avatar.dart'; +import '/models/conversation_users.dart'; +import '/models/my_profile.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 + _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 || widget.user.admin || widget.user.username == widget.profile.username) { + return const SizedBox(height: 50); + } + + 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') + ], + ), + ), + ], + offset: const Offset(0, 0), + 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: 12,right: 5,top: 0,bottom: 5), + child: Row( + children: [ + Expanded( + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + CustomCircleAvatar( + initials: widget.user.username[0].toUpperCase(), + imagePath: null, + 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/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 new file mode 100644 index 0000000..8f19a61 --- /dev/null +++ b/mobile/lib/views/main/friend/list.dart @@ -0,0 +1,195 @@ +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'; + +import '/models/friends.dart'; +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 + State createState() => _FriendListState(); +} + +class _FriendListState extends State { + List friends = []; + List friendRequests = []; + + List friendsDuplicate = []; + List friendRequestsDuplicate = []; + + @override + Widget build(BuildContext context) { + return Scaffold( + 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: () { + Navigator.of(context).push( + MaterialPageRoute(builder: (context) => const QrReader()) + );//.then(onGoBack); // TODO + }, + 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(friends); + + if(query.isNotEmpty) { + List dummyListData = []; + for (Friend item in dummySearchList) { + if(item.username.toLowerCase().contains(query)) { + dummyListData.add(item); + } + } + setState(() { + friends.clear(); + friends.addAll(dummyListData); + }); + return; + } + + setState(() { + friends.clear(); + friends.addAll(friends); + }); + } + + @override + void initState() { + super.initState(); + 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) { + 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'), + ); + } + + 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 new file mode 100644 index 0000000..582f296 --- /dev/null +++ b/mobile/lib/views/main/friend/list_item.dart @@ -0,0 +1,79 @@ +import 'package:Envelope/components/custom_circle_avatar.dart'; +import 'package:Envelope/models/conversations.dart'; +import 'package:Envelope/models/friends.dart'; +import 'package:Envelope/utils/storage/conversations.dart'; +import 'package:Envelope/utils/strings.dart'; +import 'package:Envelope/views/main/conversation/detail.dart'; +import 'package:flutter/material.dart'; + +class FriendListItem extends StatefulWidget{ + final Friend friend; + const FriendListItem({ + Key? key, + required this.friend, + }) : super(key: key); + + @override + _FriendListItemState createState() => _FriendListItemState(); +} + +class _FriendListItemState extends State { + + @override + Widget build(BuildContext context) { + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { findOrCreateConversation(context); }, + 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)), + ], + ), + ), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } + + Future findOrCreateConversation(BuildContext context) async { + Conversation? conversation = await getTwoUserConversation(widget.friend.friendId); + + conversation ??= await createConversation( + generateRandomString(32), + [ widget.friend ], + true, + ); + + uploadConversation(conversation, context); + + Navigator.push(context, MaterialPageRoute(builder: (context){ + return ConversationDetail( + conversation: conversation!, + ); + })); + } +} 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..21b81b0 --- /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.friendId, + '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 new file mode 100644 index 0000000..f6bfb92 --- /dev/null +++ b/mobile/lib/views/main/home.dart @@ -0,0 +1,207 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_dotenv/flutter_dotenv.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); + + @override + State createState() => _HomeState(); +} + +class _HomeState extends State { + List conversations = []; + List friends = []; + List friendRequests = []; + MyProfile profile = MyProfile( + id: '', + username: '', + ); + + bool isLoading = true; + int _selectedIndex = 0; + List _widgetOptions = [ + const ConversationList(conversations: [], friends: []), + FriendList(friends: const [], friendRequests: const [], callback: () {}), + Profile( + profile: MyProfile( + id: '', + username: '', + ) + ), + ]; + + @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', + ), + ], + ), + ), + ); + } + + Future checkLogin() async { + bool isLoggedIn = false; + + try { + isLoggedIn = await MyProfile.isLoggedIn(); + } catch (Exception) { + Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); + return false; + } + + 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'), + headers: { + 'cookie': await getSessionCookie(), + } + ); + statusCode = resp.statusCode; + } catch(SocketException) { + if (await MyProfile.isLoggedIn()) { + return true; + } + } + + if (isLoggedIn && statusCode == 200) { + return true; + } + + MyProfile.logout(); + Navigator.pushNamedAndRemoveUntil(context, '/landing', ModalRoute.withName('/landing')); + return false; + } + + @override + void initState() { + updateData(); + super.initState(); + } + + 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...'), + ], + ) + ), + ] + ); + } + + void updateData() async { + if (!await checkLogin()) { + return; + } + + await updateFriends(); + await updateConversations(); + await updateMessageThreads(); + + 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; + }); + } + + 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) async { + await reinitDatabaseRecords(); + setState(() { + _selectedIndex = index; + }); + } +} diff --git a/mobile/lib/views/main/profile/profile.dart b/mobile/lib/views/main/profile/profile.dart new file mode 100644 index 0000000..5127da0 --- /dev/null +++ b/mobile/lib/views/main/profile/profile.dart @@ -0,0 +1,164 @@ +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'; +import '/utils/storage/database.dart'; +import '/models/my_profile.dart'; +import '/components/custom_circle_avatar.dart'; + +class Profile extends StatefulWidget { + 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() { + bool isTesting = dotenv.env["ENVIRONMENT"] == 'development'; + 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')); + } + ), + 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(), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + 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(), + ], + ) + ), + ); + } +} diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock new file mode 100644 index 0000000..917ab66 --- /dev/null +++ b/mobile/pubspec.lock @@ -0,0 +1,425 @@ +# 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: + 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.16.0" + convert: + dependency: transitive + description: + name: convert + 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: + 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.3.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 + 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: + 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" + flutter_web_plugins: + dependency: transitive + 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" + 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" + intl: + dependency: "direct main" + description: + name: intl + url: "https://pub.dartlang.org" + source: hosted + version: "0.17.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.4" + meta: + dependency: transitive + description: + name: meta + url: "https://pub.dartlang.org" + source: hosted + version: "1.7.0" + path: + dependency: "direct main" + description: + name: path + url: "https://pub.dartlang.org" + source: hosted + version: "1.8.1" + 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: + name: pointycastle + 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" + qr: + dependency: transitive + description: + name: qr + 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: + name: qr_flutter + url: "https://pub.dartlang.org" + source: hosted + version: "4.0.0" + 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 + source: sdk + version: "0.0.99" + source_span: + dependency: transitive + description: + name: source_span + 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: + 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" + synchronized: + dependency: transitive + description: + name: synchronized + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.0+2" + 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.9" + typed_data: + dependency: transitive + description: + name: typed_data + 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: + name: vector_math + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.2" + 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.17.0 <3.0.0" + flutter: ">=2.8.0" diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml new file mode 100644 index 0000000..6007c51 --- /dev/null +++ b/mobile/pubspec.yaml @@ -0,0 +1,40 @@ +name: Envelope +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 + asn1lib: ^1.1.0 + http: ^0.13.4 + shared_preferences: ^2.0.15 + sqflite: ^2.0.2 + path: 1.8.1 + flutter_dotenv: ^5.0.2 + intl: ^0.17.0 + uuid: ^3.0.6 + qr_flutter: ^4.0.0 + qr_code_scanner: ^1.0.1 + +dev_dependencies: + flutter_test: + sdk: flutter + + flutter_lints: ^1.0.0 + +flutter: + uses-material-design: true + + assets: + - .env + + diff --git a/mobile/test/pajamasenergy_qr_code.png b/mobile/test/pajamasenergy_qr_code.png new file mode 100644 index 0000000..84584a2 Binary files /dev/null and b/mobile/test/pajamasenergy_qr_code.png differ diff --git a/mobile/test/qr_payload.json b/mobile/test/qr_payload.json new file mode 100644 index 0000000..4ed2a36 --- /dev/null +++ b/mobile/test/qr_payload.json @@ -0,0 +1 @@ +{"i": "deffd741-d67f-469e-975f-b2272404a43e", "u": "pajamasenergy","k": "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KICBNSUlCSWpBTkJna3Foa2lHOXcwQkFRRUZBQU9DQVE4QU1JSUJDZ0tDQVFFQXlVbkVFQ2NWc1NzS254Wmx4K3VFCiAgSjBRVmNsdTNGTnVSZmp2V2N2ZW5hazQyMWVLN2xxODIrUHJjWml0dEdUMEx6TVF5M240Uk0wMTFteDJWZFQvMQogIDhZSmhLV2dWUjhCNTVJV2o4OHdvVG12eHRmQWc2QWphNE1sYzRlV3Q5VHFMVXdyaHBVdFcwcEVlZHhNVDEwS3YKICBKenlTcWpkYlhjQUxKYStIRSt0YzhxU2twbWJDV3ZkZlNHWGh5L2FkZjFERjVKMzA0WEVmYzk2MGVKWmVqdS9uCiAgWnEyYzJnM1NjOS9TQXQvQ3VjaWJFNFdydVlaM1hhYkxNTytwT0syZlNoUlpXMWlVaHhiMWlBSWJMWlFsZEpBcwogIEhRSmp6VlRXcjgwSDcwOFZuamRjZmJpVkxMVlpZT3RBMFFwa1lZd3ZQQ3UrN0ZQdFk2ZUhLZjFML0draGthY3IKICBaUUlEQVFBQgogIC0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQ=="} 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 0000000..8aaa46a Binary files /dev/null and b/mobile/web/favicon.png differ diff --git a/mobile/web/icons/Icon-192.png b/mobile/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/mobile/web/icons/Icon-192.png differ diff --git a/mobile/web/icons/Icon-512.png b/mobile/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/mobile/web/icons/Icon-512.png differ diff --git a/mobile/web/icons/Icon-maskable-192.png b/mobile/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/mobile/web/icons/Icon-maskable-192.png differ diff --git a/mobile/web/icons/Icon-maskable-512.png b/mobile/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/mobile/web/icons/Icon-maskable-512.png differ 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..b93c4c3 --- /dev/null +++ b/mobile/windows/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_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) + +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) 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 0000000..c04e20c Binary files /dev/null and b/mobile/windows/runner/resources/app_icon.ico differ 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_