Help on user id and just coding

I have made a small flask app, but I need to debug it and I also think the user id isn’t working. Can you tell me your username and i’ll invite you, but i’ll have to check you just to make sure you don’t steal important api keys or secrets

Hey!
@AndrewDeng3 I’d love to help you resolve any issues. My Replit username is RedCoder.

You should put those in your Secrets, and if you do that you could share your code here instead of inviting to your Repl.

3 Likes

Bro is ur last name Fang, cuz someone at my school is named Austin Fang

:open_mouth:

Nope, definitely not Fang, though cool last name :slight_smile:


Anyways, can you share your code here?

yea sure (I used AI cuz im new to flask btw)

from flask import Flask, request, render_template, jsonify, send_from_directory, redirect, session
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
import os
import random
import stripe

# Initialize Flask app with the current directory for static and template files
app = Flask(__name__, static_url_path='', static_folder='.', template_folder='.')

# ... rest of your code ...

# Replace 'postgres://' with 'postgresql://' in the DATABASE_URL
uri = os.environ['DATABASE_URL']
if uri.startswith("postgres://"):
    uri = uri.replace("postgres://", "postgresql://", 1)
uri += "?sslmode=prefer"
app.config['SQLALCHEMY_DATABASE_URI'] = uri

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
secret_key = os.urandom(24)
print(secret_key)
app.config['SECRET_KEY'] = secret_key
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)

@app.route('/')
def home():
  return send_from_directory(app.static_folder, 'login.html')

# Add the is_subscribed column to the User model in your main.py
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False) #<- nullable is false yet Username is None
    password = db.Column(db.String(120), nullable=False) # <- nullable is false yet Password is None
    is_subscribed = db.Column(db.Boolean, default=False, nullable=False)
    def __init__(self, id, username, password, is_subscribed):
        self.id = id
        self.username = username
        self.password = password
        self.is_subscribed = is_subscribed
    def toggle_subscription(self):
        self.is_subscribed = not self.is_subscribed
    def toggle_id(self):
      self.is_subscribed = not self.is_subscribed
  # New column for subscription status


stripe.api_key = os.environ.get('S_KEY')
@app.route('/buy', methods=['POST'])
def buy():
        global username
        username = request.form['username']
        user = User.query.filter_by(username=username).first()
        if not user.is_subscribed:
            # Amount in cents
            amount = 500
            try:
                # Create a charge: this will charge the user's card
                charge = stripe.Charge.create(
                    amount=amount,
                    currency='usd',
                    description='Subscription charge',
                    source=request.form['stripeToken']
                )
                # If the charge is successful, update user's subscription status
                user.is_subscribed = True
                db.session.commit()

                return render_template('embed.html')  # or any other success page
            except stripe.error.StripeError as e:
                # Handle the exception
                return str(e), 400


@app.route('/publishable-key')
def get_publishable_key():
    return jsonify(publishable_key=os.environ.get('P_KEY'))

go = False
@app.route('/embed')
def embed():
    global go
    if not go:
      return redirect('/login')
    return send_from_directory(app.static_folder, 'embed.html')
@app.route('/index')
def index():
    global go
    if not go:
      return redirect('/login')
    return send_from_directory(app.static_folder, 'index.html')

username = ''
password = ''

@app.route('/login', methods=['GET', 'POST'])
def login():
    global go, usernmae, password
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()
        if user and bcrypt.check_password_hash(user.password, password):
            session['id'] = user.id
            print(user.id)
            go = True
            # Redirect subscribed users to embed.html
            if user.is_subscribed:
                return redirect('/embed')
            else:
                return redirect('/index')
        else:
            return 'Invalid username or password'
    return render_template('login.html')



@app.route('/purchase')
def purchase():
        global username
        username = request.form['username']
        user = User.query.filter_by(username=username).first()
        if user.is_subscribed:
            return render_template('embed.html')
        else:
            return send_from_directory(app.static_folder, 'index.html')

# main.py
# Add the signup route to your Flask app in main.p

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        # Ensure the username does not exist already
        existing_user = User.query.filter_by(username=username).first()
        if existing_user is None:
            hashed_pw = bcrypt.generate_password_hash(password).decode('utf-8')
            # Set is_subscribed to False by default when a new user signs up
            new_user = User(id = random.randint(10000000, 99999999),username=username, password=hashed_pw, is_subscribed=True) # W H A T  D O E S  T H I S  D O ? ? ? ? ? ? ? ? ? 
            db.session.add(new_user)
            db.session.commit()
            return redirect('/login')
        else:
            return 'Username already exists'
    return render_template('signup.html')


@app.route('/get-spock-link')
def get_spock_link():
  return os.environ.get('SPOCK_LINK', '')

if __name__ == '__main__':
  with app.app_context():  # Activates the application context
    db.drop_all()
    db.create_all()  # Create database tables
  app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))
2 Likes

Do you get any errors? What exactly isn’t working for you?

so /login doesn’t work because ever time i try and get session[‘user_id’], it returns None

What is user.id value? It is possible that that is set to None, resulting in your login not working.

1 Like

u can analyze the code :stuck_out_tongue:

session['id'] = user.id

yea its defined in login

Which one are you trying to read?

2 Likes

ooooo
i think i get it now
ty

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.