Beispiel #1
0
def login():
    # YOUR SOLUTION HERE
    if request.method == 'GET':
        return render_template('login.html', error=request.args.get('error'))
    elif request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        users = get_users()

        # Check if username in database
        if username in users:
            password_encripted = hash_password(password)
            password_db = users[username]
            
            # Check if password matches
            if password_encripted == password_db:
                session['logged_in'] = username
                print ('Ok')
                return render_template('dashboard.html', title='Dashboard')
            else:
                print ('Nok')
                return redirect(url_for('login', error=True))
        else:
            return redirect(url_for('login', error=True))
    return render_template('login.html', title='Login')
def signup():
    '''
        Sign up view for new users, redirecting to  the RSS list page.
    '''
    if not session.get('logged_in'):

        form = LoginForm(request.form)

        if request.method == 'POST':

            username = request.form['username'].lower()
            password = hash_password(request.form['password'])
            email = request.form['email']

            if form.validate():

                if not is_user_key_take(username):

                    add_user(username, password, email)
                    session['logged_in'] = True
                    session['name'] = username
                    return json.dumps({'status': 'Signup successful'})

                return json.dumps({'status': 'Username taken'})

            return json.dumps({'status': 'User/Pass required'})

        return render_template('index.html', form=form)

    return redirect(url_for('login'))
Beispiel #3
0
    def authenticate(cls, username, password, password_salt):
        """TODO

        Args:
            username (str)
            password (str)

        Returns:
            User
        """
        user = cls.get_by_username(username)

        if user is None:
            return None
        if user.locked is True:
            return (
                None
            )  # TODO: Let the API consumer know and allow them to reset.
        if hash_password(password, password_salt) != user.password:
            user.failed_login_attempts += 1
            if user.failed_login_attempts >= 5:
                user.locked = True
            db.session.commit()
            return None
        else:
            user.failed_login_attempts = 0
            db.session.commit()
            return user
def _login(username, password):
    salt_query = """SELECT salt
                    FROM clients
                    WHERE username = ?
                    LIMIT 1"""
    cursor.execute(salt_query, (username,))
    auth_result = cursor.fetchone()

    if auth_result is None:
        return False

    pwd_hash, _ = hash_password(password, salt=auth_result['salt'])

    select_query = """SELECT id, username, balance, message
                      FROM clients
                      WHERE username = ? AND password = ?
                      LIMIT 1"""

    cursor.execute(select_query, (username, pwd_hash))
    user = cursor.fetchone()

    if(user):
        return Client(user[0], user[1], user[2], user[3])
    else:
        return False
Beispiel #5
0
 def register(email, password):
     user = User()
     user.email = email
     user.name = email
     user.password = helpers.hash_password(password)
     user.put()
     return user
def _login(username, password):
    salt_query = """SELECT salt
                    FROM clients
                    WHERE username = ?
                    LIMIT 1"""
    cursor.execute(salt_query, (username, ))
    auth_result = cursor.fetchone()

    if auth_result is None:
        return False

    pwd_hash, _ = hash_password(password, salt=auth_result['salt'])

    select_query = """SELECT id, username, balance, message
                      FROM clients
                      WHERE username = ? AND password = ?
                      LIMIT 1"""

    cursor.execute(select_query, (username, pwd_hash))
    user = cursor.fetchone()

    if (user):
        return Client(user[0], user[1], user[2], user[3])
    else:
        return False
def change_pass(new_pass, logged_user):
    update_sql = session.query(Clients).update({"password": new_pass})
    update_sql = """UPDATE clients
                    SET password = ?, salt = ?
                    WHERE id = ?"""
    pwd_hash, salt = hash_password(new_pass)

    cursor.execute(update_sql, (pwd_hash, salt, logged_user.get_id()))
Beispiel #8
0
    def __init__(self, username, password, password_salt, config=None):
        self.username = username.lower()
        self.password = hash_password(password, password_salt)
        self.failed_login_attempts = 0
        self.locked = False
        self.created = datetime.utcnow()

        db.session.add(self)
        db.session.commit()
def change_pass(new_pass, logged_user):
    update_sql = """UPDATE clients
                    SET password = ?, salt = ?
                    WHERE id = ?"""
    pwd_hash, salt = hash_password(new_pass)

    cursor.execute(update_sql,
                   (pwd_hash, salt, logged_user.get_id()))
    conn.commit()
