コード例 #1
0
ファイル: user_controller.py プロジェクト: booxorg/boox-api
def user_info(variables={}, request={}):

    result = {}
    try:
        user_id = Token.Token().query('USERID').where(
            'TOKEN', '=', request.params['token']).get()[0]['USERID']
        user_query = User.User()\
            .query('USERS.ID', 'USERS.USERNAME', 'USERS.FIRSTNAME', 'USERS.LASTNAME', 'USERS.EMAIL')\
            .where('USERS.ID', '=', user_id).get()[0]
        locations = Location.Location()\
            .query('LOCATIONS.COUNTRY', 'LOCATIONS.CITY', 'LOCATIONS.STREET')\
            .where('USERID', '=', user_id).get()
        if locations:
            locations = locations[0]
        else:
            locations = dict()

        prefs = Preference.Preference().query('*').where(
            'USERID', '=', user_id).get()
        if prefs:
            prefs = prefs[0]
        else:
            prefs = dict()

        result['firstname'] = user_query['USERS.FIRSTNAME']
        result['lastname'] = user_query['USERS.LASTNAME']
        result['email'] = user_query['USERS.EMAIL']
        result['country'] = locations.get('LOCATIONS.COUNTRY', '')
        result['city'] = locations.get('LOCATIONS.CITY', '')
        result['street'] = locations.get('LOCATIONS.STREET', '')
        result['title_preferences'] = prefs.get('PREFERENCE', '')

    except UserWarning, e:
        logging.exception('User warning')
        return Controller.response_json({'status': 'error', 'message': str(e)})
コード例 #2
0
def token_valid(variables={}, request={}):
    status = 'success'
    message = ''
    token_ok = False

    if not 'token' in request.params:
        status = 'error'
        message = 'token must be present for this api'
    else:
        token = Token.Token()
        user_token = request.params['token']
        count = len(token.query('ID').where('TOKEN', '=', user_token).get())
        if count == 0:
            status = 'error'
            message = 'invalid user token'
        else:
            token_ok = True

    if token_ok:
        return (True, None)
    else:
        result = {
            'status' : status,
            'message' : message
        }
        return (False, Controller.response_json(result))
コード例 #3
0
def propose_exchange(variables={}, request={}):
    status = 'success'
    message = ''

    token = request.params['token']
    book_id = request.params['bookid']

    dict_book = Book.Book().query("DELETED").where("ID", "=", book_id).get()
    if not dict_book:
        status = 'error'
        message = 'the book does not exist'
    elif (dict_book[0]['DELETED'] == 1):
        status = 'error'
        message = 'the book is not available for exchange'
    else:
        dict_receiver = Token.Token().query("USERID").where(
            "TOKEN", "=", token).get()
        dict_owner = UserBook.UserBook().query("USERID").where(
            "BOOKID", "=", book_id).get()
        logging.debug(dict_owner)
        if (dict_receiver[0]['USERID'] == dict_owner[0]['USERID']):
            status = 'error'
            message = 'users cannot send requests to themselves'
        else:
            dict_exchange = Exchange.Exchange().query('ID').where("OWNERID", "=", dict_owner[0]['USERID']). \
                condition("AND", "RECEIVERID", "=", dict_receiver[0]['USERID']). \
                condition("AND", "BOOKID1", "=", book_id).get()
            if (dict_exchange):
                status = 'error'
                message = 'the exchange already exists'
            else:
                date = datetime.datetime.now().strftime("%Y-%m-%d")

                insert_dict = {
                    'OWNERID': dict_owner[0]['USERID'],
                    'RECEIVERID': dict_receiver[0]['USERID'],
                    'BOOKID1': book_id,
                    'EXCHANGEDATE': date,
                    'ISFINISHED': 0,
                    'HASSUCCEEDED': 0
                }
                message = 'the request has been registered'
                Exchange.Exchange().insert(insert_dict)

    result = {'status': status, 'message': message}

    return Controller.response_json(result)
