Esempio n. 1
0
def test_get_playbooks(client):
    without_login = client.get('/api/playbook/all')
    authenticate(client)
    playbooks = client.get('/api/playbook/all').json
    logout(client)
    assert without_login.status_code == 302
    assert isinstance(playbooks['playbooks'], list)
Esempio n. 2
0
def test_get_inventory(client):
    without_login = client.get('/api/inventory/all')
    authenticate(client)
    room = client.get('/api/inventory/all').json
    logout(client)
    assert without_login.status_code == 302
    assert isinstance(room['rooms'], list)
Esempio n. 3
0
def test_change_password(client):
    # TODO: Fix the change password repetition code
    without_login = client.post('/change',
                                data={"password": "******",
                                      "new_password": "******",
                                      "new_password_confirm": "new_password"})

    authenticate(client)
    new_password = client.post(
        '/change',
        data={
            "password": "******",
            "new_password": "******",
            "new_password_confirm": "new_password",
        }
    )
    password = client.post(
        '/change',
        data={
            "password": "******",
            "new_password": "******",
            "new_password_confirm": "password",
        }
    )
    logout(client)
    assert without_login.status_code == 302
    print new_password.data
    assert '/#/settings/user' in new_password.location
    assert password.status_code == 302
    assert '/#/settings/user' in password.location
Esempio n. 4
0
def test_save_playbook(client):
    without_login = client.post('/api/playbook/save')
    wrong_method = client.get('/api/playbook/save')
    authenticate(client)
    change_pb = client.post('/api/playbook/get', data={
        'key': 1,
    }).json
    change_pb['name'] = 'Modified initial setup'
    change_pb['description'] = 'Modified description'
    save_pb = client.post('/api/playbook/save', data=change_pb).json
    check_pb = client.post('/api/playbook/get', data={
        'key': 1,
    }).json
    wrong_id = client.post('/api/playbook/save', data={
        'key': 0,
        'name': 'Not Good',
        'description': 'This is a test of a non valid id'
    }).json
    logout(client)
    assert without_login.status_code == 302
    assert wrong_method.status_code == 405
    assert save_pb['messageMode'] == 0
    assert wrong_id['messageMode'] == 1
    assert check_pb['name'] == 'Modified initial setup'
    assert check_pb['description'] == 'Modified description'
    assert isinstance(check_pb['tasks'], list)
Esempio n. 5
0
	def decorated(*args, **kwargs):
		auth = request.authorization
		if not auth:
			return authenticate()
		elif not check_auth(auth.username, auth.password):
			return authenticate()
		return f(*args, **kwargs)
Esempio n. 6
0
def test_get_all(client):
    without_login = client.get('/api/user/all')
    authenticate(client)
    user_login = client.get('/api/user/all')
    logout(client)
    users = user_login.json
    assert without_login.status_code == 302
    assert 2 == len(users['users'])
Esempio n. 7
0
    def process_request(self, request):
        """
        Writes the signed_request into the Session
        """
        fb = get_session(request)
        setattr(request, 'fb_session', fb)
        application = get_app_dict()

        logger.debug('Request Method = %s\n, AccessToken=%s' % (request.method, fb.access_token))

        if 'feincms' in settings.INSTALLED_APPS:
            # if feincms is installed, try to get the application from the page
            from facebook.feincms.utils import get_application_from_request
            page_app = get_application_from_request(request)
            if application:
                application = get_app_dict(page_app)

        # Temporary OAuth2.0 fix due to missing access_token in cookie sr:
        if 'access_token' in request.GET:
            fb.store_token(request.GET.get('access_token'))

        # default POST/GET request from facebook with a signed request
        if 'signed_request' in request.POST:
            parsed_request = parseSignedRequest(request.POST['signed_request'], application['SECRET'])
            logger.debug(u'got signed_request from facebook: %s' % parsed_request)
            if 'user' in parsed_request:
                language = parsed_request['user']['locale']
                logger.debug('language: %s' %language)
                request.LANGUAGE_CODE = language
                translation.activate(language)
            fb.signed_request = parsed_request
            logger.debug('stored signed_request')
            expires = None
            # rewrite important data
            if 'oauth_token' in parsed_request:
                expires = datetime.fromtimestamp(float(parsed_request['expires']))
                fb.store_token(parsed_request['oauth_token'], expires)
            elif 'access_token' in parsed_request:
                expires = datetime.fromtimestamp(float(parsed_request['expires']))
                fb.store_token(parsed_request['access_token'], expires)
            else:
                #The chance is good that there is already a valid token in the session. Remove it.
                fb.store_token(None)

            if 'user_id' in parsed_request:
                fb.user_id = parsed_request['user_id']

            else:
                logger.debug("Signed Request didn't contain public user info.")
            if expires:
                logger.debug('Signed Request issued at: %s' % datetime.fromtimestamp(float(parsed_request['issued_at'])))
        
        # auth via callback from facebook
        elif 'code' in request.GET and 'facebook' in request.META.get('HTTP_REFERER', u''):
            authenticate(request.REQUEST['code'], fb, application,
                         request.build_absolute_uri().split('?')[0] \
                            .replace(application['CANVAS-URL'], application['CANVAS-PAGE']))
def test_custom_post_change_view(client):
    authenticate(client)
    response = client.post('/change', data={
        'password': '******',
        'new_password': '******',
        'new_password_confirm': 'newpassword'
    }, follow_redirects=True)

    assert b'Profile Page' in response.data
Esempio n. 9
0
def test_multiple_role_required(client):
    for user in ("*****@*****.**", "*****@*****.**"):
        authenticate(client, user)
        response = client.get("/admin_and_editor", follow_redirects=True)
        assert b'Home Page' in response.data
        client.get('/logout')

    authenticate(client, '*****@*****.**')
    response = client.get("/admin_and_editor", follow_redirects=True)
    assert b'Admin and Editor Page' in response.data
Esempio n. 10
0
def test_user_deleted_during_session_reverts_to_anonymous_user(app, client):
    authenticate(client)

    with app.test_request_context('/'):
        user = app.security.datastore.find_user(email='*****@*****.**')
        app.security.datastore.delete_user(user)
        app.security.datastore.commit()

    response = client.get('/')
    assert b'Hello [email protected]' not in response.data
Esempio n. 11
0
def test_roles_accepted(client):
    for user in ("*****@*****.**", "*****@*****.**"):
        authenticate(client, user)
        response = client.get("/admin_or_editor")
        assert b'Admin or Editor Page' in response.data
        logout(client)

    authenticate(client, "*****@*****.**")
    response = client.get("/admin_or_editor", follow_redirects=True)
    assert b'Home Page' in response.data