Beispiel #10
0
def change_pass(new_pass, logged_user):
    update_sql = """UPDATE clients
                    SET password = ?, salt = ?
                    WHERE id = ?"""
    pwd_hash, salt = hash_password(new_pass)

    cursor.execute(update_sql,
                   (pwd_hash, salt, logged_user.get_id()))
    conn.commit()
Beispiel #11
0
    def find_or_create_user(self, request):
        user = Users.objects.filter(email=request.get('email')).first()
        if user:
            return user, 'invitation_email'

        user_details = UserDetails.objects.create(first_name=request.get('display_name'))
        data = {'id': generate_unique_code(), 'email': request.get('email'), 'display_name': request.get('display_name'),
            'user_detail_id': user_details.id, 'password': hash_password('sync#125'), 'is_password_change_required': True,
            'confirmation_code': get_confirmation_code(request.get('email')) }
        return Users.objects.create(**data), 'activation_email'
Beispiel #12
0
def create_mock_teams():
    conn = sqlite3.connect(db.DATABASE_NAME)
    c = conn.cursor()
    c.execute("INSERT INTO teams VALUES (?, ?, ?, ?)",
              ("test team 1", "test1", helpers.hash_password("test1"),
               "*****@*****.**"))
    c.execute("INSERT INTO teams VALUES (?, ?, ?, ?)",
              ("test team 2", "test2", helpers.hash_password("test2"),
               "*****@*****.**"))
    c.execute("INSERT INTO team_scores VALUES (?, ?, ?)",
              ("test team 1", 0, time.time()))
    c.execute("INSERT INTO team_scores VALUES (?, ?, ?)",
              ("test team 2", 0, time.time()))
    c.execute("INSERT INTO team_puzzles VALUES (?, ?, ?)",
              ("test team 1", False, False))
    c.execute("INSERT INTO team_puzzles VALUES (?, ?, ?)",
              ("test team 2", False, False))
    conn.commit()
    conn.close()
Beispiel #13
0
    def add_user_to_db(self, request):
        Users.params['firstName'] = request.get("firstName")
        Users.params['lastName'] = request.get("lastName")
        Users.params['userEmail'] = request.get("userEmail")
        password = hash_password(request.get("password"))
        Users.params['password'] = password

        query = "INSERT INTO users (firstName, lastName, userEmail, password) \
        VALUES (%(firstName)s, %(lastName)s, %(userEmail)s, %(password)s)"

        connect_db(query, Users.params)
    def register(self, username, password):
        if self.__is_registered(username) is not None:
            return False
        
        client = Client(username=username, 
                        password=hash_password(password), 
                        is_blocked=False,
                        blocked_until = None)

        self.__commit_changes([client])
        
        return True
def register(username, password):
    validator = get_validator(username)

    if not validator.is_valid(password):
        raise StrongPasswordException(messages.STRONG_PASSWORD)

    hashed_password, salt = hash_password(password)
    insert_sql = """INSERT INTO clients (username, password, salt)
                    VALUES (?, ?, ?)"""

    cursor.execute(insert_sql, (username, hashed_password, salt))
    conn.commit()
Beispiel #16
0
def register(username, password):
    validator = get_validator(username)

    if not validator.is_valid(password):
        raise StrongPasswordException(messages.STRONG_PASSWORD)

    hashed_password, salt = hash_password(password)
    insert_sql = """INSERT INTO clients (username, password, salt)
                    VALUES (?, ?, ?)"""

    cursor.execute(insert_sql, (username, hashed_password, salt))
    conn.commit()
Beispiel #17
0
def settings():
    if session.get('logged_in'):
        if request.method == 'POST':
            password = request.form['password']
            if password != "":
                password = helpers.hash_password(password)
            email = request.form['email']
            helpers.change_user(password=password, email=email)
            return json.dumps({'status': 'Saved'})
        user = helpers.get_user()
        return render_template('settings.html', user=user)
    return redirect(url_for('login'))
    def register(self, username, password):
        if self.__is_registered(username) is not None:
            return False

        client = Client(username=username,
                        password=hash_password(password),
                        is_blocked=False,
                        blocked_until=None)

        self.__commit_changes([client])

        return True
