예제 #1
0
 def __render__(self):
     login_url = self.request.route_url('login')
     referrer = self.request.url
     if referrer == login_url:
         referrer = '/'  # never use login form itself as came_from
     came_from = self.request.params.get('came_from', referrer)
     message = ''
     login = ''
     password = ''
     if self.request.method == 'POST':
         login = self.request.POST['login']
         password = self.request.POST['password']
         valid_user = User.get(login, password)
         if valid_user:
             headers = remember(self.request, str(valid_user.id))
             User.log_login(str(valid_user.id))
             if valid_user.needs_pw_reset:
                 url = self.request.route_url('user_update')
                 return HTTPFound(location=url,
                                  headers=headers)
             return HTTPFound(location=came_from,
                              headers=headers)
         forget(self.request)
         message = 'Failed login'
     else:
         pass
     return {
         'request': self.request,
         'message': message,
     }
예제 #2
0
def forbidden_view(request):
    loc = route_url('login', request, _query=(('next', request.path),))

    # tries to refresh the token
    refresh_token = request.session.get('refresh_token')
    if refresh_token:
        print 'refreshing token'
        payload = {}
        payload['refresh_token'] = refresh_token
        payload['client_id'] = request.registry.settings.get('alfresco.consumer_key')
        payload['client_secret'] = request.registry.settings.get('alfresco.consumer_secret')
        payload['grant_type'] = 'refresh_token'
        r = requests.post('https://api.alfresco.com/auth/oauth/versions/2/token',
                          data=payload)
        if r.status_code != 200:
            headers = forget(request)
            request.session.invalidate()
            return HTTPFound(location=loc, headers=headers)
        else:
            request.session['access_token'] = r.json()['access_token']
            request.session['refresh_token'] = r.json()['refresh_token']
            return HTTPFound(location=request.path)

    elif authenticated_userid(request):
        headers = forget(request)
        return HTTPFound(location=loc, headers=headers)
    return HTTPFound(location=loc)
예제 #3
0
def maybe_merge(
        backend, details, user=None, other_users=None,
        *args, **kwargs):
    # If we do not already have a user, see if we're in a situation
    # where we're adding an account to an existing user, and maybe
    # even merging
    request = backend.strategy.request
    adding_account = request.session.get("add_account", None)
    if adding_account is not None:
        del request.session["add_account"]
    # current discussion and next?
    logged_in = request.authenticated_userid
    if logged_in:
        logged_in = User.get(logged_in)
        if adding_account:
            if user and user != logged_in:
                # logged_in presumably newer?
                logged_in.merge(user)
                logged_in.db.delete(user)
                logged_in.db.flush()
            user = logged_in
        else:
            forget(request)
    if other_users:
        if not user:
            user = other_users.pop(0)
        # Merge other accounts with same verified email
        for profile in other_users:
            user.merge(profile)
            profile.delete()
    return {"user": user}
예제 #4
0
def logout(request):
    forget(request)
    referer = request.referer or '/'
    redirect_to = request.params.get('redirect', referer)
    if redirect_to == request.route_url('logout'):
        redirect_to = '/'
    raise httpexceptions.HTTPFound(location=redirect_to)
예제 #5
0
파일: views.py 프로젝트: assembl/assembl
def logout(request):
    logout_url = maybe_social_logout(request)
    forget(request)
    if logout_url:
        return HTTPFound(location=logout_url)
    next_view = handle_next_view(request, True)
    return HTTPFound(location=next_view)
예제 #6
0
	def logout(self):
		request = self.request

		forget(request)
		request.session['bypass_login'] = None

		return HTTPFound(location=request.route_url('login'))
예제 #7
0
def build_sync_client(request):
    # Get the BID assertion
    is_authorization_defined = AUTHORIZATION_HEADER in request.headers
    starts_with_browser_id = False
    if is_authorization_defined:
        authorization = request.headers[AUTHORIZATION_HEADER].lower()
        starts_with_browser_id = authorization.startswith("browserid")

    if not is_authorization_defined or not starts_with_browser_id:
        error_msg = "Provide a BID assertion %s header." % (
            AUTHORIZATION_HEADER)
        response = http_error(httpexceptions.HTTPUnauthorized(),
                              errno=ERRORS.MISSING_AUTH_TOKEN,
                              message=error_msg)
        response.headers.extend(forget(request))
        raise response

    is_client_state_defined = CLIENT_STATE_HEADER in request.headers
    if not is_client_state_defined:
        error_msg = "Provide the tokenserver %s header." % (
            CLIENT_STATE_HEADER)
        response = http_error(httpexceptions.HTTPUnauthorized(),
                              errno=ERRORS.MISSING_AUTH_TOKEN,
                              message=error_msg)
        response.headers.extend(forget(request))
        raise response

    authorization_header = request.headers[AUTHORIZATION_HEADER]

    bid_assertion = authorization_header.split(" ", 1)[1]
    client_state = request.headers[CLIENT_STATE_HEADER]
    sync_client = SyncClient(bid_assertion, client_state)
    return sync_client
예제 #8
0
def get_avatar(request):
    """
        Returns the current User object
    """
    logger.info("# Retrieving avatar #")
    login = request.unauthenticated_userid
    logger.info(u"  + Login : %s" % login)
    result = None
    if login is not None:
        logger.info("  + Returning the user")
        query = request.dbsession.query(User)
        query = query.join(Login)
        query = query.options(load_only("firstname", "lastname"))
        query = query.options(
            contains_eager(User.login).load_only('login').selectinload(
                Login._groups).load_only('name'),
            selectinload(User.companies).load_only('id', 'active'),
        )
        query = query.filter(Login.login == login)
        result = query.first()
        if result is None:
            forget(request)
            raise HTTPFound("/")
    else:
        logger.info("  + No user found")
    logger.debug(u"-> End of the avatar collection")
    return result
