Esempio n. 1
0
def login_view(context, request):
    whence = request.registry.queryUtility(ICameFromURL)
    if whence is not None:
        came_from = whence(request)
    else:
        came_from = resource_url(context, request)
    form = Form(Login(), buttons=('login',))
    rendered_form = form.render({'came_from': came_from})
    message = request.GET.get('message')

    if 'login' in request.POST:
        try:
            appstruct = form.validate(request.POST.items())
        except ValidationFailure, e:
            rendered_form = e.render()
            message = 'Please supply required values'
        else:
            credentials = {'login': appstruct['login_name'],
                           'password': appstruct['password'],
                          }
            api = get_api(request.environ)
            identity, headers =  api.login(credentials)
            if identity is not None:
                came_from = appstruct.get('came_from')
                if came_from is None:
                    came_from = resource_url(context, request)
                return HTTPFound(location=came_from, headers=headers)
            message = 'Login failed'
Esempio n. 2
0
    def logout(self):
        """Action to log the user out of ecomaps - removing their session"""

        who_api = get_api(request.environ)
        headers = who_api.logout()

        return HTTPFound(location='/account/login', headers=headers)
def login(request):
    form = login_form(request)
    params = base_view_params(request, _(u"Login")).copy()
    params["form"] = form.render()

    controls = request.POST.items()
    if controls:
        who_api = get_api(request.environ)

        try:
            data = form.validate(controls)
        except ValidationFailure, e:
            params['form'] = e.render()
            return params

        # check and authenticate
        authenticated, headers = who_api.login(data)
        if authenticated:
            came_from = request.params.get('came_from', '/')

            return HTTPFound(
                location=came_from,
                headers=headers
            )
        else:
            set_status_message(
                request,
                _(u"Invalid username or password"),
                type_='danger'
            )
            return HTTPFound(location=request.route_url('login'))
    def authenticate(self, environ, identity):
        """Authenticate the identity from the given request environment.

        This method checks whether an entry matching the identity is currently
        stored in the cache.  If so, it loads data from the stored entry and
        return successfully.
        """
        # Only do anything if we're wrapping an authenticator.
        if self.authenticator_name is None:
            return None
        api = get_api(environ)
        if api is None:
            return None
        wrapped_authenticator = api.name_registry[self.authenticator_name]
        # Check if we've got cached data already.
        data = self._get_cached(environ, identity, "authenticate")
        if data is not None:
            identity.update(data)
            return identity.get("repoze.who.userid")
        # Not cached, check with the wrapped authenticator.
        value_items = self.value_items
        if value_items is None:
            old_keys = set(identity.iterkeys())
        userid = wrapped_authenticator.authenticate(environ, identity)
        if userid is None:
            return None
        # If that was successful, cache it along with any added data.
        # Make sure to always cache repoze.who.userid.
        if value_items is None:
            value_items = [k for k in identity.iterkeys() if k not in old_keys]
        identity.setdefault("repoze.who.userid", userid)
        value_items = ["repoze.who.userid"] + list(value_items)
        self._set_cached(environ, identity, value_items, "authenticate")
        return userid
Esempio n. 5
0
    def register(self):
        if app_globals.sandbox_mode:
            default_roles = ["user", "admin"]
        else:
            default_roles = ["user"]

        errors, values = {}, None
        if request.method == 'POST':
            try:
                schema = Register()
                values = request.params
                account = schema.deserialize(values)
                exists = model.Account.find_one({"name": account['name']})
                if exists:
                    raise colander.Invalid(
                        Register.name,
                        _("Login name already exists, please choose a "
                          "different one"))
                if not account['password1'] == account['password2']:
                    raise colander.Invalid(Register.password1, _("Passwords \
                        don't match!"))
                password = account['password1']
                account['password_hash'] = \
                    generate_password_hash(password)
                del account['password1']
                del account['password2']
                account['_roles'] = default_roles
                model.Account.c.insert(account)
                who_api = get_api(request.environ)
                authenticated, headers = who_api.login(
                    {"login": account['name'], "password": password})
                response.headers.extend(headers)
                return redirect("/")
            except colander.Invalid, i:
                errors = i.asdict()
