Example #1
0
    def test_form_valid(self, user: User, request_factory: RequestFactory):
        form_data = {"name": "John Doe"}
        request = request_factory.post(reverse("users:update"), form_data)
        request.user = user
        session_middleware = SessionMiddleware()
        session_middleware.process_request(request)
        msg_middleware = MessageMiddleware()
        msg_middleware.process_request(request)

        response = UserUpdateView.as_view()(request)
        user.refresh_from_db()

        assert response.status_code == 302
        assert user.name == form_data["name"]
Example #2
0
    def mutate_and_get_payload(root, info, **input):
        "Login check"
        if not info.context.user.is_anonymous:
            raise GraphQLError('Already logged in.')
        # remove password from input to allow spaces in password
        password = input.pop('password')
        input = clean_input(input)
        "Extra username validation"
        if ' ' in input.get('username'):
            raise GraphQLError('Invalid username format.')
        "Email validation"
        try:
            validate_email(input.get('email'))
        except ValidationError:
            raise GraphQLError('Invalid email format.')
        "Checks to see if the user exists in the database"
        if UserModel.objects.filter(username=input.get('username')).first():
            raise GraphQLError('Username already taken.')
        if UserModel.objects.filter(email=input.get('email')).first():
            raise GraphQLError('Email already taken.')
        "Checks name format"
        if not validate_name(input.get('first_name')) or not validate_name(
                input.get('last_name')):
            raise GraphQLError('Invalid first/last name.')

        confirmation_link = input.pop('confirmation_link')

        "Convert username to lowercase"
        input['username'] = input.get('username').lower()

        new_user = UserModel(**input)
        new_user.set_password(password)
        new_user.save()

        # Email Authentication
        # try:
        #     server = smtplib.SMTP('smtp.gmail.com:587')
        #     server.ehlo()
        #     server.starttls()
        #     server.login("EMAIL", "PASSWORD")
        #     message = 'Subject: {}\n\n{}'.format(
        #         'Email Confirmation',
        #         'Please click the link below to confirm your email address:\n' + confirmation_link
        #     )
        #     server.sendmail("EMAIL", input.get('email'), message)
        #     server.quit()
        # except:
        #     print('Email failed to send.')

        return Register(user=new_user)
Example #3
0
def test_valid_registration(client):
    email = "*****@*****.**"
    password = "******"

    response = client.post("/api/user/register/",
                           json={
                               "email": email,
                               "password": password
                           })
    res = response.get_json()

    assert 200 == response.status_code
    assert res['success']
    assert res['auth_token']

    User.delete_by_email(email=email)
Example #4
0
 def post(self):
     """
     post /users/
     用户注册接口
     """
     json_data = Munch(request.json)
     redis_conn = get_redis_connection(4)
     redis_code = redis_conn.get(json_data.mobile)
     if not redis_code:
         # raise Exception("验证码失效")
         print("111222221")
     if redis_code.decode() != json_data.sms_code:
         # raise Exception("验证码输入错误")
         print("1111")
     password_hash = generate_password_hash(json_data.password)
     user = User(username=json_data.username,
                 password=password_hash,
                 mobile=json_data.mobile)
     db.session.add(user)
     db.session.commit()
     token = generate_token(user.id, 60 * 60 * 2)
     return jsonify({
         "code": 200,
         "msg": "success",
         "id": user.id,
         "username": json_data.username,
         "token": token
     })
Example #5
0
def before_each_request():
    # Try to get & set the current user if an auth token has been provided.
    auth_token = request.headers.get("Authorization")

    try:
        auth_token = auth_token.replace("Bearer ", "")
        g.current_user = User.get_user_by_authtoken(auth_token=auth_token)
    except Exception as e:
        g.current_user = None
Example #6
0
def test_user():
    test_user_email = "test_" + str(int(time.time())) + "@example.com"
    test_user_pass = "******"

    test_user = User.register_new_user(email=test_user_email,
                                       password=test_user_pass)

    yield (test_user_email, test_user_pass, test_user.generate_auth_token(),
           test_user.meta.id)

    # After this test user has been used, delete him
    test_user.delete()
