Пример #1
0
def login():
    #for test use
    if request.method == 'GET':
        return render_template('login.html')
    else:
        user = User.query.filter(User.name == request.form['name']).first()
        auth_login(user)
        return redirect('/')
Пример #2
0
def login(request, template_name='registration/login.html',
          redirect_if_logged_in=None,
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm):
    """Displays the login form and handles the login action."""

    if request.user.is_authenticated() and redirect_if_logged_in:
        return HttpResponseRedirect(reverse(redirect_if_logged_in))

    redirect_to = request.REQUEST.get(redirect_field_name, '')
    
    if request.method == "POST":
        form = authentication_form(data=request.POST)
        if form.is_valid():
            # Light security check -- make sure redirect_to isn't garbage.
            if not redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            
            # Heavier security check -- redirects to http://example.com should 
            # not be allowed, but things like /view/?param=http://example.com 
            # should be allowed. This regex checks if there is a '//' *before* a
            # question mark.
            elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
                    redirect_to = settings.LOGIN_REDIRECT_URL

            # Okay, security checks complete. Log the user in.
            auth_login(request, form.get_user())

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

            return HttpResponseRedirect(redirect_to)

    else:
        form = authentication_form(request)
    
    request.session.set_test_cookie()
    
    if Site._meta.installed:
        current_site = Site.objects.get_current()
    else:
        current_site = RequestSite(request)
    
    return render_to_response(template_name, {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }, context_instance=RequestContext(request))
Пример #3
0
def login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.REQUEST.get(redirect_field_name, '')

    if request.method == "POST":
        form = authentication_form(data=request.POST)
        if form.is_valid():
            netloc = urlparse.urlparse(redirect_to)[1]

            # Use default setting if redirect_to is empty
            if not redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Heavier security check -- don't allow redirection to a different
            # host.
            elif netloc and netloc != request.get_host():
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Okay, security checks complete. Log the user in.
            auth_login(request, form.get_user())
            translation.activate(form.get_user().member.language)
            request.session['django_language'] = form.get_user().member.language
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

            return HttpResponseRedirect(redirect_to)
    else:
        form = authentication_form(request)

    request.session.set_test_cookie()

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
        'navbar':'login',
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context,
                            current_app=current_app)
Пример #4
0
def login_by_renren():
    verification_code = request.args.get("code")
    args = dict(client_id=RENREN_APP_API_KEY, redirect_uri='http://www.oxxooox.com:5000/loginbyrenren')   
    error = request.args.get("error")
    if error:
        args["error"] = error
        args["error_description"] = request.args.get("error_description")
        args["error_uri"] = request.args.get("error_uri")

        args = dict(error=args)
        return args["error_description"]
    elif verification_code:
        args["client_secret"] = RENREN_APP_SECRET_KEY
        args["code"] = verification_code
        args["grant_type"] = "authorization_code"
        response = urllib.urlopen(RENREN_ACCESS_TOKEN_URI + "?" + urllib.urlencode(args)).read()
        access_token = parse_json(response)["access_token"]        
        '''Obtain session key from the Resource Service.'''
        session_key_request_args = {"oauth_token": access_token}
        response = urllib.urlopen(RENREN_SESSION_KEY_URI + "?" + urllib.urlencode(session_key_request_args)).read()
        session_key = str(parse_json(response)["renren_token"]["session_key"])
        
        '''Requesting the Renren API Server obtain the user's base info.'''
        params = {"method": "users.getInfo", "fields": "name,tinyurl"}
        api_client = RenRenAPIClient(session_key, RENREN_APP_API_KEY, RENREN_APP_SECRET_KEY)
        response = api_client.request(params);
        if type(response) is list:
            response = response[0]
        user_id = response["uid"]
        name = response["name"]
        avatar = response["tinyurl"]

        renren_user = RenrenUser.query.filter(RenrenUser.renren_id == user_id).first()
        if renren_user is None:
            renren_user = RenrenUser(name, avatar, user_id)
            renren_user.save()
        elif renren_user.portrait != avatar:
            renren_user.portrait = avatar
            renren_user.save()
        auth_login(renren_user)

        return redirect("/")
    else:
        args["response_type"] = "code"
        args["scope"] = "publish_feed email status_update"
        return redirect(
            RENREN_AUTHORIZATION_URI + "?" +
            urllib.urlencode(args))
Пример #5
0
def http_auth_login():
    '''
    Wrapper function for auth_login (logs a user in)
    POST: JSON containing "email" (str) and "password" (str)
    Returns JSON containing "u_id" (int) and "token" (str)
    '''
    payload = request.get_json()
    return dumps(auth_login(payload['email'], payload['password']))
Пример #6
0
def login():
    data = request.get_json()
    email = data["email"]
    password = data['password']
    login_user = auth_login(email, password)
    u_id = int(login_user['u_id'])
    token = str(login_user['token'])
    return dumps({'u_id': u_id, 'token': token})
