def skip_persona_selection(self):
     # set cookie and redirect
     response = HTTPFound(location=get_redirect_url(self.request))
     response.set_cookie(
         PERSONA_COOKIE_NAME, value=PERSONA_SKIP_COOKIE_VALUE,
         max_age=ONE_YEAR)
     return response
Exemple #2
0
    def record_edit(self):
        zonename = self.request.matchdict['zonename']
        recordname = self.request.matchdict['recordname']
        zonefile = settings.zones[zonename]
        zone = Zone(zonename, zonefile)
        protected = name_is_protected(zonename, recordname)
        response = {"zonename": zonename,
                    "recordname": recordname}

        if self.request.POST and protected:
            return HTTPForbidden("You can not modify this domain name")

        elif protected:
            response['protected'] = protected
            response['record'] = zone.get_record(recordname)
            return response

        schema = Record(validator=record_validator)
        form = deform.Form(schema, buttons=('submit',))

        if self.request.POST:
            controls = self.request.POST.items()
            try:
                data = form.validate(controls)
            except deform.ValidationFailure, e:
                response['form'] = e.render()
                return response
            else:
                zone.add_record(**data)
                response = HTTPFound()
                response.location = self.request.route_url('record',
                                                            zonename=zonename,
                                                            recordname=data['name'])
                return response
Exemple #3
0
def lang(request):
    # Set language
    code = request.matchdict['code']
    # TODO redirect where we came_from
    response = HTTPFound(location='/')
    response.set_cookie('lang', value=code, max_age=31536000) # max_age = year
    return response
Exemple #4
0
    def record_add(self):
        zonename = self.request.matchdict['zonename']
        zonefile = settings.zones[zonename]
        zone = Zone(zonename, zonefile)

        schema = Record(validator=record_validator)
        form = deform.Form(schema, buttons=('submit',))

        response = {"zonename": zonename,
                    "recordname": "new"}
        response["form"] = form.render()

        if 'submit' in self.request.POST:
            controls = self.request.POST.items()
            try:
                data = form.validate(controls)
            except deform.ValidationFailure, e:
                response['form'] = e.render()
                return response
            if not name_is_protected(zonename, data['name']):
                zone.add_record(**data)
                response = HTTPFound()
                response.location = self.request.route_url('record',
                                                            zonename=zonename,
                                                            recordname=data['name'])
                return response
            else:
                return HTTPForbidden()
Exemple #5
0
def fbauth(request):
    code = request.params['code']
    fb_user = User.fb_user(code)
    user_id = str(fb_user.id)
    response = HTTPFound(location="/")
    response.set_cookie('user_id', value=user_id, max_age=31536000)
    return response
Exemple #6
0
    def __call__(self):
        """Log the user out by deleting cookies and redirecting to CAS logout.
        """
        if security.authenticated_userid(self.request):
            # Return to this view once we've logged out.
            here = self.request.route_url(self.request.matched_route.name)
            here += '?return=' + self.request.referrer
            response = HTTPFound(location=here)

            # Drop the current session for the user. Copy the session to the
            # new response so the cookies get cleared.
            response.session = self.request.session
            response.session.invalidate()

            # Forget the user's login cookie
            forget_headers = security.forget(self.request)
            response.headerlist.extend(forget_headers)
            return response
        else:
            # Once cookies are gone, sign out. Either SSO or redirection.
            route = self.request.registry.settings[RETURN_ROUTE]
            # Go back to the original page, or the default
            return_url = self.request.params.get('return',
                                                 self.request.route_url(route))

            sso_url = self.request.registry.settings[SSO_URL]
            logout_url = (sso_url + '?url=' + return_url) if \
                self.request.registry.settings[ENABLE_SLO] else return_url

            return HTTPFound(location=logout_url)
Exemple #7
0
def account_verify_email(request):
    login_store = request.find_service(name="redis_login")

    try:
        user_id = int(request.GET["user_id"].strip())
        email_address = request.GET["email_address"].strip()
        token = request.GET["token"].strip()
    except (KeyError, ValueError):
        raise HTTPNotFound
    stored_token = login_store.get("verify_email:%s:%s" % (user_id, email_address))
    if not user_id or not email_address or not token or not stored_token:
        raise HTTPNotFound

    stored_token = stored_token.decode("utf-8")

    if not stored_token == token:
        raise HTTPNotFound

    try:
        db = request.find_service(name="db")
        user = db.query(User).filter(User.id == user_id).one()
    except NoResultFound:
        raise HTTPNotFound

    user.email = email_address

    response = HTTPFound(request.route_path("account", _query={"saved": "email_address"}))

    if not request.user or request.user.id != user.id:
        new_session_id = str(uuid4())
        login_store.set("session:" + new_session_id, user.id)
        response.set_cookie("cherubplay", new_session_id, 31536000)

    return response
