Unable to login with Flask Login when deployed to Heroku using PostgreSQL - postgresql

I am building a simple authentication page that uses Flask and Flask SQLAlchemy deployed on Heroku with PostgreSQL.
I was able to register users but was unable to log in.
Code for Log in:
`
#indexbp.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
flash("You have already logged in!", 'success')
return redirect('/')
form = LoginForm()
if form.validate_on_submit():
try:
user = User.query.filter_by(username=form.username.data).first()
if bcrypt.check_password_hash(user.hashed_password, form.password.data):
login_user(user)
flash('You are logged in!', 'success')
return redirect('/')
except AttributeError:
db.session.rollback()
flash('Wrong username, password or email. Please try again!', 'info')
return redirect('/login')
except Exception as e:
print(e)
db.session.rollback()
flash('Something went wrong inside our systems, please try again later. If this problem persists, please contact our admin team.', 'danger')
return redirect('/login')
return render_template('login.html', form=form)
`
Code for Register:
`
#indexbp.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
flash("You have already logged in!", 'success')
return redirect('/')
form = RegisterForm()
if form.validate_on_submit():
try:
new_user = User(username=form.username.data, hashed_password=bcrypt.generate_password_hash(form.password.data), user_id=str(uuid.uuid1()))
db.session.add(new_user)
db.session.commit()
return redirect('/login')
except Exception as e:
print(str(e))
db.session.rollback()
flash('Something went wrong inside our systems, please try again later. If this problem persists, please contact our admin team.', 'danger')
return redirect('/register')
return render_template('register.html', form=form)
`
User table:
`
#User table
class User(db.Model, UserMixin):
id = db.Column(db.Integer(), primary_key=True, unique=True, nullable=False)
username = db.Column(db.String(), unique=True, nullable=False)
hashed_password = db.Column(db.String(), unique=False, nullable=False)
user_id = db.Column(db.String(), unique=True, nullable=False)
`
Flask Configs:
`
app.config['SQLALCHEMY_DATABASE_URI'] = "link-to-database-provided-by-heroku"
app.config['SECRET_KEY'] = "g3AbKqKhxhCACvFNlNgLv802LUBwXQKr4X4Z9J9d"
`
I have tried to migrate the database, rechecking it multiple times.
I have also attempted to run it locally but only registering works.
I installed psycopg2 as well as reconfiguring the User table.

Problem was Flask-Bcrypt not working properly. Changed my hashing function to md5 and it worked.

Related

How to secure Superset '/login/' endpoint

Recently I integrated superset with my web application so that when an user who is authenticated by my web application can enter superset and view/edit/create dashboards based on their role just by clicking the link no need to even login. For doing this I had to bypass the login for which I referred this article.
Custom SecurityManager I used to bypass login
class CustomAuthDBView(AuthDBView):
#expose('/login/', methods=['GET', 'POST'])
def login(self):
redirect_url = self.appbuilder.get_url_for_index
user_name = request.args.get('username')
user_role = request.args.get('role')
if user_name is not None:
user = self.appbuilder.sm.find_user(username=user_name)
if not user:
role = self.appbuilder.sm.find_role(user_role)
user = self.appbuilder.sm.add_user(user_name, user_name, 'last_name', user_name + "#domain.com", role, password = "password")
if user:
login_user(user, remember=False)
return redirect(redirect_url)
else:
print('Unable to auto login', 'warning')
return super(CustomAuthDBView,self).login()
class CustomSecurityManager(SupersetSecurityManager):
authdbview = CustomAuthDBView
def __init__(self, appbuilder):
super(CustomSecurityManager, self).__init__(appbuilder)
So according to above code using url http://localhost:8088/login?username=John will login the user John internally or if user John does not exist account is created with some role which is based on the role of user in my web application
Now the problem is anyone who can guess this url http://localhost:8088/login?username=USER_NAME can create their account in superset, so how to protect or secure this '/login' endpoint
You can use the API so that you dont expose request details over the URL.
from flask_appbuilder.api import BaseApi, expose
from . import appbuilder
class LoginApi(BaseApi):
resource_name = "login"
#expose('/loginapi/', methods=['GET','POST'])
##has_access
def loginapi(self):
if request.method == 'POST':
username = request.json['username']
password = request.json['password']
appbuilder.add_api(LoginApi)