Пример #7
0
def login_user_http():
    """Logs in user"""
    if request.is_json:
        req_data = request.get_json()
        response = auth_login(req_data["email"], \
        req_data["password"])
        return json.dumps(response), 200
    return "JSON not received", 400
Пример #8
0
def test_wrong_password():
    """
    Test login function to throw an error when the wrong password is entered.
    """
    registered_email = "*****@*****.**"
    wrong_password = "******"
    with pytest.raises(InputError):
        assert auth_login(registered_email, wrong_password)
Пример #9
0
def test_invalid_name_last_short():
    reset()
    person1 = auth.auth_register('*****@*****.**', 'abc123', 'Hayden',
                                 'Jacobs')
    login_person1 = auth.auth_login('*****@*****.**', 'abc123')
    person1_token = login_person1['token']
    with pytest.raises(InputError) as e:
        assert user.user_profile_setname(person1_token, 'Python', '')
Пример #10
0
def login():
    """
    Logs user in using http
    """
    data = request.get_json()
    email = data["email"]
    password = data["password"]
    return auth.auth_login(email, password)
Пример #11
0
def test_already_logged_in():
    dict = auth.auth_register("*****@*****.**", "123456", "Sinha", "Nawa")
    token = dict["token"]
    u_id = dict["u_id"]
    assert auth.auth_login("*****@*****.**", "123456") == {
        'u_id': 1,
        'token': '12345',
    }
Пример #12
0
def test_channel_addowner():
    '''
        #valid test
        #register user1, user2, user3, user4 and user5
        #user2 create a channel
        #user2 invites user1, user3, user4 and user5
        #user2 adds user3 as new owner (original owner)
        #user1 adds user4 as new owner (the owner of flockr)
        #user3 adds user5 as new owner (new added owner)
    '''
    clear()
    u1_id = auth.auth_register('*****@*****.**', 'password', 'user1_name',
                               'user1_name')['u_id']
    token_1 = auth.auth_login('*****@*****.**', 'password')['token']
    u2_id = auth.auth_register('*****@*****.**', 'password', 'user2_name',
                               'user2_name')['u_id']
    token_2 = auth.auth_login('*****@*****.**', 'password')['token']
    u3_id = auth.auth_register('*****@*****.**', 'password', 'user3_name',
                               'user3_name')['u_id']
    token_3 = auth.auth_login('*****@*****.**', 'password')['token']
    u4_id = auth.auth_register('*****@*****.**', 'password', 'user4_name',
                               'user4_name')['u_id']
    u5_id = auth.auth_register('*****@*****.**', 'password', 'user5_name',
                               'user5_name')['u_id']

    # create channel and invites users
    channel_id = channels_create(token_2, 'channel_name', True)['channel_id']
    channel.channel_invite(token_2, channel_id, u1_id)
    channel.channel_invite(token_2, channel_id, u3_id)
    channel.channel_invite(token_2, channel_id, u4_id)
    channel.channel_invite(token_2, channel_id, u5_id)

    assert u1_id not in channels[0]['owner_members']
    assert u2_id in channels[0]['owner_members']
    assert u3_id not in channels[0]['owner_members']
    assert u4_id not in channels[0]['owner_members']
    assert u5_id not in channels[0]['owner_members']

    # do add owner
    channel.channel_addowner(token_2, channel_id, u3_id)
    channel.channel_addowner(token_1, channel_id, u4_id)
    channel.channel_addowner(token_3, channel_id, u5_id)
    assert u3_id in channels[0]['owner_members']
    assert u4_id in channels[0]['owner_members']
    assert u5_id in channels[0]['owner_members']
Пример #13
0
def auth_login():
    '''
    Route that will login a user
    '''
    payload = request.get_json()
    email = payload['email']
    password = payload['password']
    dump = auth.auth_login(email, password)
    return dumps(dump)
Пример #14
0
def api_login(request):
    if request.method == "POST" :
        form = AuthenticationForm(data=request.POST)
    else:
        return api_error(request, '407')

    if form.is_valid():
        auth_login(request, form.get_user())
        info = {}
        email = request.user.username
        info['email'] = email
        info['feedback'] = settings.DEFAULT_FROM_EMAIL
        info['sessionid'] = request.session.session_key
        info['usage'] = seafserv_threaded_rpc.get_user_quota_usage(email)
        info['total'] = seafserv_threaded_rpc.get_user_quota(email)
        return HttpResponse(json.dumps([info]), status=200, content_type=json_content_type)
    else:
        return api_error(request, '408')
