Пример #1
0
def sign_up_user():
    """Shows form to sign-up user if not logged in and then redirects to /"""

    user = session.get('logged_in_user', None)

    if user:
        return redirect('/')

    form = SignUp()

    if form.validate_on_submit():

        if is_username(form.username.data) == True:
            flash(
                Markup(
                    'Username already exists. Go to <a href="/login" class="alert-link">login</a> page.'
                ))
            return redirect('/sign_up')

        signup(form.name.data, form.username.data, form.password.data)
        session['logged_in_user'] = data.user
        data.board = None
        return redirect('/')

    else:
        return render_template('/signup.html', form=form, user=user)
Пример #2
0
def sign_up():
    '''
    회원가입 화면
    '''
    sign_up_form = SignUp()
    if sign_up_form.validate_on_submit():
        inputName = sign_up_form.data.get("inputName")
        inputEmail = sign_up_form.data.get("inputEmail")
        inputPassword = sign_up_form.data.get("inputPassword")
        inputPhone = sign_up_form.data.get("inputPhone")

        email_check = db.session.query(User).filter(
            User.email == inputEmail).first()
        if email_check is None:
            user = User()
            user.name = inputName
            user.email = inputEmail
            user.password = inputPassword
            user.phone = inputPhone
            db.session.add(user)
            db.session.commit()
            return redirect('/sign_in')
        else:
            flash("중복된 이메일입니다.", "email_error")

    return render_template('sign_up.html', sign_up_form=sign_up_form)
Пример #3
0
def register_user():
    """Returns form to register a new user.

    If form validates, adds the new User to the db, and redirects to homepage.
    
    If username is taken, re-render the form and flash msg to user """
    form=SignUp()
    if form.validate_on_submit():
        try:
            user = User.signup(
                form.username.data,
                form.email.data,
                form.password.data,
                form.profile_img.data or User.profile_img.default.arg
            )
            db.session.commit()

        except IntegrityError:
            flash("Username already taken, please choose another", 'danger')
            return render_template('sign_up.html', form=form)

        do_login(user)
        flash(f"Welcome {user.username}", "success")

        return redirect("/")

    else:
        return render_template('sign_up.html', form=form)
Пример #4
0
def edit_user_page():
    """Shows form to edit user if logged in, edits if password is authenticated, 
    and then redirects back to user profile"""

    user = session.get('logged_in_user', None)

    if not user:
        return redirect('/')

    form = SignUp()

    if form.validate_on_submit():
        print(form.username.data)
        print(get_user(user).username)

        if form.username.data != get_user(user).username:

            if is_username(form.username.data) == True:
                print("hi")
                flash('Username already exists.')
                return redirect('/edit')
        if login(get_user(user).username, form.password.data) == False:
            flash('Incorrect Password.')
            logout_user()
            data.user = None
            session.pop('logged_in_user')
            return redirect('/login')

        edit_user(form.name.data, get_user(user).username, form.username.data)
        # session['logged_in_user'] = data.user
        return redirect('/profile')

    else:
        return render_template('/signup.html', form=form, user=user)
Пример #5
0
def index():

    user_id = session.get('u_id')
    if user_id:
        return redirect(url_for('dashboard'))

    form_one = SignUp()

    if form_one.validate_on_submit():
        fname = form_one.fname.data
        email = form_one.email.data
        username = form_one.username.data
        password = form_one.password.data

        hash_password = bcrypt.generate_password_hash(password).decode('utf-8')

        user = db.execute("SELECT * FROM reg_accounts WHERE email = :email", {
            "email": email
        }).fetchone()

        db.execute(
            "INSERT INTO reg_accounts (fname, username, email, password) VALUES (:fname, :username, :email, :password)",
            {
                "fname": fname,
                "username": username,
                "email": email,
                "password": hash_password
            })
        db.commit()

        flash(
            f'Your Account has been registered successfully, you can now login.',
            'success')

        return redirect(url_for('index'))

    form_two = Login()

    if form_two.validate_on_submit():
        username_two = form_two.username_two.data
        password = form_two.password.data

        user = db.execute(
            "SELECT * FROM reg_accounts WHERE username = :username", {
                "username": username_two
            }).fetchone()

        if user and bcrypt.check_password_hash(user.password,
                                               password) is True:
            session['u_id'] = user.id
            session['u_email'] = user.email
            return redirect(url_for('dashboard'))
        else:
            flash(
                f'You have entered incorrect Email ID or Password, please check your entered Email ID/Password.',
                'warning')
            return redirect(url_for('index'))

    return render_template('index.html', form_one=form_one, form_two=form_two)