Esempio n. 12
0
def test_categories(client):
    without_login = client.get('/api/task/categories')
    authenticate(client)

    categories = client.get('/api/task/categories').json

    logout(client)
    assert without_login.status_code == 302
    assert isinstance(categories, dict)
    assert isinstance(categories['categories'], list)
def test_context_processors(client, app):
    @app.security.forgot_password_context_processor
    def forgot_password():
        return {"foo": "bar"}

    response = client.get("/reset")
    assert b"bar" in response.data

    @app.security.login_context_processor
    def login():
        return {"foo": "bar"}

    response = client.get("/login")
    assert b"bar" in response.data

    @app.security.register_context_processor
    def register():
        return {"foo": "bar"}

    response = client.get("/register")
    assert b"bar" in response.data

    @app.security.reset_password_context_processor
    def reset_password():
        return {"foo": "bar"}

    response = client.get("/reset")
    assert b"bar" in response.data

    @app.security.change_password_context_processor
    def change_password():
        return {"foo": "bar"}

    authenticate(client)
    response = client.get("/change")
    assert b"bar" in response.data

    @app.security.send_confirmation_context_processor
    def send_confirmation():
        return {"foo": "bar"}

    response = client.get("/confirm")
    assert b"bar" in response.data

    @app.security.mail_context_processor
    def mail():
        return {"foo": "bar"}

    with app.mail.record_messages() as outbox:
        client.post("/reset", data=dict(email="*****@*****.**"))

    email = outbox[0]
    assert "bar" in email.html
Esempio n. 14
0
def test_category(client):
    without_login = client.post('/api/task/category')
    authenticate(client)

    category = client.post('/api/task/category',
                           data={'name': 'cloud'}).json
    not_valid_form = client.post('/api/task/category').json
    logout(client)
    assert without_login.status_code == 302
    assert isinstance(category['modules'], list)
    assert category['category_name'] == 'cloud'
    assert isinstance(not_valid_form, dict)
Esempio n. 15
0
def test_basic_custom_forms(app, sqlalchemy_datastore):
    class MyLoginForm(LoginForm):
        email = StringField('My Login Email Address Field')

    class MyRegisterForm(RegisterForm):
        email = StringField('My Register Email Address Field')

    class MyForgotPasswordForm(ForgotPasswordForm):
        email = StringField(
            'My Forgot Email Address Field',
            validators=[
                email_required,
                email_validator,
                valid_user_email])

    class MyResetPasswordForm(ResetPasswordForm):
        password = StringField('My Reset Password Field')

    class MyChangePasswordForm(ChangePasswordForm):
        password = PasswordField('My Change Password Field')

    app.security = Security(app,
                            datastore=sqlalchemy_datastore,
                            login_form=MyLoginForm,
                            register_form=MyRegisterForm,
                            forgot_password_form=MyForgotPasswordForm,
                            reset_password_form=MyResetPasswordForm,
                            change_password_form=MyChangePasswordForm)

    populate_data(app)
    client = app.test_client()

    response = client.get('/login')
    assert b'My Login Email Address Field' in response.data

    response = client.get('/register')
    assert b'My Register Email Address Field' in response.data

    response = client.get('/reset')
    assert b'My Forgot Email Address Field' in response.data

    with capture_reset_password_requests() as requests:
        response = client.post('/reset', data=dict(email='*****@*****.**'))

    token = requests[0]['token']
    response = client.get('/reset/' + token)
    assert b'My Reset Password Field' in response.data

    authenticate(client)

    response = client.get('/change')
    assert b'My Change Password Field' in response.data
Esempio n. 16
0
def test_get_user(client):
    user = {
        "admin": True,
        "email": "*****@*****.**",
        "key": 1,
        "username": "******"
    }
    without_login = client.get('/api/user/get')
    authenticate(client)
    user_login = client.get('/api/user/get')
    logout(client)
    assert without_login.status_code == 302
    assert user == user_login.json
Esempio n. 17
0
def test_trackable_flag(app, client):
    e = '*****@*****.**'
    authenticate(client, email=e)
    logout(client)
    authenticate(client, email=e, headers={'X-Forwarded-For': '127.0.0.1'})

    with app.app_context():
        user = app.security.datastore.find_user(email=e)
        assert user.last_login_at is not None
        assert user.current_login_at is not None
        assert user.last_login_ip == 'untrackable'
        assert user.current_login_ip == '127.0.0.1'
        assert user.login_count == 2
Esempio n. 18
0
def test_get_playbook(client):
    wrong_method = client.get('/api/playbook/get')
    without_login = client.post('/api/playbook/get')
    authenticate(client)
    check_pb = client.post('/api/playbook/get', data={
        'key': 1,
    }).json
    logout(client)
    assert without_login.status_code == 302
    assert wrong_method.status_code == 405
    assert check_pb['name'] == 'Initial setup'
    assert check_pb['description'] == 'Hardening of the operative system'
    assert isinstance(check_pb['tasks'], list)
Esempio n. 19
0
def test_set_unauthorized_handler(app, client):
    @app.security.unauthorized_handler
    def unauthorized():
        app.unauthorized_handler_set = True
        return 'unauthorized-handler-set', 401

    app.unauthorized_handler_set = False

    authenticate(client, "*****@*****.**")
    response = client.get("/admin", follow_redirects=True)

    assert app.unauthorized_handler_set is True
    assert b'unauthorized-handler-set' in response.data
    assert response.status_code == 401
Esempio n. 20
0
def test_trackable_with_multiple_ips_in_headers(app, client):
    e = '*****@*****.**'
    authenticate(client, email=e)
    logout(client)
    authenticate(client, email=e, headers={
        'X-Forwarded-For': '99.99.99.99, 88.88.88.88'})

    with app.app_context():
        user = app.security.datastore.find_user(email=e)
        assert user.last_login_at is not None
        assert user.current_login_at is not None
        assert user.last_login_ip == 'untrackable'
        assert user.current_login_ip == '88.88.88.88'
        assert user.login_count == 2
Esempio n. 21
0
def test_delete_rooms(client):
    without_login = client.post('/api/inventory/delete')
    authenticate(client)
    delete = client.post('/api/inventory/delete', data={
        'key': 1
    }).json
    fail = client.post('/api/inventory/delete', data={
        'key': 1
    }).json

    logout(client)
    assert without_login.status_code == 302
    assert delete['messageMode'] == 0
    assert fail['messageMode'] == 1
Esempio n. 22
0
def test_unauthorized_access_with_referrer(client, get_message):
    authenticate(client, '*****@*****.**')
    response = client.get('/admin', headers={'referer': '/admin'})
    assert response.headers['Location'] != '/admin'
    client.get(response.headers['Location'])

    response = client.get('/admin',
                          headers={'referer': 'http://localhost/admin'})
    assert response.headers['Location'] != '/admin'
    client.get(response.headers['Location'])

    response = client.get('/admin',
                          headers={'referer': '/admin'},
                          follow_redirects=True)
    assert response.data.count(get_message('UNAUTHORIZED')) == 1
