Beispiel #1
0
    def login(self, params):
        email = params.get('Email')
        password = params.get('password')
        result = ""

        query = f'SELECT * FROM User  ' \
                f'where email = "{email}"'
        result_set = self.conn.execute(query).fetchone()
        print(result_set)
        if verify_password(result_set['password'], password):
            access_token = create_access_token(identity={
                'Name': result_set['Name'],
                'Email': result_set['Email']
            })
            result = {
                'data': {
                    'access_token': access_token,
                    'userData': {
                        'id': result_set['_id'],
                        'Name': result_set['Name'],
                        'Email': result_set['Email'],
                        'CreatedOn': result_set['CreatedOn']
                    }
                }
            }
        else:
            result = {"error": "Invalid email and password"}
            print(result)
        return result
Beispiel #2
0
def get_auth_token():

	print flask.request.form.__dict__

	# Extract params
	email	= flask.request.form['email']
	password = flask.request.form['password']

	print email, password

	# Find the user
	user_profile = mongo.db.user_profiles.find_one({ 'email': email })

	# Return the result
	if user_profile is not None:
		if auth.verify_password(user_profile, password):
			token = auth.generate_auth_token(email)
			return app.utils.json_result({
				'success': 1,
				'result' : {
					'token'	  : token,
					'userProfile': user_profile,
				},
			})
		else:
			return app.utils.json_result({
				'success': 0,
				'error'  : 'email/password incorrect',
			})
	else:
		return app.utils.json_result({
			'success': 0,
			'error'  : 'user not found',
		})
Beispiel #3
0
 def validate(name, password):
     query = User.query \
                 .with_entities(User.password) \
                 .filter_by(db.func.lower(name) == db.func.lower(User.name))
     user = query.first()
     if user:
         return auth.verify_password(user.password, password)
     return False
Beispiel #4
0
    async def mutate(root, info, phone, password):
        phone164 = Phone(phone=phone).phone
        user = await get_volunteer(phone164)
        if not user:
            raise GraphQLError("Нет такого пользователя")
        if not verify_password(password, user.password):
            raise GraphQLError("Неверный пароль")

        return GetJWT.create_tokens(info, user.uid)
Beispiel #5
0
    def login():
        login_data = request.get_json(cache=False)
        email = login_data['email']
        passwd = login_data['password']

        u = User.query.filter_by(email=email).first()
        if u and u.is_active and verify_password(passwd, u.password):
            login_user(u)
            return dict(user=u.to_dict(), token=get_auth_token(u))
        return abort(401)
    def post(self):
        """
        POST method for the /signup action.
        Validates the inputs and redirects the user to the welcome page if
        validations are ok.
        If not, render the signup page, keeping the username and email values,
        and show error messages.
        """
        input_username = self.request.get("username")
        input_password = self.request.get("password")
        input_verify = self.request.get("verify")
        input_email = self.request.get("email")

        params = dict(username=input_username, email=input_email)

        valid_username = verify_username(input_username)
        valid_password = verify_password(input_password)
        valid_email = verify_email(input_email)
        match = verify_match(input_password, input_verify)
        error = False

        if not valid_username:
            params["invalid_username"] = "******"
            error = True
        else:
            if User.by_name(input_username):
                params["invalid_username"] = "******"
                error = True

        if not valid_password:
            params["invalid_password"] = "******"
            error = True

        if not match:
            params["not_match"] = "Your password didn't match."
            error = True

        if not valid_email:
            params["invalid_email"] = "That's not a valid email."
            error = True

        if error:
            self.render("signup.html", **params)

        else:
            encrypted_password = utils.make_pw_hash(input_username,
                                                    input_password)
            user = User(username=input_username,
                        pw_hash=encrypted_password,
                        email=input_email)
            user.put()

            self.set_secure_cookie("user_id", str(user.key().id()))

            self.redirect("/welcome")
Beispiel #7
0
def login():
    if request.method == 'POST':
        input_password = request.form['password']
        db_password = data_manager.login(request.form['user_name'])
        if auth.verify_password(input_password, db_password['password']):
            session['user_name'] = request.form['user_name']
            user_name = session['user_name']
            user_id = data_manager.get_user_id_from_user_name(user_name)
            session['id'] = user_id['id']
            return redirect(url_for('list', user_name=user_name, user_id=session['id']))
        else:
            flash("Wrong password")
    return render_template('login.html')
Beispiel #8
0
def login_user():

    auth = request.authorization
    if (auth is None) or (auth.username is None) or (auth.password is None):
        return make_response('Could not login!', 401, {'WWW-Authenticate' : 'Basic realm="Login Required"'})
    else:
        username = auth.username

    if not verify_password(username, auth.password):
        return make_response('Could not verify!', 401, {'WWW-Authenticate' : 'Basic realm="Incorrect username or password"'})
    else:
        user = db.session.query(User).filter_by(username=username).scalar()
        return make_response(str(user.id), 200)
Beispiel #9
0
def delete_user(username, password):
    message = h.msg()
    if auth.verify_password(username, password):
        password = auth.create_password_hash(password)
        query = "DELETE FROM users WHERE name = ? and password = ?"
        qvals = (username, password)
        if h.db_do(query, qvals, sys_db):
            message['success'] = True
        else:
            message['errors'].append(1003)
    else:
        message['errors'].append(1002)
    return message
Beispiel #10
0
def auth():
    username = request.json['username']
    password = request.json['password']

    user = user_dao.get_by_username(username)

    if user is None:
        raise UnauthorizedException('Bad username or password')

    if not verify_password(user.password, password):
        raise UnauthorizedException('Bad username or password')

    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token), 200
