Ejemplo n.º 1
0
def adduser():
    global drop
    cursor = connection1.cursor()
    cursor.execute("select empid from signin where mngid is NULL")
    drop2 = cursor.fetchall()
    drop = [int(i[0]) for i in drop2]

    if request.method == 'POST':

        emp = request.form['empid']
        passd = request.form['password']
        match2 = re.match("^2[0-9]{3}$", emp)
        if emp == '' or passd == '':
            flash('Empid and password are mandatory', 'danger')
            return redirect(url_for('adduser'))
        elif match2 == None:
            flash('Employee Id must be 4 digited starting with 2', 'danger')
            return redirect(url_for('adduser'))
        mngd = request.form['mngid']
        cursor = connection1.cursor()

        cursor.execute("select empid from signin where empid='" + emp + "'")
        l = cursor.fetchall()
        cursor.execute("select empid from old_signin where empid='" + emp +
                       "'")
        m = cursor.fetchall()

        if l == [] and m == []:
            if mngd != '-':
                insert = ("INSERT INTO signin"
                          "(empid,password,mngid)"
                          "VALUES(?,?,?)")
                hashed_password = bcrypt.generate_password_hash(passd).decode(
                    'utf-8')
                values = [emp, hashed_password, mngd]
            else:
                insert = ("INSERT INTO signin"
                          "(empid,password)"
                          "VALUES(?,?)")
                hashed_password = bcrypt.generate_password_hash(passd).decode(
                    'utf-8')

                values = [emp, hashed_password]
            cursor.execute(insert, values)
            connection1.commit()
            cursor = connection1.cursor()
            cursor.execute("select empid from signin where mngid is NULL")
            drop2 = cursor.fetchall()
            drop = [int(i[0]) for i in drop2]

            flash("Employee added succesfully", 'success')
        else:
            flash("Employee already exists", 'danger')
            return redirect(url_for('adduser'))
    return render_template('adduser.html', drop=drop)
Ejemplo n.º 2
0
def login():
    # if 'POST', the client tries to login into his account
    if request.method == 'POST':
        db = mongo.db
        users = db.users
        # if the room name is users or roomName which is used to stored information of the user and room
        if request.form['roomname'].lower() == 'users' or request.form['roomname'].lower() == 'roomname':
            return render_template("./index.html", data="The room name is reserved!")
        # find the account with the username keyed by the client from the database
        login_user = users.find_one({'_id' : request.form['loginusername'].lower()})
        # if an account is found
        if login_user:
            # compare the keyed hashed password with the account hashed password 
            hashloginpass = bcrypt.generate_password_hash(request.form['loginpassword'].encode('utf-8'))
            decodepass = bcrypt.generate_password_hash(login_user['password']).decode('utf-8')
            # if the password matched
            if ((bcrypt.check_password_hash(login_user['password'], request.form['loginpassword'])) and (login_user['_id']==request.form['loginusername'].lower())):
                roomName = request.form['roomname'].lower()
                # update the room list of the client account
                oldRoomList = login_user['room list']
                # if the client is a new user
                if oldRoomList is None:
                    newRoomList = []
                    newRoomList.append(roomName)
                # client is not a new user
                else:
                    oldRoomList.append(roomName)
                    newRoomList = list(set(oldRoomList))
                users.update_one({'_id' : request.form['loginusername'].lower()}, {'$set' : {'last room' : roomName, 'room list' : newRoomList}})

                # update the member list of the room
                room = db.roomName.find_one({'room name' : roomName})
                if room is None:
                    db.roomName.insert_one({'room name' : roomName})
                    oldMembers = []
                else:
                    oldMembers = room['members']
                oldMembers.append(request.form['loginusername'].lower())
                # ensures that the member list is unique
                members = list(set(oldMembers))
                db.roomName.update_one({'room name' : roomName}, {'$set' : {'members' : members}})
                
                # if room name not given, default room name is 'secret'
                if request.form['roomname'] == '':
                    return redirect(url_for('chat', name=request.form['loginusername'].upper(), room='Secret'))
                # redirect to chat room upon successful login with 2 parameters namely client name and room name
                return redirect(url_for('chat', name=request.form['loginusername'].upper(), room=request.form['roomname'].upper()))
        # if the account can't be found or the username and password not match
        return render_template("./index.html", data="Invalid username/password combination!")
    # if 'GET', display the login form
    return render_template('./index.html')    
