async def is_login_exists(login, request=None): db_engine = request.app.db_engine async with db_engine.acquire() as conn: query = users.select().where(users.c.login == login) ret = await conn.execute(query) user = await ret.fetchone() return False if user == None else True
async def registration_handler(request: web.Request) -> web.json_response: request_json = await json_handler(request) user_email = request_json['user']['email'] user_password = request_json['user']['password'] user_access_level = 'primary' data = { 'is_registered': True, 'username': '', 'user_id': '', 'error': None } db = request.app['db'] db.dispose() with db.connect() as conn: try: insert_stmt = insert(users).values(username=user_email, password=user_password, access_level=user_access_level) conn.execute(insert_stmt) except exc.IntegrityError as err: print(f"REGISTRATION ERROR: {err}") data['is_registered'] = False data['error'] = 'User already exists' return web.json_response(data) select_stmt = users.select().where(users.c.username == user_email) new_user = conn.execute(select_stmt) for row in new_user: # print(f"ROW: {row}") data['user_id'] = row[0] data['username'] = row[1] # print(data) return web.json_response(data)
def create_listing(): """"" @summary A function to render and handle a for creating an ad Page for a form to be able to create a listing """ cookie_session_id = request.cookies.get('session_id') user_id, user_name = sessionutils.get_customer_details_from_session_id(cookie_session_id) if request.method == 'POST': uploadFileFlag = 0 filename = secure_filename("default.jpg") # Remove this print statement if running flask in prod print("DEBUG: Posting form") # ### code for the ad listing form ### # Get the form inputs # Remove this print statement if running flask in prod # print(request.form) _title = request.form['inputTitle'] _desc = request.form['inputDesc'] _name = "NULL" try: session.select(session.customer_id).where(session.session_id == request.cookies.get['session_id']).first() except: print("SQL error getting user session") try: _name = users.select(users.name).join(session).where(session.customer_id == users.id).first() except: print("SQL error getting user's name from session") _cond = request.form['inputCond'] _isbn = request.form['inputISBN13'] _author = request.form['inputAuthor'] _price = request.form['inputPrice'] _year = request.form['inputYear'] _pub = request.form['inputPublisher'] _edi = request.form['inputEdi'] try: file = request.files['imgFile'] #print(file) if file.filename != '': filename = secure_filename(file.filename) #print(filename) uploadFileFlag = 1 except: print("Looks like no file attached") adListing.create(title=_title.strip(), sellerId=user_id, price=_price, imageLocation=filename, description=_desc, condition=_cond, _price=_price, sellerName=_name, author=_author, year=_year, publisher=_pub, edition=_edi, isbn=_isbn, status="active") if uploadFileFlag == 1: print("attempting to upload image") upload_from_another_form(file) return redirect('/') else: return render_template('newad.html', name=user_name)
def sign_up(): """ @summary A function to render and handle the sign up page form Server-side method for the UI to interact with the MySQL database """ if request.method == 'POST': # read the posted values from the UI _name = request.form['inputName'] _surname = request.form['inputSurname'] _email = request.form['inputEmail'] _password = request.form['inputPassword'] _phone = request.form['inputPhone'] # Checks for redundancy/existing user account email_query = users.select().where(users.email == _email) for item in email_query: if item.email == _email: info = "Error! Email already exists!" flash(info) return redirect('/') phone_query = users.select().where(users.phoneNumber == _phone) for item in phone_query: if item.phoneNumber == _phone: info = "Error! Phone already exists!" flash(info) return redirect('/') # Create the user in our database try: users.create(firstName=_name, surname=_surname, email=_email, password=_password, phoneNumber=_phone) user_id = users.get(users.firstName == _name, users.email == _email, users.phoneNumber == _phone).id send_verification_email(_name, user_id, _email) info = """ Congratulations, we've signed you up. Now just one last step - Please verify your email address before signing in again.""" flash(info) except: info = "We couldn't sign you up at this time. Please continue later." flash(info) return redirect('/') else: return render_template('signup.html')
async def login_handler(request: web.Request) -> web.json_response: # print("FIND USER AND LOG IN") session = await new_session(request) request_json = await json_handler(request) # print(f"TRY TO LOG IN DATA: {request_json}") username = request_json['user']['email'] password = request_json['user']['password'] # print(f"TRY TO LOG IN USERNAME {username} WITH PASSWORD {password}") data = { 'logged_in': False, 'user_id': None, 'username': None, 'access_level': None } db = request.app['db'] db.dispose() selected_user = None with db.connect() as conn: query_stmt = users.select().where( and_(users.c.username == username, users.c.password == password)) selected_user_result = conn.execute(query_stmt) for row in selected_user_result: selected_user = row # print(f"SELECTED USER: {selected_user}") if not selected_user: print(f"NO USER FOUND {selected_user}") return web.json_response(data) else: data['logged_in'] = True data['user_id'] = selected_user[0] data['username'] = selected_user[1] data['access_level'] = selected_user[3] # Delete auth token after certain amount of time (or log out?) # This will require user to log back in auth_token = uuid4() auth_token = auth_token.hex session["username"] = username session["user_id"] = selected_user[0] session["auth_token"] = auth_token session["access_level"] = selected_user[3] session["logged_in"] = True # print(f"LOGIN DATA: {data}") with db.connect() as conn: update_stmt = users.update().where( users.c.username == username).values(auth_token=auth_token) conn.execute(update_stmt) # print("UPDATED") return web.json_response(data)
async def fetch_full_user(user_id=None, request=None): db_engine = request.app.db_engine async with db_engine.acquire() as conn: query = users.select().where(users.c.id == user_id) ret = await conn.execute(query) user = await ret.fetchone() print(user) user_edit = dict(id=user[0], login=user[1], is_superuser=user[3], disabled=user[4]) print(user_edit) # fetch user permissions query = permissions.select().where(permissions.c.user_id == user_id) async for permission in conn.execute(query): print('permission', permission) p_list = user_edit.get(PERM, list()) p_list.append(permission[2]) user_edit[PERM] = p_list
async def fetch_all_users(request=None): db_engine = request.app.db_engine users_recs = [] async with db_engine.acquire() as conn: async for user in conn.execute(users.select()): users_recs += [ dict(id=user[0], login=user[1], is_superuser=user[3], disabled=user[4]) ] # fetch permissions and mutate users_recs async for permission in conn.execute(permissions.select().order_by( permissions.c.user_id)): user_id = permission[1] - 1 p_name = permission[2] permission_list = users_recs[user_id].get(PERM, list()) permission_list += [p_name] users_recs[user_id][PERM] = permission_list return users_recs
async def test_index_post_route_success(): # Verify successful post request start_time = time() user_data = {"age": 1, "name": "Bob", "city": "Oakland"} resp = await client.post("/", data=user_data) # Assert that there is a delay of 10 seconds assert (time() - start_time) >= 10 assert resp.status == 200 text = await resp.text() assert "Your data has been saved and processed" in text # Assert that data is saved in the database engine = await get_mysql_engine() async with engine.acquire() as conn: cursor = await conn.execute(users.select().order_by( users.c.id.desc()).limit(1)) record = await cursor.fetchone() assert record.age == user_data["age"] assert record.name == user_data["name"] assert record.city == user_data["city"] await close_mysql_engine(engine)
async def retrieve_images(app: web.Application, current_user_id: Integer) -> list: """Retrieve images for specified IDs.""" db = app['db'] db.dispose() photo_data = [] id_list = [] with db.connect() as c: selected_user = c.execute( users.select().where(users.c.id == current_user_id)) for user in selected_user: id_list.append(user[0]) related_users = c.execute(user_to_user_relationships.select().where( user_to_user_relationships.c.user_id == current_user_id)) for r_user in related_users: id_list.append(r_user[1]) # print(f"ID LIST: {id_list}") try: with db.connect() as conn: for single_id in id_list: results = conn.execute( images.select().where(images.c.user_id == single_id)) for res in results: # print(f"RESULT: {res}") # p = parse_image_data(res)[0] p = parse_image_data(app, res)[0] # print(f"P!: {p}") photo_data.append(p) except exc.SQLAlchemyError as err: print( f"ERROR ADDING IMAGES FOR {current_user_id} TO PHOTO DATA: {err}") # print(f"PHOTO DATA: {photo_data}") return photo_data
async def index_handler(request: web.Request) -> web.json_response: data = {"photos": None, "tags": None} session = await get_session(request) username = session.get("username") # print(f"USERNAME: {username}") # print(f"SESSION: {session}") user_id = session.get("user_id") # print(f"USER ID: {user_id}") db = request.app['db'] db.dispose() try: with db.connect() as conn: conn.execute(users.select().where(users.c.id == user_id)) except exc.SQLAlchemyError as err: print(f"ERROR RETRIEVING USER: {err}") available_photos = await retrieve_images(request.app, user_id) order_images(available_photos) # available_photos = await insert_person_tag(request.app, available_photos) people_tags = await retrieve_people_tags(request.app, user_id) data['photos'] = available_photos data['tags'] = people_tags return web.json_response(data)
async def register_invite_handler(request: web.Request) -> web.json_response: # print(f"REGISTER THE INVITE") data = { 'invite_redeemed': False, 'error': None, 'username': None, 'user_id': None, 'user_access_level': None } session = await new_session(request) invite_confirm_data = await json_handler(request) invitee_email = invite_confirm_data['inviteInfo']['email'] invitee_code = invite_confirm_data['inviteInfo']['code'] invitee_access_level = None invited_by = None invitee_key = None db = request.app['db'] db.dispose() # print(f"Invitee_email: {invitee_email}; Invitee_code: {invitee_code}") try: with db.connect() as conn: select_stmt = (invites.select().where( invites.c.invite_code == invitee_code)) selected_invites = conn.execute(select_stmt) for row in selected_invites: # print(f"INVITES ROW: {row}") tdy = str(datetime.datetime.now(datetime.timezone.utc)) if row[3].isoformat() < tdy: data['invite_redeemed'] = False data['error'] = "Invite code has expired." return web.json_response(data) else: data['invite_redeemed'] = True invitee_access_level = row[4] invited_by = row[1] invitee_key = row[0] except exc.SQLAlchemyError as err: data['invite_redeemed'] = False data['error'] = "There was a database error." print(f"REDEEM INVITE ERROR: {err}") if data['invite_redeemed']: # print(f"INVITE REDEEMED") temp_password_uuid4 = uuid4() temp_password = temp_password_uuid4.hex with db.connect() as conn: insert_users_stmt = (insert(users).values( username=invitee_email, password=temp_password, access_level=invitee_access_level)) conn.execute(insert_users_stmt) new_user = conn.execute(users.select().where( and_(users.c.username == invitee_email, users.c.password == temp_password))) # print(f"NEW USER: {new_user}") new_user_id = None for row in new_user: new_user_id = row[0] insert_users_relationship = ( insert(user_to_user_relationships).values( user_id=new_user_id, linked_to=invited_by)) conn.execute(insert_users_relationship) auth_token = uuid4() auth_token = auth_token.hex session['username'] = invitee_email session['user_id'] = new_user_id session['auth_token'] = auth_token session['access_level'] = invitee_access_level session['logged_in'] = True data['username'] = invitee_email data['user_id'] = new_user_id data['user_access_level'] = invitee_access_level # print(f"{session}") update_auth_token = (users.update().where( users.c.username == invitee_email).values( auth_token=auth_token)) conn.execute(update_auth_token) delete_invite = (invites.delete().where( invites.c.invite_code == invitee_code)) conn.execute(delete_invite) # print(f"INVITE DATA: {data}") return web.json_response(data)