Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 60 additions & 14 deletions client/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package main

import (
"bufio"
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"strings"
Expand All @@ -24,26 +24,57 @@ func connectToEchoServer(serverURL string, username string, password string) err
defer c.Close()

fmt.Printf("[%s] ✓ Connected to server\n", getTimestamp())
err = c.WriteMessage(websocket.TextMessage, []byte(username))

// Create authentication JSON
authData := map[string]string{
"username": username,
"password": password,
}
authJSON, err := json.Marshal(authData)
if err != nil {
return fmt.Errorf("Failed to create authentication data: %v", err)
}

err = c.WriteMessage(websocket.TextMessage, authJSON)
if err != nil {
return fmt.Errorf("Failed to write to server: %v", err)

}
fmt.Printf("[%s] ✓ Username sent: %s\n", getTimestamp(), username)
fmt.Printf("[%s] ✓ Authentication data sent for user: %s\n", getTimestamp(), username)
fmt.Println("-------------------------------------------")
fmt.Println("Waiting for authentication response...")

// Wait for authentication response
messageType, data, err := c.ReadMessage()
if err != nil {
return fmt.Errorf("[%s] ✗ Connection error: %v", getTimestamp(), err)
}

if messageType == websocket.TextMessage {
message := string(data)
if strings.HasPrefix(message, "ERROR:") {
fmt.Printf("\r%s%s\n", "\033[K", message)
return fmt.Errorf("Authentication failed: %s", message)
} else {
fmt.Printf("\r%s%s\n", "\033[K", message)
fmt.Printf("[%s] ✓ Authentication successful!\n", getTimestamp())
}
}

fmt.Println("Listening for messages from server...")

// Run a goroutine so incoming messages are received in background while user types
go func() {
for {
messageType, data, err := c.ReadMessage()
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v", err)
log.Println(err)
fmt.Printf("\r%sConnection closed by server.\n", "\033[K")
os.Exit(1)
return
}
if err != nil {
fmt.Printf("error: %v\n", err)
fmt.Printf("\r%sConnection error: %v\n", "\033[K", err)
os.Exit(1)
break
}
if messageType == websocket.TextMessage {
Expand All @@ -70,12 +101,18 @@ func connectToEchoServer(serverURL string, username string, password string) err

func getUsername() string {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your username: ")
username, _ := reader.ReadString('\n')
if len(username) > 0 && username[len(username)-1] == '\n' {
username = username[:len(username)-1]
for {
fmt.Print("Enter your username: ")
username, _ := reader.ReadString('\n')
username = strings.TrimSpace(username)

if username == "" {
fmt.Println("Username cannot be empty. Please try again.")
continue
}

return username
}
return username
}

func getTimestamp() string {
Expand All @@ -97,7 +134,16 @@ func getServerAddress() string {

func getPassword() string {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your password: ")
password, _ := reader.ReadString('\n')
return strings.TrimSpace(password)
for {
fmt.Print("Enter your password: ")
password, _ := reader.ReadString('\n')
password = strings.TrimSpace(password)

if password == "" {
fmt.Println("Password cannot be empty. Please try again.")
continue
}

return password
}
}
29 changes: 28 additions & 1 deletion documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ getTimestamp() // returns the current timestamp as a string in the format of "02
- Updated client/chat.go:
- Added getServerAddress() function to capture server URL from user input via stdin.
- Implemented default fallback to "localhost:8080" if input is empty.

- Updated client/main.go:
- Removed dependency on command-line flags for server address.
- Reordered logic to prompt for Server Address first, then Username.
Expand All @@ -80,6 +79,7 @@ getTimestamp() // returns the current timestamp as a string in the format of "02
### {Krishna200608} {#108 Into Fire (Client ver.)}

- Updated client/chat.go:

- Added getPassword() function to capture user password from stdin.
- Updated connectToEchoServer() signature to accept password parameter.
- Modified message listener loop to remove "Server -> Client" prefix and redundant client-side timestamp, aligning output with the required spec.
Expand All @@ -88,3 +88,30 @@ getTimestamp() // returns the current timestamp as a string in the format of "02
- Added call to getPassword() after username prompt.
- Passed password to connectToEchoServer().
- Tested locally: Verified password prompt appears and chat messages display cleanly.

### {dwivediprashant} {#111 Into Fire (Server ver.)}

- Updated server/server.js:

- Added bcrypt dependency for password hashing.
- Implemented authentication functions: hashPassword(), verifyPassword(), findUser(), createUser().
- Modified connection logic to handle JSON authentication data.
- Added proper error handling for wrong passwords and duplicate online users.

- Updated server/models/User.js:

- Added password field to user schema for storing hashed passwords.

- Updated server/package.json:

- Added bcrypt dependency for secure password hashing.

- Updated client/chat.go:

- Added JSON encoding for authentication data.
- Modified connectToEchoServer() to send {"username": "...", "password": "..."}.
- Added input validation to prevent empty usernames and passwords.
- Implemented proper authentication error handling with clean exit on failure.
- Added success message display for correct authentication.

- Tested locally: Verified new user registration, existing user login, wrong password rejection, and proper error handling.
1 change: 1 addition & 0 deletions server/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
MONGODB_URI=your_mongodb_uri
4 changes: 4 additions & 0 deletions server/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ const userSchema = new mongoose.Schema({
unique: true,
trim: true,
},
password: {
type: String,
required: true,
},
connectedAt: {
type: Date,
default: Date.now,
Expand Down
35 changes: 35 additions & 0 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^6.0.0",
"dotenv": "^17.2.3",
"mongoose": "^9.1.2",
"nodemon": "^3.1.11",
Expand Down
Loading