Пример #6
0
def signup():
    form = SignUp()
    if request.method == "GET":
        if "email" in session:
            return redirect(url_for("myprofile"))
        else:
            return render_template("signup.html", form=form)
    elif request.method == "POST":
        if form.validate() == False:
            flash("All fields are required")
            return render_template("signup.html", form=form)
            # finds if a user exists with specificed email
        elif users_collection.find_one({"email": form.email.data}) != None:
            flash("This email has already been used.")
            return render_template("signup.html", form=form)
            # finds if a user exists with specificed username
        elif users_collection.find_one({"_id": form.username.data}) != None:
            flash("Sorry, that username is already taken.")
            return render_template("signup.html", form=form)

        # adds new user to database, sends email, initiates new session,
        # redirects to myprofile.html
        else:
            # hash password
            pw_hash = bcrypt.generate_password_hash(form.password.data)
            # add user to wisdom.users db
            users_collection.insert(
                {
                    "_id": form.username.data,
                    "firstName": form.firstName.data,
                    "lastName": form.lastName.data,
                    "email": form.email.data,
                    "password": pw_hash,
                    "createdAt": datetime.datetime.now(),
                }
            )
            # creates new cookie session based on email
            session["email"] = form.email.data

            msg = Message(
                "Wisdom.ly account confirmation",
                # sender
                sender="*****@*****.**",
                # recipient
                recipients=[form.email.data],
            )

            msg.body = """
            %s, 
                Please authenticate your email by pressing this 'link'
                
            """ % (
                form.firstName.data
            )
            mail.send(msg)

            # redirects to custom profile based on session
            userData = users_collection.find({"email": session["email"]})
            return redirect(url_for("myprofile"))
Пример #7
0
def newUser():
    form = SignUp()
    if form.validate_on_submit():
        data = request.form
        newUser = User(username=data['username'], email=data['email'])
        newUser.set_password(data['password'])
        db.session.add(newUser)
        db.session.commit()
        return redirect(url_for('login'))
    return redirect(url_for('signup'))
Пример #8
0
def signUp():
    form = SignUp()
    if form.validate_on_submit():
        passHash = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        print(form.email.data, passHash)
        insertUser(form.email.data, passHash)
        return redirect('/')
    print(form.errors)
    return render_template('signUp.html', form=form)
Пример #9
0
def AddUser(request):
    if request.method == "POST":
        form = SignUp(request.POST)
        if form.is_valid():
            new_user = User.objects.create_user(**form.cleaned_data)
            login(request, new_user)
            return render(request, 'login/main.html', {})
    else:
        form = SignUp()
        return render(request, 'login/signup.html', {'form':form})
Пример #10
0
def signup():
    #adds page title and form
    page_title = "Sign Up"
    form = SignUp()
    #populate team dropdown
    try:
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            sql = "SELECT * FROM teamname;"
            cursor.execute(sql)
            teamname = cursor.fetchall()

    except:
        flash('database busy plesae try later')
        return redirect('/')

    if request.method == 'POST' and form.validate_on_submit():

        fullname = request.form['fullname']
        team = request.form['teamie']
        password = generate_password_hash(request.form['password'])
        email = request.form['email']
        profileImage = 'blank_profile.png'
        location = 4
        #check user e mail does not exsist in db

        try:
            with connection.cursor() as cursor:
                sql = "SELECT `email` FROM `users` WHERE `email`=%s"
                cursor.execute(sql, (email))
                result = cursor.fetchall()

                #checks email is not already in use

                if len(result) != 0:
                    flash('already registered')
                    return redirect('signup')