Exemple #8
0
 def handle_get(self):
     request = self.request
     view = request.view_name
     subpath = request.subpath
     if not view:
         route = self.request.matched_route.name
         if route == 'home':
             self.response = HTTPFound('/frontdoor')
             return
         raise HTTPNotFound()
     elif view in ['login', 'logout']:
         # This breaks GET has no side effects
         if view == 'logout':
             return self.handle_logout({})
         self.response = HTTPFound('/frontdoor')
         return
     elif view == 'frontdoor':
         if not len(subpath):
             template = 'trumpet:templates/webview-app.mako'
             settings = self.get_app_settings()
             basecolor = settings['default.css.basecolor']
             env = dict(appname='frontdoor', basecolor=basecolor)
             content = render(template, env)
             self.response = Response(body=content)
             self.response.encode_content()
         else:
             assetpath = 'trumpet:static/apps/frontdoor'
             asset = os.path.join(assetpath, *subpath)
             self.response = static_asset_response(request, asset)
     else:
         self.response = HTTPNotFound()
Exemple #9
0
    def item_add(self):
        groupname = self.request.matchdict['groupname']
        groupfile = self.files[groupname]
        group = self.backend(groupname, groupfile)

        schema = group.get_add_schema()
        form = deform.Form(schema, buttons=('submit',))

        response = {"groupname": groupname,
                    "itemname": "new"}
        response["form"] = form.render()

        if 'submit' in self.request.POST and self.request.POST['submit'] == 'submit':
            controls = self.request.POST.items()
            try:
                data = form.validate(controls)
            except deform.ValidationFailure, e:
                response['form'] = e.render()
                return response

            if data['name'] not in self.protected_names[groupname]:
                group.add_item(data)
                response = HTTPFound()
                response.location = self.request.route_url('item',
                                                            groupname=groupname,
                                                            itemname=data['name'])
                return response
            else:
                return HTTPForbidden()
    def login(self):
        hubclient = self.request.registry.hubclient
        response = HTTPFound()

        # redeem ticket to get user data
        ticket = self.request.GET.get('ticket', None)
        if ticket and hubclient:
            try:
                user = hubclient.get_user(
                    ticket, self.request.route_url('redirect_to_login'))
                self.request.session[USER_DATA_SESSION_KEY] = user.data
                user_id = user.get('uuid')
                headers = remember(self.request, user_id)
                response.headerlist.extend(headers)

            except HubClientException:
                # TODO: what to do when ticket is invalid?
                pass

        redirect_url = self.request.GET.get('url', None)
        if not (redirect_url and same_origin(
                redirect_url, self.request.current_route_url())):
            redirect_url = self.request.route_url(route_name='home')
        response.location = redirect_url

        return response
Exemple #11
0
def logout(request):
    next = request.params.get('next') or request.route_url('index')
    if not authenticated_userid(request):
        return HTTPFound(location=request.route_url('login'))
    headers = forget(request)
    response = HTTPFound(location=next, headers=headers)
    response.set_cookie('csrf_token', value=None)
    return response
Exemple #12
0
def logout_view(request):
    """
        The logout view
    """
    loc = request.route_url('index')
    headers = forget(request)
    response = HTTPFound(location=loc, headers=headers)
    response.delete_cookie("remember_me")
    return response
    def logout(self):
        response = HTTPFound(headers=forget(self.request))

        if self.request.referrer and same_origin(
                self.request.referrer, self.request.current_route_url()):
            response.location = self.request.referrer
        else:
            response.location = self.request.route_url(route_name='home')

        return response
def login(request):
    username = request.params.get('username', None)
    password = request.params.get('password', None)
    session = DBSession()
    user = session.query(User).filter(User.username==username).first()
    if user is not None and user.password == password:
        response = HTTPFound('/')
        # totally insecure, TODO in workshop: use auth token or something
        response.set_cookie('user_id', str(user.id), max_age=timedelta(30))
        return response
    return {'username': username}
Exemple #15
0
    def auth(self):
        self.twitter = Twython(APP_KEY, APP_SECRET)
        auth = self.twitter.get_authentication_tokens(callback_url=CALLBACK_URL)
        OAUTH_TOKEN = auth['oauth_token']
        OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
        auth_url = auth['auth_url']

        # set cookies and redirect
        response = HTTPFound(location=auth_url)
        response.set_cookie('oauth_token', OAUTH_TOKEN, max_age=86400)
        response.set_cookie('oauth_token_secret', OAUTH_TOKEN_SECRET, max_age=86400)
        return response
Exemple #16
0
    def do_logout(self, request, location):
        """ do the logout """
        # convenient method to set Cache-Control and Expires headers
        request.response.cache_expires = 0

        headers = forget(request)
        response = HTTPFound(location=location, headers=headers)
        response.delete_cookie('cis_account', path="/")
        response.cache_control = 'no-cache'

        request.session.pop_flash('token')
        return response
Exemple #17
0
 def logout(self, request):
     request_cookie = request.cookies.get('signed')
     if not request_cookie:
         return {}
     cookie = signed_deserialize(request_cookie, SECRET)
     cookie_csrf = cookie.get('csrf')
     if request.method == 'POST':
         csrf = request.POST.get('csrf')
         if csrf == cookie_csrf:
             response = HTTPFound(request.route_url('admin.index'))
             response.delete_cookie('signed')
             return response
     return dict(csrf=cookie_csrf)
