示例#1
0
    def login(self, username, password):
        try:
            # Verificare existenta user
            cursor = self.db.cursor()
            hashed = cursor.callproc('get_password', (username, ''))[1]
            
            if hashed == None:
                return None

            # Verificare parola
            if not security.check_encrypted_password(password, hashed):
                return None

            # Verificare cont activ
            is_active = cursor.callproc('is_active', (username, ''))[1]

            if not is_active:
                return None

            # Stergere sesiuni vechi
            cursor.callproc('delete_sessions', (username, ))

            # Adaugare sesiune
            token = security.login_token(username)
            expiration_date = cursor.callproc('create_session', (username, token, ''))[2]

            return (token, expiration_date)
        except Exception as e:
            raise Exception(error.Error.new(e))
        finally:
            cursor.close()
def test_submission(reddit_username, reddit_password):

    hash = encrypt_password(reddit_password)
    print("Checking if password was encrypted successfully...")
    if (check_encrypted_password(reddit_password, hash)):
        print("Password successfully encrypted.")
    else:
        print("Uh oh, password was not encrypted correctly. Exiting...")
        exit(1)

    # Bot Creation
    print("Connecting to Reddit...")
    reddit = praw.Reddit(
        client_id=reddit_client_id,
        client_secret=reddit_client_secret,
        user_agent='<console:ncaa_stream_app:0.0.1 (by /u/sdsu-stream-bot)>',
        username=reddit_username,
        password=reddit_password)
    subreddit = reddit.subreddit('SecretSharedDawn')

    for submission in subreddit.stream.submissions():
        if "test post" in submission.title:
            print("Submission found. Replying...")
            reply_text = "hello i am a bot!"
            submission.reply(reply_text)
            print("Replied to post.")
            break
        else:
            continue
示例#3
0
def userAuth():
    try:
        conn = mysql.connect()
        cur = conn.cursor(pymysql.cursors.DictCursor)
        cur.execute("select password,role from user where email = '" +
                    request.json['userid'] + "';")
        rows = cur.fetchall()
        if len(rows) == 0:
            response = jsonify('InvalidUser')
        else:
            check = auth.check_encrypted_password(request.json['password'],
                                                  rows[0]['password'])
            if check == True:
                response = {
                    "key": generateKey(request.json['userid']),
                    "role": rows[0]['role']
                }
                response = jsonify(response)
                print(response)
                if response == False:
                    response = jsonify('False')
            else:
                response = jsonify('AuthenticationFailed')
        response.status_code = 200
        return response
    except Exception as e:
        response = jsonify('Error occured')
        response.status_code = 500
        print(e)
        return response
    finally:
        conn.close()
        cur.close()
示例#4
0
def changePassword():
    userid = request.args.get('userid')
    token = request.args.get('tok')
    try:
        if apiAuth.apiAuth(token, userid) == True:
            conn = mysql.connect()
            cur = conn.cursor(pymysql.cursors.DictCursor)
            _req = request.json
            cur.execute("select password from user where email = %s;",
                        (userid))
            rows = cur.fetchall()
            check = auth.check_encrypted_password(_req['curPass'],
                                                  rows[0]['password'])
            if check == True:
                _encrpass = auth.encrypt_password(_req['newPass'])
                cur.execute("update user set password = %s where email = %s",
                            (_encrpass, userid))
                conn.commit()
                response = jsonify("success")
            elif check == False:
                response = jsonify("invalid")
                response.status_code = 200
            return response
        else:
            response = jsonify('Unauthorized Access')
            response.status_code = 401
            return response
    except Exception as e:
        print(e)
        response = jsonify('Server Error')
        response.status_code = 500
        return response
示例#5
0
def login():
    username = input('Username: '******'Login Successful!\n')
        return user_info