Esempio n. 23
0
def test_delete_task(client):
    without_login = client.post('/api/task/delete')
    authenticate(client)

    delete = client.post('/api/task/delete', data={
        'key': 1
    }).json
    wrong_id = client.post('/api/task/delete', data={
        'key': 0
    }).json
    delete_playbook(client)
    logout(client)
    assert without_login.status_code == 302
    assert delete['messageMode'] == 0
    assert wrong_id['messageMode'] == 1
Esempio n. 24
0
def test_login_with_bcrypt_enabled(app, sqlalchemy_datastore):
    init_app_with_options(app, sqlalchemy_datastore, **{
        'SECURITY_PASSWORD_HASH': 'bcrypt',
        'SECURITY_PASSWORD_SALT': 'salty'
    })
    response = authenticate(app.test_client(), follow_redirects=True)
    assert b'Home Page' in response.data
Esempio n. 25
0
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        username = request.form["username"]
        password = request.form["password"]
        if request.form['b']:
            if request.form['b'] == "login_tutee":
                user_type = "tutee"
            else:
                user_type = "tutor"
            #print(request.form)
            #print(user_type)
            user = authenticate(username, user_type, password, db)
            #print(user)
            if user:
                #print("UR A USER")
                # Loops over dictionary, creates new session element for each key
                for key in user.keys():
                    session[key] = user[key]
                session["logged_in"] = True
                flash("Welcome, " + session['first_name'])
                return redirect("homepage")
            else:
                flash("Your username or password is incorrect")
                return render_template("index.html")
Esempio n. 26
0
def index():
    if request.method=="GET":
        return render_template("index.html")
    else: 
        button = request.form['button']
        if button == "logout":
            return render_template("logout.html")
        if button == "go!":
            city=request.form['city']
            shirt=request.form['shirt']
            shorts=request.form['shorts']
            sweater=request.form['sweater']
            jacket=request.form['jacket']
            hat=request.form['hat']
            umbrella=request.form['umbrella']
            d = {'city':city,
                 'shirt':shirt,
                 'shorts':shorts,
                 'sweater':sweater,
                 'jacket':jacket,
                 'hat':hat,
                 'umbrella':umbrella}
            return render_template("backEnd.html",d=d)
        else:
            uname=request.form['username']
            pword=request.form['password']
            if utils.authenticate(uname,pword):
                return render_template("weather.html")
            else:
                return render_template("index.html")
Esempio n. 27
0
def login_register():
    if request.method == "GET":
        if "un" in session and session["un"] != 0:
            user = session["un"]
            return redirect(url_for("home"))
        else:
            return render_template("home.html", unlogged="You are not currently logged in.")
    else:
        # button = request.form['button']
        if "in_username" in request.form:
            user = request.form["in_username"]
            passwd = request.form["in_password"]
            if utils.authenticate(user, passwd):
                session["un"] = user
                session["pw"] = passwd
                return redirect(url_for("blog"))
            else:
                error = "INVALID USERNAME AND/OR PASSWORD"
                return render_template("home.html", error=error)
        else:
            user = request.form["regis_username"]
            passwd = request.form["regis_password"]
            # conn = sqlite3.connect('bloginator.db')
            # c = conn.cursor()
            # c.execute('select * from users where username="******"')
            # r = c.fetchall()
            # conn.commit()
            if utils.newUser(user, passwd):
                success = "Account Created!"
                session["un"] = user
                session["pw"] = passwd
                return redirect(url_for("blog"))
            else:
                failure = "There is already an account with this username"
                return render_template("home.html", created=failure)
Esempio n. 28
0
def login():
    if request.method == "GET":
        users = db.users.find()
        count = 0
        for u in users:
            if u['logged_in'] == True:
                count += 1
        return render_template("login.html", logged_in = count)
    else:
        if request.form["b"] == "Start Poopin'":
            user = authenticate(request.form["email"], request.form["password"], db)
            if user:
                # Loops over dictionary, creates new session element for each key
                for key in user.keys():
                    session[key] = user[key]
                print "Welcome, " + session['first_name']
                return redirect("home")
            else:
                flash("Your username or password is incorrect")
                return redirect('login')
        elif request.form["b"] == "Cancel":
            return redirect("login")
        elif request.form["b"] == "Sign Up":
            return redirect("register")
        elif request.form["b"] == "About":
            return redirect("about")
Esempio n. 29
0
def index():
    if "logged_in" not in session:
        session["logged_in"] = False
    if "user" not in session:
        session["user"] = "******"
    if request.method == "GET":
        return render_template("index.html", log="", s=session)
    if request.method == "POST":
        button = request.form["button"]
        username = request.form["username"]
        password = request.form["password"]
        if button == "Login":
            result = utils.authenticate(username, password)
            if result == "success":
                currentUser = username
                session["user"] = username
                session["logged_in"] = True
                session["posts"] = utils.getPosts()
                return redirect("/posts")
            elif result == "noUser":
                return render_template("index.html", log="noUser", s=session)
            else:
                return render_template("index.html", log="fail", s=session)
        else:
            return "bye"
Esempio n. 30
0
def test_addition_identity_attributes(app, sqlalchemy_datastore):
    init_app_with_options(app, sqlalchemy_datastore, **{
        'SECURITY_USER_IDENTITY_ATTRIBUTES': ('email', 'username')
    })
    client = app.test_client()
    response = authenticate(client, email='matt', follow_redirects=True)
    assert b'Hello [email protected]' in response.data
Esempio n. 31
0
def login():
    if 's' in session:
        return redirect(url_for("profile"))

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

    else:
        name = request.form['username']
        passwd = request.form['password']

        if utils.authenticate(name, passwd):
            session['s'] = name
            return redirect(url_for("profile"))
        else:
            return render_template("login.html")
Esempio n. 32
0
def login(message='',logout=False):
    if request.method== "GET":
	    if 'user' in session and session['user'] != '':
		return(render_template("login.html",message='Already logged in.',logout=True))
	    else:
        	return(render_template("login.html",message=message))
    else:
        uname=request.form['username']
        pword = request.form['password']
	if not utils.user_exists(uname):
		return(render_template("login.html",message="User does not exist."))
        elif utils.authenticate(uname,pword): # checks if pword matches uname in database
	    session['user'] = uname # set current user 
            return redirect(url_for('profile', username=uname))
        else:
            return(render_template("login.html",message="Incorrect username or password."))
