Example #1
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)
Example #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 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)
Example #3
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')))
Example #5
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')))
Example #6
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')))