Exemple #18
0
    def record_delete(self):
        zonename = self.request.matchdict['zonename']
        recordname = self.request.matchdict['recordname']
        zonefile = settings.zones[zonename]
        zone = Zone(zonename, zonefile)
        if name_is_protected(zonename, recordname):
            raise HTTPForbidden("You can not modify this domain name")

        zone.del_record(recordname)
        response = HTTPFound()
        response.location = self.request.route_url('zoneview',
                                                    zonename=zonename)
        return response
Exemple #19
0
def change_profile(request, profile):
    """
    Sets a cookie for the given profile and deletes any location set in the
    cookies.
    Returns a response which directs to the map view.
    """
    response = HTTPFound(location=request.route_url('map_view'))
    response.set_cookie('_PROFILE_', profile, timedelta(days=90))

    if '_LOCATION_' in request.cookies:
        response.delete_cookie('_LOCATION_')

    return response
Exemple #20
0
    def item_delete(self):
        groupname = self.request.matchdict['groupname']
        itemname = self.request.matchdict['itemname']
        groupfile = self.files[groupname]
        group = self.backend(groupname, groupfile)
        if itemname in self.protected_names[groupname]:
            raise HTTPForbidden("You can not modify this domain name")

        group.del_item(itemname)
        response = HTTPFound()
        response.location = self.request.route_url('groupview',
                                                    groupname=groupname)
        return response
Exemple #21
0
def login(request):
    """
    Login view.
        request - Reads AJAX request to get user data and checks permissions on database.
    """
    try:

        login_url = route_url('login', request)

        referrer = request.url

        if referrer == login_url:
            referrer = '/'

        came_from = request.params.get('came_from', referrer)

        message = ''
        email = ''
        password = ''

        if 'form.submitted' in request.params:

            login = request.params['login']
            password = request.params['password']

            permissions = groupfinder(login, password, request)

            if permissions is None:
                message = 'BŁĘDNE HASŁO.'
            elif permissions is []:
                message = 'UŻYTKOWNIK %s NIE JEST ZAREJESTROWANY.' % email
            elif 'permission:' in permissions:
                headers = remember(request, permissions)

                response = HTTPFound(location=came_from, headers=headers)

                #Add user cookie
                response.set_cookie('user', value=login, max_age=31536000)

                return response

        return dict(
            message=message,
            url=request.application_url + '/login',
            came_from=came_from,
            login=email,
            password=password, )

    except DBAPIError, ex:
        print ex
        return Response(conn_err_msg, content_type='text/plain', status_int=500)
Exemple #22
0
    def sudo_employer(self):
        employer_id = self.request.matchdict['id']
        employer = DBSession.query(Employer).get(employer_id)
        if not employer:
            raise HTTPNotFound('Unknown employer id')
        else:
            self.request.session['employer_id'] = employer.id

        location = self.request.params.get('furl')
        if not location:
            location = 'http://%s/employer' % self.request.frontend_domain
        response = HTTPFound(location=location)
        response.set_cookie('__admin__', value='true') # max_age = year
        return response
Exemple #23
0
    def sudo_candidate(self):
        candidate_id = self.request.matchdict['id']
        candidate = DBSession.query(Candidate).get(candidate_id)
        if not candidate:
            raise HTTPNotFound('Unknown candidate id')
        else:
            self.request.session['candidate_id'] = candidate.id

        location = self.request.params.get('furl')
        if not location:
            location = 'http://%s/candidate' % self.request.frontend_domain
        response = HTTPFound(location=location)
        response.set_cookie('__admin__', value='true') # max_age = year
        return response
