This is the first time t work with flask and pymongo. Anyone can tell my why and how to fix this problem ?
I had watched this video: https://www.youtube.com/watch?v=7Abxa0q4Vuk and use his code. However, it isn't work when i try to login.
It is a picture I captured when I tried to log in with an account had already register
This is the login_check code:
if(request.method == 'POST'):
req = request.form
req = dict(req)
print(req)
query = user_table.find({'uid', req['uid']})
flag = 0
temp = None
for x in query:
if(x['uid'] == req['uid']):
flag = 1
temp = x
break
if(flag == 1):
if(temp['password'] == req['password']):
return render_template('dashboard.html', uid = req['uid'])
else:
return render_template('invalid.html', message = 'incorrect password')
else:
return render_template('invalid.html', message = "User not registered")
return render_template('login.html')
This is the error:
filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping
Related
I have a Flask Webserver running with a site where you can create a user in my Windows Active-Directory. If I run the script as a separate file and set the variables manually it works as it should. But when I try to use input from the website in my script in my Flask program it does not work. I get the following error code: pywintypes.com_error: (-2147352567, 'Exception error occurred.', (0, None, None, 0, -2147221020), None). I am wondering that outside of the Flask script, it works. When I replace all varibles with strings it doesn't work either. So it seems to me that my function has a problem with Flask.
My Python code is the following:
from flask import Flask, redirect, url_for, render_template, request
from pyad import *
app = Flask(__name__)
def replaceUmlauts(string):
string = string.replace('ü', 'u')
string = string.replace('ö', 'o')
string = string.replace('ä', 'a')
string = string.replace('Ü', 'U')
string = string.replace('Ö', 'O')
string = string.replace('Ä', 'A')
return string
def createUser(firstname,lastname):
initials = replaceUmlauts(firstname)[0:1] + replaceUmlauts(lastname)[0:1]
loginName = replaceUmlauts(lastname)[0:4].lower() + replaceUmlauts(firstname)[0:2].lower()
email = replaceUmlauts(firstname).lower() + "." + replaceUmlauts(lastname).lower() + "#my.domain"
pyad.set_defaults(ldap_server="my.domain", username="Administrator", password="mypassword")
ou = pyad.adcontainer.ADContainer.from_dn("ou=OU1, ou=OU2, ou=OU3, dc=my, dc=domain")
new_user = pyad.aduser.ADUser.create(loginName, ou, password="Secret123", optional_attributes={
"givenName": firstname,
"sn": lastname,
"displayName": firstname + " " + lastname,
"mail": email,
"initials": initials
})
return True
#app.route("/")
def home():
return render_template("index.html")
#app.route("/addUser", methods=["POST", "GET"])
def addUser():
if request.method == "POST":
firstname = request.form["firstname"]
lastname = request.form["lastname"]
department = request.form["category"]
passwort = request.form["password"]
if len(firstname) == 0:
return redirect(url_for("addUser", error="The first name must not be empty!"))
exit(1)
elif any(chr.isdigit() for chr in firstname):
return redirect(url_for("addUser", error="The first name must not contain numbers!"))
exit(1)
elif len(lastname) == 0:
return redirect(url_for("addUser", error="The last name must not be empty!"))
exit(1)
elif any(chr.isdigit() for chr in lastname):
return redirect(url_for("addUser", error="The last name must not contain numbers!"))
exit(1)
elif len(passwort) < 6:
return redirect(url_for("addUser", error="The password must not have less than 6 characters!"))
exit(1)
createUser(firstname,lastname)
else:
return render_template("addUser.html")
if __name__ == "__main__":
app.run(debug=True)
I fixed the error by importing the libary called pythoncom and add the initialize command in my function, like this:
import pythoncom
def createUser(firstname, lastname):
pythoncom.CoInitialize()
And yes, it is a problem between pyad and Flask
I'm trying to complete this program I need to be able to update a password saved in txt file for a user already saved in the text file and I can't figure out how to do so.
Looking for help on tasks A-C
a. Password update Form – This Python form allows a previously registered user to reset their password after they have successfully logged in.
b. Authentication functions – These Python functions will check the following NIST SP 800-63B criteria are met upon password update:
Use the previous criteria for password length and complexity. (This work should already be
done.)
Compare the prospective secrets against a list that contains values known to be commonly-
used, expected, or compromised (Provided as CommonPasswords.txt).
If the chosen secret is found in the list, the application SHALL advise the subscriber that they
need to select a different secret.
c. Logger – Create a log to log all failed login attempts. The Log should include date, time and IP
address.
from datetime import datetime
from flask import Flask, flash, redirect, render_template, request, session, url_for
import re
from wtforms import Form, PasswordField
from wtforms.validators import DataRequired
app = Flask(__name__)
def validate_password(password):
SpecialSym = ['$', '#', '#', '%', '!', '&', '*']
val = True
if len(password) < 6:
print('length should be at least 6')
val = False
if len(password) > 20:
print('length should be not be greater than 8')
val = False
if not any(char.isdigit() for char in password):
print('Password should have at least one numeral')
val = False
if not any(char.isupper() for char in password):
print('Password should have at least one uppercase letter')
val = False
if not any(char.islower() for char in password):
print('Password should have at least one lowercase letter')
val = False
if not any(char in SpecialSym for char in password):
print('Password should have at least one of the symbols $##')
val = False
if val:
return val
else:
return False
now = datetime.now() # current date and time
date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
# each route for the pages
#app.route("/")
def welcome():
"""the welcome page"""
return render_template("welcome.html")
#app.route("/home")
def home():
"""the home page"""
if not session.get('logged_in'):
return render_template('login.html')
else:
return redirect('home')
#app.route("/register", methods=['GET', 'POST'])
def register():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
f = open("/Users/Brian/PycharmProjects/StateList/Flask_Blog/static/database.txt", "a")
if not validate_password(password):
message = "Invalid Credentials"
return render_template("register.html", error=message)
else:
f.write("%s %s\n" % (email, password))
f.close()
flash("SUCCESSFUL REGISTERED *")
return render_template("homepage.html", error="SUCCESSFUL REGISTERED *")
else:
return render_template("register.html")
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
f = open("/Users/Brian/PycharmProjects/StateList/Flask_Blog/static/database.txt", "r")
data = f.readlines()
f.close()
data = [x.split() for x in data]
for item in data:
if request.form['email'] == item[0].strip() and request.form['password'] == item[1].strip():
session['logged_in'] = True
return render_template('homepage.html')
else:
error = "Wrong Credentials"
return render_template("login.html", error=error)
else:
return render_template("login.html")
#app.route("/reset", methods=['GET', 'POST'])
def reset():
"""reset page"""
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
f = open("/Users/Brian/PycharmProjects/StateList/Flask_Blog/static/database.txt", "a")
if not validate_password(password):
message = "Invalid Credentials"
return render_template("reset.html", error=message)
else:
f.write("%s %s\n" % (email, password))
f.close()
flash("Password Reset *")
return render_template("reset.html", error="Password Reset *")
suppose there as an audio server, you can upload Songs, podcasts, or Audiobook. So in the create endpoint i have created 4 endpoints, so i have put an condition if the audio_type is a song, return all audio of that type but unfortunately this return null
#app.get('/audio/{audio_type}')
def show_all(audio_type):
if audio_type == "Songs":
#app.get("audio/song")
def all(db: Session = Depends(database.get_db)):
songs = db.query(models.Song).all()
print("songs = ", songs)
return songs
elif audio_type == "podcast":
#app.get('audio/podcast')
def all(db: Session = Depends(database.get_db)):
podcast = db.query(models.Podcast).all()
return podcast
elif audio_type == "audiobook":
#app.get('audio/audiobook')
def all(db: Session = Depends(database.get_db)):
audiobook = db.query(models.Audiobook).all()
return audiobook
else:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f' {audio_type} - audio type is not valid')
You are defeating the purpose of an API with your implementation.
For such an implementation, try passing the value as an argument to your API and based upon that you can bifurcate the flow.
def all(db: Session = Depends(database.get_db), audio_type):
if audio_type == "Songs":
songs = db.query(models.Song).all()
print("songs = ", songs)
return songs
elif audio_type == "podcast":
podcast = db.query(models.Podcast).all()
return podcast
elif audio_type == "audiobook":
audiobook = db.query(models.Audiobook).all()
return audiobook
else:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f' {audio_type} - audio type is not valid')
#app.get('/audio')
def show_all(audio_type: str):
return all(Depends(database.get_db), audio_type):
I am new to coding and have been trying to write an automated email formater and sender but am running into trouble trying to get it to realise when it has already sent someone an email.
I tried using a searchable dictionary as shown in the code below however once it sends one email it stops due to something in the code.
This is only a segment of a class for the full code please ask.
def send_email(self):
self.message_format()
if len(self.messages) > 0:
for i in self.messages:
user_email = self.messages[i]["email"]
user_msg = self.messages[i]["message"]
if i in self.sent_to_list:
return False
else:
try:
email_conn = smtplib.SMTP(host,port)
email_conn.ehlo()
email_conn.starttls()
email_conn.login(username, password)
the_msg = MIMEMultipart("alternative")
the_msg["Subject"] = "Hello there!"
the_msg["From"] = from_email
the_msg["To"] = user_email
right_msg = MIMEText(user_msg, "plain")
the_msg.attach(right_msg)
email_conn.sendmail(from_email, [user_email], the_msg.as_string())
email_conn.quit()
self.sent_to_list[str(i)] = self.messages[i]
except smtplib.SMTPException:
print("Error sending message")
except smtplib.SMTPAuthenticationError:
print("An error occured during login")
return True
return False
When your function executes return statement, it immediately stops and returns the value you wrote in return. So in your function it will stop after the first iteration (because of return True in the pre-last line). If you want your function to work more or less correctly, you should:
Replace the first return False with continue. It will skip every bad message. Moreover, because of this you will not need else. You can just have your code to work.
Remove two last lines. return True because you need to iterate through all messages, return False because it has nearly no sense.
Here is the final code:
def send_email(self):
self.message_format()
if len(self.messages) > 0:
for i in self.messages:
user_email = self.messages[i]["email"]
user_msg = self.messages[i]["message"]
if i in self.sent_to_list:
continue
try:
email_conn = smtplib.SMTP(host,port)
email_conn.ehlo()
email_conn.starttls()
email_conn.login(username, password)
the_msg = MIMEMultipart("alternative")
the_msg["Subject"] = "Hello there!"
the_msg["From"] = from_email
the_msg["To"] = user_email
right_msg = MIMEText(user_msg, "plain")
the_msg.attach(right_msg)
email_conn.sendmail(from_email, [user_email], the_msg.as_string())
email_conn.quit()
self.sent_to_list[str(i)] = self.messages[i]
except smtplib.SMTPException:
print("Error sending message")
except smtplib.SMTPAuthenticationError:
print("An error occured during login")
If I understand it correctly you want to send emails to everyone in the dictionary self.messages unless you have already sent it. Currently you call return after one iteration, which terminates the function.
To handle cases where you have already sent an email use continue which simple jumps to the next iteration. You should also remove the return True since it will terminate the function. If you want a boolean return value it should be false only if there are no messages in self.messages, otherwise it doesn't really make sense. The code would then be.
def send_email(self):
self.message_format()
if len(self.messages) > 0:
for i in self.messages:
user_email = self.messages[i]["email"]
user_msg = self.messages[i]["message"]
if i in self.sent_to_list:
continue
try:
email_conn = smtplib.SMTP(host,port)
email_conn.ehlo()
email_conn.starttls()
email_conn.login(username, password)
the_msg = MIMEMultipart("alternative")
the_msg["Subject"] = "Hello there!"
the_msg["From"] = from_email
the_msg["To"] = user_email
right_msg = MIMEText(user_msg, "plain")
the_msg.attach(right_msg)
email_conn.sendmail(from_email, [user_email], the_msg.as_string())
email_conn.quit()
self.sent_to_list[str(i)] = self.messages[i]
except smtplib.SMTPException:
print("Error sending message")
except smtplib.SMTPAuthenticationError:
print("An error occured during login")
return True
return False
I realise now that my error was in the function I iterate at the top of that function.
def message_format(self):
if len (self.user_details) > 0:
for details in self.get_details():
name = details["name"]
date = details["date"]
total = details["total"]
finished_msg = self.base_message.format(
name = name,
date = date,
total = total
)
user_email = details.get("email")
if user_email:
user_data = {"email": user_email,
"message": finished_msg
}
self.messages["customer_" + str(len(self.messages)+1)] = user_data
return self.messages
else:
return ["No user data given"]
I'm using jira-python to loop through all of our users and add them to a specific group. One would think that the 'add_user_to_group' function would have done this, but I ended up having to customize it a bit. At any rate, it mostly worked except for a dozen users that are triggering the 'XSRF Security Token Missing' error. I can't see any common thread in those users that distinguishes them from any body else. If I log into jira I can add the users manually. I'm not really sure where to go from here.
Here's my (slightly modified) add_user_to_group function:
def add_user_to_group(username, group):
url = jira._options['server'] + '/secure/admin/user/EditUserGroups.jspa'
payload = {
'groupsToJoin': group,
'name': username,
'join': 'submit'}
connect = jira._session.post(url, headers=jira._options['headers'], data=payload)
if connect.status_code == 200:
content = connect.content.decode('utf8')
if content.find('class="error">') != -1:
m = re.search('class="error">(.*)</div>', content)
if m:
msg = m.groups()[0]
if msg == 'A user with that username already exists.':
print msg
return True
else:
print "your message is: ", msg
return False
elif 'XSRF Security Token Missing' in content:
print('XSRF Security Token Missing')
return False
else:
return True
return False