Skip to content

Commit

Permalink
fix some little bug
Browse files Browse the repository at this point in the history
  • Loading branch information
xdzqyyds committed Nov 28, 2024
1 parent b31e058 commit 079df30
Show file tree
Hide file tree
Showing 4 changed files with 165 additions and 177 deletions.
112 changes: 56 additions & 56 deletions server/api/v1/login.go
Original file line number Diff line number Diff line change
@@ -1,56 +1,56 @@
package v1

import (
"context"
"encoding/json"
"log"
"net/http"

"github.com/go-chi/render"
)

type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}

type LoginResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
}

func (h *Handler) HandleLogin(w http.ResponseWriter, r *http.Request) {
var loginReq LoginRequest

// Decode JSON request body
if err := json.NewDecoder(r.Body).Decode(&loginReq); err != nil {
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, LoginResponse{Success: false, Message: "Invalid request"})
return
}

// Redis hash key
userStorageKey := "user_storage"

// get password
ctx := context.Background()
passwordKey := loginReq.Username + ".password"
log.Printf("Attempting to fetch password for key: %s\n", passwordKey) // 增加调试日志
password, err := h.rdb.HGet(ctx, userStorageKey, passwordKey).Result()
if err != nil {
log.Printf("Failed to find password for key: %s, error: %v\n", passwordKey, err) // 增加调试日志
w.WriteHeader(http.StatusUnauthorized)
render.JSON(w, r, LoginResponse{Success: false, Message: "User not found"})
return
}

// verify password
if password != loginReq.Password {
log.Printf("Password mismatch: expected %s, got %s\n", password, loginReq.Password) // 增加调试日志
w.WriteHeader(http.StatusUnauthorized)
render.JSON(w, r, LoginResponse{Success: false, Message: "Invalid password"})
return
}

render.JSON(w, r, LoginResponse{Success: true, Message: "Login successful"})
}
package v1

import (
"context"
"encoding/json"
"log"
"net/http"

"github.com/go-chi/render"
)

type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}

type LoginResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
}

func (h *Handler) HandleLogin(w http.ResponseWriter, r *http.Request) {
var loginReq LoginRequest

// Decode JSON request body
if err := json.NewDecoder(r.Body).Decode(&loginReq); err != nil {
w.WriteHeader(http.StatusBadRequest)
render.JSON(w, r, LoginResponse{Success: false, Message: "Invalid request"})
return
}

// Redis hash key
userStorageKey := "user_storage"

// get password
ctx := context.Background()
passwordKey := loginReq.Username
log.Printf("Attempting to fetch password for key: %s\n", passwordKey)
password, err := h.rdb.HGet(ctx, userStorageKey, passwordKey).Result()
if err != nil {
log.Printf("Failed to find password for key: %s, error: %v\n", passwordKey, err)
w.WriteHeader(http.StatusUnauthorized)
render.JSON(w, r, LoginResponse{Success: false, Message: "User not found"})
return
}

// verify password
if password != loginReq.Password {
log.Printf("Password mismatch: expected %s, got %s\n", password, loginReq.Password)
w.WriteHeader(http.StatusUnauthorized)
render.JSON(w, r, LoginResponse{Success: false, Message: "Invalid password"})
return
}

render.JSON(w, r, LoginResponse{Success: true, Message: "Login successful"})
}
83 changes: 39 additions & 44 deletions server/daemon/redis.go
Original file line number Diff line number Diff line change
@@ -1,44 +1,39 @@
package daemon

import (
"context"
"log"

"github.com/redis/go-redis/v9"
)

func clearRedis(rdb *redis.Client) {
ctx := context.Background()
if err := rdb.FlushDB(ctx).Err(); err != nil {
log.Printf("Failed to clear Redis database: %v\n", err)
} else {
log.Println("Redis database cleared")
}
}

func initUserData(rdb *redis.Client) {
ctx := context.Background()

// Redis hash
userStorageKey := "user_storage"

// users_storage
users := map[string]map[string]string{
"a": {"password": "aaa"},
"b": {"password": "bbb"},
"c": {"password": "ccc"},
"d": {"password": "ddd"},
}

// add to Redis
for user, fields := range users {
for key, value := range fields {
fullKey := user + "." + key
if err := rdb.HSet(ctx, userStorageKey, fullKey, value).Err(); err != nil {
log.Printf("Failed to set user %s data: %v\n", user, err)
} else {
log.Printf("Set Redis key: %s, value: %s\n", fullKey, value)
}
}
}
}
package daemon