Exemple #24
0
def order(request): 
	server = Settings.Session.query(Server).filter(Server.id == request.matchdict['server']).scalar()
	item = Settings.Session.query(Item).filter(Item.id == request.matchdict['product']).scalar()
	path = [{"href": request.route_url('home'), "name": "Home", "active": False}, 
			{"href": '{href}?sid={sid}'.format(href=request.route_url('home'), sid=server.id), "name": server.name, "active": False},
			{"href": request.route_url('order', server=server.id, product=item.id), "name": item.name, "active": True}]
	errors = []
	if not server or not item or not item in [servitem.item for servitem in server.items]:
		return HTTPFound(location=request.route_url('home'))
	price = item.price
	for promotion in [promo.promotion for promo in item.promotions if promo.promotion.type == 1 and '%' not in promo.promotion.value and time.time() < promo.promotion.expires]:
		try:
			price = price - float(promotion.value)
		except:
			continue
	for promotion in [promo.promotion for promo in item.promotions if promo.promotion.type == 1 and '%' in promo.promotion.value and time.time() < promo.promotion.expires]:
		try:
			price = price - (price * (float(promotion.value.replace('%', '')) / 100))
		except:
			continue;
	if price < 0:
		price = 0
	if 'form.submitted' in request.params:
		try:
			steamid = SteamIDToCommunityID(request.params['input.steamid'])
		except SteamFormatException:
			errors.append('steamid')
		if not re.match(r'[^@]+@[^@]+\.[^@]+', request.params['input.email']):
			errors.append('email')
		if request.params['input.code'].strip():
			print "Code: %s" % request.params['input.code']
			code = None
			for promotion in [promo.promotion for promo in item.promotions if promo.promotion.type == 2 and time.time() < promo.promotion.expires]:
				if promotion.code == request.params['input.code']:
					code = promotion
					break
			if not code:
				errors.append('promo')
		if not errors:
			order = {'steamid': request.params['input.steamid'], 'email': request.params['input.email'], 
					'promocode': request.params['input.code'], 'server': server.id, 'item': item.id}
			response = HTTPFound(location=request.route_url('confirm'))
			response.set_cookie('order', value=json.dumps(order), max_age=300)
			return response

	path = [{"href": request.route_url('home'), "name": "Home", "active": False}, 
			{"href": '{href}?sid={sid}'.format(href=request.route_url('home'), sid=server.id), "name": server.name, "active": False},
			{"href": request.route_url('order', server=server.id, product=item.id), "name": item.name, "active": True}]
	return {'community': Settings.Community, 'item': item, 'server': server, 'path': path, 'errors': errors, 'price': round(price,2), 'path': path}
Exemple #25
0
 def get_main(self, appname=None, basecolor=None, view=None):
     settings = self.get_app_settings()
     if appname is None:
         appname = settings.get('default.js.mainapp', 'frontdoor')
     content = make_page(appname, settings, basecolor=basecolor, view=view)
     self.response = Response(body=content)
     self.response.encode_content()
Exemple #26
0
def directory_view(context, request):
    path_info = request.environ["PATH_INFO"]
    if not path_info.endswith("/"):
        response = HTTPFound(location=path_info + "/")
        return response

    defaults = ("index.html", "index.stx", "index.pt")
    for name in defaults:
        try:
            index = context[name]
        except KeyError:
            continue
        return file_view(index, request)
    response = Response("No default view for %s" % context.path)
    response.content_type = "text/plain"
    return response
Exemple #27
0
def directory_view(context, request):
    path_info = request.environ['PATH_INFO']
    if not path_info.endswith('/'):
        response = HTTPFound(location=path_info + '/')
        return response

    defaults = ('index.html', 'index.stx', 'index.pt')
    for name in defaults:
        try:
            index = context[name]
        except KeyError:
            continue
        return file_view(index, request)
    response = Response('No default view for %s' % context.path)
    response.content_type = 'text/plain'
    return response
    def select_persona(self):
        slug = self.request.matchdict['slug'].upper()
        if slug not in PERSONAE:
            raise HTTPNotFound

        # set cookie and redirect
        response = HTTPFound(location=get_redirect_url(self.request))
        response.set_cookie(PERSONA_COOKIE_NAME, value=slug, max_age=ONE_YEAR)

        # set persona dimension value on GA
        # NOTE: the persona dimension has to be configured with scope 'user'
        persona_dimension_id = self.settings.get('ga.persona_dimension_id')
        if persona_dimension_id:
            self.request.google_analytics[persona_dimension_id] = slug

        return response
Exemple #29
0
def sign_up(request):
    # Disable signing up in read-only mode.
    if "cherubplay.read_only" in request.registry.settings:
        raise HTTPForbidden
    # Make sure this IP address hasn't created an account recently.
    # Also don't explode if Redis is down.
    ip_check_key = "ip:" + request.environ["REMOTE_ADDR"]
    try:
        ip_check = request.login_store.get(ip_check_key)
    except ConnectionError:
        return {
            "sign_up_error": "We can't create your account because we're having problems with the login server. Please try again later."
        }
    if ip_check is not None:
        return {
            "sign_up_error": "An account has already been created from your IP address. Please try again in a few hours."
        }
    # Validate password.
    if request.POST["password"] == "":
        return {"sign_up_error": "Please don't use a blank password."}
    if request.POST["password"] != request.POST["password_again"]:
        return {"sign_up_error": "The two passwords didn't match."}
    # Make sure username hasn't been taken.
    username = request.POST["username"].lower()[:100]
    if username_validator.match(username) is None:
        return {"sign_up_error": "Usernames can only contain letters, numbers, hyphens and underscores."}
    existing_username = Session.query(User.id).filter(User.username == username).count()
    if existing_username == 1 or username in reserved_usernames:
        return {"sign_up_error": 'The username "%s" has already been taken.' % username}
    # Create the user.
    new_user = User(
        username=username,
        password=hashpw(request.POST["password"].encode(), gensalt()),
        last_ip=request.environ["REMOTE_ADDR"],
    )
    Session.add(new_user)
    Session.flush()
    # Generate session ID and add it to the login store.
    new_session_id = str(uuid.uuid4())
    request.login_store.set("session:" + new_session_id, new_user.id)
    # Remember their IP address for 12 hours.
    ip_check = request.login_store.set(ip_check_key, "1")
    ip_check = request.login_store.expire(ip_check_key, 43200)
    # Set cookie for session ID.
    response = HTTPFound(request.route_path("home"))
    response.set_cookie("cherubplay", new_session_id, 31536000)
    return response