# add user to db

                else:
                    with connection.cursor() as cursor:
                        sql = "INSERT INTO `users` (`name`, `email`, `password`,`profileImage`,`teamId`,`locationId`) VALUES (%s, %s, %s, %s,%s,%s)"
                        cursor.execute(sql, (fullname, email, password,
                                             profileImage, team, location))
                        connection.commit()
                        flash('User created please login')
                        session['user'] = request.form['email']
                        return redirect('/mail')
        except:

            flash("An exception occurred")

    return render_template('signup.html',
                           form=form,
                           page_title=page_title,
                           teamname=teamname)
Пример #11
0
def signup():
    form = SignUp()
    if form.validate_on_submit():
        data = request.form
        newuser = user(username=data['username'], email=data['email'], login_counter = 0)
        newuser.set_password(data['password'])
        db.session.add(newuser)
        db.session.commit()
        flash('Account Succesfully Created!')
        return redirect(url_for('login'))
    return render_template('SignUp.html', form=form)
Пример #12
0
def signup():
  form = SignUp() # create form object
  if form.validate_on_submit():
    data = request.form # get data from form submission
    newuser = User(username=data['username'], email=data['email']) # create user object
    newuser.set_password(data['password']) # set password
    db.session.add(newuser) # save new user
    db.session.commit()
    flash('Account Created!')# send message
    return redirect(url_for('login'))# redirect to login page
  return render_template('signup.html', form=form) # pass form object to template
Пример #13
0
 def post(self,request):
     form = SignUp(request.POST)
     if form.is_valid():
         p1 = form.cleaned_data['password']
         p2 = form.cleaned_data['password1']
         if p1 != p2:
             return render(request, 'signup.html', {'form': form, 'error': True})
             #raise form.ValidationError("passwords do not match!!!")
         else:
             form.save()
             return HttpResponseRedirect('/thanks1/')
     #request.POST['password']=''
     return render(request,'signup.html',{'form':form})
Пример #14
0
def apply():
	form = SignUp()
	if form.validate_on_submit():
		try:
			filename = document.save(form.pdf_file.data)
			url = document.url(filename)
			user = User(email = form.email.data, full_name = form.name.data,
			    	    password = form.password.data, ssn = form.ssn.data)
			db.session.add(user)
			db.session.commit()
			flash('Your application has been submitted. You may now login but you will not be able to use the account until it is approved.')
			return redirect(url_for('home.homepage'))
		except:
			flash('Something went wrong during registration')
			return render_template('home/index.html')
	return render_template('home/apply.html', form = form)
Пример #15
0
def index():
    email = None
    result, err = None, None
    f_form = ForgotForm()
    s_form = SignUp()
    l_login = LoginForm()
    if l_login.email_login.data and l_login.validate_on_submit():
        result, err = login(l_login)
        l_login.email_login.data = ''
    elif f_form.email_f.data and f_form.validate_on_submit():
        result, err = forgot(f_form)
        f_form.email_f.data = ''
    elif s_form.email_s.data and s_form.validate_on_submit():
        result, err = signup(s_form)
        s_form.email_s.data = ''
    return result if result else render_template(
        'fc.html', f_form=f_form, s_form=s_form, login_form=l_login, error=err)
Пример #16
0
def signup():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = SignUp()
    if form.validate_on_submit():
        file = form.profilepic.data
        filename = uuid.uuid4().hex
        file.save(os.path.join(os.path.abspath("static/"),'photos', filename))
        user = User(username = form.username.data,
                    email = form.email.data,
                    fullname = form.fullname.data,
                    profilepic = filename
                    )
        user.set_password(form.password1.data)
        
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('login'))
    return render_template('signup.html', form=form)
Пример #17
0
def signup():
    form = SignUp()
    if form.validate_on_submit():
        data = request.form  # get data from form submission
        # added and indented
        try:
            newuser = User(username=data['username'],
                           email=data['email'])  # create user object
            newuser.set_password(data['password'])  # set password
            db.session.add(newuser)  # save new user
            db.session.commit()
            flash('Account Created!')  # send message
            return redirect(url_for('login'))  # redirect to login page
        # added
        except:
            flash('Account Exists')  # send message
            db.session.rollback()

    return render_template('signup.html', form=form)
