Beispiel #1
0
    def login(cls):
        """
        Simple login based on the email and password

        Required post data see :class:LoginForm
        """
        login_form = LoginForm(request.form)

        if not request.is_guest_user and request.args.get('next'):
            return redirect(request.args['next'])

        if request.method == 'POST' and login_form.validate():
            NereidUser = Pool().get('nereid.user')
            user = NereidUser.authenticate(
                login_form.email.data, login_form.password.data
            )
            # Result can be the following:
            # 1 - Browse record of User (successful login)
            # 2 - None - Login failure without message
            # 3 - Any other false value (no message is shown. useful if you
            #       want to handle the message shown to user)
            if user:
                # NOTE: Translators leave %s as such
                flash(_("You are now logged in. Welcome %(name)s",
                        name=user.display_name))
                if login_user(user, remember=login_form.remember.data):
                    if request.is_xhr:
                        return jsonify({
                            'success': True,
                            'user': user.serialize(),
                        })
                    else:
                        return redirect(
                            request.values.get(
                                'next', url_for('nereid.website.home')
                            )
                        )
                else:
                    flash(_("Your account has not been activated yet!"))
            elif user is None:
                flash(_("Invalid login credentials"))

            failed_login.send(form=login_form)

            if request.is_xhr:
                rv = jsonify(message="Bad credentials")
                rv.status_code = 401
                return rv

        return render_template('login.jinja', login_form=login_form)
Beispiel #2
0
    def login(cls):
        """
        Simple login based on the email and password

        Required post data see :class:LoginForm
        """
        login_form = LoginForm(request.form)

        if not current_user.is_anonymous() and request.args.get('next'):
            return redirect(request.args['next'])

        if request.method == 'POST' and login_form.validate():
            NereidUser = Pool().get('nereid.user')
            user = NereidUser.authenticate(
                login_form.email.data, login_form.password.data
            )
            # Result can be the following:
            # 1 - Browse record of User (successful login)
            # 2 - None - Login failure without message
            # 3 - Any other false value (no message is shown. useful if you
            #       want to handle the message shown to user)
            if user:
                # NOTE: Translators leave %s as such
                flash(_("You are now logged in. Welcome %(name)s",
                        name=user.display_name))
                if login_user(user, remember=login_form.remember.data):
                    if request.is_xhr:
                        return jsonify({
                            'success': True,
                            'user': user.serialize(),
                        })
                    else:
                        return redirect(
                            request.values.get(
                                'next', url_for('nereid.website.home')
                            )
                        )
                else:
                    flash(_("Your account has not been activated yet!"))
            elif user is None:
                flash(_("Invalid login credentials"))

            failed_login.send(form=login_form)

            if request.is_xhr:
                rv = jsonify(message="Bad credentials")
                rv.status_code = 401
                return rv

        return render_template('login.jinja', login_form=login_form)
Beispiel #3
0
    def login(self):
        """
        Simple login based on the email and password

        Required post data see :class:LoginForm
        """
        login_form = LoginForm(request.form)

        if not request.is_guest_user and request.args.get('next'):
            return redirect(request.args['next'])

        if request.method == 'POST' and login_form.validate():
            user_obj = Pool().get('nereid.user')
            result = user_obj.authenticate(
                login_form.email.data, login_form.password.data
            )
            # Result can be the following:
            # 1 - Browse record of User (successful login)
            # 2 - None - Login failure without message
            # 3 - Any other false value (no message is shown. useful if you 
            #       want to handle the message shown to user)
            if result:
                # NOTE: Translators leave %s as such
                flash(_("You are now logged in. Welcome %(name)s",
                    name=result.name))
                session['user'] = result.id
                login.send(self)
                if request.is_xhr:
                    return 'OK'
                else:
                    return redirect(
                        request.values.get(
                            'next', url_for('nereid.website.home')
                        )
                    )
            elif result is None:
                flash(_("Invalid login credentials"))

            failed_login.send(self, form=login_form)

            if request.is_xhr:
                return 'NOK'

        return render_template('login.jinja', login_form=login_form)
