My “register” function in pset9 is not working - cs50

What mistake am I doing in the code below for pset9 "register" function:
#app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
if request.method == "GET":
return render_template("register.html")
elif request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username", 400)
# Ensure password was submitted
elif not request.form.get("password"):
return apology("must provide password", 400)
# Ensure password confirmation was submitted
elif not request.form.get("password-confirmation"):
return apology("must provide password confirmation", 400)
# Check if the password confirmation field matches the password field
elif request.form.get("password-confirmation") != request.form.get("password"):
return apology("Your passwords didn't match", 400)
# Insert username and password into the database AND Hash user's password
insert = db.execute("INSERT INTO users (username,hash) VALUES(?,?)" , request.form.get("username"), generate_password_hash(request.form.get("password"))
# Query database for that username
row = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username"))
# Database
database = db.exexcute("SELECT * FROM users")
# Ensure username is not already in the database
if row in database:
return apology("username already exists", 400)
# Remember which user has logged in
session["user_id"] = insert
# Redirect user to home page
return redirect("/")
ts giving me the below error:
row = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username")) ^ SyntaxError: invalid syntax

Related

Getting None instead of string

I have a Streamlit application that lets the user login (by checking with SQLite databse) and then do some action. My problem is that I'm trying to print a welcome message with the user's username but I'm getting 'None' instead.
This is my Login function:
def show_login_page():
with loginSection:
if st.session_state['loggedIn'] == False:
username = st.text_input (label="Username", value="", placeholder="Enter your username")
password = st.text_input (label="Password", value="", placeholder="Enter password", type="password")
hashed_password = make_hash(password)
st.button("Login", on_click=LoggedIn_Clicked, args= (username, hashed_password))
return username
Then after clicking the login button, user's information will be checked with the database
def LoggedIn_Clicked(username, password):
# check with database
if login_user(username, password):
st.session_state['loggedIn'] = True
else:
st.session_state['loggedIn'] = False
st.error("Invalid username or password")
After sucessfully logging in, the session_state will change and the user will login to the main page
with headerSection:
st.title("Streamlit Application")
#first run will have nothing in session_state
if 'loggedIn' not in st.session_state:
st.session_state['loggedIn'] = False
show_login_page()
else:
if st.session_state['loggedIn']:
show_logout_button()
# getting the username from login page
# Problem is here
usr = show_login_page()
show_main_page(usr)
else:
show_login_page()
This is the main page function:
def show_main_page(username):
with mainSection:
st.header(f"Hello {username}")
# Do some action
processingClicked = st.button("Start Processing", key="processing")
if processingClicked:
st.balloons()
I've tried many ways was to get the username variable from the login_page to the main_page function to no avail. Help would be appreciated.

Django - How to Manually update/set/Reset password

I tried to reset password manually by passing key But it always says
AttributeError : 'str' object has no attribute 'get'
I googled many times even if i saw Manual Password with hiding password field Django but no luck favor me.
// In my form #forms.py
class UserResetPasswordForm(forms.Form):
new_password1 = forms.CharField(
label=_("New Password"),
widget=forms.PasswordInput(attrs={"autocomplete":"off"}),
strip=False,
help_text=password_validation.password_validators_help_text_html(),
)
new_password2 = forms.CharField(
label=_("New Password Confirmation"),
strip=False,
widget=forms.PasswordInput(attrs={"autocomplete":"off"}),
)
In Url
path('password-reset/confirm/<str:reg_key>/', accounts_view.myreset_password_confirm, name='myreset_password_confirm'),
In View #views.py
def myreset_password_confirm(request, reg_key):
user = User.objects.filter(activate_key=reg_key).first()
if user is not None:
if request.method == 'POST':
form = UserResetPasswordForm(request.POST)
if form.is_valid():
#password1 = form.cleaned_data.get('new_password1')
#password2 = form.cleaned_data.get('new_password2')
password1 = request.POST['new_password1']
password2 = request.POST['new_password2']
if password1 and password2:
if password1 != password2:
raise ValidationError("Your password didn't match.")
password_validation.password_validators_help_text_html()
return password2
print(password2)
user.activate_key = ''
user.set_password(password2)
user.save()
print("Print User")
print(type(user))
messages.success(request, f"Your password for {user.email} has been reset successfully!")
return HttpResponseRedirect('/')
else:
form = UserResetPasswordForm()
return render(request, 'reset_password_confirm.html', {'form':form})
else:
print("U R Boomed")
messages.error(request, "Your requested URL is not Valid, Please try with valid URL.")
return HttpResponseRedirect('/')
Please help, how to solve it?
You are returning return password2, which is not proper HttpResonse. I don't think you wanted to do that. Just delete this line.

How to rewrite django admin login view?

This is my custom login view where user can only login if their email verified. I also added two step verification in my login view. is there any way where I can implement this view in django admin login ?
def login_view(request):
username = None
password = None
two_factor = None
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
otp = request.POST.get('auth_code')
user = authenticate(request, username=username, password=password)
User = get_user_model()
if user is not None and user.is_active:
user_mail = user.userprofile.filter(
user=user, email_confirmed=True)
two_factor = user.userprofile.filter(
user=user, two_factor=True)
for i in two_factor:
....my two factor code
if user_mail and two_factor:
if secret_code == otp:
login(request, user)

validating user input using flask_wtf and sqlalchemy

Noob question. I am building a login/registration pages, on the registration page, I am using flask_wtf to verify certain things like length of password, email format and whether the two password a user supplies match. Here is the flask_wtf code I am using to do that.
# import statements omitted for brevity
class RegistrationForm(FlaskForm):
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email',validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password',
validators=[DataRequired(),Length(min=4, max=20), EqualTo('password')])
submit = SubmitField('Sign Up')
After checking the input, I am using sqlalchemy to check if the username and email already exists in my DB. The problem I am facing right now is I cant get flask_wtf to verify the form. I can type whatever I want and it will be converted to a sql query. Here are my two flask routes that handle registration and user input validation.
#app.route('/register',methods=['GET','POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
return redirect(url_for('check_user_input'))
return render_template('register.html',form=form)
#app.route('/status',methods=['POST'])
def check_user_input():
name = request.form.get("username")
email = request.form.get("email")
password = request.form.get("password")
if db.execute("SELECT * FROM DB WHERE username= :username",{"username":name}).rowcount==1:
return render_template("404.html", message="Sorry username already exists")
elif db.execute("SELECT * FROM DB WHERE email= :email",
{"email":email}).rowcount==1:
return render_template("404.html", message="Sorry email already exists")
else:
db.execute("INSERT INTO DB (username,email,password) VALUES
(:username,:email,:password)",
{"username":name, "email":email,"password":password})
db.commit()
return render_template("success.html")
How can I get flask_wtf form to do its verification first and then hand the input to check_user_input() function?
My register.html contains the following line.
<form class="form-signin" method="POST" action="{{url_for('check_user_input')}}">
Any help would be greatly appreciated.
A way is to add a custom validation to the form :
class RegistrationForm(FlaskForm):
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email',validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password',
validators=[DataRequired(),Length(min=4, max=20), EqualTo('password')])
submit = SubmitField('Sign Up')
def validate(self):
rv = FlaskForm.validate(self)
if not rv:
return False
if db.execute("SELECT * FROM DB WHERE username= :username",{"username":self.username.data}).rowcount>0:
self.username.errors.append('Sorry username already exists')
return False
if db.execute("SELECT * FROM DB WHERE email= :email", {"email":self.email.data}).rowcount>0:
self.email.errors.append('Sorry email already exists')
return False
return True

