Beispiel #1
0
def common_design_update(request, nick):
    view = api.actor_get(api.ROOT, nick)
    if request.POST:
        try:
            validate.nonce(request, 'update_design')

            color = request.POST.get('bg_color')
            repeat = request.POST.get('bg_repeat', 'no-repeat')
            if not repeat:
                repeat = ''

            img = request.FILES.get('bg_image')
            img_url = None
            if img:
                img_url = api.background_upload(request.user, nick, img.read())
            api.background_set_actor(request.user, nick, img_url, color,
                                     repeat)
            return util.RedirectFlash(view.url() + '/settings/design',
                                      'design updated')
        except:
            exception.handle_exception(request)

    if request.GET and 'restore' in request.GET:
        api.background_clear_actor(request.user, nick)
        return util.RedirectFlash(view.url() + '/settings/design',
                                  'design updated')

    return None
Beispiel #2
0
def install_rootuser(request):
    # requires an admin
    user = users.get_current_user()
    if not user:
        return http.HttpResponseRedirect(users.create_login_url('/install'))
    else:
        if not users.is_current_user_admin():
            return http.HttpResponseRedirect('/')

    try:
        root_user = api.actor_get(api.ROOT, settings.ROOT_NICK)
    except:
        root_user = None

    if request.POST:
        try:
            logging.warning('Making root user: %s', settings.ROOT_NICK)
            validate.nonce(request, 'create_root')
            root_user = api.user_create_root(api.ROOT)
            return util.RedirectFlash('/install', 'Root user created')
        except:
            exception.handle_exception(request)

    redirect_to = '/'

    c = template.RequestContext(request, locals())
    t = loader.get_template('install/templates/rootuser.html')
    return http.HttpResponse(t.render(c))
Beispiel #3
0
def common_design_update(request, nick):
  view = api.actor_get(api.ROOT, nick)
  if request.POST:
    try:
      validate.nonce(request, 'update_design')

      color = request.POST.get('bg_color')
      repeat = request.POST.get('bg_repeat', 'no-repeat')
      if not repeat:
        repeat = ''

      img = request.FILES.get('bg_image')
      img_url = None
      if img:
        img_url = api.background_upload(request.user,
                                        nick,
                                        img.read())
      api.background_set_actor(request.user,
                               nick,
                               img_url,
                               color,
                               repeat)
      return util.RedirectFlash(view.url() + '/settings/design',
                                'design updated')
    except:
      exception.handle_exception(request)

  if request.GET and 'restore' in request.GET:
      api.background_clear_actor(request.user, nick)
      return util.RedirectFlash(view.url() + '/settings/design',
                                'design updated')

  return None
Beispiel #4
0
def common_design_update(request, success="/", nick=None):
  if not nick:
    nick = request.user.nick
  view = api.actor_get(api.ROOT, nick)
  if request.POST:
    try:
      validate.nonce(request, 'update_design')

      color = request.POST.get('bg_color')
      repeat = request.POST.get('bg_repeat', 'no-repeat')
      if not repeat:
        repeat = ''

      img = request.FILES.get('bg_image')
      img_url = None
      if img:
        img_url = api.background_upload(request.user,
                                        nick,
                                        img.read())
      api.background_set_actor(request.user,
                               nick,
                               img_url,
                               color,
                               repeat)
      return util.RedirectFlash(success,
                                'Thiết lập về màu nền/ảnh nền đã được cập nhật lại.')
    except:
      exception.handle_exception(request)

  if request.GET and 'restore' in request.GET:
      api.background_clear_actor(request.user, nick)
      return util.RedirectFlash(success,
                                'Thiết lập ảnh nền/màu nền đã được khôi phục về trạng thái mặc định.')

  return None
Beispiel #5
0
def install_rootuser(request):
  # requires an admin
  user = users.get_current_user()
  if not user:
    return http.HttpResponseRedirect(users.create_login_url('/install'))
  else:
    if not users.is_current_user_admin():
      return http.HttpResponseRedirect('/')

  try:
    root_user = api.actor_get(api.ROOT, settings.ROOT_NICK)
  except:
    root_user = None

  if request.POST:
    try:
      logging.warning('Making root user: %s', settings.ROOT_NICK)
      validate.nonce(request, 'create_root')
      root_user = api.user_create_root(api.ROOT)
      return util.RedirectFlash('/install', 'Root user created')
    except:
      exception.handle_exception(request)

  redirect_to = '/'

  c = template.RequestContext(request, locals())
  t = loader.get_template('install/templates/rootuser.html')
  return http.HttpResponse(t.render(c))
Beispiel #6
0
def call_api_from_request(request, api_call):
  """Call an API function 'api_call' if it's present in the request parameters.

  The first parameter to the API call is always the logged-in user.

  The rest of the parameters may come in two forms:
    api_call_name=first_param& ... rest of params
    or
    api_call_name=& ... rest of params

    rest_of_params is always turned into Python keyword arguments.

    If the api_call_name has a value, that is turned into Python positional
    params.
  RETURNS:
    (False, None) if it isn't or the call throws an exception,
    (True, return value from call) otherwise.
  """
  # TODO(termie): make this only accept POST once we update javascript
  #               to turn the links into POSTs
  for request_dict in (request.POST, request.GET):
    if api_call in request_dict:
      # debug
      logging.info(">>> CALL: %s", str(api_call))
      # end debug
      call = getattr(api, api_call)
      try:
        validate.nonce(request, api_call)
        confirm_msg = messages.confirmation(api_call)
        # debug
        # logging.info(">>> MESSAGE : %s", str(confirm_msg))
        # end debug
 
        if not confirm_msg is None:
          validate.confirm_dangerous(
              request, messages.confirmation(api_call))
        kwparams = util.query_dict_to_keywords(request_dict)
        # debug
        logging.info(">>> KWPARAMS: %s", str(kwparams))
        # end debug
 
        if '' in kwparams:
          del kwparams['']
        first_param = kwparams.pop(api_call, '')
        params = list()
        if len(first_param):
          params = (first_param,)
        validate.nonce(request, api_call)
        kwparams.pop('_nonce')
        kwparams.pop('confirm', None)
        kwparams.pop('redirect_to', None)
        # debug
        logging.info("##### CALL: %s", str((params, kwparams)))
        # end debug

        return (True, call(request.user, *params, **kwparams))
      except:
        exception.handle_exception(request)
  return (False, None)
