Skip to content

Commit

Permalink
feat(frontend): Implement opening chat page after auth, feat(client):…
Browse files Browse the repository at this point in the history
… Implement full pipeline of register, login, send message
  • Loading branch information
ddlifter committed May 22, 2024
1 parent 0b20d41 commit b10b984
Show file tree
Hide file tree
Showing 13 changed files with 179 additions and 192 deletions.
33 changes: 0 additions & 33 deletions client/src/common/register.go

This file was deleted.

39 changes: 0 additions & 39 deletions client/src/common/send_message.go

This file was deleted.

8 changes: 4 additions & 4 deletions client/src/create_room/create_room.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ func main() {
client := proto.NewChatClient(conn)

ctx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs(
"user_uuid", "d9890202-a129-4044-8736-e7770fcae7f5",
"auth_token", "f94ee0212842c6434f019eb42bfcdc63",
"user_uuid", "17c4ab93-0b16-4233-9936-9f1c89ab96d7",
"auth_token", "70ea0d70360f118b4de4dd7d2b40c543",
))

roomReq := &proto.ClientsideRoom{
Name: "Room2",
Name: "Room0",
Members: []*proto.UUID{
&proto.UUID{Uuid: "d9890202-a129-4044-8736-e7770fcae7f5"},
&proto.UUID{Uuid: "17c4ab93-0b16-4233-9936-9f1c89ab96d7"},
},
}

Expand Down
26 changes: 20 additions & 6 deletions client/src/handle_front/handle_front.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package main

import (
"bb-hackathon/tcp-chat.git/src/common"
sendmessage "bb-hackathon/tcp-chat.git/src/send_message"
"encoding/json"
"fmt"
"log"
Expand Down Expand Up @@ -37,10 +37,8 @@ func sendMessageHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Println(t)
common.SendMessage(t, "36537ef0-ee3e--aaa1-6547e466dd4a")
sendmessage.SendMessage(t, "8299ace8-e565-497a-868a-e48fde731fef")

// Ответ клиенту
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "success"})
}
Expand All @@ -54,9 +52,24 @@ func registerHandler(w http.ResponseWriter, r *http.Request) {
return
}
fmt.Println(username, password)
common.Register(username, password)
sendmessage.Register(username, password)

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "success"})
}

func loginHandler(w http.ResponseWriter, r *http.Request) {
var msg UserCreds
err := json.NewDecoder(r.Body).Decode(&msg)
username := msg.Login
password := msg.Password
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Println(username, password)
sendmessage.Login(username, password)

// Ответ клиенту
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "success"})
}
Expand All @@ -65,6 +78,7 @@ func main() {
mux := http.NewServeMux()
mux.HandleFunc("/send", sendMessageHandler)
mux.HandleFunc("/register", registerHandler)
mux.HandleFunc("/login", loginHandler)
// Добавляем CORSHandler
handler := CORSHandler(mux)

Expand Down
35 changes: 0 additions & 35 deletions client/src/login/login.go

This file was deleted.

10 changes: 10 additions & 0 deletions client/src/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package main

import (
sendmessage "bb-hackathon/tcp-chat.git/src/send_message"
)

func main() {
sendmessage.Login("user1234", "1234")
sendmessage.SendMessage("message", "8299ace8-e565-497a-868a-e48fde731fef")
}
110 changes: 110 additions & 0 deletions client/src/send_message/send_message.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package sendmessage

import (
"context"
"log"
"sync"

proto "bb-hackathon/tcp-chat.git/proto"

"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)

var (
UserUUID string
AuthToken string
authDataMux sync.Mutex
)

func setUserAuthData(uuid, token string) {
authDataMux.Lock()
defer authDataMux.Unlock()
UserUUID = uuid
AuthToken = token
}

func getUserAuthData() (string, string) {
authDataMux.Lock()
defer authDataMux.Unlock()
return UserUUID, AuthToken
}

func Register(username string, password string) {
conn, err := grpc.Dial("luna:9001", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()

client := proto.NewRegistryClient(conn)

ctx := context.Background()
userCredentials := &proto.UserCredentials{
Username: username,
Password: password,
}

_, err = client.RegisterNewUser(ctx, userCredentials)
if err != nil {
log.Fatalf("could not register new user: %v", err)
}

log.Printf("Registered new user successfully")
}

func Login(username, password string) {
conn, err := grpc.Dial("luna:9001", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()

client := proto.NewRegistryClient(conn)

ctx := context.Background()
userCredentials := &proto.UserCredentials{
Username: username,
Password: password,
}

response, err := client.LoginAsUser(ctx, userCredentials)
if err != nil {
log.Fatalf("could not login: %v", err)
}

setUserAuthData(response.UserUuid.Uuid, response.Token.Token)

log.Printf("Logged in successfully")
}

func SendMessage(t string, room string) {
userUUID, authToken := getUserAuthData()

conn, err := grpc.Dial("luna:9001", grpc.WithInsecure())
if err != nil {
log.Fatalf("Failed to connect: %v", err)
}
defer conn.Close()

client := proto.NewChatClient(conn)

md := metadata.Pairs(
"user_uuid", userUUID,
"auth_token", authToken,
)

ctx := metadata.NewOutgoingContext(context.Background(), md)
log.Println(t)
messageReq := &proto.ClientsideMessage{
RoomUuid: &proto.UUID{Uuid: room},
Text: t,
}

_, err = client.SendMessage(ctx, messageReq)
if err != nil {
log.Fatalf("SendMessage failed: %v", err)
} else {
log.Printf("Message sent successfully: %s", t)
}
}
33 changes: 32 additions & 1 deletion frontend/scripts/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const signUpButton = document.getElementById('signUp');
const signInButton = document.getElementById('signIn');
const container = document.getElementById('container');
const registerButton = document.getElementById('register');
const loginButton = document.getElementById('login');
signUpButton.addEventListener('click', () => {
container.classList.add("right-panel-active");
});
Expand All @@ -27,7 +28,37 @@ registerButton.addEventListener('click', () => {
.then(response => response.json())
.then(data => {
console.log("Message sent:", data);
messageInput.value = ""; // Clear the input field
loginInput.value = "";
passwordInput.value = "";
window.location.href = "index.html";

})
.catch(error => {
console.error("Error sending message:", error);
});
}
});

loginButton.addEventListener('click', () => {
var loginInput = document.getElementById("login_login");
var login = loginInput.value;
var passwordInput = document.getElementById("login_password");
var password = passwordInput.value;

if (login.trim() !== "" && password.trim() !== "") {
fetch("http://localhost:8080/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ login: login, password: password })
})
.then(response => response.json())
.then(data => {
console.log("Message sent:", data);
loginInput.value = "";
passwordInput.value = "";
window.location.href = "index.html";
})
.catch(error => {
console.error("Error sending message:", error);
Expand Down
Empty file removed frontend/scripts/signin.js
Empty file.
Empty file removed frontend/scripts/signup.js
Empty file.
6 changes: 3 additions & 3 deletions frontend/templates/auth.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ <h1>Создать аккаунт</h1>
<form action="#">
<h1>Войти в аккаунт</h1>
<span></span>
<input type="email" placeholder="Логин" />
<input type="password" placeholder="Пароль" />
<button style="border: none; cursor: pointer;">Войти</button>
<input type="text" placeholder="Логин" id='login_login' />
<input type="password" placeholder="Пароль" id='login_password' />
<button style="border: none; cursor: pointer;" id = "login">Войти</button>
</form>
</div>
<div class="overlay-container">
Expand Down
Loading

0 comments on commit b10b984

Please sign in to comment.