Пример #1
0
    def test_from_login(self):
        with self.app.app_context():
            user = User.from_login(
                '*****@*****.**',
                'woot1LoveCookies!',
            )
            self.assertEqual(user.href, self.user.href)

            user = User.from_login(
                'randall',
                'woot1LoveCookies!',
            )
            self.assertEqual(user.href, self.user.href)
Пример #2
0
def login():
    """
    This view logs in a user given an email address and password.

    This works by querying Stormpath with the user's credentials, and either
    getting back the User object itself, or an exception (in which case well
    tell the user their credentials are invalid).

    If the user is valid, we'll log them in, and store their session for later.
    """
    if request.method == 'GET':
        return render_template('login.html')

    try:
        _user = User.from_login(
            request.form.get('email'),
            request.form.get('password'),
        )
    except StormpathError as err:
        return render_template('login.html',
                               error=err.message,
                               email=request.form.get('email'))

    login_user(_user, remember=True)
    return redirect(request.args.get('next') or url_for('dashboard'))
Пример #3
0
 def login():
     user = User.from_login(
         request.form.get('email'),
         request.form.get('password'),
     )
     login_user(user, remember=True)
     return 'logged in'
Пример #4
0
def register():
    """
    Register a new user with Stormpath.
    """
    form = RegistrationForm()

    # If we received a POST request with valid information, we'll continue
    # processing.
    if form.validate_on_submit():

        data = {}
        # Attempt to create the user's account on Stormpath.
        try:
            # email and password
            data['email'] = form.email.data
            data['password'] = form.password.data

            # given_name and surname are required fields
            data['given_name'] = 'Anonymous'
            data['surname'] = 'Anonymous'

            # create a tenant ID
            tenant_id = str(uuid.uuid4())
            data['custom_data'] = {'tenant_id': tenant_id, 'site_admin': True}

            # Create the user account on Stormpath.  If this fails, an
            # exception will be raised.
            account = User.create(**data)

            # create a new stormpath group
            directory = stormpath_manager.application.default_account_store_mapping.account_store
            tenant_group = directory.groups.create({
                'name': tenant_id,
                'description': data['email']
            })

            # assign new user to the newly created group
            account.add_group(tenant_group)
            account.add_group('site_admin')

            # If we're able to successfully create the user's account,
            # we'll log the user in (creating a secure session using
            # Flask-Login), then redirect the user to the
            # STORMPATH_REDIRECT_URL setting.
            login_user(account, remember=True)

            # redirect to dashboard
            redirect_url = current_app.config['STORMPATH_REDIRECT_URL']
            return redirect(redirect_url)

        except StormpathError as err:
            flash(err.message.get('message'))

    return render_template(
        'account/register.html',
        form=form,
    )
Пример #5
0
    def test_user_can_login(self):
        _user = User.from_login(
            TestConfig.USER_EMAIL,
            TestConfig.USER_PASSWORD,
        )
        login_user(_user)

        user_id = user.get_id()
        app_user = AppUser.query.get(stormpathUserHash(user_id))
        assert app_user.user_href == user_id
Пример #6
0
    def test_user_can_login(self):
        _user = User.from_login(
                TestConfig.USER_EMAIL,
                TestConfig.USER_PASSWORD,
            )
        login_user(_user)

        user_id = user.get_id()
        app_user = AppUser.query.get(stormpathUserHash(user_id))
        assert app_user.user_href == user_id
Пример #7
0
def authorize_iOS():
    """ User login/auth/session management """

    username = request.form.get('username', '')
    password = request.form.get('password', '')
    user = None

    try:
        user = User.from_login(username, password)
    except StormpathError, err:
        pass
Пример #8
0
def authorize_iOS():
    """ User login/auth/session management """

    username = request.form.get('username', '')
    password = request.form.get('password', '')
    user = None

    try:
        user = User.from_login(username, password)
    except StormpathError, err:
        pass