Esempio n. 6
0
    def create(self):
        require.user.create()
        if self.email_is_blacklisted(self.form_result['email']):
            return ret_abort(_("Sorry, but we don't accept registrations with "
                               "this email address."), category='error',
                             code=403)

        # SPAM protection recaptcha
        captacha_enabled = config.get('recaptcha.public_key', "")
        if captacha_enabled:
            recaptcha_response = h.recaptcha.submit()
            if not recaptcha_response.is_valid:
                c.recaptcha = h.recaptcha.displayhtml(
                    use_ssl=True,
                    error=recaptcha_response.error_code)
                redirect("/register")
        # SPAM protection hidden input
        input_css = self.form_result.get("input_css")
        input_js = self.form_result.get("input_js")
        if input_css or input_js:
            redirect("/")

        #create user
        user = model.User.create(self.form_result.get("user_name"),
                                 self.form_result.get("email").lower(),
                                 password=self.form_result.get("password"),
                                 locale=c.locale)
        model.meta.Session.commit()

        event.emit(event.T_USER_CREATE, user)
        libmail.send_activation_link(user)

        if c.instance:
            membership = user.instance_membership(c.instance)
            if membership is None:
                membership = model.Membership(user, c.instance,
                                              c.instance.default_group)
                model.meta.Session.expunge(membership)
                model.meta.Session.add(membership)
                model.meta.Session.commit()

        # authenticate the new registered member using the repoze.who
        # api. This is done here and not with an redirect to the login
        # to omit the generic welcome message
        who_api = get_api(request.environ)
        login = self.form_result.get("user_name").encode('utf-8')
        credentials = {
            'login': login,
            'password': self.form_result.get("password").encode('utf-8')}
        authenticated, headers = who_api.login(credentials)
        if authenticated:
            # redirect to dashboard with login message
            session['logged_in'] = True
            session.save()
            location = h.base_url('/user/%s/dashboard' % login)
            raise HTTPFound(location=location, headers=headers)
        else:
            raise Exception('We have added the user to the Database '
                            'but cannot authenticate him: '
                            '%s (%s)' % (credentials['login'], user))
Esempio n. 7
0
    def logout(self):
        """Action to log the user out - removing their session"""

        who_api = get_api(request.environ)
        who_api.logout()
        self.current_user = None
        redirect(url(controller='home', action='index'))
    def login(self):
        request = self.request
        who_api = get_api(request.environ)
        came_from = request.params.get("came_from", request.referrer or "/")
        message = ''
        login = ''
        password = ''
        if 'form.submitted' in request.params:
            creds = {}
            creds['login'] = request.params.get('login', '')
            creds['password'] = request.params.get('password', '')
            authenticated, headers = who_api.login(creds)
            if authenticated:
                return HTTPFound(location=came_from,
                                 headers=headers)
            message = _(u'Failed login')
        else:
            # Remove authentication
            if who_api:
                anon, headers = who_api.login({})

        if 'REMOTE_USER' in request.environ:
            del request.environ['REMOTE_USER']

        return dict(page_title=_(u'Login'),
                    message=message,
                    url=request.application_url,
                    came_from=came_from,
                    login=login,
                    password=password,
                   )
Esempio n. 9
0
 def register(self):
     require.account.create()
     errors, values = {}, None
     if request.method == 'POST':
         try:
             schema = AccountRegister()
             values = request.params
             data = schema.deserialize(values)
             if Account.by_name(data['name']):
                 raise colander.Invalid(
                     AccountRegister.name,
                     _("Login name already exists, please choose a "
                       "different one"))
             if not data['password1'] == data['password2']:
                 raise colander.Invalid(AccountRegister.password1, _("Passwords \
                     don't match!"))
             account = Account()
             account.name = data['name']
             account.fullname = data['fullname']
             account.email = data['email']
             account.password = generate_password_hash(data['password1'])
             db.session.add(account)
             db.session.commit()
             who_api = get_api(request.environ)
             authenticated, headers = who_api.login({
                 "login": account.name,
                 "password": data['password1']
             })
             response.headers.extend(headers)
             return redirect("/")
         except colander.Invalid, i:
             errors = i.asdict()
Esempio n. 10
0
def login(request, user_name, password):
    from repoze.who.api import get_api
    who_api = get_api(request.environ)

    credentials = {
        'login': user_name,
        'password': password,
        }
    return who_api.login(credentials)