how to find the username of a user from database when email is given in django

i am creating a website where a banks loggs in with its username which is a code but i wanted that bank could log in with its first_name.
i am using default user model for registration.
but authenticate() function works only with username so what i wanted to do is that bank fill their name and function finds the value of username with corrosponding name in the database and then use authenticate() function to log the bank in.
my login function in view.py
def login(request):
if request.method == 'POST':
name = request.POST.get('first_name')
password = request.POST.get('password')
username = ????????
user = authenticate(username=username, password=password)
if user:
if user.is_active and has_role(user,Banker):
auth_login(request,user)
return HttpResponseRedirect(reverse('business:dashboard'))
else:
messages.error(request,"Your account is not active")
return render(request,'accounts/bank_login.html')
else:
messages.error(request,"Invalid Username or Password")
return render(request,'accounts/bank_login.html')
else:
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('business:dashboard'))
else:
return render(request,'accounts/bank_login.html')
so please anybody could tell what should i write in that username to get the value of username from database
**my models.py **
from django.db import models
from django.contrib import auth
# Create your models here.
class User(auth.models.User,auth.models.PermissionsMixin):
def __str__(self):
return self.user.username
This is slightly more complex than doing a simple query. Also, you cannot rule our that two users with the same first name will choose the same password. Here the first user found is taken
Something like this:
from django.contrib.auth.hashers import check_password
firstnameusers = User.objects.filter(first_name=name)
for usr in firstnameusers:
if check_password(password, usr.password):
username = usr.username
break
Note that you will need to write some code to handle the case where a user is not found.
I used this in my views.py file and it works perfectly
def login(request):
if request.method == 'POST':
name = (request.POST.get('name')).upper()
username = (get_user_model().objects.all().filter(first_name = name)).values("username")[0]["username"]
password = request.POST.get('password')
user = authenticate(username=username, password=password)

Resources