Beispiel #1
0
def display_topic(request, topic):
    """ Display the contents of the given topic.

        'topic' is a dictionary representation of the topic to be displayed, as
        returned by a call to core.api.topics.get().

        We return an HttpResponse object containing the web page to display for
        the given topic.
    """
    eventRecorder.record_event(eventRecorder.EVENT_TYPE_VIEW_TOPIC)

    user = User.objects.get(id=topic['user_id'])

    if topic['hide_username']:
        username = "******" + topic['hidden_url']
    else:
        username = user.username

    if topic.get("name") not in ["", None]:
        topic_name = username + "/" + topic['name']
    else:
        topic_name = username

    topics = Topic.objects.filter(user_id=topic['user_id'])

    if request.is_secure():
        baseURL = "https://" + request.get_host()
    else:
        baseURL = "http://" + request.get_host()

    return render_to_response('topic.html',
                              {'topic'   : topic,
                               'user'    : user,
                               'baseURL' : baseURL},
                              context_instance=RequestContext(request))
Beispiel #2
0
def taken_mobile():
    """ Mark a conversation as having been taken mobile.
    """
    raise UnauthorizedException() # Disable for now.

    eventRecorder.record_event(eventRecorder.
                                  EVENT_TYPE_TAKE_CONVERSATION_MOBILE)
Beispiel #3
0
def start_conversation(user_1_id, user_2_id, topic_id, sender_name=None):
    """ Start a conversation between the given two users about the given topic.

        The parameters are as follows:

            'user_1_id'
            'user_2_id'

                The record ID of the two users participating in the new
                conversation.

            'topic_id'
            
                The record ID of the topic this conversation will be about.

            'sender_name'

                The optional name for the sender of this message.

        We create and return a new Conversation object based on the given
        parameters.  Note that we also send an "introduction" SMS message to
        the owner of the topic, telling them that the conversation has started.
    """
    # Create the new conversation.

    conversation = Conversation()
    conversation.user_1_id = user_1_id
    conversation.user_2_id = user_2_id
    conversation.stopped   = False
    conversation.topic_id  = topic_id
    conversation.save()

    # Send the owner of the topic an "intro" SMS.

#    topic = conversation.topic
#    owner = topic.user
#    if owner.verified:
#        if sender_name in ["", None]:
#            sender_name = "Anonymous"
#
#        if topic.name in ["", None]:
#            msg = settings.SMS_TEXT_NEW_CONVERSATION_ABOUT_DEFAULT_TOPIC \
#                % sender_name
#        else:
#            msg = settings.SMS_TEXT_NEW_CONVERSATION_ABOUT_NAMED_TOPIC \
#                % (sender_name, topic.name)
#
#        _send_sms(conversation, owner, msg)

    # Tell our event recorder that a conversation has been started, so we can
    # report on it.

    eventRecorder.record_event(eventRecorder.EVENT_TYPE_START_CONVERSATION)

    # Finally, return the conversation back to the caller.

    return conversation
Beispiel #4
0
def welcome(request):
    """ Respond to the "/" URL.

        We display the welcome page for the application, or redirect the user to
        to /web/home if they are logged in.
    """
    return render(request, "disabled.html")

    if webHelpers.is_logged_in(request):
        return redirect("/web/home/")

    if request.is_secure():
        base_url = "https://" + request.get_host()
    else:
        base_url = "http://" + request.get_host()

    eventRecorder.record_event(eventRecorder.EVENT_TYPE_HOME_PAGE_HIT)

    return render(request, "welcome.html",
                  {"hideBrand"      : True,
                   "base_url"       : base_url,
                   "help_div_class" : "messageme-international-help " +
                                      "modal mm-hidden well"})