Beispiel #7
0
def api_authorize(request):
  """
  checks on the request token provided or ask the user enter one
  allows the user to authorize this
  if consumer style is web and a callback is provided redirect to it
    otherwise suggest that the user notify their application that authorization
    has completed
  """
  redirect = urllib.quote(request.get_full_path())

  view = user.get_user_from_cookie_or_legacy_auth(request)
  if view is None:
    logging.info("Redirect: %s " % redirect)
    return http.HttpResponseRedirect("/login?redirect_to=%s" % redirect)
  
  oauth_token = request.REQUEST.get('oauth_token', None)
  if not oauth_token:
    # please enter token page
    pass

  oauth_token_ref = api.oauth_get_request_token(api.ROOT, oauth_token)
  if not oauth_token_ref:
    raise Exception("bad token")

  oauth_consumer_ref = api.oauth_get_consumer(api.ROOT,
                                              oauth_token_ref.consumer)
  if not oauth_consumer_ref:
    raise Exception("bad consumer")
  if "active" != oauth_consumer_ref.status:
    raise Exception("inactive consumer")
  
  perms = request.REQUEST.get('perms', 'read')
  if request.POST:
    # we posted to this page to authorize
    # TODO verify nonce
    validate.nonce(request, "authorize_token")

    api.oauth_authorize_request_token(api.ROOT, oauth_token_ref.key_,
                                      actor=request.user.nick, perms=perms)

    oauth_callback = request.POST.get("oauth_callback", None)
    if oauth_consumer_ref.type == "web":
      if oauth_callback:
        return http.HttpResponseRedirect(oauth_callback)
      elif oauth_consumer_ref.callback_url is not None:
        return http.HttpResponseRedirect(oauth_consumer_ref.callback_url)

    c = template.RequestContext(request, locals())
    t = loader.get_template('api/templates/authorized.html')
    return http.HttpResponse(t.render(c))
  
  perms_pretty = {'read': 'view',
                  'write': 'view and update',
                  'delete': 'view, update and delete'}[perms]

  c = template.RequestContext(request, locals())
  t = loader.get_template('api/templates/authorize.html')
  return http.HttpResponse(t.render(c))
Beispiel #8
0
    def test_good_nonces(self):
        fake_user = '******'
        action = 'some_action'

        nonce = util.create_nonce(fake_user, action)
        params = {'_nonce': nonce}

        validate.nonce(test_util.FakeRequest(user=fake_user, post=params),
                       action)

        validate.nonce(test_util.FakeRequest(user=fake_user, get=params),
                       action)
Beispiel #9
0
def api_authorize(request):
    """
  checks on the request token provided or ask the user enter one
  allows the user to authorize this
  if consumer style is web and a callback is provided redirect to it
    otherwise suggest that the user notify their application that authorization
    has completed
  """
    oauth_token = request.REQUEST.get('oauth_token', None)
    if not oauth_token:
        # please enter token page
        pass

    oauth_token_ref = api.oauth_get_request_token(api.ROOT, oauth_token)
    if not oauth_token_ref:
        raise Exception("bad token")

    oauth_consumer_ref = api.oauth_get_consumer(api.ROOT,
                                                oauth_token_ref.consumer)
    if not oauth_consumer_ref:
        raise Exception("bad consumer")
    if "active" != oauth_consumer_ref.status:
        raise Exception("inactive consumer")

    perms = request.REQUEST.get('perms', 'read')
    if request.POST:
        # we posted to this page to authorize
        # TODO verify nonce
        validate.nonce(request, "authorize_token")

        api.oauth_authorize_request_token(api.ROOT,
                                          oauth_token_ref.key_,
                                          actor=request.user.nick,
                                          perms=perms)

        oauth_callback = request.POST.get("oauth_callback", None)
        if oauth_callback and oauth_consumer_ref.type == "web":
            return http.HttpResponseRedirect(oauth_callback)

        c = template.RequestContext(request, locals())
        t = loader.get_template('api/templates/authorized.html')
        return http.HttpResponse(t.render(c))

    perms_pretty = {
        'read': 'view',
        'write': 'view and update',
        'delete': 'view, update and delete'
    }[perms]

    c = template.RequestContext(request, locals())
    t = loader.get_template('api/templates/authorize.html')
    return http.HttpResponse(t.render(c))
Beispiel #10
0
  def test_good_nonces(self):
    fake_user = '******'
    action = 'some_action'


    nonce = util.create_nonce(fake_user, action)
    params = {'_nonce': nonce}

    validate.nonce(test_util.FakeRequest(
                       user=fake_user,
                       post=params),
                   action)

    validate.nonce(test_util.FakeRequest(
                      user=fake_user,
                      get=params),
                   action)
Beispiel #11
0
def install(request):
  try:
    root_user = api.actor_get(api.ROOT, settings.ROOT_NICK)
    if root_user:
      return util.RedirectFlash('/', 'Already Installed')
  except:
    root_user = None

  post_name = util.get_metadata('POST_NAME')
  default_channel = util.get_metadata('DEFAULT_CHANNEL')

  if request.POST:
    site_name = request.POST.get('site_name', None)
    tagline = request.POST.get('tagline', None)
    post_name = request.POST.get('post_name', None)

    root_mail = request.POST.get('root_mail', None)
    password = request.POST.get('password', None)
    confirm =  request.POST.get('confirm', None)
    default_channel = request.POST.get('default_channel', None)

    try:
      logging.info('saving values')
      validate.nonce(request, 'install')
      validate.email(root_mail)
      validate.password(password)
      validate.password_and_confirm(password, confirm)
      channel = clean.channel(default_channel)

      admin_helper.validate_and_save_sitesettings(site_name, tagline, post_name)
      root_user = api.user_create_root(api.ROOT, password=password)
      api.email_associate(api.ROOT, root_user.nick, root_mail)
      channel_ref = api.channel_create(api.ROOT, nick=api.ROOT.nick, channel=channel, tags=[],
                                       type='', description='Support Channel')
      util.set_metadata('DEFAULT_CHANNEL', default_channel)

      logging.info('Installed and Redirecting to front')
      return util.RedirectFlash('/', 'Installed Successfully')
    except:
      exception.handle_exception(request)

  redirect_to = '/'

  c = template.RequestContext(request, locals())
  return render_to_response('administration/templates/install.html', c)