Пример #18
0
def sign_up():
    """ Save new user info into Mongo Database """
    form = SignUp(csrf_enabled=False)

    name = []
    phone = []
    email = []
    occupation = []
    age = []
    description = []
    unique_id = []

    if request.method == "POST":

        name.append(form.name.data)
        phone.append(form.phone.data)
        email.append(form.email.data)
        occupation.append(form.occupation.data)
        age.append(form.age.data)
        description.append(form.description.data)
        unique_id.append(form.unique_id.data)

        # Save new user's image for retraining the face recognition model
        save_image_for_training(unique_id[0], name[0])

        new_entry = pd.DataFrame()

        new_entry["Name"] = name
        new_entry["Phone"] = phone
        new_entry["Email"] = email
        new_entry["Occupation"] = occupation
        new_entry["Age"] = age
        new_entry["Description"] = description
        new_entry["Unique ID"] = unique_id

        # Create new collection for users in app database and insert data
        collection = "users"
        db_cm = db[collection]
        data = new_entry.to_dict(orient='records')
        db_cm.insert(data)

        try:
            # Retrain model with new users
            print("Training KNN classifier...")
            train("static/train_test/train",
                  model_save_path="static/models/trained_knn_model.clf",
                  n_neighbors=None)
            print("Training complete!")
        except:
            print("Oh no, unable to train model.")

        status = "Agent assignment complete."
        return render_template("index.html", form=form, status=status)
    else:
        return render_template("index.html", form=form)
Пример #19
0
def sign_up():
	''' Set up a user account '''
	if g.user is not None and g.user.is_authenticated():
		flash('You are already logged in as '+ g.user.first_name+' '+g.user.last_name)
		return redirect(url_for('home'))
	form = SignUp()
	if form.validate_on_submit():

		if User.query.filter_by(email=form.email.data).count()==0: #ensure the email isn't already used.
			user = User(first_name = form.firstname.data,
				last_name=form.lastname.data,nickname = form.nickname.data, email=form.email.data,
				dob=form.dob.data, home=form.hometown.data, password=form.password1.data)
			db.session.add(user)
			db.session.commit()
			login_user(user)
			flash("You have successfully signed up. Welcome "+user.first_name)
			return redirect(url_for('home'))

		flash("This email address is already in use. Please enter a valid email address")
	return render_template('signup.html',form=form)
Пример #20
0
def register():
    form = SignUp()
    if request.method == 'POST' and form.validate_on_submit():
        name = request.form['username']
        email = request.form['email']
        pw = request.form['password']
        #setup database connection and cursor
        db = pymysql.connect(host='localhost',
                             user='******',
                             password='******',
                             database='rainbow')
        cursor = db.cursor()
        #sql command
        cursor.execute(
            "INSERT INTO Account (Type, Name, Email, Password) VALUES ('User', %s, %s, %s)",
            (name, email, pw))
        db.commit()

        flash(f'Account created for ' + name + '.', 'success')
        return redirect(url_for('home'))
    return render_template('sign_up.html', title='Sign Up', form=form)
Пример #21
0
def sign_up():
    """ Save new user info into Mongo Database """
    form = SignUp(csrf_enabled=False)

    name = []
    phone = []
    email = []
    occupation = []
    age = []
    description = []
    unique_id = []
    # image = []
    # face_encoding = []

    if request.method == "POST":

        name.append(form.name.data)
        phone.append(form.phone.data)
        email.append(form.email.data)
        occupation.append(form.occupation.data)
        age.append(form.age.data)
        description.append(form.description.data)
        unique_id.append(form.unique_id.data)

        # Save new user's image for retraining the face recognition model
        save_image_for_training(unique_id[0], name[0])

        new_entry = pd.DataFrame()

        new_entry["Name"] = name
        new_entry["Phone"] = phone
        new_entry["Email"] = email
        new_entry["Occupation"] = occupation
        new_entry["Age"] = age
        new_entry["Description"] = description
        new_entry["Unique ID"] = unique_id

        # Create new collection for users in app database and insert data
        collection = "users"
        db_cm = db[collection]
        data = new_entry.to_dict(orient='records')
        db_cm.insert(data)

        status="Agent assignment complete."
        return render_template("index.html", form=form, status=status)
    else:
        return render_template("index.html", form=form)