SQL Database Operational Error - no such table : users

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: users
[SQL: SELECT users.id AS users_id, users.username AS users_username, users.password AS users_password
FROM users
WHERE users.username = ?]
the above is the error im getting.
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(24), unique=True, nullable=False)
password = db.Column(db.String(), nullable=False)
this is my User code.
#app.route('/', methods=['GET', 'POST'])
def index():
reg_form = Registeration()
if reg_form.validate_on_submit():
username = reg_form.username.data
password = reg_form.password.data
# for checking if someone has taken the username already
user_object = User.query.filter_by(username=username).all()
if user_object:
return "This username has been taken. Try another one.."
#registering in the database and commiting and etc
user = User(username=username, password=password)
db.session.add(user)
db.session.commit()
return 'Registered into the database!'
return db.create_all()
the application code.
I'm unable to figure out.. any help would be greatly appreciated. Btw im trying to make a registration system where the username and the pass get stored in Postgres Database.

how to store bcrypt hashpw result in db correctly?

I am in the process of creating a login system.
I use python flask and as database the Prostgresql.
I think I just store the hash value wrong.
I have saved it as vachar 255 so far
My code:
from flask import Flask, render_template, redirect, request, url_for, session
from flask_sqlalchemy import SQLAlchemy
import bcrypt
import psycopg2
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:PostGreSQL_13#localhost/test'
sql = SQLAlchemy(app)
#app.route('/')
def home():
return render_template("home.html")
#app.route('/register', methods=["GET","POST"])
def register():
if request.method == "GET":
return render_template("register.html")
else:
name = request.form['name']
email = request.form['email']
password = request.form['password'].encode('utf-8')
hash_password = bcrypt.hashpw(password, bcrypt.gensalt())
t_host = 'localhost'
t_port = "5432"
t_dbname = "test"
t_user = "postgres"
t_pw = "password"
db_conn = psycopg2.connect(host=t_host, port=t_port, dbname=t_dbname, user=t_user, password=t_pw)
db_cursor = db_conn.cursor()
db_cursor.execute("INSERT INTO users (UserName,UserEmail,UserPassword) VALUES (%s,%s,%s)",(name,email,hash_password,))
db_conn.commit()
session['name'] = name
session['email'] = email
return redirect(url_for("home"))
#app.route('/login', methods=["GET","POST"])
def login():
if request.method == "POST":
email = request.form['email']
password = request.form['password'].encode('utf-8')
t_host = 'localhost'
t_port = "5432"
t_dbname = "test"
t_user = "postgres"
t_pw = "password"
db_conn = psycopg2.connect(host=t_host, port=t_port, dbname=t_dbname, user=t_user, password=t_pw)
db_cursor = db_conn.cursor()
db_cursor.execute("SELECT username, useremail, userpassword FROM users WHERE useremail=%s",(email,))
user = db_cursor.fetchone()
db_conn.close()
if len(user) > 0:
name = user[0]
if bcrypt.hashpw(password, user[2].encode('utf-8')) == user[2].encode('utf-8'):
session['name'] = user[0]
session['email'] = user[1]
return render_template("home.html")
else:
return "Versuch es doch Nochmal"
else:
return render_template("login.html")
#app.route('/logout')
def logout():
session.clear()
return render_template("home.html")
if __name__ == '__main__':
app.secret_key = '012#!ApaAjaBoleh)(*^%'
app.run(debug=True)
the procedure I got from the Youtube video. see attachment.
I need a login system and this was recommended to me, it works pretty good.
The last one has to work somehow and if it works I would be very happy.
Can anyone tell me what I'm doing wrong or if my appendix with the database is right or wrong?
I know nothing about this language you're using, but any bcrypt implementation will output a string similar to:
$2a$12$ieXy2Rj/TEGqVRx0JihGFesujNFCdmlQWpUaTNvwQ0XuB3lzOcTWK
Yes, you should store that varchar string in your database.