コード例 #4
0
ファイル: login_controller.py プロジェクト: booxorg/boox-api
def register(variables={}, request={}):
    status = 'success'
    message = ''

    username = request.params['username']
    password = request.params['password']

    user = User.User()
    response_dict_user = user.query("ID").where("USERNAME", "=",
                                                username).condition(
                                                    "OR", "EMAIL", "=",
                                                    username).get()
    if not response_dict_user:
        message = 'incorrect username or password'
        status = 'error'
    else:
        response_dict_pass = user.query("PASSWORD", "SALT").where(
            "USERNAME", "=", username).condition("OR", "EMAIL", "=",
                                                 username).get()
        input_pass_hash = bcrypt.hashpw(password.encode('utf8'),
                                        response_dict_pass[0]["SALT"])

        if input_pass_hash != response_dict_pass[0]["PASSWORD"]:
            message = 'incorrect username or password'
            status = 'error'
        else:
            token = Token.Token()
            response_dict_token = token.query("TOKEN").where(
                "USERID", "=",
                response_dict_user[0]["ID"]).condition("AND", "TOKENTYPE", "=",
                                                       "booxtoken").get()
            message = 'log in successful'
            status = 'success'

    if status == 'success':
        response = {
            'token': response_dict_token[0]['TOKEN'],
            'id': response_dict_user[0]['ID']
        }
        result = {'status': status, 'message': message, 'response': response}
    else:
        result = {'status': status, 'message': message}

    return Controller.response_json(result)
コード例 #5
0
def match_book(variables={}, request={}):
    status = 'success'
    message = ''

    token = request.params['token']
    receiver_id = request.params['receiverid']
    book_id1 = request.params['bookid1']
    book_id2 = request.params['bookid2']

    user_dict = Token.Token().query("USERID").where("TOKEN", "=", token).get()
    book1_dict = Book.Book().query("TITLE").where("ID", "=", book_id1).get()
    book2_dict = Book.Book().query("TITLE").where("ID", "=", book_id2).get()

    if not book1_dict or not book2_dict:
        status = 'error'
        message = 'one of the books does not exist'
    else:
        exchange_dict = Exchange.Exchange().query("*").where("OWNERID", "=", user_dict[0]['USERID']). \
                      condition("AND", "BOOKID1", "=", book_id1). \
                      condition("AND", "RECEIVERID", "=", receiver_id).get()

        if not exchange_dict:
            status = 'error'
            message = 'the exchange does not exist'
        else:
            if exchange_dict[0]['ISFINISHED'] == 1:
                status = 'error'
                message = 'the exchange has already been approved/denied'
            else:
                if exchange_dict[0]['BOOKID2'] != None:
                    status = 'error'
                    message = 'you cannot respond to this exchange'
                else:
                    Exchange.Exchange().update({ 'BOOKID2' : book_id2 }). \
                         where("OWNERID", "=", user_dict[0]['USERID']). \
                            condition("AND", "BOOKID1", "=", book_id1). \
                            condition("AND", "RECEIVERID", "=", receiver_id).execute()

                    status = 'success'
                    message = 'user responded to the exchange'

    result = {'status': status, 'message': message}

    return Controller.response_json(result)
コード例 #6
0
def list_offers(variables={}, request={}):
    status = 'success'
    message = ''
    exchange_status = ''

    token = request.params['token']

    user_dict = Token.Token().query("USERID").where("TOKEN", "=", token).get()
    exchange_dict = Exchange.Exchange().query("EXCHANGES.OWNERID", "EXCHANGES.RECEIVERID", "EXCHANGES.BOOKID1", "EXCHANGES.BOOKID2", "EXCHANGES.ISFINISHED"). \
        where("EXCHANGES.OWNERID", "=", user_dict[0]['USERID']). \
        condition("OR", "EXCHANGES.RECEIVERID", "=", user_dict[0]['USERID']).get()

    result = None
    if not exchange_dict:
        status = 'success'
        message = 'no entries found'
        result = {'status': status, 'message': message}
    else:
        status = 'success'
        message = 'entries found'
        response = exchange_dict

        for exchange in exchange_dict:
            if exchange['EXCHANGES.ISFINISHED'] == 1:
                exchange['exchange_status'] = 'exchange_finished'
            else:
                if exchange['EXCHANGES.BOOKID2'] == None:
                    exchange['exchange_status'] = 'pending_match'
                else:
                    exchange['exchange_status'] = 'request_sent'

            if user_dict[0]['USERID'] == exchange['EXCHANGES.OWNERID']:
                exchange['user_status'] = 'owner'
            else:
                exchange['user_status'] = 'receiver'

        result = {'status': status, 'message': message, 'response': response}

    return Controller.response_json(result)
