FastAPI 學習之路(四十七)WebSockets(三)登錄後纔可以聊天

 之前我們是通過前端自動生成的,這次我們通過註冊登錄,保存到本地去實現。我們可以應該如何實現呢,首先我們實現一個登錄界面。放在templates文件下。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<div>
    <p><input id="username" placeholder="用戶名"></p>
    <p><input id="password" placeholder="密碼" type="password"></p>
    <button id="login">登錄</button>
</div>
<script>
    $('#login').click(function () {
        $.ajax({
            type: "post",
            url: "/token",
             contentType: "application/json; charset=utf-8",
            data: JSON.stringify({
                email: $("#username").val(),
                password: $("#password").val()
            }),
            success: function (data) {
                if (data['msg'] == "pass") {
                    window.localStorage.setItem("token", data['token'])
                    window.location.href="/"
                }else {
                    alert(data['msg'])
                }
            }
        })

    })
</script>
</body>
</html>

我們在後端去編寫一個返回靜態文件的頁面,一個返回token的方法、

@app.get("/login")
async def login(request: Request):
    return templates.TemplateResponse(
        "login.html",
        {
            "request": request
        }
    )
@app.post('/token')
def token(user: UserCreate, db: Session = Depends(get_db)):
    db_crest = get_user_emai(db, user.email)
    fake_hashed_password = user.password + "notreallyhashed"
    if db_crest:
        if fake_hashed_password==db_crest.hashed_password:
            return {"token":"leizishuoceshi",'msg':'pass'}
    return {'msg':'fail'}

然後我們可以去啓動下,當我們啓動完成登錄後發現本地存了token,那麼這個時候我們需要改造下webchat.html,我們的取本地的 token,同時也實現了一個退出的功能。

<!DOCTYPE html>
<html>
<head>
    <title>Chat</title>
</head>
<body>
<h1>WebSocket 聊天</h1>
<form action="" onsubmit="sendMessage(event)">
    <input type="text" id="messageText" autocomplete="off"/>
    <button>Send</button>
</form>
<button onclick="logout()">退出</button>
<ul id='messages'>
</ul>
<script>
    var  token=window.localStorage.getItem("token")
    if (token==null ){
        window.location.href="/login"
    }
    var ws = new WebSocket("ws://localhost:8000/items/ws?token="+token);

    ws.onmessage = function (event) {

        var messages = document.getElementById('messages')

        var message = document.createElement('li')

        var content = document.createTextNode(event.data)

        message.appendChild(content)

        messages.appendChild(message)

    };

    function sendMessage(event) {

        var input = document.getElementById("messageText")

        ws.send(input.value)

        input.value = ''

        event.preventDefault()

    }
    function logout() {
        window.localStorage.removeItem("token")
        window.location.href='/login'
    }
</script>

</body>

</html>

  這樣我們就可以登錄後,然後去獲取登錄產生的token,然後和後端發發送消息,這樣我們完成了一個登錄聊天,退出後無法聊天的功能。我們如果直接訪問聊天的頁面,也是可以直接去定向到我們的登錄的界面呢,我們的聊天是依賴於我們的登錄的。

 

 

 

 成功後纔可以發送聊天內容

 

 點擊退出,直接退出

 

 本地存儲也無任何

 

 

文章首發在公衆號,歡迎關注。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章