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
Example #2
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
Example #3
0
 def validate_password(self, key, password):
     if not password:
         raise AssertionError('Password not provided')
     if not re.match('\\d.*[A-Z]|[A-Z].*\\d', password):
         raise AssertionError('Password must contain 1 capital letter and 1 number')
     if len(password) < 8 or len(password) > 20:
         raise AssertionError('Password must be between 8 and 20 characters')
     return encrypt_password(password)
Example #4
0
 def register(self, username, password, email, first_name, last_name):
     try: 
         cursor = self.db.cursor()
         cursor.callproc('create_user', [username, security.encrypt_password(password), email, first_name, last_name, security.activation_token()])
     except Exception as e:
         raise Exception(error.Error.new(e))
     finally:
         cursor.close()
Example #5
0
 def register_user(data) -> User:
     user = User()
     user._id = UserModel.getcounter()
     user.email = data['email']
     user.username = data['username']
     user.password = encrypt_password(data['password'])
     user.role = data['role']
     user.save()
     return user
    def post(self):
        data = _user_parser.parse_args()
        data.password = encrypt_password(data.password)

        if UserModel.find_by_username(data['username']):
            return {"message": f"User {username} already exists."}, 400

        user = UserModel(**data)
        user.save_to_db()

        return {"message": "User created successfully."}, 201
Example #7
0
def addadminuser():
    adKey = "v(i'7#5x>~}>n.j3H:F)*T),D-Er~1L6g|RPtRI$S)1VSvL/u/sanFP0PZ<9S0q"
    uKey = "17TZ27vRus"
    try:
        conn = mysql.connect()
        cur = conn.cursor(pymysql.cursors.DictCursor)
        _req = request.json
        if _req['role'] == "AD":
            if adKey == _req['key']:
                _encrpass = auth.encrypt_password(_req['password'])
                cur.execute(
                    "insert into user(email, firstName,lastName,password,phone,init,role) values(%s, %s, %s, %s, %s, %s, %s)",
                    (_req['userid'], _req['fname'], _req['lname'], _encrpass,
                     _req['phone'], _req['initial'], _req['role']))
                conn.commit()
                resp = jsonify('User added successfully')
                resp.status_code = 200
            else:
                resp = jsonify('Incorrect Key')
                resp.status_code = 200
        elif _req['role'] == "DE" or _req['role'] == "AP":
            if uKey == _req['key']:
                _encrpass = auth.encrypt_password(_req['password'])
                cur.execute(
                    "insert into user(email, firstName,lastName,password,phone,init,role) values(%s, %s, %s, %s, %s, %s, %s)",
                    (_req['userid'], _req['fname'], _req['lname'], _encrpass,
                     _req['phone'], _req['initial'], _req['role']))
                conn.commit()
                resp = jsonify('User added successfully')
                resp.status_code = 200
            else:
                resp = jsonify('Incorrect Key')
                resp.status_code = 200
        return resp
    except Exception as e:
        resp = jsonify(e)
        resp.status_code = 500
        return resp
    finally:
        cur.close()
        conn.close()
def register():
    if (request.method == 'POST'):
        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')
        hashpassword = encrypt_password(password)

        entry = Users(username=username, email=email, password=hashpassword)
        db.session.add(entry)
        db.session.commit()
        return redirect("/login")

    return render_template("register.html")
def create_account(account: AccountCreateRequestSchema,
                   Authorize: AuthJWT = Depends(),
                   db: Session = Depends(get_db)):
    check_for_existing_username_or_email(account, db)
    if account.password is not None:
        check_valid_password(account.password)
        account.password = encrypt_password(account.password)
    account = Account(**account.dict())
    db.add(account)
    db.commit()
    create_account_settings(account.uuid, db)
    create_access_and_refresh_tokens(str(account.uuid), Authorize)
    return account