コード例 #7
0
ファイル: user_controller.py プロジェクト: booxorg/boox-api
def get_user_by_token(variables={}, request={}):
    status = 'success'
    message = ''

    token = request

    user_dict = Token.Token().query("TOKENS.USERID").where(
        "TOKENS.TOKEN", "=", request.params['token']).get()

    if not user_dict:
        status = 'error'
        message = 'invalid token'
    else:
        status = 'success'
        message = 'valid token'

    if user_dict:
        response = {'userid': user_dict[0]['TOKENS.USERID']}
    else:
        response = []

    result = {'status': status, 'message': message, 'response': response}

    return Controller.response_json(result)
コード例 #8
0
ファイル: book_controller.py プロジェクト: booxorg/boox-api
def add_book(variables={}, request={}):
    status = 'success'
    message = ''
    values = {}

    #title = request.params['title']
    #author = request.params['author']
    expires = request.params['expires']
    genre = request.params['genre']
    goodreads_id = request.params['goodreads_id']
    ok, error_message = Validator.validate([
        #(title, r'^[A-Za-z0-9\s\-_,\.;:()]+$', 'title value is invalid'),
        #(author, r'^[a-zA-Z0-9 ,.\'-]+$', 'author value is invalid'),
        (genre, r'^(%s)$' % ('|'.join(genres)), 'genre value is invalid'),
        (expires,
         r'^([1-9]|([012][0-9])|(3[01]))\-([0]{0,1}[1-9]|1[012])\-\d\d\d\d$',
         'expires value is invalid'),
        (goodreads_id, r'^[0-9]|[1-9][0-9]+$',
         'goodreads_id value is invalid'),
    ])

    try:
        if not ok:
            raise UserWarning(error_message)
        book = Goodreads.find_book_by_id(int(goodreads_id))
        if not book:
            raise UserWarning('no book with such id was found')

        current_user_id = Token.Token().query('USERID').where(
            'TOKEN', '=', request.params['token']).get()[0]['USERID']
        if not current_user_id or current_user_id == 0:
            raise UserWarning('invalid user connected to token')

        created_author = Author.Author().update_or_create(
            {'NAME': book['author']}, {'NAME': book['author']})
        if not created_author:
            raise UserWarning('unable to create or update the book author')

        datetime_object = datetime.strptime(expires, '%d-%m-%Y')
        created_book = Book.Book().insert({
            'ISBN':
            book['isbn'],
            'GOODREADSID':
            int(goodreads_id),
            'TITLE':
            book['title'],
            'GENRE':
            genre,
            'COVER':
            book['image_url'],
            'EXPIRES':
            datetime_object.strftime('%Y-%m-%d'),
            'AUTHORID':
            created_author['ID']
        })
        if not created_book:
            raise UserWarning('unable to add book to the database')

        created_user_book = UserBook.UserBook().insert({
            'BOOKID':
            created_book['ID'],
            'USERID':
            current_user_id
        })
        if not created_user_book:
            raise UserWarning('unable to connect user to book')

        message = 'the book has been added'
        values['book_id'] = created_book['ID']
        values['user_id'] = current_user_id
        values['author_id'] = created_author['ID']

    except UserWarning, e:
        logging.exception('User Warning')
        return Controller.response_json({'status': 'error', 'message': str(e)})
