예제 #1
0
    def post(self):
        """ Endpoint to login the user """

        request_data = request.get_json()
        email = request_data['email']
        password = bytes(request_data['password'], encoding='utf-8')
        user = User.query.filter(User.email == email,
                                 User.is_activated).first()
        error_response['message'] = 'Incorrect username or password'
        user_schema = UserSchema()

        if user:
            user_data = user_schema.dump(user)
            hashed = bytes(user_data['password'], encoding='utf-8')

            if bcrypt.checkpw(password, hashed):
                user_schema = UserSchema(exclude=['password'])
                logged_in_user = user_schema.dump(user)
                token = generate_auth_token(logged_in_user)
                success_response['message'] = 'User successfully logged in'
                success_response['data'] = {
                    'token': token,
                    'user': logged_in_user
                }

                return success_response, 200
            return error_response, 404
        return error_response, 404
예제 #2
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_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(to=user.email, subject=subject, template=html)
        result = user_schema.dump(user.create())
        return response_with(resp.SUCCESS_201, value={"user": result})
    except IntegrityError:
        return response_with(resp.INVALID_INPUT_422,
                             message="User already registered.")
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
예제 #3
0
 async def get(self, request: Request) -> HTTPResponse:
     """
     Resource for get all users
     """
     schema = UserSchema(many=True)
     users = await UserModel.find(sort="name")
     return json(schema.dump(users.objects))
예제 #4
0
    def post(self):
        """ Endpoint to create the user """

        request_data = request.get_json()
        UserValidators.validate(request_data)

        request_data = request_data_strip(request_data)

        bytes_password = bytes(request_data['password'], encoding='utf-8')
        hashed = bcrypt.hashpw(bytes_password, bcrypt.gensalt(10))
        request_data['password'] = hashed.decode('utf-8')

        new_user = User(**request_data)
        new_user.save()

        user_schema = UserSchema()
        user_data = user_schema.dump(new_user)

        send_email(user_data, 'Confirmation Email', 'confirmation_email.html')

        return {
            'status':
            'success',
            'message':
            'User successfully created. Please check your email to continue.'
        }, 201
예제 #5
0
    def post(self):
        """POST method for user login

        Returns:
            tuple: Success response with 200 status code
        """
        request_data = request.get_json()

        user, is_authenticated = User.authenticate(
            email=request_data.get('email'),
            password=request_data.get('password'))

        user_schema = UserSchema(exclude=['password', 'confirm_password'])

        if user and is_authenticated:
            return {
                'status': 'success',
                'message': SUCCESS_MESSAGES['USER_LOGIN'],
                'data': {
                    'token': user.token,
                    'user': user_schema.dump(user).data
                }
            }, 200
        else:
            return {
                'status': 'fail',
                'message': ERROR_MESSAGES['USER_LOGIN'],
                'error': ERROR_MESSAGES['INVALID_LOGIN_CREDENTIALS']
            }, 401
예제 #6
0
def admin_auth_header(init_db, new_admin):
    """ Admin auth header fixture """

    new_admin.save()

    user_schema = UserSchema()
    user_data = user_schema.dump(new_admin)
    token = generate_auth_token(user_data)
    return {'Authorization': token, 'Content-Type': 'application/json'}
예제 #7
0
def admin_auth_header(init_db, admin_user):
    """ admin auth header fixture """

    admin_user.save()
    user_schema = UserSchema()
    token = generate_auth_token(user_schema.dump(admin_user)['id'])

    return {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
예제 #8
0
def user_auth_header(init_db, new_user):
    """ user auth header fixture """

    new_user.save()
    new_user.update({'is_verified': True})
    user_schema = UserSchema()
    token = generate_auth_token(user_schema.dump(new_user)['id'])

    return {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
    def decorated(*args, **kwargs):
        decoded_token = request.decoded_token
        current_user = User.find_by_id(decoded_token['user']['id'])
        user_schema = UserSchema()
        user_data = user_schema.dump(current_user)

        if not user_data['is_admin']:
            message = 'Permission denied. You are not authorized to perform this action'
            error_response['message'] = message
            return error_response, 403

        return f(*args, **kwargs)
예제 #10
0
    def post(self):
        """ Endpoint to request password reset link """

        request_data = request.get_json()
        email = request_data['email']
        user = User.find_by_email(email)

        if not user:
            error_response['message'] = 'User not found'
            return error_response, 404

        user_schema = UserSchema()
        send_email(user_schema.dump(user), 'Password Reset Request',
                   'password_reset_email.html')

        return {
            'status':
            'success',
            'message':
            'Request successfully submitted. Please check your email to continue.'
        }, 200
예제 #11
0
    def post(self):
        """POST method for user signup

        Returns:
            tuple: Success response with 201 status code
        """

        request_data = request.get_json()

        user_schema = UserSchema()
        user_data = user_schema.load_object_into_schema(request_data)

        user = User(**user_data)
        user.save()

        return {
            'status': 'success',
            'message': SUCCESS_MESSAGES['USER_SIGNUP'],
            'data': {
                'token': user.token,
                'user': user_schema.dump(user).data
            }
        }, 201
예제 #12
0
def register_user():
    schema = UserSchema()
    input_data = request.get_json()
    if 'uid' not in input_data['data']['attributes'].keys():
        data, err = schema.load(input_data)
        if err:
            return jsonify(err)
        try:
            user = auth.create_user(
                email=data['email'],
                email_verified=False,
                password=data['password'],
                display_name=data['username'],
            )
        except auth.AuthError as e:
            if e.code == 'USER_CREATE_ERROR':
                errmsg = 'User with email already exists'
            return ErrorResponse(
                FirebaseError(errmsg).message, 422, {
                    'Content-Type': 'application/json'
                }).respond()

        newUser = User(id_=user.uid,
                       username=data['username'],
                       email=user.email,
                       password=data['password'])

        if user.email in admins:
            newUser.siteAdmin = True

        newUser.save_to_db()

        if newUser.email in admins:
            perm = Permissions(isUser=True,
                               isAdmin=True,
                               user_permissions=newUser)
            perm.save_to_db()
        else:
            perm = Permissions(isUser=True, user_permissions=newUser)
            perm.save_to_db()

        return jsonify(schema.dump(newUser).data)
    else:
        schema = OAuthUserSchema()
        data, err = schema.load(input_data)
        if err:
            return jsonify(err)

        uid = input_data['data']['attributes']['uid']
        user_ = User.getUser(user_id=uid)
        if not user_:
            newUser = User(id_=uid,
                           username=data['username'],
                           email=data['email'],
                           password=data['password'],
                           photoURL=data['photoURL'])
            if data['email'] in admins:
                newUser.siteAdmin = True
            newUser.save_to_db()

            if newUser.email in admins:
                perm = Permissions(isUser=True,
                                   isAdmin=True,
                                   user_permissions=newUser)
                perm.save_to_db()
            else:
                perm = Permissions(isUser=True, user_permissions=newUser)
                perm.save_to_db()
        else:
            newUser = user_
        return jsonify(schema.dump(newUser).data)