Beispiel #12
0
    def test_slightly_old_nonces(self):
        fake_user = '******'
        action = 'some_action'

        nonce = util.create_nonce(fake_user, action, offset=-1)

        validate.nonce(
            test_util.FakeRequest(user=fake_user, post={'_nonce': nonce}),
            action)

        old_nonce = util.create_nonce(fake_user, action, offset=-2)

        def _old_nonce():
            validate.nonce(
                test_util.FakeRequest(user=fake_user,
                                      post={'_nonce': old_nonce}), action)

        self.assertRaises(exception.ValidationError, _old_nonce)
Beispiel #13
0
  def test_slightly_old_nonces(self):
    fake_user = '******'
    action = 'some_action'

    nonce = util.create_nonce(fake_user, action, offset= -1)

    validate.nonce(test_util.FakeRequest(
                       user=fake_user,
                       post={'_nonce': nonce}),
                   action)

    old_nonce = util.create_nonce(fake_user, action, offset= -2)
    def _old_nonce():
      validate.nonce(test_util.FakeRequest(
                         user=fake_user,
                         post={'_nonce': old_nonce}),
                     action)
    self.assertRaises(exception.ValidationError, _old_nonce)
Beispiel #14
0
def call_api_from_request(request, api_call):
    """Call an API function 'api_call' if it's present in the request parameters.

  The first parameter to the API call is always the logged-in user.

  The rest of the parameters may come in two forms:
    api_call_name=first_param& ... rest of params
    or
    api_call_name=& ... rest of params

    rest_of_params is always turned into Python keyword arguments.

    If the api_call_name has a value, that is turned into Python positional
    params.
  RETURNS:
    (False, None) if it isn't or the call throws an exception,
    (True, return value from call) otherwise.
  """
    # TODO(termie): make this only accept POST once we update javascript
    #               to turn the links into POSTs
    for request_dict in (request.POST, request.GET):
        if api_call in request_dict:
            call = getattr(api, api_call)
            try:
                validate.nonce(request, api_call)
                confirm_msg = messages.confirmation(api_call)
                if not confirm_msg is None:
                    validate.confirm_dangerous(request,
                                               messages.confirmation(api_call))
                kwparams = util.query_dict_to_keywords(request_dict)
                if '' in kwparams:
                    del kwparams['']
                first_param = kwparams.pop(api_call, '')
                params = list()
                if len(first_param):
                    params = (first_param, )
                validate.nonce(request, api_call)
                kwparams.pop('_nonce')
                kwparams.pop('confirm', None)
                kwparams.pop('redirect_to', None)
                return (True, call(request.user, *params, **kwparams))
            except:
                exception.handle_exception(request)
    return (False, None)
Beispiel #15
0
def api_authorize(request):
    """
  checks on the request token provided or ask the user enter one
  allows the user to authorize this
  if consumer style is web and a callback is provided redirect to it
    otherwise suggest that the user notify their application that authorization
    has completed
  """
    oauth_token = request.REQUEST.get("oauth_token", None)
    if not oauth_token:
        # please enter token page
        pass

    oauth_token_ref = api.oauth_get_request_token(api.ROOT, oauth_token)
    if not oauth_token_ref:
        raise Exception("bad token")

    oauth_consumer_ref = api.oauth_get_consumer(api.ROOT, oauth_token_ref.consumer)
    if not oauth_consumer_ref:
        raise Exception("bad consumer")
    if "active" != oauth_consumer_ref.status:
        raise Exception("inactive consumer")

    perms = request.REQUEST.get("perms", "read")
    if request.POST:
        # we posted to this page to authorize
        # TODO verify nonce
        validate.nonce(request, "authorize_token")

        api.oauth_authorize_request_token(api.ROOT, oauth_token_ref.key_, actor=request.user.nick, perms=perms)

        oauth_callback = request.POST.get("oauth_callback", None)
        if oauth_callback and oauth_consumer_ref.type == "web":
            return http.HttpResponseRedirect(oauth_callback)

        c = template.RequestContext(request, locals())
        t = loader.get_template("api/templates/authorized.html")
        return http.HttpResponse(t.render(c))

    perms_pretty = {"read": "view", "write": "view and update", "delete": "view, update and delete"}[perms]

    c = template.RequestContext(request, locals())
    t = loader.get_template("api/templates/authorize.html")
    return http.HttpResponse(t.render(c))
Beispiel #16
0
def common_confirm(request):
    message = request.REQUEST['message']
    redirect_to = request.REQUEST['redirect_to']

    try:
        validate.nonce(request, message + redirect_to)

        parts = urlparse.urlparse(redirect_to)
        action_url = parts[2]
        query_dict = cgi.parse_qs(parts[4], keep_blank_values=True)
        query_dict = dict([(k, v[0]) for k, v in query_dict.iteritems()])

    except:
        message = None
        exception.handle_exception(request)

    c = template.RequestContext(request, locals())
    t = loader.get_template('common/templates/confirm.html')
    return http.HttpResponse(t.render(c))
Beispiel #17
0
def common_confirm(request):
  message = request.REQUEST['message']
  redirect_to = request.REQUEST['redirect_to']

  try:
    validate.nonce(request, message + redirect_to)

    parts = urlparse.urlparse(redirect_to)
    action_url = parts[2]
    query_dict = cgi.parse_qs(parts[4], keep_blank_values=True)
    query_dict = dict([(k, v[0]) for k, v in query_dict.iteritems()])

  except:
    message = None
    exception.handle_exception(request)


  c = template.RequestContext(request, locals())
  t = loader.get_template('common/templates/confirm.html')
  return http.HttpResponse(t.render(c))
Beispiel #18
0
def admin_site(request):
  page = 'site'
  title = 'Site Settings'
  
  site_name = util.get_metadata('SITE_NAME')
  tagline = util.get_metadata('TAGLINE')
  post_name = util.get_metadata('POST_NAME')
  
  if request.POST:
    site_name = request.POST.get('site_name', None)
    tagline = request.POST.get('tagline', None)
    post_name = request.POST.get('post_name', None)
    site_description = request.POST.get('site_description', None)
    try:
      validate.nonce(request, 'site')
      admin_helper.validate_and_save_sitesettings(site_name, tagline, post_name, site_description)
    except exception.ValidationError:
      exception.handle_exception(request)

  c = template.RequestContext(request, locals())
  return render_to_response('administration/templates/site.html', c)