Exemple #30
0
 def login(self, request):
     if request.method == 'POST':
         login = request.POST.get('login')
         password = request.POST.get('password')
         if login and password:
             user = dbs.query(StaffModel).filter_by(name=login).first()
             if user and user.password == sha256(
                     password + user.salt).hexdigest():
                 now = datetime.datetime.utcnow()
                 csrf = sha256(str(now)).hexdigest()
                 val = signed_serialize({'time': now, 'csrf': csrf}, SECRET)
                 response = HTTPFound(request.route_url('admin.index'))
                 response.set_cookie('signed', val)
                 return response
             return dict(
                 error='Something went wrong. Try "admin" and "111111"')
     return {}
Exemple #31
0
def logout_view(request):
    headers = forget(request)
    loc = request.route_url('home')
    return HTTPFound(location=loc, headers=headers)
Exemple #32
0
 def __call__(self):
     getter = getattr(self, 'get_redirect_url', None)
     url = getter() if getter else self.redirect_url
     return HTTPFound(location=url)
 def redirect(self):
     return HTTPFound(self._redirect_url())
Exemple #34
0
 def redirect(self):
     return HTTPFound(
         self.request.route_path('/users/{id}', id=self.context.user_id))
Exemple #35
0
def view_wiki(request):
    return HTTPFound(
        location=request.route_url('view_page', pagename='FrontPage'))
Exemple #36
0
def post_register(
    request: Request,
    username: str,
    password: str,
    password_confirm: str,
    invite_code: str,
) -> HTTPFound:
    """Process a registration request."""
    if not request.params.get("accepted_terms"):
        raise HTTPUnprocessableEntity(
            "Terms of Use and Privacy Policy must be accepted.")

    if password != password_confirm:
        raise HTTPUnprocessableEntity(
            "Password and confirmation do not match.")

    # attempt to fetch and lock the row for the specified invite code (lock prevents
    # concurrent requests from using the same invite code)
    #lookup_code = UserInviteCode.prepare_code_for_lookup(invite_code)
    #code_row = (
    #    request.query(UserInviteCode)
    #    .filter(
    #        UserInviteCode.code == lookup_code,
    #        UserInviteCode.invitee_id == None,  # noqa
    #    )
    #    .with_for_update(skip_locked=True)
    #    .one_or_none()
    #)

    #if not code_row:
    #    incr_counter("invite_code_failures")
    #    raise HTTPUnprocessableEntity("Invalid invite code")

    # create the user and set inviter to the owner of the invite code
    user = User(username, password)
    #user.inviter_id = code_row.user_id

    # flush the user insert to db, will fail if username is already taken
    request.db_session.add(user)
    try:
        request.db_session.flush()
    except IntegrityError:
        raise HTTPUnprocessableEntity(
            "That username has already been registered.")

    # the flush above will generate the new user's ID, so use that to update the invite
    # code with info about the user that registered with it
    #code_row.invitee_id = user.user_id

    # subscribe the new user to all groups except ~test
    all_groups = request.query(Group).all()
    for group in all_groups:
        if group.path == "test":
            continue
        request.db_session.add(GroupSubscription(user, group))

    _send_welcome_message(user, request)

    incr_counter("registrations")

    # log the user in to the new account
    remember(request, user.user_id)

    # set request.user before logging so the user is associated with the event
    request.user = user
    request.db_session.add(Log(LogEventType.USER_REGISTER, request))

    # redirect to the front page
    raise HTTPFound(location="/")
Exemple #37
0
def user(context, request):
    gallery = retrieve_gallery(context)
    if gallery is not None:
        return HTTPFound(location=request.resource_url(gallery))
    else:
        return HTTPNotFound()