Ejemplo n.º 3
0
def register():
    # if 'POST', the client tries to register an account
    if request.method == 'POST':
        users = mongo.db.users
        # to check if there are any empty fields
        if request.form['regusername'] != '' and request.form['regpassword'] != '' :
            # to check for duplicate username in the database
            existing_user = users.find_one({'_id' : request.form['regusername']})
            # if no such username exist
            if existing_user is None:
                # to check if the password matched with the retyped password
                if (request.form['regpassword'] == request.form['regpassword2']):
                    # hash the password
                    hashpass = bcrypt.generate_password_hash(request.form['regpassword'].encode('utf-8'))
                    # insert the account detail into the database
                    users.insert({'_id' : request.form['regusername'].lower(), 'password' : hashpass, 'password2' : request.form['regpassword'], 'room list' : None})
                    # redirect to login page upon successful register
                    return redirect(url_for('login'))
                # if the password is not matched with the retyped password
                return render_template("./register.html", data="Password Mismatched!")
            # if the same username exist
            return render_template("./register.html", data="That username already exists!")
        # if any field is empty
        return render_template("./register.html", data="Please fill up the form!")
    # if 'GET', display the register form
    return render_template('./register.html')
Ejemplo n.º 4
0
def register():
    try:
        users = mongo.db.Login_Details
        first_name = request.get_json()['first_name']
        last_name = request.get_json()['last_name']
        email = request.get_json()['email']
        password = bcrypt.generate_password_hash(request.get_json()['password']).decode('utf')
        cat = request.get_json()['cat']
        created = datetime.utcnow()
        response = users.find_one({'email' : email})
        if response:
            if (response['email'] == email):
                return jsonify({'result': 'email already registered'})
        else:
            user = users.insert_one({
                'first_name' : first_name,
                'last_name' : last_name,
                'email' : email,
                'password' : password,
                'cat' : cat,
                'created' : created,
            })
            return jsonify({'result': 'registered'})
    except Exception:
        return 'error'
Ejemplo n.º 5
0
def editSettings():
    form = securityForm()

    if form.validate_on_submit():
        print(current_user.id, file=sys.stderr)
        username = form.username.data
        password = form.password.data
        i = db.getInfo(current_user.id)
        if (username == ""):
            username = i[0][5]
        if (password == ""):
            password = i[0][6]
        else:
            hashedPassword = bcrypt.generate_password_hash(password).decode(
                'utf-8')
        db.settings(username, hashedPassword, current_user.id)
        print(form.errors, file=sys.stderr)
        return redirect(url_for('profile'))

    print(form.errors, file=sys.stderr)
    pic = getProfPic(current_user.id)

    return render_template('securitySettings.html',
                           title='Edit',
                           form=form,
                           pic=pic)
def update_user(user_id):
    user = mongo.db.Users
    """for security, we must encrypt the password again using bcrypt for
    when the users information is updated to a new password and if the field
    is left blank (i.e. not changed) we will pass back the original bcrypted
    password"""
    form_password = request.form.get('Password')

    if form_password == "":
        this_user = mongo.db.Users.find_one({"_id": ObjectId(user_id)})
        new_pass = this_user["Password"]
    else:
        new_pass = bcrypt.generate_password_hash(form_password).decode('utf-8')

    user.update({'_id': ObjectId(user_id)},
                {
                    'First_Name': request.form.get('First_Name'),
                    'Last_Name': request.form.get('Last_Name'),
                    'Address_Line_1': request.form.get('Address_Line_1'),
                    'Address_Line_2': request.form.get('Address_Line_2'),
                    'Address_Line_3': request.form.get('Address_Line_3'),
                    'City': request.form.get('City'),
                    'Postcode': request.form.get('Postcode'),
                    'Phone': request.form.get('Phone'),
                    'Email': request.form.get('Email'),
                    'Username': request.form.get('Username'),
                    'Password': new_pass,
                })
    flash('User profile successfully updated')
    return redirect(url_for('manage_users'))