import (
"context"
"log"

"github.com/redis/go-redis/v9"
)

func clearRedis(rdb *redis.Client) {
ctx := context.Background()
if err := rdb.FlushDB(ctx).Err(); err != nil {
log.Printf("Failed to clear Redis database: %v\n", err)
} else {
log.Println("Redis database cleared")
}
}

func initUserData(rdb *redis.Client) {
ctx := context.Background()

// Redis hash
userStorageKey := "user_storage"

// users storage with key as username and value as password
users := map[string]string{
"a": "aaa",
"b": "bbb",
"c": "ccc",
"d": "ddd",
}

// add to Redis
for user, password := range users {
if err := rdb.HSet(ctx, userStorageKey, user, password).Err(); err != nil {
log.Printf("Failed to set user %s data: %v\n", user, err)
}
}
}
137 changes: 68 additions & 69 deletions webapp/components/login.tsx
Original file line number Diff line number Diff line change
@@ -1,69 +1,68 @@
import { useState } from 'react'
import { useAtom } from 'jotai'
import { userIdAtom, userPasswordAtom, isLoggedInAtom } from '../store/atom'
import Join from '../components/join'
import { login } from '../lib/api'

export default function Login() {
const [userId, setUserId] = useAtom(userIdAtom)
const [password, setPassword] = useAtom(userPasswordAtom)
const [isLoggedIn, setIsLoggedIn] = useAtom(isLoggedInAtom)
const [error, setError] = useState<string | null>(null)

const handleLogin = async () => {
if (userId === '' || password === '') {
setError('User ID and password cannot be empty')
return
}

try {
const response = await login(userId, password)
if (response.success) {
setError(null)
setIsLoggedIn(true)
} else {
setError(response.message || 'Login failed')
}
} catch {
setError('Network error or server unavailable')
}
}

if (isLoggedIn) {
return <Join />
}

return (
<div className="flex flex-col justify-around bg-gray-800/80 p-6 my-4 rounded-lg">
<center className="flex flex-col items-center space-y-4">
<input
className="text-center text-lg border border-gray-300 rounded p-2"
placeholder="Enter User ID"
value={userId}
onChange={(e) => setUserId(e.target.value)}
/>

<input
type="password"
className="text-center text-lg border border-gray-300 rounded p-2"
placeholder="Enter Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>

{error && (
<p className="text-red-500 text-sm">
{error}
</p>
)}

<button
className="btn-primary"
onClick={handleLogin}
>
Sign In
</button>
</center>
</div>
)
}
import { useState } from 'react'
import { useAtom } from 'jotai'
import { userIdAtom, userPasswordAtom, isLoggedInAtom } from '../store/atom'
import Join from '../components/join'
import { login } from '../lib/api'

export default function Login() {
const [userId, setUserId] = useAtom(userIdAtom)
const [password, setPassword] = useAtom(userPasswordAtom)
const [isLoggedIn, setIsLoggedIn] = useAtom(isLoggedInAtom)
const [error, setError] = useState<string | null>(null)

const handleLogin = async () => {
if (userId === '' || password === '') {
setError('User ID and password cannot be empty')
return
}
try {
const response = await login(userId, password)
if (response.success) {
setError(null)
setIsLoggedIn(true)
} else {
setError(response.message || 'Login failed')
}
} catch {
setError('Network error or server unavailable')
}
}

if (isLoggedIn) {
return <Join />
}

return (
<div className="flex flex-col justify-around bg-gray-800/80 p-6 my-4 rounded-lg">
<center className="flex flex-col items-center space-y-4">
<input
className="text-center text-lg border border-gray-300 rounded p-2"
placeholder="Enter User ID"
value={userId}
onChange={(e) => setUserId(e.target.value)}
/>

<input
type="password"
className="text-center text-lg border border-gray-300 rounded p-2"
placeholder="Enter Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>

{error && (
<p className="text-red-500 text-sm">
{error}
</p>
)}

<button
className="btn-primary"
onClick={handleLogin}
>
Sign In
</button>
</center>
</div>
)
}
10 changes: 2 additions & 8 deletions webapp/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,19 +118,13 @@ async function delStream(roomId: string, streamId: string): Promise<any> {
}

async function login(username: string, password: string): Promise<{ success: boolean; message: string }> {
const response = await fetch('/login/', {
return (await fetch('/login/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
})

if (!response.ok) {
return { success: false, message: 'Login failed' }
}

return response.json()
})).json()
}

export {
Expand Down

0 comments on commit 079df30

Please sign in to comment.