Beispiel #19
0
def admin_channel(request):
  page = 'channel'
  title = 'Channels Settings'

  enable_channels = util.get_metadata('ENABLE_CHANNELS')
  enable_channel_types = util.get_metadata('ENABLE_CHANNEL_TYPES')
  
  if request.POST:
    enable_channels = request.POST.get('enable_channels', False)
    enable_channel_types = request.POST.get('enable_channel_types', False)
    
    try:
      validate.nonce(request, 'admin_channel')
      validate.bool_checkbox(enable_channels)
      validate.bool_checkbox(enable_channel_types)

      util.set_metadata('ENABLE_CHANNELS', str(enable_channels), 0, {'type':'bool'})
      util.set_metadata('ENABLE_CHANNEL_TYPES', str(enable_channel_types), 0, {'type':'bool'})

    except exception.ValidationError:
      exception.handle_exception(request)
    
  c = template.RequestContext(request, locals())
  return render_to_response('administration/templates/channel.html', c)
Beispiel #20
0
def common_photo_upload(request, success="/", nick=None):
  if not nick:
    nick = request.user.nick
  if request.FILES:
    try:
      # we're going to handle a file upload, wee
      validate.nonce(request, 'change_photo')
      img = request.FILES.get('imgfile')

      if not img:
        raise exception.ValidationError('imgfile must be set')
      validate.avatar_photo_size(img)

      img_url = api.avatar_upload(request.user,
                                  nick,
                                  img.read())
      api.avatar_set_actor(request.user, nick, img_url)
      return util.RedirectFlash(success, "Avatar uploaded")
    except:
      exception.handle_exception(request)

  elif 'avatar' in request.POST:
    try:
      validate.nonce(request, 'change_photo')
      avatar_path = request.POST.get('avatar')
      if not avatar_path:
        raise exception.ValidationError('avatar must be set')

      rv = api.avatar_set_actor(request.user, nick, avatar_path)
      if not rv:
        raise exception.ValidationError('failed to set avatar')
      return util.RedirectFlash(success, "Avatar changed")
    except:
      exception.handle_exception(request)

  if 'delete' in request.REQUEST:
    try:
      validate.nonce(request, 'delete_photo')
      validate.confirm_dangerous(request, 'Delete your photo?')
      rv = api.avatar_clear_actor(request.user, nick)
      return util.RedirectFlash(success, "Avatar deleted")
    except:
      exception.handle_exception(request)
Beispiel #21
0
def common_photo_upload(request, success="/", nick=None):
    if not nick:
        nick = request.user.nick
    if request.FILES:
        try:
            # we're going to handle a file upload, wee
            validate.nonce(request, 'change_photo')
            img = request.FILES.get('imgfile')

            if not img:
                raise exception.ValidationError('imgfile must be set')
            validate.avatar_photo_size(img)

            img_url = api.avatar_upload(request.user, nick, img.read())
            api.avatar_set_actor(request.user, nick, img_url)
            return util.RedirectFlash(success, "Avatar uploaded")
        except:
            exception.handle_exception(request)

    elif 'avatar' in request.POST:
        try:
            validate.nonce(request, 'change_photo')
            avatar_path = request.POST.get('avatar')
            if not avatar_path:
                raise exception.ValidationError('avatar must be set')

            rv = api.avatar_set_actor(request.user, nick, avatar_path)
            if not rv:
                raise exception.ValidationError('failed to set avatar')
            return util.RedirectFlash(success, "Avatar changed")
        except:
            exception.handle_exception(request)

    if 'delete' in request.REQUEST:
        try:
            validate.nonce(request, 'delete_photo')
            validate.confirm_dangerous(request, 'Delete your photo?')
            rv = api.avatar_clear_actor(request.user, nick)
            return util.RedirectFlash(success, "Avatar deleted")
        except:
            exception.handle_exception(request)
Beispiel #22
0
 def _old_nonce():
     validate.nonce(
         test_util.FakeRequest(user=fake_user,
                               post={'_nonce': old_nonce}), action)