Beispiel #19
0
def valid_login(username, password):
    # username = request.form['username']
    # password = request.form['password']
    user_db = get_users()
    hsd_enterd_pw = hash_password(password)
    # check if user in db
    result = False
    if username in list(user_db.keys()):
        # check if hashed pw matches with db_pw
        if user_db[username] == hsd_enterd_pw:
            result = True
    return result
Beispiel #20
0
def reset_pass():
    form = ResetPasswordForm()
    email = session.get('email')
    if request.method == 'GET':
        return render_template('reset_password.html', title='Reset Password', form=form)

    else:

        response = table.get_item(Key={'email': email})
        user = response['Item']
        user['password'] = hash_password(form.password.data)
        table.put_item(Item=user)
    return redirect('/Prod/login')
Beispiel #21
0
def bootstrap():
    cleanup()
    """
        Adding bootstrap model objects to the database
    """

    # Seed an admin user, which equivalent to a normal user as for now
    user = Player(username="******", password_hash=hash_password("default"))
    user.put()

    # Seed 10 users and a game

    player_ids = []
    for i in range(0, 10):
        player = Player(username="******" + str(i), password_hash=hash_password("p" + str(i)))
        player_ids.append(player.put().id())

    player_names = player_ids[0:5]
    game_title = "Java"
    shuffle(player_names)
    players_to_join = [Player.get_by_id(player_id) for player_id in player_names]
    new_game = Game(title=game_title, num_player=len(players_to_join))
    new_game.put()
    for i in range(-1, len(players_to_join) - 1):
        killer = players_to_join[i]
        target = players_to_join[i + 1]
        if killer is not None and target is not None:
            GamePlayer(game=new_game, player=killer).put()
            GameHistory(killer=killer, target=target, game=new_game, is_complete=False, confirm_msg=msg_generator()).put()
        else:
            cleanup()
            print("Error in seeding!")

    names = ["Ken", "Rebecca", "Paul", "Sam", "Yulun"]
    for name in names:
        player = Player(username=name, password_hash=hash_password("p" + string.lower(name[0])))
        player.put()
Beispiel #22
0
def request_loader(request):
    username = request.form.get('username')
    ####################
    #  FOR SUPER USER  #
    ####################
    if username == "admin" and request.form['password'] == "admin":
        return User(username)
    tm = team.get_team_by_username(username)
    if not tm:
        return

    user = User(username, tm)

    if helpers.hash_password(request.form['password']) == tm.code:
        return user
    return
    def register(self, user, password):
        validator = get_validator(user)

        if not validator.is_valid(password):
            raise StrongPasswordException("Your password is not strong enough")

        hashed_password, salt = hash_password(password)

        current_user = self.session.query(Clients.username).\
                        filter(Clients.username == user).first()

        if current_user is not None:
            raise ClientAlreadyRegistered('Client already registered')

        client = Clients(username=user, password=hashed_password, salt=salt)
        self.__commit_object(client)
def create_user(data):
    create_user_rule(data)
    repo = AuthRepository()
    inputs = {
        'id': helpers.generate_unique_code().__str__(),
        'email': data['email'],
        'age': str(data['age']),
        'weight': str(data['weight']),
        'height': str(data['height']),
        'activity': data['activity'],
        'gendar': data['gendar'],
        'password': helpers.hash_password(data['password']),
        'name': data['name'],
    }
    user = repo.store(User, inputs)
    return user