Esempio n. 33
0
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        button = request.form['button']
        uname = request.form['username']
        pword = request.form['password']
        if button == "cancel":
            return render_template("login.html")
        if utils.authenticate(uname, pword):
            if 'n' not in session:
                session['n'] = 0
            return redirect(url_for('home'))
        else:
            return render_template("login.html",
                                   error="INVALID USERNAME OR PASSWORD")
Esempio n. 34
0
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        username = request.form['username']
        password = request.form['password']
        button = request.form['button']
        if button == "cancel":
            return redirect(url_for('home'))

        if utils.authenticate(username, password):
            session['username'] = username
            session['password'] = password
            return redirect(url_for('home'))
        else:
            error = "Bad username or password"
            return render_template("login.html", err=error)
Esempio n. 35
0
def login():
    if "logged" not in session:
        session["logged"] = False
    if request.method == "GET":
        return render_template("login.html")
    else:
        uname = request.form['username']
        pword = request.form['password']
        button = request.form['button']
        if button == "cancel":
            return render_template("login.html")
        if utils.authenticate(uname, pword):
            session["logged"] = True
            return redirect(url_for("success"))
        else:
            error = 'INVALID IDENTIFICATION, ABORT SITE!!!'
            return render_template("login.html", err=error)
Esempio n. 36
0
def login():
    SQL_Users = sqlite3.connect('SQL_Users')
    if request.method == "GET":
        return render_template("login.html")
    else:
        button = request.form['button']
        if button == 'Login':
            username = request.form['username'].encode('ascii', "ignore")
            password = request.form['password'].encode('ascii', "ignore")
            if utils.authenticate(SQL_Users, username, password) == 1:
                session['username'] = username
                return redirect("/success")
            else:
                return redirect("/login")
                print 'login attempt failed. Try again.'
        else:
            return redirect("/register")
Esempio n. 37
0
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        uname = request.form['username']
        pword = request.form['password']
        button = request.form['button']
        if button == "cancel":
            return render_template("login.html")
        if utils.authenticate(uname, pword):
            if 'logged' not in session:
                print session
                session['logged'] = True
            return redirect(url_for("about"))
        else:
            error = "Invalid username or password"
            return render_template("login.html", err=error)
Esempio n. 38
0
def delete_extra_ips_from_storage_table(storage_table_name):
    credentials_dict = authenticate(client_id, key, tenant_id)
    table_service = TableService(account_name='progaccount',
                                 account_key=table_key)
    table_rows = get_all_rows(storage_table_name)
    print 'LIST of table rows:\n', table_rows
    print 'list of NIC rows:\n', get_all_ips(resource_group_name, vm_ss_name)
    for curr_storage_table_ip in table_rows['ip']:
        if curr_storage_table_ip not in get_new_ips(
                get_all_rows(table_name),
                get_all_ips(resource_group_name, vm_ss_name)):
            print 'Deleting Entity:', table_rows['partition_key'][
                table_rows['ip'].index(
                    curr_storage_table_ip
                )], ' Current storage table IP: ', curr_storage_table_ip
            table_service.delete_entity(
                storage_table_name, table_rows['partition_key'][
                    table_rows['ip'].index(curr_storage_table_ip)],
                curr_storage_table_ip)
Esempio n. 39
0
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        uname = request.form['username']
        pword = request.form['password']
        button = request.form['button']
        if button == "cancel":
            return render_template('login.html')

        # if we get here, we have the uname and pword
        # to try to authenticate
        if utils.authenticate(uname, pword):
            if 'l' not in session:
                session['l'] = True
            return redirect(url_for('secretpage'))
        else:
            error = "Invalid user or password"
            return render_template("login.html", err=error)
Esempio n. 40
0
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        button = request.form['button']
        uname = request.form['username']
        pword = request.form['password']
        if button == "cancel":
            return render_template("login.html")
        # if we're here we should have
        # a username and password
        session['uname'] = uname
        session['pword'] = pword
        if utils.authenticate(uname, pword):
            return redirect(url_for("hidden"))
        else:
            session['uname'] = ''
            session['pword'] = ''
            return render_template("login.html",
                                   error="INVALID USERNAME OR PASSWORD")
Esempio n. 41
0
def login():
    if isLoggedIn():
        return '<center><h1>You are already logged in!</h1><br>Press the logout link in order to log out. Redirecting to horoscope...</center><META HTTP-EQUIV="refresh" CONTENT="3;url=/info">'
    elif request.method == "GET":
        return render_template("login.html")
    else:
        uname = request.form['username']
        pword = request.form['password']
        button = request.form['button']
        if button == "cancel":
            return render_template("login.html")
        if utils.authenticate(uname, pword):
            session["loggedIn"] = True
            session["uname"] = uname
            session["pass"] = pword
            return redirect(url_for("enterInfo"))
        else:
            session["loggedIn"] = False
            error = "Bad username or password"
            return render_template("login.html", err=error)
Esempio n. 42
0
def test_inactive_forbids(app, client, get_message):
    """ Make sure that existing session doesn't work after
    user marked inactive
    """
    response = authenticate(client, follow_redirects=True)
    assert response.status_code == 200
    # make sure can access restricted page
    response = client.get("/profile", follow_redirects=True)
    assert b"Profile Page" in response.data

    # deactivate matt
    with app.test_request_context("/"):
        user = app.security.datastore.find_user(email="*****@*****.**")
        app.security.datastore.deactivate_user(user)
        app.security.datastore.commit()

    response = client.get("/profile", follow_redirects=True)
    # should be thrown back to login page.
    assert response.status_code == 200
    assert b"Please log in to access this page" in response.data
Esempio n. 43
0
def test_view_configuration(client):
    response = client.get('/custom_login')
    assert b"<h1>Login</h1>" in response.data

    response = authenticate(client, endpoint='/custom_login')
    assert 'location' in response.headers
    assert response.headers['Location'] == 'http://localhost/post_login'

    response = logout(client, endpoint='/custom_logout')
    assert 'location' in response.headers
    assert response.headers['Location'] == 'http://localhost/post_logout'

    response = client.get('/http',
                          headers={
                              'Authorization':
                              'Basic %s' %
                              base64.b64encode(b"[email protected]:bogus")
                          })
    assert b'<h1>Unauthorized</h1>' in response.data
    assert 'WWW-Authenticate' in response.headers
    assert 'Basic realm="Custom Realm"' == response.headers['WWW-Authenticate']
Esempio n. 44
0
def fix(msg=''):
    if request.method == 'GET':
        return render_template("fix.html",msg='')
    else:
        uname = request.form['username']
        password = request.form['password']
        if (uname in utils.users()):
            if utils.authenticate(uname, password):
                new_password = request.form['newpass']
                confirm = request.form['confirm']
                if new_password != confirm:
                    return render_template("fix.html", msg="The passwords do not match. Try again")
                elif len(new_password) < 6:
                    return render_template("fix.html", msg="The password must be at least 6 characters")
                else:
                    utils.correct_password(password, new_password)
                    if 'user' in session:
                        session['user'] = ''
                    return redirect(url_for("login"))
            else:
                return render_template("fix.html", msg="That's the wrong username!")