Пример #22
0
 def _signup():
     """Signup."""
     form = SignUp()
     if form.validate_on_submit():
         return "done."
     return render_template('signup.html', form=form)
Пример #23
0
 def get(self,request):
     f=SignUp(request.POST)
     k='Your Registration is Succesfull!!,please wait for approval'
     return render(request,'back.html', {'msg':k,'value':'back'})
Пример #24
0
def signup(request):
    form = SignUp()
    return render(request,'signup.html', {'form': form})
Пример #25
0
 def get(self,request,*args,**kwargs):
     form = SignUp()
     return render(request,'signup.html', {'form': form})
Пример #26
0
def signup():
    form = SignUp()
    return render_template('SignUp.html', form=form)
Пример #27
0
def signup():
    # Now, everything that you need to do for that particular
    # path of the web app is done under this function.
    up = SignUp()
    # As we have imported the 'forms.py' module in this module, we
    # create an object of the 'SignUp' class here to be able
    # to access all the direct or indirect attributes pertaining
    # to that class. Now, we can send this object to our html
    # to work with fields and labels, manipulate submitted
    # data, use validators, etc.
    if up.validate_on_submit():
        # validate_on_submit() is a function that checks if the data
        # entered by the user is valid according to the conditions that
        # we set on 'forms.py'. It is a function of the 'FlaskForm'
        # class that we inherited in our 'SignUp' class.
        hashed_password = bcrypt.generate_password_hash(up.Password.data)
        # Here, we are hashing the password that is sent by the user
        # from the webpage. For that, we use 'generate_password_hash',
        # which is a function of the 'flask_bcrypt' module which
        # , in some black box way, communicates with a different function
        # in the 'bcrypt' module to generate the required password hash.
        # We store that in a variable for later use.
        user = User(firstname=up.FirstName.data,
                    middlename=up.MiddleName.data,
                    lastname=up.LastName.data,
                    email=up.email.data,
                    username=up.Username.data,
                    password=hashed_password)
        # Here, we are creating an instance of the 'User' class that
        # we created above by providing the data entered by the user to the
        # respective attributes of the class. We specify the variables
        # because we are not sending them in order; specifically, we are
        # skipping over 'id' as it is automatically created internally.
        # For 'password', we evidently provide the 'hashed_password'
        # variable.
        db.session.add(user)
        # Analogous to 'git', we stage our instances before committing
        # them to the databse. This just provides extra degree of freedom
        # to the user in terms of the order of committing instances. You
        # only use it when necessary, but it is still good to have the
        # feature. 'session' is an attribute of the 'SQLAlchemy' class
        # and 'add' is a function of the 'sqlalchemy' library.
        db.session.commit()
        # This commits our 'user' instance or the data sent by the user
        # from the webpage to the database. Now that user has the ability
        # to start a session.
        flash(
            f'Account for {up.Username.data} has been created. Sign in from here.'
        )
        # The 'flash' function is used to return a string for one
        # request only i.e. after the string is seen once on a page,
        # we don't see it if we refresh it or specifically, we don't
        # see it if another request is made. This is especially useful
        # if we want to tell the user about their success or failure in
        # regards to the creation of their account on a pre-existing page
        # rather than creating a completely different page for it. But
        # if we use a pre-existing page whose purpose is not to only
        # show the message of success or failure, we want it to be a one
        # time thing only--thus, the usage of 'flash'.
        return redirect(url_for('login'))
        # The 'redirect' function is used to redirect the user to a
        # particular path. The argument is the URL address of the path.
        # If we don't want to type the whole URL, we can just use the
        # 'url_for' function which builds the URL pertaining to the
        # function given as argument for us.
    return render_template('signup.html', up=up)