Esempio n. 11
0
def autoLoginViaWhoAPI(uuid, request):
    api = get_api(request.environ)
    if api is None:
        raise ValueError("Couldn't find / create repoze.who API object")
    credentials = {'repoze.who.plugins.auth_tkt.userid': uuid}
    settings = request.registry.settings
    plugin_id = settings.get('cartouche.auto_login_identifier', 'auth_tkt')
    identity, headers = api.login(credentials, plugin_id)
    return headers
Esempio n. 12
0
def autoLoginViaWhoAPI(uuid, request):
    api = get_api(request.environ)
    if api is None:
        raise ValueError("Couldn't find / create repoze.who API object")
    credentials = {'repoze.who.plugins.auth_tkt.userid': uuid}
    settings = request.registry.settings
    plugin_id = settings.get('cartouche.auto_login_identifier', 'auth_tkt')
    identity, headers = api.login(credentials, plugin_id)
    return headers
Esempio n. 13
0
File: home.py Progetto: tonky/croner
    def index(self):
        who_api = get_api(request.environ)

        user = who_api.authenticate()

        if not user:
            return who_api.challenge()

        # Return a rendered template
        return render('/index.mako', {'user': user})
Esempio n. 14
0
def logout_view(context, request):
    if 'logout' in request.POST:
        api = get_api(request.environ)
        headers =  api.logout()
        after_logout_url = view_url(context, request, 'after_logout_url', '')
        return HTTPFound(location=after_logout_url, headers=headers)
    identity = request.environ.get('repoze.who.identity', {})
    main_template = get_renderer('templates/main.pt')
    return {'userid': identity.get('repoze.who.userid'),
            'main_template': main_template.implementation(),
           }
def logout(request):
    who_api = get_api(request.environ)
    headers = who_api.logout()

    set_status_message(
        request,
        _(u"Logged out"),
        type_='success'
    )

    return HTTPFound(location='/login', headers=headers)
    def forget(self, environ, identity):
        """Forget the authenticated identity.

        BrowserID has no builtin mechanism for persistent logins.  This
        method simply delegates to another IIdentifier plugin if configured.
        """
        headers = []
        api = get_api(environ)
        if self.rememberer_name is not None and api is not None:
            plugin = api.name_registry[self.rememberer_name]
            i_headers = plugin.forget(environ, identity)
            if i_headers is not None:
                headers.extend(i_headers)
        return headers
Esempio n. 17
0
    def forget(self, environ, identity):
        """Forget the authenticated identity.

        BrowserID has no builtin mechanism for persistent logins.  This
        method simply delegates to another IIdentifier plugin if configured.
        """
        headers = []
        api = get_api(environ)
        if self.rememberer_name is not None and api is not None:
            plugin = api.name_registry[self.rememberer_name]
            i_headers = plugin.forget(environ, identity)
            if i_headers is not None:
                headers.extend(i_headers)
        return headers
Esempio n. 18
0
    def login(self, req, session, start_response):
        """Handles submission of the login form.

        @type req: webob.Request
        @param req: HTTP request object

        @type session: Beaker SessionObject
        @param session: session data

        @type start_response: 
        @param start_response: WSGI start response function

        @rtype: iterable
        @return: WSGI response
        """
        if ('submit' in req.params) and ('cancel' not in req.params):
            username = req.params.get('username')
            password = req.params.get('password')
            credentials = {'login': username, 'password': password}
            repoze_who_api = get_api(req.environ)
            (identity, headers) = repoze_who_api.login(credentials)
            if identity is not None:
                logged_in_username = identity['repoze.who.userid']
                log.debug("Logged in using username %s as %s", username,
                          logged_in_username)
    
                if self.combined_authorization:
                    self._set_client_authorization(req, session,
                                                   logged_in_username)
                return_url = req.params.get(self.return_url_param)
                return self._redirect(return_url, start_response, headers)
            else:
                # Login failed - redirect to login form.
                return_url = req.params.get(self.return_url_param)
                form_url = (req.application_url + self.base_path +
                    '/login_form' + '?' +
                    urllib.urlencode({self.return_url_param: return_url}))
                return self._redirect(form_url, start_response)
        else:
            # User cancelled authentication - confirm this.
            c = {'baseURL': req.application_url}
            response = self.renderer.render(self.authentication_cancelled,
                            self._renderingConfiguration.merged_parameters(c))
            start_response(self._get_http_status_string(httplib.OK),
               [('Content-type', 'text/html'),
                ('Content-length', str(len(response)))
                ])
            return [response]
