Skip to content

Instantly share code, notes, and snippets.

@The-XSS-Rat
Created April 2, 2024 20:52
Show Gist options
  • Save The-XSS-Rat/a30dc483ed34a9e5a7677b7c898a1593 to your computer and use it in GitHub Desktop.
Save The-XSS-Rat/a30dc483ed34a9e5a7677b7c898a1593 to your computer and use it in GitHub Desktop.
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from werkzeug.security import generate_password_hash, check_password_hash
import os
# Flask application setup
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://<username>:<password>@localhost/humanRatsources'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['JWT_SECRET_KEY'] = 'super-secret' # Change this to a random secret key in production
# Initialize extensions
db = SQLAlchemy(app)
jwt = JWTManager(app)
# Database models
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), nullable=False)
email = db.Column(db.String(100), nullable=False)
password = db.Column(db.String(255), nullable=False)
created_at = db.Column(db.TIMESTAMP, server_default=db.func.current_timestamp())
class Account(db.Model):
__tablename__ = 'accounts'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
name = db.Column(db.String(100), nullable=False)
company_address = db.Column(db.String(255))
vat_number = db.Column(db.String(20))
user = db.relationship('User', backref=db.backref('accounts', lazy=True))
# API Endpoints
@app.route('/register', methods=['POST'])
def register():
data = request.get_json()
hashed_password = generate_password_hash(data['password'], method='sha256')
new_user = User(username=data['username'], email=data['email'], password=hashed_password)
db.session.add(new_user)
db.session.commit() # Commit to get the new user's ID
new_account = Account(user_id=new_user.id, name=data['company_name'], company_address=data['address'], vat_number=data['vat_number'])
db.session.add(new_account)
db.session.commit()
return jsonify({'message': 'Registered successfully!'}), 201
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
user = User.query.filter_by(username=data['username']).first()
if user and check_password_hash(user.password, data['password']):
access_token = create_access_token(identity=data['username'])
return jsonify({'access_token': access_token}), 200
return jsonify({'message': 'Invalid username or password'}), 401
# Run the Flask app
if __name__ == '__main__':
db.create_all() # Create tables if they don't exist yet
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment