def get_profiles(self): self.user_list = TargetUser.get_all_targets() self.accounts = AccountParameters.get_account_parameters(DOMAIN3) self.running_account = self.get_account() print 'Account %s loaded!' % (self.running_account.account,) self.account_timer = Timer() for uid in self.user_list: uid = str(uid) print 'Getting UID: %s profile...' % (uid,) profile = self.get_profile(uid) if profile is None: print 'No profile!!!' continue self.profile_list.append(profile) if len(self.profile_list) > PROFILE_LIMIT: User.dumps(self.profile_list) self.profile_list = [] User.dumps(self.profile_list) # clean up the bottom print 'All Done!'
def prefill_users(clean=True, amount=1000): if clean: session.query(User).delete() for counter in range(amount): user = User(email=faker.email(), password=generate_password(), name=faker.name()) session.add(user) user = User(email="admin", password="******", name="Administrator") session.add(user) session.commit()
def reset_buffer(self): """ reset buffer via flushing data into database :return: """ Timelines.dump(self.buffer) self.buffer = [] User.dumps(self.profile_list) self.profile_list = [] print 'Reset buffer and dump data into DB!'
def saveUser(self, name, email, password): arrayOfData = [name, email, password] if self.checkData(arrayOfData): hashedPw = hashlib.sha256(password.encode('utf-8')).hexdigest() userObject = User(name=name.lower(), email=email.lower(), password=hashedPw, authenticated=False) return persister.storeObject(userObject) #True or False depening on succes return False #1 or more necessary fields were empty
def register(arg=None): if request.method == "GET": if arg == 1: msg = "Not registered user !!! Please register here" return render_template("index.html", name = msg) return render_template("index.html") elif request.method == "POST": session["data"] = [] name = request.form['name'] session["data"].append(name) email = request.form['email'] session["data"].append(email) pswd1 = request.form['pswd'] # pswdhash1 = sha256_crypt.encrypt(pswd1) pswdhash1 = hashlib.md5(pswd1.encode()).hexdigest() session["data"].append(pswdhash1) pswd2 = request.form['rpswd'] # pswdhash2 = sha256_crypt.encrypt(pswd2) pswdhash2 = hashlib.md5(pswd2.encode()).hexdigest() if pswd1 == pswd2: try: user = User(email=email, name=name, pswd=pswdhash1,timestamp=datetime.now()) db.add(user) except: return render_template("index.html", name="Registration unsuccessful") db.commit() return render_template("login.html", name="Registration success. Please login here!!!") # return redirect(url_for('login')) else: return render_template("index.html", name="Passwords mismatch please register again")
def check_database(): database_name = database_getter(without_exceptions=True) if database_name: if database_name == DATABASE_NAME: session = make_session() try: superuser = session.query(User).filter_by( user_id=SUPERUSER_ID).first() if superuser is None: session.add(User(SUPERUSER_ID, True, False, False, 0)) else: superuser.is_admin, superuser.is_pdt, superuser.is_promotion = True, False, False superuser.subscription = 0 session.commit() session.close() print('Database was checked!') except Exception: session.close() remove(database_name) __make_database() print('Database was recreated and filled!') else: remove(database_name) __make_database() print('Database was created and filled!') else: __make_database() print('Database was created and filled!')
def createNewUser(login_session): user = User(username=login_session['username'], email=login_session['email'], picture=login_session['picture']) session.add(user) session.commit() userId = session.query(User).filter_by(email=login_session['email']).one() return userId.id
def __make_database(): engine = create_engine(f'sqlite:///{DATABASE_NAME}', echo=False) metadata = MetaData() users_table = Table(USER_TABLE_NAME, metadata, *User.get_all_columns_with_attributes()) events_table = Table(EVENT_TABLE_NAME, metadata, *Event.get_all_columns_with_attributes()) metadata.create_all(engine) __fill_database()
def createUser(login_session): newUser = User(username=login_session['username'], email=login_session['email'], picture=login_session['picture']) # user is added to table session.add(newUser) session.commit() # user is queried from table and the ID is returned user = session.query(User).filter_by(email=login_session['email']).one() return user.id
def signup(): if current_user.is_authenticated: return redirect(url_for('home')) form = CreateUserForm() if form.validate_on_submit(): # email hashed_email_data = hashlib.sha256( form.email.data.encode()).hexdigest() exists = False user_list = User.query.filter_by(email=hashed_email_data).all() if len(user_list) >= 1: exists = True # check username exists2 = False user_list = User.query.filter_by(username=form.username.data).all() if len(user_list) >= 1: exists2 = True if not exists and not exists2: # bcrypt hashed_password = bcrypt.hashpw(form.password.data.encode(), bcrypt.gensalt(rounds=16)) hashed_security_Q = bcrypt.hashpw( form.security_questions.data.encode(), bcrypt.gensalt()) hashed_security_ans = bcrypt.hashpw( form.security_questions_answer.data.encode(), bcrypt.gensalt(rounds=16)) # bcrypt newuser = User(public_id=str(uuid.uuid4()), username=form.username.data, email=hashed_email_data, password=hashed_password, security_questions=hashed_security_Q, security_questions_answer=hashed_security_ans, is_active=True, is_authenticated=False, is_admin=False) db.session.add(newuser) db.session.commit() flash("You have successfully signed up!") # return redirect(url_for('login')) # 2FA - redirect to the two-factor auth page, passing username in session session['username'] = form.username.data return redirect(url_for('two_factor_setup')) if exists: flash("Email exists!") if exists2: flash("Username is taken!") return redirect(url_for('signup')) return render_template('sign up.html', title="Sign Up", form=form)
def create_user(current_user): if BadRequest: raise BadRequest() if not current_user.is_admin: return jsonify({'Message': 'Unauthorized to perform that function'}) # data = request.get_json() # data_email = data['email'] data_email = request.form['email'] #Check for existing records hashed_email_data = hashlib.sha256(data_email.encode()).hexdigest() exists = db.session.query( User.id).filter_by(email=hashed_email_data).scalar() exists2 = db.session.query( User.id).filter_by(username=request.form['username']).scalar() if exists is None and exists2 is None: # hashed_password = generate_password_hash(request.form['password'], method='sha512') # hashed_security_Q = generate_password_hash(request.form['security_questions'], method='sha1') #with salt # hashed_security_ans = generate_password_hash(request.form['security_questions_answer'], method='sha512') #with salt hashed_password = bcrypt.hashpw(request.form['password'].encode(), bcrypt.gensalt(rounds=16)) hashed_security_Q = bcrypt.hashpw( request.form['security_questions'].encode(), bcrypt.gensalt()) hashed_security_ans = bcrypt.hashpw( request.form['security_questions_answer'].encode(), bcrypt.gensalt()) new_user = User(public_id=str(uuid.uuid4()), username=request.form['username'], password=hashed_password, email=hashed_email_data, security_questions=hashed_security_Q, security_questions_answer=hashed_security_ans, is_active=True, is_authenticated=False, is_admin=False) db.session.add(new_user) db.session.commit() return jsonify({'message': 'New user created!'}), 201 else: return jsonify({'message': 'Username or email exist!!'}), 409
def create_account(): try: check_logged_in() return redirect(url_for(DEFAULT_PAGE)) except AuthorisationException: try: email = request.form['email'] password = request.form["password"] name = request.form["name"] session.add(User(name=name, email=email, password=password)) session.commit() resp = redirect(url_for(DEFAULT_PAGE)) resp.set_cookie('email', email) resp.set_cookie('password', password) return resp except Exception: return redirect('/register?error="UnknownError')
class Panel(Tk): resource = Resource() user = User() def __init__(self): super().__init__() self.top = self.winfo_toplevel() self.screencenter = (self.winfo_screenwidth()/2, self.winfo_screenheight()/2) self.title("انبار دار") self.widget() self.update_idletasks() self.size = tuple(int(_) for _ in self.geometry().split('+')[0].split('x')) self.geometry("+%d+%d" % (self.screencenter[0]-self.size[0]/2, self.screencenter[1]-self.size[1]/2)) @abc.abstractmethod def widget(self): pass
def saveUser(self, name, email, password, locationCity, profilePhoto, description , organisation): arrayOfData = [name, email, password, locationCity, profilePhoto, description , organisation] if self.checkData(arrayOfData): hashedPw = hashlib.sha256(password.encode('utf-8')).hexdigest() path = "C:/Users/Jelmer/Bos-Backend/profilephoto's/" mediaPath = path + name + "Base64.txt" mediaFile = open(mediaPath, "w+") mediaFile.write(profilePhoto) mediaFile.close() userObject = User( name=name.lower(), email=email.lower(), password=hashedPw, authenticated=False, locationCity=locationCity, profilePhoto=mediaPath, description=description, organisation=organisation) return persister.storeObject(userObject) #True or False depening on succes return False #1 or more necessary fields were empty
def handle(request, userId): user = None if userId != 0: user = User.User.get(id=userId) if user is not None and request.method == 'POST': user.name = request.form['name'] user.password = Utils.encrypt_password(request.form['password']) user.token = 0 user.ip = "edited" orm.commit() return redirect(url_for('showUsers')) if user is None and request.method == 'POST': User.User(name=request.form['name'], password=Utils.encrypt_password(request.form['password']), token=0, ip="new") return redirect(url_for('showUsers')) return render_template('editUser.html', user=user)
def create_user(current_user): if not current_user.is_admin: return jsonify({'Message': 'Unauthorized to perform that function'}) data = request.get_json() hashed_password = generate_password_hash(data['password'], method='sha512') new_user = User(public_id=str(uuid.uuid4()), username=data['username'], password=hashed_password, email=data['email'], security_questions=data['security_questions'], security_questions_answer=data['security_questions_answer'], is_active=True, is_authenticated=False, is_admin=False) db.session.add(new_user) db.session.commit() return jsonify({'message': 'New user created!'})
def __fill_database(): session = make_session() session.add(User(SUPERUSER_ID, True, False, False, 0)) session.commit() session.close()
def signup(): if current_user.is_authenticated: return redirect(url_for('home')) form = CreateUserForm() if form.validate_on_submit(): # hashed_username_data = hashlib.sha256(form.username.data.encode()).hexdigest() # --Plaintext--- # exists = db.session.query(User.id).filter_by(email=form.email.data).scalar() # exists2 = db.session.query(User.id).filter_by(username=form.username.data).scalar() # --Plaintext--- # --sha512--- # email hashed_email_data = hashlib.sha256(form.email.data.encode()).hexdigest() exists = False statement = text("SELECT * FROM users WHERE email = '{}'".format(hashed_email_data)) results = db.engine.execute(statement) count = 0 for row in results: count += 1 if count >= 1: exists = True # check username exists2 = False statement = text("SELECT * FROM users WHERE username = '******'".format(form.username.data)) results = db.engine.execute(statement) count = 0 for row in results: count += 1 if count >= 1: exists2 = True # --sha512--- # bcrypt # hashed_email_data = bcrypt.hashpw(form.email.data.encode(), bcrypt.gensalt()) # exists = db.session.query(User.id).filter_by(email=hashed_email_data).scalar() # exists2 = db.session.query(User.id).filter_by(username=form.username.data).scalar() # bcrypt if not exists and not exists2: # ---sha algorithm---- # hashed_password = generate_password_hash(form.password.data, method='sha512') #with salt # hashed_security_Q = generate_password_hash(form.security_questions.data, method='sha1') #with salt # hashed_security_ans = generate_password_hash(form.security_questions_answer.data, method='sha512') #with salt # ---sha algorithm---- # bcrypt hashed_password = bcrypt.hashpw(form.password.data.encode(), bcrypt.gensalt(rounds=16)) hashed_security_Q = bcrypt.hashpw(form.security_questions.data.encode(), bcrypt.gensalt()) hashed_security_ans = bcrypt.hashpw(form.security_questions_answer.data.encode(), bcrypt.gensalt()) # bcrypt # password=form.password.data newuser = User(public_id=str(uuid.uuid4()), username=form.username.data, email=hashed_email_data, password=hashed_password, security_questions=hashed_security_Q, security_questions_answer=hashed_security_ans, is_active=True, is_authenticated=False, is_admin=False) # newuser = User(public_id=str(uuid.uuid4()),username=form.username.data, email=form.email.data, password=hashed_password, # security_questions=form.security_questions.data, # security_questions_answer=form.security_questions_answer.data, # is_active=True, is_authenticated=False, is_admin=False) # Role.create('customer') # newuser.roles.append(Role(name='customer', id=2)) # newuser.set_password(form.password.data) db.session.add(newuser) db.session.commit() flash("You have successfully signed up!") return redirect(url_for('login')) if exists: flash("Email exists!") if exists2: flash("Username is taken!") return redirect(url_for('signup')) return render_template('sign up.html', title="Sign Up", form=form)
def gconnect(): """Processes a login via Google""" # Validate state token if request.args.get('state') != login_session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers['Content-Type'] = 'application/json' return response # Obtain authorization code code = request.data try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError: response = make_response( json.dumps('Failed to upgrade the authorization code.'), 401) response.headers['Content-Type'] = 'application/json' return response # Check that the access token is valid. access_token = credentials.access_token url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) h = httplib2.Http() result = json.loads((h.request(url, 'GET')[1]).decode()) # If there was an error in the access token info, abort. if result.get('error') is not None: response = make_response(json.dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' return response # Verify that the access token is used for the intended user. gplus_id = credentials.id_token['sub'] if result['user_id'] != gplus_id: response = make_response( json.dumps("Token's user ID doesn't match given user ID."), 401) response.headers['Content-Type'] = 'application/json' return response # Verify that the access token is valid for this app. if result['issued_to'] != CLIENT_ID: response = make_response( json.dumps("Token's client ID does not match app's."), 401) print("Token's client ID does not match app's.") response.headers['Content-Type'] = 'application/json' return response stored_access_token = login_session.get('access_token') stored_gplus_id = login_session.get('gplus_id') # if stored_access_token is not None and gplus_id == stored_gplus_id: # response = make_response(json.dumps( # 'Current user is already connected.'), 200) # response.headers['Content-Type'] = 'application/json' # return response # Store the access token in the session for later use. login_session['access_token'] = credentials.access_token login_session['gplus_id'] = gplus_id # Get user info userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() login_session['username'] = data['name'] login_session['picture'] = data['picture'] login_session['email'] = data['email'] session = DBSession() session.merge( User(name=login_session['username'], email=login_session['email'])) session.commit() output = '' output += '<h1>Welcome, ' output += login_session['username'] output += '!</h1>' output += '<img src="' output += login_session['picture'] output += ' " style = "width: 30px; height: 30px;"> ' flash("You are now logged in as %s" % login_session['username']) print("done!") return output
from Database import db, Role, User db.create_all() admin_role = Role(name = 'Admin') mod_role = Role(name = 'Moderator') user_role = Role(name = 'User') user_john = User(username = '******', role = admin_role) user_susan = User(username = '******', role = user_role) user_david = User(username = '******', role = user_role) # 到此这些对象只存在于Python中,还未写入数据库,id的值为None # 对数据库的改动通过数据库会话管理,准备将对象写入数据库之前,要先添加到会话中 # 可直接写成:db.session.add_all([admin_role,mod_role,user_role,user_john,user_susan,user_david]) db.session.add(admin_role) db.session.add(mod_role) db.session.add(user_role) db.session.add(user_john) db.session.add(user_susan) db.session.add(user_david) # 把对象写入数据库,调用commit()方法提交会话 db.session.commit()