예제 #9
0
    def anggaran_032(self):
        ursKd = "0.00"
        prgKd = "00"
        kegKd = "32"
        params = self.request.params

        self.datas["mod"] = self.session["mod"]
        self.datas["kegiatanKd"] = "urusankd=%s&programkd=%s&kegiatankd=%s" %(ursKd, prgKd,kegKd)
        
        if self.logged and self.is_akses_mod('read'):
            self.datas['kegiatan'] = DBSession.query(KegiatanModel).\
                       join(ProgramModel).join(Urusan).filter(
                            Urusan.kode==ursKd,
                            ProgramModel.kode==prgKd,
                            KegiatanModel.kode==kegKd 
                            ).first()
            row = DBSession.query(KegiatanSubModel
                      ).filter(KegiatanSubModel.tahun_id == self.tahun,
                               KegiatanSubModel.unit_id == self.unit_id,
                               KegiatanSubModel.kegiatan_id==self.datas['kegiatan'].id
                               ).first()
            if row:
                self.datas['subkegiatan'] = row
                self.session["sub_keg_id"]=row.id
            else:
                self.datas['subkegiatan'] = ""
                self.session["sub_keg_id"]=0
            return dict(datas=self.datas)
        else:
            if not self.logged:
                headers=forget(self.request)
                return HTTPFound(location='/login?app=%s' % self.app, headers=headers)
            else:
                headers=forget(self.request)
                return HTTPFound(location='/anggaran', headers=headers)
예제 #10
0
 def logout(self):
     if 'redirect' in self.request.params:
         headers = forget(self.request)
         return HTTPFound(location=self.request.params.get('redirect'), headers=headers)
     else:
         headers = forget(self.request)
         return HTTPFound(location=route_url('menu', self.request), headers=headers)
예제 #11
0
    def anggaran_022_frm(self):
        req = self.request
        params = req.params
        url_dict = req.matchdict
        self.datas['id'] = 'id' in url_dict and int(url_dict['id']) or 0
        self.datas['pegawai_nama'] = 'pegawai_nama' in params and int(params['pegawai_nama']) or 0
        
        if self.logged and self.is_akses_mod('read'):
            if (not self.datas['id'] and self.is_akses_mod('add'))\
                or (self.datas['id'] and self.is_akses_mod('edit')):
                #row = KegiatanSubModel.get_by_id(self.datas['id'])
                row = DBSession.query(KegiatanSubModel).filter(KegiatanSubModel.id==self.datas['id']).first()
                if row:
                    rows = KegiatanSubModel.row2dict(row)
                    rows['unit_nm'] = row.units.nama
                    rows['kegiatan_nm'] = row.kegiatans.nama
                    return dict(datas=self.datas, rows=rows)
                else:
                    if self.datas['id']>0:
                        return HTTPNotFound() #TODO: Warning Data Not Found
                rows = {}
                #rows['tahun_id'] = self.datas['tahun']
                return dict(datas = self.datas,rows = '')
            else:
                return HTTPNotFound() #TODO: Warning Hak Akses 

        else:
            if not self.logged:
                headers=forget(self.request)
                return HTTPFound(location='/login?app=%s' % self.app, headers=headers)
            else:
                headers=forget(self.request)
                return HTTPFound(location='/anggaran', headers=headers)
예제 #12
0
	def sign_in_out(self, request):
		username = request.POST.get('username')
		password = request.POST.get('password')
		if username:
			self.log.info("Login attempt: u = %s, pass = %s", username, password)
			if username in users and users[username] == password:
				self.log.info("Successful Login!")
				age = 60*60*24*32
				headers = pys.remember(request, username, max_age='%d' % age)

				reqPath = request.path.lstrip("/")

				reqPath = reqPath + ".mako"
				pgTemplate = self.lookupEngine.get_template(reqPath)
				pageContent = pgTemplate.render_unicode(request=request)
				return Response(body=pageContent, headers=headers)

			else:
				self.log.warn("Invalid user. Deleting cookie.")
				headers = pys.forget(request)
		else:
			self.log.warn("No user specified - Deleting cookie.")
			headers = pys.forget(request)

		return HTTPFound(location=request.route_url('login'))
예제 #13
0
 def logout(self):
     if "redirect" in self.request.params:
         headers = forget(self.request)
         return HTTPFound(location=self.request.params.get("redirect"), headers=headers)
     else:
         headers = forget(self.request)
         return HTTPFound(location=route_url("menu", self.request), headers=headers)