コード例 #9
0
ファイル: user_controller.py プロジェクト: booxorg/boox-api
def user_edit(variables={}, request={}):
    status = 'success'
    message = ''

    fname = request.params.get('fname', '')
    lname = request.params.get('lname', '')
    email = request.params.get('email', '')
    password = request.params.get('password', None)
    new_password = request.params.get('npassword', None)
    confirm_new_password = request.params.get('cnpassword', None)
    country = request.params.get('country', '')
    city = request.params.get('city', '')
    street = request.params.get('street', '')
    title_prefs = request.params.get('title_preferences', '')
    result = None
    try:
        if not fname or not lname or not email:
            raise UserWarning(
                'firstname, lastname and email are mandatory fields')
        user_id = Token.Token().query('USERID').where(
            'TOKEN', '=', request.params['token']).get()[0]['USERID']

        User.User().update({
            'FIRSTNAME': fname,
            'LASTNAME': lname,
            'EMAIL': email
        }).where('ID', '=', user_id).execute()
        user = User.User().query('*').where('ID', '=', user_id).get()[0]

        Preference.Preference().update_or_create(
            {
                'USERID': user_id,
                'PREFERENCETYPE': 'bookname'
            }, {
                'USERID': user_id,
                'PREFERENCETYPE': 'bookname',
                'PREFERENCE': title_prefs
            })

        if country or city or street:
            Location.Location().update_or_create({'USERID': user_id}, {
                'USERID': user_id,
                'COUNTRY': country,
                'CITY': city,
                'STREET': street
            })

        if password:
            old_password_hash = bcrypt.hashpw(password.encode('utf8'),
                                              user['SALT'])
            if old_password_hash != user['PASSWORD']:
                raise UserWarning('password incorrect')
            if new_password != confirm_new_password:
                raise UserWarning(
                    'new password and confirm password don\'t match')
            else:
                new_password_hash = bcrypt.hashpw(new_password.encode('utf8'),
                                                  user['SALT'])
                User.User().update({
                    'PASSWORD': new_password_hash
                }).where('ID', '=', user_id).execute()

    except UserWarning, e:
        logging.exception('User warning')
        return Controller.response_json({'status': 'error', 'message': str(e)})
