Browse Source

Refactor to use model based create / update / delete

feature/add-notifications
Tovi Jaeschke-Rogers 2 years ago
parent
commit
78d51f70b8
55 changed files with 408 additions and 480 deletions
  1. +3
    -4
      Backend/Api/Auth/AddProfileImage.go
  2. +1
    -2
      Backend/Api/Auth/AddProfileImage_test.go
  3. +2
    -6
      Backend/Api/Auth/ChangePassword.go
  4. +2
    -6
      Backend/Api/Auth/ChangeUserMessageExpiry.go
  5. +4
    -5
      Backend/Api/Auth/Login.go
  6. +1
    -2
      Backend/Api/Auth/Login_test.go
  7. +1
    -2
      Backend/Api/Auth/Logout_test.go
  8. +6
    -7
      Backend/Api/Auth/Session.go
  9. +2
    -3
      Backend/Api/Auth/Signup.go
  10. +1
    -2
      Backend/Api/Auth/Signup_test.go
  11. +4
    -5
      Backend/Api/Friends/AcceptFriendRequest.go
  12. +4
    -5
      Backend/Api/Friends/AcceptFriendRequest_test.go
  13. +4
    -5
      Backend/Api/Friends/CreateFriendRequest.go
  14. +6
    -7
      Backend/Api/Friends/CreateFriendRequest_test.go
  15. +2
    -3
      Backend/Api/Friends/Friends.go
  16. +3
    -4
      Backend/Api/Friends/Friends_test.go
  17. +2
    -3
      Backend/Api/Friends/RejectFriendRequest.go
  18. +3
    -4
      Backend/Api/Messages/AddConversationImage.go
  19. +2
    -6
      Backend/Api/Messages/ChangeConversationMessageExpiry.go
  20. +4
    -5
      Backend/Api/Messages/Conversations.go
  21. +11
    -12
      Backend/Api/Messages/Conversations_test.go
  22. +13
    -14
      Backend/Api/Messages/CreateConversation.go
  23. +8
    -9
      Backend/Api/Messages/CreateConversation_test.go
  24. +5
    -6
      Backend/Api/Messages/CreateMessage.go
  25. +2
    -4
      Backend/Api/Messages/CreateMessage_test.go
  26. +2
    -3
      Backend/Api/Messages/MessageThread.go
  27. +8
    -9
      Backend/Api/Messages/MessageThread_test.go
  28. +9
    -10
      Backend/Api/Messages/UpdateConversation.go
  29. +15
    -16
      Backend/Api/Messages/UpdateConversation_test.go
  30. +1
    -2
      Backend/Api/Users/SearchUsers.go
  31. +2
    -2
      Backend/Api/Users/SearchUsers_test.go
  32. +16
    -8
      Backend/Database/Attachments.go
  33. +1
    -1
      Backend/Database/Base.go
  34. +22
    -11
      Backend/Database/ConversationDetailUsers.go
  35. +23
    -8
      Backend/Database/ConversationDetails.go
  36. +29
    -10
      Backend/Database/FriendRequests.go
  37. +9
    -11
      Backend/Database/Init.go
  38. +16
    -6
      Backend/Database/MessageData.go
  39. +1
    -1
      Backend/Database/MessageExpiry.go
  40. +25
    -8
      Backend/Database/Messages.go
  41. +6
    -7
      Backend/Database/Seeder/FriendSeeder.go
  42. +26
    -27
      Backend/Database/Seeder/MessageSeeder.go
  43. +5
    -6
      Backend/Database/Seeder/UserSeeder.go
  44. +19
    -6
      Backend/Database/Sessions.go
  45. +29
    -14
      Backend/Database/UserConversations.go
  46. +39
    -12
      Backend/Database/Users.go
  47. +0
    -11
      Backend/Models/Attachments.go
  48. +0
    -45
      Backend/Models/Conversations.go
  49. +0
    -22
      Backend/Models/Friends.go
  50. +0
    -31
      Backend/Models/Messages.go
  51. +0
    -18
      Backend/Models/Sessions.go
  52. +0
    -33
      Backend/Models/Users.go
  53. +6
    -7
      Backend/Tests/Init.go
  54. +2
    -3
      Backend/Util/UserHelper.go
  55. +1
    -1
      Backend/dev.sh

+ 3
- 4
Backend/Api/Auth/AddProfileImage.go View File