Beispiel #25
0
def register():
    """Let users register"""

    if request.method == "POST":

        #Check if all fields were filled in
        if not request.form.get("username"):
            return render_template("sorry.html", error="Username field not filled in")

        elif not request.form.get("password"):
            return render_template("sorry.html", error="Password field not filled in")

        elif not request.form.get("passwordConfirm"):
            return render_template("sorry.html", error="Password confirmation field not filled in")

        #Get all fields from the form
        username = request.form.get("username")
        password = request.form.get("password")
        passwordConfirm = request.form.get("passwordConfirm")

        ## DEBUG:
        print(username, file=sys.stderr)
        print(password, file=sys.stderr)
        print(passwordConfirm, file=sys.stderr)

        #Check form for correctness
        if not password == passwordConfirm:
            return render_template("sorry.html", error="Passwords did not match")

        # Check whether we have an entry with that username
        userrow = db.execute("SELECT * FROM users WHERE username = :username", {"username": username})
        user_exists = userrow.first()
        if not user_exists:
            # If we do not have an entry with that username, store the username and hashed password in the database
            hashedPassword = hash_password(password)
            db.execute("INSERT INTO users (username, passwordhash) VALUES (:username, :hashedPassword)",
                {"username": username, "hashedPassword": hashedPassword})
            db.commit()
            return render_template("registercomplete.html")

        # If a row with that username was found, apologize to user
        else:
            return render_template("sorry.html", error="That username is taken.")

    # GET-method for register: present register form
    else:
        return render_template("register.html")
    def login(self, username, password):
        user = self.__is_registered(username)

        if user is None:
            return "USER_NOT_EXISTS"

        if not self.__can_login(user):
            return "USER_BLOCKED"
    
        password = hash_password(password)

        if user.password == password:
            self.__success_login_attempt(user)
            return user
        
        self.__failed_login_attempt(user)
        return "FAILED_LOGIN"
    def login(self, username, password):
        user = self.__is_registered(username)

        if user is None:
            return "USER_NOT_EXISTS"

        if not self.__can_login(user):
            return "USER_BLOCKED"

        password = hash_password(password)

        if user.password == password:
            self.__success_login_attempt(user)
            return user

        self.__failed_login_attempt(user)
        return "FAILED_LOGIN"
Beispiel #28
0
def signup():
    if not session.get('logged_in'):
        form = LoginForm(request.form)
        if request.method == 'POST':
            username = request.form['username'].lower()
            password = helpers.hash_password(request.form['password'])
            email = request.form['email']
            if form.validate():
                if not helpers.username_taken(username):
                    helpers.add_user(username, password, email)
                    session['logged_in'] = True
                    session['username'] = username
                    return json.dumps({'status': 'Signup successful'})
                return json.dumps({'status': 'Username taken'})
            return json.dumps({'status': 'User/Pass required'})
        return render_template('login.html', form=form)
    return redirect(url_for('login'))
def register():
    """ Registers a user """

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

    username = request.form.get("username").lower()

    row = DB.execute("SELECT username FROM users WHERE username=:username", {
        "username": username
    }).fetchone()

    if row:
        message = "Username already exists"
        return render_template("error.html", message=message)

    password = request.form.get("password")
    confirm_password = request.form.get("confirm-password")

    if password != confirm_password:
        message = "The two password fields don't match"
        return render_template("error.html", message=message)

    if is_invalid(password):
        message = "Not a valid password"
        detailed_message = """ A password is valid if it is
                            at Least 8 character long,
                             contains atleast 1 lowercase character,
                             contains atleast 1 uppercase character,
                             contains atleast 1 special character """
        return render_template("error.html",
                               message=message,
                               detailed_message=detailed_message)

    password = hash_password(password)

    DB.execute(
        "INSERT INTO users(username, password) VALUES(:username, :password)", {
            "username": username,
            "password": password
        })
    DB.commit()

    session["username"] = username

    return redirect("/")
    def post(self):
        args_list = ['email', 'password']

        data = request.get_json()
        if not check_request(data, args_list):
            return error_response

        user = users.find_one({
            'email': data['email'],
            'password': hash_password(data['password'])
        })
        if not user:
            return 'Invalid email/password', 401

        _id = user['_id']
        session['id'] = _id.binary

        return '', 200
Beispiel #31
0
def create_user():

    form = RegistrationForm()
    if request.method == 'GET':
        return render_template('register.html', title='Register', form=form)

    else:
        if form.validate_on_submit():

            user_data = {'id': generate_uid(), 'fullname': form.username.data, 'email': form.email.data,
                         'password': hash_password(form.password.data)}
            if table.get_item(Key={'email': form.email.data}):
                flash('User with email address already exists', 'danger')
                return redirect('/Prod/register')

            table.put_item(Item=user_data)
            flash('user has been created', 'success')
            return redirect('/Prod/login')
        return render_template('register.html', title='Register', form=form)