Storage of DriveAPI credentials using oauth2client.django_orm.Storage-class

I want to save the client credentials obtained from Drive API. I tried the following code below, it's working well to store credentials but when I'm accessing the data in upload view it's not returning the credential
views.py
from oauth2client.django_orm import Storage
from drv_app.models import CredentialsModel
#authorization of the client by the user
def authorize_application(request):
#setting flow to get permission and code
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI, ACCESS_TYPE)
authorize_url = flow.step1_get_authorize_url()
code = request.GET.get('code', '')
if code:
#setting flow step2 to exchage code for access token
credential = flow.step2_exchange(code)
#initialising httplib2 instance and building a DriveAPI service
http = httplib2.Http()
http = credential.authorize(http)
drive_service = build('drive', 'v2', http=http)
user, created = User.objects.get_or_create(username=username, email=email)
#saving credentials to database
if created == True:
storage = Storage(CredentialsModel, 'id', user, 'credential')
storage.put(credential)
return HttpResponseRedirect('/upload/')
else:
return HttpResponseRedirect('/upload/')
else:
return HttpResponseRedirect(authorize_url)
def upload_file(request):
username = request.session['username']
user = User.objects.get(username=username)
storage = Storage(CredentialsModel, 'id', user, 'credential')
credential = storage.get()
http = httplib2.Http()
http = credentials.authorize(http)
drive_service = build('drive', 'v2', http=http)
media_body = MediaFileUpload(FILENAME, mimetype='text/plain', resumable=True)
body = {
'title': 'vishnu_test',
'description': 'A test document',
'mimeType': 'text/plain'
}
file = drive_service.files().insert(body=body, media_body=media_body).execute()
pprint.pprint(file)
return HttpResponse('uploaded')
models.py
from oauth2client.django_orm import FlowField
from oauth2client.django_orm import CredentialsField
class CredentialsModel(models.Model):
id = models.ForeignKey(User, primary_key=True)
credential = CredentialsField()
What I'm doing wrong? Please suggest the necessary improvements.
Replace ForeignKey with OneToOneField in CredentialsModel

About interacting and testing with django tastypie

I read many tutorial about django testing but I don't know how can I test for function insde resource , for example this User resource with signin function and obj_create. I really appreciate any helps because I can not figure out how to test them. k thanks.
class UserResource(ModelResource):
school = fields.ToOneField('frittie.app.api.api.LocationResource', 'user')
class Meta:
queryset = UserProfile.objects.all()
resource_name = 'User'
allowed_methods = ['get','post']
serializer = Serializer(formats=['json', 'plist'])
authorization= Authorization()
#models.signals.post_save.connect(create_api_key, sender=User)
#fields = ['username', 'email']
def obj_create(self, bundle, request=None, **kwargs):
if not request.method == "POST":
raise BadRequest('Object not found or not allowed to create a new one.')
username, email, password = bundle.data['username'], bundle.data['password'], bundle.data['password'],
try:
bundle.obj = User.objects.create_user(username, email, password)
except IntegrityError:
raise BadRequest('That username already exists')
return bundle
def signin(self, request, **kwargs):
self.method_check(request, allowed=['post'])
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return self.create_response(request, {'success': True})
else:
# Return a 'disabled account' error message
return self.create_response(request, {'success': False})
else:
# Return an 'invalid login' error message.
return self.create_response(request, {'success': False})
Tastypie has a descent testing documentation - ResourceTestCase API Reference