Example #10
0
    def create_user(self, username, password, firstname, lastname, weight, age,
                    gender):
        self.db.cursor().execute(
            '''
            INSERT INTO users
            (username, password, firstname, lastname, weight, age, gender)
            VALUES(%s, %s, %s, %s, %s, %s, %s)
            ''', (username, security.encrypt_password(password), firstname,
                  lastname, weight, age, gender))

        self.add_training(username, '0', '0', '0', '0', '0')

        self.db.commit()
Example #11
0
def register():
    username = request.form.get('username')
    password = request.form.get('password')
    email = request.form.get('email')
    decipher_password = decrypt_password(password)
    result = validate_register(username, decipher_password, email)
    if result is True:
        username, email = username.strip(), email.strip()
        encipher_password = encrypt_password(username, decipher_password)
        status = _save(username, encipher_password, email)
        if status:
            return render_200(_('register successfully'))
        return render_400(_('register failed'))
    return result
Example #12
0
    def update_user(data, username) -> User:

        exist_user = User.objects(username=username).first()

        if exist_user:
            if data['email']:
                exist_user.email = data['email']
            if data['username']:
                exist_user.username = data['username']
            if data['password']:
                exist_user.password = encrypt_password(data['password'])
            if data['role']:
                exist_user.role = data['role']

            updated_user = exist_user.save()
            return updated_user

        return exist_user
Example #13
0
def forgotPassword():
    userid = request.args.get('userid')
    try:
        conn = mysql.connect()
        cur = conn.cursor(pymysql.cursors.DictCursor)
        _req = request.json
        _encrpass = auth.encrypt_password(_req['newPass'])
        print(_encrpass)
        cur.execute("update user set password = %s where email = %s",
                    (_encrpass, userid))
        conn.commit()
        response = jsonify("success")
        return response
    except Exception as e:
        print(e)
        response = jsonify('Server Er7ror')
        response.status_code = 500
        return response
def update_password(uuid,
                    partial_account: AccountNewPasswordSchema,
                    Authorize: AuthJWT = Depends(),
                    db: Session = Depends(get_db)):
    try:
        Authorize.jwt_required()
        check_matching_user(uuid, Authorize)
        account = db.query(Account).filter_by(uuid=uuid).first()
        if partial_account.password is None:
            raise HTTPException(status_code=400, detail=f"Password is missing")
        else:
            check_valid_password(partial_account.password)
            account.password = encrypt_password(partial_account.password)
        db.merge(account)
        db.commit()
        db.refresh(account)
    except Exception as e:
        logging.warning(e)
        raise e
    return account
Example #15
0
def create_account():

    #check username valid
    #check password valid
    username = bottle.request.forms['username']
    raw_password1 = bottle.request.forms['password1']
    raw_password2 = bottle.request.forms['password2']

    valid_username = interface.check_valid_username(username)
    valid_password = interface.check_valid_password(raw_password1,
                                                    raw_password2)

    if not valid_username:
        set_cookie('error', 'That username is taken.')
        bottle.redirect('/')

    if not valid_password:
        set_cookie('error', 'That password is invalid.')
        bottle.redirect('/')

    #check account is authentic
    #check user has commented on photo
    #--get photo url from cookie
    #--check comments
    valid_account = insta.check_valid_account(username,
                                              get_cookie('auth_image_url'))

    if valid_account:
        #encrypt pass
        password = security.encrypt_password(raw_password1)
        #creat accounte
        interface.create_account(username, password)
        #login
        set_cookie('username', username)
    else:
        set_cookie(
            'error',
            'Please comment on the photo before attempting to validate account.'
        )

    bottle.redirect('/')