Beispiel #5
0
def update(session, username=None, password=None, phone_number=None):
    """ Update the details of the currently logged-in user.
    """
    raise UnauthorizedException() # Disable for now.

    logger.debug("in core.api.users.update(" +
                 "session=%s, username=%s, password=%s, phone_number=%s)" %
                 (repr(session), repr(username), repr(password),
                  repr(phone_number)))

    if session == None:
        raise InvalidParametersException()

    sessionHandler.validate(session)
    user = sessionHandler.get_user(session)

    # Remember if the user had a username or password.

    if user.username not in ["", None]:
        had_username = True
    else:
        had_username = False

    if user.password_salt not in ["", None]:
        had_password = True
    else:
        had_password = False

    # If we're setting a username and password for this user, and we didn't
    # have one previously, create a 3taps Identity for this user.  Note that
    # this may fail, if the username is already in use.

    if not had_username and username != None:
        if password == None: raise InvalidParametersException()
        _check_username(username)
        _check_password(password)

        # Try creating this user within the 3taps Identity API.

        success,response = identity_api.create(username, password)
        if not success:
            if response.startswith("403 error"):
                raise DuplicateUsernameException()
            else:
                raise InvalidParametersException()

        # Check that we don't have a local user with that username.

        try:
            existing_user = User.objects.get(username__iexact=username)
        except User.DoesNotExist:
            existing_user = None

        if existing_user != None:
            raise DuplicateUsernameException()

        # Finally, save the updated user details into our database.

        salt = response['server_salt']
        hash = hashlib.md5(password + salt).hexdigest()

        user.uses_identity_api = True
        user.username          = username
        user.identity_api_salt = salt
        user.identity_api_hash = hash
        user.save()

    # If we're changing the username for this user, ask the 3taps Identity API
    # to change the username.  Note that this may fail, if the new username is
    # already in use.

    if had_username and username != None and username != user.username:
        success,response = identity_api.login(user.username,
                                              pass_hash=user.identity_api_hash)
        if not success:
            raise UnauthorizedException()

        session = response

        success,response = identity_api.update(session,
                                               {'username' : username})
        if not success:
            if response.startswith("403 error"):
                raise DuplicateUsernameException()
            else:
                raise InvalidParametersException()

        identity_api.logout(session)

        # Check that we don't have a local user with that username.

        try:
            existing_user = User.objects.get(username__iexact=username)
        except User.DoesNotExist:
            existing_user = None

        if existing_user != None:
            raise DuplicateUsernameException()

        # Finally, save the updated user details into our database.

        user.username = username
        user.save()

    # If we're changing the password for this user, ask the 3taps Identity API
    # to change the password.

    if password != None:
        if user.username in ["", None]:
            # We can't change the password if we don't have a username.
            raise InvalidParametersException()

        if user.uses_identity_api:
            success,response = \
                    identity_api.login(user.username,
                                       pass_hash=user.identity_api_hash)
        else:
            success,response = \
                    identity_api.login(user.username,
                                       password="******")

        if not success:
            raise UnauthorizedException()

        session = response

        success,response = identity_api.update(session,
                                               {'username' : username})
        if not success:
            if response.startswith("403 error"):
                raise DuplicateUsernameException()
            else:
                raise InvalidParametersException()

        identity_api.logout(session)

        salt = response['server_salt']
        hash = hashlib.md5(password + salt).hexdigest()

        user.uses_identity_api = True
        user.identity_api_salt = salt
        user.identity_api_hash = hash
        user.save()

    # If we've been asked to update the user's phone number, do so.

    # NOTE: someone was using this to hack our system, so I've disabled it.

    if False: # phone_number != None:
        if phone_number == "":
            user.phone_number = None # Remove current phone number.
        else:
            phone_number = utils.format_phone_number(phone_number)

            try:
                existing_user = User.objects.get(phone_number=phone_number)
            except User.DoesNotExist:
                existing_user = None

            if existing_user != None and user.id != existing_user.id:
                raise DuplicatePhoneNumberException()

        user.phone_number = phone_number

    # If this was an ad hoc user who we're now making permanent, change their
    # "ad hoc" status, and create a new default topic for the user.

    if user.ad_hoc and (username != None or password != None or
                        phone_number != None):
        user.ad_hoc = False
        _create_default_topic(user)

    # If we have been given a username and password for this user, record them
    # as signing up.

    if not had_username and not had_password:
        if username not in ["", None] and password not in ["", None]:
            eventRecorder.record_event(eventRecorder.EVENT_TYPE_NEW_USER_SIGNUP)

    # Finally, save the updated user and return a copy of it back to the
    # caller.

    user.updated_at = datetime.datetime.utcnow()
    user.save()

    return user.to_dict()