Esempio n. 45
0
def test_view_configuration(client):
    response = client.get("/custom_login")
    assert b"<h1>Login</h1>" in response.data

    response = authenticate(client, endpoint="/custom_login")
    assert "location" in response.headers
    assert response.headers["Location"] == "http://localhost/post_login"

    response = logout(client, endpoint="/custom_logout")
    assert "location" in response.headers
    assert response.headers["Location"] == "http://localhost/post_logout"

    response = client.get(
        "/http",
        headers={
            "Authorization": "Basic %s" % base64.b64encode(b"[email protected]:bogus")
        },
    )
    assert response.status_code == 302
    assert response.headers[
        "Location"] == "http://localhost/custom_login?next=%2Fhttp"
Esempio n. 46
0
def test_view_configuration(client):
    response = client.get("/custom_login")
    assert b"<h1>Login</h1>" in response.data

    response = authenticate(client, endpoint="/custom_login")
    assert "location" in response.headers
    assert response.headers["Location"] == "http://localhost/post_login"

    response = logout(client, endpoint="/custom_logout")
    assert "location" in response.headers
    assert response.headers["Location"] == "http://localhost/post_logout"

    response = client.get(
        "/http",
        headers={
            "Authorization": "Basic %s" % base64.b64encode(b"[email protected]:bogus")
        },
    )
    assert b"<h1>Unauthorized</h1>" in response.data
    assert "WWW-Authenticate" in response.headers
    assert 'Basic realm="Custom Realm"' == response.headers["WWW-Authenticate"]
def test_can_add_password(app, client, get_message):
    # Test that if register w/o a password, can use 'recover password' to assign one
    data = dict(email="*****@*****.**", password="")
    response = client.post("/register", data=data, follow_redirects=True)
    assert b"Welcome [email protected]" in response.data
    logout(client)

    with capture_reset_password_requests() as requests:
        client.post("/reset",
                    data=dict(email="*****@*****.**"),
                    follow_redirects=True)
    token = requests[0]["token"]

    response = client.post(
        "/reset/" + token,
        data={
            "password": "******",
            "password_confirm": "awesome sunset"
        },
        follow_redirects=True,
    )

    assert get_message("PASSWORD_RESET") in response.data

    # authenticate with new password using standard/old login endpoint.
    response = authenticate(client,
                            "*****@*****.**",
                            "awesome sunset",
                            follow_redirects=True)
    assert b"Welcome [email protected]" in response.data

    logout(client)
    # authenticate with password and us-signin endpoint
    response = client.post(
        "/us-signin",
        data=dict(identity="*****@*****.**", passcode="awesome sunset"),
        follow_redirects=True,
    )
    assert b"Welcome [email protected]" in response.data
Esempio n. 48
0
def upload_manifest():
    '''Target uploads a list of all client files.

    Parameters
    ----------
    name : str
        Name of the machine.
    token : str
        Authentication token.
    data : json string
        JSON string containing the list of files for each client
        machine on the target.
    '''

    # Make sure we trust this machine as a target
    name = request.form['name']
    token = request.form['token']
    if not authenticate(name, token, role='target'):
        return False

    # Get the manifests for each client
    manifests = json.loads(request.form['data'])
def test_evil_validate(app, client):
    """
    Test logged in, and randomly try to validate a token
    """
    signalled_identity = []

    @identity_changed.connect_via(app)
    def on_identity_changed(app, identity):
        signalled_identity.append(identity.id)

    response = authenticate(client, "*****@*****.**")
    session = get_session(response)
    assert "tf_state" not in session
    # Jill is 4th user to be added in utils.py
    assert signalled_identity[0] == 4
    del signalled_identity[:]

    # try to validate
    response = client.post("/tf-validate", data=dict(code="?"), follow_redirects=True)
    # This should log us out since it thinks we are evil
    assert not signalled_identity[0]
    del signalled_identity[:]
Esempio n. 50
0
def login_register():
    if request.method == "GET":
        if 'un' in session and session['un'] != 0:
            user = session['un']
            return redirect(url_for("home"))
        else:
            return render_template("home.html",
                                   unlogged="You are not currently logged in.")
    else:
        #button = request.form['button']
        if 'in_username' in request.form:
            user = request.form['in_username']
            passwd = request.form['in_password']
            if utils.authenticate(user, passwd):
                session['un'] = user
                session['pw'] = passwd
                return redirect(url_for("blog"))
            else:
                error = "INVALID USERNAME AND/OR PASSWORD"
                return render_template("home.html", error=error)
        else:
            user = request.form['regis_username']
            passwd = request.form['regis_password']
            conn = sqlite3.connect('bloginator.db')
            c = conn.cursor()
            c.execute('select * from users where username="******"')
            r = c.fetchall()
            conn.commit()
            if len(r) == 0:
                utils.newUser(user, passwd)
                success = "Account Created!"
                session['un'] = user
                session['pw'] = passwd
                return redirect(url_for("blog"))
            else:
                failure = "There is already an account with this username"
                return render_template("home.html", created=failure)
Esempio n. 51
0
File: app.py Progetto: ldalynyc/blag
def login():
        all_rows = utils.getAllUsers()
        for n in range(len(all_rows)):
                all_rows[n] = all_rows[n][0]
        if request.method == 'POST':
                user = str(request.form['user'])
                password = str(request.form['pass'])
                error = ""
                if request.form['press'] == "login":
                        if utils.authenticate(user,password):
                                session['user'] = user
                                return redirect("/home")
                        else:
                                error = "Incorrect Username or Password. Try Again."
                                return render_template("login.html",error=error)
                else:
                        if user in all_rows:
                                error = "Username already exists. Please try another"
                                return render_template("login.html",error=error)
                        else: 
                                utils.addUser(user,password)
                                session['user'] = user
                                return redirect("/home")
        return render_template("login.html") #login failed