Example #16
0
    def post(self, token):
        try:
            data = user_forgot_password_schema.load(request.get_json())
        except ValidationError as err:
            return err.messages, 400

        try:
            decoded_token = decode_token(token)
        except:
            return {"message": "This reset token is invalid."}, 400

        # if the time (now) is less than the time of expiry
        # the token is still valid
        # else, the token is invalid and they must request a new one
        now = time()
        expiry = decoded_token['exp']

        if expiry < now:
            return {
                "message":
                "This link has expired. Please request a new password reset"
            }, 400

        revoke_token(decoded_token['jti'])

        user = UserModel.find_by_uuid(decoded_token['identity'])

        if user:
            password = encrypt_password(data['password'])
            user.password = password
            try:
                user.save_to_db()
            except:
                return {"message": GENERIC_ERROR_HAS_OCCURRED}, 500

            return {"message": "Password reset successful!"}, 200
        else:
            return {"message": "This is not a valid request."}, 400

        return {"message": GENERIC_ERROR_HAS_OCCURRED}, 400
    def post(self):
        try:
            request_json = request.get_json()
            request_data = user_register_schema.load(request_json)
        except ValidationError as err:
            return err.messages, 400

        if UserModel.find_by_email(request_data['email']):
            return {"message": REGISTER_ERROR_EMAIL_ALREADY_IN_USE}, 400

        name = request_data['name']
        email = request_data['email']
        password = encrypt_password(request_data['password'])
        uuid = str(uuid4())

        user = UserModel(name=name, email=email, password=password, uuid=uuid)

        verification_code = generate_verification_code(user_uuid=user.uuid)

        try:
            Thread(target=send_confirmation_email, args=(
                user.email, verification_code)).start()
        except:
            return {"message": GENERIC_ERROR_HAS_OCCURRED}, 500

        try:
            user.save_to_db()
        except:
            return {"message": GENERIC_ERROR_HAS_OCCURRED}, 400

        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

        return {"message": "Account created successfully, a confirmation email is on its way!", "u": user.uuid, "first_login": True}, 201
Example #18
0
def adduser():
    try:
        conn = mysql.connect()
        cur = conn.cursor(pymysql.cursors.DictCursor)
        _req = request.json
        print(_req)
        _encrpass = auth.encrypt_password(_req['password'])
        cur.execute(
            "insert into user(email, firstName,lastName,password,phone,init,role) values(%s, %s, %s, %s, %s, %s, %s)",
            (_req['userid'], _req['fname'], _req['lname'], _encrpass,
             _req['phone'], _req['initial'], 'user'))
        conn.commit()
        resp = jsonify('User added successfully')
        resp.status_code = 200
        return resp
    except Exception as e:
        resp = jsonify(e)
        resp.status_code = 500
        return resp
    finally:
        cur.close()
        conn.close()
Example #19
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
def generate_str_for_hash(username: str, curr_time: datetime):
    one_rand_num = random.uniform(1, 101)
    password_reset_hash = encrypt_password(username + str(curr_time) + str(
        random.uniform(1, one_rand_num) + random.uniform(1, one_rand_num) +
        random.uniform(1, one_rand_num)))
    return password_reset_hash
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)
Example #22
0
 def setup_method(self, method):
     """ setup any state tied to the execution of the given method in a
     class.  setup_method is invoked for every test method of a class.
     """
     os.environ['DATABASE_URL'] = 'sqlite:////tmp/test.db'
     from cagenix import db
     from cagenix.users.models import User
     from cagenix.practices.models import Practice
     from cagenix.patients.models import Patient
     self.practice = Practice(practice_name='Cookie Dental Clinic', address_one='123 Cookie Lane', city='Cookieville', state='TN', zip_code='37037', phone='+16155555555', active=True)
     db.session.add(self.practice)
     db.session.commit()
     self.user = User(first_name='Chocolate', last_name='Chip', email='*****@*****.**', activation_code='DPJE3XFBVM271HC', password=encrypt_password('cookies'))
     self.user.gen_secret()
     self.user.activated = True
     db.session.add(self.user)
     db.session.commit()
     self.patient = Patient(first_name='Chocolate', last_name='Chip', address_one='123 Cookie Lane', city='Cookieville', state='TN', zip_code='37201', email='[email protected]', practice=self.practice, dentist=self.user)
     db.session.add(self.patient)
     db.session.commit()