Beispiel #4
0
    def login(cls):
        """
        Simple login based on the email and password

        Required post data see :class:LoginForm
        """
        login_form = LoginForm(request.form)

        if not request.is_guest_user and request.args.get('next'):
            return redirect(request.args['next'])

        if request.method == 'POST' and login_form.validate():
            NereidUser = Pool().get('nereid.user')
            result = NereidUser.authenticate(login_form.email.data,
                                             login_form.password.data)
            # Result can be the following:
            # 1 - Browse record of User (successful login)
            # 2 - None - Login failure without message
            # 3 - Any other false value (no message is shown. useful if you
            #       want to handle the message shown to user)
            if result:
                # NOTE: Translators leave %s as such
                flash(
                    _("You are now logged in. Welcome %(name)s",
                      name=result.name))
                session['user'] = result.id
                login.send()
                if request.is_xhr:
                    return 'OK'
                else:
                    return redirect(
                        request.values.get('next',
                                           url_for('nereid.website.home')))
            elif result is None:
                flash(_("Invalid login credentials"))

            failed_login.send(form=login_form)

            if request.is_xhr:
                return 'NOK'

        return render_template('login.jinja', login_form=login_form)
Beispiel #5
0
    def login(cls):
        """
        Simple login based on the email and password

        Required post data see :class:LoginForm
        """
        login_form = LoginForm(request.form)

        if not request.is_guest_user and request.args.get("next"):
            return redirect(request.args["next"])

        if request.method == "POST" and login_form.validate():
            NereidUser = Pool().get("nereid.user")
            result = NereidUser.authenticate(login_form.email.data, login_form.password.data)
            # Result can be the following:
            # 1 - Browse record of User (successful login)
            # 2 - None - Login failure without message
            # 3 - Any other false value (no message is shown. useful if you
            #       want to handle the message shown to user)
            if result:
                # NOTE: Translators leave %s as such
                flash(_("You are now logged in. Welcome %(name)s", name=result.display_name))
                session["user"] = result.id
                login.send()
                if request.is_xhr:
                    return "OK"
                else:
                    return redirect(request.values.get("next", url_for("nereid.website.home")))
            elif result is None:
                flash(_("Invalid login credentials"))

            failed_login.send(form=login_form)

            if request.is_xhr:
                return "NOK"

        return render_template("login.jinja", login_form=login_form)
class NereidUser:
    "******"
    __name__ = "nereid.user"

    github_id = fields.Integer('Github ID')
    github_url = fields.Char('Github URL')

    @classmethod
    @route("/auth/github", methods=["GET"])
    def github_login(cls):
        """
        The URL to which a new request to authenticate to github begins
        Usually issues a redirect.
        """
        github = request.nereid_website.get_github_oauth_client()
        if github is None:
            return redirect(request.referrer
                            or url_for('nereid.website.login'))
        return github.authorize(callback=url_for(
            'nereid.user.github_authorized_login',
            next=request.args.get('next') or request.referrer or None,
            _external=True))

    @classmethod
    @route("/auth/github-authorized-login", methods=["GET"])
    def github_authorized_login(cls):
        """
        Authorized handler to which github will redirect the user to
        after the login attempt is made.
        """
        github = request.nereid_website.get_github_oauth_client()
        if github is None:
            return redirect(request.referrer
                            or url_for('nereid.website.login'))

        try:
            # The response is an oauth2 response with code. But Github API
            # requires the
            if 'oauth_verifier' in request.args:
                data = github.handle_oauth1_response()
            elif 'code' in request.args:
                data = github.handle_oauth2_response()
            else:
                data = github.handle_unknown_response()
            github.free_request_token()
        except Exception, exc:
            current_app.logger.error("Github login failed %s" % exc)
            flash(_("We cannot talk to github at this time. Please try again"))
            return redirect(request.referrer
                            or url_for('nereid.website.login'))

        if data is None:
            flash(
                _("Access was denied to github: %(reason)s",
                  reason=request.args['error_reason']))
            failed_login.send(form=data)
            return redirect(url_for('nereid.website.login'))

        # Write the oauth token to the session
        session['github_oauth_token'] = data['access_token']

        # Find the information from facebook
        me = requests.get('https://api.github.com/user',
                          params={
                              'access_token': session['github_oauth_token']
                          }).json

        # Find the user
        users = cls.search([
            ('email', '=', me['email']),
            ('company', '=', request.nereid_website.company.id),
        ])
        if not users:
            current_app.logger.debug("No Github user with email %s" %
                                     me['email'])
            current_app.logger.debug("Registering new user %s" % me['name'])
            user, = cls.create([{
                'name': me['name'],
                'display_name': me['name'],
                'email': me['email'],
                'github_id': me['id'],
                'addresses': False,
                'github_url': me['html_url'],
            }])
            flash(_('Thanks for registering with us using github'))
        else:
            user, = users

        # Add the user to session and trigger signals
        session['user'] = user.id
        if not user.github_id:
            cls.write([user], {
                'github_id': me['id'],
                'github_url': me['html_url']
            })
        flash(_("You are now logged in. Welcome %(name)s", name=user.name))
        login.send()
        if request.is_xhr:
            return 'OK'
        return redirect(
            request.values.get('next', url_for('nereid.website.home')))