def main():
    """
    Main entry point for script.

    Handles argument parsing and validation and then calls the script payload.
    """

    usage = "%prog [options] config_descriptor target_path"

    desc = "Bake a self contained Toolkit config from a descriptor"

    epilog = """

Details and Examples
--------------------

In its simplest form, just provide a local path and target folder for the build.

> python bake_config.py ~/dev/tk-config-myconfig /tmp/baked_configurations

Or you can specify a version with a Toolkit config descriptor uri.

> python bake_config.py "sgtk:descriptor:dev?version=v1.0.9&path=../tk-config-myconfig" /tmp/baked_configurations

Any type of Toolkit config descriptor uri can be used, if a version is not specified, the latest for the descriptor is resolved.

> python bake_config.py "sgtk:descriptor:app_store?name=tk-config-basic" /tmp/baked_configurations

By default, all bundle types are cached. If you want to omit certain types, simply provide a comma seperated list
of bundle types to skip, e.g. --skip-bundle-types=app_store,shotgun,github_release.

{automated_setup_documentation}

For information about the various descriptors that can be used, see
http://developer.shotgridsoftware.com/tk-core/descriptor


""".format(
        automated_setup_documentation=automated_setup_documentation
    ).format(
        script_name="bake_config.py"
    )
    parser = OptionParserLineBreakingEpilog(
        usage=usage, description=desc, epilog=epilog
    )

    parser.add_option(
        "-d", "--debug", default=False, action="store_true", help="Enable debug logging"
    )

    parser.add_option(
        "-z", "--zip", default=False, action="store_true", help="Zip archive the config"
    )

    parser.add_option(
        "--skip-bundle-types",
        # You can't have an empty default optional value, so we'll pick something
        # and treat it accordingly.
        default="none",
        help="Comma separated list of bundle types to skip. Possible values are 'app_store', "
        "'git', 'git_branch', 'github_release', 'shotgun'. Empty by default.",
    )

    add_authentication_options(parser)

    # parse cmd line
    (options, remaining_args) = parser.parse_args()

    logger.info("Welcome to the Toolkit config baker.")
    logger.info("")

    if options.debug:
        LogManager().global_debug = True

    if len(remaining_args) != 2:
        parser.print_help()
        return 2

    # Get config descriptor
    config_descriptor = remaining_args[0]
    # Try to parse it, check if it is a local path if it fails
    try:
        descriptor_uri_to_dict(config_descriptor)
    except TankDescriptorError:
        # Check if it is a local path
        path = os.path.abspath(
            os.path.expanduser(os.path.expandvars(config_descriptor))
        )
        if os.path.isdir(path):
            logger.info("Using a dev descriptor for local path %s" % path)
            # Forge a dev descriptor, using "latest" for the version.
            # TODO: try to retrieve a valid version from the folder, e.g. with a
            # git tag from the folder.
            config_descriptor = "sgtk:descriptor:dev?name=%s&path=%s&version=latest" % (
                os.path.basename(path),
                path,
            )
        else:
            logger.error(
                "%s is not a valid descriptor nor a local path." % config_descriptor
            )
            raise
    # Get output path
    target_path = remaining_args[1]
    target_path = os.path.expanduser(os.path.expandvars(target_path))

    sg_user = authenticate(options)

    sg_connection = sg_user.create_sg_connection()
    # make sure we are properly connected
    try:
        sg_connection.find_one("HumanUser", [])
    except Exception as e:
        logger.error("Could not communicate with ShotGrid: %s" % e)
        return 3

    # Strip any extra whitespaces and make sure every bundle type exists.
    skip_bundle_types = options.skip_bundle_types.split(",")
    skip_bundle_types = [bundle_type.strip() for bundle_type in skip_bundle_types]
    for bundle_type in skip_bundle_types:
        if bundle_type not in [
            "app_store",
            "git",
            "git_branch",
            "github_release",
            "shotgun",
            "none",
        ]:
            logger.error("Unknown bundle type: %s" % bundle_type)
            return 4

    # we are all set.
    bake_config(
        sg_connection, config_descriptor, target_path, options.zip, skip_bundle_types,
    )

    # all good!
    return 0
Esempio n. 53
0
def test_registerable_flag(client, app, get_message):
    recorded = []

    # Test the register view
    response = client.get("/register")
    assert b"<h1>Register</h1>" in response.data

    # Test registering is successful, sends email, and fires signal
    @user_registered.connect_via(app)
    def on_user_registered(app, user, confirm_token, form_data):

        assert isinstance(app, Flask)
        assert isinstance(user, UserMixin)
        assert confirm_token is None
        assert len(form_data.keys()) > 0

        recorded.append(user)

    data = dict(
        email="*****@*****.**",
        password="******",
        password_confirm="battery staple",
        next="",
    )
    with app.mail.record_messages() as outbox:
        response = client.post("/register", data=data, follow_redirects=True)

    assert len(recorded) == 1
    assert len(outbox) == 1
    assert b"Post Register" in response.data

    logout(client)

    # Test user can login after registering
    response = authenticate(client,
                            email="*****@*****.**",
                            password="******")
    assert response.status_code == 302

    logout(client)

    # Test registering with an existing email
    data = dict(email="*****@*****.**",
                password="******",
                password_confirm="password",
                next="")
    response = client.post("/register", data=data, follow_redirects=True)
    assert get_message("EMAIL_ALREADY_ASSOCIATED",
                       email="*****@*****.**") in response.data

    # Test registering with an existing email but case insensitive
    data = dict(email="*****@*****.**",
                password="******",
                password_confirm="password",
                next="")
    response = client.post("/register", data=data, follow_redirects=True)
    assert get_message("EMAIL_ALREADY_ASSOCIATED",
                       email="*****@*****.**") in response.data

    # Test registering with JSON
    data = dict(email="*****@*****.**", password="******")
    response = client.post("/register",
                           json=data,
                           headers={"Content-Type": "application/json"})

    assert response.headers["content-type"] == "application/json"
    assert response.json["meta"]["code"] == 200
    assert len(response.json["response"]) == 2
    assert all(k in response.json["response"] for k in ["csrf_token", "user"])

    logout(client)

    # Test registering with invalid JSON
    data = dict(email="bogus", password="******")
    response = client.post("/register",
                           json=data,
                           headers={"Content-Type": "application/json"})
    assert response.headers["content-type"] == "application/json"
    assert response.json["meta"]["code"] == 400

    logout(client)

    # Test ?next param
    data = dict(
        email="*****@*****.**",
        password="******",
        password_confirm="horse staple",
        next="",
    )

    response = client.post("/register?next=/page1",
                           data=data,
                           follow_redirects=True)
    assert b"Page 1" in response.data
def test_custom_change_template(client):
    authenticate(client)
    response = client.get('/change')
    assert b'CUSTOM CHANGE PASSWORD' in response.data