Beispiel #23
0
def join_welcome_contacts(request):

  """
  if we have an access token for this user attempt to fetch the contacts
  else if we have a request token attempt to get an access token
  if we have neither
    if we are trying to authorize, grab a request token and redirect to authorize page
    else
      show the page
  """
  redirect_to = request.REQUEST.get('redirect_to', '/')
  next = '/welcome/done'


  # these are for the find more contacts bits
  start_index = int(request.REQUEST.get('index', 1))
  max = 100
  token = request.REQUEST.get('token')
  contacts_more = int(request.REQUEST.get('contacts_more', 0))
  # this won't be seen unless contacts_more is positive,
  # so no worries about the possible negative value
  contacts_so_far = contacts_more - 1


  try:
    if not settings.GOOGLE_CONTACTS_IMPORT_ENABLED:
      raise exception.FeatureDisabledError('Google Contacts import is currently disabled')
    
    if 'lookup_remote_contacts' in request.POST:
      validate.nonce(request, 'lookup_remote_contacts')

      next_url = util.qsa(util.here(request), 
                          {'redirect_to': redirect_to,
                           'upgrade_auth_token': '',
                           '_nonce': util.create_nonce(request.user, 
                                                       'upgrade_auth_token'),
                           }
                          )
      auth_url = google_contacts.auth_sub_url(next_url)
      return http.HttpResponseRedirect(auth_url)
    elif 'actor_add_contacts' in request.POST:
      validate.nonce(request, 'actor_add_contacts')

  
      targets = request.POST.getlist('targets')
      owner = request.POST.get('owner', '')

      rv = api.actor_add_contacts(request.user, owner, targets)

      next_url = util.qsa(util.here(request),
                          {'redirect_to': redirect_to,
                           'contacts_more': contacts_more,
                           'index': start_index,
                           'token': token,
                           }
                          )

      return util.RedirectFlash(next_url, 'Contacts added.')
  
    elif 'upgrade_auth_token' in request.GET:
      validate.nonce(request, 'upgrade_auth_token')
      
      auth_token = google_contacts.auth_sub_token_from_request(request)
      session_token = google_contacts.upgrade_to_session_token(auth_token)
      
      next_url = util.qsa(util.here(request),
                          {'redirect_to': redirect_to,
                           'fetch_contacts': '',
                           'token': session_token.get_token_string(),
                           '_nonce': util.create_nonce(request.user, 
                                                       'fetch_contacts'),
                           }
                          )
      
      return http.HttpResponseRedirect(next_url)

    elif 'fetch_contacts' in request.REQUEST:
      validate.nonce(request, 'fetch_contacts')
      
      # start_index and max are gathered above
      session_token = google_contacts.auth_sub_token_from_request(request)
      
      # check for the "My Contacts" group, otherwise, fetch it
      my_contacts = memcache.client.get('%s/my_contacts' % token)
      if not my_contacts:
        my_contacts = google_contacts.get_system_group(session_token, 
                                                       'Contacts')
        memcache.client.set('%s/my_contacts' % token, my_contacts)


      rv, more = google_contacts.get_contacts_emails(session_token,
                                                     group=my_contacts,
                                                     index=start_index,
                                                     max=max)

      contacts = []

      for name, email in rv:
        logging.info('looking up "%s" %s', name, email)
        contacts.append(api.actor_lookup_email(request.user, email))

      contacts = [x for x in contacts if x]

      # for the template
      contacts_found = True
      contacts_more = more
      contacts_so_far = contacts_more - 1
      token = session_token.get_token_string()
      contacts_emails = rv

      # if no contacts were found and more are available, try some more
      if not contacts and contacts_more:
        next_url = util.qsa(util.here(request),
                            {'fetch_contacts': '',
                             'contacts_more': contacts_more,
                             'index': contacts_more,
                             'token': token,
                             '_nonce': util.create_nonce(request.user,
                                                         'fetch_contacts'),
                             'redirect_to': redirect_to,
                             }
                            )
        # TODO(termie): this can take a really long time, probably not really
        #               viable until we can do it with javascript
        #return util.MetaRefresh(next_url, message='Still working...', second=1)
        #return http.HttpResponseRedirect(next_url)

  except:
    exception.handle_exception(request)


  # set the progress
  welcome_photo = True
  welcome_mobile = True

  view = request.user
  page = 'contacts'

  area = 'welcome'
  c = template.RequestContext(request, locals())
  
  t = loader.get_template('join/templates/welcome_%s.html' % page)
  return http.HttpResponse(t.render(c))
Beispiel #24
0
 def _old_nonce():
   validate.nonce(test_util.FakeRequest(
                      user=fake_user,
                      post={'_nonce': old_nonce}),
                  action)
Beispiel #25
0
def actor_settings(request, nick, page="index"):
    """ just a static page that links to the rest"""
    nick = clean.nick(nick)

    view = api.actor_lookup_nick(api.ROOT, nick)
    if not api.actor_owns_actor(request.user, view):
        raise exception.ApiOwnerRequired(
            "Operation not allowed: %s does not own %s" % (request.user and request.user.nick or "(nobody)", view.nick)
        )

    handled = common_views.handle_view_action(
        request,
        {
            "activation_activate_mobile": view.url("/settings/mobile"),
            "activation_request_email": view.url("/settings/email"),
            "activation_request_mobile": view.url("/settings/mobile"),
            "settings_change_notify": view.url("/settings/notifications"),
            "settings_change_privacy": request.path,
            "settings_update_account": view.url("/settings/profile"),
            "actor_remove": "/logout",
            #'oauth_remove_consumer': request.path,
            #'oauth_remove_access_token': request.path
        },
    )
    if handled:
        return handled

    # TODO(tyler/termie):  This conflicts with the global settings import.
    # Also, this seems fishy.  Do none of the settings.* items work in templates?
    import settings

    # TODO(tyler): Merge this into handle_view_action, if possible
    if "password" in request.POST:
        try:
            validate.nonce(request, "change_password")

            password = request.POST.get("password", "")
            confirm = request.POST.get("confirm", "")

            validate.password_and_confirm(password, confirm, field="password")

            api.settings_change_password(request.user, view.nick, password)
            response = util.RedirectFlash(view.url() + "/settings/password", "Password updated")
            request.user.password = util.hash_password(request.user.nick, password)
            # TODO(mikie): change when cookie-auth is changed
            user.set_user_cookie(response, request.user)
            return response
        except:
            exception.handle_exception(request)

    if page == "feeds":
        try:
            if not settings.FEEDS_ENABLED:
                raise exception.DisabledFeatureError("Feeds are currently disabled")
        except:
            exception.handle_exception(request)

    if page == "photo":
        redirect_to = view.url() + "/settings/photo"
        handled = common_views.common_photo_upload(request, redirect_to)
        if handled:
            return handled

    area = "settings"
    full_page = page.capitalize()

    if page == "mobile":
        full_page = "Mobile Number"

        mobile = api.mobile_get_actor(request.user, view.nick)
        sms_notify = view.extra.get("sms_notify", False)

    elif page == "im":
        full_page = "IM Address"
        im_address = api.im_get_actor(request.user, view.nick)
        im_notify = view.extra.get("im_notify", False)
    elif page == "index":
        email = api.email_get_actor(request.user, view.nick)
        email_notify = view.extra.get("email_notify", False)
        im_address = api.im_get_actor(request.user, view.nick)
        im_notify = view.extra.get("im_notify", False)
    elif page == "feeds":
        full_page = "Web Feeds"
    elif page == "email":
        full_page = "Email Address"
        email_notify = view.extra.get("email_notify", False)

        # check if we already have an email
        email = api.email_get_actor(request.user, view.nick)

        # otherwise look for an unconfirmed one
        if not email:
            unconfirmeds = api.activation_get_actor_email(api.ROOT, view.nick)
            if unconfirmeds:
                unconfirmed_email = unconfirmeds[0].content

    elif page == "design":
        redirect_to = view.url() + "/settings/design"
        handled = common_views.common_design_update(request, redirect_to, view.nick)
        if handled:
            return handled
        full_page = "Look and Feel"

    elif page == "notifications":
        email = api.email_get_actor(request.user, view.nick)
        email_notify = view.extra.get("email_notify", False)
        im_address = api.im_get_actor(request.user, view.nick)
        im_notify = view.extra.get("im_notify", False)
        mobile = api.mobile_get_actor(request.user, request.user.nick)
        sms_notify = view.extra.get("sms_notify", False)

        sms_confirm = sms_notify and not view.extra.get("sms_confirmed", False)
        # TODO(termie): remove this once we can actually receive sms
        sms_confirm = False
    elif page == "profile":
        # check if we already have an email
        email = api.email_get_actor(request.user, view.nick)

        # otherwise look for an unconfirmed one
        if not email:
            unconfirmeds = api.activation_get_actor_email(api.ROOT, view.nick)
            if unconfirmeds:
                unconfirmed_email = unconfirmeds[0].content

    elif page == "photo":
        avatars = display.DEFAULT_AVATARS
        small_photos = api.image_get_all_keys(request.user, view.nick, size="f")

        # TODO(tyler): Fix this avatar nonsense!
        own_photos = [
            {"path": small_photo.key().name(), "name": small_photo.key().name()[len("images/") : -len("_f.jpg")]}
            for small_photo in small_photos
        ]

    elif page == "privacy":
        PRIVACY_PUBLIC = api.PRIVACY_PUBLIC
        PRIVACY_CONTACTS = api.PRIVACY_CONTACTS
    elif page == "jsbadge":
        full_page = "Javascript Badges"
    elif page == "badge":
        badges = [
            {
                "id": "badge-stream",
                "width": "200",
                "height": "300",
                "src": "/themes/%s/badge.swf" % settings.DEFAULT_THEME,
                "title": "Stream",
            },
            {
                "id": "badge-map",
                "width": "200",
                "height": "255",
                "src": "/themes/%s/badge-map.swf" % settings.DEFAULT_THEME,
                "title": "Map",
            },
            {
                "id": "badge-simple",
                "width": "200",
                "height": "200",
                "src": "/themes/%s/badge-simple.swf" % settings.DEFAULT_THEME,
                "title": "Simple",
            },
        ]

    elif page in ["password", "delete"]:
        # Catch for remaining pages before we generate a 404.
        pass

    else:
        return common_views.common_404(request)

    # rendering
    c = template.RequestContext(request, locals())
    t = loader.get_template("actor/templates/settings_%s.html" % page)
    return http.HttpResponse(t.render(c))