Esempio n. 19
0
    def login(self):
        c.message = ""
        who_api = get_api(request.environ)
        if "login" in request.POST:
            authenticated, headers = who_api.login({"login": request.POST["login"], "passwd": request.POST["passwd"]})
            if authenticated:
                response.headers = headers
                return redirect("/")
            c.message = "Zły login lub hasło"
        else:
            # Forcefully forget any existing credentials.
            authenticated, headers = who_api.login({})

        if "REMOTE_USER" in request.environ:
            del request.environ["REMOTE_USER"]

        return render("/users/login.mako")
Esempio n. 20
0
def login_user(user, request, response):
    '''
    log an user in.

    *user* (:class:`adhocracy.model.User`)
         The user as whom to login
    *request* (:class:`webob.request.Request`)
         The current request object to return to the user
    '''
    identity = {'repoze.who.userid': str(user.user_name),
                'timestamp': int(datetime.utcnow().strftime("%s")),
                'user': user}

    api = get_api(request.environ)
    for name, identifier in api.identifiers:
        headers = identifier.remember(request.environ, identity)
        if headers is not None:
            response.headerlist.extend(headers)
Esempio n. 21
0
def login_view(context, request):
    whence = request.registry.queryUtility(ICameFromURL)
    if whence is not None:
        came_from = whence(request)
    else:
        came_from = resource_url(context, request)
    form = Form(Login(), buttons=('login',))
    rendered_form = form.render({'came_from': came_from})
    message = request.GET.get('message')

    if 'login' in request.POST:
        try:
            appstruct = form.validate(request.POST.items())
        except ValidationFailure as e:
            rendered_form = e.render()
            message = 'Please supply required values'
        else:
            credentials = {'login': appstruct['login_name'],
                           'password': appstruct['password'],
                          }
            api = get_api(request.environ)
            identity, headers =  api.login(credentials)
            if identity is not None:
                came_from = appstruct.get('came_from')
                if came_from is None:
                    came_from = resource_url(context, request)
                return HTTPFound(location=came_from, headers=headers)
            message = 'Login failed'

    main_template = get_renderer('templates/main.pt')
    return {'main_template': main_template.implementation(),
            'came_from': came_from,
            'rendered_form': rendered_form,
            'message': message,
            'register_url': view_url(context, request,
                                     'register_url',
                                     'register.html'),
            'recover_account_url': view_url(context, request,
                                            'recover_account_url',
                                            'recover_account.html'),
            'reset_password_url': view_url(context, request,
                                           'reset_password_url',
                                           'reset_password.html'),
           }
Esempio n. 22
0
def login_user(user, request):
    '''
    log an user in.

    *user* (:class:`adhocracy.model.User`)
         The user as whom to login
    *request* (:class:`webob.request.Request`)
         The current request object to return to the user
    '''
    identity = {'repoze.who.userid': str(user.user_name),
                'timestamp': int(datetime.utcnow().strftime("%s")),
                'user': user}

    api = get_api(request.environ)
    for name, identifier in api.identifiers:
        if identity is not None:
            headers = identifier.remember(request.environ, identity)
            if headers is not None:
                request.response.headerlist.extend(headers)
Esempio n. 23
0
    def register(self):
        require.account.create()
        c.config = config
        self._disable_cache()
        errors, values = {}, None
        if request.method == 'POST':
            try:
                schema = AccountRegister()
                values = request.params
                data = schema.deserialize(values)
                if Account.by_name(data['name']):
                    raise colander.Invalid(
                        AccountRegister.name,
                        _("Login name already exists, please choose a "
                          "different one"))
                if not data['password1'] == data['password2']:
                    raise colander.Invalid(AccountRegister.password1,
                                           _("Passwords don't match!"))
                account = Account()
                account.name = data['name']
                account.fullname = data['fullname']
                account.email = data['email']
                account.password = generate_password_hash(data['password1'])
                db.session.add(account)
                db.session.commit()
                who_api = get_api(request.environ)
                authenticated, headers = who_api.login({
                    "login":
                    account.name,
                    "password":
                    data['password1']
                })

                errors = subscribe_lists(('community', 'developer'), data)
                if errors:
                    h.flash_notice(
                        _("Subscription to the following mailing " +
                          "lists probably failed: %s.") % ', '.join(errors))

                response.headers.extend(headers)
                return redirect("/")
            except colander.Invalid, i:
                errors = i.asdict()