Beispiel #6
0
def create(username=None, password=None, phone_number=None):
    """ Create a new User within the system.
    """
    raise UnauthorizedException() # Disable for now.

    logger.debug("in core.api.users.create(" +
                 "username=%s, password=%s, phone_number=%s)" %
                 (repr(username), repr(password), repr(phone_number)))

    if username     == "": username     = None
    if password     == "": password     = None
    if phone_number == "": phone_number = None

    if username == None and password == None and phone_number == None:
        ad_hoc = True
    else:
        ad_hoc = False

    if username != None: _check_username(username)
    if password != None: _check_password(password)

    if username != None or password != None:
        if username == None or password == None:
            # username and password must both be set at the same time.
            raise InvalidParametersException()

    if phone_number != None:
        phone_number = utils.format_phone_number(phone_number)

        try:
            existing_user = User.objects.get(phone_number=phone_number)
        except User.DoesNotExist:
            existing_user = None

        if existing_user != None:
            raise DuplicatePhoneNumberException()

    if username != None:
        # The user is attempting to create a new user with a username and
        # password.  Try to create the 3taps identity for this new user, and
        # raise a DuplicateUsernameException if the user already exists.
        success,response = identity_api.create(username, password)
        if not success:
            if response.startswith("403 error"):
                raise DuplicateUsernameException()
            else:
                raise InvalidParametersException()

    user = User()

    user.ad_hoc   = ad_hoc
    user.username = username

    if username != None:
        salt = response['server_salt']
        hash = hashlib.md5(password + salt).hexdigest()

        user.uses_identity_api = True
        user.identity_api_salt = salt
        user.identity_api_hash = hash
    else:
        user.uses_identity_api = False
        user.identity_api_hash = None
        user.identity_api_salt = None

    user.phone_number      = phone_number
    user.verification_code = None
    user.verified          = False
    user.created_at        = datetime.datetime.utcnow()
    user.updated_at        = datetime.datetime.utcnow()
    user.save()

    # If the new user has a username and password, record it as a new user
    # signup.

    if username != None and password != None:
        eventRecorder.record_event(eventRecorder.EVENT_TYPE_NEW_USER_SIGNUP)

    # While we're at it, create a default topic for the new user if they're not
    # an ad hoc user.

    if not ad_hoc:
        _create_default_topic(user)

    # Finally, return the new user's details to the caller.

    return user.to_dict()
