Пример #1
0
def signup():
    """sign up a new user"""
    try:
        username = json.loads(request.data.decode())['username']
        password = json.loads(request.data.decode())['password'].replace(
            " ", "")
        email = json.loads(request.data.decode())['email'].replace(" ", "")

        if re.match('^[a-zA-Z][-\w.]{0,22}([a-zA-Z\d]|(?<![-.])_)$',
                    username) is None:
            return jsonify({'response': 'invalid username'}), 400
        if not validate_email(email):
            return jsonify({'response': 'invalid email'}), 400
        if re.match('[A-Za-z0-9@#$%^&+=]{8,}', password) is None:
            return jsonify(
                {'response':
                 'password must contain 6 or more characters'}), 400
        """
        search if the user exists in the database
        """
        user = User(username, email, "")
        if user.exists() is None:
            user.create_user(password)
            return jsonify({'response': 'user created successfully'}), 201
        else:
            return jsonify({'response': 'user already exists'}), 409
    except (KeyError, ValueError) as ex:
        print('response', ex)
        return jsonify({
            'response':
            'json body must contain username, password and email'
        }), 400
    except (psycopg2.DatabaseError, psycopg2.IntegrityError, Exception) as ex:
        print('error in signup', ex)
        return jsonify({'response': 'something went wrong'}), 500
Пример #2
0
def login():
    """
    login an existing user
    """
    try:
        username = json.loads(request.data.decode())['username'].replace(
            " ", "")
        password = json.loads(request.data.decode())['password'].replace(
            " ", "")
        user = User(username, "", "")

        user = user.exists()
        if check_password_hash(user.password_hash, password):
            """token if password is correct"""
            token = auth_encode(user.user_id)
            if token:
                response = {
                    'response': 'login successful',
                    'token': token.decode()
                }
                return jsonify(response), 200
        else:
            return jsonify({'response': 'invalid username/password'}), 422
    except (KeyError, ValueError) as ex:
        print('error in login', ex)
        return jsonify(
            {'response': 'json body must contain username and password'}), 400
    except (psycopg2.DatabaseError, psycopg2.IntegrityError, Exception) as ex:
        print('error in login', ex)
        return jsonify({'response': 'user not found'}), 404