예제 #14
0
파일: views.py 프로젝트: assembl/assembl
def finish_password_change(request):
    localizer = request.localizer
    token = request.params.get('token')
    title = request.params.get('title')
    welcome = asbool(request.params.get('welcome'))
    discussion = discussion_from_request(request)
    if welcome:
        title = localizer.translate(_(
            'Welcome to {discussion_topic}.')).format(
            discussion_topic=discussion.topic if discussion else "Assembl")
    else:
        title = localizer.translate(_('Change your password'))

    user, validity = verify_password_change_token(token)
    logged_in = request.authenticated_userid  # if mismatch?
    if user and user.id != logged_in:
        # token for someone else: forget login.
        logged_in = None
        forget(request)
    token_date = get_data_token_time(token)
    old_token = (
        user is None or token_date is None or (
            user.last_login and token_date < user.last_login))

    if (validity != Validity.VALID or old_token) and not logged_in:
        # V-, V+P+W-B-L-: Invalid or obsolete token (obsolete+logged in treated later.)
        # Offer to send a new token
        if validity != Validity.VALID:
            error = localizer.translate(_(
                "This link is not valid. Do you want us to send another?"))
        else:
            error = localizer.translate(_(
                "This link has been used. Do you want us to send another?"))
        request.session.flash(error)
        return HTTPFound(location=maybe_contextual_route(
            request, 'request_password_change', _query=dict(
                user_id=user.id if user else '')))

    error = None
    p1, p2 = (request.params.get('password1', '').strip(),
              request.params.get('password2', '').strip())
    if p1 != p2:
        error = localizer.translate(_('The passwords are not identical'))
    elif p1:
        user.password_p = p1
        user.successful_login()
        headers = remember(request, user.id)
        request.response.headerlist.extend(headers)
        if discussion:
            maybe_auto_subscribe(user, discussion)
        request.session.flash(localizer.translate(_(
            "Password changed")), 'message')
        return HTTPFound(location=request.route_url(
            'home' if discussion else 'discussion_list',
            discussion_slug=discussion.slug))

    return dict(
        get_default_context(request),
        title=title, token=token, error=error)
예제 #15
0
파일: user.py 프로젝트: wangjun/todolist
def logout(request):
    """
    POST /api/logout
    :param request:
    :return:
    """
    forget(request)
    return {}
예제 #16
0
파일: tasks.py 프로젝트: AndrewCEmil/slshr
def logout_view(request):
    logger.info('in logout view')
    user = authenticated_userid(request)
    if user is None:
        request.session.flash("need to be logged in to log out, lol")
    else:
        forget(request)
    return HTTPFound(location=request.route_url('playlists'))
예제 #17
0
def logout_view(request):
    """
        The logout view
    """
    loc = request.route_url('index')
    forget(request)
    request.response.delete_cookie("remember_me")
    response = HTTPFound(location=loc, headers=request.response.headers)
    return response
예제 #18
0
파일: views.py 프로젝트: festrade/assembl
def finish_password_change(request):
    localizer = request.localizer
    token = request.params.get('token')
    title = request.params.get('title')
    user, validity = verify_password_change_token(token)
    logged_in = authenticated_userid(request)  # if mismatch?
    if user and user.id != logged_in:
        # token for someone else: forget login.
        logged_in = None
        forget(request)
    token_date = get_data_token_time(token)
    old_token = (
        user is None or token_date is None or (
            user.last_login and token_date < user.last_login))

    if (validity != Validity.VALID or old_token) and not logged_in:
        # V-, V+P+W-B-L-: Invalid or obsolete token (obsolete+logged in treated later.)
        # Offer to send a new token
        if validity != Validity.VALID:
            error = localizer.translate(_(
                "This link is not valid. Do you want us to send another?"))
        else:
            error = localizer.translate(_(
                "This link has been used. Do you want us to send another?"))

        return HTTPFound(location=maybe_contextual_route(
            request, 'request_password_change', _query=dict(
                user_id=user.id if user else '',
                error=error)))

    discussion_slug = request.matchdict.get('discussion_slug', None)
    error = None
    p1, p2 = (request.params.get('password1', '').strip(),
              request.params.get('password2', '').strip())
    if p1 != p2:
        error = localizer.translate(_('The passwords are not identical'))
    elif p1:
        user.password_p = p1
        user.last_login = datetime.utcnow()
        headers = remember(request, user.id)
        request.response.headerlist.extend(headers)
        if discussion_slug:
            discussion = discussion_from_request(request)
            maybe_auto_subscribe(user, discussion)
        return HTTPFound(location=request.route_url(
            'home' if discussion_slug else 'discussion_list',
            discussion_slug=discussion_slug,
            _query=dict(
                message=localizer.translate(_(
                    "Password changed")))))

    slug_prefix = "/" + discussion_slug if discussion_slug else ""
    return dict(
        get_default_context(request),
        title=title, slug_prefix=slug_prefix, token=token, error=error)
예제 #19
0
 def anggaran_022(self):
     params = self.request.params
     if self.logged and self.is_akses_mod('read'):
         return dict(datas=self.datas)
     else:
         if not self.logged:
             headers=forget(self.request)
             return HTTPFound(location='/login?app=%s' % self.app, headers=headers)
         else:
             headers=forget(self.request)
             return HTTPFound(location='/anggaran', headers=headers)
예제 #20
0
파일: default.py 프로젝트: antleocar/blog
def sign_in_out(request):
    username = request.POST.get('username')
    if username:
        user = UserService.by_name(username, request=request)
        if user and user.verify_password(request.POST.get('password')):
            headers = remember(request, user.name)
        else:
            headers = forget(request)
    else:
        headers = forget(request)
    return HTTPFound(location=request.route_url('home'), headers=headers)
예제 #21
0
def test_forget_warning():
    policy = JWTAuthenticationPolicy('secret', http_header='X-Token')
    with testConfig() as config:
        config.set_authorization_policy(DummySecurityPolicy())
        config.set_authentication_policy(policy)
        request = DummyRequest()
        with warnings.catch_warnings(record=True) as w:
            forget(request)
    assert len(w) == 1
    assert issubclass(w[-1].category, UserWarning)
    assert 'JWT tokens' in str(w[-1].message)
    assert w[-1].filename.endswith('test_policy.py')
예제 #22
0
def index_view(request):
  session = request.session
  if not request.session['logado']:
    headers = forget(request)
    return HTTPFound(location = "/")
  p = ProjetosDAO()
  c_id = request.matchdict["id"]
  retorno = p.listar_cliente(c_id)
  if int(c_id) != int(session["id"]):
    headers = forget(request)
    return HTTPFound(location = "/")
  return {'resultado': retorno}    