Example #7
0
    def mutate_and_get_payload(root, info, **input):
        password = input.pop('password')
        cleaned_input = clean_input(input)
        cleaned_input['username'] = cleaned_input.get('username').lower()
        username = cleaned_input.get('username')

        # check if username exists
        if UserModel.objects.filter(username=username).exists():
            raise GraphQLError('Username Taken.')

        new_user = UserModel(username=username)
        new_user.set_password(password)
        new_user.save()

        UserSubscriptions.broadcast(group='users-subscription',
                                    payload={
                                        "type":
                                        SpecialMutationTypes.REGISTER.name,
                                        "username": username
                                    })

        return Register(user=new_user)
Example #8
0
def user_register():
    """
    This route handles user registration.

    Pre-conditions:
    - The POST request should contain the user's (valid) email and password.

    Post-conditions:
    - This route will create the user's account & return an authentication token
      that the front-end should include in all future requests
      (in order to authenticate the user in the backend).

    Sample responses:

    success (HTTP status 200):
    {
        "success" : true,
        "auth_token" : "<some auth token>"
    }

    failure (HTTP status 400):
    {
        "success" : false,
        "error" : "<some error message>"
    }

    :return:    A JSON response with the user's auth token
    """
    data = request.get_json(force=True)
    email = data['email']
    password = data['password']

    # Check if the email is valid.
    if not is_email_valid(email=email):
        return jsonify(success=False, error="Invalid email."), 400

    # Check if the password is valid.
    if not is_password_valid(password=password):
        return jsonify(success=False, error="Invalid password."), 400

    # We have a valid email & password, so let's register a new user.
    try:
        new_user = User.register_new_user(email=email, password=password)

        # Generate an auth token for this new user
        auth_token = new_user.generate_auth_token()

        return jsonify(success=True, auth_token=auth_token)
    except ValueError as e:
        return jsonify(success=False, error=str(e)), 400
def signup():
    try:

        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')

        if not username or not password or not email:
            return jsonify({
                "status": 401,
                "field": "common",
                "msg": "All fields are required!"
            })

        hashed_pwd = bcrypt.generate_password_hash(password).decode('utf-8')

        if User.query.filter_by(username=username).first():

            # user with username exists
            return jsonify({
                "status": 409,
                "field": "username",
                "msg": "Username already exists..."
            }), 409
        elif User.query.filter_by(email=email).first():

            # user with that email exists
            return jsonify({
                "status": 409,
                "field": "email",
                "msg": "Email already exists..."
            }), 409
        else:
            # New user
            user = User(username=username, email=email, password=hashed_pwd)

            db.session.add(user)
            db.session.commit()
            return jsonify({
                "status": 200,
                "field": "success",
                "msg": "Your account has been succesfully created! Please Login to Continue..."
            })
    except:
        return jsonify({
            "status": 500,
            "field": "common",
            "msg": "Oops, Some error happened!"
        }), 500
Example #10
0
def user_send_password_recovery_email():
    data = request.get_json(force=True)
    email = data['email']

    try:
        user = User.find_by_email(email)
    except ValueError as e:
        return jsonify(success=False, error=str(e)), 400

    try:
        user.send_forgot_password_email()
        return jsonify(success=True)
    except Exception:
        return jsonify(
            success=False,
            error="The password recovery email could not be sent."), 400
Example #11
0
def user_set_new_password():
    data = request.get_json(force=True)
    password_token = data['password_token']
    email = data['email']

    try:
        user = User.find_by_email(email)
    except ValueError as e:
        return jsonify(success=False, error=str(e)), 400

    if not user.verify_password_token(password_token):
        return jsonify(success=False,
                       error="Invalid password verification token."), 400

    new_password = data['new_password']
    try:
        user.set_password(new_password)
    except Exception as e:
        return jsonify(success=False, error=str(e)), 400

    return jsonify(success=True)