Esempio n. 24
0
def login(request):
    message = ''
    info = {}

    # Remember any 'came_from', for redirection on succcesful login.
    came_from = request.params.get('came_from')
    if came_from is not None:
        info['came_from'] = (
        '<input type="hidden" name="came_from" value="%s" />' % came_from)
    else:
        info['came_from'] = ''

    who_api = get_api(request.environ)
    if 'form.login' in request.POST:
        # Validate credentials.
        creds = {}
        creds['login'] = request.POST['login']
        creds['password'] = request.POST['password']
        authenticated, headers = who_api.login(creds)

        if authenticated:
            # Redirect to 'came_from', or to root.
            # headers here are "remember" headers, setting the
            # auth_tkt cookies.
            return HTTPFound(location=came_from or '/',
                             headers=headers)

        else:
            message = 'Invalid login.'
    else:
        # Forcefully forget any existing credentials.
        _, headers = who_api.login({})

    # Headers here are "forget" headers, clearing the auth_tkt cookies.
    request.response_headerlist = headers

    if 'REMOTE_USER' in request.environ:
        del request.environ['REMOTE_USER']

    info['message'] = message

    return Response(LOGIN_FORM % info)
Esempio n. 25
0
    def __call__(self):
        data = self.extract()

        if not data or not data['login'] or not data['password']:
            return FAILURE, [], data

        who_api = get_api(self.environ)
        self.environ['remote.hub'] = self.context
        authenticated, headers = who_api.login(data)
        
        if authenticated:
            return SUCCESS, headers, data
        else:
            _, headers = who_api.login({})

        self.request.response_headerlist = headers
        if 'REMOTE_USER' in self.request.environ:
            del self.request.environ['REMOTE_USER']

        return FAILURE, headers, data
Esempio n. 26
0
def login(request):
    message = ''
    info = {}

    # Remember any 'came_from', for redirection on succcesful login.
    came_from = request.params.get('came_from')
    if came_from is not None:
        info['came_from'] = (
            '<input type="hidden" name="came_from" value="%s" />' % came_from)
    else:
        info['came_from'] = ''

    who_api = get_api(request.environ)
    if 'form.login' in request.POST:
        # Validate credentials.
        creds = {}
        creds['login'] = request.POST['login']
        creds['password'] = request.POST['password']
        authenticated, headers = who_api.login(creds)

        if authenticated:
            # Redirect to 'came_from', or to root.
            # headers here are "remember" headers, setting the
            # auth_tkt cookies.
            return HTTPFound(location=came_from or '/', headers=headers)

        else:
            message = 'Invalid login.'
    else:
        # Forcefully forget any existing credentials.
        _, headers = who_api.login({})

    # Headers here are "forget" headers, clearing the auth_tkt cookies.
    request.response_headerlist = headers

    if 'REMOTE_USER' in request.environ:
        del request.environ['REMOTE_USER']

    info['message'] = message

    return Response(LOGIN_FORM % info)
