0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HTMLでアカウント登録、ログイン機能を作ってみた

Posted at

Renderで無料データベースを作成し、アカウント管理ができるようになりました。

主にこちらのサイトを参考にさせていただきました。
https://note.com/watanabe_kf1983/n/n9e4597ae223e
https://qiita.com/plumfield56/items/ebe5f6f5b1c884b07c99

オンラインゲームが作りたかったので、ユーザー名、パスワード、アバター、自己紹介文、勝利数、敗北数、引き分け数を保存できるようにしました。
最初に、ターミナルでテーブルを作成しました。それぞれ初期値を設定してあります。

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    avatar VARCHAR(255) DEFAULT '(´・ω・`)',
    bio TEXT DEFAULT '',
    wins INTEGER DEFAULT 0,
    losses INTEGER DEFAULT 0,
    draws INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

usernameは重複しないようにUNIQUEを使ておきます。
なぜusernameとpasswordがTEXTじゃないかは後ほど...。

htmlから、このテーブルに接触できるようにします。バックエンドにはpythonを用いました。

バックエンド側では、ルーティングプログラムroute.pyを編集。
アカウント登録用のサイトregister.htmlに紐づけたプログラム↓

@main.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        
        conn = get_db_connection()
        cur = conn.cursor()
        
        #同名ユーザーの存在確認
        cur.execute("SELECT * FROM users WHERE username = %s;", (username,))
        existing_user = cur.fetchone()
        
        if existing_user:
            flash("このユーザー名はすでに使われています。")
        else:
            hashed_password = generate_password_hash(password)
            
            cur.execute("INSERT INTO users (username, password) VALUES (%s, %s);", (username, hashed_password))
            conn.commit()
            flash("登録が完了しました")
            cur.close()
            conn.close()
            return redirect(url_for("main.login"))

        cur.close()
        conn.close()

    return render_template("register.html")

usernameが存在するか確認します。(fetchone関数にて結果が返される。)

安全性を保つため、generate_password_hash関数を使って、パスワードをハッシュ化しています。INSERTコマンドから、ハッシュ化されたパスワードをusersテーブルに挿入しました。

ログイン確認

@main.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]

        conn = get_db_connection()
        cur = conn.cursor()
        cur.execute("SELECT * FROM users WHERE username = %s;", (username,))
        user = cur.fetchone()
        cur.close()
        conn.close()
        if user:
            stored_hash = user[2]
            if check_password_hash(stored_hash, password):
                flash(f"ようこそ、{username}さん!")
                session["username"] = username
                return redirect(url_for("main.account"))
            else:
                flash("パスワードが違います。")
        else:
            flash("ユーザー名が存在しません。")
        
    return render_template("login.html")

ユーザー名検索➡入力パスワードの確認という流れで実装しました。check_password_hash関数を使えば、ハッシュ化されたパスワードと、入力パスワードの比較ができるらしい。werkzeug.securityは、素晴らしいライブラリです。

確認
ターミナル上でデータベースに接続して確認してみました。

image.png

アカウント登録したアカウント一覧が表示されます。パスワードはハッシュ化されており、直接確認することはできません。
当然、ログインすることもできます。

拙い文章ですいません。ではまた!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?