def decorated_function(*args, **kwargs): try: if not User.api_key_exists(request.get_json(force=True)[GraphConstants.FIELDS['api_key']['name']]): raise GraphErrors.IncorrectAPIKeyError("Your provided API key is invalid or does not exist.") except KeyError: raise GraphErrors.MissingKeyError("You did not provide an API key in your JSON body request.") return func(*args, **kwargs)
def login_user(): if request.method == 'POST': email = request.form['email'] password = request.form['password'] try: if User.login_valid_user(email, password): session['email'] = email return redirect(url_for(".alerts_user")) except UserError as e: return e.message return render_template("users/login.html")
def register(): form = RegisterForm(request.form) # make sure data are valid, but doesn't validate password is right if form.validate_on_submit(): try: user = User.register_user(email=form.email.data, password=form.password.data) session['id'] = user._id except UserErrors.UserError as e: return redirect(url_for('index', message=e.message)) return redirect(url_for('.profile')) return render_template('users/register.jinja2', form=form)
def trip_add(): if request.method == 'POST': # event_name = request.form['event_name'] # venue = request.form['venue'] source = request.form['source'] destination = request.form['destination'] total_days = int(request.form['total_days']) first_city = request.form['first_city'] reservation = request.form['reservation'] #messaging code begins - sender code msg = "Destination city sent for events is:" + destination res_msg = TripConstants.sqs.send_message( QueueUrl=TripConstants.queue_url, #Queue URL DelaySeconds=1, MessageAttributes={ #Metadata 'Sender': { 'DataType': 'String', 'StringValue': destination } }, MessageBody=( #Main Message msg)) time.sleep(2) print(res_msg['MessageId']) # event_date = int(request.form['event_date']) # json_object=r.json() # print(json_object) Trip(source, destination, total_days, first_city, reservation).save_to_mongo() trip = { "source": source, "destination": destination, "total_days": total_days, "first_city": first_city, "reservation": reservation # "total": total } user = User.find_by_email(session['email']) user.trips = {uuid.uuid4().hex: trip} # # user.points_earned += (price/100) # print(user) trip_data = json.dumps(trip) # user.save_to_mongo() return redirect(url_for(".index")) return jsonify({'trips': trip}) return render_template('trips/new_trip.html')
def validate_username(form, field): reg_pattern = "^[a-zA-Z0-9_.-]+$" if User.find_by_username(username=field.data): logger.warning( f"An attempt was made to register with the {field.data.lower()} a username that already exists " ) raise UsernameAlreadyExists( "A users with that name already exists") if not is_string_a_match(reg_expression_pattern=reg_pattern, str_to_match=field.data): raise InvalidUsernameFormat("The username is invalid")
def test_attempt_login(self): # Setup conn = get_test_connection() reset_database(conn) cur = conn.cursor() # Create children user_id = User.create_user( cur, User(user_id=None, username='******', pin='1234', user_type_id=1, created_at=None, updated_at=None, deleted=None)) user = User.attempt_login(cur, 'bad_username', '1234') # Test wrong name assert user is None user = User.attempt_login(cur, 'username', '0000') # Test wrong pin assert user is None user = User.attempt_login(cur, 'username', '1234') # Test correct creds assert user is not None conn.commit() pass
def login(): if request.method == "GET": # first time coming to login page return render_template("user/login.html", error=False) elif request.method == "POST": # requested login email = request.form.get("email") password = request.form.get("password") user = User(email, password) user_data = user.valid() if user_data: # maybe add more than email later session['email'] = email session['user_id'] = user_data['id'] session['name'] = user_data['name'] user_type = user_data['type'] if user_type == "admin": return redirect(url_for(".admin")) return redirect("/") # return utils.redirect_previous_url() else: # no user with this combo email:pw return render_template("user/login.html", error=True)
def login_user(): if request.method == 'POST': email = request.form['email_login'] password = request.form['password_login'] try: if User.is_login_valid(email, password): session['email'] = email return redirect(url_for('.user_dashboard')) except UserErrors.UserError as e: return e.message # this return works if the request method is GET or the login credentials are invalid return redirect(url_for('home_english'))
def register_user(): if request.method == 'POST': name = request.form['name'] email = request.form['email'] password = request.form['password'] address = request.form['address'] ph_no = request.form['ph_no'] try: if User.register_user(email, password, name, address, ph_no): session['email'] = email return redirect(url_for(".user_dashboard")) except UserErrors.UserError as e: return e.message return render_template("users/register.html")
def register_user(): try: if request.method == 'POST': email = request.form['email'] password = request.form['password'] nick_name = request.form['nickname'] try: if User.register_user(email, password, nick_name): session['email'] = email message = Message( title="Welcome to Note-it™!", content="""Welcome to Note-it! You can make a note, and share it with other users! Or you can just keep the note to your selves. You can send messages to other users too! Check out this website!!""", reciver_id=User.find_by_email(email)._id, sender_id=User.find_by_email('*****@*****.**')._id) message.save_to_db() return redirect(url_for("home")) except UserErrors.UserError as e: return e.message return render_template("users/register.html") except: error_msg = traceback.format_exc().split('\n') Error_obj = Error_( error_msg=''.join(error_msg), error_location='register_user while registering user') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during registering you...')
def group(group_id): try: group_ = Group.find_by_id(group_id) if group_ is None: return render_template( 'groups/group.html', error_msg='The group you requested is no longer exists!') members = [] shared_notes = [] for member in group_.members: members.append(User.find_by_id(member)) for note in group_.shared_notes: append_data = Note.find_by_id(note['note_id']) if append_data is not None: shared_notes.append({"data": append_data, "error_note": False}) else: shared_notes.append({"error_note": True, "data": None}) group_.shared_notes.remove(note) if session['_id'] in group_.members: is_in_group = True else: is_in_group = False group_alerts = Notification.find_by_type('to_group', group_._id, session['_id']) try: group_.save_to_elastic() except: pass group_.save_to_mongo() return render_template('groups/group.html', group=group_, members=members, shared_notes=shared_notes, is_in_group=is_in_group, session_id=session['_id'], group_alerts=group_alerts) except: error_msg = traceback.format_exc().split('\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='group getting group') Error_obj.save_to_mongo() return render_template( 'base_htmls/error_page.html', error_msgr='Crashed during getting your group info...')
def register_user(): if request.method == 'POST': email = request.form['email'] password = request.form['password'] try: if User.register_user(email, password): session['email'] = email return redirect(url_for(".user_accounts")) except UserErrors.UserError as e: return e.message return render_template( "users/register.jinja2" ) # Send the user an error if their login was invalid
def user_notes(): try: user = User.find_by_email(session['email']) user_notes = User.get_notes(user) user_name = user.email if request.method == 'POST': form_ = request.form['Search_note'] notes = Note.search_with_elastic(form_, user_nickname=user.nick_name) return render_template('/notes/my_notes.html', user_notes=notes, user_name=user_name, form=form_) else: return render_template('/notes/my_notes.html', user_name=user_name, user_notes=user_notes) except: error_msg = traceback.format_exc().split('\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='user note reading USER:'******'email']) Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your notes...')
def forgot_password_email(): email = request.form.get('email') user = User.get_user_object(email=email) msg = Message('Password change request', sender='*****@*****.**', recipients=[email]) msg.body = "Please click on the following link to change your password- " \ "http://127.0.0.1:5000/users/change_password/{}".format(user._id) MailSender.send_mail(msg) # mail.send(msg) return render_template( 'general.html', message='Please check your email inbox for reset link.')
def register(): if request.method == "GET": return render_template("user/register.html", error=False) elif request.method == "POST": email = request.form.get('email') if utils.email_valid(email) and not get_user_by_email(email): # login with same method (POST) and same values name = request.form.get("first_name") + " " + request.form.get( "last_name") password = request.form.get("password") # tempo if email == "*****@*****.**": user_type = "admin" else: user_type = "normal" user = User(email=email, name=name, password=password, type=user_type) user.save() return redirect(url_for(".login"), code=307) else: # either email not valid or already exists in db return render_template("user/register.html", error=True)
def login_user_hindi(): if request.method == 'POST': email = request.form['email_login_hindi'] password = request.form['password_login_hindi'] try: if User.is_login_valid(email, password): session['email'] = email return redirect(url_for('.user_dashboard_hindi')) except UserErrors.UserError as e: gs = goslate.Goslate() message = gs.translate(e.message, 'hi') return message # this return works if the request method is GET or the login credentials are invalid return redirect(url_for('home_hindi'))
def post(self): data = self.parser.parse_args() username = data.get('username', None) key = data.get('key', None) if not username or not key: return {'error': 'Invalid request.'}, 400 user = UserModel.findByKeys(username, key) if not user: return {'error': 'Invalid keys.'}, 403 return self.schema.jsonify(GlycaemiaModel.findByUserId(user.id), many=True)
def add_phone_number() -> "render_template": form = AddPhoneNumberForm() if request.method == "POST" and form.validate_on_submit(): user = User.find_by_username(session["username"]) user.phone_number = form.phone_number.data user.save() log = f"You added your phone number to your account on {format_date(get_date_now())}" log_account_activity(log=log, username=user.username) flash("You have successfully added your phone number", "success") return secure_redirect_or_403(url_for("account_app.view_account")) return render_template("add_details/add_phone.html", form=form, login_form=LoginForm())
def login_user(): if request.method == 'POST': email = request.form['email'] password = request.form['password'] try: if User.is_login_valid(email, password): session['email'] = email return redirect(url_for(".user_alerts")) #return "login successfully" except UserErrors.UserError as e: return e.message return render_template( "users/login.html" ) # Send the user an error if their login was invalid
def account_setup(username) -> "redirect(url_for('home_app.landing_page'))": user = User.find_by_username(username=username.lower()) if user and not user.account: Account.setup_user_account(user.username) logger.info(msg=f"The user <{user.username.title()}> has setup their account") log_account_activity(username=user.username, log=f"Your account was set up on {format_date(get_date_now())}") elif user and user.account[0].live: logger.debug(msg=user.username) log_account_activity(username=user.username, log=f"You confirmed your email address on {format_date(get_date_now())}") return redirect(url_for("home_app.landing_page"))
def register(): if request.method == 'POST': user = User(request.form['username'], request.form['email'], request.form['full_name'], request.form['phone_number'], [], request.form['password']) user.save_to_db() user.login() return redirect('users/profile') else: return render_template('users/register.html')
def login_user(): if request.method == "POST": email = request.json["email"] password = request.json["password"] try: if User.is_login_valid(email, password): #session['email'] = email #return redirect(url_for(".user_alerts")) return jsonify({'email': email}) except UserErrors.UserError as e: return jsonify({'error': 'Error, ' + e.message}) #return jsonify({'error': 'Failed Try Again' }) return render_template( "users/login.jinja2" ) # Send the user an error if their login was invalid
def post(self): user_email = get_jwt_identity() data = self.parser.parse_args() name = data.get('username', None) if not name: return {'error': "Invalid request."}, 400 user = UserModel.find(user_email).id key = KeyModel(user) key.value = KeyModel.generateKey() key.username = name key.safe() return self.schema.jsonify(key, many=False)
def users_page(): try: users = User.get_all() # TODO: 일래스틱서치 배우고 완료하기 return render_template('/users/users_page.html', users=users) except: error_msg = traceback.format_exc().split('\n') Error_obj = Error_( error_msg=''.join(error_msg), error_location= 'users_page while loading users info and posting to html') Error_obj.save_to_mongo() return render_template( 'error_page.html', error_msgr='Crashed during reading information...')
def patch(self): text_fields = ['name', 'sex', 'diabetes'] date_fields = ['birthday', 'detection'] user = UserModel.find(get_jwt_identity()) data = self.parser.parse_args() for field in data: value = data.get(field, None) if value is not None and (field in date_fields or field in text_fields): if field in date_fields: value = datetime.datetime.strptime(value, "%Y-%m-%d").date() setattr(user, field, value) user.safe() return self.schema.jsonify(user, many=False)
def add_to_group(): # # getting all user's notes # notes = Note.get_user_notes(session['email']) # getting user object user = User.find_by_id(session['_id']) # getting user group notes group_notes = Group.find_by_id(user.group_id).get_user_shared_notes( session['email']) # not_added_notes = list(OrderedDict.fromkeys(user.get_notes() + group_notes)) not_added_notes = list(set(user.get_notes()) - set(group_notes)) # not_added_notes = list(dict.fromkeys(user.get_notes() + group_notes)) if request.method == 'POST': if user.group_id is None: # flash("You aren't in a group. Please join a group to share notes to friends.") flash( '{ "message":"You aren\'t in a group. Please join a group to share notes to friends.", "type":"error" , "captaion":"Group Share Error", "icon_id": "fas fa-exclamation-triangle"}' ) return redirect(url_for('groups.groups')) group_ = Group.find_by_id(user.group_id) add_notes = request.form.getlist('selected_notes') for note in add_notes: note = Note.find_by_id(note) if { 'author': user._id, 'note_id': note._id } in group_.shared_notes: pass else: group_.shared_notes.extend([{ 'author': user._id, 'note_id': note._id }]) group_.shared_notes = group_.shared_notes # saving to database group_.save_to_elastic() group_.save_to_mongo() return redirect(url_for('groups.group', group_id=group_._id)) return render_template('notes/add_to_group.html', notes=not_added_notes)
def gen_all_friends_diclist(): all_firends_ = User.find_by_id(session['_id']).get_friends() all_firends_diclist = [] for user in all_firends_: try: image = url_for('static', filename=user.picture) except werkzeug.routing.BuildError: image = url_for('static', filename='img/index.jpg') all_firends_diclist.append({ 'url': image, 'user_id': user._id, "last_logined": user.last_logined, "nickname": user.nick_name, "email": user.email }) return all_firends_diclist
def my_recived_messages(user_id): try: messages = Message.find_by_reciver_id(user_id) user_nickname = User.find_by_id(session['_id']).nick_name return render_template('messages/my_recived_messages.html', messages=messages, user_nickname=user_nickname) except: error_msg = traceback.format_exc().split('\n') Error_obj = Error_( error_msg=''.join(error_msg), error_location='my_recived_messages-during message finding') Error_obj.save_to_mongo() return render_template( 'error_page.html', error_msgr='Crashed during reading your messages')
def secession_chatbox(secession_chatbox_id): user_chatboxs = ChatBox.get_user_chatboxs(session['_id']) if secession_chatbox_id is not None: chatbox_obj = ChatBox.find_by_id(secession_chatbox_id) chatbox_obj.user_ids.remove(session['_id']) chatbox_obj.save_to_mongo() current_user_name = User.find_by_id(session['_id']).nick_name # flash('Successfully secessioned chatbox ' + chatbox_obj.name) flash( '{ "message":"Successfully secessioned chatbox " + chatbox_obj.name, "type":"success" , "captaion":"Chatbox Secession", "icon_id": "fas fa-sign-out-alt"}' ) message_bar = Message(title="User %s has secessioned." % (current_user_name), content=None, reciver_id=None, sender_id=None, sender_name="System") message_bar.save_to_mongo() return redirect(url_for('chatboxs.chatboxs')) if request.method == 'POST': if secession_chatbox_id is not None: chatbox_obj = ChatBox.find_by_id(secession_chatbox_id) chatbox_obj.user_ids.remove(session['_id']) chatbox_obj.save_to_mongo() # flash('Successfully secessioned chatbox '+ chatbox_obj.name) flash( '{ "message":"Successfully secessioned chatbox " + chatbox_obj.name, "type":"success" , "captaion":"Chatbox Secession", "icon_id": "fas fa-sign-out-alt"}' ) return redirect(url_for('chatboxs.chatboxs')) secession_chatboxes = request.form.getlist('secession_chatboxes') chatbox_objs = [] for _id in secession_chatboxes: if ChatBox.find_by_id(_id) is not None: chatbox_objs.append(ChatBox.find_by_id(_id)) for chatbox in chatbox_objs: chatbox.user_ids.remove(session['_id']) chatbox.save_to_mongo() return redirect(url_for('chatboxs.chatboxs')) # socketio.emit('secession') return render_template('chatboxs/secession_chatbox.html', user_chatboxs=user_chatboxs)
def home() -> "render_template('index.html')": form = RegisterForm() if request.method == "POST": if form.validate_on_submit(): email, username = form.email.data.lower().strip( ), form.username.data.strip().lower() token = gen_confirmation_string_token_from_email(email) try: email_user_confirmation_email_link(username=username, email=email, token=token) except FailedToSendEmail: logger.critical( f"Failed to send a confirmation email to the user with the email <{email}> address" ) else: user = User( email=email, email_confirmation_sent_on=datetime.utcnow(), username=username, password=PasswordImplementer.hash_password( form.new_password.data), token=token, ).save() email_notification_to_owner_about_new_user_registration(user) flash("You have successfully registered.", "success") flash( "Check your email for a confirmation link or your junk or spam box if it is not in your inbox.", "info") return secure_redirect_or_403(url_for("home_app.home")) else: flash( "Your registration form could not be submitted because it contains errors", "danger") return render_template("index.html", contact_form=ContactForm(), login_form=LoginForm(), register_form=form)
def login() -> "render_template('index.html')": login_form = LoginForm() email = login_form.email.data if request.method == "POST" and login_form.validate_on_submit(): user = User.find_by_email(email=email) if not user: flash("Incorrect Username and password", "danger") logger.warning( f"An unregistered user with the email <{email}> attempted to login" ) elif user and user.account and not user.account[0].live: flash("Your account is no longer active.", "danger") flash("Contact the administrator using the contact us form below", "info") elif user and not user.email_confirmed: flash( "You need to confirm your email before you can use the website", "danger") elif user and PasswordImplementer.is_password_valid( user.password, login_form.password.data): session["username"] = user.username.lower() session["admin"] = user.account[0].admin session["email"] = user.email.lower() return secure_redirect_or_403(url_for("home_app.dashboard")) else: flash("Incorrect Username and password", "danger") logger.warning( f"The user <{user.username.title()}> failed to login with the correct username and password" ) return render_template("index.html", contact_form=ContactForm(), login_form=login_form, register_form=RegisterForm())
def reset_password() -> "render_template": form = ForgottenPasswordForm() if request.method == "POST" and form.validate_on_submit(): user = User.find_by_email(form.email.data) if user: token = gen_confirmation_string_token_from_email(user.email) email_user_forgotten_password_link(email=user.email, username=user.username, token=token) user.token = token user.save() logger.info(f"The user <{user.username.title()}> has requested a password reset link") log = f"You requested a forgotten password link on {format_date(get_date_now())}" log_account_activity(log=log, username=user.username) flash("If you email address is found we will send you a reset link", "info") return render_template('password/forgotten_password.html', form=form, login_form=LoginForm())
def add_friend(json, methods=['POST', 'GET']): data = json['data_'] chatbox = ChatBox.find_by_id(session['chatbox_id']) if data is '': return else: user_objs = [] for dic in data: if not dic['value'] in chatbox.user_ids: chatbox.user_ids.append(dic['value']) user_obj = User.find_by_id(dic['value']) if user_obj.picture is None or user_obj.picture == '': user_objs.append({ "user_name": user_obj.nick_name, "user_email": user_obj.email, "user_photo_path": url_for('static', filename='img/index.jpg'), "user_url": url_for('users.user_page', user_id=user_obj._id) }) else: user_objs.append({ "user_name": user_obj.nick_name, "user_email": user_obj.email, "user_photo_path": url_for('static', filename=user_obj.picture), "user_url": url_for('users.user_page', user_id=user_obj._id) }) chatbox.save_to_mongo() emit("addfriend response", { 'data': data, 'user_objs': user_objs }, broadcast=True, room=json['room'])
def check_login(): g.user = None if 'id' in session.keys() and session['id'] is not None: g.user = User.find_by_id(session['id'])
def profile(): user = User.find_by_id(session['id']) return render_template('users/profile.jinja2', user=user)