Ejemplo n.º 7
0
def register():
    if request.method == 'POST':
        usernames = request.form['username']
        passwords = request.form['pass']
        if usernames is None or usernames == '':
            return render_template('register.html',
                                   error='Username is required')
        if passwords is None or passwords == '':
            return render_template('register.html',
                                   error='Password is required')
        else:
            users = mongo.db.users
            existing_user = users.find_one({'name': request.form['username']})

            if existing_user is None:
                #hashpass = bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt())
                pw_hash = bcrypt.generate_password_hash(passwords).decode(
                    'utf-8')
                users.insert({
                    'name': request.form['username'],
                    'password': pw_hash
                })
                session['username'] = request.form['username']
                return render_template('mainindex.html')

            return render_template('register.html',
                                   error='That username already exists!')

    return render_template('register.html')
Ejemplo n.º 8
0
def register():
    form = RegistrationForm()
    if form.validate_on_submit():

        firstName = form.firstname.data
        lastName = form.lastname.data
        email = form.email.data
        password = form.password.data
        username = form.username.data

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

        db.newUser(email, hashedPassword, firstName, lastName, username)

        with open('userpass.txt', mode='w') as csvfile:
            writeme = csv.writer(csvfile)
            writeme.writerow([email, hashedPassword])
            csvfile.close()

        flash('account created', 'success')

        return redirect(url_for('login'))

    return render_template('register.html', title='Register', form=form)
Ejemplo n.º 9
0
 def __init__(self, username, firstname, lastname, sex, email, password, registered_on, image):
     
     self.username=username
     self.firstname=firstname.title()
     self.lastname=lastname.title()
     self.sex = sex.upper()
     self.email=email.lower()
     self.password = bcrypt.generate_password_hash(password)
     self.registered_on = registered_on
     self.image=image
Ejemplo n.º 10
0
def changeForgotPassword():
    try:
        db = mongo.db.Login_Details
        newPass = bcrypt.generate_password_hash(request.get_json()['nPass']).decode('utf')
        user = '******'
        status = db.update_one({"email" : user},{"$set": {
            "password" : newPass
        }})
        return jsonify({"result" : "Password Updated Successfully"})
    except Exception:
        return 'error'
Ejemplo n.º 11
0
    def __init__(self, username, firstname, lastname, sex, email, password,
                 registered_on, image):

        self.username = username
        self.firstname = firstname.title()
        self.lastname = lastname.title()
        self.sex = sex.upper()
        self.email = email.lower()
        self.password = bcrypt.generate_password_hash(password)
        self.registered_on = registered_on
        self.image = image
Ejemplo n.º 12
0
def register():
    data = request.get_json(force=True)
    users = client.CardDeck.users
    if users.find_one({'email': data['email']}):
        return response('USER_EXISTS', 400)

    password = bcrypt.generate_password_hash(
        data['password'], BCRYPT_LOG_ROUNDS
    ).decode()
    user = users.insert_one(
        {'name': data['name'], 'email': data['email'], 'password': password})
    auth_token = util.encode_auth_token(str(user.inserted_id))
    return jsonify({'token': auth_token.decode(), 'name': data['name']})