Beispiel #26
0
 def _notany_nonce():
   validate.nonce(test_util.FakeRequest(
                      user=None,
                      post={'_nonce': notany_nonce},
                  ),
                  action)
Beispiel #27
0
 def _madeup_nonce():
     validate.nonce(
         test_util.FakeRequest(user=fake_user, post={'_nonce': 'TEST'}),
         action)
Beispiel #28
0
 def _notme_nonce():
   validate.nonce(test_util.FakeRequest(
                      user='******',
                      post={'_nonce': notme_nonce}),
                  action)
Beispiel #29
0
 def _madeup_nonce():
   validate.nonce(test_util.FakeRequest(
                      user=fake_user,
                      post={'_nonce': 'TEST'}),
                  action)
Beispiel #30
0
 def _notme_nonce():
     validate.nonce(
         test_util.FakeRequest(user='******',
                               post={'_nonce': notme_nonce}), action)
Beispiel #31
0
 def _notany_nonce():
     validate.nonce(
         test_util.FakeRequest(
             user=None,
             post={'_nonce': notany_nonce},
         ), action)
Beispiel #32
0
def actor_settings(request, nick, page='index'):
  """ just a static page that links to the rest"""
  nick = clean.nick(nick)

  view = api.actor_lookup_nick(api.ROOT, nick)
  if not api.actor_owns_actor(request.user, view):
    raise exception.ApiOwnerRequired(
        'Operation not allowed: %s does not own %s'
        % (request.user and request.user.nick or '(nobody)', view.nick))

  handled = common_views.handle_view_action(
      request,
      {
        'activation_activate_mobile': view.url('/settings/mobile'),
        'activation_request_email': view.url('/settings/email'),
        'activation_request_mobile': view.url('/settings/mobile'),
        'settings_change_notify': view.url('/settings/notifications'),
        'settings_change_privacy': request.path,
        'settings_update_account': view.url('/settings/profile'),
        'actor_remove': '/logout',
        #'oauth_remove_consumer': request.path,
        #'oauth_remove_access_token': request.path
      }
  )
  if handled:
    return handled



  # TODO(tyler/termie):  This conflicts with the global settings import.
  # Also, this seems fishy.  Do none of the settings.* items work in templates?
  import settings

  # TODO(tyler): Merge this into handle_view_action, if possible
  if 'password' in request.POST:
    try:
      validate.nonce(request, 'change_password')

      password = request.POST.get('password', '')
      confirm = request.POST.get('confirm', '')

      validate.password_and_confirm(password, confirm, field = 'password')

      api.settings_change_password(request.user, view.nick, password)
      response = util.RedirectFlash(view.url() + '/settings/password',
                                    'Password updated')
      request.user.password = util.hash_password(request.user.nick, password)
      # TODO(mikie): change when cookie-auth is changed
      user.set_user_cookie(response, request.user)
      return response
    except:
      exception.handle_exception(request)

  if page == 'feeds':
    try:
      if not settings.FEEDS_ENABLED:
        raise exception.DisabledFeatureError('Feeds are currently disabled')
    except:
      exception.handle_exception(request)

  if page == 'photo':
    redirect_to = view.url() + '/settings/photo'
    handled = common_views.common_photo_upload(request, redirect_to)
    if handled:
      return handled


  area = 'settings'
  full_page = page.capitalize()

  if page == 'mobile':
    full_page = 'Mobile Number'

    mobile = api.mobile_get_actor(request.user, view.nick)
    sms_notify = view.extra.get('sms_notify', False)
    
  elif page == 'im':
    full_page = 'IM Address'
    im_address = api.im_get_actor(request.user, view.nick)
    im_notify = view.extra.get('im_notify', False)
  elif page == 'index':
    email = api.email_get_actor(request.user, view.nick)
    email_notify = view.extra.get('email_notify', False)
    im_address = api.im_get_actor(request.user, view.nick)
    im_notify = view.extra.get('im_notify', False)
  elif page == 'feeds':
    full_page = 'Web Feeds'
  elif page == 'email':
    full_page = 'Email Address'
    email_notify = view.extra.get('email_notify', False)

    # check if we already have an email
    email = api.email_get_actor(request.user, view.nick) 

    # otherwise look for an unconfirmed one
    if not email:
      unconfirmeds = api.activation_get_actor_email(api.ROOT, view.nick)
      if unconfirmeds:
        unconfirmed_email = unconfirmeds[0].content

  elif page == 'design':
    handled = common_views.common_design_update(request, view.nick)
    if handled:
      return handled
    full_page = 'Look and Feel'

  elif page == 'notifications':
    email = api.email_get_actor(request.user, view.nick)
    email_notify = view.extra.get('email_notify', False)
    im_address = api.im_get_actor(request.user, view.nick)
    im_notify = view.extra.get('im_notify', False)
    mobile = api.mobile_get_actor(request.user, request.user.nick)
    sms_notify = view.extra.get('sms_notify', False)

    sms_confirm = sms_notify and not view.extra.get('sms_confirmed', False)
    # TODO(termie): remove this once we can actually receive sms
    sms_confirm = False
  elif page == 'profile':
    # check if we already have an email
    email = api.email_get_actor(request.user, view.nick) 

    # otherwise look for an unconfirmed one
    if not email:
      unconfirmeds = api.activation_get_actor_email(api.ROOT, view.nick)
      if unconfirmeds:
        unconfirmed_email = unconfirmeds[0].content

  elif page == 'photo':
    avatars = display.DEFAULT_AVATARS
    small_photos = api.image_get_all_keys(request.user, view.nick, size='f')

    # TODO(tyler): Fix this avatar nonsense!
    own_photos = [{
        'path' : small_photo.key().name(),
        'name' : small_photo.key().name()[len('image/'):-len('_f.jpg')],
      } for small_photo in small_photos
    ]

  elif page == 'privacy':
    PRIVACY_PUBLIC = api.PRIVACY_PUBLIC
    PRIVACY_CONTACTS = api.PRIVACY_CONTACTS
  elif page == 'jsbadge':
    full_page = 'Javascript Badges'
  elif page == 'badge':
    badges = [{'id': 'badge-stream',
               'width': '200',
               'height': '300',
               'src': '/themes/%s/badge.swf' % settings.DEFAULT_THEME,
               'title': 'Stream',
               },
              {'id': 'badge-map',
               'width': '200',
               'height': '255',
               'src': '/themes/%s/badge-map.swf' % settings.DEFAULT_THEME,
               'title': 'Map',
               },
              {'id': 'badge-simple',
               'width': '200',
               'height': '200',
               'src': '/themes/%s/badge-simple.swf' % settings.DEFAULT_THEME,
               'title': 'Simple',
               },
              ]

  elif page in ['password', 'delete']:
    # Catch for remaining pages before we generate a 404.
    pass

  else:
    return common_views.common_404(request)

  # rendering
  c = template.RequestContext(request, locals())
  t = loader.get_template('actor/templates/settings_%s.html' % page)
  return http.HttpResponse(t.render(c))