Example #12
0
def user_login():
    """
    This route handles user login.

    Pre-conditions:
    - A POST request with the provided email & password

    Post-conditions:
    - success: The auth token for the front-end to use for the user
    - failure: an error message

    Sample responses:

    success (HTTP status 200):
    {
        "success" : true,
        "auth_token" : "<auth token goes here>"
    }

    failure (HTTP status 400):
    {
        "success" : false,
        "error" : "Invalid email or password."
    }

    :return:    A JSON response with the user's auth token
    """
    data = request.get_json(force=True)
    email = data['email']
    password = data['password']

    try:
        logged_in_user = User.get_by_login_credentials(email=email,
                                                       password=password)
    except ValueError as e:
        return jsonify(success=False, error=str(e)), 400

    auth_token = logged_in_user.generate_auth_token()
    return jsonify(success=True, auth_token=auth_token)
Example #13
0
from backend.users.models import User

print("Clearing all users...")
User.search().query("match_all").delete()
print("Done.")
Example #14
0
def test_user_forgot_password(client, test_user):
    (test_user_email, test_user_password, auth_token, test_user_id) = test_user

    # Should fail for invalid email
    response = client.post(f"/api/user/send_password_recovery_email/",
                           json={"email": test_user_email + "asdas"})
    res = response.get_json()
    assert 400 == response.status_code
    assert not res["success"]
    assert "Invalid email." == res['error']

    # Should succeed for valid email
    response = client.post(f"/api/user/send_password_recovery_email/",
                           json={"email": test_user_email})
    res = response.get_json()
    assert 200 == response.status_code
    assert res["success"]

    password_recovery_token = User.get(id=test_user_id).password_recovery_token
    assert password_recovery_token

    incorrect_password_recovery_token = password_recovery_token + "q32ee"
    new_password = test_user_password + "123e1"

    # Should fail for invalid email
    response = client.post(f"/api/user/set_new_password/",
                           json={
                               "password_token":
                               incorrect_password_recovery_token,
                               "new_password": new_password,
                               "email": test_user_email + "asdas"
                           })
    res = response.get_json()
    assert 400 == response.status_code
    assert not res["success"]
    assert "Invalid email." == res['error']

    # Trying to set a new password with an incorrect recovery token should fail
    response = client.post(f"/api/user/set_new_password/",
                           json={
                               "password_token":
                               incorrect_password_recovery_token,
                               "new_password": new_password,
                               "email": test_user_email
                           })
    res = response.get_json()
    assert 400 == response.status_code
    assert not res["success"]
    assert "Invalid password verification token." == res['error']

    # Try to set a new password with a correct recovery token
    response = client.post(f"/api/user/set_new_password/",
                           json={
                               "password_token": password_recovery_token,
                               "new_password": new_password,
                               "email": test_user_email
                           })
    res = response.get_json()
    assert 200 == response.status_code
    assert res["success"]

    # Double check that we cannot login with old credentials
    response = client.post("/api/user/login/",
                           json={
                               "email": test_user_email,
                               "password": test_user_password
                           })
    res = response.get_json()

    assert 400 == response.status_code
    assert not res['success']
    assert "Incorrect password." == res['error']

    # Verify that we can login with the newly-set password
    response = client.post("/api/user/login/",
                           json={
                               "email": test_user_email,
                               "password": new_password
                           })
    res = response.get_json()

    assert 200 == response.status_code
    assert res['success']
    assert res['auth_token']
def test_user_get_absolute_url(user: User):
    assert user.get_absolute_url() == f"/users/{user.username}/"
Example #16
0
def init_db():
    User.init()
    PodcastTranscriptionBlob.init()
    Podcast.init()
Example #17
0
from backend.users.models import User, HistoryItem
from backend.podcasts.models import Podcast
from backend.search.models import PodcastTranscriptionBlob

# Fresh test user
test_user1_email = "*****@*****.**"
test_user1_pass = "******"

# Populated test user
test_user2_email = "*****@*****.**"
test_user2_pass = "******"

# Delete any existing test users
print("Deleting any existing test users...")
User.delete_by_email(test_user1_email)
User.delete_by_email(test_user2_email)

time.sleep(2)

# Register these 2 test users
print("Registering 2 test users...")
test_user1 = User.register_new_user(email=test_user1_email,
                                    password=test_user1_pass)
test_user2 = User.register_new_user(email=test_user2_email,
                                    password=test_user2_pass)

random_transcription_blobs = [
    transcription_blob
    for transcription_blob in PodcastTranscriptionBlob.search().query(
        "match_all").extra(collapse={"field": "podcast_id"})[:20]