def create_user():
    try:
        data = request.get_json()
        if User.find_by_email(
                data['email']) is not None or User.find_by_username(
                    data['username']) is not None:
            return response_with(resp.INVALID_INPUT_422)
        data['password'] = User.generate_hash(data['password'])
        user_schema = UserSchema()
        user = user_schema.load(data)
        token = generate_verification_token(data['email'])
        verification_email = url_for('user_routes.verify_email',
                                     token=token,
                                     _external=True)
        html = render_template_string(
            "<p>Welcome! Thanks for signing up. Please follow this link to activate your "
            "account:</p> <p><a href='{{ verification_email }}'>{{ verification_email "
            "}}</a></p> <br> <p>Thanks!</p>",
            verification_email=verification_email)
        subject = "Please Verify your email"
        send_email(user.email, subject, html)
        result = user_schema.dump(user.create())
        return response_with(resp.SUCCESS_201, value={'author': result})
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
def authenticate_user():
    try:
        data = request.get_json()
        if data.get('email'):
            current_user = User.find_by_email(data['email'])
        elif data.get('username'):
            current_user = User.find_by_username(data['username'])
        if not current_user:
            return response_with(resp.SERVER_ERROR_404)
        if current_user and not current_user.isVerified:
            return response_with(resp.BAD_REQUEST_400)
        if User.verify_hash(data['password'], current_user.password):
            access_token = create_access_token(identity=current_user.username)
            return response_with(resp.SUCCESS_200,
                                 value={
                                     'message':
                                     'Logged in as {} '.format(
                                         current_user.username),
                                     "access_token":
                                     access_token
                                 })
        else:
            return response_with(resp.UNAUTHORIZED_401)
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
Example #3
0
def authenticate_user():
    try:
        data = request.get_json()
        if data.get('email'):
            current_user = User.find_by_email(data['email'])
        elif data.get('username'):
            current_user = User.find_by_username(data['username'])
        if not current_user:
            return response_with(resp.SERVER_ERROR_404)

        # Comment from this line if you don't want use email.
        if current_user and not current_user.isVerified:
            return jsonify(message='User is not verified'), 403
        #Comment to this line if you don't want use email.

        if User.verify_hash(data['password'], current_user.password):
            access_token = create_access_token(
                identity=current_user.id)  #,   expires_delta = False)
            return response_with(resp.SUCCESS_200, \
                                 value={'message': 'Logged in as {}'.format(current_user.username), \
                                        "access_token": access_token})
        else:
            return response_with(resp.UNAUTHORIZED_401)
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
Example #4
0
def authenticate_user():
    try:
        data = request.get_json()
        if data.get('email'):
            current_user = User.find_by_email(data.get('email'))
        elif data.get('username'):
            current_user = User.find_by_username(data.get('username'))
        if not current_user:
            return response_with(resp.SERVER_ERROR_404)
        if current_user and not current_user.is_verified:
            return response_with(resp.BAD_REQUEST_400)
        if User.verify_hash(data.get('password'), current_user.password):
            access_token = create_access_token(identity=data.get('username'))
            user_schema = UserSchema()
            user = user_schema.dump(current_user)
            return response_with(resp.SUCCESS_200,
                                 value={
                                     'message':
                                     'Logged in as {}'.format(
                                         current_user.username),
                                     'access_token':
                                     access_token,
                                     'user':
                                     user
                                 })
        else:
            return response_with(resp.UNAUTHORIZED_401,
                                 value={'message': 'Password is wrong'})
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
Example #5
0
    def test_delete_user(self):
        token = login(3)

        user = User.find_by_email("*****@*****.**")

        response = self.app.delete(
            '/api/users/' + str(user.id),
            content_type='application/json',
            headers={'Authorization': 'Bearer ' + token})

        self.assertEqual(204, response.status_code)
Example #6
0
    def test_change_status_user(self):
        token = login(3)

        data = {"role": "admin"}

        user = User.find_by_email("*****@*****.**")

        response = self.app.post('/api/users/status/' + str(user.id),
                                 data=json.dumps(data),
                                 content_type='application/json',
                                 headers={'Authorization': 'Bearer ' + token})

        self.assertEqual(200, response.status_code)
Example #7
0
def login():
    """
    Login existing user
    :return: Access token and Refresh token
    """
    payload = request.json
    email = payload.get('email', None)
    password = payload.get('password', None)

    user = User.find_by_email(email)
    validate_credentials(user, password)

    return jsonify({**generate_jwt(user.uuid), 'user': user})