Esempio n. 27
0
    def register(self):
        require.account.create()
        c.config = config
        self._disable_cache()
        errors, values = {}, None
        if request.method == 'POST':
            try:
                schema = AccountRegister()
                values = request.params
                data = schema.deserialize(values)
                if Account.by_name(data['name']):
                    raise colander.Invalid(
                        AccountRegister.name,
                        _("Login name already exists, please choose a "
                          "different one"))
                if not data['password1'] == data['password2']:
                    raise colander.Invalid(AccountRegister.password1,
                                           _("Passwords don't match!"))
                account = Account()
                account.name = data['name']
                account.fullname = data['fullname']
                account.email = data['email']
                account.password = generate_password_hash(data['password1'])
                db.session.add(account)
                db.session.commit()
                who_api = get_api(request.environ)
                authenticated, headers = who_api.login({
                    "login": account.name,
                    "password": data['password1']
                })

                errors = subscribe_lists(('community', 'developer'), data)
                if errors:
                    h.flash_notice(_("Subscription to the following mailing " +
                            "lists probably failed: %s.") % ', '.join(errors))

                response.headers.extend(headers)
                return redirect("/")
            except colander.Invalid, i:
                errors = i.asdict()
 def add_metadata(self, environ, identity):
     """Add metadata to the given identity dict."""
     # Only do anything if we're wrapping an mdprovider.
     if self.mdprovider_name is None:
         return None
     api = get_api(environ)
     if api is None:
         return None
     wrapped_mdprovider = api.name_registry[self.mdprovider_name]
     # Check if we've got cached data already.
     data = self._get_cached(environ, identity, "add_metadata")
     if data is not None:
         identity.update(data)
         return None
     # Not cached, check with the wrapped mdprovider.
     value_items = self.value_items
     if value_items is None:
         old_keys = set(identity.iterkeys())
     wrapped_mdprovider.add_metadata(environ, identity)
     # Cache any data that was added.
     if value_items is None:
         value_items = [k for k in identity.iterkeys() if k not in old_keys]
     self._set_cached(environ, identity, value_items, "add_metadata")
Esempio n. 29
0
    def download(self):
        """
        Download an output dataset specified by model run ID (model_run_id),
        output variable ID (output), period string (period) and year (year)
        :return: NetCDF File download
        """
        # NOTE: This controller action can be accessed without being a logged in user.
        if request.method == 'POST':
            who_api = get_api(request.environ)
            authenticated, headers = who_api.login(dict(request.params))
            if authenticated:
                self.current_user = self._user_service.get_user_by_username(request.environ['user.username'])
        if self.current_user is None:
            abort(status_code=400, detail="User not logged in - action aborted")

        dl_format = request.params.get('format')
        _config = dict(config)
        if dl_format.lower() == 'ascii':
            download_helper = AsciiDatasetDownloadHelper(config=_config)
        else:
            download_helper = NetcdfDatasetDownloadHelper(config=_config)
        try:
            model_run_id, output_var_name, period, year = download_helper.validate_parameters(request.params,
                                                                                              self.current_user)
            model_run = self._model_run_service.get_model_by_id(self.current_user, model_run_id)
            single_cell = not model_run.get_python_parameter_value(constants.JULES_PARAM_LATLON_REGION)
            file_path = download_helper.generate_output_file_path(
                model_run_id, output_var_name, period, year, single_cell)
            download_helper.set_response_header(response.headers, file_path, model_run, output_var_name, period, year)
            # This will stream the file to the browser without loading it all in memory
            # BUT only if the .ini file does not have 'debug=true' enabled
            return download_helper.download_file_generator(file_path, model_run)
        except (ValueError, TypeError):
            abort(status_code=400, detail="Invalid request parameters")
        except NoResultFound:
            abort(status_code=400, detail="Model run ID or Output variable ID could not be found.")
Esempio n. 30
0
    def register(self):
        """
        Perform registration of a new user
        """

        # We must allow account creation
        require.account.create()

        # We add the config as a context variable in case anything happens
        # (like with login we need this to allow subscriptions to mailing lists)
        c.config = config

        # Disable the cache (don't want anything getting in the way)
        self._disable_cache()

        # Initial values and errors
        errors, values = {}, None

        # If this is a POST operation somebody is trying to register
        if request.method == 'POST':
            try:
                # Get the account register schema (for validation)
                schema = AccountRegister()

                # Set values from the request parameters
                # (for validation and so we can autofill forms)
                values = request.params

                # Grab the actual data and validate it
                data = schema.deserialize(values)

                # Check if the username already exists, return an error if so
                if Account.by_name(data['name']):
                    raise colander.Invalid(
                        AccountRegister.name,
                        _("Login name already exists, please choose a "
                          "different one"))

                # Check if passwords match, return error if not
                if not data['password1'] == data['password2']:
                    raise colander.Invalid(AccountRegister.password1,
                                           _("Passwords don't match!"))

                # Create the account
                account = Account()

                # Set username and full name
                account.name = data['name']
                account.fullname = data['fullname']

                # Set email and if email address should be public
                account.email = data['email']
                account.public_email = data['public_email']

                # Hash the password and store the hash
                account.password = generate_password_hash(data['password1'])

                # Commit the new user account to the database
                db.session.add(account)
                db.session.commit()

                # Perform a login for the user
                who_api = get_api(request.environ)
                authenticated, headers = who_api.login({
                    "login": account.name,
                    "password": data['password1']
                })
                # Add the login headers
                response.headers.extend(headers)

                # Subscribe the user to the mailing lists
                errors = subscribe_lists(('community', 'developer'), data)
                # Notify if the mailing list subscriptions failed
                if errors:
                    h.flash_notice(_("Subscription to the following mailing " +
                            "lists probably failed: %s.") % ', '.join(errors))

                # Registration successful - Redirect to the front page
                return redirect("/")
            except colander.Invalid, i:
                # Mark colander errors
                errors = i.asdict()