Beispiel #7
0
def login(user_id=None,
          username=None, password=None,
          phone_number=None, verification_code=None):
    """ Log a user in, creating a new login session.
    """
    raise UnauthorizedException() # Disable for now.

    logger.debug("in core.api.users.login(" +
                 "user_id=%s, username=%s, password=%s, phone=%s, code=%s)" %
                 (repr(user_id), repr(username), repr(password),
                  repr(phone_number), repr(verification_code)))

    if user_id != None:
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            raise NoSuchUserException()
        if not user.ad_hoc:
            raise UnauthorizedException()
    elif username != None and password != None:
        # Log in using a username and password.  Note that we have to use the
        # 3taps identity API for this.

        try:
            user = User.objects.get(username__iexact=username)
        except User.DoesNotExist:
            # We don't know about this user, but that doesn't mean the user
            # doesn't exist.  It could be that the user already has an identity
            # within the 3taps Identity API, but hasn't used MessageMe before.

            # See if the user exists in the identity API.

            success,response = identity_api.login(username=username,
                                                  password=password)
            if success:
                identity_api.logout(response)

                # Create a MessageMe record for this user.

                salt = response['server_salt']
                hash = hashlib.md5(password + salt).hexdigest()

                user = User()
                user.username          = username
                user.uses_identity_api = True
                user.identity_api_salt = salt
                user.identity_api_hash = hash
                user.phone_number      = phone_number
                user.verification_code = None
                user.verified          = False
                user.created_at        = datetime.datetime.utcnow()
                user.updated_at        = datetime.datetime.utcnow()
                user.save()

                eventRecorder.record_event(
                    eventRecorder.EVENT_TYPE_NEW_USER_SIGNUP)
                _create_default_topic(user)
            else:
                # We don't know about this user, and the 3taps Identity API
                # doesn't either -> give up.
                raise LoginRejectedException()

        if user.uses_identity_api:
            # Ask the 3taps Identity API to validate the supplied username and
            # password.
            salt = user.identity_api_salt
            hash = hashlib.md5(password + salt).hexdigest()

            success,response = identity_api.login(username=username,
                                                  pass_hash=hash)
            if success:
                identity_api.logout(response)

                # Update the password hash, just in case the user changed their
                # password.

                salt = response['server_salt']
                hash = hashlib.md5(password + salt).hexdigest()

                user.identity_api_salt = salt
                user.identity_api_hash = hash
                user.save()
            else:
                raise LoginRejectedException()
        else:
            # We haven't yet migrated this user over to the identity API.  We
            # first check the password against the old password hash to see if
            # it matches our private user details.

            hash = bcrypt.hashpw(password, user.password_salt)
            if hash == user.password_hash:
                # We know the user entered the correct password.  Try logging
                # in with the "mm_temp" password, and if this works update the
                # user's details to use the supplied (real) password.
                success,response = identity_api.login(username=user.username,
                                                      password="******")
                if success:
                    session = response
                    ignore = identity_api.update(session,
                                                 {'password' : password})
                    identity_api.logout(session)

                    salt = response['server_salt']
                    hash = hashlib.md5(password + salt).hexdigest()

                    user.uses_identity_api = True
                    user.identity_api_salt = salt
                    user.identity_api_hash = hash
                    user.save()
                else:
                    # The user may have updated their password using another
                    # client of the 3taps Identity API.  Try logging in using
                    # the supplied password.
                    success,response = \
                            identity_api.login(username=user.username,
                                               password=password)
                    if success:
                        session = response
                        identity_api.logout(session)

                        salt = response['server_salt']
                        hash = hashlib.md5(password + salt).hexdigest()

                        user.uses_identity_api = True
                        user.identity_api_salt = salt
                        user.identity_api_hash = hash
                        user.save()
                    else:
                        # We can't log in -> give up.
                        raise LoginRejectedException()
            else:
                # The supplied password doesn't match our local records.  All
                # we can do is hope the password is accepted by the 3taps
                # Identity API, and if so accept the login.
                success,response = identity_api.login(username=user.username,
                                                      password=password)
                if success:
                    session = response
                    identity_api.logout(session)

                    salt = response['server_salt']
                    hash = hashlib.md5(password + salt).hexdigest()

                    user.uses_identity_api = True
                    user.identity_api_salt = salt
                    user.identity_api_hash = hash
                    user.save()
                else:
                    # We can't log in -> give up.
                    raise LoginRejectedException()
    elif phone_number != None and verification_code != None:
        phone_number = utils.format_phone_number(phone_number)
        try:
            user = User.objects.get(phone_number=phone_number,
                                    verification_code=verification_code)
        except User.DoesNotExist:
            raise LoginRejectedException()
        user.verified = True
        user.save()
    elif (user_id == None and username == None and password == None and
          phone_number == None and verification_code == None):
        # Create a new ad hoc user on-the-fly for this session.
        user = User()
        user.ad_hoc            = True
        user.username          = None
        user.password_salt     = None
        user.password_hash     = None
        user.phone_number      = None
        user.verification_code = None
        user.verified          = False
        user.created_at        = datetime.datetime.utcnow()
        user.updated_at        = datetime.datetime.utcnow()
        user.save()
    else:
        raise InvalidParametersException()

    return sessionHandler.create(user)