示例#6
0
def verify_password(payload: AccountPasswordSchema,
                    Authorize: AuthJWT = Depends(),
                    db: Session = Depends(get_db)):
    Authorize.jwt_required()
    existing_acct = db.query(Account).filter_by(uuid=payload.uuid).first()
    password_valid = check_encrypted_password(payload.old_password,
                                              existing_acct.password)
    if password_valid is True:
        return True
    else:
        raise HTTPException(status_code=403, detail=f"Password is incorrect")
    def post(self):

        data = _user_parser.parse_args()
        user = UserModel.find_by_username(data['username'])
        if user and check_encrypted_password(data['password'], user.password):
            access_token = create_access_token(identity=user, fresh=True)
            refresh_token = create_refresh_token(user)
            return {
                "access_token": access_token,
                "refresh_token": refresh_token
            }, 200

        return {"message": "invalid credentials"}, 401
示例#8
0
    def post(self):

        data = _user_parser.parse_args()
        user = UserModel.find_by_username(data['username'])
        # this is what the `authenticate()` function did in security.py
        if user and check_encrypted_password(data['password'], user.password):
            # identity= is what the identity() function did in security.py—now stored in the JWT
            access_token = create_access_token(identity=user.id, fresh=True)
            refresh_token = create_refresh_token(user.id)
            return {
                'access_token': access_token,
                'refresh_token': refresh_token
            }, 200

        return {"message": "Invalid Credentials!"}, 401
示例#9
0
    def login(self, username, password):
        cursor = self.db.cursor(pymysql.cursors.DictCursor)

        if cursor.execute(
                '''
            SELECT * FROM users
            WHERE username = %s
            ''', (username, )) != 1:
            return False

        user = cursor.fetchone()

        if user == None:
            return False

        return security.check_encrypted_password(password, user['password'])
示例#10
0
def login():
    if (request.method == 'POST'):
        username = request.form.get('username')
        password = request.form.get('password')

        user = Users.query.filter_by(username=username).first()
        if user:
            if check_encrypted_password(password, user.password):
                login_user(user, remember=request.form.get('remember'))
                return redirect("/dashboard")
            else:
                return "problem in password"
        else:
            return "No such user"

    return render_template("login.html")
示例#11
0
    def post(self):
        data = self.parser.parse_args()
        # read from database to find the user and then check the password
        user = UserModel.find_by_username(data['username'])

        if user and check_encrypted_password(data['password'], user.password):
            # when authenticated, return a fresh access token and a refresh token
            access_token = create_access_token(identity=user.role,
                                               fresh=True,
                                               expires_delta=False)
            refresh_token = create_refresh_token(user.id)
            return {
                'access_token': access_token,
                'refresh_token': refresh_token
            }, 200

        return {"message": "Invalid Credentials!"}, 401
