Chatgpt

ใช้ SQLite เพื่อเก็บ storing user credentials securely
และ RESTful APIs for – registration and login.

  1. Install Dependencies
    Make sure you have Flask and SQLite installed:
pip install Flask Flask-SQLAlchemy Flask-Cors

2. Create the Flask Backend
Folder Structure

backend/
│-- app.py
└-- users.db  (SQLite database will be created automatically)

app.py

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes to allow communication from Android

# Database configuration
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

# User model
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(150), unique=True, nullable=False)
    password = db.Column(db.String(256), nullable=False)

# Initialize the database
with app.app_context():
    db.create_all()

# Route for user registration
@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({'message': 'Please provide both username and password'}), 400

    hashed_password = generate_password_hash(password)

    if User.query.filter_by(username=username).first():
        return jsonify({'message': 'Username already exists'}), 400

    new_user = User(username=username, password=hashed_password)
    db.session.add(new_user)
    db.session.commit()

    return jsonify({'message': 'User registered successfully'}), 201

# Route for user login
@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({'message': 'Please provide both username and password'}), 400

    user = User.query.filter_by(username=username).first()

    if user and check_password_hash(user.password, password):
        return jsonify({'message': 'Login successful'}), 200
    else:
        return jsonify({'message': 'Invalid credentials'}), 401

# Run the server
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

3. Run the Backend
In the terminal, navigate to the backend folder and run:

python app.py

The server will start at http://:5000.


4. Connect Android App to Flask Backend
Android Register and Login Code
ใช้ Retrofit library to make HTTP requests to the Flask backend.

Add Dependencies to build.gradle (Module: app):

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.google.code.gson:gson:2.8.6'
}