Example #8
0
def create_user():
    try:
        data = request.get_json()
        if (User.find_by_email(data['email']) is not None
                or User.find_by_username(data['username']) is not None):
            return response_with(resp.INVALID_INPUT_422)
        data['password'] = User.generate_hash(data['password'])
        user_schmea = UserSchema()
        user = user_schmea.load(data)
        sendEmailToken(data['email'])
        result = user_schmea.dump(user.create())
        return response_with(resp.SUCCESS_201)

    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
Example #9
0
    def test_get_user(self):
        token = login(3)

        user_to_get = User.find_by_email("*****@*****.**")

        response = self.app.get('/api/users/' + str(user_to_get.id),
                                content_type='application/json',
                                headers={'Authorization': 'Bearer ' + token})
        data = json.loads(response.data)

        print(data)

        user = {'email': '*****@*****.**', 'id': 2, 'role': 'user', \
                'username': '******', 'isVerified': False}

        self.assertEqual(200, response.status_code)
        self.assertTrue(user == data['user'])  #check the user
Example #10
0
def create_user():
    """
    Create user endpoint
    ---
    parameters:
        - in: body
          name: body
          schema:
            id: UserSignup
            required:
                - username
                - password
                - email
            properties:
                username:
                    type: string
                    description: Unique username of the user
                    default: "Johndoe"
                password:
                    type: string
                    description: Password of the user
                    default: "somethingstrong"
            email:
                type: string
                description: email of the user
                default: "*****@*****.**"
            responses:
                    201:
                        description: User successfully created
                        schema:
                        id: UserSignUpSchema
                        properties:
                            code:
                            type: string
                    422:
                        description: Invalid input arguments
                        schema:
                        id: invalidInput
                        properties:
                            code:
                                type: string
                            message:
                                type: string
    """
    try:
        data = request.get_json()
        if (User.find_by_email(data["email"]) is not None
                or User.find_by_username(data["username"]) is not None):
            return response_with(resp.INVALID_FIELD_NAME_SENT_422)
        data["password"] = User.generate_hash(data["password"])
        user_schema = UserSchema()
        user = user_schema.load(data)
        token = generate_verification_token(data["email"])
        verification_email = url_for("user_routes.verify_email",
                                     token=token,
                                     _external=True)
        html = render_template_string(
            "<p>Welcome! Thanks for signing up. Please follow this link to activate your account:</p> <p><a href='{{ verification_email }}'>{{ verification_email }}</a></p> <br> <p>Thanks!</p>",
            verification_email=verification_email,
        )
        subject = "Please Verify your email"
        # send_email(user.email, subject, html)
        result = user_schema.dump(user.create())
        return response_with(resp.SUCCESS_201)

    except Exception as e:
        print(e)
        return response_with(resp.INVALID_FIELD_NAME_SENT_422)
Example #11
0
def authenticate_user():
    """
    User Login
    ---
    parameters:
        - in: body
          name: body
          schema:
            id: UserLogin
            required:
                - password
                - username
            properties:
                username:
                    type: string
                    description: username of the user
                    default: "test1"
                password:
                    type: string
                    description: Password of the user
                    default: "123456"
            responses:
                200:
                    description: User successfully logged In
                    schema:
                    id: UserLoggedIn
                    properties:
                        code:
                        type: string
                        message:
                        type: string
                        value:
                        schema:
                            id: UserToken
                            properties:
                                access_token:
                                    type: string
                                code:
                                    type: string
                                message:
                                    type: string
                401:
                    description: Invalid input arguments
                    schema:
                        id: invalidInput
                        properties:
                            code:
                                type: string
                            message:
                                type: string
    """

    try:
        data = request.get_json()
        if data.get("email"):
            current_user = User.find_by_email(data["email"])
        elif data.get("username"):
            current_user = User.find_by_username(data["username"])
        if not current_user:
            return response_with(resp.SERVER_ERROR_404)
        if current_user and not current_user.isVerified:
            return response_with(resp.BAD_REQUEST_400)
        if User.verify_hash(data["password"], current_user.password):
            access_token = create_access_token(identity=current_user.username)
            return response_with(
                resp.SUCCESS_200,
                value={
                    "message": "Logged in as admin",
                    "access_token": access_token
                },
            )
        else:
            return response_with(resp.UNAUTHORIZED_401)
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)