예제 #23
0
파일: views.py 프로젝트: assembl/assembl
def assembl_login_complete_view(request):
    """
    This backend view handles login form submissions received from both v1 and v2 frontend views.
    Check if proper authorization. Otherwise send to another page.
    """
    session = AgentProfile.default_db
    # POST before GET
    identifier = (request.POST.get('identifier').strip() or
                  request.GET.get('identifier').strip() or '')
    password = request.params.get('password', '').strip()
    referrer = request.POST.get('referrer', None)
    is_v2 = True if referrer == 'v2' else False
    next_view = handle_next_view(request, True)
    logged_in = request.authenticated_userid
    localizer = request.localizer
    user = None
    user, account = from_identifier(identifier)
    query = {"identifier": identifier,
             "next": next_view} if identifier else {"next": next_view}
    if not user:
        error_message = localizer.translate(_("This user cannot be found"))
        request.session.flash(error_message)
        route_name = 'react_login' if is_v2 else 'login'
        return HTTPFound(location=maybe_contextual_route(
            request, route_name,
            _query=query))
    if account and not account.verified:
        return HTTPFound(location=maybe_contextual_route(
            request, 'confirm_emailid_sent', email_account_id=account.id))
    if logged_in:
        if user.id != logged_in:
            # logging in as a different user
            # Could I be combining account?
            forget(request)
        else:
            # re-logging in? Why?
            return HTTPFound(location=next_view)
    if not user.check_password(password):
        error_message = localizer.translate(_("Invalid user and password"))
        user.login_failures += 1
        # TODO: handle high failure count
        request.session.flash(error_message)
        route_name = 'react_login' if is_v2 else 'login'
        return HTTPFound(location=maybe_contextual_route(
            request, route_name,
            _query=query))
    user.successful_login()
    headers = remember(request, user.id)
    request.response.headerlist.extend(headers)
    discussion = discussion_from_request(request)
    if discussion:
        maybe_auto_subscribe(user, discussion)
    return HTTPFound(location=next_view)
예제 #24
0
파일: util.py 프로젝트: assembl/assembl
def get_non_expired_user_id(request):
    user_id = request.authenticated_userid
    discussion = discussion_from_request(request)
    if user_id:
        user = User.get(user_id)
        if user.login_expired(discussion):
            forget(request)
            localizer = request.localizer
            request.session.flash(localizer.translate(_(
                "Your session has expired, you need to login again")))
            user_id = None
    return user_id
예제 #25
0
def sign_in(request):
    login_form = None
    if request.method == 'POST':
        login_form = LoginForm(request.POST)
    if login_form and login_form.validate():
        user = User.by_name(login_form.username.data)
        if user and user.verify_password(login_form.password.data):
            headers = remember(request, user.name)
        else:
            headers = forget(request)
    else:
        headers = forget(request)
    return HTTPFound(location=request.route_url('home'), headers=headers)
예제 #26
0
def logout_view(request):
    # Opening this view in a new window will post an 'afterLogout'
    # message to the application then redirect to the logout page
    # of the authorisation provider.
    # Do not open this view in an iframe, as it would prevent the
    # authorisation provider from receiving the user's cookies (see
    # Third-party cookies).
    forget(request)
    request.session.clear()
    return {
        'auth_provider_logout_uri': app['logout_uri'],
        'csrf_token': request.session.get_csrf_token()
    }
예제 #27
0
def logout(request):
    """Logs out the user from the application."""
    settings = request.registry.settings
    forget(request)
    referer = request.referer
    redirect_to = request.params.get('redirect', referer)
    default_redirect_to = settings.get(
        'openstax_accounts.logout_redirects_to', '/')

    if redirect_to == request.route_url('logout') or redirect_to is None:
        redirect_to = default_redirect_to

    raise httpexceptions.HTTPFound(location=redirect_to)
예제 #28
0
 def anggaran_003(self):
     params = self.request.params
     if self.logged and self.is_akses_mod('read'):
         pegawais = PegawaiModel.get_enabled()
         jabatans = JabatanModel.get_enabled()
         return dict(datas=self.datas, jabatans=jabatans, pegawais=pegawais)
     else:
         if not self.logged:
             headers=forget(self.request)
             return HTTPFound(location='/login?app=%s' % self.app, headers=headers)
         else:
             headers=forget(self.request)
             return HTTPFound(location='/anggaran', headers=headers)
예제 #29
0
파일: models.py 프로젝트: mbijon/nefertari
    def get_groups_by_userid(cls, userid, request):
        """ Return group identifiers of user with id :userid:

        Used by Ticket-based auth as `callback` kwarg.
        """
        try:
            cache_request_user(cls, request, userid)
        except Exception as ex:
            log.error(str(ex))
            forget(request)
        else:
            if request._user:
                return ['g:%s' % g for g in request._user.groups]
예제 #30
0
파일: models.py 프로젝트: mbijon/nefertari
    def get_token_credentials(cls, username, request):
        """ Get api token for user with username of :username:

        Used by Token-based auth as `credentials_callback` kwarg.
        """
        try:
            user = cls.get_item(username=username)
        except Exception as ex:
            log.error(str(ex))
            forget(request)
        else:
            if user:
                return user.api_key.token
예제 #31
0
def logout(request):
    headers = forget(request)
    return HTTPFound(location=request.url_for('/auth/logout_view'),
                     headers=headers)
예제 #32
0
def logout_view(request):
    request.session.invalidate()
    request.session.flash(u'Logged out successfully.')
    headers = forget(request)
    return HTTPFound(location=request.route_url('main'), headers=headers)