Пример #9
0
def login():
    """Allow users to log into the site."""
    if request.method == 'GET':
        return render_template('login.html')

    try:
        _user = User.from_login(
            request.form.get('email'),
            request.form.get('password')
        )
    except StormpathError, err:
        return render_template('login.html', error=err.message)
Пример #10
0
def login():
    error = None

    if request.method == "POST":
        try:
            _user = User.from_login(request.form["email"], request.form["password"])
            login_user(_user, remember=True)
            flash("Has entrado al sistema.")

            return redirect(url_for("show_posts"))
        except StormpathError, err:
            error = err.message
Пример #11
0
def login():
    error = None
    if request.method == 'POST':
        try:
            _user = User.from_login(
                request.form['email'],
                request.form['password'],
            )
            login_user(_user, remember=True)
            flash('You were logged in.')
            return redirect(url_for('show_posts'))
        except StormpathError, err:
            error = err.message
Пример #12
0
def register():
    """
    Register a new user with Stormpath.
    """
    form = RegistrationForm()

    # If we received a POST request with valid information, we'll continue
    # processing.
    if form.validate_on_submit():

        data = {}
        # Attempt to create the user's account on Stormpath.
        try:
            # email and password
            data["email"] = form.email.data
            data["password"] = form.password.data

            # given_name and surname are required fields
            data["given_name"] = "Anonymous"
            data["surname"] = "Anonymous"

            # create a tenant ID
            tenant_id = str(uuid.uuid4())
            data["custom_data"] = {"tenant_id": tenant_id, "site_admin": True}

            # Create the user account on Stormpath.  If this fails, an
            # exception will be raised.
            account = User.create(**data)

            # create a new stormpath group
            directory = stormpath_manager.application.default_account_store_mapping.account_store
            tenant_group = directory.groups.create({"name": tenant_id, "description": data["email"]})

            # assign new user to the newly created group
            account.add_group(tenant_group)
            account.add_group("site_admin")

            # If we're able to successfully create the user's account,
            # we'll log the user in (creating a secure session using
            # Flask-Login), then redirect the user to the
            # STORMPATH_REDIRECT_URL setting.
            login_user(account, remember=True)

            # redirect to dashboard
            redirect_url = current_app.config["STORMPATH_REDIRECT_URL"]
            return redirect(redirect_url)

        except StormpathError as err:
            flash(err.message.get("message"))

    return render_template("account/register.html", form=form)
Пример #13
0
def login():
    """ User login/auth/session management """
    if request.method == 'GET':
        if user.is_authenticated():
            return redirect(url_for('index'))

        return render_template('login.html')

    try:
        _user = User.from_login(
            request.form.get('email'),
            request.form.get('password'),
        )
    except StormpathError, err:
        return render_template('login.html', error=err.message)
Пример #14
0
def login():
	error = None
	try:
		_user = User.from_login(
			request.form['email'],
			request.form['password']
			)

		login_user(_user, remember = True)
		flash('You were logged in.')

		return redirect(url_for('show_posts'))

	except StormpathError, err:
		error = err.message
Пример #15
0
def login():
    """ User login/auth/session management """
    if request.method == 'GET':
        if user.is_authenticated():
            return redirect(url_for('index'))

        return render_template('login.html')

    try:
        _user = User.from_login(
            request.form.get('email'),
            request.form.get('password'),
        )
    except StormpathError, err:
        return render_template('login.html', error=err.message)
Пример #16
0
def add_user_confirm(token):
    """
    Decode invite token and create new user account
    """
    form = RegistrationForm()
    decoded = None
    try:
        ts = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])
        decoded = ts.loads(token, max_age=86400)
        email = decoded[0]
    except:
        abort(404)

    if form.validate_on_submit():
        try:
            tenant_id = decoded[1]

            data = {}
            data['email'] = email
            data['password'] = request.form['password']

            # given_name and surname are required fields
            data['given_name'] = 'Anonymous'
            data['surname'] = 'Anonymous'

            # set tenant id and site_admin status
            data['custom_data'] = {
                'tenant_id': tenant_id,
                'site_admin': 'False'
            }

            # create account
            account = User.create(**data)

            # add user to tenant group
            account.add_group(tenant_id)

            # login user
            login_user(account, remember=True)

            # success redirect
            return render_template('account/add_user_complete.html')
        except StormpathError as err:
            flash(err.message.get('message'))

    return render_template('account/add_user_setpassword.html',
                           form=form,
                           email=email)