Beispiel #33
0
def actor_settings(request, nick, page='index'):
    """ just a static page that links to the rest"""
    nick = clean.nick(nick)

    view = api.actor_lookup_nick(api.ROOT, nick)
    if not api.actor_owns_actor(request.user, view):
        raise exception.ApiOwnerRequired(
            'Operation not allowed: %s does not own %s' %
            (request.user and request.user.nick or '(nobody)', view.nick))

    handled = common_views.handle_view_action(
        request,
        {
            'activation_activate_mobile': view.url('/settings/mobile'),
            'activation_request_email': view.url('/settings/email'),
            'activation_request_mobile': view.url('/settings/mobile'),
            'settings_change_notify': view.url('/settings/notifications'),
            'settings_change_privacy': request.path,
            'settings_update_account': view.url('/settings/profile'),
            'actor_remove': '/logout',
            #'oauth_remove_consumer': request.path,
            #'oauth_remove_access_token': request.path
        })
    if handled:
        return handled

    # TODO(tyler/termie):  This conflicts with the global settings import.
    # Also, this seems fishy.  Do none of the settings.* items work in templates?
    import settings

    # TODO(tyler): Merge this into handle_view_action, if possible
    if 'password' in request.POST:
        try:
            validate.nonce(request, 'change_password')

            password = request.POST.get('password', '')
            confirm = request.POST.get('confirm', '')

            validate.password_and_confirm(password, confirm, field='password')

            api.settings_change_password(request.user, view.nick, password)
            response = util.RedirectFlash(view.url() + '/settings/password',
                                          'Password updated')
            request.user.password = util.hash_password(request.user.nick,
                                                       password)
            # TODO(mikie): change when cookie-auth is changed
            user.set_user_cookie(response, request.user)
            return response
        except:
            exception.handle_exception(request)

    if page == 'feeds':
        try:
            if not settings.FEEDS_ENABLED:
                raise exception.DisabledFeatureError(
                    'Feeds are currently disabled')
        except:
            exception.handle_exception(request)

    if page == 'photo':
        redirect_to = view.url() + '/settings/photo'
        handled = common_views.common_photo_upload(request, redirect_to)
        if handled:
            return handled

    area = 'settings'
    full_page = page.capitalize()

    if page == 'mobile':
        full_page = 'Mobile Number'

        mobile = api.mobile_get_actor(request.user, view.nick)
        sms_notify = view.extra.get('sms_notify', False)

    elif page == 'im':
        full_page = 'IM Address'
        im_address = api.im_get_actor(request.user, view.nick)
        im_notify = view.extra.get('im_notify', False)
    elif page == 'index':
        email = api.email_get_actor(request.user, view.nick)
        email_notify = view.extra.get('email_notify', False)
        im_address = api.im_get_actor(request.user, view.nick)
        im_notify = view.extra.get('im_notify', False)
    elif page == 'feeds':
        full_page = 'Web Feeds'
    elif page == 'email':
        full_page = 'Email Address'
        email_notify = view.extra.get('email_notify', False)

        # check if we already have an email
        email = api.email_get_actor(request.user, view.nick)

        # otherwise look for an unconfirmed one
        if not email:
            unconfirmeds = api.activation_get_actor_email(api.ROOT, view.nick)
            if unconfirmeds:
                unconfirmed_email = unconfirmeds[0].content

    elif page == 'design':
        handled = common_views.common_design_update(request, view.nick)
        if handled:
            return handled
        full_page = 'Look and Feel'

    elif page == 'notifications':
        email = api.email_get_actor(request.user, view.nick)
        email_notify = view.extra.get('email_notify', False)
        im_address = api.im_get_actor(request.user, view.nick)
        im_notify = view.extra.get('im_notify', False)
        mobile = api.mobile_get_actor(request.user, request.user.nick)
        sms_notify = view.extra.get('sms_notify', False)

        sms_confirm = sms_notify and not view.extra.get('sms_confirmed', False)
        # TODO(termie): remove this once we can actually receive sms
        sms_confirm = False
    elif page == 'profile':
        # check if we already have an email
        email = api.email_get_actor(request.user, view.nick)

        # otherwise look for an unconfirmed one
        if not email:
            unconfirmeds = api.activation_get_actor_email(api.ROOT, view.nick)
            if unconfirmeds:
                unconfirmed_email = unconfirmeds[0].content

    elif page == 'photo':
        avatars = display.DEFAULT_AVATARS
        small_photos = api.image_get_all_keys(request.user,
                                              view.nick,
                                              size='f')

        # TODO(tyler): Fix this avatar nonsense!
        own_photos = [{
            'path':
            small_photo.key().name(),
            'name':
            small_photo.key().name()[len('image/'):-len('_f.jpg')],
        } for small_photo in small_photos]

    elif page == 'privacy':
        PRIVACY_PUBLIC = api.PRIVACY_PUBLIC
        PRIVACY_CONTACTS = api.PRIVACY_CONTACTS
    elif page in ['password', 'delete']:
        # Catch for remaining pages before we generate a 404.
        pass

    else:
        return common_views.common_404(request)

    # rendering
    c = template.RequestContext(request, locals())
    t = loader.get_template('actor/templates/settings_%s.html' % page)
    return http.HttpResponse(t.render(c))