Beispiel #7
0
    def sign_in(cls):
        '''
        Step 1: Sign In or Register

        GET
        ~~~

        Renders a sign-in or register page. If guest checkout is enabled, then
        an option to continue as guest is also permitted, in which case the
        email is a required field.

        POST
        ~~~~

        For guest checkout, this sign in would create a new party with the name
        as the current session_id and move the shopping cart's sale to the
        new user's ownership

        Designer notes: The registration or login must contact the
        corresponding handlers. Login and Registraion handlers are designed to
        handle a `next` parameter where the user would be redirected to if the
        operation was successful. The next url is provided in the context

        OTOH, if the user desires to checkout as guest, the user is required to
        fill in the email and submit the form, which posts the email to this
        handler.
        '''
        NereidCart = Pool().get('nereid.cart')
        NereidUser = Pool().get('nereid.user')
        Party = Pool().get('party.party')

        if not current_user.is_anonymous:
            form = cls.sign_in_form(
                email=current_user.email,
                checkout_mode='account',
            )
        else:
            # Guest user
            form = cls.sign_in_form(
                email=session.get('email'),
                checkout_mode='guest',
            )

        if form.validate_on_submit():
            if form.checkout_mode.data == 'guest':

                if not cls.allowed_as_guest(form.email.data):
                    return render_template(
                        'checkout/signin-email-in-use.jinja',
                        email=form.email.data)

                cart = NereidCart.open_cart()
                party_name = unicode(
                    _('Guest with email: %(email)s', email=form.email.data))
                if cart.sale.party == current_website.guest_user.party:
                    # Create a party with the email as email, and session as
                    # name, but attach the session to it.
                    party, = Party.create([{
                        'name':
                        party_name,
                        'nereid_session':
                        session.sid,
                        'addresses': [],
                        'contact_mechanisms': [('create', [{
                            'type':
                            'email',
                            'value':
                            form.email.data,
                        }])]
                    }])

                    cart.sale.party = party
                    # TODO: Avoid this if the user comes to sign-in twice.
                    cart.sale.shipment_address = None
                    cart.sale.invoice_address = None
                    cart.sale.save()
                else:
                    # Perhaps the email changed ?
                    party = cart.sale.party
                    party.name = party_name

                    # contact_mechanism of email type will always be there for
                    # Guest user
                    contact_mechanism = filter(lambda c: c.type == 'email',
                                               party.contact_mechanisms)[0]
                    contact_mechanism.value = form.email.data
                    contact_mechanism.save()
                    party.email = form.email.data
                    party.save()

                return redirect(url_for('nereid.checkout.shipping_address'))
            else:
                # The user wants to use existing email to login
                user = NereidUser.authenticate(form.email.data,
                                               form.password.data)
                if user:
                    # FIXME: Remove remember_me
                    login_user(user, remember=form.remember.data)
                    return redirect(
                        url_for('nereid.checkout.shipping_address'))
                else:
                    failed_login.send()

        if not current_user.is_anonymous:
            # Registered user with a fresh login can directly proceed to
            # step 2, which is filling the shipping address
            #
            # if this is a recent sign-in by a registred user
            # automatically proceed to the shipping_address step
            return redirect(url_for('nereid.checkout.shipping_address'))

        return render_template(
            'checkout/signin.jinja',
            form=form,
            next=url_for('nereid.checkout.shipping_address'))