Esempio n. 31
0
 def login(self):
     if not tg.request.identity:
         who_api = get_api(tg.request.environ)
         return who_api.challenge()
     redirect(url('/'))
Esempio n. 32
0
    def dologin(self):
        """ Handles the log in request"""

        who_api = get_api(request.environ)
        message = ''
        came_from = request.params.get('came_from')

        if not request.POST:
            return redirect(url(controller='account', action='login', came_from=came_from))

        if came_from is u'':
            came_from = '/home'

        schema = LoginForm()
        c.form_errors = {}

        if request.POST:

            try:
                c.form_result = schema.to_python(request.params)
            except formencode.Invalid, error:
                message = 'Could not log you in as there are missing values'
                c.form_result = error.value
                c.form_errors = error.error_dict or {}
            else:

                authenticated, headers = who_api.login(c.form_result)

                if authenticated:

                    # Who is this user?
                    # If we've got enough info, we should see if they are in
                    # the ecomaps database already
                    if request.environ['user.username']:

                        user_name = request.environ['user.username']

                        log.debug("Looking for %s in Ecomaps DB" % user_name)

                        try:

                            u = self._user_service.get_user_by_username(request.environ['user.username'])

                            if not u:

                                log.debug("Couldn't find %s in Ecomaps DB, creating user" % user_name)

                                self._user_service.create(user_name,
                                                          request.environ['user.first-name'],
                                                          request.environ['user.last-name'],
                                                          request.environ['user.email'],
                                                          None)


                            return HTTPFound(location=came_from, headers=headers)

                        except ServiceException as sx:

                            # Something has gone wrong at a fundamental level, so we can't realistically continue
                            message = 'The EcoMaps database is unavailable, please contact technical support'
                            log.error("EcoMaps database unavailable: %s" % sx)

                else:
                    # Authentication not successful
                    message = 'Login failed: check your username and/or password.'
Esempio n. 33
0
    def register(self):
        """
        Perform registration of a new user
        """

        # We must allow account creation
        require.account.create()

        # We add the config as a context variable in case anything happens
        # (like with login we need this for subscriptions to mailing lists)
        c.config = config

        # Disable the cache (don't want anything getting in the way)
        self._disable_cache()

        # Initial values and errors
        errors, values = {}, None

        # If this is a POST operation somebody is trying to register
        if request.method == 'POST':
            try:
                # Get the account register schema (for validation)
                schema = AccountRegister()

                # Set values from the request parameters
                # (for validation and so we can autofill forms)
                values = request.params

                # Grab the actual data and validate it
                data = schema.deserialize(values)

                # Check if the username already exists, return an error if so
                if Account.by_name(data['name']):
                    raise colander.Invalid(
                        AccountRegister.name,
                        _("Login name already exists, please choose a "
                          "different one"))

                # Check if passwords match, return error if not
                if not data['password1'] == data['password2']:
                    raise colander.Invalid(AccountRegister.password1,
                                           _("Passwords don't match!"))

                # Create the account
                account = Account()

                # Set username and full name
                account.name = data['name']
                account.fullname = data['fullname']

                # Set email and if email address should be public
                account.email = data['email']
                account.public_email = data['public_email']

                # Hash the password and store the hash
                account.password = generate_password_hash(data['password1'])

                # Commit the new user account to the database
                db.session.add(account)
                db.session.commit()

                # Perform a login for the user
                who_api = get_api(request.environ)
                authenticated, headers = who_api.login({
                    "login":
                    account.name,
                    "password":
                    data['password1']
                })
                # Add the login headers
                response.headers.extend(headers)

                # Subscribe the user to the mailing lists
                errors = subscribe_lists(('community', 'developer'), data)
                # Notify if the mailing list subscriptions failed
                if errors:
                    h.flash_notice(
                        _("Subscription to the following mailing " +
                          "lists probably failed: %s.") % ', '.join(errors))

                # Registration successful - Redirect to the front page
                return redirect("/")
            except colander.Invalid as i:
                # Mark colander errors
                errors = i.asdict()

        # Show the templates (with possible errors and form values)
        return templating.render('account/login.html',
                                 form_fill=values,
                                 form_errors=errors)