Пример #17
0
def login():
    error = None

    if request.method == 'POST':
        try:
            _user = User.from_login(
                request.form['email'],
                request.form['password'],
            )
            login_user(_user, remember=True)
            flash('You were logged in.')

            return redirect(url_for('show_posts'))
        except StormpathError as err:
            error = err.message

    return render_template('login.html', error=error)
Пример #18
0
def login():
    error = None
    form = LoginForm()
    if form.validate_on_submit():
        try:
            _user = User.from_login(
                form.email.data,
                form.password.data,
            )
            login_user(_user, remember=True)
            flash('You were logged in.')
            tutnames = db.session.query(Tut.name).all()
            tutnames = [tutname for (tutname, ) in tutnames]
            return redirect(
                url_for('tutorial', tno=g.user.custom_data["tutno"]))
        except StormpathError, err:
            error = err.message
            flash('Please try again')
Пример #19
0
def login():
    """
    This view logs in a user given an email address and password.
    Flask-Stormpath handles logins and user sessions.
    """
    if request.method == 'GET':
        return render_template('login.html')

    try:
        _user = User.from_login(
            request.form.get('email'),
            request.form.get('password'),
        )

        # Verify if the user is already in the database, if not we create a new entry
        # You might think doing this upon registration is a better idea, but we only want
        # to create database entries for users that confirmed their emails, and we need to
        # create entries before any page is displayed to the user.

        user_in_db = mongodb.users.find_one({ 'username': _user.username })

        if not user_in_db:
            # uid is generated here and not upon registering due to regression issues
            # TODO: change this after current users log in?
            uid = str(uuid4())

            mongodb.users.insert({
                'uid': uid,
                'username': _user.username,
                'email': _user.email,
                'given_name': _user.given_name,
                'surname': _user.surname
            })

            _user.custom_data['uid'] = uid
            _user.save()

        if not 'uid' in _user.custom_data:
            _user.custom_data['uid'] = user_in_db['uid']
            _user.save()

    except StormpathError, err:
        # TODO, some errors have wrong messages (e.g. 'incorrect password' upon unverified account)
        return render_template('login.html', error=err.message), 400
Пример #20
0
def add_user_confirm(token):
    """
    Decode invite token and create new user account
    """
    form = RegistrationForm()
    decoded = None
    try:
        ts = URLSafeTimedSerializer(current_app.config["SECRET_KEY"])
        decoded = ts.loads(token, max_age=86400)
        email = decoded[0]
    except:
        abort(404)

    if form.validate_on_submit():
        try:
            tenant_id = decoded[1]

            data = {}
            data["email"] = email
            data["password"] = request.form["password"]

            # given_name and surname are required fields
            data["given_name"] = "Anonymous"
            data["surname"] = "Anonymous"

            # set tenant id and site_admin status
            data["custom_data"] = {"tenant_id": tenant_id, "site_admin": "False"}

            # create account
            account = User.create(**data)

            # add user to tenant group
            account.add_group(tenant_id)

            # login user
            login_user(account, remember=True)

            # success redirect
            return render_template("account/add_user_complete.html")
        except StormpathError as err:
            flash(err.message.get("message"))

    return render_template("account/add_user_setpassword.html", form=form, email=email)
Пример #21
0
def login():
    """
    This view logs in a user given an email address and password.

    This works by querying Stormpath with the user's credentials, and either
    getting back the User object itself, or an exception (in which case well
    tell the user their credentials are invalid).

    If the user is valid, we'll log them in, and store their session for later.
    """
    if request.method == 'GET':
        return render_template('login.html')

    try:
        _user = User.from_login(
            request.form.get('email'),
            request.form.get('password'),
        )
    except StormpathError, err:
        return render_template('login.html', error=err.message)
