Пример #1
0
def main():

    secretKey = 'k5PG9-GT0x016M-rKZPqpCPQYj2HFlLXTU8kJpQl5L8'
    salt = createSalt()
    keyAndSalt = salt + ':' + secretKey
    thirdPartyAccessid = 'CA1TAuUG9Ned35wF'
    requestId = 'requestID'
    deviceID = 'deviceID'
    apiRegistrationId = 'CA1ARFrD8x2J5U94'
    email = '*****@*****.**'
    name = 'soham'
    contactID = 'CAb6354mWzEW'
    encodedKey = encodeSecretKey(keyAndSalt)
    print(encodedKey)
    secretKeyString = encodedKey  #need to
    access_token = auth(salt, secretKeyString, thirdPartyAccessid)
    toDate = '2018-05-20T16:12:12.000Z'

    randomID = '34674366743hsvgkjvgskvb'
    fromDate = '2018-05-16T16:12:12.000Z'
    referenceNumber = ''

    print('starting')

    return auth(salt, encodedKey, thirdPartyAccessid)
Пример #2
0
def user_tag_add(username):
    """
    Add new tags to a user
    :param username:
    :return:
    """

    try:
        assert username == request.view_args['username']

        if not auth(  # authenticate user
                app.config['SECRET_KEY'],
                request,
                username
        ):
            return response_unauthorised()

        json_request = request.json

        # Check user_tags parameter exists
        try:
            new_tags = json_request['user_tags']
            current_tags = user.user_info(username)['user_tags']
            separate = "" if current_tags == "" else ","  # stop incorrect commas at start of comma separated lists
            current_tags = current_tags + separate + new_tags.replace(" ", "")  # remove whitespace in tags
            user.update_user(username, tags=current_tags)
        except:
            return response_invalid()

        response_json = json_dict({"user_tags": current_tags}, indent=4)
        return Response(response_json, status=success_code, mimetype='application/json')

    except Exception as e:
        print(e)
        return response_unknown()
Пример #3
0
def user_reward_update(username):
    """
    Update a users reward points
    :param username:
    :return:
    """
    try:
        assert username == request.view_args['username']

        if not auth(  # authenticate user
                app.config['SECRET_KEY'],
                request,
                username
        ):
            return response_unauthorised()

        json_request = request.json

        try:
            points = json_request['reward_points']
            user.update_user(username, reward_points=points)
        except:
            return response_invalid()

        response_json = json_dict({"reward_points": points}, indent=4)
        return Response(response_json, status=success_code, mimetype='application/json')

    except Exception as e:
        print(e)
        return response_unknown()
Пример #4
0
    def login(self):
        """
        Takes the credentials,validates them and redirects to specific user tasks.
        :return:
        """
        try:
            print("WELCOME TO AIMS!!\n")
            print("Login as: \n"
                  "1: Admin \n"
                  "2: Supervisor \n"
                  "3: Member\n")
            num = int(input("Select user: "******"Enter Email: ")
                password = input("Enter password: "******"Invalid Choice. Please Enter again: ")
                self.login()

        except Exception as e:
            print("Error", e)
            self.login()
Пример #5
0
def user_tag_remove(username):
    """
    Delete SINGLE tag associate with user
    :param username:
    :return:
    """
    if not auth(  # authenticate user
            app.config['SECRET_KEY'],
            request,
            username
    ):
        return response_unauthorised()
    try:
        assert username == request.view_args['username']

        try:
            tag = request.json['user_tag']
            tags = user.user_info(username)['user_tags']
            new_tags = tags.replace(tag, '')
            new_tags = util.tag_validator(new_tags)  # format tags
            user.update_user(username, tags=new_tags)
        except KeyError:
            return response_invalid()

        response_json = json_dict({"user_tags": new_tags}, indent=4)
        return Response(response_json, status=success_code, mimetype='application/json')

    except Exception as e:
        print(e)
        return response_unknown()
Пример #6
0
def driver(str):
    try:
        api_obj, usrName = auth()
        print("Logged in as:", usrName)
    except ValueError:
        print("Invalid keys or tokens.\nAuthentication Failed!!\n")
        print("Please checkout \"README.md\" and \"authentication.py\" file.")
        sys.exit()
    twat = []
    srch, tweets = fetch_tweets(api_obj, str)
    for strippin in tweets:
        texts = strippin.text
        anal_text = ' '.join(
            sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])| (\w+: / / \S+)", " ",
                texts).split())

        bob = TextBlob(anal_text)
        textiment = {'tweet': texts, 'sentiment': bob.sentiment.polarity}

        if strippin.retweet_count:
            twat.append(textiment)
        else:
            if textiment not in tweets:
                twat.append(textiment)
    get_Final(twat, srch)