Example #23
0
    def setup_method(self, method):
        """ setup any state tied to the execution of the given method in a
        class.  setup_method is invoked for every test method of a class.
        """
        os.environ['DATABASE_URL'] = 'sqlite:////tmp/test.db'
        from cagenix import db
        from cagenix.users.models import User

        self.user = User(first_name='Chocolate', last_name='Chip', email='*****@*****.**', activation_code='DPJE3XFBVM271HC', password=encrypt_password('cookies'))
        self.user.gen_secret()
        db.session.add(self.user)
        db.session.commit()
Example #24
0
 def save_password(self, password):
     self.password = security.encrypt_password(self.username, password)
    def post():
        data = RegisterPsychologist.parser.parse_args()

        if PersonModel.find_by_email(data['email']):
            return {"message": "A user with that email already exists"}, 400

        if PsychologistModel.find_by_crp(data['crp']):
            return {"message": "A user with that crp already exists"}, 422

        if TelephoneModel.find_by_number(data['number']):
            return {"message": "A user with that number already exists"}, 400

        if len(data['name']) <= 1:
            return {"message": "Type a valid name"}

        if len(data['crp']) != 7 or not data['crp'].isdigit():
            return {"message": "Type a valid crp"}

        if data['registry_number']:
            if len(data["registry_number"]) > 14:
                return {"message": "Type a valid registry_number"}

        if data['password']:
            if not any(char.isdigit() for char in data['password']):
                return {"message": "The password needs one digit, at least"}

            if len(data['password']) < 7:
                return {"message": "The password needs 7 characters, at least"}

            if data['password'].islower():
                return {
                    "message":
                    "The password needs one upper character, at least"
                }

            if data['password'].isupper():
                return {
                    "message":
                    "The password needs one lower character, at least"
                }

            if not data['password'].isalnum():
                return {
                    "message":
                    "The password does not support symbols, special characters and empty spaces"
                }

            if data['password'].isdigit():
                return {"message": "The password does not to be only numbers"}

            if data['password'].isspace():
                return {
                    "message":
                    "The password does not to be only blank characters"
                }

        if len(data['number']) > 15 or len(
                data['number']) < 8 or not data['number'].isdigit():
            return {"message": "Type a valid telephone_number"}

        if str(data['telephone_type'].lower()) != str("residencial") and str(data['telephone_type'].lower()) != str("pessoal") \
                and str(data['telephone_type'].lower()) != str("comercial"):
            return {"message": "Type a valid telephone_type"}

        new_person = PersonModel(data['name'], data['email'])
        new_person.save_to_db()

        new_telephone = TelephoneModel(data['number'], data['telephone_type'],
                                       new_person.id)
        new_telephone.save_to_db()

        password_crip = encrypt_password(data['password'])

        new_psychologist = PsychologistModel(data['crp'], password_crip,
                                             data['date_of_birth'],
                                             new_person.id)
        new_psychologist.save_to_db()

        if not HospitalModel.find_by_registry_number("4002"):
            new_hospital_person = PersonModel("Hospital da Crianca",
                                              "*****@*****.**")
            new_hospital_person.save_to_db()

            new_hospital = HospitalModel("4002", "HOSPITAL DA CRIANCA LTDA",
                                         new_hospital_person.id)
            new_hospital.save_to_db()

            new_psychologist_hospital = PsychologistHospitalModel(
                new_hospital.registry_number, new_psychologist.crp)
            new_psychologist_hospital.save_to_db()

        else:
            hosp = HospitalModel.find_by_registry_number("4002")
            new_psychologist_hospital = PsychologistHospitalModel(
                hosp.registry_number, new_psychologist.crp)
            new_psychologist_hospital.save_to_db()

        return {"message": "User created successfully."}, 201
