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
Related
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
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 *")
A friend asked me to develop a counter on Flask with python that updates itself when someone enters a number in an input but I'm a real beginner.
My method was to create a text file that keeps the precedent count so I could print the count + the input.
But I have a 400 error : "Bad Request The browser (or proxy) sent a request that this server could not understand."
Below is the code I wrote so far
Thanks for your help!
from flask import Flask, request
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def index():
choice = ''
choice = int(request.form["choice"])
if request.method == "POST":
with open( "count.txt", "r" ) as f:
count = f.read()
output = """#Content-type: text/html\r\n\r\n
<html>
<center>
<p>The count is now : {count}</p>
</center>
</html>
""".format(count=count)
count = int(count)
with open( "count.txt", "w" ) as f:
f.write(str(count+choice) )
print(output)
else:
choice = input("Enter a number : ")
choice = int(choice)
if __name__ == "__main__":
app.run(debug=True)
To simplify you could just:
from flask import Flask
app = Flask(__name__)
counter = 1 #or whatever you want to start with
#app.route('/')
def main():
global counter
counter += 1
return str(counter)
So this code works - now you need to adapt the changes of yours to the file.
Btw for what do you need to store it in a .txt file?
I am trying to make a python program that will allow a user to sign up or sign in, and I am currently doing so by creating a file that stores every username and its password. Right now, it is not writing to the file, and I was wondering if anyone could tell me what I'm doing wrong. Please forgive me if it is a stupid error, I am not very experienced with python, but I can still make a basic program. This is my code:
# -*- coding: utf-8 -*-
from time import sleep
def signin():
usrlist = open("users.txt", 'w+')
complete = False
while (complete == False):
usr = raw_input("Username: ")
pwd = raw_input("Password: ")
usrinfo = (usr + ":" + pwd)
if (usrinfo in usrlist.read()):
print("Welcome back " + usr + ".")
complete = True
else:
print("Username or Password incorrect. Please try again.")
def signup():
usrlist = open("users.txt", 'w+')
usravailable = False
while (usravailable == False):
newusr = raw_input("Please choose a Username: ")
if (newusr in usrlist.read()):
print("Username taken. Please choose again.")
else:
usravailable = True
newpwd = raw_input("Please choose a password: ")
oldusrlist = usrlist.read()
usrlist.write(oldusrlist + newusr + ":" + newpwd + ".")
print("Thank You. Please Sign in.")
signin()
print("Please Choose An Option:")
print("1. Sign In")
print("2. Sign Up")
inorup = input()
if (inorup == 1):
signin()
elif (inorup == 2):
signup()
Also, if you have any suggestions about how I could do this differently, or better(even if it's using a different language) Thank you and I appreciate your help.
EDIT:
If anyone can give me information on doing a program like this either using JSON, javascript, or multiple files that can store larger amounts of data about each account, please tell me how in the comments or an answer. I appreciate the help.
To fix your not saving issue, you need to do two changes:
1) in your signin() routine, change the line 'usrlist = open("users.txt", 'w+')' into 'usrlist = open("users.txt", 'r')
2) in your singup() routine, after the line 'usrlist.write(oldusrlist + newusr + ":" + newpwd + ".")', add: 'usrlist.close()'
Then you should be able to see the stuff got saved.
here is a way to use json
import json
import os
FILENAME = "./f.json"
# init the data file
def init_data():
with open(FILENAME, "wb") as f:
json.dump({}, f)
def load_content():
with open(FILENAME) as f:
infos = json.load(f)
return infos
def save_content(content):
with open(FILENAME, "w+") as f:
json.dump(content, f)
return True
def save_info(username, password):
infos = load_content()
if username in infos:
return False
infos[username] = password
save_content(infos)
return True
def sign_in(username, password,):
status = save_info(username, password)
if not status:
print "username exists"
def login(username, password):
infos = load_content()
if username in infos:
if password == infos[username]:
print "login success"
return True
else:
print "password wrong"
return False
else:
print "no user named %s" %username
if __name__ == "__main__":
# here is some simple test
os.system("rm -f %s" %FILENAME)
if not os.path.exists(FILENAME):
init_data()
# login fail
login("hello","world")
# sign_in
sign_in("hello", "world")
# login success
login("hello","world")
# sign_in fail
sign_in("hello", "world")
# login fail
login("hello", "hello")
I am working on a flask file and I am trying to to take some of the functionality and methods and place them in a separate python file so that it is easier to work with and creates a file that is just for functionality in my flask app. I have looked up how to do but for some reason it is not working with me and I was hoping someone can help me. I have file snippets and github link below.
github: https://github.com/omar-jandali/RoadTripWebsite
original init.py file:
import modu
from flask import Flask, render_template, request, redirect, url_for, flash
from flask import escape, session
from datetime import datetime
from sqlalchemy import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Users, Groups, Records, Base
#app.route('/validate_registration', methods=['GET', 'POST'])
def Validate_Registration():
usernameMinChars = 4
usernameMaxChars = 12
passwordMinChars = 8
passwordMaxChars = 14
if request.method == 'POST':
# this is all of the fields in the form
username = request.form['username']
email = request.form['email']
password = request.form['password']
verify = request.form['verify']
check_username = db_session.query(Users).filter_by(Username = username).\
first()
check_email = db_session.query(Users).filter_by(Email = email).first()
if username != None:
if len(username) >= usernameMinChars:
if len(username) <= usernameMaxChars:
if check_username == None:
valid_username = username
else:
flash('The username ' + username + ' is already in use')
return redirect(url_for('Registration'))
else:
flash('The username is too long')
return redirect(url_for('Registration'))
else:
flash('The username is too short')
return redirect(url_for('Registration'))
else:
flash('Youh ave to enter a username to register')
return redirect(url_for('Registration'))
Changed server/init.py file (I want to chagne it so that I call a def in a different file in order to validate the username and submit the username if valid.)
Replace:
if username != None:
if len(username) >= usernameMinChars:
if len(username) <= usernameMaxChars:
if check_username == None:
valid_username = username
else:
flash('The username ' + username + ' is already in use')
return redirect(url_for('Registration'))
else:
flash('The username is too long')
return redirect(url_for('Registration'))
else:
flash('The username is too short')
return redirect(url_for('Registration'))
else:
flash('Youh ave to enter a username to register')
return redirect(url_for('Registration'))
with:
valid_username = modu.ValidateUsername(check_username)
** I have added a new file called modu in the same file directory that is imported at the top of the init.py file
Here is the modu.py file that was created to hold all of the defs in that can be called by the init.py file when needed:
from flask import Flask, render_template, request, redirect, url_for, flash
from flask import escape, session
from datetime import datetime
from sqlalchemy import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Users, Groups, Records, Base
def ValidateUsername(username):
if username != None:
if len(username) >= usernameMinChars:
if len(username) <= usernameMaxChars:
if check_username == None:
valid_username = username
return valid_username
else:
flash('The username ' + username + ' is already in use')
return redirect(url_for('Registration'))
else:
flash('The username is too long')
return redirect(url_for('Registration'))
else:
flash('The username is too short')
return redirect(url_for('Registration'))
else:
flash('Youh ave to enter a username to register')
return redirect(url_for('Registration'))
First, try not nesting things when you don't have to
Second, you're trying to return two different objects, so you'll need to catch that
def is_valid_user(username):
go_register = False
if not username:
flash('You have to enter a username to register')
go_register = True
if len(username) >= usernameMinChars:
flash('The username is too long')
go_register = True
if len(username) <= usernameMaxChars:
flash('The username is too short')
go_register = True
if not check_username:
flash('The username ' + username + ' is already in use')
go_register = True
# return two items, a redirect and the username
if go_register:
return redirect(url_for('Registration')), None
# If there was no error, you don't redirect
return None, username
For example,
go_register, valid_username = is_valid_user(username)
if go_register:
return go_register
else:
flash("valid " + valid_username)