Beispiel #8
0
class NereidUser(ModelSQL, ModelView):
    "Nereid User"
    _name = "nereid.user"

    facebook_id = fields.Char('Facebook ID')

    def facebook_login(self):
        """The URL to which a new request to authenticate to facebook begins
        Usually issues a redirect.
        """
        website_obj = Pool().get('nereid.website')

        facebook = website_obj.get_facebook_oauth_client()
        if facebook is None:
            return redirect(request.referrer
                            or url_for('nereid.website.login'))
        return facebook.authorize(callback=url_for(
            'nereid.user.facebook_authorized_login',
            next=request.args.get('next') or request.referrer or None,
            _external=True))

    def facebook_authorized_login(self):
        """Authorized handler to which facebook will redirect the user to
        after the login attempt is made.
        """
        website_obj = Pool().get('nereid.website')

        facebook = website_obj.get_facebook_oauth_client()
        if facebook is None:
            return redirect(request.referrer
                            or url_for('nereid.website.login'))

        try:
            if 'oauth_verifier' in request.args:
                data = facebook.handle_oauth1_response()
            elif 'code' in request.args:
                data = facebook.handle_oauth2_response()
            else:
                data = facebook.handle_unknown_response()
            facebook.free_request_token()
        except Exception, exc:
            current_app.logger.error("Facebook login failed", exc)
            flash(
                _("We cannot talk to facebook at this time. Please try again"))
            return redirect(request.referrer
                            or url_for('nereid.website.login'))

        if data is None:
            flash(
                _("Access was denied to facebook: %(reason)s",
                  reason=request.args['error_reason']))
            failed_login.send(self, form=data)
            return redirect(url_for('nereid.website.login'))

        # Write the oauth token to the session
        session['facebook_oauth_token'] = (data['access_token'], '')

        # Find the information from facebook
        me = facebook.get('/me')

        # Find the user
        user_ids = self.search([
            ('email', '=', me.data['email']),
            ('company', '=', request.nereid_website.company.id),
        ])
        if not user_ids:
            current_app.logger.debug("No FB user with email %s" %
                                     me.data['email'])
            current_app.logger.debug("Registering new user %s" %
                                     me.data['name'])
            user_id = self.create({
                'name': me.data['name'],
                'display_name': me.data['name'],
                'email': me.data['email'],
                'facebook_id': me.data['id'],
                'addresses': False,
            })
            flash(_('Thanks for registering with us using facebook'))
        else:
            user_id, = user_ids

        # Add the user to session and trigger signals
        session['user'] = user_id
        user = self.browse(user_id)
        if not user.facebook_id:
            # if the user has no facebook id save it
            self.write(user_id, {'facebook_id': me.data['id']})
        flash(_("You are now logged in. Welcome %(name)s", name=user.name))
        login.send(self)
        if request.is_xhr:
            return 'OK'
        return redirect(
            request.values.get('next', url_for('nereid.website.home')))
    def sign_in(cls):
        '''
        Step 1: Sign In or Register

        GET
        ~~~

        Renders a sign-in or register page. If guest checkout is enabled, then
        an option to continue as guest is also permitted, in which case the
        email is a required field.

        POST
        ~~~~

        For guest checkout, this sign in would create a new party with the name
        as the current session_id and move the shopping cart's sale to the
        new user's ownership

        Designer notes: The registration or login must contact the
        corresponding handlers. Login and Registraion handlers are designed to
        handle a `next` parameter where the user would be redirected to if the
        operation was successful. The next url is provided in the context

        OTOH, if the user desires to checkout as guest, the user is required to
        fill in the email and submit the form, which posts the email to this
        handler.
        '''
        NereidCart = Pool().get('nereid.cart')
        NereidUser = Pool().get('nereid.user')
        Party = Pool().get('party.party')

        if not current_user.is_anonymous():
            form = cls.sign_in_form(
                email=current_user.email,
                checkout_mode='account',
            )
        else:
            # Guest user
            form = cls.sign_in_form(
                email=session.get('email'),
                checkout_mode='guest',
            )

        if form.validate_on_submit():
            if form.checkout_mode.data == 'guest':

                if not cls.allowed_as_guest(form.email.data):
                    return render_template(
                        'checkout/signin-email-in-use.jinja',
                        email=form.email.data
                    )

                cart = NereidCart.open_cart()
                party_name = unicode(_(
                    'Guest with email: %(email)s', email=form.email.data
                ))
                if cart.sale.party == request.nereid_website.guest_user.party:
                    # Create a party with the email as email, and session as
                    # name, but attach the session to it.
                    party, = Party.create([{
                        'name': party_name,
                        'nereid_session': session.sid,
                        'addresses': [],
                        'contact_mechanisms': [('create', [{
                            'type': 'email',
                            'value': form.email.data,
                        }])]
                    }])

                    cart.sale.party = party
                    # TODO: Avoid this if the user comes to sign-in twice.
                    cart.sale.shipment_address = None
                    cart.sale.invoice_address = None
                    cart.sale.save()
                else:
                    # Perhaps the email changed ?
                    party = cart.sale.party
                    party.name = party_name

                    # contact_mechanism of email type will always be there for
                    # Guest user
                    contact_mechanism = filter(
                        lambda c: c.type == 'email', party.contact_mechanisms
                    )[0]
                    contact_mechanism.value = form.email.data
                    contact_mechanism.save()
                    party.email = form.email.data
                    party.save()

                return redirect(
                    url_for('nereid.checkout.shipping_address')
                )
            else:
                # The user wants to use existing email to login
                user = NereidUser.authenticate(
                    form.email.data, form.password.data
                )
                if user:
                    # FIXME: Remove remember_me
                    login_user(user, remember=form.remember.data)
                    return redirect(
                        url_for('nereid.checkout.shipping_address')
                    )
                else:
                    failed_login.send()

        if not current_user.is_anonymous():
            # Registered user with a fresh login can directly proceed to
            # step 2, which is filling the shipping address
            #
            # if this is a recent sign-in by a registred user
            # automatically proceed to the shipping_address step
            return redirect(url_for('nereid.checkout.shipping_address'))

        return render_template(
            'checkout/signin.jinja',
            form=form,
            next=url_for('nereid.checkout.shipping_address')
        )