Example #26
0
def new_user():
    bank_id = int()
    while True:
        has_bank = input(
            'Are you currently a member at a bank? (Yes/No) ').upper().strip()
        if has_bank == 'YES' or has_bank == 'Y':
            bank_name = input(
                'What is the name of your bank? ').upper().strip()
            bank_location = input(
                'Where is your bank located? ').upper().strip()
            bank = Bank(bank_name, bank_location)
            try:
                if check_bank_exists(bank):
                    bank_id = bank.bank_id
                    break
                else:
                    print(f'{bank_name} is not registered with us.')
                    continue
            except IndexError:
                print(
                    'Internal Error. Please contact your system administrator for help resolving this issue.'
                )
                return 0
        else:
            print(
                'Please register with a bank before accessing this application.'
            )
            return 0
    while True:
        first_name = input('First Name: ').rstrip().upper()
        if name_validation(first_name):
            break
        else:
            continue
    while True:
        last_name = input('Last Name: ').rstrip().upper()
        if name_validation(last_name):
            break
        else:
            continue
    while True:
        username = input('Username: '******'Username {username} already exists, please try a different one'
            )
            continue
        else:
            break
    while True:
        pt_password = getpass.getpass()
        print('Please confirm your password')
        confirm_password = getpass.getpass()
        if pt_password == confirm_password:
            password = encrypt_password(pt_password)
            break
        else:
            print('Passwords do not match. Please try again')
            continue
    while True:
        dob = input('Date of Birth (Month-Day-Year): ').strip().split('-')
        try:
            dob = datetime.date(int(dob[2]), int(dob[0]), int(dob[1]))
            break
        except ValueError:
            print(
                'Date of Birth not entered in correct format. Please try again.'
            )
            continue
    while True:
        ssn = input('SSN (###-##-####): ').strip()
        if ssn_validation(ssn):
            break
        else:
            print("SSN is not valid. Please enter in specified format.")
            continue
    while True:
        email = str(input('Email: ')).lower().strip()
        if email_validation(email):
            break
        else:
            print(f'{email} is not a valid email address, please try again.')
            continue
    print(f'\nYour username is: {username}')
    user = User(first_name, last_name, username, password, dob, ssn, email,
                bank_id)
    insert_user(user)
    return user
Example #27
0
    def put(self, crp):
        data = EditPsychologist.parser.parse_args()
        psychologist = PsychologistModel.find_by_crp(crp)

        if psychologist:
            if data['name']:
                if len(data['name']) <= 1:
                    return {"message": "Type a valid name"}
                psychologist.PERSON.name = data['name']

            if data['email']:
                psychologist.PERSON.email = data['email']

            if data['number']:
                if len(data['number']) > 15 or len(
                        data['number']) < 8 or not data['number'].isdigit():
                    return {"message": "Type a valid telephone_number"}
                psychologist.PERSON.telephones[0].number = data['number']

            if data['telephone_type']:
                if str(data['telephone_type'].lower()) != str("residencial") and str(
                        data['telephone_type'].lower()) != str("pessoal") \
                        and str(data['telephone_type'].lower()) != str("comercial"):
                    return {"message": "Type a valid telephone_type"}
                psychologist.PERSON.telephones[0].telephone_type = data[
                    'telephone_type']

            if data['date_of_birth']:
                psychologist.date_of_birth = data['date_of_birth']

            if data['password']:
                if not any(char.isdigit() for char in data['password']):
                    return {
                        "message": "The password needs one digit, at least"
                    }

                if len(data['password']) < 7:
                    return {
                        "message": "The password needs 7 characters, at least"
                    }

                if data['password'].islower():
                    return {
                        "message":
                        "The password needs one upper character, at least"
                    }

                if data['password'].isupper():
                    return {
                        "message":
                        "The password needs one lower character, at least"
                    }

                if not data['password'].isalnum():
                    return {
                        "message":
                        "The password does not support symbols, special characters and empty spaces"
                    }

                if data['password'].isdigit():
                    return {
                        "message": "The password does not to be only numbers"
                    }

                password_crip = encrypt_password(data['password'])
                psychologist.password = password_crip
            # if data['registry_number']:
            #     psychologist.hospital_psychologists[0].hospital.registry_number = data['registry_number']
            # if data['social_reason']:
            #     psychologist.hospital_psychologists[0].hospital.social_reason = data['social_reason']

            if data['crp']:
                return {'message': 'You cannot change the crp'}

        else:
            return {'message': 'User not found.'}, 404

        psychologist.save_to_db()

        return {'message': 'User updated'}, 200