Beispiel #34
0
def join_welcome_contacts(request):
    """
  if we have an access token for this user attempt to fetch the contacts
  else if we have a request token attempt to get an access token
  if we have neither
    if we are trying to authorize, grab a request token and redirect to authorize page
    else
      show the page
  """
    redirect_to = get_clean_redirect(request)
    next = '/welcome/done'

    # these are for the find more contacts bits
    start_index = int(request.REQUEST.get('index', 1))
    max = 100
    token = request.REQUEST.get('token')
    contacts_more = int(request.REQUEST.get('contacts_more', 0))
    # this won't be seen unless contacts_more is positive,
    # so no worries about the possible negative value
    contacts_so_far = contacts_more - 1

    try:
        if not settings.GOOGLE_CONTACTS_IMPORT_ENABLED:
            raise exception.FeatureDisabledError(
                'Google Contacts import is currently disabled')

        if 'lookup_remote_contacts' in request.POST:
            validate.nonce(request, 'lookup_remote_contacts')

            next_url = util.qsa(
                util.here(request), {
                    'redirect_to':
                    redirect_to,
                    'upgrade_auth_token':
                    '',
                    '_nonce':
                    util.create_nonce(request.user, 'upgrade_auth_token'),
                })
            auth_url = google_contacts.auth_sub_url(next_url)
            return http.HttpResponseRedirect(auth_url)
        elif 'actor_add_contacts' in request.POST:
            validate.nonce(request, 'actor_add_contacts')

            targets = request.POST.getlist('targets')
            owner = request.POST.get('owner', '')

            rv = api.actor_add_contacts(request.user, owner, targets)

            next_url = util.qsa(
                util.here(request), {
                    'redirect_to': redirect_to,
                    'contacts_more': contacts_more,
                    'index': start_index,
                    'token': token,
                })

            return util.RedirectFlash(next_url, 'Contacts added.')

        elif 'upgrade_auth_token' in request.GET:
            validate.nonce(request, 'upgrade_auth_token')

            auth_token = google_contacts.auth_sub_token_from_request(request)
            session_token = google_contacts.upgrade_to_session_token(
                auth_token)

            next_url = util.qsa(
                util.here(request), {
                    'redirect_to': redirect_to,
                    'fetch_contacts': '',
                    'token': session_token.get_token_string(),
                    '_nonce': util.create_nonce(request.user,
                                                'fetch_contacts'),
                })

            return http.HttpResponseRedirect(next_url)

        elif 'fetch_contacts' in request.REQUEST:
            validate.nonce(request, 'fetch_contacts')

            # start_index and max are gathered above
            session_token = google_contacts.auth_sub_token_from_request(
                request)

            # check for the "My Contacts" group, otherwise, fetch it
            my_contacts = memcache.client.get('%s/my_contacts' % token)
            if not my_contacts:
                my_contacts = google_contacts.get_system_group(
                    session_token, 'Contacts')
                memcache.client.set('%s/my_contacts' % token, my_contacts)

            rv, more = google_contacts.get_contacts_emails(session_token,
                                                           group=my_contacts,
                                                           index=start_index,
                                                           max=max)

            contacts = []

            for name, email in rv:
                logging.info('looking up "%s" %s', name, email)
                contacts.append(api.actor_lookup_email(request.user, email))

            contacts = [x for x in contacts if x]

            # for the template
            contacts_found = True
            contacts_more = more
            contacts_so_far = contacts_more - 1
            token = session_token.get_token_string()
            contacts_emails = rv

            # if no contacts were found and more are available, try some more
            if not contacts and contacts_more:
                next_url = util.qsa(
                    util.here(request), {
                        'fetch_contacts': '',
                        'contacts_more': contacts_more,
                        'index': contacts_more,
                        'token': token,
                        '_nonce': util.create_nonce(request.user,
                                                    'fetch_contacts'),
                        'redirect_to': redirect_to,
                    })
                # TODO(termie): this can take a really long time, probably not really
                #               viable until we can do it with javascript
                #return util.MetaRefresh(next_url, message='Still working...', second=1)
                #return http.HttpResponseRedirect(next_url)

    except:
        exception.handle_exception(request)

    # set the progress
    welcome_photo = True
    welcome_mobile = True

    view = request.user
    page = 'contacts'

    area = 'welcome'
    c = template.RequestContext(request, locals())

    t = loader.get_template('join/templates/welcome_%s.html' % page)
    return http.HttpResponse(t.render(c))