Esempio n. 34
0
 def glogin(self):
     if not tg.request.identity:
         tg.request.environ['repoze.who.challenge'] = 'glogin'
         who_api = get_api(tg.request.environ)
         return who_api.challenge()
     redirect(url('/'))
Esempio n. 35
0
 def logout(self):
     who_api = get_api(request.environ)
     response.headers = who_api.forget()
     return redirect("/login")
Esempio n. 36
0
def logout_app(environ, start_response):
    who_api = get_api(environ)
    headers = who_api.logout()
    return HTTPFound(location='/login', headers=headers)(
                    environ, start_response)
Esempio n. 37
0
    def dologin(self):
        """ Handles the log in request"""

        who_api = get_api(request.environ)
        message = ''
        came_from = request.params.get('came_from')

        if not request.POST:
            return redirect(url(controller='account', action='login', came_from=came_from))

        if came_from is u'' or came_from is None:
            came_from = '/home'

        schema = LoginForm()
        c.form_errors = {}

        if request.POST:

            try:
                c.form_result = schema.to_python(request.params)
            except formencode.Invalid, error:
                message = 'Could not log you in as there are missing values'
                c.form_result = error.value
                c.form_errors = error.error_dict or {}
            else:
                c.form_result['login'] = c.form_result['login'].strip()
                try:
                    authenticated, headers = who_api.login(c.form_result)

                    if authenticated:

                        # Who is this user?
                        # If we've got enough info, we should see if they are in
                        # the database already

                        if request.environ['user.username']:

                            user_name = request.environ['user.username']

                            log.debug("Looking for %s in Majic DB" % user_name)

                            try:

                                u = self._user_service.get_user_by_username(request.environ['user.username'])

                                if not u:

                                    log.debug("Couldn't find %s in Majic DB, creating user" % user_name)

                                    self._user_service.create(user_name,
                                                              request.environ['user.first-name'],
                                                              request.environ['user.last-name'],
                                                              request.environ['user.email'],
                                                              None)

                                return HTTPFound(location=came_from, headers=headers)

                            except ServiceException as sx:

                                # Something has gone wrong at a fundamental level, so we can't realistically continue
                                message = 'The Majic database is unavailable, please try again later or alert ' \
                                          'the Majic administrator: %s' % config['email.admin_address']
                                log.exception("Majic database unavailable: %s" % sx)

                    else:
                        # Authentication not successful
                        message = 'Login failed: check your username and/or password.'
                except AuthenticationFailedException:
                    message = 'Login failed: check your username and/or password.'
                except ClientException:
                    message = 'Login failed: The authentication server is not responding correctly. ' \
                              'Please try again later. If the problem persists please report it to {}.'\
                        .format(config['email.admin_address'])
Esempio n. 38
0
 def _callFUT(self, environ):
     from repoze.who.api import get_api
     return get_api(environ)
Esempio n. 39
0
def logout(request):
    # Use repoze.who API to get "forget" headers.
    who_api = get_api(request.environ)
    return HTTPFound(location='/', headers=who_api.logout())
Esempio n. 40
0
 def _callFUT(self, environ):
     from repoze.who.api import get_api
     return get_api(environ)
Esempio n. 41
0
 def logout(self):
     who_api = get_api(tg.request.environ)
     headers = who_api.logout()
     return HTTPFound(headers=headers)