Пример #15
0
def test_user_profile_sethandle():
    reset()
    person1 = auth.auth_register('*****@*****.**', 'abc123', 'Hayden',
                                 'Jacobs')
    login_person1 = auth.auth_login('*****@*****.**', 'abc123')
    person1_u_id = login_person1['u_id']
    person1_token = login_person1['token']
    assert user.user_profile_sethandle(person1_token, handle_str) == {
    }  #, "user_profile_sethandle fail"
Пример #16
0
def auth_login():
    """
    Function auth_login route
    """
    login_details = request.get_json()

    user_infor = auth.auth_login(login_details['email'],
                                 login_details['password'])
    return dumps(user_infor)
Пример #17
0
def test_login():
    workspace_reset()

    user = auth_register('*****@*****.**', 'great_password101', 'Max',
                         'Smith')
    auth_logout(user['token'])
    user_logging_in = auth_login('*****@*****.**', 'great_password101')

    assert user['u_id'] == user_logging_in['u_id']
Пример #18
0
def test_invalid_channel2():
    results = auth_register("*****@*****.**", '123!Asdf', 'John', 'Smith')
    results = auth_login('*****@*****.**', '123!Asdf')
    u_id1 = results['u_id']
    token1 = results['token']

    results2 = auth_register('*****@*****.**', 'zxc123asd', 'Bob',
                             'Builder')
    results2 = auth_login('*****@*****.**', 'zxc123asd')
    u_id2 = results2['u_id']
    token2 = results2['token']

    channel_info3 = channels_create(token1, 'Slakrs', True)
    channel_addowner(token1, channel_info3, u_id2)
    invalidChannelID = 1

    with pytest.raises(InputError):
        channel_removeowner(token2, invalidChannelID, u_id1)
Пример #19
0
def login(request,
          template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None,
          extra_context=None):
    """
    Displays the login form and handles the login action.
    """
    redirect_to = request.REQUEST.get(redirect_field_name, '')

    if request.method == "POST":
        form = authentication_form(data=request.POST)
        if form.is_valid():
            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = settings.LOGIN_REDIRECT_URL

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

            return HttpResponseRedirect(redirect_to)
    else:
        form = authentication_form(request)

    request.session.set_test_cookie()

    current_site = get_current_site(request)

    context = {
        'form': form,
        redirect_field_name: redirect_to,
        'site': current_site,
        'site_name': current_site.name,
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request,
                            template_name,
                            context,
                            current_app=current_app)
Пример #20
0
def test_invalid_used_handle():
    reset()
    person1 = auth.auth_register('*****@*****.**', 'abc123', 'Hayden',
                                 'Jacobs')
    person2 = auth.auth_register('*****@*****.**', 'abc1234', 'Marry',
                                 'Jacobs')
    login_person1 = auth.auth_login('*****@*****.**', 'abc123')
    person1_token = login_person1['token']
    with pytest.raises(InputError) as e:
        assert user.user_profile_sethandle(person1_token, 'marryjacobs')
Пример #21
0
def auth_login():
    input_data = request.get_json()
    login_data(input_data)
    email = input_data['email']
    password = input_data['password']
    returned_data = auth.auth_login(email, password)
    return dumps({
        'u_id': returned_data['u_id'],
        'token': returned_data['token'],
    })
Пример #22
0
def test_non_user_email():
    """
    Test login function to throw an error for a non-user email.
    """
    # No user is attached to the email
    # (Assumme currently no one is)
    no_user_email = "*****@*****.**"
    password = "******"
    with pytest.raises(InputError):
        assert auth_login(no_user_email, password)
Пример #23
0
def connect():
    '''
    A route to login a user
    '''
    payload = request.get_json()
    if not payload['email'] or not payload['password']:
        raise RequestError(description="Missing data in request body")

    login_info = auth_login(payload['email'], payload['password'])
    return dumps(login_info)
Пример #24
0
def test_invalid_email():
    reset()
    person1 = auth.auth_register('*****@*****.**', 'abc123', 'Hayden',
                                 'Jacobs')
    login_person1 = auth.auth_login('*****@*****.**', 'abc123')
    person1_token = login_person1['token']
    #if check('123.com') != "Valid Email":
    #      raise Exception(error.InputError)
    with pytest.raises(InputError) as e:
        assert user.user_profile_setemail(person1_token, '123.com')
Пример #25
0
def test_login():
    """
    Test if the logout function works as intended with valid input.
    """
    # Use registered account information to login
    registered_email = "*****@*****.**"
    registered_password = "******"
    return_dict = auth_login(registered_email, registered_password)
    return_type = type(return_dict)
    assert return_type == dict
Пример #26
0
def login():
    '''Given a registered users' email and password,
    generates a valid token for the user to remain authenticated'''
    payload = request.get_json()
    email = payload['email']
    password = payload['password']
    if email is None or password is None:
        raise InputError(description='Empty email/password')
    res = auth_login(email, password)
    return dumps(res)
