Skip to content

Commit

Permalink
ECDH usage for user auth and data encryption
Browse files Browse the repository at this point in the history
  • Loading branch information
berkkirtay committed Sep 21, 2024
1 parent 42f8c1a commit 3baab8d
Show file tree
Hide file tree
Showing 17 changed files with 330 additions and 126 deletions.
9 changes: 4 additions & 5 deletions src/api/controllers/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,19 @@ package controllers
import (
"encoding/json"
"main/services/auth"
"main/services/user"
"net/http"

"github.com/gin-gonic/gin"
)

func postAuthRequest(c *gin.Context) {
var userBody user.User
err := json.NewDecoder(c.Request.Body).Decode(&userBody)
var authBody auth.AuthenticationModel
err := json.NewDecoder(c.Request.Body).Decode(&authBody)
if err != nil {
panic(err)
}
res := auth.Authenticate(userBody, c)
if res.Token == "" {
res := auth.Authenticate(authBody, c)
if res.Id == "" {
c.AbortWithStatusJSON(http.StatusBadRequest, res)
return
}
Expand Down
6 changes: 5 additions & 1 deletion src/api/controllers/room.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,11 @@ func leaveRoom(c *gin.Context) {
}

func receiveMessagesHTTP(c *gin.Context) {
res := room.ReceiveMessages(c.Query("id"), c.Query("size"), c.Query("sort"), c.Request.Header.Get("Session"))
res := room.ReceiveMessages(
c.Query("id"),
c.Query("size"),
c.Query("sort"),
c.Request.Header.Get("Session"))
if len(res) == 0 {
c.JSON(http.StatusNotFound, res)
} else {
Expand Down
2 changes: 0 additions & 2 deletions src/api/controllers/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ package controllers

import (
"encoding/json"
"fmt"
"main/services/audit"
"main/services/user"
"net/http"
Expand All @@ -29,7 +28,6 @@ func postUser(c *gin.Context) {
}
userBody.Audit = audit.CreateAuditForUser(c.ClientIP())
res := user.PostUser(userBody)
fmt.Println(userBody.Audit)
c.JSON(http.StatusCreated, res)
}

Expand Down
13 changes: 11 additions & 2 deletions src/api/middlewares/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package middlewares

import (
"crypto/rand"
"main/services/auth"
"net/http"

"github.com/gin-contrib/sessions"
Expand Down Expand Up @@ -34,6 +35,14 @@ func ValidateAuthentication() gin.HandlerFunc {

func isAuthenticated(c *gin.Context) bool {
session := sessions.Default(c)
sessionId := session.Get(c.Request.Header.Get("Authorization"))
return sessionId == c.Request.Header.Get("Session")
authToken := c.Request.Header.Get("Authorization")
userId := c.Request.Header.Get("Session")
publicKey := c.Request.Header.Get("PublicKey")
if publicKey != "" {
// var token string =
auth.InitializeSessionWithDiffieHellman(c, publicKey, userId)
// return token == authToken
}
sessionId := session.Get(authToken)
return sessionId == userId
}
20 changes: 13 additions & 7 deletions src/commands/peer_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package commands
import (
"encoding/json"
"fmt"
"main/infra/cryptography"
"main/infra/http"
"main/services/peer"
)
Expand All @@ -15,32 +16,37 @@ func InitializeAMasterPeer(hostname string, address string) {
assignedPeer = peer.CreatePeer(
peer.WithHostname(hostname),
peer.WithAddress(address),
peer.WithRole(peer.INBOUND))
peer.WithRole(peer.INBOUND),
peer.WithCryptography(cryptography.CreateCommonCrypto()))
peer.PostPeer(assignedPeer)
}

// TODO review here:
func RegisterPeer(targetAddress string, hostname string, address string) {
var newPeer peer.Peer = peer.CreatePeer(
peer.WithHostname(hostname),
peer.WithAddress(address),
peer.WithRole(peer.OUTBOUND))
peer.WithRole(peer.OUTBOUND),
peer.WithCryptography(assignedPeer.Cryptography))
body, err := json.Marshal(newPeer)
if err != nil {
panic("err")

}
res := http.POST(targetAddress+"/peer", string(body), &newPeer)
res := http.POST(assignedPeer, targetAddress+"/peer", string(body), &newPeer)
if res.StatusCode != http.CREATED {
fmt.Println(res)
panic("err")
}
peer.PostPeer(peer.CreatePeer(
peer.WithPeer(newPeer),
peer.WithRole(peer.INBOUND)))
peer.WithRole(peer.INBOUND),
peer.WithCryptography(
cryptography.CreateCryptography(
cryptography.WithElliptic(assignedPeer.Cryptography.Elliptic)))))
}

func DeletePeer(peer.Peer) {
res := http.DELETE(assignedPeer.Address+"/peer", nil, "hostId", assignedPeer.Hostname)
res := http.DELETE(assignedPeer, assignedPeer.Address+"/peer", nil, "hostId", assignedPeer.Hostname)
if res.StatusCode != http.OK {
fmt.Printf("Error removing the peer.")
}
Expand All @@ -57,7 +63,7 @@ func IsPeerInitialized() bool {
}

func isPeerOnline(peer peer.Peer) bool {
res := http.GET(peer.Address+"/peer", nil)
res := http.GET(peer, peer.Address+"/peer", nil)
if res == nil || (res != nil && res.StatusCode != http.OK) {
fmt.Printf("Peer %s is offline.\n", peer.Hostname)
return false
Expand Down
60 changes: 35 additions & 25 deletions src/commands/room_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,18 @@ var retrieveMessagesFlag bool
var lastMessageId int64

func HandleGetRooms() {
url := assignedPeer.Address + "/room"
var rooms = make([]room.Room, 5)
var res = http.GET(url, &rooms, "size", "5")
if res.StatusCode != http.OK {
fmt.Printf("Error")
return
}
fmt.Printf("Available rooms in the server:\n")
fmt.Printf("------------\n")
for _, room := range rooms {
fmt.Printf("Id and Room Name: %s - %s\nInfo: %s\n", room.Id, room.Name, room.Info)
fmt.Printf("Capacity: %v\nOther details: %s\n", room.Capacity, room.Audit.CreateDate)
var res = http.GET(assignedPeer, assignedPeer.Address+"/room", &rooms, "size", "5")
if res.StatusCode == http.OK {
fmt.Printf("Available rooms in the server:\n")
fmt.Printf("------------\n")
for _, room := range rooms {
fmt.Printf("Id and Room Name: %s - %s\nInfo: %s\n", room.Id, room.Name, room.Info)
fmt.Printf("Capacity: %v\nOther details: %s\n", room.Capacity, room.Audit.CreateDate)
fmt.Printf("------------\n")
}
} else {
fmt.Printf("No rooms found.")
}
}

Expand All @@ -57,7 +56,7 @@ func HandleCreateRoom(command []string) {
fmt.Printf("Error: %s", err)
return
}
res := http.POST(assignedPeer.Address+"/room", string(body), &room)
res := http.POST(assignedPeer, assignedPeer.Address+"/room", string(body), &room)
if res.StatusCode != http.CREATED {
fmt.Printf("Error")
return
Expand All @@ -66,7 +65,6 @@ func HandleCreateRoom(command []string) {
}

func HandleText(command string) {
url := assignedPeer.Address + "/room/messages"
var message room.Message = room.CreateMessage(
room.WithText(cryptography.EncryptAES(command, currentRoom.RoomMasterKey)),
room.WithIsEncrypted(true))
Expand All @@ -76,7 +74,7 @@ func HandleText(command string) {
return
}

res := http.POST(url, string(body), message, "id", currentRoom.Id)
res := http.POST(assignedPeer, assignedPeer.Address+"/room/messages", string(body), message, "id", currentRoom.Id)
if res.StatusCode != http.CREATED {
fmt.Printf("Message could not be sent.")
return
Expand All @@ -92,7 +90,6 @@ func HandleJoinRoom(command []string, user user.User) {
}

func joinRoom(roomId string, roomPassword string) {
url := assignedPeer.Address + "/room/join"
var room = room.CreateRoom(
room.WithId(roomId),
room.WithPassword(roomPassword))
Expand All @@ -101,7 +98,7 @@ func joinRoom(roomId string, roomPassword string) {
fmt.Printf("Error: %s", err)
return
}
res := http.POST(url, string(body), &room, "id", roomId)
res := http.POST(assignedPeer, assignedPeer.Address+"/room/join", string(body), &room, "id", roomId)
if res.StatusCode != http.OK {
fmt.Printf("Error")
return
Expand All @@ -113,14 +110,8 @@ func joinRoom(roomId string, roomPassword string) {
fmt.Printf("Joined the room. You will talk with:\n")
roomUsers = make(map[string]user.User)
for _, userId := range room.Members {
var userBody = []user.User{}
var res = http.GET(assignedPeer.Address+"/users", &userBody, "id", userId)
if res.StatusCode != http.OK {
fmt.Printf("Error")
return
}
roomUsers[userId] = userBody[0]
fmt.Printf("%s\n", userBody[0].Name)
roomUsers[userId] = getUser(userId)
fmt.Printf("%s\n", roomUsers[userId].Name)
}
}

Expand All @@ -140,6 +131,7 @@ func messageLoop() {
func getMessages(size int64) {
var messages = []room.Message{}
res := http.GET(
assignedPeer,
assignedPeer.Address+"/room/messages",
&messages,
"id",
Expand All @@ -160,6 +152,9 @@ func printMessages(messages []room.Message) {
for _, message := range messages {
currentMessageId, _ := strconv.ParseInt(message.Id, 10, 64)
if currentMessageId > lastMessageId {
if roomUsers[message.UserId].Id == "" {
roomUsers[message.UserId] = getUser(message.UserId)
}
fmt.Printf(
"\r%s >> %s\n", roomUsers[message.UserId].Name,
buildAReadableText(message))
Expand All @@ -171,13 +166,14 @@ func printMessages(messages []room.Message) {
func fetchLastMessageId() int64 {
var messages = []room.Message{}
res := http.GET(
assignedPeer,
assignedPeer.Address+"/room/messages",
&messages,
"id",
currentRoom.Id,
"size",
"1")
if res.StatusCode != http.NOT_FOUND {
if res != nil && res.StatusCode != http.NOT_FOUND {
lastStoredMessageId, _ := strconv.ParseInt(messages[0].Id, 10, 64)
return lastStoredMessageId
}
Expand All @@ -192,6 +188,20 @@ func buildAReadableText(message room.Message) string {
}
}

func getUser(userId string) user.User {
var userBody = []user.User{}
var res = http.GET(
assignedPeer,
assignedPeer.Address+"/users",
&userBody,
"id",
userId)
if res.StatusCode == http.OK {
return userBody[0]
}
return user.CreateDefaultUser()
}

func HandleExitRoom() {
retrieveMessagesFlag = false
fmt.Println("You left the room.")
Expand Down
Loading

0 comments on commit 3baab8d

Please sign in to comment.