Пример #22
0
def login():
  error = None

  # Attempt to login using email and password
  if request.method == 'POST':
    try:
      _user = User.from_login(
        request.form['email'],
        request.form['password'],
        )

      # No errors occur and user is logged in
      login_user(_user, remember = True)
      flash('You were logged in.')

      return redirect(url_for('show_posts'))

    except (StormpathError, err):
      error = err.message

  return render_template('login.html', error = error)
    def setUp(self):
        """Provision a single user account and some groups for testing."""
        # Call the parent setUp method first -- this will bootstrap our tests.
        super(TestGroupsRequired, self).setUp()

        with self.app.app_context():

            # Create our Stormpath user.
            self.user = User.create(
                given_name = 'Randall',
                surname = 'Degges',
                email = '*****@*****.**',
                password = '******',
            )

            # Create two groups.
            self.admins = self.application.groups.create({
                'name': 'admins',
            })
            self.developers = self.application.groups.create({
                'name': 'developers',
            })
Пример #24
0
def register():
    error = None
    form = RegisterForm()
    if form.validate_on_submit():
        try:
            account = stormpath_manager.application.accounts.create({
                'given_name':
                form.given_name.data,
                'surname':
                form.surname.data,
                'username':
                form.username.data,
                'email':
                form.email.data,
                'password':
                form.password.data,
                'custom_data': {
                    'tutno':
                    1,
                    'completed':
                    False,
                    'avatar':
                    'http://www.gravatar.com/avatar/%s?d=mm&s=%d' %
                    (md5(form.email.data.encode('utf-8')).hexdigest(), 128)
                }
            })
            _user = User.from_login(
                form.email.data,
                form.password.data,
            )
            login_user(_user, remember=True)
            flash('You were logged in.')
            tutnames = db.session.query(Tut.name).all()
            tutnames = [tutname for (tutname, ) in tutnames]
            return render_template('startpage.html', tutnames=tutnames)
        except StormpathError, err:
            error = err.message
            flash('Please try again' + str(error))
Пример #25
0
    def test_create(self):
        with self.app.app_context():

            # Ensure all defaults fields are properly set.
            user = User.create(
                email = '*****@*****.**',
                password = '******',
                given_name = 'Cookie',
                surname = 'Monster',
            )
            self.assertEqual(user.email, '*****@*****.**')
            self.assertEqual(user.given_name, 'Cookie')
            self.assertEqual(user.surname, 'Monster')
            self.assertEqual(user.username, '*****@*****.**')
            self.assertEqual(user.middle_name, None)
            self.assertEqual(dict(user.custom_data), {})

            # Ensure we can the middle name and username fields to custom
            # entities.
            user = User.create(
                username = '******',
                email = '*****@*****.**',
                password = '******',
                given_name = 'Austin',
                surname = 'Powers',
                middle_name = 'Danger',
            )
            self.assertEqual(user.username, 'powerful')
            self.assertEqual(user.middle_name, 'Danger')

            # Ensure we can set custom data when we create a user.
            user = User.create(
                email = '*****@*****.**',
                password = '******',
                given_name = 'Snoop',
                surname = 'Dogg',
                custom_data = {
                    'favorite_state': 'California',
                    'favorite_genre': 'reggae',
                    'bank_details': {
                        'name': 'Bank of America',
                        'amount': 9999999.99,
                        'branch': {
                            'name': 'Bank of Venice',
                            'address': '111 9th Street',
                            'city': 'Venice',
                            'state': 'CA',
                        },
                    },
                },
            )
            self.assertEqual(dict(user.custom_data), {
                'favorite_state': 'California',
                'favorite_genre': 'reggae',
                'bank_details': {
                    'name': 'Bank of America',
                    'amount': 9999999.99,
                    'branch': {
                        'name': 'Bank of Venice',
                        'address': '111 9th Street',
                        'city': 'Venice',
                        'state': 'CA',
                    },
                },
            })