Exemple #38
0
def assembl_profile(request):
    session = AgentProfile.default_db
    localizer = request.localizer
    profile = get_profile(request)
    id_type = request.matchdict.get('type').strip()
    logged_in = request.authenticated_userid
    save = request.method == 'POST'
    # if some other user
    if not profile or not logged_in or logged_in != profile.id:
        if save:
            raise HTTPUnauthorized()
        # Add permissions to view a profile?
        return render_to_response(
            'assembl:templates/view_profile.jinja2',
            dict(get_default_context(request),
                 profile=profile,
                 user=logged_in and session.query(User).get(logged_in)))

    confirm_email = request.params.get('confirm_email', None)
    if confirm_email:
        return HTTPTemporaryRedirect(location=request.route_url(
            'confirm_emailid_sent', email_account_id=int(confirm_email)))
    errors = []
    if save:
        user_id = profile.id
        redirect = False
        username = request.params.get('username', '').strip()
        if username and (profile.username is None
                         or username != profile.username.username):
            # check if exists
            if session.query(Username).filter_by(username=username).count():
                errors.append(
                    localizer.translate(_('The username %s is already used')) %
                    (username, ))
            else:
                old_username = profile.username
                if old_username is not None:
                    # free existing username
                    session.delete(old_username)
                    session.flush()
                # add new username
                session.add(Username(username=username, user=profile))

                if id_type == 'u':
                    redirect = True
        name = request.params.get('name', '').strip()
        if name:
            profile.name = name
        p1, p2 = (request.params.get('password1', '').strip(),
                  request.params.get('password2', '').strip())
        if p1 != p2:
            errors.append(
                localizer.translate(_('The passwords are not identical')))
        elif p1:
            profile.password_p = p1
        add_email = request.params.get('add_email', '').strip()
        if add_email:
            if not is_email(add_email):
                return dict(get_default_context(request),
                            error=localizer.translate(
                                _("This is not a valid email")))
            # No need to check presence since not validated yet
            email = EmailAccount(email=add_email, profile=profile)
            session.add(email)
        if redirect:
            return HTTPFound(location=request.route_url(
                'profile_user', type='u', identifier=username))
        profile = session.query(User).get(user_id)
    unverified_emails = [
        (ea,
         session.query(AbstractAgentAccount).filter_by(email_ci=ea.email_ci,
                                                       verified=True).first())
        for ea in profile.email_accounts if not ea.verified
    ]
    get_route = create_get_route(request)
    providers = get_provider_data(get_route)
    return render_to_response(
        'assembl:templates/profile.jinja2',
        dict(get_default_context(request),
             error='<br />'.join(errors),
             unverified_emails=unverified_emails,
             providers=providers,
             providers_json=json.dumps(providers),
             google_consumer_key=request.registry.settings.get(
                 'google.consumer_key', ''),
             the_user=profile,
             user=session.query(User).get(logged_in)))
Exemple #39
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
            print "email token:", request.route_url(
                'user_confirm_email', token=email_token(email_account))
        headers = remember(request, user.id)
        user.successful_login()
        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))
Exemple #40
0
 def cancel_handler(self):
     return HTTPFound(location=self.get_next_url())
Exemple #41
0
 def get(self):
     today = datetime.datetime.now().date()
     url = self.request.url_for('/times/report/pivot',
                                month=today.strftime('%m.%Y'))
     return HTTPFound(location=url)
Exemple #42
0
 def add_success(self, appstruct):
     registry = self.request.registry
     name = appstruct.pop('name')
     document = registry.content.create('Document', **appstruct)
     self.context[name] = document
     return HTTPFound(self.request.mgmt_path(document, '@@properties'))