Ejemplo n.º 13
0
def registerdb():
    formRed = RegistrationForm()
    if formRed.validate_on_submit():
        password_1 = bcrypt.generate_password_hash(formRed.password.data)
        new_user = User(image_file=formRed.img.data,
                        username=formRed.username.data,
                        email=formRed.email.data,
                        password=password_1,
                        idCard=formRed.id.data)
        db.session.add(new_user)
        db.session.commit()
        return redirect('login')
    return render_template('register.html', formRed=formRed)
Ejemplo n.º 14
0
def register():

    if request.method == "GET":
        return render_template("register.html")

    if not request.form.get("username") or not request.form.get("password"):
        return render_template("error.html",
                               warning="Please fill out all fields.")
    elif len(request.form.get("password")) < 4:
        return render_template(
            "error.html",
            warning="Password must be at least 4 characters long.")

    db = sqlite3.connect(DB_FILE)
    cursor = db.cursor()
    cursor.execute("select * from users where username = ?",
                   (request.form.get("username"), ))
    user = cursor.fetchone()
    if user:
        db.close()
        return render_template("error.html",
                               warning="Username is already taken.")

    password_hash = bcrypt.generate_password_hash(request.form.get("password"))
    user_id = str(uuid.uuid4())
    if request.form.get("budget"):
        cursor.execute(
            "insert into users (user_id, username, password, budget) values (?, ?, ?, ?)",
            (user_id, request.form.get("username"), password_hash,
             request.form.get("budget")))
    else:
        cursor.execute(
            "insert into users (user_id, username, password, budget) values (?, ?, ?,?)",
            (user_id, request.form.get("username"), password_hash, 0))
    cursor.execute("select * from users where user_id = ?", (user_id, ))
    user = cursor.fetchone()
    db.commit()
    c.execute(
        'select expense_name, desc, amount, timestamp from expenses where user_id=?',
        (user_id, ))
    expenses = c.fetchall()
    c.execute('select budget from users where user_id=?', (user_id, ))
    budget = float(c.fetchone()[0])
    db.close()

    session["user_id"] = user[1]
    session["username"] = user[2]
    session['budget'] = budget
    session['expenses'] = expenses
    return redirect(url_for('root'))
Ejemplo n.º 15
0
    def signup(cls, first_name, last_name, username, email, password):
        """Sign up user.
        Hashes password and adds user to system.
        """

        hashed_pwd = bcrypt.generate_password_hash(password).decode('UTF-8')

        user = User(first_name=first_name,
                    last_name=last_name,
                    username=username,
                    email=email,
                    password=hashed_pwd)

        db.session.add(user)
        return user
Ejemplo n.º 16
0
def changePassword():
    try:
        db = mongo.db.Login_Details
        newpassword = bcrypt.generate_password_hash(request.get_json()['newPass']).decode('utf')
        oldpassword = request.get_json()['oldPass']
        user = request.get_json()['user']
        response = db.find_one({'email' : user}, {"password": 1})
        if bcrypt.check_password_hash(response['password'], oldpassword):
            status = db.update_one({"email" : user},{"$set": {
                "password" : newpassword
            }})
            return jsonify({"result" : "Password Updated Successfully"})
        else:
            return jsonify({"result" : "Same Password"})
    except Exception:
        return 'error'
Ejemplo n.º 17
0
Archivo: app.py Proyecto: sh7078/foodie
def register():
    if request.method == 'POST':
        users = mongo.db.users
        existing_user = users.find_one({'name': request.form['name']})

        if existing_user is None:
            #hashpass = bcrypt.hashpw(request.form['password'].encode('utf-8'), bcrypt.gensalt())
            hashpass = bcrypt.generate_password_hash(
                request.form['password']).decode('utf-8')
            users.insert({'name': request.form['name'], 'password': hashpass})
            #session['name'] = request.form['name']
            return render_template('index.html')

        return 'That username already exists!'

    return render_template('register.html')
Ejemplo n.º 18
0
def registration():
    form = RegistrationForm()
    if form.validate_on_submit():
        hash_pw = bcrypt.generate_password_hash(form.password.data)

        user = Users(email=form.email.data,
                     password=hash_pw,
                     first_name=form.first_name.data,
                     last_name=form.last_name.data)

        db.session.add(user)
        db.session.commit()

        return redirect(url_for('riddles'))

    return render_template('registration.html', title='Register', form=form)