@ -6,15 +6,14 @@ import (
"net/http" "net/http"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Util" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Util"
) )
// AddProfileImage adds a profile image // AddProfileImage adds a profile image
func AddProfileImage(w http.ResponseWriter, r *http.Request) { func AddProfileImage(w http.ResponseWriter, r *http.Request) {
var ( var (
user Models.User
attachment Models.Attachment
user Database.User
attachment Database.Attachment
decodedFile []byte decodedFile []byte
fileName string fileName string
err error err error
@ -50,7 +49,7 @@ func AddProfileImage(w http.ResponseWriter, r *http.Request) {
user.Attachment = attachment user.Attachment = attachment
err = Database.UpdateUser(user.ID.String(), &user)
err = (&user).UpdateUser()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return


+ 1
- 2
Backend/Api/Auth/AddProfileImage_test.go View File

@ -10,7 +10,6 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests"
) )
@ -40,7 +39,7 @@ func Test_AddProfileImage(t *testing.T) {
return return
} }
a := Models.Attachment{
a := Database.Attachment{
Mimetype: "image/png", Mimetype: "image/png",
Extension: "png", Extension: "png",
Data: base64.StdEncoding.EncodeToString(encDat), Data: base64.StdEncoding.EncodeToString(encDat),


+ 2
- 6
Backend/Api/Auth/ChangePassword.go View File

@ -6,7 +6,6 @@ import (
"net/http" "net/http"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
type rawChangePassword struct { type rawChangePassword struct {
@ -19,7 +18,7 @@ type rawChangePassword struct {
// ChangePassword handle change password action // ChangePassword handle change password action
func ChangePassword(w http.ResponseWriter, r *http.Request) { func ChangePassword(w http.ResponseWriter, r *http.Request) {
var ( var (
user Models.User
user Database.User
changePassword rawChangePassword changePassword rawChangePassword
requestBody []byte requestBody []byte
err error err error
@ -63,10 +62,7 @@ func ChangePassword(w http.ResponseWriter, r *http.Request) {
// Private key doesn't change at this point, is just re-encrypted with the new password // Private key doesn't change at this point, is just re-encrypted with the new password
user.AsymmetricPrivateKey = changePassword.PrivateKey user.AsymmetricPrivateKey = changePassword.PrivateKey
err = Database.UpdateUser(
user.ID.String(),
&user,
)
err = (&user).UpdateUser()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return


+ 2
- 6
Backend/Api/Auth/ChangeUserMessageExpiry.go View File

@ -6,7 +6,6 @@ import (
"net/http" "net/http"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
type rawChangeMessageExpiry struct { type rawChangeMessageExpiry struct {
@ -16,7 +15,7 @@ type rawChangeMessageExpiry struct {
// ChangeUserMessageExpiry handles changing default message expiry for user // ChangeUserMessageExpiry handles changing default message expiry for user
func ChangeUserMessageExpiry(w http.ResponseWriter, r *http.Request) { func ChangeUserMessageExpiry(w http.ResponseWriter, r *http.Request) {
var ( var (
user Models.User
user Database.User
changeMessageExpiry rawChangeMessageExpiry changeMessageExpiry rawChangeMessageExpiry
requestBody []byte requestBody []byte
err error err error
@ -43,10 +42,7 @@ func ChangeUserMessageExpiry(w http.ResponseWriter, r *http.Request) {
return return
} }
err = Database.UpdateUser(
user.ID.String(),
&user,
)
err = (&user).UpdateUser()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return


+ 4
- 5
Backend/Api/Auth/Login.go View File

@ -7,7 +7,6 @@ import (
"time" "time"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
type credentials struct { type credentials struct {
@ -29,8 +28,8 @@ type loginResponse struct {
func Login(w http.ResponseWriter, r *http.Request) { func Login(w http.ResponseWriter, r *http.Request) {
var ( var (
creds credentials creds credentials
user Models.User
session Models.Session
user Database.User
session Database.Session
expiresAt time.Time expiresAt time.Time
messageExpiryRaw driver.Value messageExpiryRaw driver.Value
messageExpiry string messageExpiry string
@ -59,12 +58,12 @@ func Login(w http.ResponseWriter, r *http.Request) {
// TODO: Revisit before production // TODO: Revisit before production
expiresAt = time.Now().Add(12 * time.Hour) expiresAt = time.Now().Add(12 * time.Hour)
session = Models.Session{
session = Database.Session{
UserID: user.ID, UserID: user.ID,
Expiry: expiresAt, Expiry: expiresAt,
} }
err = Database.CreateSession(&session)
err = (&session).CreateSession()
if err != nil { if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized) http.Error(w, "Unauthorized", http.StatusUnauthorized)
return return


+ 1
- 2
Backend/Api/Auth/Login_test.go View File

@ -7,7 +7,6 @@ import (
"testing" "testing"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests"
) )
@ -50,7 +49,7 @@ func Test_Login(t *testing.T) {
return return
} }
var session Models.Session
var session Database.Session
err = Database.DB.First(&session, "user_id = ?", u.ID.String()).Error err = Database.DB.First(&session, "user_id = ?", u.ID.String()).Error


+ 1
- 2
Backend/Api/Auth/Logout_test.go View File

@ -5,7 +5,6 @@ import (
"testing" "testing"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests"
) )
@ -28,7 +27,7 @@ func Test_Logout(t *testing.T) {
return return
} }
var session Models.Session
var session Database.Session
u, err := Database.GetUserByUsername("test") u, err := Database.GetUserByUsername("test")
if err != nil { if err != nil {


+ 6
- 7
Backend/Api/Auth/Session.go View File

@ -5,14 +5,13 @@ import (
"net/http" "net/http"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
func CheckCookie(r *http.Request) (Models.Session, error) {
func CheckCookie(r *http.Request) (Database.Session, error) {
var ( var (
c *http.Cookie c *http.Cookie
sessionToken string sessionToken string
userSession Models.Session
userSession Database.Session
err error err error
) )
@ -31,17 +30,17 @@ func CheckCookie(r *http.Request) (Models.Session, error) {
// If the session is present, but has expired, we can delete the session, and return // If the session is present, but has expired, we can delete the session, and return
// an unauthorized status // an unauthorized status
if userSession.IsExpired() { if userSession.IsExpired() {
Database.DeleteSession(&userSession)
(&userSession).DeleteSession()
return userSession, errors.New("Cookie expired") return userSession, errors.New("Cookie expired")
} }
return userSession, nil return userSession, nil
} }
func CheckCookieCurrentUser(w http.ResponseWriter, r *http.Request) (Models.User, error) {
func CheckCookieCurrentUser(w http.ResponseWriter, r *http.Request) (Database.User, error) {
var ( var (
session Models.Session
userData Models.User
session Database.Session
userData Database.User
err error err error
) )


+ 2
- 3
Backend/Api/Auth/Signup.go View File

@ -5,7 +5,6 @@ import (
"net/http" "net/http"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
type signup struct { type signup struct {
@ -20,7 +19,7 @@ type signup struct {
// Signup to the platform // Signup to the platform
func Signup(w http.ResponseWriter, r *http.Request) { func Signup(w http.ResponseWriter, r *http.Request) {
var ( var (
user Models.User
user Database.User
err error err error
) )
@ -58,7 +57,7 @@ func Signup(w http.ResponseWriter, r *http.Request) {
return return
} }
err = Database.CreateUser(&user)
err = (&user).CreateUser()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return


+ 1
- 2
Backend/Api/Auth/Signup_test.go View File

@ -13,7 +13,6 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Api" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
@ -65,7 +64,7 @@ func Test_Signup(t *testing.T) {
return return
} }
var user Models.User
var user Database.User
err = Database.DB.First(&user, "username = ?", "test").Error err = Database.DB.First(&user, "username = ?", "test").Error


+ 4
- 5
Backend/Api/Friends/AcceptFriendRequest.go View File

@ -7,15 +7,14 @@ import (
"time" "time"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
// AcceptFriendRequest accepts friend requests // AcceptFriendRequest accepts friend requests
func AcceptFriendRequest(w http.ResponseWriter, r *http.Request) { func AcceptFriendRequest(w http.ResponseWriter, r *http.Request) {
var ( var (
oldFriendRequest Models.FriendRequest
newFriendRequest Models.FriendRequest
oldFriendRequest Database.FriendRequest
newFriendRequest Database.FriendRequest
urlVars map[string]string urlVars map[string]string
friendRequestID string friendRequestID string
requestBody []byte requestBody []byte
@ -51,7 +50,7 @@ func AcceptFriendRequest(w http.ResponseWriter, r *http.Request) {
return return
} }
err = Database.UpdateFriendRequest(&oldFriendRequest)
err = (&oldFriendRequest).UpdateFriendRequest()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return
@ -60,7 +59,7 @@ func AcceptFriendRequest(w http.ResponseWriter, r *http.Request) {
newFriendRequest.AcceptedAt.Time = time.Now() newFriendRequest.AcceptedAt.Time = time.Now()
newFriendRequest.AcceptedAt.Valid = true newFriendRequest.AcceptedAt.Valid = true
err = Database.CreateFriendRequest(&newFriendRequest)
err = (&newFriendRequest).CreateFriendRequest()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return


+ 4
- 5
Backend/Api/Friends/AcceptFriendRequest_test.go View File

@ -10,7 +10,6 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests"
) )
@ -47,7 +46,7 @@ func Test_AcceptFriendRequest(t *testing.T) {
return return
} }
friendReq := Models.FriendRequest{
friendReq := Database.FriendRequest{
UserID: u.ID, UserID: u.ID,
FriendID: base64.StdEncoding.EncodeToString( FriendID: base64.StdEncoding.EncodeToString(
Seeder.EncryptWithPublicKey( Seeder.EncryptWithPublicKey(
@ -69,13 +68,13 @@ func Test_AcceptFriendRequest(t *testing.T) {
), ),
} }
err = Database.CreateFriendRequest(&friendReq)
err = (&friendReq).CreateFriendRequest()
if err != nil { if err != nil {
t.Errorf("Expected nil, recieved %s", err.Error()) t.Errorf("Expected nil, recieved %s", err.Error())
return return
} }
friendReqResponse := Models.FriendRequest{
friendReqResponse := Database.FriendRequest{
UserID: u2.ID, UserID: u2.ID,
FriendID: base64.StdEncoding.EncodeToString( FriendID: base64.StdEncoding.EncodeToString(
Seeder.EncryptWithPublicKey( Seeder.EncryptWithPublicKey(
@ -120,7 +119,7 @@ func Test_AcceptFriendRequest(t *testing.T) {
return return
} }
var reqs []Models.FriendRequest
var reqs []Database.FriendRequest
err = Database.DB.Find(&reqs).Error err = Database.DB.Find(&reqs).Error
if err != nil { if err != nil {


+ 4
- 5
Backend/Api/Friends/CreateFriendRequest.go View File

@ -7,13 +7,12 @@ import (
"time" "time"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
// CreateFriendRequest creates a FriendRequest from post data // CreateFriendRequest creates a FriendRequest from post data
func CreateFriendRequest(w http.ResponseWriter, r *http.Request) { func CreateFriendRequest(w http.ResponseWriter, r *http.Request) {
var ( var (
friendRequest Models.FriendRequest
friendRequest Database.FriendRequest
requestBody []byte requestBody []byte
returnJSON []byte returnJSON []byte
err error err error
@ -33,7 +32,7 @@ func CreateFriendRequest(w http.ResponseWriter, r *http.Request) {
friendRequest.AcceptedAt.Scan(nil) friendRequest.AcceptedAt.Scan(nil)
err = Database.CreateFriendRequest(&friendRequest)
err = (&friendRequest).CreateFriendRequest()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return
@ -53,7 +52,7 @@ func CreateFriendRequest(w http.ResponseWriter, r *http.Request) {
// CreateFriendRequestQrCode creates a FriendRequest from post data from qr code scan // CreateFriendRequestQrCode creates a FriendRequest from post data from qr code scan
func CreateFriendRequestQrCode(w http.ResponseWriter, r *http.Request) { func CreateFriendRequestQrCode(w http.ResponseWriter, r *http.Request) {
var ( var (
friendRequests []Models.FriendRequest
friendRequests Database.FriendRequestList
requestBody []byte requestBody []byte
i int i int
err error err error
@ -76,7 +75,7 @@ func CreateFriendRequestQrCode(w http.ResponseWriter, r *http.Request) {
friendRequests[i].AcceptedAt.Valid = true friendRequests[i].AcceptedAt.Valid = true
} }
err = Database.CreateFriendRequests(&friendRequests)
err = (&friendRequests).CreateFriendRequests()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return


+ 6
- 7
Backend/Api/Friends/CreateFriendRequest_test.go View File

@ -9,7 +9,6 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests"
) )
@ -46,7 +45,7 @@ func Test_CreateFriendRequest(t *testing.T) {
return return
} }
friendReq := Models.FriendRequest{
friendReq := Database.FriendRequest{
UserID: u.ID, UserID: u.ID,
FriendID: base64.StdEncoding.EncodeToString( FriendID: base64.StdEncoding.EncodeToString(
Seeder.EncryptWithPublicKey( Seeder.EncryptWithPublicKey(
@ -83,7 +82,7 @@ func Test_CreateFriendRequest(t *testing.T) {
return return
} }
var r Models.FriendRequest
var r Database.FriendRequest
err = Database.DB.First(&r).Error err = Database.DB.First(&r).Error
if err != nil { if err != nil {
@ -130,7 +129,7 @@ func Test_CreateFriendRequestQrCode(t *testing.T) {
return return
} }
friendReq := Models.FriendRequest{
friendReq := Database.FriendRequest{
UserID: u.ID, UserID: u.ID,
FriendID: base64.StdEncoding.EncodeToString( FriendID: base64.StdEncoding.EncodeToString(
Seeder.EncryptWithPublicKey( Seeder.EncryptWithPublicKey(
@ -152,7 +151,7 @@ func Test_CreateFriendRequestQrCode(t *testing.T) {
), ),
} }
friendReq2 := Models.FriendRequest{
friendReq2 := Database.FriendRequest{
UserID: u2.ID, UserID: u2.ID,
FriendID: base64.StdEncoding.EncodeToString( FriendID: base64.StdEncoding.EncodeToString(
Seeder.EncryptWithPublicKey( Seeder.EncryptWithPublicKey(
@ -174,7 +173,7 @@ func Test_CreateFriendRequestQrCode(t *testing.T) {
), ),
} }
jsonStr, _ := json.Marshal([]Models.FriendRequest{friendReq, friendReq2})
jsonStr, _ := json.Marshal([]Database.FriendRequest{friendReq, friendReq2})
req, _ := http.NewRequest("POST", ts.URL+"/api/v1/auth/friend_request/qr_code", bytes.NewBuffer(jsonStr)) req, _ := http.NewRequest("POST", ts.URL+"/api/v1/auth/friend_request/qr_code", bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
@ -189,7 +188,7 @@ func Test_CreateFriendRequestQrCode(t *testing.T) {
return return
} }
var r Models.FriendRequest
var r Database.FriendRequest
err = Database.DB.First(&r).Error err = Database.DB.First(&r).Error
if err != nil { if err != nil {


+ 2
- 3
Backend/Api/Friends/Friends.go View File

@ -8,14 +8,13 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
// FriendRequestList gets friend request list // FriendRequestList gets friend request list
func FriendRequestList(w http.ResponseWriter, r *http.Request) { func FriendRequestList(w http.ResponseWriter, r *http.Request) {
var ( var (
userSession Models.Session
friends []Models.FriendRequest
userSession Database.Session
friends Database.FriendRequestList
values url.Values values url.Values
returnJSON []byte returnJSON []byte
page int page int


+ 3
- 4
Backend/Api/Friends/Friends_test.go View File

@ -11,7 +11,6 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests"
) )
@ -45,7 +44,7 @@ func Test_FriendRequestList(t *testing.T) {
return return
} }
friendReq := Models.FriendRequest{
friendReq := Database.FriendRequest{
UserID: u.ID, UserID: u.ID,
FriendID: base64.StdEncoding.EncodeToString( FriendID: base64.StdEncoding.EncodeToString(
Seeder.EncryptWithPublicKey( Seeder.EncryptWithPublicKey(
@ -72,7 +71,7 @@ func Test_FriendRequestList(t *testing.T) {
friendReq.AcceptedAt.Valid = true friendReq.AcceptedAt.Valid = true
} }
err = Database.CreateFriendRequest(&friendReq)
err = (&friendReq).CreateFriendRequest()
if err != nil { if err != nil {
t.Errorf("Expected nil, recieved %s", err.Error()) t.Errorf("Expected nil, recieved %s", err.Error())
return return
@ -98,7 +97,7 @@ func Test_FriendRequestList(t *testing.T) {
return return
} }
var users []Models.FriendRequest
var users Database.FriendRequestList
json.Unmarshal(requestBody, &users) json.Unmarshal(requestBody, &users)


+ 2
- 3
Backend/Api/Friends/RejectFriendRequest.go View File

@ -4,7 +4,6 @@ import (
"net/http" "net/http"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
@ -12,7 +11,7 @@ import (
// RejectFriendRequest rejects friend requests // RejectFriendRequest rejects friend requests
func RejectFriendRequest(w http.ResponseWriter, r *http.Request) { func RejectFriendRequest(w http.ResponseWriter, r *http.Request) {
var ( var (
friendRequest Models.FriendRequest
friendRequest Database.FriendRequest
urlVars map[string]string urlVars map[string]string
friendRequestID string friendRequestID string
ok bool ok bool
@ -32,7 +31,7 @@ func RejectFriendRequest(w http.ResponseWriter, r *http.Request) {
return return
} }
err = Database.DeleteFriendRequest(&friendRequest)
err = (&friendRequest).DeleteFriendRequest()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return


+ 3
- 4
Backend/Api/Messages/AddConversationImage.go View File

@ -6,7 +6,6 @@ import (
"net/http" "net/http"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Util" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Util"
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
@ -14,8 +13,8 @@ import (
// AddConversationImage adds an image for a conversation icon // AddConversationImage adds an image for a conversation icon
func AddConversationImage(w http.ResponseWriter, r *http.Request) { func AddConversationImage(w http.ResponseWriter, r *http.Request) {
var ( var (
attachment Models.Attachment
conversationDetail Models.ConversationDetail
attachment Database.Attachment
conversationDetail Database.ConversationDetail
urlVars map[string]string urlVars map[string]string
detailID string detailID string
decodedFile []byte decodedFile []byte
@ -54,7 +53,7 @@ func AddConversationImage(w http.ResponseWriter, r *http.Request) {
conversationDetail.Attachment = attachment conversationDetail.Attachment = attachment
err = Database.UpdateConversationDetail(&conversationDetail)
err = (&conversationDetail).UpdateConversationDetail()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return


+ 2
- 6
Backend/Api/Messages/ChangeConversationMessageExpiry.go View File

@ -6,7 +6,6 @@ import (
"net/http" "net/http"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
@ -17,9 +16,8 @@ type rawChangeMessageExpiry struct {
// ChangeUserMessageExpiry handles changing default message expiry for user // ChangeUserMessageExpiry handles changing default message expiry for user
func ChangeConversationMessageExpiry(w http.ResponseWriter, r *http.Request) { func ChangeConversationMessageExpiry(w http.ResponseWriter, r *http.Request) {
var ( var (
// user Models.User
changeMessageExpiry rawChangeMessageExpiry changeMessageExpiry rawChangeMessageExpiry
conversationDetail Models.ConversationDetail
conversationDetail Database.ConversationDetail
requestBody []byte requestBody []byte
urlVars map[string]string urlVars map[string]string
detailID string detailID string
@ -62,9 +60,7 @@ func ChangeConversationMessageExpiry(w http.ResponseWriter, r *http.Request) {
return return
} }
err = Database.UpdateConversationDetail(
&conversationDetail,
)
err = (&conversationDetail).UpdateConversationDetail()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return


+ 4
- 5
Backend/Api/Messages/Conversations.go View File

@ -10,14 +10,13 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
// ConversationList returns an encrypted list of all Conversations // ConversationList returns an encrypted list of all Conversations
func ConversationList(w http.ResponseWriter, r *http.Request) { func ConversationList(w http.ResponseWriter, r *http.Request) {
var ( var (
conversationDetails []Models.UserConversation
userSession Models.Session
conversationDetails []Database.UserConversation
userSession Database.Session
returnJSON []byte returnJSON []byte
values url.Values values url.Values
page int page int
@ -55,8 +54,8 @@ func ConversationList(w http.ResponseWriter, r *http.Request) {
// ConversationDetailsList returns an encrypted list of all ConversationDetails // ConversationDetailsList returns an encrypted list of all ConversationDetails
func ConversationDetailsList(w http.ResponseWriter, r *http.Request) { func ConversationDetailsList(w http.ResponseWriter, r *http.Request) {
var ( var (
conversationDetails []Models.ConversationDetail
detail Models.ConversationDetail
conversationDetails []Database.ConversationDetail
detail Database.ConversationDetail
query url.Values query url.Values
conversationIds []string conversationIds []string
messageExpiryRaw driver.Value messageExpiryRaw driver.Value


+ 11
- 12
Backend/Api/Messages/Conversations_test.go View File

@ -10,7 +10,6 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests"
) )
@ -41,12 +40,12 @@ func Test_ConversationsList(t *testing.T) {
return return
} }
messageThread := Models.ConversationDetail{
messageThread := Database.ConversationDetail{
Name: base64.StdEncoding.EncodeToString(nameCiphertext), Name: base64.StdEncoding.EncodeToString(nameCiphertext),
TwoUser: base64.StdEncoding.EncodeToString(twoUserCiphertext), TwoUser: base64.StdEncoding.EncodeToString(twoUserCiphertext),
} }
err = Database.CreateConversationDetail(&messageThread)
err = (&messageThread).CreateConversationDetail()
if err != nil { if err != nil {
t.Errorf("Expected nil, recieved %s", err.Error()) t.Errorf("Expected nil, recieved %s", err.Error())
return return
@ -66,7 +65,7 @@ func Test_ConversationsList(t *testing.T) {
pubKey := Seeder.GetPubKey() pubKey := Seeder.GetPubKey()
messageThreadUser := Models.UserConversation{
messageThreadUser := Database.UserConversation{
UserID: u.ID, UserID: u.ID,
ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext), ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext),
Admin: base64.StdEncoding.EncodeToString(adminCiphertext), Admin: base64.StdEncoding.EncodeToString(adminCiphertext),
@ -75,7 +74,7 @@ func Test_ConversationsList(t *testing.T) {
), ),
} }
err = Database.CreateUserConversation(&messageThreadUser)
err = (&messageThreadUser).CreateUserConversation()
req, _ := http.NewRequest("GET", ts.URL+"/api/v1/auth/conversations", nil) req, _ := http.NewRequest("GET", ts.URL+"/api/v1/auth/conversations", nil)
@ -96,7 +95,7 @@ func Test_ConversationsList(t *testing.T) {
return return
} }
var conversations []Models.UserConversation
var conversations Database.UserConversationList
json.Unmarshal(requestBody, &conversations) json.Unmarshal(requestBody, &conversations)
@ -130,7 +129,7 @@ func Test_ConversationsList(t *testing.T) {
return return
} }
var conversationDetails []Models.ConversationDetail
var conversationDetails []Database.ConversationDetail
requestBody, err = ioutil.ReadAll(resp.Body) requestBody, err = ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
@ -190,12 +189,12 @@ func Test_ConversationsListPagination(t *testing.T) {
return return
} }
messageThread := Models.ConversationDetail{
messageThread := Database.ConversationDetail{
Name: base64.StdEncoding.EncodeToString(nameCiphertext), Name: base64.StdEncoding.EncodeToString(nameCiphertext),
TwoUser: base64.StdEncoding.EncodeToString(twoUserCiphertext), TwoUser: base64.StdEncoding.EncodeToString(twoUserCiphertext),
} }
err = Database.CreateConversationDetail(&messageThread)
err = (&messageThread).CreateConversationDetail()
if err != nil { if err != nil {
t.Errorf("Expected nil, recieved %s", err.Error()) t.Errorf("Expected nil, recieved %s", err.Error())
return return
@ -215,7 +214,7 @@ func Test_ConversationsListPagination(t *testing.T) {
pubKey := Seeder.GetPubKey() pubKey := Seeder.GetPubKey()
messageThreadUser := Models.UserConversation{
messageThreadUser := Database.UserConversation{
UserID: u.ID, UserID: u.ID,
ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext), ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext),
Admin: base64.StdEncoding.EncodeToString(adminCiphertext), Admin: base64.StdEncoding.EncodeToString(adminCiphertext),
@ -224,7 +223,7 @@ func Test_ConversationsListPagination(t *testing.T) {
), ),
} }
err = Database.CreateUserConversation(&messageThreadUser)
err = (&messageThreadUser).CreateUserConversation()
} }
req, _ := http.NewRequest("GET", ts.URL+"/api/v1/auth/conversations?page=0", nil) req, _ := http.NewRequest("GET", ts.URL+"/api/v1/auth/conversations?page=0", nil)
@ -246,7 +245,7 @@ func Test_ConversationsListPagination(t *testing.T) {
return return
} }
var conversations []Models.UserConversation
var conversations []Database.UserConversation
json.Unmarshal(requestBody, &conversations) json.Unmarshal(requestBody, &conversations)


+ 13
- 14
Backend/Api/Messages/CreateConversation.go View File

@ -7,26 +7,25 @@ import (
"github.com/gofrs/uuid" "github.com/gofrs/uuid"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
// RawCreateConversationData for holding POST payload // RawCreateConversationData for holding POST payload
type RawCreateConversationData struct { type RawCreateConversationData struct {
ID string `json:"id"`
Name string `json:"name"`
TwoUser string `json:"two_user"`
AdminAddMembers string `json:"admin_add_members"`
AdminEditInfo string `json:"admin_edit_info"`
AdminSendMessages string `json:"admin_send_messages"`
Users []Models.ConversationDetailUser `json:"users"`
UserConversations []Models.UserConversation `json:"user_conversations"`
ID string `json:"id"`
Name string `json:"name"`
TwoUser string `json:"two_user"`
AdminAddMembers string `json:"admin_add_members"`
AdminEditInfo string `json:"admin_edit_info"`
AdminSendMessages string `json:"admin_send_messages"`
Users []Database.ConversationDetailUser `json:"users"`
UserConversations Database.UserConversationList `json:"user_conversations"`
} }
// CreateConversation creates ConversationDetail, ConversationDetailUsers and UserConversations // CreateConversation creates ConversationDetail, ConversationDetailUsers and UserConversations
func CreateConversation(w http.ResponseWriter, r *http.Request) { func CreateConversation(w http.ResponseWriter, r *http.Request) {
var ( var (
rawConversationData RawCreateConversationData rawConversationData RawCreateConversationData
messageThread Models.ConversationDetail
messageThread Database.ConversationDetail
err error err error
) )
@ -36,8 +35,8 @@ func CreateConversation(w http.ResponseWriter, r *http.Request) {
return return
} }
messageThread = Models.ConversationDetail{
Base: Models.Base{
messageThread = Database.ConversationDetail{
Base: Database.Base{
ID: uuid.FromStringOrNil(rawConversationData.ID), ID: uuid.FromStringOrNil(rawConversationData.ID),
}, },
Name: rawConversationData.Name, Name: rawConversationData.Name,
@ -48,13 +47,13 @@ func CreateConversation(w http.ResponseWriter, r *http.Request) {
Users: rawConversationData.Users, Users: rawConversationData.Users,
} }
err = Database.CreateConversationDetail(&messageThread)
err = (&messageThread).CreateConversationDetail()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return
} }
err = Database.CreateUserConversations(&rawConversationData.UserConversations)
err = (&rawConversationData.UserConversations).CreateUserConversations()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return


+ 8
- 9
Backend/Api/Messages/CreateConversation_test.go View File

@ -9,7 +9,6 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests"
"github.com/gofrs/uuid" "github.com/gofrs/uuid"
) )
@ -74,16 +73,16 @@ func Test_CreateConversation(t *testing.T) {
pubKey := Seeder.GetPubKey() pubKey := Seeder.GetPubKey()
d := struct { d := 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"`
ID string `json:"id"`
Name string `json:"name"`
TwoUser string `json:"two_user"`
Users []Database.ConversationDetailUser `json:"users"`
UserConversations []Database.UserConversation `json:"user_conversations"`
}{ }{
ID: id.String(), ID: id.String(),
Name: base64.StdEncoding.EncodeToString(nameCiphertext), Name: base64.StdEncoding.EncodeToString(nameCiphertext),
TwoUser: base64.StdEncoding.EncodeToString(twoUserCiphertext), TwoUser: base64.StdEncoding.EncodeToString(twoUserCiphertext),
Users: []Models.ConversationDetailUser{
Users: []Database.ConversationDetailUser{
{ {
ConversationDetailID: id, ConversationDetailID: id,
UserID: base64.StdEncoding.EncodeToString(userIDCiphertext), UserID: base64.StdEncoding.EncodeToString(userIDCiphertext),
@ -93,7 +92,7 @@ func Test_CreateConversation(t *testing.T) {
Admin: base64.StdEncoding.EncodeToString(adminCiphertext), Admin: base64.StdEncoding.EncodeToString(adminCiphertext),
}, },
}, },
UserConversations: []Models.UserConversation{
UserConversations: []Database.UserConversation{
{ {
UserID: u.ID, UserID: u.ID,
ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext), ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext),
@ -119,7 +118,7 @@ func Test_CreateConversation(t *testing.T) {
t.Errorf("Expected %d, recieved %d", http.StatusNoContent, resp.StatusCode) t.Errorf("Expected %d, recieved %d", http.StatusNoContent, resp.StatusCode)
} }
var c Models.ConversationDetail
var c Database.ConversationDetail
err = Database.DB.First(&c, "id = ?", id.String()).Error err = Database.DB.First(&c, "id = ?", id.String()).Error
if err != nil { if err != nil {
t.Errorf("Expected conversation detail record, received %s", err.Error()) t.Errorf("Expected conversation detail record, received %s", err.Error())


+ 5
- 6
Backend/Api/Messages/CreateMessage.go View File

@ -7,13 +7,12 @@ import (
"time" "time"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Util" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Util"
) )
type rawMessageData struct { type rawMessageData struct {
MessageData Models.MessageData `json:"message_data"`
Messages []Models.Message `json:"message"`
MessageData Database.MessageData `json:"message_data"`
Messages Database.MessageList `json:"message"`
} }
// CreateMessage sends a message // CreateMessage sends a message
@ -21,7 +20,7 @@ func CreateMessage(w http.ResponseWriter, r *http.Request) {
var ( var (
messagesData []rawMessageData messagesData []rawMessageData
messageData rawMessageData messageData rawMessageData
message Models.Message
message Database.Message
t time.Time t time.Time
decodedFile []byte decodedFile []byte
fileName string fileName string
@ -53,13 +52,13 @@ func CreateMessage(w http.ResponseWriter, r *http.Request) {
} }
} }
err = Database.CreateMessageData(&messageData.MessageData)
err = (&messageData.MessageData).CreateMessageData()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return
} }
err = Database.CreateMessages(&messageData.Messages)
err = (&messageData.Messages).CreateMessages()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return


+ 2
- 4
Backend/Api/Messages/CreateMessage_test.go View File

@ -10,13 +10,11 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests"
"github.com/gofrs/uuid" "github.com/gofrs/uuid"
) )
// TODO: Write test for message expiry // TODO: Write test for message expiry
func Test_CreateMessage(t *testing.T) { func Test_CreateMessage(t *testing.T) {
client, ts, err := Tests.InitTestEnv() client, ts, err := Tests.InitTestEnv()
if err != nil { if err != nil {
@ -116,14 +114,14 @@ func Test_CreateMessage(t *testing.T) {
return return
} }
var m Models.Message
var m Database.Message
err = Database.DB.First(&m).Error err = Database.DB.First(&m).Error
if err != nil { if err != nil {
t.Errorf("Expected conversation detail record, received %s", err.Error()) t.Errorf("Expected conversation detail record, received %s", err.Error())
return return
} }
var md Models.MessageData
var md Database.MessageData
err = Database.DB.First(&md).Error err = Database.DB.First(&md).Error
if err != nil { if err != nil {
t.Errorf("Expected conversation detail record, received %s", err.Error()) t.Errorf("Expected conversation detail record, received %s", err.Error())


+ 2
- 3
Backend/Api/Messages/MessageThread.go View File

@ -7,7 +7,6 @@ import (
"strconv" "strconv"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
@ -15,8 +14,8 @@ import (
// Messages gets messages by the associationKey // Messages gets messages by the associationKey
func Messages(w http.ResponseWriter, r *http.Request) { func Messages(w http.ResponseWriter, r *http.Request) {
var ( var (
messages []Models.Message
message Models.Message
messages []Database.Message
message Database.Message
urlVars map[string]string urlVars map[string]string
associationKey string associationKey string
values url.Values values url.Values


+ 8
- 9
Backend/Api/Messages/MessageThread_test.go View File

@ -9,7 +9,6 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests"
) )
@ -56,8 +55,8 @@ func Test_Messages(t *testing.T) {
pubKey := Seeder.GetPubKey() pubKey := Seeder.GetPubKey()
message := Models.Message{
MessageData: Models.MessageData{
message := Database.Message{
MessageData: Database.MessageData{
Data: base64.StdEncoding.EncodeToString(dataCiphertext), Data: base64.StdEncoding.EncodeToString(dataCiphertext),
SenderID: base64.StdEncoding.EncodeToString(senderIDCiphertext), SenderID: base64.StdEncoding.EncodeToString(senderIDCiphertext),
SymmetricKey: base64.StdEncoding.EncodeToString(keyCiphertext), SymmetricKey: base64.StdEncoding.EncodeToString(keyCiphertext),
@ -68,7 +67,7 @@ func Test_Messages(t *testing.T) {
AssociationKey: "AssociationKey", AssociationKey: "AssociationKey",
} }
err = Database.CreateMessage(&message)
err = (&message).CreateMessage()
if err != nil { if err != nil {
t.Errorf("Expected nil, recieved %s", err.Error()) t.Errorf("Expected nil, recieved %s", err.Error())
return return
@ -91,7 +90,7 @@ func Test_Messages(t *testing.T) {
return return
} }
var m []Models.Message
var m Database.MessageList
err = json.Unmarshal(requestBody, &m) err = json.Unmarshal(requestBody, &m)
if len(m) != 1 { if len(m) != 1 {
@ -160,8 +159,8 @@ func Test_MessagesPagination(t *testing.T) {
pubKey := Seeder.GetPubKey() pubKey := Seeder.GetPubKey()
for i := 0; i < 50; i++ { for i := 0; i < 50; i++ {
message := Models.Message{
MessageData: Models.MessageData{
message := Database.Message{
MessageData: Database.MessageData{
Data: base64.StdEncoding.EncodeToString(dataCiphertext), Data: base64.StdEncoding.EncodeToString(dataCiphertext),
SenderID: base64.StdEncoding.EncodeToString(senderIDCiphertext), SenderID: base64.StdEncoding.EncodeToString(senderIDCiphertext),
SymmetricKey: base64.StdEncoding.EncodeToString(keyCiphertext), SymmetricKey: base64.StdEncoding.EncodeToString(keyCiphertext),
@ -172,7 +171,7 @@ func Test_MessagesPagination(t *testing.T) {
AssociationKey: "AssociationKey", AssociationKey: "AssociationKey",
} }
err = Database.CreateMessage(&message)
err = (&message).CreateMessage()
if err != nil { if err != nil {
t.Errorf("Expected nil, recieved %s", err.Error()) t.Errorf("Expected nil, recieved %s", err.Error())
return return
@ -196,7 +195,7 @@ func Test_MessagesPagination(t *testing.T) {
return return
} }
var m []Models.Message
var m Database.MessageList
err = json.Unmarshal(requestBody, &m) err = json.Unmarshal(requestBody, &m)
if len(m) != 20 { if len(m) != 20 {


+ 9
- 10
Backend/Api/Messages/UpdateConversation.go View File

@ -7,21 +7,20 @@ import (
"github.com/gofrs/uuid" "github.com/gofrs/uuid"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
type rawUpdateConversationData struct { type rawUpdateConversationData struct {
ID string `json:"id"`
Name string `json:"name"`
Users []Models.ConversationDetailUser `json:"users"`
UserConversations []Models.UserConversation `json:"user_conversations"`
ID string `json:"id"`
Name string `json:"name"`
Users []Database.ConversationDetailUser `json:"users"`
UserConversations Database.UserConversationList `json:"user_conversations"`
} }
// UpdateConversation updates the conversation data, such as title, users, etc // UpdateConversation updates the conversation data, such as title, users, etc
func UpdateConversation(w http.ResponseWriter, r *http.Request) { func UpdateConversation(w http.ResponseWriter, r *http.Request) {
var ( var (
rawConversationData rawUpdateConversationData rawConversationData rawUpdateConversationData
messageThread Models.ConversationDetail
messageThread Database.ConversationDetail
err error err error
) )
@ -31,22 +30,22 @@ func UpdateConversation(w http.ResponseWriter, r *http.Request) {
return return
} }
messageThread = Models.ConversationDetail{
Base: Models.Base{
messageThread = Database.ConversationDetail{
Base: Database.Base{
ID: uuid.FromStringOrNil(rawConversationData.ID), ID: uuid.FromStringOrNil(rawConversationData.ID),
}, },
Name: rawConversationData.Name, Name: rawConversationData.Name,
Users: rawConversationData.Users, Users: rawConversationData.Users,
} }
err = Database.UpdateConversationDetail(&messageThread)
err = (&messageThread).UpdateConversationDetail()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return
} }
if len(rawConversationData.UserConversations) > 0 { if len(rawConversationData.UserConversations) > 0 {
err = Database.UpdateOrCreateUserConversations(&rawConversationData.UserConversations)
err = (&rawConversationData.UserConversations).UpdateOrCreateUserConversations()
if err != nil { if err != nil {
http.Error(w, "Error", http.StatusInternalServerError) http.Error(w, "Error", http.StatusInternalServerError)
return return


+ 15
- 16
Backend/Api/Messages/UpdateConversation_test.go View File

@ -9,15 +9,14 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests"
) )
func createConversation(key Seeder.AesKey) (Models.ConversationDetail, Models.UserConversation, Models.ConversationDetailUser, error) {
func createConversation(key Seeder.AesKey) (Database.ConversationDetail, Database.UserConversation, Database.ConversationDetailUser, error) {
var ( var (
cd Models.ConversationDetail
uc Models.UserConversation
cdu Models.ConversationDetailUser
cd Database.ConversationDetail
uc Database.UserConversation
cdu Database.ConversationDetailUser
) )
u, err := Database.GetUserByUsername("test") u, err := Database.GetUserByUsername("test")
@ -32,12 +31,12 @@ func createConversation(key Seeder.AesKey) (Models.ConversationDetail, Models.Us
return cd, uc, cdu, err return cd, uc, cdu, err
} }
cd = Models.ConversationDetail{
cd = Database.ConversationDetail{
Name: base64.StdEncoding.EncodeToString(nameCiphertext), Name: base64.StdEncoding.EncodeToString(nameCiphertext),
TwoUser: base64.StdEncoding.EncodeToString(twoUserCiphertext), TwoUser: base64.StdEncoding.EncodeToString(twoUserCiphertext),
} }
err = Database.CreateConversationDetail(&cd)
err = (&cd).CreateConversationDetail()
if err != nil { if err != nil {
return cd, uc, cdu, err return cd, uc, cdu, err
} }
@ -54,7 +53,7 @@ func createConversation(key Seeder.AesKey) (Models.ConversationDetail, Models.Us
pubKey := Seeder.GetPubKey() pubKey := Seeder.GetPubKey()
uc = Models.UserConversation{
uc = Database.UserConversation{
UserID: u.ID, UserID: u.ID,
ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext), ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext),
Admin: base64.StdEncoding.EncodeToString(adminCiphertext), Admin: base64.StdEncoding.EncodeToString(adminCiphertext),
@ -63,7 +62,7 @@ func createConversation(key Seeder.AesKey) (Models.ConversationDetail, Models.Us
), ),
} }
err = Database.CreateUserConversation(&uc)
err = (&uc).CreateUserConversation()
if err != nil { if err != nil {
return cd, uc, cdu, err return cd, uc, cdu, err
} }
@ -93,7 +92,7 @@ func createConversation(key Seeder.AesKey) (Models.ConversationDetail, Models.Us
return cd, uc, cdu, err return cd, uc, cdu, err
} }
cdu = Models.ConversationDetailUser{
cdu = Database.ConversationDetailUser{
ConversationDetailID: cd.ID, ConversationDetailID: cd.ID,
UserID: base64.StdEncoding.EncodeToString(userIDCiphertext), UserID: base64.StdEncoding.EncodeToString(userIDCiphertext),
Username: base64.StdEncoding.EncodeToString(usernameCiphertext), Username: base64.StdEncoding.EncodeToString(usernameCiphertext),
@ -102,7 +101,7 @@ func createConversation(key Seeder.AesKey) (Models.ConversationDetail, Models.Us
PublicKey: base64.StdEncoding.EncodeToString(publicKeyCiphertext), PublicKey: base64.StdEncoding.EncodeToString(publicKeyCiphertext),
} }
err = Database.CreateConversationDetailUser(&cdu)
err = (&cdu).CreateConversationDetailUser()
return cd, uc, cdu, err return cd, uc, cdu, err
} }
@ -131,15 +130,15 @@ func Test_UpdateConversation(t *testing.T) {
d := struct { d := struct {
ID string `json:"id"` ID string `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Users []Models.ConversationDetailUser
UserConversations []Models.UserConversation
Users []Database.ConversationDetailUser
UserConversations []Database.UserConversation
}{ }{
ID: cd.ID.String(), ID: cd.ID.String(),
Name: base64.StdEncoding.EncodeToString(nameCiphertext), Name: base64.StdEncoding.EncodeToString(nameCiphertext),
Users: []Models.ConversationDetailUser{
Users: []Database.ConversationDetailUser{
cdu, cdu,
}, },
UserConversations: []Models.UserConversation{
UserConversations: []Database.UserConversation{
uc, uc,
}, },
} }
@ -158,7 +157,7 @@ func Test_UpdateConversation(t *testing.T) {
t.Errorf("Expected %d, recieved %d", http.StatusNoContent, resp.StatusCode) t.Errorf("Expected %d, recieved %d", http.StatusNoContent, resp.StatusCode)
} }
var ncd Models.ConversationDetail
var ncd Database.ConversationDetail
err = Database.DB.First(&ncd, "id = ?", cd.ID.String()).Error err = Database.DB.First(&ncd, "id = ?", cd.ID.String()).Error
if err != nil { if err != nil {
t.Errorf("Expected nil, recieved %s", err.Error()) t.Errorf("Expected nil, recieved %s", err.Error())


+ 1
- 2
Backend/Api/Users/SearchUsers.go View File

@ -6,13 +6,12 @@ import (
"net/url" "net/url"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
// SearchUsers searches a for a user by username // SearchUsers searches a for a user by username
func SearchUsers(w http.ResponseWriter, r *http.Request) { func SearchUsers(w http.ResponseWriter, r *http.Request) {
var ( var (
user Models.User
user Database.User
query url.Values query url.Values
rawUsername []string rawUsername []string
username string username string


+ 2
- 2
Backend/Api/Users/SearchUsers_test.go View File

@ -7,7 +7,7 @@ import (
"net/http" "net/http"
"testing" "testing"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Tests"
) )
@ -43,7 +43,7 @@ func Test_SearchUsers(t *testing.T) {
return return
} }
var user Models.User
var user Database.User
json.Unmarshal(requestBody, &user) json.Unmarshal(requestBody, &user)


+ 16
- 8
Backend/Database/Attachments.go View File

@ -1,16 +1,24 @@
package Database package Database
import ( import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
) )
// Attachment holds the attachment data
type Attachment struct {
Base
FilePath string `gorm:"not null" json:"-"`
Mimetype string `gorm:"not null" json:"mimetype"`
Extension string `gorm:"not null" json:"extension"`
Data string `gorm:"-" json:"data"`
ImageLink string `gorm:"-" json:"image_link"`
}
// GetAttachmentByID gets the attachment record by the id // GetAttachmentByID gets the attachment record by the id
func GetAttachmentByID(id string) (Models.MessageData, error) {
func GetAttachmentByID(id string) (MessageData, error) {
var ( var (
messageData Models.MessageData
messageData MessageData
err error err error
) )
@ -22,21 +30,21 @@ func GetAttachmentByID(id string) (Models.MessageData, error) {
} }
// CreateAttachment creates the attachment record // CreateAttachment creates the attachment record
func CreateAttachment(messageData *Models.MessageData) error {
func (attachment *Attachment) CreateAttachment() error {
var ( var (
err error err error
) )
err = DB.Session(&gorm.Session{FullSaveAssociations: true}). err = DB.Session(&gorm.Session{FullSaveAssociations: true}).
Create(messageData).
Create(attachment).
Error Error
return err return err
} }
// DeleteAttachment deletes the attachment record // DeleteAttachment deletes the attachment record
func DeleteAttachment(messageData *Models.MessageData) error {
func (attachment *Attachment) DeleteAttachment() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}). return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Delete(messageData).
Delete(attachment).
Error Error
} }

Backend/Models/Base.go → Backend/Database/Base.go View File


+ 22
- 11
Backend/Database/ConversationDetailUsers.go View File

@ -1,15 +1,26 @@
package Database package Database
import ( import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"github.com/gofrs/uuid"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
) )
func GetConversationDetailUserById(id string) (Models.ConversationDetailUser, error) {
// ConversationDetailUser all users associated with a conversation
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
}
func GetConversationDetailUserById(id string) (ConversationDetailUser, error) {
var ( var (
messageThread Models.ConversationDetailUser
messageThread ConversationDetailUser
err error err error
) )
@ -21,21 +32,21 @@ func GetConversationDetailUserById(id string) (Models.ConversationDetailUser, er
return messageThread, err return messageThread, err
} }
func CreateConversationDetailUser(messageThread *Models.ConversationDetailUser) error {
func (detailUser *ConversationDetailUser) CreateConversationDetailUser() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}). return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Create(messageThread).
Create(detailUser).
Error Error
} }
func UpdateConversationDetailUser(messageThread *Models.ConversationDetailUser) error {
func (detailUser *ConversationDetailUser) UpdateConversationDetailUser() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}). return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Where("id = ?", messageThread.ID).
Updates(messageThread).
Where("id = ?", detailUser.ID).
Updates(detailUser).
Error Error
} }
func DeleteConversationDetailUser(messageThread *Models.ConversationDetailUser) error {
func (detailUser *ConversationDetailUser) DeleteConversationDetailUser() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}). return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Delete(messageThread).
Delete(detailUser).
Error Error
} }

+ 23
- 8
Backend/Database/ConversationDetails.go View File

@ -1,16 +1,31 @@
package Database package Database
import ( import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"github.com/gofrs/uuid"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
) )
// 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"`
AttachmentID *uuid.UUID ` json:"attachment_id"`
Attachment Attachment ` json:"attachment"`
MessageExpiryDefault MessageExpiry `gorm:"default:no_expiry" json:"-" sql:"type:ENUM('fifteen_min', 'thirty_min', 'one_hour', 'three_hour', 'six_hour', 'twelve_hour', 'one_day', 'three_day', 'no_expiry')"` // Stored encrypted
MessageExpiry string `gorm:"-" json:"message_expiry"` // Stored encrypted
AdminAddMembers string ` json:"admin_add_members"` // Stored encrypted
AdminEditInfo string ` json:"admin_edit_info"` // Stored encrypted
AdminSendMessages string ` json:"admin_send_messages"` // Stored encrypted
}
// GetConversationDetailByID gets by id // GetConversationDetailByID gets by id
func GetConversationDetailByID(id string) (Models.ConversationDetail, error) {
func GetConversationDetailByID(id string) (ConversationDetail, error) {
var ( var (
conversationDetail Models.ConversationDetail
conversationDetail ConversationDetail
err error err error
) )
@ -23,9 +38,9 @@ func GetConversationDetailByID(id string) (Models.ConversationDetail, error) {
} }
// GetConversationDetailsByIds gets by multiple ids // GetConversationDetailsByIds gets by multiple ids
func GetConversationDetailsByIds(id []string) ([]Models.ConversationDetail, error) {
func GetConversationDetailsByIds(id []string) ([]ConversationDetail, error) {
var ( var (
conversationDetail []Models.ConversationDetail
conversationDetail []ConversationDetail
err error err error
) )
@ -38,14 +53,14 @@ func GetConversationDetailsByIds(id []string) ([]Models.ConversationDetail, erro
} }
// CreateConversationDetail creates a ConversationDetail record // CreateConversationDetail creates a ConversationDetail record
func CreateConversationDetail(conversationDetail *Models.ConversationDetail) error {
func (conversationDetail *ConversationDetail) CreateConversationDetail() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}). return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Create(conversationDetail). Create(conversationDetail).
Error Error
} }
// UpdateConversationDetail updates a ConversationDetail record // UpdateConversationDetail updates a ConversationDetail record
func UpdateConversationDetail(conversationDetail *Models.ConversationDetail) error {
func (conversationDetail *ConversationDetail) UpdateConversationDetail() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}). return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Where("id = ?", conversationDetail.ID). Where("id = ?", conversationDetail.ID).
Updates(conversationDetail). Updates(conversationDetail).
@ -53,7 +68,7 @@ func UpdateConversationDetail(conversationDetail *Models.ConversationDetail) err
} }
// DeleteConversationDetail deletes a ConversationDetail record // DeleteConversationDetail deletes a ConversationDetail record
func DeleteConversationDetail(conversationDetail *Models.ConversationDetail) error {
func (conversationDetail *ConversationDetail) DeleteConversationDetail() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}). return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Delete(conversationDetail). Delete(conversationDetail).
Error Error


+ 29
- 10
Backend/Database/FriendRequests.go View File

@ -1,16 +1,35 @@
package Database package Database
import ( import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"database/sql"
"time"
"github.com/gofrs/uuid"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
) )
// 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
FriendImagePath string ` json:"friend_image_path"`
FriendPublicAsymmetricKey string ` json:"asymmetric_public_key"` // Stored encrypted
SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted
AcceptedAt sql.NullTime ` json:"accepted_at"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
}
type FriendRequestList []FriendRequest
// GetFriendRequestByID gets friend request // GetFriendRequestByID gets friend request
func GetFriendRequestByID(id string) (Models.FriendRequest, error) {
func GetFriendRequestByID(id string) (FriendRequest, error) {
var ( var (
friendRequest Models.FriendRequest
friendRequest FriendRequest
err error err error
) )
@ -22,16 +41,16 @@ func GetFriendRequestByID(id string) (Models.FriendRequest, error) {
} }
// GetFriendRequestsByUserID gets friend request by user id // GetFriendRequestsByUserID gets friend request by user id
func GetFriendRequestsByUserID(userID string, page int) ([]Models.FriendRequest, error) {
func GetFriendRequestsByUserID(userID string, page int) ([]FriendRequest, error) {
var ( var (
friends []Models.FriendRequest
friends []FriendRequest
offset int offset int
err error err error
) )
offset = page * PageSize offset = page * PageSize
err = DB.Model(Models.FriendRequest{}).
err = DB.Model(FriendRequest{}).
Where("user_id = ?", userID). Where("user_id = ?", userID).
Offset(offset). Offset(offset).
Limit(PageSize). Limit(PageSize).
@ -43,26 +62,26 @@ func GetFriendRequestsByUserID(userID string, page int) ([]Models.FriendRequest,
} }
// CreateFriendRequest creates friend request // CreateFriendRequest creates friend request
func CreateFriendRequest(friendRequest *Models.FriendRequest) error {
func (friendRequest *FriendRequest) CreateFriendRequest() error {
return DB.Create(friendRequest). return DB.Create(friendRequest).
Error Error
} }
// CreateFriendRequests creates multiple friend requests // CreateFriendRequests creates multiple friend requests
func CreateFriendRequests(friendRequest *[]Models.FriendRequest) error {
func (friendRequest *FriendRequestList) CreateFriendRequests() error {
return DB.Create(friendRequest). return DB.Create(friendRequest).
Error Error
} }
// UpdateFriendRequest Updates friend request // UpdateFriendRequest Updates friend request
func UpdateFriendRequest(friendRequest *Models.FriendRequest) error {
func (friendRequest *FriendRequest) UpdateFriendRequest() error {
return DB.Where("id = ?", friendRequest.ID). return DB.Where("id = ?", friendRequest.ID).
Updates(friendRequest). Updates(friendRequest).
Error Error
} }
// DeleteFriendRequest deletes friend request // DeleteFriendRequest deletes friend request
func DeleteFriendRequest(friendRequest *Models.FriendRequest) error {
func (friendRequest *FriendRequest) DeleteFriendRequest() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}). return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Delete(friendRequest). Delete(friendRequest).
Error Error


+ 9
- 11
Backend/Database/Init.go View File

@ -3,8 +3,6 @@ package Database
import ( import (
"log" "log"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"gorm.io/driver/postgres" "gorm.io/driver/postgres"
"gorm.io/gorm" "gorm.io/gorm"
) )
@ -20,15 +18,15 @@ const (
var DB *gorm.DB var DB *gorm.DB
var models = []interface{}{ var models = []interface{}{
&Models.Session{},
&Models.Attachment{},
&Models.User{},
&Models.FriendRequest{},
&Models.MessageData{},
&Models.Message{},
&Models.ConversationDetail{},
&Models.ConversationDetailUser{},
&Models.UserConversation{},
&Session{},
&Attachment{},
&User{},
&FriendRequest{},
&MessageData{},
&Message{},
&ConversationDetail{},
&ConversationDetailUser{},
&UserConversation{},
} }
// Init initializes the database connection // Init initializes the database connection


+ 16
- 6
Backend/Database/MessageData.go View File

@ -1,15 +1,25 @@
package Database package Database
import ( import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"github.com/gofrs/uuid"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
) )
func GetMessageDataById(id string) (Models.MessageData, error) {
// MessageData holds the content of the message
// encrypted through the Message.SymmetricKey
type MessageData struct {
Base
Data string ` json:"data"` // Stored encrypted
AttachmentID *uuid.UUID ` json:"attachment_id"`
Attachment Attachment ` json:"attachment"`
SenderID string `gorm:"not null" json:"sender_id"` // Stored encrypted
SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted
}
func GetMessageDataById(id string) (MessageData, error) {
var ( var (
messageData Models.MessageData
messageData MessageData
err error err error
) )
@ -20,7 +30,7 @@ func GetMessageDataById(id string) (Models.MessageData, error) {
return messageData, err return messageData, err
} }
func CreateMessageData(messageData *Models.MessageData) error {
func (messageData *MessageData) CreateMessageData() error {
var ( var (
err error err error
) )
@ -32,7 +42,7 @@ func CreateMessageData(messageData *Models.MessageData) error {
return err return err
} }
func DeleteMessageData(messageData *Models.MessageData) error {
func (messageData *MessageData) DeleteMessageData() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}). return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Delete(messageData). Delete(messageData).
Error Error


Backend/Models/MessageExpiry.go → Backend/Database/MessageExpiry.go View File


+ 25
- 8
Backend/Database/Messages.go View File

@ -1,16 +1,33 @@
package Database package Database
import ( import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"database/sql"
"time"
"github.com/gofrs/uuid"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
) )
// Message holds data pertaining to each users' message
type Message struct {
Base
MessageDataID uuid.UUID ` json:"message_data_id"`
MessageData MessageData ` json:"message_data"`
SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted
AssociationKey string `gorm:"not null" json:"association_key"` // Stored encrypted
ExpiryRaw string ` json:"expiry"`
Expiry sql.NullTime ` json:"-"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
}
type MessageList []Message
// GetMessageByID gets a message // GetMessageByID gets a message
func GetMessageByID(id string) (Models.Message, error) {
func GetMessageByID(id string) (Message, error) {
var ( var (
message Models.Message
message Message
err error err error
) )
@ -22,9 +39,9 @@ func GetMessageByID(id string) (Models.Message, error) {
} }
// GetMessagesByAssociationKey for getting whole thread // GetMessagesByAssociationKey for getting whole thread
func GetMessagesByAssociationKey(associationKey string, page int) ([]Models.Message, error) {
func GetMessagesByAssociationKey(associationKey string, page int) ([]Message, error) {
var ( var (
messages []Models.Message
messages []Message
offset int offset int
err error err error
) )
@ -43,7 +60,7 @@ func GetMessagesByAssociationKey(associationKey string, page int) ([]Models.Mess
} }
// CreateMessage creates a message record // CreateMessage creates a message record
func CreateMessage(message *Models.Message) error {
func (message *Message) CreateMessage() error {
var err error var err error
err = DB.Session(&gorm.Session{FullSaveAssociations: true}). err = DB.Session(&gorm.Session{FullSaveAssociations: true}).
@ -54,7 +71,7 @@ func CreateMessage(message *Models.Message) error {
} }
// CreateMessages creates multiple records // CreateMessages creates multiple records
func CreateMessages(messages *[]Models.Message) error {
func (messages *MessageList) CreateMessages() error {
var err error var err error
err = DB.Session(&gorm.Session{FullSaveAssociations: true}). err = DB.Session(&gorm.Session{FullSaveAssociations: true}).
@ -65,7 +82,7 @@ func CreateMessages(messages *[]Models.Message) error {
} }
// DeleteMessage deletes a message // DeleteMessage deletes a message
func DeleteMessage(message *Models.Message) error {
func (message *Message) DeleteMessage() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}). return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Delete(message). Delete(message).
Error Error


+ 6
- 7
Backend/Database/Seeder/FriendSeeder.go View File

@ -7,12 +7,11 @@ import (
"time" "time"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
func seedFriend(userRequestTo, userRequestFrom Models.User, accepted bool) error {
func seedFriend(userRequestTo, userRequestFrom Database.User, accepted bool) error {
var ( var (
friendRequest Models.FriendRequest
friendRequest Database.FriendRequest
symKey AesKey symKey AesKey
encPublicKey []byte encPublicKey []byte
err error err error
@ -28,7 +27,7 @@ func seedFriend(userRequestTo, userRequestFrom Models.User, accepted bool) error
return err return err
} }
friendRequest = Models.FriendRequest{
friendRequest = Database.FriendRequest{
UserID: userRequestTo.ID, UserID: userRequestTo.ID,
FriendID: base64.StdEncoding.EncodeToString( FriendID: base64.StdEncoding.EncodeToString(
EncryptWithPublicKey( EncryptWithPublicKey(
@ -55,7 +54,7 @@ func seedFriend(userRequestTo, userRequestFrom Models.User, accepted bool) error
friendRequest.AcceptedAt.Valid = true friendRequest.AcceptedAt.Valid = true
} }
return Database.CreateFriendRequest(&friendRequest)
return (&friendRequest).CreateFriendRequest()
} }
func copyProfileImage() error { func copyProfileImage() error {
@ -83,8 +82,8 @@ func copyProfileImage() error {
// SeedFriends creates dummy friends for testing/development // SeedFriends creates dummy friends for testing/development
func SeedFriends() { func SeedFriends() {
var ( var (
primaryUser Models.User
secondaryUser Models.User
primaryUser Database.User
secondaryUser Database.User
accepted bool accepted bool
i int i int
err error err error


+ 26
- 27
Backend/Database/Seeder/MessageSeeder.go View File

@ -4,19 +4,18 @@ import (
"encoding/base64" "encoding/base64"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"github.com/gofrs/uuid" "github.com/gofrs/uuid"
) )
func seedMessage( func seedMessage(
primaryUser, secondaryUser Models.User,
primaryUser, secondaryUser Database.User,
primaryUserAssociationKey, secondaryUserAssociationKey string, primaryUserAssociationKey, secondaryUserAssociationKey string,
i int, i int,
) error { ) error {
var ( var (
message Models.Message
messageData Models.MessageData
message Database.Message
messageData Database.MessageData
key, userKey AesKey key, userKey AesKey
keyCiphertext []byte keyCiphertext []byte
plaintext string plaintext string
@ -61,13 +60,13 @@ func seedMessage(
panic(err) panic(err)
} }
messageData = Models.MessageData{
messageData = Database.MessageData{
Data: base64.StdEncoding.EncodeToString(dataCiphertext), Data: base64.StdEncoding.EncodeToString(dataCiphertext),
SenderID: base64.StdEncoding.EncodeToString(senderIDCiphertext), SenderID: base64.StdEncoding.EncodeToString(senderIDCiphertext),
SymmetricKey: base64.StdEncoding.EncodeToString(keyCiphertext), SymmetricKey: base64.StdEncoding.EncodeToString(keyCiphertext),
} }
message = Models.Message{
message = Database.Message{
MessageData: messageData, MessageData: messageData,
SymmetricKey: base64.StdEncoding.EncodeToString( SymmetricKey: base64.StdEncoding.EncodeToString(
EncryptWithPublicKey(userKey.Key, decodedPublicKey), EncryptWithPublicKey(userKey.Key, decodedPublicKey),
@ -75,12 +74,12 @@ func seedMessage(
AssociationKey: primaryUserAssociationKey, AssociationKey: primaryUserAssociationKey,
} }
err = Database.CreateMessage(&message)
err = (&message).CreateMessage()
if err != nil { if err != nil {
return err return err
} }
message = Models.Message{
message = Database.Message{
MessageData: messageData, MessageData: messageData,
SymmetricKey: base64.StdEncoding.EncodeToString( SymmetricKey: base64.StdEncoding.EncodeToString(
EncryptWithPublicKey(userKey.Key, decodedPublicKey), EncryptWithPublicKey(userKey.Key, decodedPublicKey),
@ -88,12 +87,12 @@ func seedMessage(
AssociationKey: secondaryUserAssociationKey, AssociationKey: secondaryUserAssociationKey,
} }
return Database.CreateMessage(&message)
return (&message).CreateMessage()
} }
func seedConversationDetail(key AesKey) (Models.ConversationDetail, error) {
func seedConversationDetail(key AesKey) (Database.ConversationDetail, error) {
var ( var (
conversationDetail Models.ConversationDetail
conversationDetail Database.ConversationDetail
name string name string
nameCiphertext []byte nameCiphertext []byte
falseCiphertext []byte falseCiphertext []byte
@ -118,7 +117,7 @@ func seedConversationDetail(key AesKey) (Models.ConversationDetail, error) {
panic(err) panic(err)
} }
conversationDetail = Models.ConversationDetail{
conversationDetail = Database.ConversationDetail{
Name: base64.StdEncoding.EncodeToString(nameCiphertext), Name: base64.StdEncoding.EncodeToString(nameCiphertext),
TwoUser: base64.StdEncoding.EncodeToString(falseCiphertext), TwoUser: base64.StdEncoding.EncodeToString(falseCiphertext),
AdminAddMembers: base64.StdEncoding.EncodeToString(trueCiphertext), AdminAddMembers: base64.StdEncoding.EncodeToString(trueCiphertext),
@ -126,17 +125,17 @@ func seedConversationDetail(key AesKey) (Models.ConversationDetail, error) {
AdminSendMessages: base64.StdEncoding.EncodeToString(falseCiphertext), AdminSendMessages: base64.StdEncoding.EncodeToString(falseCiphertext),
} }
err = Database.CreateConversationDetail(&conversationDetail)
err = (&conversationDetail).CreateConversationDetail()
return conversationDetail, err return conversationDetail, err
} }
func seedUserConversation( func seedUserConversation(
user Models.User,
user Database.User,
threadID uuid.UUID, threadID uuid.UUID,
key AesKey, key AesKey,
) (Models.UserConversation, error) {
) (Database.UserConversation, error) {
var ( var (
messageThreadUser Models.UserConversation
messageThreadUser Database.UserConversation
conversationDetailIDCiphertext []byte conversationDetailIDCiphertext []byte
adminCiphertext []byte adminCiphertext []byte
err error err error
@ -152,7 +151,7 @@ func seedUserConversation(
return messageThreadUser, err return messageThreadUser, err
} }
messageThreadUser = Models.UserConversation{
messageThreadUser = Database.UserConversation{
UserID: user.ID, UserID: user.ID,
ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext), ConversationDetailID: base64.StdEncoding.EncodeToString(conversationDetailIDCiphertext),
Admin: base64.StdEncoding.EncodeToString(adminCiphertext), Admin: base64.StdEncoding.EncodeToString(adminCiphertext),
@ -161,19 +160,19 @@ func seedUserConversation(
), ),
} }
err = Database.CreateUserConversation(&messageThreadUser)
err = (&messageThreadUser).CreateUserConversation()
return messageThreadUser, err return messageThreadUser, err
} }
func seedConversationDetailUser( func seedConversationDetailUser(
user Models.User,
conversationDetail Models.ConversationDetail,
user Database.User,
conversationDetail Database.ConversationDetail,
associationKey uuid.UUID, associationKey uuid.UUID,
admin bool, admin bool,
key AesKey, key AesKey,
) (Models.ConversationDetailUser, error) {
) (Database.ConversationDetailUser, error) {
var ( var (
conversationDetailUser Models.ConversationDetailUser
conversationDetailUser Database.ConversationDetailUser
userIDCiphertext []byte userIDCiphertext []byte
usernameCiphertext []byte usernameCiphertext []byte
@ -215,7 +214,7 @@ func seedConversationDetailUser(
return conversationDetailUser, err return conversationDetailUser, err
} }
conversationDetailUser = Models.ConversationDetailUser{
conversationDetailUser = Database.ConversationDetailUser{
ConversationDetailID: conversationDetail.ID, ConversationDetailID: conversationDetail.ID,
UserID: base64.StdEncoding.EncodeToString(userIDCiphertext), UserID: base64.StdEncoding.EncodeToString(userIDCiphertext),
Username: base64.StdEncoding.EncodeToString(usernameCiphertext), Username: base64.StdEncoding.EncodeToString(usernameCiphertext),
@ -224,7 +223,7 @@ func seedConversationDetailUser(
PublicKey: base64.StdEncoding.EncodeToString(publicKeyCiphertext), PublicKey: base64.StdEncoding.EncodeToString(publicKeyCiphertext),
} }
err = Database.CreateConversationDetailUser(&conversationDetailUser)
err = (&conversationDetailUser).CreateConversationDetailUser()
return conversationDetailUser, err return conversationDetailUser, err
} }
@ -232,11 +231,11 @@ func seedConversationDetailUser(
// SeedMessages seeds messages & conversations for testing // SeedMessages seeds messages & conversations for testing
func SeedMessages() { func SeedMessages() {
var ( var (
conversationDetail Models.ConversationDetail
conversationDetail Database.ConversationDetail
key AesKey key AesKey
primaryUser Models.User
primaryUser Database.User
primaryUserAssociationKey uuid.UUID primaryUserAssociationKey uuid.UUID
secondaryUser Models.User
secondaryUser Database.User
secondaryUserAssociationKey uuid.UUID secondaryUserAssociationKey uuid.UUID
i int i int
err error err error


+ 5
- 6
Backend/Database/Seeder/UserSeeder.go View File

@ -5,7 +5,6 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
) )
var userNames = []string{ var userNames = []string{
@ -22,9 +21,9 @@ var userNames = []string{
"pajamasenergy", "pajamasenergy",
} }
func createUser(username string) (Models.User, error) {
func createUser(username string) (Database.User, error) {
var ( var (
userData Models.User
userData Database.User
userKey AesKey userKey AesKey
password string password string
err error err error
@ -37,10 +36,10 @@ func createUser(username string) (Models.User, error) {
password, err = Auth.HashPassword("password") password, err = Auth.HashPassword("password")
if err != nil { if err != nil {
return Models.User{}, err
return Database.User{}, err
} }
userData = Models.User{
userData = Database.User{
Username: username, Username: username,
Password: password, Password: password,
AsymmetricPrivateKey: EncryptedPrivateKey, AsymmetricPrivateKey: EncryptedPrivateKey,
@ -50,7 +49,7 @@ func createUser(username string) (Models.User, error) {
), ),
} }
err = Database.CreateUser(&userData)
err = (&userData).CreateUser()
return userData, err return userData, err
} }


+ 19
- 6
Backend/Database/Sessions.go View File

@ -1,15 +1,28 @@
package Database package Database
import ( import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"time"
"github.com/gofrs/uuid"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
) )
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
}
// GetSessionByID Gets session // GetSessionByID Gets session
func GetSessionByID(id string) (Models.Session, error) {
func GetSessionByID(id string) (Session, error) {
var ( var (
session Models.Session
session Session
err error err error
) )
@ -21,7 +34,7 @@ func GetSessionByID(id string) (Models.Session, error) {
} }
// CreateSession creates session // CreateSession creates session
func CreateSession(session *Models.Session) error {
func (session *Session) CreateSession() error {
var ( var (
err error err error
) )
@ -32,14 +45,14 @@ func CreateSession(session *Models.Session) error {
} }
// DeleteSession deletes session // DeleteSession deletes session
func DeleteSession(session *Models.Session) error {
func (session *Session) DeleteSession() error {
return DB.Delete(session).Error return DB.Delete(session).Error
} }
// DeleteSessionByID deletes session // DeleteSessionByID deletes session
func DeleteSessionByID(id string) error { func DeleteSessionByID(id string) error {
return DB.Delete( return DB.Delete(
&Models.Session{},
&Session{},
"id = ?", "id = ?",
id, id,
).Error ).Error


+ 29
- 14
Backend/Database/UserConversations.go View File

@ -1,15 +1,30 @@
package Database package Database
import ( import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"time"
"github.com/gofrs/uuid"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
) )
func GetUserConversationById(id string) (Models.UserConversation, error) {
// 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
CreatedAt time.Time `gorm:"not null" json:"created_at"`
}
type UserConversationList []UserConversation
func GetUserConversationById(id string) (UserConversation, error) {
var ( var (
message Models.UserConversation
message UserConversation
err error err error
) )
@ -19,9 +34,9 @@ func GetUserConversationById(id string) (Models.UserConversation, error) {
return message, err return message, err
} }
func GetUserConversationsByUserId(id string, page int) ([]Models.UserConversation, error) {
func GetUserConversationsByUserId(id string, page int) ([]UserConversation, error) {
var ( var (
conversations []Models.UserConversation
conversations []UserConversation
offset int offset int
err error err error
) )
@ -37,7 +52,7 @@ func GetUserConversationsByUserId(id string, page int) ([]Models.UserConversatio
return conversations, err return conversations, err
} }
func CreateUserConversation(userConversation *Models.UserConversation) error {
func (userConversation *UserConversation) CreateUserConversation() error {
var err error var err error
err = DB.Session(&gorm.Session{FullSaveAssociations: true}). err = DB.Session(&gorm.Session{FullSaveAssociations: true}).
@ -47,7 +62,7 @@ func CreateUserConversation(userConversation *Models.UserConversation) error {
return err return err
} }
func CreateUserConversations(userConversations *[]Models.UserConversation) error {
func (userConversations *UserConversationList) CreateUserConversations() error {
var err error var err error
err = DB.Create(userConversations). err = DB.Create(userConversations).
@ -56,30 +71,30 @@ func CreateUserConversations(userConversations *[]Models.UserConversation) error
return err return err
} }
func UpdateUserConversation(userConversation *Models.UserConversation) error {
func (userConversation *UserConversation) UpdateUserConversation() error {
var err error var err error
err = DB.Model(Models.UserConversation{}).
err = DB.Model(UserConversation{}).
Updates(userConversation). Updates(userConversation).
Error Error
return err return err
} }
func UpdateUserConversations(userConversations *[]Models.UserConversation) error {
func (userConversations *UserConversationList) UpdateUserConversations() error {
var err error var err error
err = DB.Model(Models.UserConversation{}).
err = DB.Model(UserConversation{}).
Updates(userConversations). Updates(userConversations).
Error Error
return err return err
} }
func UpdateOrCreateUserConversations(userConversations *[]Models.UserConversation) error {
func (userConversations *UserConversationList) UpdateOrCreateUserConversations() error {
var err error var err error
err = DB.Model(Models.UserConversation{}).
err = DB.Model(UserConversation{}).
Clauses(clause.OnConflict{ Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}}, Columns: []clause.Column{{Name: "id"}},
DoUpdates: clause.AssignmentColumns([]string{"admin"}), DoUpdates: clause.AssignmentColumns([]string{"admin"}),
@ -90,7 +105,7 @@ func UpdateOrCreateUserConversations(userConversations *[]Models.UserConversatio
return err return err
} }
func DeleteUserConversation(userConversation *Models.UserConversation) error {
func (userConversation *UserConversation) DeleteUserConversation() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}). return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Delete(userConversation). Delete(userConversation).
Error Error


+ 39
- 12
Backend/Database/Users.go View File

@ -3,15 +3,42 @@ package Database
import ( import (
"errors" "errors"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"github.com/gofrs/uuid"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
) )
func GetUserById(id string) (Models.User, error) {
// BeforeUpdate prevents updating the username or 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")
}
if !tx.Statement.Changed("Email") {
tx.Statement.Omit("Email")
}
return nil
}
// User holds user data
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"`
Email string ` json:"email"`
AsymmetricPrivateKey string `gorm:"not null" json:"asymmetric_private_key"` // Stored encrypted
AsymmetricPublicKey string `gorm:"not null" json:"asymmetric_public_key"`
SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted
AttachmentID *uuid.UUID ` json:"attachment_id"`
Attachment Attachment ` json:"attachment"`
MessageExpiryDefault MessageExpiry `gorm:"default:no_expiry" json:"-" sql:"type:ENUM('fifteen_min', 'thirty_min', 'one_hour', 'three_hour', 'six_hour', 'twelve_hour', 'one_day', 'three_day', 'no_expiry')"` // Stored encrypted
}
func GetUserById(id string) (User, error) {
var ( var (
user Models.User
user User
err error err error
) )
@ -22,9 +49,9 @@ func GetUserById(id string) (Models.User, error) {
return user, err return user, err
} }
func GetUserByUsername(username string) (Models.User, error) {
func GetUserByUsername(username string) (User, error) {
var ( var (
user Models.User
user User
err error err error
) )
@ -41,7 +68,7 @@ func CheckUniqueUsername(username string) error {
err error err error
) )
err = DB.Model(Models.User{}).
err = DB.Model(User{}).
Select("count(*) > 0"). Select("count(*) > 0").
Where("username = ?", username). Where("username = ?", username).
Find(&exists). Find(&exists).
@ -58,7 +85,7 @@ func CheckUniqueUsername(username string) error {
return nil return nil
} }
func CreateUser(user *Models.User) error {
func (user *User) CreateUser() error {
var err error var err error
err = DB.Session(&gorm.Session{FullSaveAssociations: true}). err = DB.Session(&gorm.Session{FullSaveAssociations: true}).
@ -68,11 +95,11 @@ func CreateUser(user *Models.User) error {
return err return err
} }
func UpdateUser(id string, user *Models.User) error {
func (user *User) UpdateUser() error {
var err error var err error
err = DB.Model(&user). err = DB.Model(&user).
Omit("id"). Omit("id").
Where("id = ?", id).
Where("id = ?", user.ID.String()).
Updates(user). Updates(user).
Error Error
@ -80,15 +107,15 @@ func UpdateUser(id string, user *Models.User) error {
return err return err
} }
err = DB.Model(Models.User{}).
Where("id = ?", id).
err = DB.Model(User{}).
Where("id = ?", user.ID.String()).
First(user). First(user).
Error Error
return err return err
} }
func DeleteUser(user *Models.User) error {
func (user *User) DeleteUser() error {
return DB.Session(&gorm.Session{FullSaveAssociations: true}). return DB.Session(&gorm.Session{FullSaveAssociations: true}).
Delete(user). Delete(user).
Error Error


+ 0
- 11
Backend/Models/Attachments.go View File

@ -1,11 +0,0 @@
package Models
// Attachment holds the attachment data
type Attachment struct {
Base
FilePath string `gorm:"not null" json:"-"`
Mimetype string `gorm:"not null" json:"mimetype"`
Extension string `gorm:"not null" json:"extension"`
Data string `gorm:"-" json:"data"`
ImageLink string `gorm:"-" json:"image_link"`
}

+ 0
- 45
Backend/Models/Conversations.go View File

@ -1,45 +0,0 @@
package Models
import (
"time"
"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"`
AttachmentID *uuid.UUID ` json:"attachment_id"`
Attachment Attachment ` json:"attachment"`
MessageExpiryDefault MessageExpiry `gorm:"default:no_expiry" json:"-" sql:"type:ENUM('fifteen_min', 'thirty_min', 'one_hour', 'three_hour', 'six_hour', 'twelve_hour', 'one_day', 'three_day', 'no_expiry')"` // Stored encrypted
MessageExpiry string `gorm:"-" json:"message_expiry"` // Stored encrypted
AdminAddMembers string ` json:"admin_add_members"` // Stored encrypted
AdminEditInfo string ` json:"admin_edit_info"` // Stored encrypted
AdminSendMessages string ` json:"admin_send_messages"` // Stored encrypted
}
// ConversationDetailUser all users associated with a conversation
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
CreatedAt time.Time `gorm:"not null" json:"created_at"`
}

+ 0
- 22
Backend/Models/Friends.go View File

@ -1,22 +0,0 @@
package Models
import (
"database/sql"
"time"
"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
FriendImagePath string ` json:"friend_image_path"`
FriendPublicAsymmetricKey string ` json:"asymmetric_public_key"` // Stored encrypted
SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted
AcceptedAt sql.NullTime ` json:"accepted_at"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
}

+ 0
- 31
Backend/Models/Messages.go View File

@ -1,31 +0,0 @@
package Models
import (
"database/sql"
"time"
"github.com/gofrs/uuid"
)
// MessageData holds the content of the message
// encrypted through the Message.SymmetricKey
type MessageData struct {
Base
Data string ` json:"data"` // Stored encrypted
AttachmentID *uuid.UUID ` json:"attachment_id"`
Attachment Attachment ` json:"attachment"`
SenderID string `gorm:"not null" json:"sender_id"` // Stored encrypted
SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted
}
// Message holds data pertaining to each users' message
type Message struct {
Base
MessageDataID uuid.UUID ` json:"message_data_id"`
MessageData MessageData ` json:"message_data"`
SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted
AssociationKey string `gorm:"not null" json:"association_key"` // Stored encrypted
ExpiryRaw string ` json:"expiry"`
Expiry sql.NullTime ` json:"-"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
}

+ 0
- 18
Backend/Models/Sessions.go View File

@ -1,18 +0,0 @@
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
}

+ 0
- 33
Backend/Models/Users.go View File

@ -1,33 +0,0 @@
package Models
import (
"github.com/gofrs/uuid"
"gorm.io/gorm"
)
// BeforeUpdate prevents updating the username or 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")
}
if !tx.Statement.Changed("Email") {
tx.Statement.Omit("Email")
}
return nil
}
// User holds user data
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"`
Email string ` json:"email"`
AsymmetricPrivateKey string `gorm:"not null" json:"asymmetric_private_key"` // Stored encrypted
AsymmetricPublicKey string `gorm:"not null" json:"asymmetric_public_key"`
SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted
AttachmentID *uuid.UUID ` json:"attachment_id"`
Attachment Attachment ` json:"attachment"`
MessageExpiryDefault MessageExpiry `gorm:"default:no_expiry" json:"-" sql:"type:ENUM('fifteen_min', 'thirty_min', 'one_hour', 'three_hour', 'six_hour', 'twelve_hour', 'one_day', 'three_day', 'no_expiry')"` // Stored encrypted
}

+ 6
- 7
Backend/Tests/Init.go View File

@ -14,21 +14,20 @@ import (
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Api/Auth"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database/Seeder"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
func InitTestCreateUser(username string) (Models.User, error) {
func InitTestCreateUser(username string) (Database.User, error) {
userKey, err := Seeder.GenerateAesKey() userKey, err := Seeder.GenerateAesKey()
if err != nil { if err != nil {
return Models.User{}, err
return Database.User{}, err
} }
pubKey := Seeder.GetPubKey() pubKey := Seeder.GetPubKey()
p, _ := Auth.HashPassword("password") p, _ := Auth.HashPassword("password")
u := Models.User{
u := Database.User{
Username: username, Username: username,
Password: p, Password: p,
AsymmetricPublicKey: Seeder.PublicKey, AsymmetricPublicKey: Seeder.PublicKey,
@ -38,7 +37,7 @@ func InitTestCreateUser(username string) (Models.User, error) {
), ),
} }
err = Database.CreateUser(&u)
err = (&u).CreateUser()
return u, err return u, err
} }
@ -59,12 +58,12 @@ func InitTestEnv() (*http.Client, *httptest.Server, error) {
return http.DefaultClient, ts, err return http.DefaultClient, ts, err
} }
session := Models.Session{
session := Database.Session{
UserID: u.ID, UserID: u.ID,
Expiry: time.Now().Add(12 * time.Hour), Expiry: time.Now().Add(12 * time.Hour),
} }
err = Database.CreateSession(&session)
err = (&session).CreateSession()
if err != nil { if err != nil {
return http.DefaultClient, ts, err return http.DefaultClient, ts, err
} }


+ 2
- 3
Backend/Util/UserHelper.go View File

@ -6,7 +6,6 @@ import (
"net/http" "net/http"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Models"
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
@ -26,9 +25,9 @@ func GetUserId(r *http.Request) (string, error) {
return id, nil return id, nil
} }
func GetUserById(w http.ResponseWriter, r *http.Request) (Models.User, error) {
func GetUserById(w http.ResponseWriter, r *http.Request) (Database.User, error) {
var ( var (
postData Models.User
postData Database.User
id string id string
err error err error
) )


+ 1
- 1
Backend/dev.sh View File

@ -3,6 +3,6 @@ while true; do
go build main.go go build main.go
./main & ./main &
PID=$! PID=$!
inotifywait --exclude 'attachments|/\..+' -r -e modify .
inotifywait --exclude 'attachments|main|/\..+' -r -e modify .
kill $PID kill $PID
done done

Loading…
Cancel
Save