Beispiel #11
0
def logon(username, d):
    message = h.msg()
    valid = auth.verify_password(username, d[u'password'])
    if valid:
        new_token = auth.create_session_token(username)
        current = int(time.time())
        query = "UPDATE users SET token = ?, time = ? WHERE name = ?"
        qvals = (new_token, current, username)
        if h.db_do(query, qvals, sys_db):
            message['success'] = True
            message['token'] = new_token
        else:
            message['errors'].append(1003)
    else:
        message['errors'].append(1002)
    return message
Beispiel #12
0
    def post(self):
        with locks.global_lock:
            session_id = self.get_cookie('session_id')
            session = auth.load_session(session_id)
            if session is None:
                self.redirect('/login')
                return

            old_password = self.get_argument('old_password', None)
            password = self.get_argument('password', None)
            password_c = self.get_argument('password_c', None)
            if old_password is None or old_password == '':
                self.write(
                    render_template(
                        'change_password_error.html',
                        error_message=lc.get('no_old_password'),
                        session=session,
                    ))
                return
            if not auth.verify_password(session.username, old_password):
                self.write(
                    render_template(
                        'change_password_error.html',
                        error_message=lc.get('invalid_old_password'),
                        session=session,
                    ))
                return
            if password is None or password == '':
                self.write(
                    render_template(
                        'change_password_error.html',
                        error_message=lc.get('no_password'),
                        session=session,
                    ))
                return
            if password != password_c:
                self.write(
                    render_template(
                        'change_password_error.html',
                        error_message=lc.get('password_c_failed'),
                        session=session,
                    ))
                return

            auth.update_password(session.username, password)
            self.write(
                render_template('change_password_ok.html', session=session))
async def login(form_data: UsernamePasswordForm):
    user_in_db = get_user_by_username(form_data.username)

    if not user_in_db:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail='User not found with this username.',
        )

    verified = verify_password(form_data.password, user_in_db.hashed_password)
    if not verified:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail='Password is wrong.',
        )

    return user_in_db
Beispiel #14
0
def login():
    """Route for handling the logging in of user

    Returns:
        redirect response -- if successfull log in (attaches generated
        token to session)
    """
    form = forms.LoginForm()
    if form.validate_on_submit():
        if not auth.verify_password(form.email.data, form.password.data):
            flash(message='Username and password are invalid.')
        else:
            token = g.user.generate_auth_token()
            session['token'] = token.decode('ascii')
            flash(
                message=f"You've been logged in with token {session['token']}")
            return redirect(url_for('my_todos'))
    return render_template('login.html', form=form)
Beispiel #15
0
 def test_02_equality(self, client):
     hash = auth.hash_password("test")
     assert auth.verify_password(hash, "test")
Beispiel #16
0
def login(options):
    print("Attempting to login:"******"no email")
    if 'pass' not in options:
        print("no pass")

    given_email = options['email']
    given_password = options['pass']

    print(given_email)
    print(given_password)

    #Connect to the User Database
    client = boto3.client('rds-data')
    print("Connecting to table...")
    #Check if the user does not exist in the database
    existing_user = client.execute_statement(
        secretArn=constants.SECRET_ARN,
        database=constants.DB_NAME,
        resourceArn=constants.ARN,
        sql="SELECT email FROM UserData WHERE email = '%s';" % (given_email))
    print("Checking if user exists...")
    if (existing_user['records'] == []):
        print("user DNE")
        constants.ERR = "User DNE"
        constants.STATUS_CODE = 404
        return

    #Get password from existing user and if does not match return a 400 http
    print("User exists! Acquiring password...")
    existing_password = client.execute_statement(
        secretArn=constants.SECRET_ARN,
        database=constants.DB_NAME,
        resourceArn=constants.ARN,
        sql="SELECT pass FROM UserData WHERE email = '%s';" % (given_email))
    print("Checking password...")
    if not auth.verify_password(
            existing_password['records'][0][0]['stringValue'], given_password):
        constants.ERR = "Password DNE"
        constants.STATUS_CODE = 404
        return

    #Get user type from Database
    print("Password verified. Checking perms...")
    user_type = client.execute_statement(
        secretArn=constants.SECRET_ARN,
        database=constants.DB_NAME,
        resourceArn=constants.ARN,
        sql="SELECT type FROM UserData WHERE email = '%s';" % (given_email))

    user_type = user_type['records'][0][0]['longValue']
    if user_type == 1:
        user_type = constants.GROWER
    elif user_type == 2:
        user_type = constants.RESEARCHER
    else:
        user_type = constants.PUBLIC_USER
    token = create_token.rand_token()

    #Return success
    print("Done!")
    constants.RES = {'token': str(token), 'user': str(user_type)}
    return
Beispiel #17
0
 def test_verify_password_no_user(self):
     with self.app:
         self.app.g.user = None
         result = auth.verify_password('fake', 'password')
         self.assertFalse(result)
Beispiel #18
0
 def test_verify_password_correct(self):
     with self.app:
         self.app.g.user = None
         result = auth.verify_password('test3', 'password')
         self.assertTrue(result)
 def test_hashed_password(self):
     hashed_pwd = get_password_hash(self.pwd)
     self.assertTrue(verify_password(self.pwd, hashed_pwd))
     self.assertNotEquals(hashed_pwd, self.hashed_pwd)
 def test_plain_password(self):
     self.assertTrue(verify_password(self.pwd, self.hashed_pwd))
Beispiel #21
0
 def test_verify_password_with_g_user(self):
     with self.app:
         self.app.g.user = self.user
         result = auth.verify_password('test3', 'password')
         self.assertTrue(result)