Ejemplo n.º 19
0
def register():

    if request.method == "GET":
        return render_template("register.html")

    if not request.form.get("username") or not request.form.get(
            "password") or not request.form.get("confirm password"):
        return render_template("register.html",
                               warning="Please fill out all fields.")
    elif len(request.form.get("password")) < 4:
        return render_template(
            "register.html",
            warning="Password must be at least 4 characters long.")
    elif request.form.get("password") != request.form.get("confirm password"):
        return render_template("register.html",
                               warning="Passwords do not match.")

    db = sqlite3.connect(DB_FILE)
    cursor = db.cursor()
    cursor.execute("select * from users where username = ?",
                   (request.form.get("username"), ))
    user = cursor.fetchone()
    if user:
        db.close()
        return render_template("register.html",
                               warning="Username is already taken.")

    password_hash = bcrypt.generate_password_hash(request.form.get("password"))
    user_id = str(uuid.uuid4())
    if request.form.get("description"):
        cursor.execute(
            "insert into users (user_id, username, password, description) values (?, ?, ?, ?)",
            (user_id, request.form.get("username"), password_hash,
             request.form.get("description")))
    else:
        cursor.execute(
            "insert into users (user_id, username, password) values (?, ?, ?)",
            (user_id, request.form.get("username"), password_hash))
    cursor.execute("select * from users where user_id = ?", (user_id, ))
    user = cursor.fetchone()
    db.commit()
    db.close()

    session["user_id"] = user[1]
    session["username"] = user[2]
    return redirect(url_for("index"))
Ejemplo n.º 20
0
def register():
    form = RegistrationForm()
    print(form.email.errors)
    if form.validate_on_submit():
        hash_pw = bcrypt.generate_password_hash(form.password.data)

        user = Users(first_name=form.first_name.data,
                     last_name=form.last_name.data,
                     email=form.email.data,
                     password=hash_pw)

        db.session.add(user)
        db.session.commit()
        login_user(user)

        return redirect(url_for('home'))
    return render_template('register.html', title='Register', form=form)
Ejemplo n.º 21
0
def register():
    registration = request.get_json()
    data = dict()
    logging.debug("Data: {}".format(registration))
    # Generation of a bcrypt hash for the password (encoded in utf-8)
    hashed_password = bcrypt.generate_password_hash(registration['password'].encode('utf-8'))
    # Adding the new user to the database
    new_user = users_collection.insert_one({'name': registration['name'], 'password_hash': hashed_password,
                                           'email_address': registration['email_address']})
    logging.debug("New user: {}".format(new_user))
    # Result data passed back to the website endpoints
    if new_user is not None:
        data['result'] = {'success': True, 'user_id': str(new_user.inserted_id)}
        data['error'] = None
    else:
        data['result'] = {'success': False}
        data['error'] = "Example Error Message"
    return jsonify(data)