Beispiel #10
0
class NereidUser:
    "******"
    __name__ = "nereid.user"

    linkedin_auth = fields.Boolean('LinkedIn Auth')

    @classmethod
    @route("/auth/linkedin", methods=["GET"])
    def linkedin_login(cls):
        """The URL to which a new request to authenticate to linedin begins
        Usually issues a redirect.
        """
        linkedin = request.nereid_website.get_linkedin_oauth_client()
        if linkedin is None:
            return redirect(request.referrer
                            or url_for('nereid.website.login'))
        return linkedin.authorize(callback=url_for(
            'nereid.user.linkedin_authorized_login',
            next=request.args.get('next') or request.referrer or None,
            _external=True))

    @classmethod
    @route("/auth/linkedin_authorized_login", methods=["GET"])
    def linkedin_authorized_login(cls):
        """Authorized handler to which linkedin will redirect the user to
        after the login attempt is made.
        """
        Party = Pool().get('party.party')

        linkedin = request.nereid_website.get_linkedin_oauth_client()
        if linkedin is None:
            return redirect(request.referrer
                            or url_for('nereid.website.login'))

        try:
            if 'oauth_verifier' in request.args:
                data = linkedin.handle_oauth1_response()
            elif 'code' in request.args:
                data = linkedin.handle_oauth2_response()
            else:
                data = linkedin.handle_unknown_response()
            linkedin.free_request_token()
        except Exception, exc:
            current_app.logger.error("LinkedIn login failed %s" % exc)
            flash(
                _("We cannot talk to linkedin at this time. Please try again"))
            return redirect(request.referrer
                            or url_for('nereid.website.login'))

        if data is None:
            flash(
                _("Access was denied to linkedin: %(reason)s",
                  reason=request.args['error_reason']))
            failed_login.send(form=data)
            return redirect(url_for('nereid.website.login'))

        # Write the oauth token to the session
        session['linkedin_oauth_token'] = (data['oauth_token'],
                                           data['oauth_token_secret'])

        # Find the information from facebook
        me = linkedin.get('http://api.linkedin.com/v1/people/~?format=json')
        email = linkedin.get(
            'http://api.linkedin.com/v1/people/~/email-address?format=json')
        session.pop('linkedin_oauth_token')

        # Find the user
        with Transaction().set_context(active_test=False):
            users = cls.search([
                ('email', '=', email.data),
                ('company', '=', request.nereid_website.company.id),
            ])
        if not users:
            current_app.logger.debug("No LinkedIn user with email %s" %
                                     email.data)
            name = u'%s %s' % (me.data['firstName'], me.data['lastName'])
            current_app.logger.debug("Registering new user %s" % name)
            user, = cls.create([{
                'party': Party.create([{
                    'name': name
                }])[0].id,
                'display_name': name,
                'email': email.data,
                'linkedin_auth': True,
                'active': True,
            }])
            flash(_('Thanks for registering with us using linkedin'))
        else:
            user, = users

        # Add the user to session and trigger signals
        session['user'] = user.id
        if not user.linkedin_auth:
            cls.write([user], {'linkedin_auth': True})
        flash(_("You are now logged in. Welcome %(name)s", name=user.rec_name))
        login.send()
        if request.is_xhr:
            return 'OK'
        return redirect(
            request.values.get('next', url_for('nereid.website.home')))