def test_recoverable_flag(app, client, get_message):
    recorded = []

    @password_changed.connect_via(app)
    def on_password_changed(app, user):
        assert isinstance(app, Flask)
        assert isinstance(user, UserMixin)
        recorded.append(user)

    authenticate(client)

    # Test change view
    response = client.get('/change', follow_redirects=True)
    assert b'Change password' in response.data

    # Test wrong original password
    response = client.post('/change',
                           data={
                               'password': '******',
                               'new_password': '******',
                               'new_password_confirm': 'newpassword'
                           },
                           follow_redirects=True)
    assert get_message('INVALID_PASSWORD') in response.data

    # Test mismatch
    response = client.post('/change',
                           data={
                               'password': '******',
                               'new_password': '******',
                               'new_password_confirm': 'notnewpassword'
                           },
                           follow_redirects=True)
    assert get_message('RETYPE_PASSWORD_MISMATCH') in response.data

    # Test missing password
    response = client.post('/change',
                           data={
                               'password': '******',
                               'new_password': '',
                               'new_password_confirm': ''
                           },
                           follow_redirects=True)
    assert get_message('PASSWORD_NOT_PROVIDED') in response.data

    # Test bad password
    response = client.post('/change',
                           data={
                               'password': '******',
                               'new_password': '******',
                               'new_password_confirm': 'a'
                           },
                           follow_redirects=True)
    assert get_message('PASSWORD_INVALID_LENGTH') in response.data

    # Test same as previous
    response = client.post('/change',
                           data={
                               'password': '******',
                               'new_password': '******',
                               'new_password_confirm': 'password'
                           },
                           follow_redirects=True)
    assert get_message('PASSWORD_IS_THE_SAME') in response.data

    # Test successful submit sends email notification
    with app.mail.record_messages() as outbox:
        response = client.post('/change',
                               data={
                                   'password': '******',
                                   'new_password': '******',
                                   'new_password_confirm': 'newpassword'
                               },
                               follow_redirects=True)

    assert get_message('PASSWORD_CHANGE') in response.data
    assert b'Home Page' in response.data
    assert len(recorded) == 1
    assert len(outbox) == 1
    assert "Your password has been changed" in outbox[0].html

    # Test JSON
    data = ('{"password": "******", "new_password": "******", '
            '"new_password_confirm": "newpassword2"}')
    response = client.post('/change',
                           data=data,
                           headers={'Content-Type': 'application/json'})
    assert response.status_code == 200
    assert response.headers['Content-Type'] == 'application/json'
def test_custom_change_url(client):
    authenticate(client)
    response = client.get('/custom_change')
    assert response.status_code == 200
Esempio n. 57
0
def main():
    """
    Main entry point for script.

    Handles argument parsing and validation and then calls the script payload.
    """

    usage = "%prog [options] source_path target_path"

    desc = "Builds a standard toolkit plugin structure ready for testing and deploy"

    epilog = """

Details and Examples
--------------------

In its simplest form, just provide a source and target folder for the build.

> python build_plugin.py ~/dev/tk-maya/plugins/basic /tmp/maya-plugin

For automated build setups, you can provide a specific shotgun API script name and
and corresponding script key:

> python build_plugin.py
            --shotgun-host='https://mysite.shotgunstudio.com'
            --shotgun-script-name='plugin_build'
            --shotgun-script-key='<script-key-here>'
            ~/dev/tk-maya/plugins/basic /tmp/maya-plugin

By default, the build script will use the latest app store core for its bootstrapping.
If you want to use a specific core for the bootstrap, this can be specified via the
--bootstrap-core-uri option:

> python build_plugin.py
            --bootstrap-core-uri='sgtk:descriptor:dev?path=~/dev/tk-core'
            ~/dev/tk-maya/plugins/basic /tmp/maya-plugin

For information about the various descriptors that can be used, see
http://developer.shotgunsoftware.com/tk-core/descriptor


"""
    parser = OptionParserLineBreakingEpilog(usage=usage,
                                            description=desc,
                                            epilog=epilog)

    parser.add_option("-d",
                      "--debug",
                      default=False,
                      action="store_true",
                      help="Enable debug logging")

    parser.add_option(
        "-c",
        "--bootstrap-core-uri",
        default=None,
        action="store",
        help=
        ("Specify which version of core to be used by the bootstrap process. "
         "If not specified, defaults to the most recently released core."))

    add_authentication_options(parser)

    # parse cmd line
    (options, remaining_args) = parser.parse_args()

    logger.info("Welcome to the Toolkit plugin builder.")
    logger.info("")

    if options.debug:
        LogManager().global_debug = True

    if options.bootstrap_core_uri:
        bootstrap_core_uri = options.bootstrap_core_uri
    else:
        # default
        bootstrap_core_uri = None

    if len(remaining_args) != 2:
        parser.print_help()
        return 2

    # get paths
    source_path = remaining_args[0]
    target_path = remaining_args[1]

    # convert any env vars and tildes
    source_path = os.path.expanduser(os.path.expandvars(source_path))
    target_path = os.path.expanduser(os.path.expandvars(target_path))

    sg_user = authenticate(options)

    sg_connection = sg_user.create_sg_connection()
    # make sure we are properly connected
    try:
        sg_connection.find_one("HumanUser", [])
    except Exception, e:
        logger.error("Could not communicate with Shotgun: %s" % e)
        return 3
Esempio n. 58
0
def test_confirmable_flag(app, client, sqlalchemy_datastore, get_message):
    recorded_confirms = []
    recorded_instructions_sent = []

    @user_confirmed.connect_via(app)
    def on_confirmed(app, user):
        assert isinstance(app, Flask)
        assert isinstance(user, UserMixin)
        recorded_confirms.append(user)

    @confirm_instructions_sent.connect_via(app)
    def on_instructions_sent(app, user, token):
        assert isinstance(app, Flask)
        assert isinstance(user, UserMixin)
        assert isinstance(token, string_types)
        recorded_instructions_sent.append(user)

    # Test login before confirmation
    email = "*****@*****.**"

    with capture_registrations() as registrations:
        data = dict(email=email, password="******", next="")
        response = client.post("/register", data=data)

    assert response.status_code == 302

    response = authenticate(client, email=email)
    assert get_message("CONFIRMATION_REQUIRED") in response.data

    # Test invalid token
    response = client.get("/confirm/bogus", follow_redirects=True)
    assert get_message("INVALID_CONFIRMATION_TOKEN") in response.data

    # Test JSON
    response = client.post(
        "/confirm",
        data='{"email": "*****@*****.**"}',
        headers={"Content-Type": "application/json"},
    )
    assert response.status_code == 200
    assert response.headers["Content-Type"] == "application/json"
    assert "user" in response.jdata["response"]
    assert len(recorded_instructions_sent) == 1

    # Test ask for instructions with invalid email
    response = client.post("/confirm", data=dict(email="*****@*****.**"))
    assert get_message("USER_DOES_NOT_EXIST") in response.data

    # Test resend instructions
    response = client.post("/confirm", data=dict(email=email))
    assert get_message("CONFIRMATION_REQUEST", email=email) in response.data
    assert len(recorded_instructions_sent) == 2

    # Test confirm
    token = registrations[0]["confirm_token"]
    response = client.get("/confirm/" + token, follow_redirects=True)
    assert get_message("EMAIL_CONFIRMED") in response.data
    assert len(recorded_confirms) == 1

    # Test already confirmed
    response = client.get("/confirm/" + token, follow_redirects=True)
    assert get_message("ALREADY_CONFIRMED") in response.data
    assert len(recorded_instructions_sent) == 2

    # Test already confirmed and expired token
    app.config["SECURITY_CONFIRM_EMAIL_WITHIN"] = "-1 days"
    with app.app_context():
        user = registrations[0]["user"]
        expired_token = generate_confirmation_token(user)
    response = client.get("/confirm/" + expired_token, follow_redirects=True)
    assert get_message("ALREADY_CONFIRMED") in response.data
    assert len(recorded_instructions_sent) == 2

    # Test already confirmed when asking for confirmation instructions
    logout(client)

    response = client.get("/confirm")
    assert response.status_code == 200

    response = client.post("/confirm", data=dict(email=email))
    assert get_message("ALREADY_CONFIRMED") in response.data

    # Test user was deleted before confirmation
    with capture_registrations() as registrations:
        data = dict(email="*****@*****.**", password="******", next="")
        client.post("/register", data=data)

    user = registrations[0]["user"]
    token = registrations[0]["confirm_token"]

    with app.app_context():
        sqlalchemy_datastore.delete(user)
        sqlalchemy_datastore.commit()

    response = client.get("/confirm/" + token, follow_redirects=True)
    assert get_message("INVALID_CONFIRMATION_TOKEN") in response.data