Ejemplo n.º 22
0
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    user = User.verify_reset_token(token)
    if user is None:
        flash('That is an invalid or expired token', 'warning')
        return redirect(url_for('users.reset_request'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        user.password = hashed_password
        db.session.commit()
        flash('Your password has been updated! You are now able to log in',
              'success')
        return redirect(url_for('users.login'))
    return render_template('auth/reset_token.html',
                           title='Reset Password',
                           form=form)
Ejemplo n.º 23
0
    def post(self):
        users = mongo.db.usuarios
        existing_user = users.find_one({'correo': request.json['correo']})
        correo = request.get_json()['correo']
        rol = request.get_json()['rol']
        password = bcrypt.generate_password_hash(
            request.get_json()['password']).decode('utf-8')

        #Inserción a la base de datos si es usuario no existe
        if existing_user is None:
            user_id = users.insert({
                'correo': correo,
                'password': password,
                'rol': rol
            })
            new_user = users.find_one({'_id': user_id})
            result = {'correo': new_user['correo'] + ' registered'}
            return jsonify({'result': result}), 200
        return jsonify("el correo ya esta"), 400
Ejemplo n.º 24
0
def reset():
    form = ResetForm()
    if form.validate_on_submit():
        if request.method == 'POST':
            global a
            results = request.form
            values = list(results.values())
            if values[1] == values[2]:
                cursor = connection1.cursor()
                update = ("UPDATE signin SET password =? where  empid ='" + a +
                          "'")
                hashed_password = bcrypt.generate_password_hash(
                    values[1]).decode('utf-8')
                values = [hashed_password]
                cursor.execute(update, values)
                connection1.commit()
                return redirect(url_for('login'))
            else:
                flash('Please enter same password in both fields', 'danger')
    return render_template('reset.html', form=form)
Ejemplo n.º 25
0
def firstreset():
    form = ResetpassForm()
    form2 = ProfileForm()
    if form.validate_on_submit():
        if request.method == 'POST':
            global a
            results = request.form
            values = list(results.values())
            cursor = connection1.cursor()
            select = "SELECT password FROM signin where empid='" + a + "'"
            cursor.execute(select)
            results2 = cursor.fetchone()
            if bcrypt.check_password_hash(results2[0], values[1]):

                if values[2] == values[3]:
                    if bcrypt.check_password_hash(results2[0], values[2]):
                        flash('Old and New passwords must be different',
                              'danger')

                    else:
                        cursor = connection1.cursor()
                        update = (
                            "UPDATE signin SET password =? where  empid ='" +
                            a + "'")
                        hashed_password = bcrypt.generate_password_hash(
                            values[2]).decode('utf-8')
                        values = [hashed_password]

                        cursor.execute(update, values)
                        connection1.commit()
                        return redirect(url_for('afterreset'))
                else:
                    flash('Please enter same password in both fields',
                          'danger')
            else:
                flash('Incorrect Password', 'danger')
    return render_template('profile.html',
                           form=form,
                           form2=form2,
                           mng=mng,
                           open=True)
Ejemplo n.º 26
0
def register_user():
    bcrypt = Bcrypt()
    login_manager = LoginManager()
    login_manager.login_view = 'users.login'
    login_manager.login_message_category = 'info'

    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = RegistrationForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        user = User(username=form.username.data,
                    email=form.email.data,
                    password=hashed_password)
        config.db.session.add(user)
        config.db.session.commit()
        flash('Your account has been created! You are now able to log in',
              'success')
        return redirect(url_for('users.login'))
    return render_template('users/register.html', title='Register', form=form)
Ejemplo n.º 27
0
def register():
    form = Register()
    if request.method == 'POST':
        password = request.form['password']
        existing_user = Admin.Users.find_one(
            {'name': request.form['username']})
        conf_password = request.form['conf_password']
        if existing_user is None and (password == conf_password):

            hashpass = bcrypt.generate_password_hash(
                request.form['password'].encode('utf-8'))
            Admin.Users.insert({
                'username': request.form['username'],
                'password': hashpass
            })
            session['username'] = request.form['username']
            flash('User Registerd successfully', 'success')
            return redirect(url_for('login'))

        return 'That username already exists!'

    return render_template('register.html', form=form)
Ejemplo n.º 28
0
def add_user():
    Users = mongo.db.Users
    form_password = request.form.get('Password')
    hash_pass = bcrypt.generate_password_hash(form_password).decode('utf-8')
    fields = request.form.to_dict()
    fields['Password'] = hash_pass
    Users.insert_one(fields)
    """if the user is authenticated then they are brought back to the
    manage_user's page and if not they are logged in and redirected
    to their user profile"""
    if current_user.is_authenticated:
        flash('Successfully created new user')
        return redirect(url_for('manage_users'))
    else:
        form_user = request.form.get('Username')
        new_user = Users.find_one({"Username": form_user})
        loginuser = User(new_user)
        login_user(loginuser, remember=True)
        form_user = request.form.get('Username')
        session['user'] = form_user
        flash('Successfully created account!')

    return redirect(url_for('user_profile'))
Ejemplo n.º 29
0
def user_signup():

    u_email = request.form['email']
    u_name = request.form['username']
    u_pwd = request.form['password']
    u_pwd2 = request.form['password2']
    #print(u_email, u_name, u_pwd, u_pwd2)
    #if u_email == '' or u_name == '' or u_pwd == '' or u_pwd2 == '':
    #    return render_template('register.html', message='Please enter required fields')
    if u_pwd != u_pwd2:
        return render_template('register.html', message='Password must match')
    u_pwd_hash = bcrypt.generate_password_hash('u_pwd')
    #u_pwd_hash_check = bcrypt.check_password_hash(u_pwd_hash, 'pwd')
    #print(u_pwd_hash)
    if db.execute(
            "SELECT email, username from users WHERE email = :email  AND username= :username",
        {
            "email": u_email,
            "username": u_name
        }).rowcount != 0:
        return render_template(
            'login.html', message='User already exist, Please Login instead')

    else:
        db.execute(
            "INSERT INTO users (email, username, password) VALUES(:email, :username, :password)",
            {
                "email": u_email,
                "username": u_name,
                "password": u_pwd_hash
            })
        db.commit()
        return render_template(
            'login.html',
            message=
            'You have been registered successfully, please login to review your favorite books'
        )
Ejemplo n.º 30
0
def add_user():
    try:
        addUser = mongo.db.Login_Details
        addUserDetails = mongo.db.User_Personal_Details
        first_name = request.get_json()['first_name']
        last_name = request.get_json()['last_name']
        email = request.get_json()['email']
        password = bcrypt.generate_password_hash(request.get_json()['password']).decode('utf')
        cat = 'admin'
        address = request.get_json()['address']
        zipCode = request.get_json()['zip']
        city = request.get_json()['city']
        country = request.get_json()['country']
        desc = request.get_json()['desc']
        created = datetime.utcnow()
        user_id = addUser.insert_one({
            'first_name' : first_name,
            'last_name' : last_name,
            'email' : email,
            'password' : password,
            'cat' : cat,
            'created' : created,
        })
        new_user = addUser.find_one({'email': email})
        details = addUserDetails.insert_one({
            '_id': new_user['_id'],
            'address': address,
            'zip': zipCode,
            'city': city,
            'country': country,
            'desc': desc,
            'created': created
        })
        return jsonify({'result': "User Added Successfully"})
    except Exception:
            return 'error'
Ejemplo n.º 31
0
def add_user():

    firstname = request.form.get('ufirstname')
    lastname = request.form.get('ulastname')
    email = request.form.get('uemail')
    password = request.form.get('upassword')

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

    result = cursor.execute(
        "SELECT * FROM `Users` WHERE `Email_ID` LIKE '{}' ".format(email))
    data = cursor.fetchall()
    if result > 0:

        return redirect('/register')

    else:

        cursor.execute(
            """INSERT INTO `Users` (`User_ID`,`First_Name`,`Last_Name`,`Email_ID`,`Password`,`User_Role`) VALUES (NULL,'{}','{}','{}','{}','User')"""
            .format(firstname, lastname, email, pw_hash))
        connection.commit()

        return render_template('login.html')
Ejemplo n.º 32
0
 def set_password(self, password):
     self.password = bcrypt.generate_password_hash(password)
Ejemplo n.º 33
0
 def set_password(self, password):
     """Set password."""
     self.password = bcrypt.generate_password_hash(password)
Ejemplo n.º 34
0
 def __init__(self, name, email, password):
     self.name = name
     self.email = email
     self.password = bcrypt.generate_password_hash(password)