Beispiel #32
0
def login():
    if request.method == "GET":
        print(request.args.get("error"))
        return render_template("login.html", error=request.args.get("error"))
    elif request.method == "POST":
        users = get_users()
        attempted_password = hash_password(request.form["password"])

        try:
            username = request.form["username"]
            stored_password = users[username]
        except KeyError:
            return redirect(url_for("login", error=True))

        if stored_password == attempted_password:
            session["username"] = request.form["username"]
            return redirect(url_for("dashboard"))
        else:
            return redirect(url_for("login", error=True))
Beispiel #33
0
def register():
    if not session.get('logged_in'):
        form = LoginForm(request.form)
        if request.method == 'POST':
            username = request.form['username'].lower()
            password = helpers.hash_password(request.form['password'])
            email = request.form['email']
            c1 = "#360033"
            c2 = "#0b8793"
            if form.validate():
                if not helpers.username_taken(username):
                    helpers.add_user(username, password, email, c1, c2)
                    session['logged_in'] = True
                    session['username'] = username
                    return json.dumps({'status': 'Register successful'})
                return json.dumps({'status': 'Username taken'})
            return json.dumps({'status': 'Both fields required'})
        return render_template('login.html', form=form)
    return redirect(url_for('login'))
def login():
    """ Facilitates login for a user """

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

    username = request.form.get("username").lower()
    password = hash_password(request.form.get("password"))

    user = DB.execute("SELECT * FROM users WHERE username=:username", {
        "username": username
    }).fetchone()

    if user is None or user["password"] != password:
        message = "Invalid username/password"
        return render_template("error.html", message=message)

    session["username"] = user["username"]

    return redirect("/")
    def post(self):
        ''' Submit a account creation request, to be reviewed by an admin to verify
            whether the requester is a student '''

        args_list = [
            'first_name', 'last_name', 'email', 'serial_number', 'description',
            'password'
        ]

        data = request.get_json()
        if not check_request(data, args_list):
            return error_response

        if 'student_id' not in request.files:
            return error_response

        student_id = request.files['student_id']
        if not student_id.filename or student_id.filename[-4:] not in [
                '.png', '.jpg'
        ]:
            return error_response

        for arg in ['email', 'serial_number']:
            if users.find_one({arg: data[arg]}):
                return f'An account with the same {arg} exists', 400

            if requests.find_one({arg: data[arg]}):
                return f'An account creation request with the same {arg} exists', 400

        student_id.filename = urandom(16).hex() + student_id.filename[-4:]
        student_id.save(f'student_ids/{student_id.filename}')

        data['student_id'] = student_id.filename
        data['password'] = hash_password(data['password'])
        data['status'] = 'pending'
        data['type'] = 'account'

        requests.insert_one(data)

        return 'Account creation request submitted succesfully, an admin will contact you soon', 200
Beispiel #36
0
def user_seeder():
    user_data = {
        'id': '1b3b4f40-2e7c-4a66-b1f1-0f19ff113369',
        'display_name': 'AahhoDev',
        'email': '*****@*****.**',
        'password': helpers.hash_password('feedr123'),
        'created_at': datetime.datetime.now(),
        'is_god': True,
        'is_active': True,
        'created_at': datetime.datetime.now(),
        'updated_at': datetime.datetime.now(),
    }
    user_details = {
        'id': 1,
        'user_id': '1b3b4f40-2e7c-4a66-b1f1-0f19ff113369',
        'first_name': 'AahhoDev',
        'last_name': None,
        'created_at': datetime.datetime.now(),
        'updated_at': datetime.datetime.now(),
    }
    store(User, user_data)
    store(UserDetail, user_details)
Beispiel #37
0
def login():
    form = forms.LoginForm(request.form)
    if request.method == 'GET':
        return render_template("login.html", form=form)
    if request.method == 'POST' and form.validate():
        username = form.username.data
        ####################
        #  FOR SUPER USER  #
        ####################
        if username == "admin" and form.password.data == "admin":
            flask_login.login_user(User(username))
            return redirect(url_for('index'))

        tm = team.get_team_by_username(username)
        if tm and helpers.hash_password(form.password.data) == tm.code:
            user = User(username, tm)
            flask_login.login_user(user)
            return redirect(url_for('index'))

    return render_template("login.html",
                           form=form,
                           error="Invalid username/password!")