Пример #7
0
    def post(self, *args, **kwargs):
        # verify account and password
        account = self.get_argument('account')
        passwd = self.get_argument('passwd')
        auth = verify.auth(account, passwd)

        # if pass, continue to get cf based recommendation
        if (str(auth) == 'err1' or str(auth) == 'err2'):
            info = "Wrong Password or Account"
            return self.render('index.html', info=info)

        else:
            user = [account, passwd, str(auth)]
            print("Verification Passed", auth)

        # send unique id to get recommenation of content
        id = auth
        topic = 'id'
        msg = id
        print("Start sending ID to Kafka")
        util.kafkasend(topic, msg)

        # receive recommendation content and return to front end
        print("Set Consumer")
        consumer = util.setConsumer('cf_item')
        print("Start Receive Kafka")
        while True:
            reco = util.kafkareceive(consumer)
            if (reco != None):
                break

        # receive 5 recommendation items
        #items_cf = ["Kimi no Na wa.", "Fullmetal Alchemist: Brotherhood", "Gintama°", "Steins;Gate", "Hunter x Hunter (2011)"]
        item_cf = reco
        items_cf = util.buildhtml(item_cf)

        # self.write("<h1>CF Recommendation</h1>")
        self.write(
            "<div class=\"container\"><header><p style=\"color:white border:1px\"><span></span><br /></p></header></div><div class=\"login-page\"><div class=\"form\"><div style=\"font-size:24\"><b> Welcome, <div id=\'username\' style=\"display:inline\">%s</div>!</b><br>We recommend the following shows. Click on a show you like to see similar recommendations!<br><br><table id=\'recommendations\'>"
            % (account))
        self.write(items_cf)
        self.write("</table></div></div></div>")

        return self.render("index.html", title="Recommendation", user=user)
Пример #8
0
def delete_user(username):
    """
    Delete a user
    :param username:
    :return:
    """
    assert username == request.view_args['username']
    if not auth(  # authenticate user
            app.config['SECRET_KEY'],
            request,
            username
    ):
        return response_unauthorised()

    try:
        user.delete_user(username)
        response_json = json_dict({"User deleted: ": username}, indent=4)
        return Response(response_json, status=success_code, mimetype='application/json')
    except Exception as e:
        print(e)
        return response_unknown()
Пример #9
0
def search():
    if auth():
        if request.method == "POST":
            book = request.form.get("book")
            catogry = request.form.get("catogry")
            book = book.title()
            result = db.execute(
                f"SELECT * FROM books WHERE {catogry} = '{book}'").fetchall()
            if len(result) == 0:
                flash("Book Not Found", "danger")
                return render_template(
                    "error.html",
                    message=
                    "Book You're Searching for is not available at the moment")
            return render_template("view.html", result=result)
        else:
            return render_template("search.html")
    else:
        flash("Login required", "danger")
        return render_template("error.html",
                               message="You need to be Logged in")
Пример #10
0
def user_update(username):
    assert username == request.view_args['username']
    if not auth(  # authenticate user
            app.config['SECRET_KEY'],
            request,
            username
    ):
        return response_unauthorised()

    try:
        json_request = request.json

        values = util.json_key(
            request,
            {
                "name": False,
                "avatar_path": False,
                "reward_points": False,
                "credit": False,
                "tags": False,
                "desc": False
            }
        )

        user.update_user(
            username,
            values['name'],
            values['avatar_path'],
            values['reward_points'],
            values['tags'],
            values['desc'],
            values['credit']
        )

        response_json = json_dict(values, indent=4)
        return Response(response_json, status=success_code, mimetype='application/json')
    except Exception as e:
        print(e)
        return response_unknown()
