title: Flask error 500 Internal Server Error. Firebase-authentication with email/password
body: <p><strong>I am trying to implement firebase authentication with email and password on my flask app. I am getting this error when I try to login or register.
  Any help would be appreciated.</strong></p>
  <p>I am very new to coding so please ELI5 if possible. Any pointers on how to improve anything else on my code would be appreciated.</p>
  <hr />
  <pre><code>127.0.0.1 - - [18/Jul/2021 21:02:09] &quot;GET /login HTTP/1.1&quot; 500 -
  Traceback (most recent call last):
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/flask/app.py&quot;, line 2464, in __call__
  return self.wsgi_app(environ, start_response)
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/flask_socketio/__init__.py&quot;, line 46, in __call__
  start_response)
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/engineio/middleware.py&quot;, line 74, in __call__
  return self.wsgi_app(environ, start_response)
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/flask/app.py&quot;, line 2450, in wsgi_app
  response = self.handle_exception(e)
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/flask/app.py&quot;, line 1867, in handle_exception
  reraise(exc_type, exc_value, tb)
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/flask/_compat.py&quot;, line 39, in reraise
  raise value
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/flask/app.py&quot;, line 2447, in wsgi_app
  response = self.full_dispatch_request()
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/flask/app.py&quot;, line 1952, in full_dispatch_request
  rv = self.handle_user_exception(e)
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/flask/app.py&quot;, line 1821, in handle_user_exception
  reraise(exc_type, exc_value, tb)
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/flask/_compat.py&quot;, line 39, in reraise
  raise value
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/flask/app.py&quot;, line 1950, in full_dispatch_request
  rv = self.dispatch_request()
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/flask/app.py&quot;, line 1936, in dispatch_request
  return self.view_functions[rule.endpoint](**req.view_args)
  File &quot;/Users/realp/Desktop/firebaseflask-main/factory/users/views.py&quot;, line 63, in login
  if session['user']:
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/werkzeug/local.py&quot;, line 377, in &lt;lambda&gt;
  __getitem__ = lambda x, i: x._get_current_object()[i]
  File &quot;/Users/realp/Desktop/firebaseflask-main/env/lib/python3.7/site-packages/flask/sessions.py&quot;, line 84, in __getitem__
  return super(SecureCookieSession, self).__getitem__(key)
  KeyError: 'user'
  </code></pre>
  <hr />
  <pre><code>from flask import render_template, Blueprint, redirect, request, abort, session, jsonify, make_response
  from factory import db, auth, database
  import random
  from factory.models import Users, Cards, Subscription
  from flask_login import login_user, current_user, logout_user, login_required
  from werkzeug.security import generate_password_hash, check_password_hash
  from datetime import date, datetime
  from cardvalidator import luhn
  import stripe
  import json
  users = Blueprint('users', __name__)
  u/users.route('/register')
  def register():
  if session['users']:
  return redirect('/dashboard')
  else:
  rand = random.randint(0,100000000)
  return render_template('register.html', random=rand)
  
  u/users.route('/insert-user', methods=['POST'])
  def reg_user():
  if request.method == 'POST':
  first_name = str(request.form['first_name'])
  last_name = str(request.form['last_name'])
  phone_number = str(request.form['phone_number'])
  email = str(request.form['email'])
  password = str(request.form['password'])
  user = auth.create_user_with_email_and_password(email, password)
  
  data = {
  &quot;first_name&quot;: first_name,
  &quot;last_name&quot;: last_name,
  &quot;phone_number&quot;: phone_number,
  &quot;free_trial&quot;: 1,
  &quot;email&quot;: email
  }
  push_user = database.child(&quot;users&quot;).push(data, user['idToken'])
  user_data = auth.get_account_info(user['idToken'])
  data_user = {
  &quot;email&quot;: user_data['users'][0]['email'],
  &quot;data&quot;: data
  }
  
  session['user'] = data_user
  return 'success'
  
  u/users.route('/login')
  def login():
  if session['user']:
  return redirect('/dashboard')
  else:
  rand = random.randint(0,100000000)
  return render_template('login.html', random=rand)
  u/users.route('/login-user', methods=['POST'])
  def login_user_function():
  data_user = {}
  if request.method == 'POST':
  email = str(request.form['email'])
  password = str(request.form['password'])
  login = auth.sign_in_with_email_and_password(email, password)
  # user = auth.refresh(login['refreshToken'])
  user_data = database.child(&quot;users&quot;).get(login['idToken'])
  for user in user_data.each():
  if user.val()['email'] == email:
  data_user = {
  &quot;email&quot;: email,
  &quot;data&quot;: user.val()
  }
  session['user'] = data_user
  return 'success'
  
  u/users.route('/logout')
  def logout():
  session['user'] = {}
  return redirect('/login')
  
  # Add new card
  u/users.route('/add_card', methods=['POST'])
  def new_card():
  
  if request.method == 'POST':
  user_id = int(request.form['user_id'])
  card_number = str(request.form['card_number'])
  expiry = str(request.form['expiry'])
  cvc = int(request.form['cvc'])
  card_type = str(request.form['card_type'])
  card_zip = str(request.form['card_zip'])
  check_card = Cards.query.filter_by(card_number=card_number).first()
  if check_card is None:
  # Insert card
  insert_card = Cards(card_number=card_number, expiry=expiry, cvc=cvc, user_id=user_id, card_type=card_type, card_zip=card_zip)
  db.session.add(insert_card)
  db.session.commit()
  return 'success'
  
  else:
  return 'existed'
  u/users.route('/validate-card', methods=['POST'])
  def card_valid():
  if request.method == 'POST':
  card_number = int(request.form['card_number'])
  if luhn.is_valid(card_number):
  return 'valid'
  else:
  return 'fake'
  
  u/users.route('/new-subscription', methods=['POST'])
  u/login_required
  def new_subscription():
  
  if request.method == 'POST':
  card_id = int(request.form['card_id'])
  selection = int(request.form['selection'])
  email = current_user.email
  
  # # Stripe key
  api_key_test = 'sk_test_xxxxx'
  public_key_test = 'pk_test_xxxxx'
  stripe.api_key = api_key_test
  token = stripe.Token.create(
  card={
  &quot;number&quot;: get_card_data.card_number,
  &quot;exp_month&quot;: int(month),
  &quot;exp_year&quot;: int(year),
  &quot;cvc&quot;: get_card_data.cvc,
  'address_zip': get_card_data.card_zip
  },
  )
  # return token
  customer = stripe.Customer.create(email=email, source=token)
  customer_id = customer.id
  # # PAYMENT INFORMATION
  charge = stripe.Charge.create(
  customer = customer_id,
  amount = amount,
  currency = 'usd',
  description = 'Subscription'
  )
  # Add Subscription
  new_subscription = Subscription(
  card_id=card_id,
  period=selection,
  price=(amount/100),
  last_payment=datetime.today().strftime('%Y-%m-%d-%H:%M:%S'),
  user_id=current_user.id)
  db.session.add(new_subscription)
  db.session.commit()
  return 'success'
  </code></pre>