コード例 #10
0
def notify_users(token, bookname, bookid):
    status = 'success'
    message = ''

    #token = request.params['token']
    #bookname = request.params['bookname']
    #bookid = request.params['bookid']

    user_dict = Token.Token().query("USERID").where("TOKEN", "=", token).get()
    owner_location_dict = Location.Location().query("COUNTRY", "CITY", "STREET"). \
              where("USERID", "=", user_dict[0]['USERID']).get()

    owncountry = owner_location_dict[0]['COUNTRY']
    owncity = owner_location_dict[0]['CITY']
    ownstreet = owner_location_dict[0]['STREET']

    if owncountry == "" or owncity == "" or ownstreet == "":
        status = 'error'
        message = 'the sender is missing location information'
    else:
        apiURL = "https://maps.google.com/maps/api/geocode/json?address="
        apiURL = "%s %s,%s,%s" % (apiURL, owncountry, owncity, ownstreet)
        apiURL = "%s&key=%s" % (apiURL,
                                App.config.get('GOOGLE', 'geocoding_key'))

        api_response = requests.get(apiURL)
        api_status = api_response.json()['status']

        if api_status == 'ZERO_RESULTS':
            status = 'error'
            message = 'sender address not found'
        else:
            own_lat = api_response.json(
            )['results'][0]['geometry']['location']['lat']
            own_lng = api_response.json(
            )['results'][0]['geometry']['location']['lng']

            #print("owner %s %s") % (str(own_lat), str(own_lng))

            dict_preference = Preference.Preference().query("USERID").where("PREFERENCETYPE", "=", "bookname"). \
                           condition("AND","PREFERENCE", "=", bookname).get()

            for preference in dict_preference:
                location_dict = Location.Location().query("COUNTRY", "CITY", "STREET"). \
                         where("USERID", "=", preference['USERID']).get()
                reccountry = location_dict[0]['COUNTRY']
                reccity = location_dict[0]['CITY']
                recstreet = location_dict[0]['STREET']

                if reccountry != "" and reccity != "" and recstreet != "":
                    apiURL = "https://maps.google.com/maps/api/geocode/json?address="
                    apiURL = "%s %s,%s,%s" % (apiURL, reccountry, reccity,
                                              recstreet)
                    apiURL = "%s&key=%s" % (
                        apiURL, App.config.get('GOOGLE', 'geocoding_key'))

                    api_response = requests.get(apiURL)
                    api_status = api_response.json()['status']

                    if api_status != 'ZERO_RESULTS':
                        rec_lat = api_response.json(
                        )['results'][0]['geometry']['location']['lat']
                        rec_lng = api_response.json(
                        )['results'][0]['geometry']['location']['lng']

                        #print "receiver %s %s" % (str(rec_lat), str(rec_lng))

                        R = 6373.0
                        lat1 = radians(own_lat)
                        lon1 = radians(own_lng)
                        lat2 = radians(rec_lat)
                        lon2 = radians(rec_lng)

                        dlat = lat2 - lat1
                        dlon = lon2 - lon1

                        a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(
                            dlon / 2)**2
                        c = 2 * atan2(sqrt(a), sqrt(1 - a))
                        distance = R * c

                        if (distance <= 5):
                            dict_insert = {
                                "BOOKID": bookid,
                                "OWNERID": user_dict[0]['USERID'],
                                "RECEIVERID": preference['USERID']
                            }
                            Notification.Notification().insert(dict_insert)
                    status = 'success'
                    message = 'users have been notified'

    result = {'status': status, 'message': message}

    return result
コード例 #11
0
def register(variables={}, request={}):
    status = 'success'
    message = ''

    username = request.params['username']
    password = request.params['password']
    cpassword = request.params['cpassword']
    fname = request.params['fname']
    lname = request.params['lname']
    email = request.params['email']

    ok, error_message = Validator.validate([
        (username, r'^[A-Za-z][A-Za-z0-9]+$',
         'The username should be only small and big letters with numbers'),
        (password, r'^.{7,}$', 'Password should be longer than 6 characters'),
        (cpassword, r'^.{7,}$',
         'Password confirm should be longer than 6 characters'),
        (fname, r'^[\w,-\']+$', 'first name value is invalid'),
        (lname, r'^[\w,-\']+$', 'last name value is invalid'),
        (email,
         r"""^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$""",
         'email value is invalid'),
    ])

    try:
        if not ok:
            raise UserWarning(error_message)

        user = User.User()
        token = Token.Token()
        response_dict_list = user.query("ID").where("USERNAME", "=",
                                                    username).condition(
                                                        "OR", "EMAIL", "=",
                                                        email).get()
        if not response_dict_list:
            if (password != cpassword):
                raise UserWarning('passwords do no match')
            generated_token = strgen.StringGenerator("[\w\d]{20}").render()
            salt = bcrypt.gensalt()
            password_hash = bcrypt.hashpw(password.encode('utf8'), salt)
            insert_user_dict = {
                "USERNAME": username,
                "PASSWORD": password_hash,
                "SALT": salt,
                "FIRSTNAME": fname,
                "LASTNAME": lname,
                "EMAIL": email,
                "ISADMINISTRATOR": 0
            }
            inserted_user = user.insert(insert_user_dict)

            insert_token_dict = {
                "USERID": inserted_user["ID"],
                "TOKENTYPE": "booxtoken",
                "TOKEN": generated_token
            }
            token.insert(insert_token_dict)

            message = 'user registered successfully'
        else:
            raise UserWarning('username already exists')

    except UserWarning, e:
        logging.exception('User warning')
        return Controller.response_json({'status': 'error', 'message': str(e)})