Пример #11
0
def create_post():
    """
    Create a new post
    :return:
    """
    try:

        try:  # Check parameters follow expected schema
            body_param = util.json_key(request,
                                       {
                                           "username": True,
                                           "message": True,
                                           "photo_path": False,
                                           "video_path": False,
                                           "post_tags": True
                                       })
        except:
            return response_invalid()

        if body_param['message'] == "" or body_param['post_tags'] == "":
            response_invalid()

        if not auth(app.config['SECRET_KEY'], request, body_param['username']):
            return response_unauthorised()

        post_id = post.create_post(
            body_param['username'],
            body_param['message'],
            0,
            util.tag_validator(body_param['post_tags']),  # format tags
            body_param['photo_path'],
            body_param['video_path']
        )
        response_json = json_dict({"post_id": post_id}, indent=4)
        return Response(response_json, status=created_code, mimetype='application/json')

    except Exception as e:
        print(e)
        return response_unknown()
Пример #12
0
def update_post_likes(post_id):
    """
    Update the likes associated with a post
    :param post_id:
    :return:
    """

    try:
        try:
            json_request = request.json
            username = json_request["username"]
        except:
            return response_invalid()
        if not auth(  # authenticate user
                app.config['SECRET_KEY'],
                request,
                username
        ):
            return response_unauthorised()

        assert post_id == request.view_args['post_id']

        # Get current likes
        try:
            current_likes = post.get_post(post_id)['likes']
        except:
            return response_notFound()
        new_likes = current_likes + 1
        post.update_post(
            post_id,
            likes=new_likes
        )
        response_json = json_dict({"post_likes": new_likes}, indent=4)
        return Response(response_json, status=success_code, mimetype='application/json')

    except Exception as e:
        print(e)
        return response_unknown()
Пример #13
0
def user_tags_clear(username):
    """
    Delete ALL tags associate with user
    :param username:
    :return:
    """

    if not auth(  # authenticate user
            app.config['SECRET_KEY'],
            request,
            username
    ):
        return response_unauthorised()

    try:
        assert username == request.view_args['username']

        user.update_user(username, tags="")
        response_json = flask.json.dumps({"Status": "Tags deleted"})
        return Response(response_json, status=success_code, mimetype='application/json')

    except Exception as e:
        print(e)
        return response_unknown()
Пример #14
0
 def __init__(self):
     self.service = auth()
Пример #15
0
console = logging.StreamHandler()
console.setLevel(logging.INFO)

# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')

# tell the handler to use this format
console.setFormatter(formatter)

# add the handler to the root logger
logging.getLogger('').addHandler(console)

logging.info('Starting')

# set the twitter authentication
twitter = auth()

# put all the users into table
put_users_in_table(twitter)

# sort all of the users
sort_users(9, 3)

# check the status of all the users
statuses(twitter)

spell_checker()

logging.info('Finished')

Пример #16
0
    ssh_key_gen.with_slaves()


def set_hostname():

    import set_hostname
    set_hostname.set_m1_hostname()
    set_hostname.set_m2_hostname()
    set_hostname.set_slaves_hostname()
    set_hostname.set_client_hostname()


user = input("Enter User name:\n")
passwd = input("Enter Password\n")

r = authentication.auth(user, passwd)

if r:

    menu.uper_menu()
    #set_ssh()
    #set_hostname()

    while True:
        os.system("touch hosts")
        os.system("clear")

        menu.menu()

        choice = int(input("Enter your choice"))
Пример #17
0
import sys
from re import sub
from textblob import TextBlob
from authentication import auth
from getTweets import fetch_tweets
from final_hit import get_em

if __name__ == '__main__':
    try:
        api_obj, usrName = auth()
        print("Logged in as:", usrName)
    except ValueError:
        print("Invalid keys or tokens.\nAuthentication Failed!!\n")
        print("Please checkout \"README.md\" and \"authentication.py\" file.")
        sys.exit()
    twat = []
    srch, tweets = fetch_tweets(api_obj)
    for strippin in tweets:
        texts = strippin.text
        anal_text = ' '.join(
            sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])| (\w+: / / \S+)", " ",
                texts).split())

        bob = TextBlob(anal_text)
        textiment = {'text': texts, 'sentiment': bob.sentiment.polarity}

        if strippin.retweet_count:
            twat.append(textiment)
        else:
            if textiment not in tweets:
                twat.append(textiment)
Пример #18
0
def login():
    k = authentication.auth()
    if k.auth(user, password):
        return [user, k.UserID]
    else:
        return False
Пример #19
0
 def __init__(self):
     self.user_id = 'me'
     self.service = auth()