예제 #33
0
def logout(request):
    headers = forget(request)
    return HTTPFound(location='/', headers=headers)
예제 #34
0
def logout(request):
    forget(request)
    return request.response
예제 #35
0
def logout(request):
    headers = forget(request)
    return HTTPOk(headers=headers)
예제 #36
0
def logout(request):
    headers = forget(request)
    request.response.headerlist.extend(headers)
    return dict()
예제 #37
0
파일: accounts.py 프로젝트: ziqizh/h
 def _logout(self):
     if self.request.authenticated_userid is not None:
         self.request.registry.notify(LogoutEvent(self.request))
         self.request.session.invalidate()
     headers = security.forget(self.request)
     return headers
예제 #38
0
def assembl_register_view(request):
    slug = request.matchdict.get('discussion_slug', "")
    next_view = handle_next_view(request)
    if not request.params.get('email'):
        if request.scheme == "http"\
                and asbool(config.get("accept_secure_connection")):
            return HTTPFound(get_global_base_url(True) + request.path_qs)
        response = get_login_context(request)
        return response
    forget(request)
    session = AgentProfile.default_db
    localizer = request.localizer
    name = request.params.get('name', '').strip()
    if not name or len(name) < 3:
        return dict(get_default_context(request),
                    error=localizer.translate(
                        _("Please use a name of at least 3 characters")))
    password = request.params.get('password', '').strip()
    password2 = request.params.get('password2', '').strip()
    email = request.params.get('email', '').strip()
    if not is_email(email):
        return dict(get_default_context(request),
                    error=localizer.translate(_("This is not a valid email")))
    email = EmailString.normalize_email_case(email)
    # Find agent account to avoid duplicates!
    if session.query(AbstractAgentAccount).filter_by(email_ci=email,
                                                     verified=True).count():
        return dict(get_default_context(request),
                    error=localizer.translate(
                        _("We already have a user with this email.")))
    if password != password2:
        return dict(get_default_context(request),
                    error=localizer.translate(
                        _("The passwords should be identical")))

    # TODO: Validate password quality
    # otherwise create.
    validate_registration = asbool(
        config.get('assembl.validate_registration_emails'))

    user = User(name=name,
                password=password,
                verified=not validate_registration,
                creation_date=datetime.utcnow())
    email_account = EmailAccount(email=email,
                                 verified=not validate_registration,
                                 profile=user)
    session.add(user)
    session.add(email_account)
    discussion = discussion_from_request(request)
    if discussion:
        permissions = get_permissions(Everyone, discussion.id)
        if not (P_SELF_REGISTER in permissions
                or P_SELF_REGISTER_REQUEST in permissions):
            discussion = None
    if discussion:
        _now = datetime.utcnow()
        agent_status = AgentStatusInDiscussion(
            agent_profile=user,
            discussion=discussion,
            first_visit=_now,
            last_visit=_now,
            user_created_on_this_discussion=True)
        session.add(agent_status)
    session.flush()
    if not validate_registration:
        if asbool(config.get('pyramid.debug_authorization')):
            # for debugging purposes
            from assembl.auth.password import email_token
            log.debug("email token: " + request.route_url(
                'user_confirm_email', token=email_token(email_account)))
        headers = remember(request, user.id)
        user.last_login = datetime.utcnow()
        request.response.headerlist.extend(headers)
        if discussion:
            maybe_auto_subscribe(user, discussion)
        # TODO: Tell them to expect an email.
        return HTTPFound(location=next_view)
    return HTTPFound(location=maybe_contextual_route(
        request, 'confirm_emailid_sent', email_account_id=email_account.id))
예제 #39
0
def user_confirm_email(request):
    token = request.matchdict.get('token') or ''
    account, validity = verify_email_token(token)
    session = AbstractAgentAccount.default_db
    logged_in = authenticated_userid(request)  # if mismatch?
    localizer = request.localizer
    if account and account.profile_id != logged_in:
        # token for someone else: forget login.
        logged_in = None
        forget(request)
    token_date = get_data_token_time(token)
    old_token = (account is None or token_date is None
                 or (account.profile.last_login
                     and token_date < account.profile.last_login))
    inferred_discussion = discussion = discussion_from_request(request)
    if account and not discussion:
        # We do not know from which discussion the user started to log in;
        # See if only involved in one discussion
        discussions = account.profile.involved_in_discussion
        if len(discussions) == 1:
            inferred_discussion = discussions[0]
    if account and account.verified and logged_in:
        # no need to revalidate, just send to discussion.
        # Question: maybe_auto_subscribe? Doubt it.
        return HTTPFound(location=request.route_url(
            'home' if inferred_discussion else 'discussion_list',
            discussion_slug=inferred_discussion.slug,
            _query=dict(message=localizer.translate(
                _("Email <%s> already confirmed")) % (account.email, ))))

    if validity != Validity.VALID or old_token:
        # V-, B-: Invalid or obsolete token
        # Offer to send a new token
        if account and not account.verified:
            # bad token, unverified account... offer a new token
            if validity != Validity.VALID:
                error = localizer.translate(
                    _("This link was not valid. We sent another."))
            else:
                error = localizer.translate(
                    _("This link has been used. We sent another."))
            request.session.flash(error)
            return HTTPFound(location=maybe_contextual_route(
                request, 'confirm_emailid_sent', email_account_id=account.id))
        else:
            if account and account.verified:
                # bad token, verified account... send them to login
                error = localizer.translate(
                    _("Email <%s> already confirmed")) % (account.email, )
            else:
                # now what? We do not have the email.
                # Just send to login for now
                error = localizer.translate(
                    _("This link is not valid. Please attempt to login to get another one."
                      ))
            request.session.flash(error)
            return HTTPFound(location=maybe_contextual_route(
                request,
                'login',
                _query=dict(identifier=account.email if account else None)))

    # By now we know we have a good token; make it login-equivalent.
    user = account.profile
    assert isinstance(user, User)  # accounts should not get here. OK to fail.
    headers = remember(request, user.id)
    request.response.headerlist.extend(headers)
    user.last_login = datetime.utcnow()
    username = user.username
    next_view = handle_next_view(request, False)

    if account.verified:
        message = localizer.translate(
            _("Email <%s> already confirmed")) % (account.email, )
    else:
        # maybe another profile already verified that email
        other_account = session.query(AbstractAgentAccount).filter_by(
            email_ci=account.email_ci, verified=True).first()
        if other_account:
            # We have two versions of the email, delete the unverified one
            session.delete(account)
            if other_account.profile != user:
                # Give priority to the one where the email was verified last.
                other_profile = other_account.profile
                user.merge(other_profile)
                session.delete(other_profile)
                if user.username:
                    username = user.username
            account = other_account
        account.verified = True
        user.verified = True
        # do not use inferred discussion for auto_subscribe
        user.last_login = datetime.utcnow()
        if discussion and maybe_auto_subscribe(user, discussion):
            message = localizer.translate(
                _("Your email address %s has been confirmed, "
                  "and you are now subscribed to discussion's "
                  "default notifications.")) % (account.email, )
        else:
            message = localizer.translate(
                _("Your email address %s has been confirmed.")) % (
                    account.email, )

    if inferred_discussion:
        return HTTPFound(location=request.route_url(
            'home',
            discussion_slug=inferred_discussion.slug,
            _query=dict(message=message)))
    else:
        return HTTPFound(location=request.route_url('discussion_list'))
