From c79d1f86e48e2d9d2830eb7305dcc8c4015ac489 Mon Sep 17 00:00:00 2001 From: hoernschen Date: Sat, 3 Oct 2020 14:22:29 +0200 Subject: [PATCH] Refactor Database Connector, Implement Register --- entities/device/deviceDatabaseConnector.go | 127 +++++++ entities/device/keyDatabaseConnector.go | 125 +++++++ entities/event/eventDatabaseConnector.go | 208 +++++++++++ entities/room/roomDatabaseConnector.go | 215 +++++++++++ .../transactionDatabaseConnector.go | 101 +++++ entities/user/user.go | 80 ++++ entities/user/userController.go | 157 +++++++- entities/user/userDatabaseConnector.go | 101 +++++ main.go | 19 +- sqlite.db | Bin 61440 -> 61440 bytes utils/database/databaseConnector.go | 349 +++++++++++++++++- utils/database/deviceDatabaseConnector.go | 179 --------- utils/database/eventDatabaseConnector.go | 278 -------------- utils/database/keyDatabaseConnector.go | 177 --------- utils/database/roomDatabaseConnector.go | 288 --------------- .../database/transactionDatabaseConnector.go | 146 -------- utils/database/userDatabaseConnector.go | 147 -------- utils/requestChecker.go | 32 ++ 18 files changed, 1495 insertions(+), 1234 deletions(-) create mode 100644 entities/device/deviceDatabaseConnector.go create mode 100644 entities/device/keyDatabaseConnector.go create mode 100644 entities/event/eventDatabaseConnector.go create mode 100644 entities/room/roomDatabaseConnector.go create mode 100644 entities/transaction/transactionDatabaseConnector.go create mode 100644 entities/user/userDatabaseConnector.go delete mode 100644 utils/database/deviceDatabaseConnector.go delete mode 100644 utils/database/eventDatabaseConnector.go delete mode 100644 utils/database/keyDatabaseConnector.go delete mode 100644 utils/database/roomDatabaseConnector.go delete mode 100644 utils/database/transactionDatabaseConnector.go delete mode 100644 utils/database/userDatabaseConnector.go create mode 100644 utils/requestChecker.go diff --git a/entities/device/deviceDatabaseConnector.go b/entities/device/deviceDatabaseConnector.go new file mode 100644 index 0000000..896bddb --- /dev/null +++ b/entities/device/deviceDatabaseConnector.go @@ -0,0 +1,127 @@ +package device + +import ( + "fmt" + + "nutfactory.org/Matrix/utils/database" +) + +func CreateDevice(device *Device, userId string) (err error) { + sqlStmt := fmt.Sprintf(`INSERT INTO device + (id, name, userId) + VALUES + (?, ?, ?)`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec(device.Id, device.Name, userId) + if err != nil { + return + } + tx.Commit() + return +} + +func ReadDevice(id string) (foundDevice *Device, err error) { + queryStmt := fmt.Sprintf(`SELECT id, name + FROM device + WHERE id = '%s'`, id) + + rows, err := database.DB.Query(queryStmt) + if err != nil { + return + } + + defer rows.Close() + + if rows.Next() { + foundDevice = &Device{} + err = rows.Scan(&foundDevice.Id, &foundDevice.Name) + if err != nil { + return + } + foundDevice.Keys, err = ReadKeysForDevice(foundDevice.Id) + } + + return +} + +func ReadDevicesForUser(userId string) (devices map[string]*Device, err error) { + queryStmt := fmt.Sprintf(`SELECT id, name + FROM device + WHERE userId = '%s'`, userId) + + rows, err := database.DB.Query(queryStmt) + if err != nil { + return + } + + defer rows.Close() + + devices = make(map[string]*Device) + + for rows.Next() { + foundDevice := &Device{} + err = rows.Scan(&foundDevice.Id, &foundDevice.Name) + if err != nil { + return + } + foundDevice.Keys, err = ReadKeysForDevice(foundDevice.Id) + devices[foundDevice.Id] = foundDevice + } + + return +} + +func UpdateDevice(device *Device, userId string) (err error) { + sqlStmt := fmt.Sprintf(`UPDATE device SET + name = ?, + userId = ? + WHERE id = ?`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec(device.Name, userId, device.Id) + if err != nil { + return + } + + tx.Commit() + return +} + +func DeleteDevice(id string) (err error) { + queryStmt := fmt.Sprintf(`DELETE FROM device + WHERE id = '%s'`, id) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + _, err = database.DB.Exec(queryStmt) + if err != nil { + return + } + + tx.Commit() + return +} diff --git a/entities/device/keyDatabaseConnector.go b/entities/device/keyDatabaseConnector.go new file mode 100644 index 0000000..9f2be38 --- /dev/null +++ b/entities/device/keyDatabaseConnector.go @@ -0,0 +1,125 @@ +package device + +import ( + "fmt" + + "nutfactory.org/Matrix/utils/database" +) + +func CreateKey(key *Key, deviceId string) (err error) { + sqlStmt := fmt.Sprintf(`INSERT INTO key + (id, type, key, deviceId) + VALUES + (?, ?, ?, ?)`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec(key.Id, key.Type, key.Key, deviceId) + if err != nil { + return + } + tx.Commit() + return +} + +func ReadKey(id string) (foundKey *Key, err error) { + queryStmt := fmt.Sprintf(`SELECT id, type, key + FROM key + WHERE id = '%s'`, id) + + rows, err := database.DB.Query(queryStmt) + if err != nil { + return + } + + defer rows.Close() + + if rows.Next() { + foundKey = &Key{} + err = rows.Scan(&foundKey.Id, &foundKey.Type, &foundKey.Key) + if err != nil { + return + } + } + + return +} + +func ReadKeysForDevice(deviceId string) (keys map[string]*Key, err error) { + queryStmt := fmt.Sprintf(`SELECT id, type, key + FROM key + WHERE deviceId = '%s'`, deviceId) + + rows, err := database.DB.Query(queryStmt) + if err != nil { + return + } + + defer rows.Close() + + keys = make(map[string]*Key) + + for rows.Next() { + foundKey := &Key{} + err = rows.Scan(&foundKey.Id, &foundKey.Type, &foundKey.Key) + if err != nil { + return + } + keys[foundKey.Id] = foundKey + } + + return +} + +func UpdateKey(key *Key) (err error) { + sqlStmt := fmt.Sprintf(`UPDATE key SET + type = ?, + key = ? + WHERE id = ?`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec(key.Type, key.Key, key.Id) + if err != nil { + return + } + + tx.Commit() + return +} + +func DeleteKey(id string) (err error) { + queryStmt := fmt.Sprintf(`DELETE FROM key + WHERE id = '%s'`, id) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + _, err = database.DB.Exec(queryStmt) + if err != nil { + return + } + + tx.Commit() + return +} diff --git a/entities/event/eventDatabaseConnector.go b/entities/event/eventDatabaseConnector.go new file mode 100644 index 0000000..ecc7cde --- /dev/null +++ b/entities/event/eventDatabaseConnector.go @@ -0,0 +1,208 @@ +package event + +import ( + "fmt" + + "nutfactory.org/Matrix/utils/database" +) + +func CreateEvent(event *Event, txnId string) (err error) { + sqlStmt := fmt.Sprintf(`INSERT INTO event + (id, roomId, txnId, eventType, content, parentId, depth) + VALUES + (?, ?, ?, ?, ?, ?, ?)`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec(event.Id, event.RoomId, txnId, event.EventType, event.Content, event.ParentId, event.Depth) + if err != nil { + return + } + tx.Commit() + return +} + +func CreateEventsFromTransaction(txnId string, pdus map[string]*Event) (err error) { + sqlStmt := fmt.Sprintf(`INSERT INTO event + (id, roomId, txnId, eventType, content, parentId, depth) + VALUES + (?, ?, ?, ?, ?, ?, ?)`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + for _, pdu := range pdus { + _, err = stmt.Exec(pdu.Id, pdu.RoomId, txnId, pdu.EventType, pdu.Content, pdu.ParentId, pdu.Depth) + if err != nil { + return + } + } + + tx.Commit() + return +} + +func ReadEvent(id string) (foundEvent *Event, err error) { + queryStmt := fmt.Sprintf(`SELECT id, roomId, eventType, content, parentId, depth + FROM event + WHERE id = '%s'`, id) + + rows, err := database.DB.Query(queryStmt) + if err != nil { + return + } + + defer rows.Close() + + if rows.Next() { + foundEvent = &Event{} + err = rows.Scan(&foundEvent.Id, + &foundEvent.RoomId, + &foundEvent.EventType, + &foundEvent.Content, + &foundEvent.ParentId, + &foundEvent.Depth, + ) + if err != nil { + return + } + } + + return +} + +func ReadEventsFromRoom(roomId string) (events map[string]*Event, err error) { + queryStmt := fmt.Sprintf(`SELECT id, roomId, eventType, content, parentId, depth + FROM event + WHERE roomId = '%s'`, roomId) + + rows, err := database.DB.Query(queryStmt) + if err != nil { + return + } + + defer rows.Close() + + events = make(map[string]*Event) + + for rows.Next() { + foundEvent := &Event{} + err = rows.Scan(&foundEvent.Id, + &foundEvent.RoomId, + &foundEvent.EventType, + &foundEvent.Content, + &foundEvent.ParentId, + &foundEvent.Depth, + ) + if err != nil { + return + } + events[foundEvent.Id] = foundEvent + } + + return +} + +func ReadEventsFromTransaction(txnId string) (events map[string]*Event, err error) { + queryStmt := fmt.Sprintf(`SELECT id, roomId, eventType, content, parentId, depth + FROM event + WHERE txnId = '%s'`, txnId) + + rows, err := database.DB.Query(queryStmt) + if err != nil { + return + } + + defer rows.Close() + + events = make(map[string]*Event) + + for rows.Next() { + foundEvent := &Event{} + err = rows.Scan( + &foundEvent.Id, + &foundEvent.RoomId, + &foundEvent.EventType, + &foundEvent.Content, + &foundEvent.ParentId, + &foundEvent.Depth, + ) + if err != nil { + return + } + events[foundEvent.Id] = foundEvent + } + + return +} + +func UpdateEvent(event *Event) (err error) { + sqlStmt := fmt.Sprintf(`UPDATE event SET + roomId = ?, + eventType = ?, + content = ?, + parentId = ?, + depth = ? + WHERE id = ?`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec( + event.RoomId, + event.EventType, + event.Content, + event.ParentId, + event.Depth, + event.Id, + ) + if err != nil { + return + } + + tx.Commit() + return +} + +func DeleteEvent(id string) (err error) { + queryStmt := fmt.Sprintf(`DELETE FROM event + WHERE id = '%s'`, id) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + _, err = database.DB.Exec(queryStmt) + if err != nil { + return + } + + tx.Commit() + return +} diff --git a/entities/room/roomDatabaseConnector.go b/entities/room/roomDatabaseConnector.go new file mode 100644 index 0000000..a62db57 --- /dev/null +++ b/entities/room/roomDatabaseConnector.go @@ -0,0 +1,215 @@ +package room + +import ( + "fmt" + + "nutfactory.org/Matrix/entities/event" + "nutfactory.org/Matrix/utils/database" +) + +func CreateRoom(room *Room, userId string) (err error) { + sqlStmt := fmt.Sprintf(`INSERT INTO room + (id, version) + VALUES + (?, ?)`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec(room.Id, room.Version) + if err != nil { + return + } + tx.Commit() + err = CreateRoomMember(room.Id, userId) + return +} + +func CreateRoomMember(roomId string, userId string) (err error) { + sqlStmt := fmt.Sprintf(`INSERT INTO roomMember + (roomId, userId) + VALUES + (?, ?)`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec(roomId, userId) + if err != nil { + return + } + tx.Commit() + return +} + +func ReadRoom(id string) (foundRoom *Room, err error) { + queryStmt := fmt.Sprintf(`SELECT id, version + FROM room + WHERE id = '%s'`, id) + + rows, err := database.DB.Query(queryStmt) + if err != nil { + return + } + + defer rows.Close() + + if rows.Next() { + foundRoom = &Room{} + err = rows.Scan(&foundRoom.Id, &foundRoom.Version) + if err != nil { + return + } + foundRoom.Messages, err = event.ReadEventsFromRoom(foundRoom.Id) + if err != nil { + return + } + foundRoom.Members, err = ReadRoomMembers(foundRoom.Id) + if err != nil { + return + } + } + + return +} + +func ReadRoomMembers(roomId string) (roomMembers []string, err error) { + queryStmt := fmt.Sprintf(`SELECT userId + FROM roomMember + WHERE roomId = '%s'`, roomId) + + rows, err := database.DB.Query(queryStmt) + if err != nil { + return + } + + defer rows.Close() + + roomMembers = []string{} + + for rows.Next() { + var foundUser string + err = rows.Scan(&foundUser) + if err != nil { + return + } + roomMembers = append(roomMembers, foundUser) + } + + return +} + +func UpdateRoom(room *Room) (err error) { + sqlStmt := fmt.Sprintf(`UPDATE room SET + version = ? + WHERE id = ?`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec(room.Version, room.Id) + if err != nil { + return + } + + tx.Commit() + return +} + +func DeleteRoom(id string) (err error) { + queryStmt := fmt.Sprintf(`DELETE FROM room + WHERE id = '%s'`, id) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + _, err = database.DB.Exec(queryStmt) + if err != nil { + return + } + + err = DeleteAllRoomMemberForRoom(id) + + tx.Commit() + return +} + +func DeleteRoomMember(roomId string, userId string) (err error) { + queryStmt := fmt.Sprintf(`DELETE FROM roomMember + WHERE userId = '%s' AND roomId = '%s'`, userId, roomId) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + _, err = database.DB.Exec(queryStmt) + if err != nil { + return + } + + tx.Commit() + return +} + +func DeleteAllRoomMemberForUser(userId string) (err error) { + queryStmt := fmt.Sprintf(`DELETE FROM roomMember + WHERE userId = '%s'`, userId) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + _, err = database.DB.Exec(queryStmt) + if err != nil { + return + } + + tx.Commit() + return +} + +func DeleteAllRoomMemberForRoom(roomId string) (err error) { + queryStmt := fmt.Sprintf(`DELETE FROM roomMember + WHERE roomId = '%s'`, roomId) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + _, err = database.DB.Exec(queryStmt) + if err != nil { + return + } + + tx.Commit() + return +} diff --git a/entities/transaction/transactionDatabaseConnector.go b/entities/transaction/transactionDatabaseConnector.go new file mode 100644 index 0000000..d5e4c90 --- /dev/null +++ b/entities/transaction/transactionDatabaseConnector.go @@ -0,0 +1,101 @@ +package transaction + +import ( + "fmt" + + "nutfactory.org/Matrix/entities/event" + "nutfactory.org/Matrix/utils/database" +) + +func CreateTransaction(transaction *Transaction) (err error) { + sqlStmt := fmt.Sprintf(`INSERT INTO txn + (id, origin, timestamp) + VALUES + (?, ?, ?)`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec(transaction.Id, transaction.Origin, transaction.Timestamp) + if err != nil { + return + } + tx.Commit() + return +} + +func ReadTransaction(id string) (foundTransaction *Transaction, err error) { + queryStmt := fmt.Sprintf(`SELECT id, origin, timestamp + FROM txn + WHERE id = '%s'`, id) + + rows, err := database.DB.Query(queryStmt) + if err != nil { + return + } + + defer rows.Close() + + if rows.Next() { + foundTransaction = &Transaction{} + err = rows.Scan(&foundTransaction.Id, &foundTransaction.Origin, &foundTransaction.Timestamp) + if err != nil { + return + } + foundTransaction.PDUS, err = event.ReadEventsFromTransaction(foundTransaction.Id) + } + + return +} + +func UpdateTransaction(transaction *Transaction) (err error) { + sqlStmt := fmt.Sprintf(`UPDATE txn SET + origin = ?, + timestamp = ? + WHERE id = ?`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec(transaction.Origin, transaction.Timestamp, transaction.Id) + if err != nil { + return + } + + tx.Commit() + return +} + +func DeleteTransaction(id string) (err error) { + queryStmt := fmt.Sprintf(`DELETE FROM txn + WHERE id = '%s'`, id) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + _, err = database.DB.Exec(queryStmt) + if err != nil { + return + } + + tx.Commit() + return +} diff --git a/entities/user/user.go b/entities/user/user.go index c28a9c0..1f455e8 100644 --- a/entities/user/user.go +++ b/entities/user/user.go @@ -10,3 +10,83 @@ type User struct { Password string `json:"password,omitempty"` Devices map[string]*device.Device `json:"devices,omitempty"` } + +type registerRequest struct { + Auth authentificationData `json:"auth,omitempty"` + Username string `json:"username,omitempty"` + Password string `json:"password,omitempty"` + DeviceId string `json:"device_id,omitempty"` + DeviceName string `json:"initial_device_display_name,omitempty"` + InhibitLogin bool `json:"inhibit_login,omitempty"` +} + +type registerResponse struct { + UserId string `json:"user_id,omitempty"` + AccessToken string `json:"access_token,omitempty"` + HomeServer string `json:"home_server,omitempty"` + DeviceId string `json:"device_id,omitempty"` +} + +type loginRequest struct { + LoginType string `json:"type,omitempty"` + Identifier identifier `json:"identifier,omitempty"` + Password string `json:"password,omitempty"` + Token string `json:"token,omitempty"` + DeviceId string `json:"device_id,omitempty"` + DeviceName string `json:"initial_device_display_name,omitempty"` +} + +type loginResponse struct { + UserId string `json:"user_id,omitempty"` + AccessToken string `json:"access_token,omitempty"` + DeviceId string `json:"device_id,omitempty"` + DiscoveryInfo discoveryInformation `json:"well_known,omitempty"` +} + +type deaktivateUserRequest struct { + Auth authentificationData `json:"auth,omitempty"` + IdentityServer string `json:"id_server,omitempty"` +} + +type deaktivateUserResponse struct { + Unbind3PIDS string `json:"id_server_unbind_result,omitempty"` // success or no-support +} + +type changePasswordRequest struct { + NewPassword string + LogoutDevices bool + Auth authentificationData +} + +type errorResponse struct { + ErrorCode string `json:"errcode,omitempty"` + ErrorMessage string `json:"error,omitempty"` + RetryTime int `json:"retry_after_ms,omitempty"` +} + +type identifier struct { + IdentifierType string `json:"type,omitempty"` + User string `json:"user,omitempty"` + Medium string `json:"medium,omitempty"` + Address string `json:"address,omitempty"` + Country string `json:"country,omitempty"` + Phone string `json:"phone,omitempty"` +} + +type authentificationData struct { + LoginType string `json:"type,omitempty"` + Session string `json:"session,omitempty"` +} + +type discoveryInformation struct { + Homeserver homeserverInformation `json:"m.homeserver,omitempty"` + IdentityServer identityServerInformation `json:"m.identity_server,omitempty"` +} + +type homeserverInformation struct { + BaseUrl string `json:"base_url,omitempty"` +} + +type identityServerInformation struct { + BaseUrl string `json:"base_url,omitempty"` +} diff --git a/entities/user/userController.go b/entities/user/userController.go index a75d68f..c60773a 100644 --- a/entities/user/userController.go +++ b/entities/user/userController.go @@ -1,5 +1,160 @@ package user -func New() (user *User) { +import ( + "encoding/json" + "net/http" + + "nutfactory.org/Matrix/entities/device" + "nutfactory.org/Matrix/utils" +) + +func New(id string, name, string, password string, devices map[string]*device.Device) (newUser *User) { + newUser = &User{ + Id: id, + Name: name, + Password: password, + Devices: devices, + } + return +} + +func CheckUsernameAvailability(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + w.WriteHeader(http.StatusOK) + if err := json.NewEncoder(w).Encode("Test"); err != nil { + panic(err) + } +} + +func Register(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + request := registerRequest{} + errResponse := utils.CheckRequest(r, request) + if errResponse != nil { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(errResponse); err != nil { + panic(err) + } + return + } + decoder := json.NewDecoder(r.Body) + err := decoder.Decode(&request) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorMessage: "Could not parse JSON"}); err != nil { + panic(err) + } + return + } + errResponse = checkAuthData(&request.Auth) + if errResponse != nil { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(errResponse); err != nil { + panic(err) + } + return + } + // TODO: Use New Function + newUser := &User{ + Id: request.Username, + Name: request.Username, + Password: request.Password, + } + foundUser, err := ReadUser(newUser.Id) + if foundUser != nil { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorCode: "M_USER_IN_USE", ErrorMessage: "Username already in use"}); err != nil { + panic(err) + } + return + } + err = CreateUser(newUser) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorMessage: "Database Error"}); err != nil { + panic(err) + } + return + } + userDevice, err := device.ReadDevice(request.DeviceId) + if userDevice != nil { + err = device.UpdateDevice(userDevice, newUser.Id) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorMessage: "Database Error"}); err != nil { + panic(err) + } + return + } + } else { + // TODO: Use New Function + userDevice = &device.Device{} + err = device.CreateDevice(userDevice, newUser.Id) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + if err := json.NewEncoder(w).Encode(utils.ErrorResponse{ErrorMessage: "Database Error"}); err != nil { + panic(err) + } + return + } + } + response := registerResponse{ + UserId: newUser.Id, + // TODO: Create Funktion for Token Generation + AccessToken: "TEST", + DeviceId: userDevice.Id, + } + w.WriteHeader(http.StatusOK) + if err := json.NewEncoder(w).Encode(response); err != nil { + panic(err) + } +} + +func Login(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + w.WriteHeader(http.StatusOK) + if err := json.NewEncoder(w).Encode("Test"); err != nil { + panic(err) + } +} + +func Logout(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + w.WriteHeader(http.StatusOK) + if err := json.NewEncoder(w).Encode("Test"); err != nil { + panic(err) + } +} + +func Deactivate(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + w.WriteHeader(http.StatusOK) + if err := json.NewEncoder(w).Encode("Test"); err != nil { + panic(err) + } +} + +func ChangePassword(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + w.WriteHeader(http.StatusOK) + if err := json.NewEncoder(w).Encode("Test"); err != nil { + panic(err) + } +} + +//TODO: Check if necessary +func Sync(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + w.WriteHeader(http.StatusOK) + if err := json.NewEncoder(w).Encode("Test"); err != nil { + panic(err) + } +} + +func checkAuthData(authData *authentificationData) (errResponse *utils.ErrorResponse) { + if authData.LoginType != "m.login.password" { + errResponse = &utils.ErrorResponse{ErrorCode: "M_FORBIDDEN", ErrorMessage: "Unsupported Auth Type"} + return + } return } diff --git a/entities/user/userDatabaseConnector.go b/entities/user/userDatabaseConnector.go new file mode 100644 index 0000000..5436f98 --- /dev/null +++ b/entities/user/userDatabaseConnector.go @@ -0,0 +1,101 @@ +package user + +import ( + "fmt" + + "nutfactory.org/Matrix/entities/device" + "nutfactory.org/Matrix/utils/database" +) + +func CreateUser(user *User) (err error) { + sqlStmt := fmt.Sprintf(`INSERT INTO user + (id, name, password) + VALUES + (?, ?, ?)`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec(user.Id, user.Name, user.Password) + if err != nil { + return + } + tx.Commit() + return +} + +func ReadUser(id string) (foundUser *User, err error) { + queryStmt := fmt.Sprintf(`SELECT id, name, password + FROM user + WHERE id = '%s'`, id) + + rows, err := database.DB.Query(queryStmt) + if err != nil { + return + } + + defer rows.Close() + + if rows.Next() { + foundUser = &User{} + err = rows.Scan(&foundUser.Id, &foundUser.Name, &foundUser.Password) + if err != nil { + return + } + foundUser.Devices, err = device.ReadDevicesForUser(foundUser.Id) + } + + return +} + +func UpdateUser(user *User) (err error) { + sqlStmt := fmt.Sprintf(`UPDATE user SET + name = ?, + password = ? + WHERE id = ?`) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + stmt, err := tx.Prepare(sqlStmt) + if err != nil { + return + } + defer stmt.Close() + + _, err = stmt.Exec(user.Name, user.Password, user.Id) + if err != nil { + return + } + + tx.Commit() + return +} + +func DeleteUser(id string) (err error) { + queryStmt := fmt.Sprintf(`DELETE FROM user + WHERE id = '%s'`, id) + + tx, err := database.DB.Begin() + if err != nil { + return + } + + _, err = database.DB.Exec(queryStmt) + if err != nil { + return + } + + tx.Commit() + return +} diff --git a/main.go b/main.go index 8c38643..02e4cc3 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "net/http" "os" + "nutfactory.org/Matrix/entities/user" "nutfactory.org/Matrix/utils/database" "nutfactory.org/Matrix/utils/router" ) @@ -26,13 +27,13 @@ var routes = router.Routes{ router.Route{"GetSigningKeyFromMultipleServer", "GET", "/_matrix/key/v2/query", Test}, // Users - router.Route{"CheckUsernameAvailability", "GET", "/_matrix/client/r0/register/available", Test}, - router.Route{"Register", "POST", "/_matrix/client/r0/register", Test}, - router.Route{"Login", "POST", "/_matrix/client/r0/login", Test}, - router.Route{"Logout", "POST", "/_matrix/client/r0/logout", Test}, - router.Route{"Deactivate", "POST", "/_matrix/client/r0/account/deactivate", Test}, - router.Route{"ChangePassword", "POST", "/_matrix/client/r0/account/password", Test}, - router.Route{"Sync", "GET", "/_matrix/client/r0/sync", Test}, + router.Route{"CheckUsernameAvailability", "GET", "/_matrix/client/r0/register/available", user.CheckUsernameAvailability}, + router.Route{"Register", "POST", "/_matrix/client/r0/register", user.Register}, + router.Route{"Login", "POST", "/_matrix/client/r0/login", user.Login}, + router.Route{"Logout", "POST", "/_matrix/client/r0/logout", user.Logout}, + router.Route{"Deactivate", "POST", "/_matrix/client/r0/account/deactivate", user.Deactivate}, + router.Route{"ChangePassword", "POST", "/_matrix/client/r0/account/password", user.ChangePassword}, + router.Route{"Sync", "GET", "/_matrix/client/r0/sync", user.Sync}, // Rooms router.Route{"CreateRoom", "POST", "/_matrix/client/r0/createRoom", Test}, @@ -73,8 +74,8 @@ func main() { // TODO: Remove later os.Remove("sqlite.db") - db, _ := database.InitDB("sqlite.db") - defer db.Close() + _ = database.InitDB("sqlite.db") + defer database.DB.Close() router := router.NewRouter(routes) diff --git a/sqlite.db b/sqlite.db index 53619eacbc989a3d70816563fb0da1b0f93f3711..c4f2a52ae44c871f88facbaaed4d62a0ec502262 100644 GIT binary patch delta 148 zcmZp8z})bFd4e<}=R_H2M$U~1OZeFs`9Cr6f7&c4@Pc20hmnPsSGFXzxTLf=wTO#> zfq{|#4+H-npzM2ob|9CTnU`~u0LucPu6qpp_kiM8_;nN*S!88ZVY*;+aei)UKw@!m ad45p}#H23_{9k}NUh(sAGs|+q)BylJR4Y>e delta 76 zcmZp8z})bFd4e<}*F+g-My`zsOZXSF7%bS#V!)!n#Q%1)pu#hLDPeKZlGNgo5ZB-k bBM^g&0SE*b82Eo|7BqOz&(6TW0TKoPdbbtA diff --git a/utils/database/databaseConnector.go b/utils/database/databaseConnector.go index 158cb6e..d777b90 100644 --- a/utils/database/databaseConnector.go +++ b/utils/database/databaseConnector.go @@ -8,22 +8,353 @@ import ( _ "github.com/mattn/go-sqlite3" ) -func InitDB(filepath string) (db *sql.DB, err error) { +var DB *sql.DB + +func InitDB(filepath string) (err error) { log.Printf("Init DB") - db, err = sql.Open("sqlite3", filepath) + DB, err = sql.Open("sqlite3", filepath) if err != nil { panic(err) } - if db == nil { + if DB == nil { panic("DB couldn't be initialized") } - handleError(initDeviceTable(db)) - handleError(initKeyTable(db)) - handleError(initEventTable(db)) - handleError(initRoomTable(db)) - handleError(initTransactionTable(db)) - handleError(initUserTable(db)) + handleError(initDeviceTable()) + handleError(initKeyTable()) + handleError(initEventTable()) + handleError(initRoomTable()) + handleError(initTransactionTable()) + handleError(initUserTable()) + + return +} + +func initDeviceTable() (err error) { + log.Printf("Init Device Table") + statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS device ( + id TEXT PRIMARY KEY, + name TEXT, + userId TEXT + )`) + if err != nil { + return + } + statement.Exec() + + /* + newDevice := &device.Device{Id: "test", Name: "TEST", Keys: nil} + err = CreateDevice(db, newDevice, "test") + if err != nil { + log.Printf("Error Create: %s", err) + return + } + newDevice.Name = "TEST2" + err = UpdateDevice(db, newDevice) + if err != nil { + log.Printf("Error Update: %s", err) + return + } + devices, err := ReadDevicesForUser(db, "test") + if err != nil { + log.Printf("Error Read User: %s", err) + return + } + log.Println(devices) + err = DeleteDevice(db, newDevice.Id) + if err != nil { + log.Printf("Error Delete: %s", err) + return + } + de, err := ReadDevice(db, "test") + if err != nil { + log.Printf("Error Read: %s", err) + return + } + if de != nil { + log.Printf("Device ID: %s Name: %s", de.Id, de.Name) + } else { + log.Printf("No Device found") + } + */ + + return +} + +func initKeyTable() (err error) { + log.Printf("Init Key Table") + statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS key ( + id TEXT PRIMARY KEY, + type TEXT, + key TEXT, + deviceId TEXT + )`) + if err != nil { + return + } + statement.Exec() + /* + newKey := &device.Key{Id: "test", Type: "test", Key: "test"} + err = CreateKey(db, newKey, "test") + if err != nil { + log.Printf("Error Create: %s", err) + return + } + keys, err := ReadKeysForDevice(db, "test") + if err != nil { + log.Printf("Error Read Multiple: %s", err) + return + } + log.Println(keys) + newKey.Key = "TEST123" + err = UpdateKey(db, newKey) + if err != nil { + log.Printf("Error Update: %s", err) + return + } + err = DeleteKey(db, newKey.Id) + if err != nil { + log.Printf("Error Delete: %s", err) + return + } + readKey, err := ReadKey(db, "test") + if err != nil { + log.Printf("Error Read: %s", err) + return + } + if readKey != nil { + log.Printf("Key ID: %s Type: %s, Key: %s", readKey.Id, readKey.Type, readKey.Key) + } else { + log.Printf("No Key found") + } + */ + return +} + +func initEventTable() (err error) { + log.Printf("Init Event Table") + statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS event ( + id TEXT PRIMARY KEY, + roomId TEXT, + txnId TEXT, + eventType TEXT, + content TEXT, + parentId TEXT, + depth INTEGER + )`) + if err != nil { + return + } + statement.Exec() + /* + newEvent := &event.Event{ + Id: "test", + RoomId: "test", + EventType: "test", + Content: "{TEST}", + ParentId: "test1", + Depth: 0, + } + err = CreateEvent(db, newEvent, "test") + if err != nil { + log.Printf("Error Create: %s", err) + return + } + eventsRoom, err := ReadEventsFromRoom(db, "test") + if err != nil { + log.Printf("Error Read User: %s", err) + return + } + log.Println(eventsRoom) + eventsTxn, err := ReadEventsFromTransaction(db, "test") + if err != nil { + log.Printf("Error Read User: %s", err) + return + } + log.Println(eventsTxn) + newEvent.Content = "{TEST123}" + err = UpdateEvent(db, newEvent) + if err != nil { + log.Printf("Error Update: %s", err) + return + } + err = DeleteEvent(db, newEvent.Id) + if err != nil { + log.Printf("Error Delete: %s", err) + return + } + readEvent, err := ReadEvent(db, "test") + if err != nil { + log.Printf("Error Read: %s", err) + return + } + if readEvent != nil { + log.Printf("Event ID: %s RoomId: %s EventType: %s Content: %s ParentId: %s Depth: %s", + readEvent.Id, readEvent.RoomId, readEvent.EventType, readEvent.Content, readEvent.ParentId, readEvent.Depth) + } else { + log.Printf("No Event found") + } + */ + return +} + +func initRoomTable() (err error) { + log.Printf("Init Room Table") + statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS room ( + id TEXT PRIMARY KEY, + version TEXT + )`) + if err != nil { + return + } + statement.Exec() + statement, err = DB.Prepare(`CREATE TABLE IF NOT EXISTS roomMember ( + userId TEXT, + roomId TEXT, + PRIMARY KEY (userId, roomId) + )`) + if err != nil { + return + } + statement.Exec() + /* + newRoom := &room.Room{Id: "test", Version: "test"} + err = CreateRoom(db, newRoom, "test") + if err != nil { + log.Printf("Error Create: %s", err) + return + } + err = CreateRoomMember(db, newRoom.Id, "test2") + if err != nil { + log.Printf("Error Create: %s", err) + return + } + roomMembers, err := ReadRoomMembers(db, newRoom.Id) + if err != nil { + log.Printf("Error Read Members: %s", err) + return + } + log.Println(roomMembers) + newRoom.Version = "test2" + err = UpdateRoom(db, newRoom) + if err != nil { + log.Printf("Error Update: %s", err) + return + } + err = DeleteRoomMember(db, newRoom.Id, "test") + if err != nil { + log.Printf("Error Delete: %s", err) + return + } + err = DeleteAllRoomMemberForUser(db, "test2") + if err != nil { + log.Printf("Error Delete: %s", err) + return + } + err = DeleteRoom(db, newRoom.Id) + if err != nil { + log.Printf("Error Delete: %s", err) + return + } + readRoom, err := ReadRoom(db, newRoom.Id) + if err != nil { + log.Printf("Error Read: %s", err) + return + } + if readRoom != nil { + log.Printf("Room ID: %s Version: %s Members: %s", readRoom.Id, readRoom.Version, readRoom.Members) + } else { + log.Printf("No Room found") + } + */ + return +} + +func initTransactionTable() (err error) { + log.Printf("Init Transaction Table") + statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS txn ( + id TEXT PRIMARY KEY, + origin TEXT, + timestamp INTEGER + )`) + if err != nil { + return + } + statement.Exec() + + /* + newTransaction := &transaction.Transaction{Id: "test", Origin: "test.de", Timestamp: 1234} + err = CreateTransaction(db, newTransaction) + if err != nil { + log.Printf("Error Create: %s", err) + return + } + newTransaction.Origin = "test2.de" + err = UpdateTransaction(db, newTransaction) + if err != nil { + log.Printf("Error Update: %s", err) + return + } + err = DeleteTransaction(db, newTransaction.Id) + if err != nil { + log.Printf("Error Delete: %s", err) + return + } + readTransaction, err := ReadTransaction(db, newTransaction.Id) + if err != nil { + log.Printf("Error Read: %s", err) + return + } + if readTransaction != nil { + log.Printf("Transaction ID: %s Origin: %s Timestamp: %s PDUS: %s", readTransaction.Id, readTransaction.Origin, readTransaction.Timestamp, readTransaction.PDUS) + } else { + log.Printf("No Transaction found") + } + */ + return +} + +func initUserTable() (err error) { + log.Printf("Init User Table") + statement, err := DB.Prepare(`CREATE TABLE IF NOT EXISTS user ( + id TEXT PRIMARY KEY, + name TEXT, + password TEXT + )`) + if err != nil { + return + } + statement.Exec() + + /* + newUser := &user.User{Id: "test", Name: "test", Password: "test"} + err = CreateUser(db, newUser) + if err != nil { + log.Printf("Error Create: %s", err) + return + } + newUser.Name = "TEST2" + err = UpdateUser(db, newUser) + if err != nil { + log.Printf("Error Update: %s", err) + return + } + err = DeleteUser(db, newUser.Id) + if err != nil { + log.Printf("Error Delete: %s", err) + return + } + readUser, err := ReadUser(db, newUser.Id) + if err != nil { + log.Printf("Error Read: %s", err) + return + } + if readUser != nil { + log.Printf("User ID: %s Name: %s Password: %s Devices: %s", readUser.Id, readUser.Name, readUser.Password, readUser.Devices) + } else { + log.Printf("No User found") + } + */ return } diff --git a/utils/database/deviceDatabaseConnector.go b/utils/database/deviceDatabaseConnector.go deleted file mode 100644 index 047dbaf..0000000 --- a/utils/database/deviceDatabaseConnector.go +++ /dev/null @@ -1,179 +0,0 @@ -package database - -import ( - "database/sql" - "fmt" - "log" - - "nutfactory.org/Matrix/entities/device" -) - -func initDeviceTable(db *sql.DB) (err error) { - log.Printf("Init Device Table") - statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS device ( - id TEXT PRIMARY KEY, - name TEXT, - userId TEXT - )`) - if err != nil { - return - } - statement.Exec() - - /* - newDevice := &device.Device{Id: "test", Name: "TEST", Keys: nil} - err = CreateDevice(db, newDevice, "test") - if err != nil { - log.Printf("Error Create: %s", err) - return - } - newDevice.Name = "TEST2" - err = UpdateDevice(db, newDevice) - if err != nil { - log.Printf("Error Update: %s", err) - return - } - devices, err := ReadDevicesForUser(db, "test") - if err != nil { - log.Printf("Error Read User: %s", err) - return - } - log.Println(devices) - err = DeleteDevice(db, newDevice.Id) - if err != nil { - log.Printf("Error Delete: %s", err) - return - } - de, err := ReadDevice(db, "test") - if err != nil { - log.Printf("Error Read: %s", err) - return - } - if de != nil { - log.Printf("Device ID: %s Name: %s", de.Id, de.Name) - } else { - log.Printf("No Device found") - } - */ - - return -} - -func CreateDevice(db *sql.DB, device *device.Device, userId string) (err error) { - sqlStmt := fmt.Sprintf(`INSERT INTO device - (id, name, userId) - VALUES - (?, ?, ?)`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec(device.Id, device.Name, userId) - if err != nil { - return - } - tx.Commit() - return -} - -func ReadDevice(db *sql.DB, id string) (foundDevice *device.Device, err error) { - queryStmt := fmt.Sprintf(`SELECT id, name - FROM device - WHERE id = '%s'`, id) - - rows, err := db.Query(queryStmt) - if err != nil { - return - } - - defer rows.Close() - - if rows.Next() { - foundDevice = &device.Device{} - err = rows.Scan(&foundDevice.Id, &foundDevice.Name) - if err != nil { - return - } - foundDevice.Keys, err = ReadKeysForDevice(db, foundDevice.Id) - } - - return -} - -func ReadDevicesForUser(db *sql.DB, userId string) (devices map[string]*device.Device, err error) { - queryStmt := fmt.Sprintf(`SELECT id, name - FROM device - WHERE userId = '%s'`, userId) - - rows, err := db.Query(queryStmt) - if err != nil { - return - } - - defer rows.Close() - - devices = make(map[string]*device.Device) - - for rows.Next() { - foundDevice := &device.Device{} - err = rows.Scan(&foundDevice.Id, &foundDevice.Name) - if err != nil { - return - } - foundDevice.Keys, err = ReadKeysForDevice(db, foundDevice.Id) - devices[foundDevice.Id] = foundDevice - } - - return -} - -func UpdateDevice(db *sql.DB, device *device.Device) (err error) { - sqlStmt := fmt.Sprintf(`UPDATE device SET - name = ? - WHERE id = ?`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec(device.Name, device.Id) - if err != nil { - return - } - - tx.Commit() - return -} - -func DeleteDevice(db *sql.DB, id string) (err error) { - queryStmt := fmt.Sprintf(`DELETE FROM device - WHERE id = '%s'`, id) - - tx, err := db.Begin() - if err != nil { - return - } - - _, err = db.Exec(queryStmt) - if err != nil { - return - } - - tx.Commit() - return -} diff --git a/utils/database/eventDatabaseConnector.go b/utils/database/eventDatabaseConnector.go deleted file mode 100644 index f635ea9..0000000 --- a/utils/database/eventDatabaseConnector.go +++ /dev/null @@ -1,278 +0,0 @@ -package database - -import ( - "database/sql" - "fmt" - "log" - - "nutfactory.org/Matrix/entities/event" - "nutfactory.org/Matrix/entities/transaction" -) - -func initEventTable(db *sql.DB) (err error) { - log.Printf("Init Event Table") - statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS event ( - id TEXT PRIMARY KEY, - roomId TEXT, - txnId TEXT, - eventType TEXT, - content TEXT, - parentId TEXT, - depth INTEGER - )`) - if err != nil { - return - } - statement.Exec() - /* - newEvent := &event.Event{ - Id: "test", - RoomId: "test", - EventType: "test", - Content: "{TEST}", - ParentId: "test1", - Depth: 0, - } - err = CreateEvent(db, newEvent, "test") - if err != nil { - log.Printf("Error Create: %s", err) - return - } - eventsRoom, err := ReadEventsFromRoom(db, "test") - if err != nil { - log.Printf("Error Read User: %s", err) - return - } - log.Println(eventsRoom) - eventsTxn, err := ReadEventsFromTransaction(db, "test") - if err != nil { - log.Printf("Error Read User: %s", err) - return - } - log.Println(eventsTxn) - newEvent.Content = "{TEST123}" - err = UpdateEvent(db, newEvent) - if err != nil { - log.Printf("Error Update: %s", err) - return - } - err = DeleteEvent(db, newEvent.Id) - if err != nil { - log.Printf("Error Delete: %s", err) - return - } - readEvent, err := ReadEvent(db, "test") - if err != nil { - log.Printf("Error Read: %s", err) - return - } - if readEvent != nil { - log.Printf("Event ID: %s RoomId: %s EventType: %s Content: %s ParentId: %s Depth: %s", - readEvent.Id, readEvent.RoomId, readEvent.EventType, readEvent.Content, readEvent.ParentId, readEvent.Depth) - } else { - log.Printf("No Event found") - } - */ - return -} - -func CreateEvent(db *sql.DB, event *event.Event, txnId string) (err error) { - sqlStmt := fmt.Sprintf(`INSERT INTO event - (id, roomId, txnId, eventType, content, parentId, depth) - VALUES - (?, ?, ?, ?, ?, ?, ?)`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec(event.Id, event.RoomId, txnId, event.EventType, event.Content, event.ParentId, event.Depth) - if err != nil { - return - } - tx.Commit() - return -} - -func CreateEventsFromTransaction(db *sql.DB, transaction *transaction.Transaction) (err error) { - sqlStmt := fmt.Sprintf(`INSERT INTO event - (id, roomId, txnId, eventType, content, parentId, depth) - VALUES - (?, ?, ?, ?, ?, ?, ?)`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - for _, pdu := range transaction.PDUS { - _, err = stmt.Exec(pdu.Id, pdu.RoomId, transaction.Id, pdu.EventType, pdu.Content, pdu.ParentId, pdu.Depth) - if err != nil { - return - } - } - - tx.Commit() - return -} - -func ReadEvent(db *sql.DB, id string) (foundEvent *event.Event, err error) { - queryStmt := fmt.Sprintf(`SELECT id, roomId, eventType, content, parentId, depth - FROM event - WHERE id = '%s'`, id) - - rows, err := db.Query(queryStmt) - if err != nil { - return - } - - defer rows.Close() - - if rows.Next() { - foundEvent = &event.Event{} - err = rows.Scan(&foundEvent.Id, - &foundEvent.RoomId, - &foundEvent.EventType, - &foundEvent.Content, - &foundEvent.ParentId, - &foundEvent.Depth, - ) - if err != nil { - return - } - } - - return -} - -func ReadEventsFromRoom(db *sql.DB, roomId string) (events map[string]*event.Event, err error) { - queryStmt := fmt.Sprintf(`SELECT id, roomId, eventType, content, parentId, depth - FROM event - WHERE roomId = '%s'`, roomId) - - rows, err := db.Query(queryStmt) - if err != nil { - return - } - - defer rows.Close() - - events = make(map[string]*event.Event) - - for rows.Next() { - foundEvent := &event.Event{} - err = rows.Scan(&foundEvent.Id, - &foundEvent.RoomId, - &foundEvent.EventType, - &foundEvent.Content, - &foundEvent.ParentId, - &foundEvent.Depth, - ) - if err != nil { - return - } - events[foundEvent.Id] = foundEvent - } - - return -} - -func ReadEventsFromTransaction(db *sql.DB, txnId string) (events map[string]*event.Event, err error) { - queryStmt := fmt.Sprintf(`SELECT id, roomId, eventType, content, parentId, depth - FROM event - WHERE txnId = '%s'`, txnId) - - rows, err := db.Query(queryStmt) - if err != nil { - return - } - - defer rows.Close() - - events = make(map[string]*event.Event) - - for rows.Next() { - foundEvent := &event.Event{} - err = rows.Scan( - &foundEvent.Id, - &foundEvent.RoomId, - &foundEvent.EventType, - &foundEvent.Content, - &foundEvent.ParentId, - &foundEvent.Depth, - ) - if err != nil { - return - } - events[foundEvent.Id] = foundEvent - } - - return -} - -func UpdateEvent(db *sql.DB, event *event.Event) (err error) { - sqlStmt := fmt.Sprintf(`UPDATE event SET - roomId = ?, - eventType = ?, - content = ?, - parentId = ?, - depth = ? - WHERE id = ?`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec( - event.RoomId, - event.EventType, - event.Content, - event.ParentId, - event.Depth, - event.Id, - ) - if err != nil { - return - } - - tx.Commit() - return -} - -func DeleteEvent(db *sql.DB, id string) (err error) { - queryStmt := fmt.Sprintf(`DELETE FROM event - WHERE id = '%s'`, id) - - tx, err := db.Begin() - if err != nil { - return - } - - _, err = db.Exec(queryStmt) - if err != nil { - return - } - - tx.Commit() - return -} diff --git a/utils/database/keyDatabaseConnector.go b/utils/database/keyDatabaseConnector.go deleted file mode 100644 index d7d2b7c..0000000 --- a/utils/database/keyDatabaseConnector.go +++ /dev/null @@ -1,177 +0,0 @@ -package database - -import ( - "database/sql" - "fmt" - "log" - - "nutfactory.org/Matrix/entities/device" -) - -func initKeyTable(db *sql.DB) (err error) { - log.Printf("Init Key Table") - statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS key ( - id TEXT PRIMARY KEY, - type TEXT, - key TEXT, - deviceId TEXT - )`) - if err != nil { - return - } - statement.Exec() - /* - newKey := &device.Key{Id: "test", Type: "test", Key: "test"} - err = CreateKey(db, newKey, "test") - if err != nil { - log.Printf("Error Create: %s", err) - return - } - keys, err := ReadKeysForDevice(db, "test") - if err != nil { - log.Printf("Error Read Multiple: %s", err) - return - } - log.Println(keys) - newKey.Key = "TEST123" - err = UpdateKey(db, newKey) - if err != nil { - log.Printf("Error Update: %s", err) - return - } - err = DeleteKey(db, newKey.Id) - if err != nil { - log.Printf("Error Delete: %s", err) - return - } - readKey, err := ReadKey(db, "test") - if err != nil { - log.Printf("Error Read: %s", err) - return - } - if readKey != nil { - log.Printf("Key ID: %s Type: %s, Key: %s", readKey.Id, readKey.Type, readKey.Key) - } else { - log.Printf("No Key found") - } - */ - return -} - -func CreateKey(db *sql.DB, key *device.Key, deviceId string) (err error) { - sqlStmt := fmt.Sprintf(`INSERT INTO key - (id, type, key, deviceId) - VALUES - (?, ?, ?, ?)`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec(key.Id, key.Type, key.Key, deviceId) - if err != nil { - return - } - tx.Commit() - return -} - -func ReadKey(db *sql.DB, id string) (foundKey *device.Key, err error) { - queryStmt := fmt.Sprintf(`SELECT id, type, key - FROM key - WHERE id = '%s'`, id) - - rows, err := db.Query(queryStmt) - if err != nil { - return - } - - defer rows.Close() - - if rows.Next() { - foundKey = &device.Key{} - err = rows.Scan(&foundKey.Id, &foundKey.Type, &foundKey.Key) - if err != nil { - return - } - } - - return -} - -func ReadKeysForDevice(db *sql.DB, deviceId string) (keys map[string]*device.Key, err error) { - queryStmt := fmt.Sprintf(`SELECT id, type, key - FROM key - WHERE deviceId = '%s'`, deviceId) - - rows, err := db.Query(queryStmt) - if err != nil { - return - } - - defer rows.Close() - - keys = make(map[string]*device.Key) - - for rows.Next() { - foundKey := &device.Key{} - err = rows.Scan(&foundKey.Id, &foundKey.Type, &foundKey.Key) - if err != nil { - return - } - keys[foundKey.Id] = foundKey - } - - return -} - -func UpdateKey(db *sql.DB, key *device.Key) (err error) { - sqlStmt := fmt.Sprintf(`UPDATE key SET - type = ?, - key = ? - WHERE id = ?`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec(key.Type, key.Key, key.Id) - if err != nil { - return - } - - tx.Commit() - return -} - -func DeleteKey(db *sql.DB, id string) (err error) { - queryStmt := fmt.Sprintf(`DELETE FROM key - WHERE id = '%s'`, id) - - tx, err := db.Begin() - if err != nil { - return - } - - _, err = db.Exec(queryStmt) - if err != nil { - return - } - - tx.Commit() - return -} diff --git a/utils/database/roomDatabaseConnector.go b/utils/database/roomDatabaseConnector.go deleted file mode 100644 index 6be7f11..0000000 --- a/utils/database/roomDatabaseConnector.go +++ /dev/null @@ -1,288 +0,0 @@ -package database - -import ( - "database/sql" - "fmt" - "log" - - "nutfactory.org/Matrix/entities/room" -) - -func initRoomTable(db *sql.DB) (err error) { - log.Printf("Init Room Table") - statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS room ( - id TEXT PRIMARY KEY, - version TEXT - )`) - if err != nil { - return - } - statement.Exec() - statement, err = db.Prepare(`CREATE TABLE IF NOT EXISTS roomMember ( - userId TEXT, - roomId TEXT, - PRIMARY KEY (userId, roomId) - )`) - if err != nil { - return - } - statement.Exec() - /* - newRoom := &room.Room{Id: "test", Version: "test"} - err = CreateRoom(db, newRoom, "test") - if err != nil { - log.Printf("Error Create: %s", err) - return - } - err = CreateRoomMember(db, newRoom.Id, "test2") - if err != nil { - log.Printf("Error Create: %s", err) - return - } - roomMembers, err := ReadRoomMembers(db, newRoom.Id) - if err != nil { - log.Printf("Error Read Members: %s", err) - return - } - log.Println(roomMembers) - newRoom.Version = "test2" - err = UpdateRoom(db, newRoom) - if err != nil { - log.Printf("Error Update: %s", err) - return - } - err = DeleteRoomMember(db, newRoom.Id, "test") - if err != nil { - log.Printf("Error Delete: %s", err) - return - } - err = DeleteAllRoomMemberForUser(db, "test2") - if err != nil { - log.Printf("Error Delete: %s", err) - return - } - err = DeleteRoom(db, newRoom.Id) - if err != nil { - log.Printf("Error Delete: %s", err) - return - } - readRoom, err := ReadRoom(db, newRoom.Id) - if err != nil { - log.Printf("Error Read: %s", err) - return - } - if readRoom != nil { - log.Printf("Room ID: %s Version: %s Members: %s", readRoom.Id, readRoom.Version, readRoom.Members) - } else { - log.Printf("No Room found") - } - */ - return -} - -func CreateRoom(db *sql.DB, room *room.Room, userId string) (err error) { - sqlStmt := fmt.Sprintf(`INSERT INTO room - (id, version) - VALUES - (?, ?)`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec(room.Id, room.Version) - if err != nil { - return - } - tx.Commit() - err = CreateRoomMember(db, room.Id, userId) - return -} - -func CreateRoomMember(db *sql.DB, roomId string, userId string) (err error) { - sqlStmt := fmt.Sprintf(`INSERT INTO roomMember - (roomId, userId) - VALUES - (?, ?)`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec(roomId, userId) - if err != nil { - return - } - tx.Commit() - return -} - -func ReadRoom(db *sql.DB, id string) (foundRoom *room.Room, err error) { - queryStmt := fmt.Sprintf(`SELECT id, version - FROM room - WHERE id = '%s'`, id) - - rows, err := db.Query(queryStmt) - if err != nil { - return - } - - defer rows.Close() - - if rows.Next() { - foundRoom = &room.Room{} - err = rows.Scan(&foundRoom.Id, &foundRoom.Version) - if err != nil { - return - } - foundRoom.Messages, err = ReadEventsFromRoom(db, foundRoom.Id) - if err != nil { - return - } - foundRoom.Members, err = ReadRoomMembers(db, foundRoom.Id) - if err != nil { - return - } - } - - return -} - -func ReadRoomMembers(db *sql.DB, roomId string) (roomMembers []string, err error) { - queryStmt := fmt.Sprintf(`SELECT userId - FROM roomMember - WHERE roomId = '%s'`, roomId) - - rows, err := db.Query(queryStmt) - if err != nil { - return - } - - defer rows.Close() - - roomMembers = []string{} - - for rows.Next() { - var foundUser string - err = rows.Scan(&foundUser) - if err != nil { - return - } - roomMembers = append(roomMembers, foundUser) - } - - return -} - -func UpdateRoom(db *sql.DB, room *room.Room) (err error) { - sqlStmt := fmt.Sprintf(`UPDATE room SET - version = ? - WHERE id = ?`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec(room.Version, room.Id) - if err != nil { - return - } - - tx.Commit() - return -} - -func DeleteRoom(db *sql.DB, id string) (err error) { - queryStmt := fmt.Sprintf(`DELETE FROM room - WHERE id = '%s'`, id) - - tx, err := db.Begin() - if err != nil { - return - } - - _, err = db.Exec(queryStmt) - if err != nil { - return - } - - err = DeleteAllRoomMemberForRoom(db, id) - - tx.Commit() - return -} - -func DeleteRoomMember(db *sql.DB, roomId string, userId string) (err error) { - queryStmt := fmt.Sprintf(`DELETE FROM roomMember - WHERE userId = '%s' AND roomId = '%s'`, userId, roomId) - - tx, err := db.Begin() - if err != nil { - return - } - - _, err = db.Exec(queryStmt) - if err != nil { - return - } - - tx.Commit() - return -} - -func DeleteAllRoomMemberForUser(db *sql.DB, userId string) (err error) { - queryStmt := fmt.Sprintf(`DELETE FROM roomMember - WHERE userId = '%s'`, userId) - - tx, err := db.Begin() - if err != nil { - return - } - - _, err = db.Exec(queryStmt) - if err != nil { - return - } - - tx.Commit() - return -} - -func DeleteAllRoomMemberForRoom(db *sql.DB, roomId string) (err error) { - queryStmt := fmt.Sprintf(`DELETE FROM roomMember - WHERE roomId = '%s'`, roomId) - - tx, err := db.Begin() - if err != nil { - return - } - - _, err = db.Exec(queryStmt) - if err != nil { - return - } - - tx.Commit() - return -} diff --git a/utils/database/transactionDatabaseConnector.go b/utils/database/transactionDatabaseConnector.go deleted file mode 100644 index de312a4..0000000 --- a/utils/database/transactionDatabaseConnector.go +++ /dev/null @@ -1,146 +0,0 @@ -package database - -import ( - "database/sql" - "fmt" - "log" - - "nutfactory.org/Matrix/entities/transaction" -) - -func initTransactionTable(db *sql.DB) (err error) { - log.Printf("Init Transaction Table") - statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS txn ( - id TEXT PRIMARY KEY, - origin TEXT, - timestamp INTEGER - )`) - if err != nil { - return - } - statement.Exec() - - /* - newTransaction := &transaction.Transaction{Id: "test", Origin: "test.de", Timestamp: 1234} - err = CreateTransaction(db, newTransaction) - if err != nil { - log.Printf("Error Create: %s", err) - return - } - newTransaction.Origin = "test2.de" - err = UpdateTransaction(db, newTransaction) - if err != nil { - log.Printf("Error Update: %s", err) - return - } - err = DeleteTransaction(db, newTransaction.Id) - if err != nil { - log.Printf("Error Delete: %s", err) - return - } - readTransaction, err := ReadTransaction(db, newTransaction.Id) - if err != nil { - log.Printf("Error Read: %s", err) - return - } - if readTransaction != nil { - log.Printf("Transaction ID: %s Origin: %s Timestamp: %s PDUS: %s", readTransaction.Id, readTransaction.Origin, readTransaction.Timestamp, readTransaction.PDUS) - } else { - log.Printf("No Transaction found") - } - */ - return -} - -func CreateTransaction(db *sql.DB, transaction *transaction.Transaction) (err error) { - sqlStmt := fmt.Sprintf(`INSERT INTO txn - (id, origin, timestamp) - VALUES - (?, ?, ?)`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec(transaction.Id, transaction.Origin, transaction.Timestamp) - if err != nil { - return - } - tx.Commit() - return -} - -func ReadTransaction(db *sql.DB, id string) (foundTransaction *transaction.Transaction, err error) { - queryStmt := fmt.Sprintf(`SELECT id, origin, timestamp - FROM txn - WHERE id = '%s'`, id) - - rows, err := db.Query(queryStmt) - if err != nil { - return - } - - defer rows.Close() - - if rows.Next() { - foundTransaction = &transaction.Transaction{} - err = rows.Scan(&foundTransaction.Id, &foundTransaction.Origin, &foundTransaction.Timestamp) - if err != nil { - return - } - foundTransaction.PDUS, err = ReadEventsFromTransaction(db, foundTransaction.Id) - } - - return -} - -func UpdateTransaction(db *sql.DB, transaction *transaction.Transaction) (err error) { - sqlStmt := fmt.Sprintf(`UPDATE txn SET - origin = ?, - timestamp = ? - WHERE id = ?`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec(transaction.Origin, transaction.Timestamp, transaction.Id) - if err != nil { - return - } - - tx.Commit() - return -} - -func DeleteTransaction(db *sql.DB, id string) (err error) { - queryStmt := fmt.Sprintf(`DELETE FROM txn - WHERE id = '%s'`, id) - - tx, err := db.Begin() - if err != nil { - return - } - - _, err = db.Exec(queryStmt) - if err != nil { - return - } - - tx.Commit() - return -} diff --git a/utils/database/userDatabaseConnector.go b/utils/database/userDatabaseConnector.go deleted file mode 100644 index 3ec2715..0000000 --- a/utils/database/userDatabaseConnector.go +++ /dev/null @@ -1,147 +0,0 @@ -package database - -import ( - "database/sql" - "fmt" - "log" - - "nutfactory.org/Matrix/entities/user" -) - -func initUserTable(db *sql.DB) (err error) { - log.Printf("Init User Table") - statement, err := db.Prepare(`CREATE TABLE IF NOT EXISTS user ( - id TEXT PRIMARY KEY, - name TEXT, - password TEXT - )`) - if err != nil { - return - } - statement.Exec() - - /* - newUser := &user.User{Id: "test", Name: "test", Password: "test"} - err = CreateUser(db, newUser) - if err != nil { - log.Printf("Error Create: %s", err) - return - } - newUser.Name = "TEST2" - err = UpdateUser(db, newUser) - if err != nil { - log.Printf("Error Update: %s", err) - return - } - err = DeleteUser(db, newUser.Id) - if err != nil { - log.Printf("Error Delete: %s", err) - return - } - readUser, err := ReadUser(db, newUser.Id) - if err != nil { - log.Printf("Error Read: %s", err) - return - } - if readUser != nil { - log.Printf("User ID: %s Name: %s Password: %s Devices: %s", readUser.Id, readUser.Name, readUser.Password, readUser.Devices) - } else { - log.Printf("No User found") - } - */ - - return -} - -func CreateUser(db *sql.DB, user *user.User) (err error) { - sqlStmt := fmt.Sprintf(`INSERT INTO user - (id, name, password) - VALUES - (?, ?, ?)`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec(user.Id, user.Name, user.Password) - if err != nil { - return - } - tx.Commit() - return -} - -func ReadUser(db *sql.DB, id string) (foundUser *user.User, err error) { - queryStmt := fmt.Sprintf(`SELECT id, name, password - FROM user - WHERE id = '%s'`, id) - - rows, err := db.Query(queryStmt) - if err != nil { - return - } - - defer rows.Close() - - if rows.Next() { - foundUser = &user.User{} - err = rows.Scan(&foundUser.Id, &foundUser.Name, &foundUser.Password) - if err != nil { - return - } - foundUser.Devices, err = ReadDevicesForUser(db, foundUser.Id) - } - - return -} - -func UpdateUser(db *sql.DB, user *user.User) (err error) { - sqlStmt := fmt.Sprintf(`UPDATE user SET - name = ?, - password = ? - WHERE id = ?`) - - tx, err := db.Begin() - if err != nil { - return - } - - stmt, err := tx.Prepare(sqlStmt) - if err != nil { - return - } - defer stmt.Close() - - _, err = stmt.Exec(user.Name, user.Password, user.Id) - if err != nil { - return - } - - tx.Commit() - return -} - -func DeleteUser(db *sql.DB, id string) (err error) { - queryStmt := fmt.Sprintf(`DELETE FROM user - WHERE id = '%s'`, id) - - tx, err := db.Begin() - if err != nil { - return - } - - _, err = db.Exec(queryStmt) - if err != nil { - return - } - - tx.Commit() - return -} diff --git a/utils/requestChecker.go b/utils/requestChecker.go new file mode 100644 index 0000000..a808be7 --- /dev/null +++ b/utils/requestChecker.go @@ -0,0 +1,32 @@ +package utils + +import ( + "encoding/json" + "net/http" + "strings" +) + +type ErrorResponse struct { + ErrorCode string `json:"errcode,omitempty"` + ErrorMessage string `json:"error,omitempty"` + RetryTime int `json:"retry_after_ms,omitempty"` +} + +func CheckRequest(r *http.Request, request interface{}) (response *ErrorResponse) { + if !strings.Contains(r.Header.Get("Content-Type"), "application/json") { + response = &ErrorResponse{ErrorMessage: "Content Type not JSON"} + } + return +} + +func IsJSONString(s string) bool { + var js string + return json.Unmarshal([]byte(s), &js) == nil + +} + +func IsJSON(s string) bool { + var js interface{} + return json.Unmarshal([]byte(s), &js) == nil + +}