Exemple #43
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 = request.authenticated_userid
    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))
    print "pwc V%sP%sW%sB%sL%s" % tuple(
        map(lambda b: "-" if b else "+",
            (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:
        if discussion:
            request.session.flash(
                localizer.translate(
                    _("You will enter the discussion as <b>{name}</b>.")).
                format(name=user.name), 'message')
        else:
            request.session.flash(
                localizer.translate(
                    _("You will enter Assembl as <b>{name}</b>.")).format(
                        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,
        'react_do_password_change',
        _query=dict(token=token, welcome=welcome)))
Exemple #44
0
def root(context, request):
    return HTTPFound(
        location=request.resource_url('list_albums', username='******'))
    def phrasal_form_view(self):
        phrase_group = self.phrase_group
        phrase_form = self.phrase_form

        if 'POST' in self.request.method:
            # If posting, no data would've been persisted anyways
            # NOTE: If this changes in the future, remove it from here!
            self.session_was_lost = False
            # Clear temporary data if it's a post
            self.msgs = []

        if self.session_was_lost:
            self.msgs.append(
                OpMessage(
                    MessageType.Info,
                    "Your browser says you've visited, but I don't remember "
                    "what you wrote.  The server might've been restarted.  "
                    "Pardon for any hassle.",
                    "Welcome back!"
                )
            )
            self.session_was_lost = False

        if 'clear' in self.request.params:
            log.debug(
                "phrasal_form_view: Clearing UUID {0}"
                .format(self.session_uuid)
            )
            phrase_group['seed'] = ''
            phrase_group['phrases'] = ''
            phrase_group['results'] = ''
            # Shift focus to the form
            url = self.request.route_url(
                'phrasal_form_view', _anchor='form'
            )
            return HTTPFound(url)
        elif 'demo' in self.request.params:
            log.debug(
                "phrasal_form_view: Resetting UUID {0} to demo"
                .format(self.session_uuid)
            )
            phrase_group['seed'] = ''
            phrase_group['phrases'] = PhraseStorage.get_demo_phrase_source()
            phrase_group['results'] = ''
            self.msgs.append(
                OpMessage(
                    MessageType.Info,
                    "Read the phrases above and press Submit to see the "
                    "results.",
                    "Demo ready"
                )
            )
            # Shift focus to the form
            url = self.request.route_url(
                'phrasal_form_view', _anchor='form'
            )
            return HTTPFound(url)
        elif 'submit' in self.request.params:
            controls = self.request.POST.items()
            try:
                appstruct = phrase_form.validate(controls)
            except deform.ValidationFailure as e:
                return dict(
                    phrase_group=phrase_group,
                    form=e.render()
                )

            # Change the content and redirect to the view
            phrase_group['seed'] = appstruct['seed']
            phrase_group['phrases'] = appstruct['phrases']
            # Process the source, get the results
            phrase_group['results'] = (
                process_phrase(
                    self.msgs,
                    phrase_group['phrases'],
                    phrase_group['seed']
                )
            )
            log.debug(
                "phrasal_form_view: Updating UUID {0}, new group {1}"
                .format(self.session_uuid, phrase_group)
            )
            self.phrase_group = phrase_group

            url = self.request.route_url(
                'phrasal_form_view', _anchor='results'
            )
            return HTTPFound(url)

        form = phrase_form.render(phrase_group)

        parsed_msgs = parse_messages(self.msgs)
        if parsed_msgs:
            log.debug(
                "phrasal_form_view: parsed_msgs: '{0}'"
                .format(parsed_msgs)
            )

        return dict(
            phrase_group=phrase_group, parsed_msgs=parsed_msgs, form=form
        )
Exemple #46
0
def view_wiki(request):
    """function for viewing the front page of the databank
    may become redundant"""
    next_url = request.route_url('view_page', pagename='FrontPage')
    return HTTPFound(location=next_url)
Exemple #47
0
def logout(request):
    headers = forget(request)
    return HTTPFound(location=request.route_url('view_wiki'), headers=headers)
 def redirect(self, url):
     """Return a response redirect to the given URL"""
     return HTTPFound(location=url)
Exemple #49
0
 def redirect(self):
     return HTTPFound(self.request.current_route_path())
Exemple #50
0
def register(request):
    """
    Render register page with form
    Also handles oAuth flow for registration
    """
    login_url = request.route_url("ziggurat.routes.sign_in")
    if request.query_string:
        query_string = "?%s" % request.query_string
    else:
        query_string = ""
    referrer = "%s%s" % (request.path, query_string)

    if referrer in [login_url, "/register", "/register?sign_in=1"]:
        referrer = "/"  # never use the login form itself as came_from
    sign_in_form = forms.SignInForm(
        came_from=request.params.get("came_from", referrer), csrf_context=request
    )

    # populate form from oAuth session data returned by authomatic
    social_data = request.session.get("zigg.social_auth")
    if request.method != "POST" and social_data:
        log.debug(social_data)
        user_name = social_data["user"].get("user_name", "").split("@")[0]
        form_data = {"user_name": user_name, "email": social_data["user"].get("email")}
        form_data["user_password"] = str(uuid.uuid4())
        form = forms.UserRegisterForm(MultiDict(form_data), csrf_context=request)
        form.user_password.widget.hide_value = False
    else:
        form = forms.UserRegisterForm(request.POST, csrf_context=request)
    if request.method == "POST" and form.validate():
        log.info("registering user")
        # insert new user here
        if request.registry.settings["appenlight.disable_registration"]:
            request.session.flash(_("Registration is currently disabled."))
            return HTTPFound(location=request.route_url("/"))

        new_user = User()
        DBSession.add(new_user)
        form.populate_obj(new_user)
        UserService.regenerate_security_code(new_user)
        new_user.status = 1
        UserService.set_password(new_user, new_user.user_password)
        new_user.registration_ip = request.environ.get("REMOTE_ADDR")

        if social_data:
            handle_social_data(request, new_user, social_data)

        email_vars = {
            "user": new_user,
            "request": request,
            "email_title": "AppEnlight :: Start information",
        }
        UserService.send_email(
            request,
            recipients=[new_user.email],
            variables=email_vars,
            template="/email_templates/registered.jinja2",
        )
        request.session.flash(_("You have successfully registered."))
        DBSession.flush()
        headers = security.remember(request, new_user.id)
        return HTTPFound(location=request.route_url("/"), headers=headers)
    settings = request.registry.settings
    social_plugins = {}
    if settings.get("authomatic.pr.twitter.key", ""):
        social_plugins["twitter"] = True
    if settings.get("authomatic.pr.google.key", ""):
        social_plugins["google"] = True
    if settings.get("authomatic.pr.github.key", ""):
        social_plugins["github"] = True
    if settings.get("authomatic.pr.bitbucket.key", ""):
        social_plugins["bitbucket"] = True

    return {
        "form": form,
        "sign_in_form": sign_in_form,
        "social_plugins": social_plugins,
    }
 def redirect(self, model=None):
     return HTTPFound(self._redirect_url())
Exemple #52
0
 def cancel_success(self, appstruct):
     self.request.session.flash(_('No changes were made.'), 'info')
     location = '{0}/@@setup-users'.format(self.request.application_url)
     return HTTPFound(location=location)
Exemple #53
0
    def render(self):

        return HTTPFound(location=route_url('index', self.request),
                         headers=forget(self.request))
Exemple #54
0
 def delete_success(self, appstruct):
     location = '{0}/@@delete-user?name={1}'.format(
         self.request.application_url, self.request.params['name'])
     return HTTPFound(location=location)
def project_edit(request):
    id = request.matchdict['project']
    project = DBSession.query(Project).get(id)

    licenses = DBSession.query(License).all()
    labels = DBSession.query(Label).all()

    if 'form.submitted' in request.params:
        for locale, translation in project.translations.iteritems():
            with project.force_locale(locale):
                for field in [
                        'name', 'short_description', 'description',
                        'instructions', 'per_task_instructions'
                ]:
                    translated = '_'.join([field, locale])
                    if translated in request.params:
                        setattr(project, field, request.params[translated])
                DBSession.add(project)

        for p in ['changeset_comment', 'entities_to_map', 'imagery']:
            if p in request.params:
                setattr(project, p, request.params[p])

        if 'license_id' in request.params and \
                request.params['license_id'] != "":
            license_id = int(request.params['license_id'])
            license = DBSession.query(License).get(license_id)
            project.license = license

        project.labels = []
        labels = [x for x in request.params if 'label_' in x]
        if len(labels) != 0:
            for t in labels:
                if request.params[t] != "":
                    label_id = int(t[6:])
                    label = DBSession.query(Label).get(label_id)
                    project.labels.append(label)

        if 'private' in request.params and \
                request.params['private'] == 'on':
            project.private = True
        else:
            project.private = False

        project.requires_validator_role = \
            ('requires_validator_role' in request.params and
             request.params['requires_validator_role'] == 'on')

        project.requires_experienced_mapper_role = \
            ('requires_experienced_mapper_role' in request.params and
             request.params['requires_experienced_mapper_role'] == 'on')

        project.status = request.params['status']
        project.priority = request.params['priority']

        if request.params.get('due_date', '') != '':
            due_date = request.params.get('due_date')
            due_date = datetime.datetime.strptime(due_date, "%m/%d/%Y")
            project.due_date = due_date
        else:
            project.due_date = None

        if 'josm_preset' in request.params:
            josm_preset = request.params.get('josm_preset')
            if hasattr(josm_preset, 'value'):
                project.josm_preset = josm_preset.value.decode('UTF-8')

        # Remove the previously set priority areas
        for area in project.priority_areas:
            DBSession.delete(area)
        project.priority_areas[:] = []
        DBSession.flush()

        priority_areas = request.params.get('priority_areas', '')

        if priority_areas != '':
            features = parse_geojson(priority_areas)

            for feature in features:
                geom = 'SRID=4326;%s' % feature.geometry.wkt
                project.priority_areas.append(PriorityArea(geom))

        DBSession.add(project)
        return HTTPFound(
            location=route_path('project', request, project=project.id))

    translations = project.translations.items()

    features = []
    for area in project.priority_areas:
        features.append(Feature(geometry=shape.to_shape(area.geometry)))

    return dict(page_id='project_edit',
                project=project,
                licenses=licenses,
                translations=translations,
                labels=labels,
                priority_areas=FeatureCollection(features))
Exemple #56
0
 def cancel_success(self, appstruct):
     location = self.request.resource_url(get_root())
     return HTTPFound(location=location)
def route_list(request):
    return HTTPFound(location=request.route_url('user-group'))
Exemple #58
0
 def fail(msg="Sign in link invalid. Please try again."):
     messages.add(request,
                  kind="error",
                  msg=msg,
                  msg_id="msg-bad-email-token")
     return HTTPFound(request.route_url("login"))
Exemple #59
0
 def cancel_handler(self):
     return HTTPFound(location='.')
Exemple #60
0
def user_confirm_email(request):
    token = request.matchdict.get('token') or ''
    account, validity = verify_email_token(token)
    session = AbstractAgentAccount.default_db
    logged_in = request.authenticated_userid  # 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.
        if inferred_discussion:
            if inferred_discussion.preferences['landing_page']:
                route = 'new_home'
            else:
                route = 'home'
        else:
            route = 'discussion_list'
        error = localizer.translate(
            _("Email <%s> already confirmed")) % (account.email, )
        request.session.flash(error)
        return HTTPFound(
            location=request.route_url(route,
                                       discussion_slug=inferred_discussion.
                                       slug if inferred_discussion else None))

    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,
                'react_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.successful_login()
    username = user.username.username if user.username else None
    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.username
            account = other_account
        account.verified = True
        user.verified = True
        # do not use inferred discussion for auto_subscribe
        user.successful_login()
        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:
        if inferred_discussion.preferences['landing_page']:
            route = 'new_home'
        else:
            route = 'home'
    else:
        route = 'discussion_list'
    return HTTPFound(
        location=request.route_url(route,
                                   discussion_slug=inferred_discussion.
                                   slug if inferred_discussion else None,
                                   _query=dict(message=message)))