Esempio n. 59
0
def test_registerable_flag(client, app, get_message):
    recorded = []

    # Test the register view
    response = client.get('/register')
    assert b"<h1>Register</h1>" in response.data

    # Test registering is successful, sends email, and fires signal
    @user_registered.connect_via(app)
    def on_user_registerd(app, user, confirm_token):
        recorded.append(user)

    data = dict(email='*****@*****.**',
                password='******',
                password_confirm='password',
                next='')
    with app.mail.record_messages() as outbox:
        response = client.post('/register', data=data, follow_redirects=True)

    assert len(recorded) == 1
    assert len(outbox) == 1
    assert b'Post Register' in response.data

    logout(client)

    # Test user can login after registering
    response = authenticate(client, email='*****@*****.**', password='******')
    assert response.status_code == 302

    logout(client)

    # Test registering with an existing email
    data = dict(email='*****@*****.**',
                password='******',
                password_confirm='password',
                next='')
    response = client.post('/register', data=data, follow_redirects=True)
    assert get_message('EMAIL_ALREADY_ASSOCIATED',
                       email='*****@*****.**') in response.data

    # Test registering with an existing email but case insensitive
    data = dict(email='*****@*****.**',
                password='******',
                password_confirm='password',
                next='')
    response = client.post('/register', data=data, follow_redirects=True)
    assert get_message('EMAIL_ALREADY_ASSOCIATED',
                       email='*****@*****.**') in response.data

    # Test registering with JSON
    data = '{ "email": "*****@*****.**", "password": "******"}'
    response = client.post('/register',
                           data=data,
                           headers={'Content-Type': 'application/json'})
    assert response.headers['content-type'] == 'application/json'
    assert response.jdata['meta']['code'] == 200

    logout(client)

    # Test registering with invalid JSON
    data = '{ "email": "bogus", "password": "******"}'
    response = client.post('/register',
                           data=data,
                           headers={'Content-Type': 'application/json'})
    assert response.headers['content-type'] == 'application/json'
    assert response.jdata['meta']['code'] == 400

    logout(client)

    # Test ?next param
    data = dict(email='*****@*****.**',
                password='******',
                password_confirm='password',
                next='')

    response = client.post('/register?next=/page1',
                           data=data,
                           follow_redirects=True)
    assert b'Page 1' in response.data
def test_recoverable_flag(app, client, get_message):
    recorded_resets = []
    recorded_instructions_sent = []

    @password_reset.connect_via(app)
    def on_password_reset(app, user):
        recorded_resets.append(user)

    @reset_password_instructions_sent.connect_via(app)
    def on_instructions_sent(app, user, token):
        assert isinstance(app, Flask)
        assert isinstance(user, UserMixin)
        assert isinstance(token, str)
        recorded_instructions_sent.append(user)

    # Test the reset view
    response = client.get('/reset')
    assert b'<h1>Send password reset instructions</h1>' in response.data

    # Test submitting email to reset password creates a token and sends email
    with capture_reset_password_requests() as requests:
        with app.mail.record_messages() as outbox:
            response = client.post('/reset',
                                   data=dict(email='*****@*****.**'),
                                   follow_redirects=True)

    assert len(recorded_instructions_sent) == 1
    assert len(outbox) == 1
    assert response.status_code == 200
    assert get_message('PASSWORD_RESET_REQUEST',
                       email='*****@*****.**') in response.data
    token = requests[0]['token']

    # Test view for reset token
    response = client.get('/reset/' + token)
    assert b'<h1>Reset password</h1>' in response.data

    # Test submitting a new password
    response = client.post('/reset/' + token,
                           data={
                               'password': '******',
                               'password_confirm': 'newpassword'
                           },
                           follow_redirects=True)

    assert get_message('PASSWORD_RESET') in response.data
    assert len(recorded_resets) == 1

    logout(client)

    # Test logging in with the new password
    response = authenticate(client,
                            '*****@*****.**',
                            'newpassword',
                            follow_redirects=True)
    assert b'Hello [email protected]' in response.data

    logout(client)

    # Test invalid email
    response = client.post('/reset',
                           data=dict(email='*****@*****.**'),
                           follow_redirects=True)
    assert get_message('USER_DOES_NOT_EXIST') in response.data

    logout(client)

    # Test invalid token
    response = client.post('/reset/bogus',
                           data={
                               'password': '******',
                               'password_confirm': 'newpassword'
                           },
                           follow_redirects=True)
    assert get_message('INVALID_RESET_PASSWORD_TOKEN') in response.data

    # Test mangled token
    token = ("WyIxNjQ2MzYiLCIxMzQ1YzBlZmVhM2VhZjYwODgwMDhhZGU2YzU0MzZjMiJd."
             "BZEw_Q.lQyo3npdPZtcJ_sNHVHP103syjM"
             "&url_id=fbb89a8328e58c181ea7d064c2987874bc54a23d")
    response = client.post('/reset/' + token,
                           data={
                               'password': '******',
                               'password_confirm': 'newpassword'
                           },
                           follow_redirects=True)
    assert get_message('INVALID_RESET_PASSWORD_TOKEN') in response.data