예제 #40
0
def do_password_change(request):
    "Validate the change_password token, and react accordingly."
    # Codes below refer to those cases:
    # V. token Valid(+) or invalid(-)? (Possibly expired through internal date)
    # P. user has(+) a Password or not (-)?
    # W. Welcome(+) vs change password(-)
    # B. last login absent, or Before token created (+) vs last login after token created (-)
    # L. user is already Logged in(+) or not(-)?

    welcome = 'welcome' in request.matched_route.name
    localizer = request.localizer
    discussion = discussion_from_request(request)
    token = request.matchdict.get('token')
    user, validity = verify_password_change_token(token)
    logged_in = authenticated_userid(request)
    if user and user.id != logged_in:
        # token for someone else: forget login.
        logged_in = None
        forget(request)
    lacking_password = user is not None and user.password is None
    token_date = get_data_token_time(token)
    old_token = (user is None or token_date is None
                 or (user.last_login and token_date < user.last_login))
    log.debug("pwc V%sP%sW%sB%sL%s" % tuple([
        "-" if b else "+"
        for b in (validity != Validity.VALID, lacking_password, not welcome,
                  old_token, logged_in is None)
    ]))
    if welcome and not lacking_password:
        # W+P+: welcome link sends onwards irrespective of token
        if logged_in:
            # L+: send onwards to discussion
            return HTTPFound(location=request.route_url(
                'home' if discussion else 'discussion_list',
                discussion_slug=discussion.slug))
        else:
            # L-: offer to login
            return HTTPFound(location=maybe_contextual_route(
                request,
                'login',
                _query=dict(
                    identifier=user.get_preferred_email() if user else None)))

    if (validity != Validity.VALID or old_token) and not logged_in:
        # V-, V+P+W-B-L-: Invalid or obsolete token (obsolete+logged in treated later.)
        # Offer to send a new token
        if validity != Validity.VALID:
            error = localizer.translate(
                _("This link is not valid. Do you want us to send another?"))
        else:
            error = localizer.translate(
                _("This link has been used. Do you want us to send another?"))
        request.session.flash(error)
        return HTTPFound(location=maybe_contextual_route(
            request,
            'request_password_change',
            _query=dict(user_id=user.id if user else '')))

    # V+: Valid token (encompasses P-B+, W-, B-L+); ALSO V-L+
    # V+P-B- should not happen, but we'll treat it the same.
    # go through password change dialog. We'll complete login afterwards.
    if welcome:
        platform_name = config.get("platform_name")
        if discussion:
            request.session.flash(
                localizer.translate(
                    _("You will enter the discussion as <b>{name}</b>.")).
                format(name=user.name), 'message')
        else:
            discussion_topic = platform_name
            request.session.flash(
                localizer.translate(
                    _("You will enter {platform_name} as <b>{name}</b>.")).
                format(platform_name=platform_name, name=user.name), 'message')
        request.session.flash(
            localizer.translate(
                _("Please choose your password for security reasons.")).format(
                    name=user.name), 'message')
    return HTTPFound(location=maybe_contextual_route(
        request,
        'finish_password_change',
        _query=dict(token=token, welcome=welcome)))