Пример #20
0
def runAuthTest():
    service = auth()
    return 'auth ok ;)'
Пример #21
0
def get_auth():
    # Get Authentication
    return authentication.auth()
Пример #22
0
    config = None
    if args.config:
        config = configparser.ConfigParser()
        config.read(args.config)
        args.spreadsheet_id = config['DEFAULT']['spreadsheet_id']
        args.sheet_name = config['DEFAULT']['sheet_name']
        args.sheet_id = config['DEFAULT']['sheet_id']
    if not args.report:
        args.report = get_full_report()
    if not (args.sheet_name or args.sheet_id or args.spreadsheet_id):
        print('specify a config file or spreadsheet_id, sheet_id, sheet_name')
        sys.exit()

    service = googleapiclient.discovery.build('sheets',
                                              'v4',
                                              credentials=auth())
    newly_failing, newly_passing, passing_removed = \
        update_spreadsheet(service, args.report, args.spreadsheet_id,
                           args.sheet_id, args.sheet_name)

    if newly_failing:
        print("Newly failing tests added: ")
        for test in newly_failing:
            print(test)
    if newly_passing:
        print("\nNewly passing tests: ")
        for test in newly_passing:
            print(test)
    if passing_removed:
        print("\nPreviously passing tests removed: ")
        for test in passing_removed:
Пример #23
0
def book(isbn):
    catogry = "isbn"
    print(f"SELECT * FROM books WHERE {catogry} = '{isbn}'")
    if auth():
        if request.method == "POST":
            user_id = session["user_id"]
            book_result = db.execute(
                f"SELECT * FROM books WHERE {catogry} = '{isbn}'").fetchone()
            if not book_result:
                flash("Book Not Found", "danger")
                return render_template(
                    "error.html",
                    message="Book You're Searching for does not found")

            result = db.execute(
                f"SELECT * FROM reviews WHERE user_id = {user_id} AND book_id = {book_result[0]}"
            ).fetchone()

            if result:
                flash("Review Error", "danger")
                return render_template(
                    "error.html",
                    message=
                    "You already made your review. You can't add more review")

            rating = request.form.get("rating")
            review = request.form.get("review")

            db.execute(
                f"INSERT INTO reviews(user_id, book_id, comment, rating) VALUES ({user_id}, {book_result[0]}, '{review}', {rating})"
            )
            db.commit()
            res = requests.get(
                "https://www.goodreads.com/book/review_counts.json",
                params={
                    "key": "LvAO4PSdsqCfYdRuAcmYUw",
                    "isbns": isbn
                })
            book = res.json()
            book_info = book["books"][0]
            reviews = db.execute(
                f"SELECT users.name, comment, rating, to_char(time, 'DD Mon YY - HH24:MI:SS') as time from users INNER JOIN reviews ON users.id = reviews.user_id WHERE book_id = {book_result[0]} ORDER BY time"
            ).fetchall()
            return render_template("book_isbn.html",
                                   reviews=reviews,
                                   book_Info=book_info,
                                   book_result=book_result)
        else:
            book_result = db.execute(
                f"SELECT * FROM books WHERE {catogry} = '{isbn}'").fetchone()
            if not book_result:
                flash("Book Not Found", "danger")
                return render_template(
                    "error.html",
                    message="Book You're Searching for does not found")
            res = requests.get(
                "https://www.goodreads.com/book/review_counts.json",
                params={
                    "key": "LvAO4PSdsqCfYdRuAcmYUw",
                    "isbns": isbn
                })
            book = res.json()
            book_info = book["books"][0]
            reviews = db.execute(
                f"SELECT users.name, comment, rating, to_char(time, 'DD Mon YY - HH24:MI:SS') as time from users INNER JOIN reviews ON users.id = reviews.user_id WHERE book_id = {book_result[0]} ORDER BY time"
            ).fetchall()
            print(reviews)
            return render_template("book_isbn.html",
                                   reviews=reviews,
                                   book_Info=book_info,
                                   book_result=book_result)

    else:
        flash("Login required", "danger")
        return render_template(
            "error.html", message="You need to be logged in to view this page")
Пример #24
0
def login():
	k = authentication.auth()
	if k.auth(user, password):
		return [user, k.UserID]
	else:
		return False
Пример #25
0
 def __init__(self):
     self.user_id = 'me'
     self.service = auth()
     debug.createLog()