Пример #27
0
def test_logout_success():
    '''
    Continuing on the last login details
    '''
    user_logging_in = auth_login('*****@*****.**', 'great_password101')

    user_token = user_logging_in['token']
    message = auth_logout(user_token)

    assert message['is_success'] == True
Пример #28
0
def test_correct_password():
    dict = auth.auth_register("*****@*****.**", "123456", "Sinha", "Nawa")
    token = dict["token"]
    u_id = dict["u_id"]
    auth.auth_logout(token)

    assert auth.auth_login("*****@*****.**", "123456") == {
        'u_id': 1,
        'token': '12345',
    }
Пример #29
0
def test_auth_login_valid():
    result = False
    # Now we log him in
    token_holder = auth_login('*****@*****.**', 'worthwile')
    storage = get_user_store()
    for users in storage['users']:
        if users['token'] == token_holder['token']:
            result = True

    assert (result)
Пример #30
0
def test_details_accesserror_not_authorised_member():
    '''
        #invalid test of the authorised user is not a member of channel
        #register user1 and user2
        #user1 create a channel1
        #user2 requests channel_details of channel1
    '''
    clear()
    auth.auth_register('*****@*****.**', 'password', 'user1_name',
                       'user1_name')
    token_1 = auth.auth_login('*****@*****.**', 'password')['token']
    auth.auth_register('*****@*****.**', 'password', 'user2_name',
                       'user2_name')
    token_2 = auth.auth_login('*****@*****.**', 'password')['token']
    channel_id = channels_create(token_1, 'channel_name', True)['channel_id']
    with pytest.raises(AccessError):
        channel.channel_details(token_2, channel_id)
    # access error when given token does not refer to a valid user
    with pytest.raises(AccessError):
        assert channel.channel_details('invalid_token', channel_id)
Пример #31
0
def test_successful_login():
    """
    Passing valid inputs into auth_register
    Asserting that after logging out that user
    That when passing valid login inputs, the user is logged back in
    """
    new_user = auth.auth_register("*****@*****.**", "password3", "Skater",
                                  "Pro")

    auth.auth_logout(new_user["token"])
    assert bool(auth.auth_login("*****@*****.**", "password3")) is True
Пример #32
0
def test_auth_passwordreset_reset_success_case():
    '''
    This test will be used to check whether or not the user
    receives the error_code that was sent out. (This test might be redundant).
    '''
    
    other.clear()
    test_user = auth_register("*****@*****.**", "abcd1081$#", "John", "Smith") 
    
    auth_passwordreset_request("*****@*****.**")

    code = ''
    for reset_code in data.reset_codes:
        if test_user['u_id'] == reset_code['u_id']:
            code = reset_code['reset_code']
            

    auth_passwordreset_reset(code, "wxyz1081$#") 
    auth_logout(test_user['token'])
    auth_login("*****@*****.**", "wxyz1081$#")
Пример #33
0
def test_login_success():
    '''
    Testing successful auth_login
    '''
    clear()
    auth_register('*****@*****.**', 'iuser1', 'User', 'One')
    auth_login('*****@*****.**', 'iuser1')
    auth_register('*****@*****.**', 'iuser2', 'User', 'Two')
    auth_register('*****@*****.**', 'iuser3', 'User', 'Three')
    auth_login('*****@*****.**', 'iuser3')
    auth_login('*****@*****.**', 'iuser2')
    # Assume login works even if user already logged in
    auth_login('*****@*****.**', 'iuser1')
Пример #34
0
def test_name_first_success():
    login = auth.auth_register("*****@*****.**", "123456", 
    "Hayden", "Jacobs")

    auth.auth_login("*****@*****.**", "123456")

    token = login['token']
    u_id = login['u_id']
    user.user_profile_sethandle(token, "hjacobs")

    profile = user.user_profile(token, u_id)
    #First checking that all this information is initially correct
    assert(profile['user']['name_first'] == 'Hayden')
    assert(profile['user']['name_last'] == 'Jacobs')
    assert(profile['user']['handle_str'] == 'hjacobs')
    #changing name
    user.user_profile_setname(token, "Robbie", "Jacobs") #only changes first name
    assert(profile['user']['name_first'] == 'Robbie')
    assert(profile['user']['name_last'] == 'Jacobs')
    assert(profile['user']['handle_str'] == 'hjacobs') #shows that it is the same profile
Пример #35
0
def test_invite_InputError_invalid_u_id():
    #invalid test of invalid u_id
    # register user1
    # user1 create a new channel and use correct channel_id to
    # invite another user which is not exist
    clear()
    auth.auth_register('*****@*****.**', 'password', 'user1_name',
                       'user1_name')
    token_1 = auth.auth_login('*****@*****.**', 'password')['token']
    channel_id = channels_create(token_1, 'channel_name', True)['channel_id']
    with pytest.raises(InputError):
        channel.channel_invite(token_1, channel_id, 0)