示例#12
0
def admin_login():
    username = input('Username: '******'../GeneratedFiles/AdminLogin.json'
    if os.path.exists(filename):
        try:
            with open(filename) as f:
                users_dict = json.load(f)
            if username in users_dict and check_encrypted_password(
                    pt_password, users_dict[username]):
                print(f'Login Successful!')
                return True
            else:
                print('Invalid Username or Password, Please try again.\n')
        except UnboundLocalError:
            print('Not an admin. Please try again.\n')
    else:
        print('Incorrect Username or Password, Please try again\n')
示例#13
0
def authorize_basic(account: AccountBasicLoginSchema,
                    Authorize: AuthJWT = Depends(),
                    db: Session = Depends(get_db)):
    existing_acct = db.query(Account).filter_by(email=account.email).first()
    if existing_acct is None:
        raise HTTPException(status_code=403,
                            detail=f"E-mail or password is invalid!")
    verified_pw = check_encrypted_password(account.password,
                                           existing_acct.password)
    if verified_pw is False:
        raise HTTPException(status_code=403,
                            detail=f"E-mail or password is invalid!")
    if existing_acct.is_verified is False:
        raise HTTPException(
            status_code=403,
            detail=f"Account has not been verified. Please check your e-mail.")
    create_access_and_refresh_tokens(str(existing_acct.uuid), Authorize)
    return existing_acct
示例#14
0
    def post(self):
        try:
            data = user_login_schema.load(request.get_json())
        except ValidationError as err:
            return err.messages, 400

        user = UserModel.find_by_email(data['email'])

        if not user:
            return {
                "message": "There is no account associated with that email"
            }, 401

        # Compare the encrypted password in the database to the data passed in from the user input
        # If passwords match, return an access token and a refresh token to the user
        if check_encrypted_password(data['password'], user.password):

            access_token = create_access_token(identity=user.uuid, fresh=True)
            refresh_token = create_refresh_token(identity=user.uuid)

            @after_this_request
            def set_response_cookies(response):
                set_access_cookies(response, access_token)
                set_refresh_cookies(response, refresh_token)
                return response

            user.last_active = datetime.utcnow()
            user.save_to_db()
            return {
                "message": "User Login successful!",
                "u": user.uuid,
                "user_type": user.user_type,
                "is_confirmed": user.is_confirmed,
                "is_initial_setup_complete": user.is_initial_setup_complete
            }, 200

        return {"message": "Invalid Credentials!"}, 401
示例#15
0
    def post(self):
        try:
            data = user_reset_password_schema.load(request.get_json())
        except ValidationError as err:
            return err.messages, 400

        user = UserModel.find_by_uuid(get_jwt_identity())

        # Compare the encrypted password in the database to the data passed in from the user input
        # If passwords match, return an access token and a refresh token to the user
        if check_encrypted_password(data['old_password'], user.password):
            password = encrypt_password(data['new_password'])
            user.password = password
            try:
                user.save_to_db()
            except:
                return {"message": GENERIC_ERROR_HAS_OCCURRED}, 400
        else:
            return {
                "message":
                "The old password you supplied does not match our records. Please try again."
            }, 400

        return {"message": "Password update successful!"}, 200
示例#16
0
def post_sdsu_stream(reddit_username, reddit_password):

    hash = encrypt_password(reddit_password)
    print("Checking if password was encrypted successfully...\U0001F928")
    if (check_encrypted_password(reddit_password, hash)):
        print("Password successfully encrypted.")
    else:
        print("Uh oh, password was not encrypted correctly. Exiting...\n")
        exit(1)

    # Bot Creation
    print("Seeing if we can connect to reddit...\U0001F914")
    reddit = praw.Reddit(
        client_id='oRDWYVEIfzVDAg',
        client_secret='DkfD4aB3VvrXExaJbSALR_hCmlc',
        user_agent='<console:ncaa_stream_app:0.0.1 (by /u/sdsu-stream-bot)>',
        username=reddit_username,
        password=reddit_password)
    # Check to see if post is in read only mode
    # We want it to be false
    print("Wow we connected to reddit awesome")
    print("Checking if Reddit praw obj is in read only mode...")
    if (reddit.read_only == True):
        print("Uh oh, looks like Reddit is in read only mode. Exiting...\n")
        exit(1)
    else:
        print("Reddit is not in read only mode. Continuing...\n")

    if check_if_game_today():

        subreddit = reddit.subreddit('ncaaBBallStreams')

        for submission in subreddit.stream.submissions():
            # do something with submission

            if "San Diego St" in submission.title:
                title = submission.title.split(":")
                game_title_with_time = title[1]
                game_title_with_time.lstrip()
                game_title = game_title_with_time.split("[")
                game_title_no_time = game_title[0]
                game_title_no_time.strip()
                # Get comments / create comment in submission
                print("Submission found. Replying with link...")
                print(game_title_no_time)
                reply_text = "**HD** | ["+game_title_no_time + \
                    "](https://www.viprow.me/sports-basketball-online) | Clicks: 2 | English | Disable Adblock"
                print(reply_text)
                submission.reply(reply_text)
                print(
                    "Replied to submission. \U0001F60D My job here is done. Going to sleep for 24 hours zzz...\U0001F634 \n"
                )
                create_progress_bar(86400)
                break
            else:
                continue

    else:
        print(
            "Game not found! Going to sleep for 2 hours zzz... \U0001F634 \n")
        create_progress_bar(7200)