예제 #41
0
def finish_password_change(request):
    localizer = request.localizer
    token = request.params.get('token')
    title = request.params.get('title')
    welcome = asbool(request.params.get('welcome'))
    discussion = discussion_from_request(request)
    if welcome:
        title = localizer.translate(
            _('Welcome to {discussion_topic}.')).format(
                discussion_topic=discussion.topic if discussion else config.
                get("platform_name"))
    else:
        title = localizer.translate(_('Change your password'))

    user, validity = verify_password_change_token(token)
    logged_in = authenticated_userid(request)  # if mismatch?
    if user and user.id != logged_in:
        # token for someone else: forget login.
        logged_in = None
        forget(request)
    token_date = get_data_token_time(token)
    old_token = (user is None or token_date is None
                 or (user.last_login and token_date < user.last_login))

    if (validity != Validity.VALID or old_token) and not logged_in:
        # V-, V+P+W-B-L-: Invalid or obsolete token (obsolete+logged in treated later.)
        # Offer to send a new token
        if validity != Validity.VALID:
            error = localizer.translate(
                _("This link is not valid. Do you want us to send another?"))
        else:
            error = localizer.translate(
                _("This link has been used. Do you want us to send another?"))
        request.session.flash(error)
        return HTTPFound(location=maybe_contextual_route(
            request,
            'request_password_change',
            _query=dict(user_id=user.id if user else '')))

    error = None
    p1, p2 = (request.params.get('password1', '').strip(),
              request.params.get('password2', '').strip())
    if p1 != p2:
        error = localizer.translate(_('The passwords are not identical'))
    elif p1:
        user.password_p = p1
        user.last_login = datetime.utcnow()
        headers = remember(request, user.id)
        request.response.headerlist.extend(headers)
        if discussion:
            maybe_auto_subscribe(user, discussion)
        request.session.flash(localizer.translate(_("Password changed")),
                              'message')
        return HTTPFound(location=request.route_url(
            'home' if discussion else 'discussion_list',
            discussion_slug=discussion.slug))

    return dict(get_default_context(request),
                title=title,
                token=token,
                error=error)
예제 #42
0
def logout(request):  # pragma: no cover
    headers = forget(request)
    return HTTPFound(location=request.route_path('home'), headers=headers)
예제 #43
0
def assembl_register_user(request):
    forget(request)
    localizer = request.localizer
    session = AgentProfile.default_db
    json = request.json
    discussion = discussion_from_request(request)
    permissions = get_permissions(Everyone,
                                  discussion.id if discussion else None)

    name = json.get('real_name', '').strip()
    errors = JSONError()
    if not name or len(name) < 3:
        errors.add_error(
            localizer.translate(
                _("Please use a name of at least 3 characters")),
            ErrorTypes.SHORT_NAME)
    password = json.get('password', '').strip()
    # TODO: Check password strength. maybe pwdmeter?
    email = None
    for account in json.get('accounts', ()):
        email = account.get('email', None)
        if not is_email(email):
            errors.add_error(
                localizer.translate(_("This is not a valid email")),
                ErrorTypes.INVALID_EMAIL)
            continue
        email = EmailString.normalize_email_case(email)
        # Find agent account to avoid duplicates!
        if session.query(AbstractAgentAccount).filter_by(
                email_ci=email).count():
            errors.add_error(
                localizer.translate(
                    _("We already have a user with this email.")),
                ErrorTypes.EXISTING_EMAIL, HTTPConflict.code)
    if not email:
        errors.add_error(localizer.translate(_("No email.")),
                         ErrorTypes.INVALID_EMAIL)
    username = json.get('username', None)
    if username:
        if session.query(Username).filter(
                func.lower(Username.username) == username.lower()).count():
            errors.add_error(
                localizer.translate(
                    _("We already have a user with this username.")),
                ErrorTypes.EXISTING_USERNAME, HTTPConflict.code)
        if len(username) > 20:
            errors.add_error(
                localizer.translate(
                    _("The username must be less than 20 characters.")),
                ErrorTypes.USERNAME_TOO_LONG, HTTPBadRequest.code)
    if discussion:
        check_subscription = discussion.preferences['whitelist_on_register']
        whitelist = discussion.preferences['require_email_domain']
        if check_subscription and whitelist:
            status = discussion.check_email(email)
            if not status:
                admin_emails = discussion.get_admin_emails()
                num = len(admin_emails)
                errors.add_error(
                    localizer.pluralize(
                        _("Your email domain has not been approved for registration. Please contact ${emails} for support."
                          ),
                        _("Your email domain has not been approved for registration. Please contact one of ${emails} for support."
                          ),
                        num,
                        mapping={'emails': ", ".join(admin_emails)}))
    if errors:
        raise errors

    # This logic needs to be above the JSONError checks to ensure that whitelisting is applied
    # even if the discussion does not have a P_SELF_REGISTER on system.Everyone
    if discussion and not (P_SELF_REGISTER in permissions
                           or P_SELF_REGISTER_REQUEST in permissions):
        # Consider it without context
        discussion = None

    validate_registration = asbool(
        config.get('assembl.validate_registration_emails'))

    old_autoflush = session.autoflush
    session.autoflush = False
    try:
        now = datetime.utcnow()
        user = User(name=name,
                    password=password,
                    verified=not validate_registration,
                    creation_date=now)

        session.add(user)
        session.flush()

        user.update_from_json(json, user_id=user.id)
        account = user.accounts[0]
        email = account.email
        account.verified = not validate_registration
        if discussion:
            agent_status = AgentStatusInDiscussion(
                agent_profile=user,
                discussion=discussion,
                first_visit=now,
                last_visit=now,
                user_created_on_this_discussion=True)
            session.add(agent_status)
        session.flush()

        # create the profile fields for custom fields
        for global_id, value in json.get('profileFields', {}).iteritems():
            configurable_field_id = from_global_id(global_id)[1]
            configurable_field = AbstractConfigurableField.get(
                configurable_field_id)
            profile_field = ProfileField(
                agent_profile=user,
                configurable_field=configurable_field,
                discussion=configurable_field.discussion,
                value_data={u'value': value})
            session.add(profile_field)

        session.flush()

        if validate_registration:
            send_confirmation_email(request, account)
        else:
            user.verified = True
            for account in user.accounts:
                account.verified = True
            user.successful_login()
            if asbool(config.get('pyramid.debug_authorization')):
                # for debugging purposes
                from assembl.auth.password import email_token
                print "email token:", request.route_url(
                    'user_confirm_email', token=email_token(account))
            if discussion:
                check_subscription = discussion.preferences[
                    'whitelist_on_register']
                maybe_auto_subscribe(user,
                                     discussion,
                                     check_authorization=check_subscription)
        session.flush()
        return CreationResponse(user, Everyone, permissions)
    finally:
        session.autoflush = old_autoflush