Beispiel #11
0
class NereidUser:
    "******"
    __name__ = "nereid.user"

    facebook_id = fields.Char('Facebook ID')

    @classmethod
    @route('/auth/facebook')
    def facebook_login(cls):
        """The URL to which a new request to authenticate to facebook begins
        Usually issues a redirect.
        """
        facebook = request.nereid_website.get_facebook_oauth_client()
        if facebook is None:
            return redirect(request.referrer
                            or url_for('nereid.website.login'))
        return facebook.authorize(callback=url_for(
            'nereid.user.facebook_authorized_login',
            next=request.args.get('next') or request.referrer or None,
            _external=True))

    @classmethod
    @route('/auth/facebook_authorized_login')
    def facebook_authorized_login(cls):
        """Authorized handler to which facebook will redirect the user to
        after the login attempt is made.
        """
        Party = Pool().get('party.party')

        facebook = request.nereid_website.get_facebook_oauth_client()
        if facebook is None:
            return redirect(request.referrer
                            or url_for('nereid.website.login'))

        try:
            if 'oauth_verifier' in request.args:
                data = facebook.handle_oauth1_response()
            elif 'code' in request.args:
                data = facebook.handle_oauth2_response()
            else:
                data = facebook.handle_unknown_response()
            facebook.free_request_token()
        except Exception, exc:
            current_app.logger.error("Facebook login failed", exc)
            flash(
                _("We cannot talk to facebook at this time. Please try again"))
            return redirect(request.referrer
                            or url_for('nereid.website.login'))

        if data is None:
            flash(
                _("Access was denied to facebook: %(reason)s",
                  reason=request.args['error_reason']))
            failed_login.send(form=data)
            return redirect(url_for('nereid.website.login'))

        # Write the oauth token to the session
        session['facebook_oauth_token'] = (data['access_token'], '')

        # Find the information from facebook
        me = facebook.get('/me')

        # Find the user
        with Transaction().set_context(active_test=False):
            users = cls.search([
                ('email', '=', me.data['email']),
                ('company', '=', request.nereid_website.company.id),
            ])
        if not users:
            current_app.logger.debug("No FB user with email %s" %
                                     me.data['email'])
            current_app.logger.debug("Registering new user %s" %
                                     me.data['name'])
            party, = Party.create([{'name': me.data['name']}])
            user, = cls.create([{
                'party': party.id,
                'display_name': me.data['name'],
                'email': me.data['email'],
                'facebook_id': me.data['id'],
                'active': True,
            }])
            flash(_('Thanks for registering with us using facebook'))
        else:
            user, = users

        if not user.facebook_id:
            # if the user has no facebook id save it
            cls.write([user], {'facebook_id': me.data['id']})
        flash(
            _("You are now logged in. Welcome %(name)s",
              name=user.display_name))
        login_user(user)
        if request.is_xhr:
            return 'OK'
        return redirect(
            request.values.get('next', url_for('nereid.website.home')))