예제 #44
0
def logout(request):
    headers = forget(request)
    return exc.HTTPFound(location='/login', headers=headers)
예제 #45
0
def logout(request):
    """Log out a user."""
    headers = forget(request)
    return HTTPFound(request.route_url('login'), headers=headers)
예제 #46
0
def logout(request):
    forget(request)
    next_view = handle_next_view(request, True)
    return HTTPFound(location=next_view)
예제 #47
0
파일: app7.py 프로젝트: bradyaher/bikes
 def logout(self):
     headers = forget(self.request)
     return Response(
         'Logged out',
         headers=headers
         )
예제 #48
0
    def __call__(self, request):
        """
        Handler that mimics what CubicWebPublisher.main_handle_request and
        CubicWebPublisher.core_handle do
        """

        req = request.cw_request
        vreg = request.registry['cubicweb.registry']

        try:
            content = None
            try:
                with cw_to_pyramid(request):
                    ctrlid, rset = self.appli.url_resolver.process(
                        req, req.path)

                    try:
                        controller = vreg['controllers'].select(
                            ctrlid, req, appli=self.appli)
                    except cubicweb.NoSelectableObject:
                        raise httpexceptions.HTTPUnauthorized(
                            req._('not authorized'))

                    req.update_search_state()
                    content = controller.publish(rset=rset)

                    # XXX this auto-commit should be handled by the cw_request
                    # cleanup or the pyramid transaction manager.
                    # It is kept here to have the ValidationError handling bw
                    # compatible
                    if req.cnx:
                        txuuid = req.cnx.commit()
                        # commited = True
                        if txuuid is not None:
                            req.data['last_undoable_transaction'] = txuuid
            except cubicweb.web.ValidationError as ex:
                # XXX The validation_error_handler implementation is light, we
                # should redo it better in cw_to_pyramid, so it can be properly
                # handled when raised from a cubicweb view.
                # BUT the real handling of validation errors should be done
                # earlier in the controllers, not here. In the end, the
                # ValidationError should never by handled here.
                content = self.appli.validation_error_handler(req, ex)
            except cubicweb.web.RemoteCallFailed:
                # XXX The default pyramid error handler (or one that we provide
                # for this exception) should be enough
                # content = self.appli.ajax_error_handler(req, ex)
                raise

            if content is not None:
                request.response.body = content

        except LogOut as ex:
            # The actual 'logging out' logic should be in separated function
            # that is accessible by the pyramid views
            headers = security.forget(request)
            raise HTTPSeeOther(ex.url, headers=headers)
        except cubicweb.AuthenticationError:
            # Will occur upon access to req.cnx which is a
            # cubicweb.dbapi._NeedAuthAccessMock.
            if not content:
                content = vreg['views'].main_template(req, 'login')
                request.response.status_code = 403
                request.response.body = content
        except cubicweb.web.NotFound as ex:
            view = vreg['views'].select('404', req)
            content = vreg['views'].main_template(req, view=view)
            request.response.status_code = ex.status
            request.response.body = content
        finally:
            # XXX CubicWebPyramidRequest.headers_out should
            # access directly the pyramid response headers.
            request.response.headers.clear()
            for k, v in req.headers_out.getAllRawHeaders():
                for item in v:
                    request.response.headers.add(k, item)

        return request.response
예제 #49
0
def logout(request):
    headers = forget(request)
    return HTTPFound(location=request.resource_url(request.context),
                     headers=headers)
예제 #50
0
def logout(request):
    headers = forget(request)
    return HTTPFound(location=request.route_url('login'), headers=headers)
예제 #51
0
 def logout(self):
     headers = forget(self.request)
     url = self.request.route_url('home')
     return HTTPFound(location=url, headers=headers)
예제 #52
0
 def logout(self):
     # Flush cookies and return to home
     request_api(self.request, schemas.SignoutAPI.path, "GET")
     return HTTPFound(location=self.request.route_url("home"), headers=forget(self.request))
예제 #53
0
 def logout(self):
     headers = forget(self.request)
     loginpage = route_url('login', self.request)
     return HTTPFound(location=loginpage, headers=headers)
예제 #54
0
def logout_view(request):
    headers = forget(request)
    return exc.HTTPFound(location=request.route_url('home'), headers=headers)
예제 #55
0
 def _callFUT(self, *arg):
     from pyramid.security import forget
     return forget(*arg)
예제 #56
0
def logout_view(request):
    headers = forget(request)
    loc = request.route_url('home')
    return HTTPFound(location=loc, headers=headers)
def logout(request):
    header = forget(request)
    html = render('templates/login.jinja2', {'authenticated_student_id': None})
    return Response(html, headers=header)
예제 #58
0
def logout(request):
    """."""
    headers = forget(request)
    return HTTPFound(request.route_url('home'), headers=headers)
예제 #59
0
def logout(request):
    logout_url = maybe_social_logout(request)
    forget(request)
예제 #60
0
 def deauthenticate(self, request):
     return forget(request) # pragma: no cover