Example #1
0
    def verify_user(self):
        attempts = 3
        self.user_entry = input("\nUsername: "******"Password: "******"secret.txt", "r") as f:
            for line in f:
                if line.strip():
                    key, value = [x.strip() for x in line.strip().split(':', 1)]
                    if bcrypt_sha256.verify(pass_entry, value) and self.user_entry in key:
                        print(f"\n[+] Welcome {self.user_entry}!")
                        return True    
                    elif not bcrypt_sha256.verify(pass_entry, value) or self.user_entry not in key:
                        while attempts > 0:
                            print("[-] Invalid Username or Password")
                            self.user_entry = input("Username: "******"Password: "******"[-] Too Many Password Attempts. Goodbye.")
                                exit(0)
                            if bcrypt_sha256.verify(pass_entry, value):
                                print(f"\n[+] Welcome {self.user_entry}!")
                                return True    
            f.close()
Example #2
0
File: auth.py Project: Rainism/CTFd
    def login():
        if request.method == 'POST':
            errors = []
            # team = Teams.query.filter_by(name=request.form['name'], password=sha512(request.form['password'])).first()
            team = Teams.query.filter_by(name=request.form['name']).first()
            if team and bcrypt_sha256.verify(request.form['password'],
                                             team.password):
                # session.regenerate() # NO SESSION FIXATION FOR YOU
                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = sha512(os.urandom(10))
                db.session.close()

                logger = logging.getLogger('logins')
                logger.warn("[{0}] {1} logged in".format(
                    time.strftime("%m/%d/%Y %X"),
                    session['username'].encode('utf-8')))

                # if request.args.get('next') and is_safe_url(request.args.get('next')):
                #     return redirect(request.args.get('next'))
                return redirect('/team/{0}'.format(team.id))
            else:
                errors.append("That account doesn't seem to exist")
                db.session.close()
                return render_template('login.html', errors=errors)
        else:
            db.session.close()
            return render_template('login.html')
Example #3
0
def check_password(pwd, b64ph, pep):
    # decode the encrypted base64 hash
    ph = base64.b64decode(b64ph)
    # decrypt the hash (remove pepper)
    h = pep.decrypt(ph)
    # let passlib check the hash
    return bcrypt_sha256.verify(pwd, h)
Example #4
0
File: auth.py Project: scr34m0/CTFd
def login():
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        team = Teams.query.filter_by(name=name).first()
        if team and bcrypt_sha256.verify(request.form['password'], team.password):
            try:
                session.regenerate() # NO SESSION FIXATION FOR YOU
            except:
                pass # TODO: Some session objects don't implement regenerate :(
            session['username'] = team.name
            session['id'] = team.id
            session['admin'] = team.admin
            session['nonce'] = sha512(os.urandom(10))
            db.session.close()

            logger = logging.getLogger('logins')
            logger.warn("[{0}] {1} logged in".format(time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8')))

            if request.args.get('next') and is_safe_url(request.args.get('next')):
                return redirect(request.args.get('next'))
            return redirect(url_for('challenges.challenges_view'))
        else:
            errors.append("That account doesn't seem to exist")
            db.session.close()
            return render_template('login.html', errors=errors)
    else:
        db.session.close()
        return render_template('login.html')
Example #5
0
def login():
    if request.method == 'POST':
        email = request.form['email']
        password_candidate = request.form['password']

        cursor = mysql.connection.cursor()

        result = cursor.execute("SELECT * FROM t_user WHERE use_email = %s", [email])

        if result > 0:
            data = cursor.fetchone()
            password = data['password']
            if bcrypt_sha256.verify(password_candidate, password):
                session['logged_in'] = True
                session['user'] = data['use_name']
                flash('You are now logged in', 'success')
                return redirect(url_for('dashboard'))
            else:
                error = 'Invalid credentials'
            return render_template('login.html', error = error)
        else:
            error = 'No user found'
            return render_template('login.html', error = error)
        cursor.close()
    return render_template('login.html')
Example #6
0
def login():
    if request.method == "POST":
        form = tools.LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            try:
                user = db.get_user_with_email(email)
                if bcrypt_sha256.verify(password, user['password']):
                    session['logged_in'] = True
                    session['id'] = user['id']
                    session['email'] = email
                    return redirect(
                        url_for(
                            'admin',
                            COOKIES_NOTIFICATION=tools.show_cookies_policy(),
                            LOGGED_IN=tools.is_logged_in()))
                else:
                    flash(
                        "Failed to login, please check both email and password are correct"
                    )
                    return render_template('register.html', FORGOT_PASS=True)
            except Exception as e:
                flash(
                    "Failed to login, please check both email and password are correct"
                )
                return redirect(
                    url_for('register',
                            COOKIES_NOTIFICATION=tools.show_cookies_policy(),
                            LOGGED_IN=tools.is_logged_in()))
    else:
        return render_template(
            'register.html',
            COOKIES_NOTIFICATION=tools.show_cookies_policy(),
            LOGGED_IN=tools.is_logged_in())
Example #7
0
 def testSetAPIToken(self):
     result = connection.execute(auth_user_table.insert({'email': 'a'}))
     user_id = result.inserted_primary_key[0]
     token = generate_api_token()
     connection.execute(set_api_token(token=token, auth_user_id=user_id))
     user = get_auth_user(connection, user_id)
     self.assertTrue(bcrypt_sha256.verify(token, user.token))
Example #8
0
def change_password():
    if request.method == 'GET':
        return render_template('change_pwd.html')
    # if user is not in session, redirect to login page
    elif request.method == 'POST':
        username = request.form['username']
        old_password = request.form['old_password']
        new_password = request.form['new_password']
        conn = connect_db()
        cur = conn.cursor()
        cur.execute('SELECT id, password FROM `user` WHERE username=?',
                    (username, ))
        row = cur.fetchone()
        # if username is not in database, redirect to login page
        if row is None:
            flash('This user does not exist. Please check again.', 'error')
            return redirect('/login')
        else:
            message = ""
            if bcrypt_sha256.verify(old_password, row[1]):
                encrypted_password = bcrypt_sha256.hash(new_password)
                cur.execute('UPDATE `user` SET password=? WHERE username=?',
                            (encrypted_password, username))
                message = "You have successfully changed your password."
                #print ("I am here")
            else:
                message = "You fail to change your password."
            conn.commit()
            conn.close()
            flash(message, 'info')
            return redirect('/login')
Example #9
0
def checkpasswd (username, password):
    user = userdb[username]
    try:
        return bcrypt.verify(password, user['secret'])
    except PasswordSizeError:
        print("Authentication error for {:s}: Password too long".format(username))
        return False
Example #10
0
def authenticate(session, email, password):
    user = session.query(User).filter_by(email=email).first()

    if user and bcrypt_sha256.verify(password, user.password):
        return user

    raise LoginFailed()
Example #11
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username')
        parser.add_argument('password')
        args = parser.parse_args()

        user = User.query.get(args.username)
        if (user is not None
                and bcrypt_sha256.verify(args.password, user.password)):
            user.current_session_uid = uuid4()
            user.last_active_timedate = datetime.now()
            try:
                db.session.commit()
            except InvalidRequestError:
                return {'loginError': True, 'databaseError': True}, 401
            return {
                'loginError': False
            }, 200, {
                'Authorization':
                '"Custom ' + user.username + ' ' + user.current_session_uid +
                '"'
            }
        else:
            return {'loginError': True, 'invalidCredentials': True}, 401

        return {'loginError': True}, 401
Example #12
0
    def is_authenticated(self, admin_only=True):
        """Return whether the request has been authenticated."""
        # A logged-in user (or specifically Administrator) is authenticated.
        if self.r_handler.current_user is not None:
            not_an_admin_but_should_be = (
                admin_only
                and self.r_handler.current_user_model.role != 'administrator')
            if not_an_admin_but_should_be:
                return False
            if self.request_method() not in {'GET', 'HEAD', 'OPTIONS'}:
                self._check_xsrf_cookie()
            return True

        # An Administrator can log in with a token.
        try:
            token = self.r_handler.request.headers['Token']
            email = self.r_handler.request.headers['Email']
        except KeyError:
            return False
        # Get the user's token hash and expiration time.
        try:
            user = (self.session.query(
                Administrator.token,
                Administrator.token_expiration).join(Email).filter(
                    Email.address == email).one())
        except NoResultFound:
            return False
        if user.token is None:
            return False
        if user.token_expiration.timetuple() < localtime():
            return False
        return bcrypt_sha256.verify(token, user.token)
Example #13
0
def loginAndroid():
    errors = []
    name = request.form['name']
    student = Students.query.filter_by(name=name).first()
    if student:
        if student and bcrypt_sha256.verify(request.form['password'], student.password):
            try:
                session.regenerate() # NO SESSION FIXATION FOR YOU
            except:
                pass # TODO: Some session objects don't implement regenerate :(
            session['username'] = student.name
            session['id'] = student.id
            session['admin'] = student.admin
            session['nonce'] = sha512(os.urandom(10))
            session.modified = True
            db.session.close()

            logger = logging.getLogger('logins')
            logger.warn("[{0}] {1} logged in".format(time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8')))

            if request.args.get('next') and is_safe_url(request.args.get('next')):
                return redirect(request.args.get('next'))
            return jsonify({'status': '200', 'nonce': session['nonce']})
        else: # This user exists but the password is wrong
            errors.append("Your username or password is incorrect")
            db.session.close()
            return jsonify({'status': '400', 'message': 'Invalid Login'})
    else:  # This user just doesn't exist
        errors.append("Your username or password is incorrect")
        db.session.close()
        return render_template('login.html', errors=errors)
def login(username: str, password: str) -> str:
    """Validate username and password. Return associated phone number."""
    con = sqlite3.connect(DB_NAME)

    # allows indexing rows by column name
    con.row_factory = sqlite3.Row

    # retrieve user information from the database
    # using '?' as a placeholder prevents injection attacks
    user_data = con.execute(
        'SELECT * FROM account '
        'WHERE LOWER(username) = LOWER(?)', (username, )).fetchone()
    con.close()

    # if no matching username was found
    if not user_data:
        raise AccountError(f'User "{username}" does not exist')

    # if the password was incorrect
    if not bcrypt_sha256.verify(password, user_data['password']):
        raise AccountError(f'Incorrect password for user "{username}"')

    # matching username and password: return the decrypted phone number
    return Fernet(create_fernet_key(username, password)).decrypt(
        user_data['phone']).decode()
Example #15
0
def login():
    if request.method == 'POST':
        errors = []
        username = request.form['username']
        password = request.form['password']
        member = [
            _ for _ in db.session.execute(
                text("SELECT password FROM member WHERE username = :Username"
                     ),  # selects password from corresponding user
                {"Username": username})
        ]
        if len(member) == 1 and bcrypt_sha256.verify(
                password, member[0][0]):  # verify password using bcrypt
            try:
                session.regenerate()  # NO SESSION FIXATION FOR YOU
            except:
                pass
            session['username'] = username
            session['nonce'] = hashlib.sha512(
                os.urandom(10)).hexdigest()  # generate sha512 hash
            db.session.close()

            logger = logging.getLogger('logins')
            logger.warn("[{0}] {1} logged in".format(
                time.strftime("%m/%d/%Y %X"),
                session['username'].encode('utf-8')))

            return redirect('/home')
        else:
            errors.append("That account doesn't seem to exist")
            db.session.close()
            return render_template('login.html', errors=errors)  # 2
    else:
        db.session.close()
        return render_template('login.html')
Example #16
0
def login():
    db_session = SessionDB
    try:
        username = request.json["username"]
        password = request.json["password"]
	
	db_session.rollback()
        user = User.query.filter_by(username=username).first()
	db_session.close()
        if user is not None:
            is_password_matched = bcrypt_sha256.verify(password, user.password)
            if is_password_matched is True:
                print 'Login successful'
                return jsonify(user.serialize), 200
            else:
                return jsonify('Invalid credentials'), 401

        return jsonify('User do not exist'), 400
    except KeyError as ke:
	db_session.rollback()
        db_session.close()
        return jsonify('Attribute ' + ke.args[0] + ' missing!'), 400
    except InvalidRequestError:
        db_session.rollback()
        db_session.close()
Example #17
0
 def setup():
     #if not is_setup():
     if request.method == 'POST':
         errors = []
         ## Admin user
         name = request.form['name']
         adminname = app.config['ADMINNAME']
         adminpassword = app.config['ADMINPASSWORD']
         epassword = request.form['epassword']
         password = base64.decodestring(epassword)
         if name == adminname and bcrypt_sha256.verify(
                 password, adminpassword):
             session.parmanent = False
             session['username'] = adminname
             session['password'] = adminpassword
             session['admin'] = 0
             session['nonce'] = sha512(os.urandom(10))
             flag = Flag.query.first()
             if flag == None:
                 addlmflag = 0
                 createkeyflag = 0
                 exportlmcertflag = 0
                 configIPflag = 0
                 restartflag = 0
                 configrouteflag = 0
                 importCAflag = 0
                 importsyscertflag = 0
                 initialUSBKeyflag = 0
                 importUSBKeyflag = 0
                 flag = Flag(addlmflag, createkeyflag, exportlmcertflag,
                             restartflag, configIPflag, configrouteflag,
                             importCAflag, importsyscertflag,
                             initialUSBKeyflag, importUSBKeyflag)
                 db.session.add(flag)
                 db.session.commit()
                 flag = Flag.query.first()
             count = flag.addlmflag + flag.createkeyflag + flag.exportlmcertflag + flag.restartflag + flag.configIPflag + flag.configrouteflag + flag.importCAflag + flag.importsyscertflag + flag.initialUSBKeyflag + flag.importUSBKeyflag
             if count < 1:
                 return redirect('/initial1')
             elif count < 4:
                 return redirect('/initial2')
             elif count < 5:
                 return redirect('/initial3')
             elif count < 6:
                 return redirect('/initial4')
             elif count < 7:
                 return redirect('/initial5')
             elif count < 8:
                 return redirect('/initial6')
             elif count < 10:
                 return redirect('/initial8')
             else:
                 return redirect('/initial1')
         else:
             errors.append("用户名或者密码错误。")
             db.session.close()
         return render_template('setup.html', errors=errors)
     else:
         db.session.close()
         return render_template('setup.html')
Example #18
0
    def profile():
        if authed():
            if request.method == "POST":
                errors = []

                name = request.form.get('name')
                email = request.form.get('email')
                website = request.form.get('website')
                affiliation = request.form.get('affiliation')
                country = request.form.get('country')

                user = Teams.query.filter_by(id=session['id']).first()

                names = Teams.query.filter_by(name=name).first()
                emails = Teams.query.filter_by(email=email).first()
                valid_email = re.match("[^@]+@[^@]+\.[^@]+", email)
                
                name_len = len(request.form['name']) == 0

                if ('password' in request.form.keys() and not len(request.form['password']) == 0) and \
                        (not bcrypt_sha256.verify(request.form.get('confirm').strip(), user.password)):
                    errors.append("Your old password doesn't match what we have.")
                if not valid_email:
                    errors.append("That email doesn't look right")
                if names and name!=session['username']: 
                    errors.append('That team name is already taken')
                if emails and emails.id != session['id']:
                    errors.append('That email has already been used')
                if name_len:
                    errors.append('Pick a longer team name')
                if website.strip() and not validate_url(website):
                    errors.append("That doesn't look like a valid URL")

                if len(errors) > 0:
                    return render_template('profile.html', name=name, email=email, website=website, affiliation=affiliation, country=country, errors=errors)
                else:
                    team = Teams.query.filter_by(id=session['id']).first()
                    team.name = name
                    team.email = email
                    session['username'] = name

                    if 'password' in request.form.keys() and not len(request.form['password']) == 0:
                        team.password = bcrypt_sha256.encrypt(request.form.get('password'))
                    team.website = website
                    team.affiliation = affiliation
                    team.country = country
                    db.session.commit()
                    db.session.close()
                    return redirect('/profile')
            else:
                user = Teams.query.filter_by(id=session['id']).first()
                name = user.name
                email = user.email
                website = user.website
                affiliation = user.affiliation
                country = user.country
                return render_template('profile.html', name=name, email=email, website=website, affiliation=affiliation, country=country)
        else:
            return redirect('/login')
Example #19
0
def login():
    logger = logging.getLogger('logins')
    if request.method == 'POST':
        errors = []
        name = request.form['name']

        # Check if the user submitted an email address or a team name
        if utils.check_email_format(name) is True:
            team = Teams.query.filter_by(email=name).first()
        elif utils.check_sno_format(name) is True:
            team = Teams.query.filter_by(sno=name).first()
        else:
            team = Teams.query.filter_by(name=name).first()

        if team:
            if team and bcrypt_sha256.verify(request.form['password'],
                                             team.password):
                try:
                    session.regenerate()  # NO SESSION FIXATION FOR YOU
                except:
                    pass  # TODO: Some session objects don't implement regenerate :(
                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = utils.sha512(os.urandom(10))
                db.session.close()

                logger.warn("[{date}] {ip} - {username} logged in".format(
                    date=time.strftime("%m/%d/%Y %X"),
                    ip=utils.get_ip(),
                    username=session['username'].encode('utf-8')))

                if request.args.get('next') and utils.is_safe_url(
                        request.args.get('next')):
                    return redirect(request.args.get('next'))
                return redirect(url_for('challenges.challenges_view'))

            else:  # This user exists but the password is wrong
                logger.warn(
                    "[{date}] {ip} - submitted invalid password for {username}"
                    .format(date=time.strftime("%m/%d/%Y %X"),
                            ip=utils.get_ip(),
                            username=team.name.encode('utf-8')))
                errors.append("Your username or password is incorrect")
                db.session.close()
                return render_template('login.html', errors=errors)

        else:  # This user just doesn't exist
            logger.warn(
                "[{date}] {ip} - submitted invalid account information".format(
                    date=time.strftime("%m/%d/%Y %X"), ip=utils.get_ip()))
            errors.append("Your username or password is incorrect")
            db.session.close()
            return render_template('login.html', errors=errors)

    else:
        db.session.close()
        return render_template('login.html')
Example #20
0
def Index():
    """Login portal for clients"""

    if current_user.is_authenticated:
        """If client is authenticated, return them back to their portal case view"""
        return render_template("Client_View.html",
                               title='client_view',
                               Client_id=current_user.Client_id,
                               api_key=current_user.api_key)
    form = LoginForm()
    if (request.method == 'POST') and (form.validate_on_submit()):
        Client_id = form.Client_id.data
        Password = form.Password.data
        user = User.query.filter_by(Client_id=Client_id).first()
        if not user and app.config['NO_PASSWORD'] == True:
            """Allow anyone to create their own account"""
            pass_hash = bcrypt_sha256.encrypt(Password, rounds=12)
            user = User(Client_id=Client_id, Password=pass_hash, api_key='')
            Sample_date = Client_View(client_id=Client_id,
                                      case_name='sample case',
                                      priority='1',
                                      target_date='10/7/2016',
                                      product_area='Engineering',
                                      status='In Progress',
                                      description='something')
            db.session.add(user)
            db.session.commit()
            db.session.add(Sample_date)
            db.session.commit()
        """ If user is a vaild account, proceed with verifying \
        their credentials and provide them the API key"""
        if user:
            if bcrypt_sha256.verify(
                    Password, user.Password) and user.Client_id == Client_id:
                signer = TimestampSigner(SECRET_KEY)
                API_KEY = ''.join([
                    random.choice(string.ascii_letters + string.digits)
                    for n in xrange(30)
                ])
                user.api_key = signer.sign(API_KEY)
                user.current_login_ip = request.remote_addr
                db.session.commit()
                login_user(user)
                flash('You have successfully logged in')
                return render_template("Client_View.html",
                                       title='client_view',
                                       Client_id=Client_id,
                                       api_key=user.api_key)
        if form.errors:
            flash(form.errors, 'danger')
        flash(
            'Incorrect Credentials, please enter the correct Client Id and Password'
        )
        return render_template('Index.html', form=form)
    if form.errors:
        flash(form.errors, 'danger')
    return render_template('Index.html', form=form)
Example #21
0
    def get_user_by_login(cls, email, password):
        auth_id = email.lower()

        try:
            user = cls.get(cls.auth_id == auth_id)
            if user.password and bcrypt_sha256.verify(password, user.password):
                return user
        except DoesNotExist:
            pass
Example #22
0
def verify_password(username, password):
    user = User.query.filter_by(username=username).first()
    try:
        if not user or not bcrypt_sha256.verify(password, user.pw_hash):
            return False
    except ValueError:
        return False
    g.user = user
    return True
Example #23
0
def verify_login(username, password):
    """check username and password"""
    try:
        user = Users.get(Users.username == username)
    except DoesNotExist:
        print("user does not exist")
        return False
    else:
        return bcrypt_sha256.verify(password, user.password)  # verify given pass against hash value 'True' if success
Example #24
0
def profile():
    if authed():
        if request.method == "POST":
            errors = []

            name = request.form.get('name')
            email = request.form.get('email')

            user = Students.query.filter_by(id=session['id']).first()

            if not get_config('prevent_name_change'):
                names = Students.query.filter_by(name=name).first()
                name_len = len(request.form['name']) == 0

            emails = Students.query.filter_by(email=email).first()
            valid_email = re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email)

            if ('password' in request.form.keys() and not len(request.form['password']) == 0) and \
                    (not bcrypt_sha256.verify(request.form.get('confirm').strip(), user.password)):
                errors.append("Your old password doesn't match what we have.")
            if not valid_email:
                errors.append("That email doesn't look right")
            if not get_config('prevent_name_change') and names and name != session['username']:
                errors.append('That student name is already taken')
            if emails and emails.id != session['id']:
                errors.append('That email has already been used')
            if not get_config('prevent_name_change') and name_len:
                errors.append('Pick a longer student name')

            if len(errors) > 0:
                return render_template('profile.html', name=name, email=email, errors=errors)
            else:
                student = Students.query.filter_by(id=session['id']).first()
                if not get_config('prevent_name_change'):
                    student.name = name
                if student.email != email.lower():
                    student.email = email.lower()
                    if get_config('verify_emails'):
                        student.verified = False
                session['username'] = student.name

                if 'password' in request.form.keys() and not len(request.form['password']) == 0:
                    student.password = bcrypt_sha256.encrypt(request.form.get('password'))
                db.session.commit()
                db.session.close()
                return redirect(url_for('views.profile'))
        else:
            user = Students.query.filter_by(id=session['id']).first()
            name = user.name
            email = user.email
            prevent_name_change = get_config('prevent_name_change')
            confirm_email = get_config('verify_emails') and not user.verified
            return render_template('profile.html', name=name, email=email, prevent_name_change=prevent_name_change,
                                   confirm_email=confirm_email)
    else:
        return redirect(url_for('auth.login'))
Example #25
0
    def verify_password(self, database: Database, password: str) -> bool:
        """Verifies that the given password matches that of the registered user."""
        user = database.get_user(self.__email)

        if not (user and bcrypt_sha256.verify(password, database.get_password(user))):
            self.__user = None
            return False

        self.__user = user
        return True
def verify_secret(secret, hash):
    """
    Check to see if the provided secret matches the hashed value.

    Companion to `utils.encrypt_secret`

    Returns:
        Bool indicating whether or not the secret matches the hash.
    """
    return bcrypt_sha256.verify(secret, hash)
Example #27
0
    def profile():
        if authed():
            if request.method == "POST":
                errors = []

                name = request.form.get('name')
                email = request.form.get('email')
                website = request.form.get('website')
                affiliation = request.form.get('affiliation')
                country = request.form.get('country')

                names = Teams.query.filter_by(name=name).first()
                emails = Teams.query.filter_by(email=email).first()
                valid_email = re.match("[^@]+@[^@]+\.[^@]+", email)
                
                name_len = len(request.form['name']) == 0

                if not bcrypt_sha256.verify(request.form.get('confirm').strip(), names.password):
                    errors.append("Your old password doesn't match what we have.")
                if not valid_email:
                    errors.append("That email doesn't look right")
                if names and name!=session['username']: 
                    errors.append('That team name is already taken')
                if emails and emails.id != session['id']:
                    errors.append('That email has already been used')
                if name_len:
                    errors.append('Pick a longer team name')
                if not validate_url(website):
                    errors.append("That doesn't look like a valid URL")

                if len(errors) > 0:
                    return render_template('profile.html', name=name, email=email, website=website, affiliation=affiliation, country=country, errors=errors)
                else:
                    team = Teams.query.filter_by(id=session['id']).first()
                    team.name = name
                    team.email = email
                    if 'password' in request.form.keys() and not len(request.form['password']) == 0:
                        team.password = bcrypt_sha256.encrypt(request.form.get('password'))
                    team.website = website
                    team.affiliation = affiliation
                    team.country = country
                    db.session.commit()
                    db.session.close()
                    return redirect('/profile')
            else:
                user = Teams.query.filter_by(id=session['id']).first()
                name = user.name
                email = user.email
                website = user.website
                affiliation = user.affiliation
                country = user.country
                return render_template('profile.html', name=name, email=email, website=website, affiliation=affiliation, country=country)
        else:
            return redirect('/login')
Example #28
0
def check_password(pwdhash, password):
    """Check the password hash from :func:`password_hash`.

    .. versionchanged:: 1.1.0

    :param str pwdhash: Hash from :func:`password_hash` to check
    :param str password: Password in plaintext
    :return: password match
    :rtype: bool
    """
    return bcrypt_sha256.verify(password, pwdhash)
Example #29
0
def check_password(pwdhash, password):
    """Check the password hash from :func:`password_hash`.

    .. versionchanged:: 1.1.0

    :param str pwdhash: Hash from :func:`password_hash` to check
    :param str password: Password in plaintext
    :return: password match
    :rtype: bool
    """
    return bcrypt_sha256.verify(password, pwdhash)
Example #30
0
 def _check_password(_session, password):
     if not isinstance(account, Account):
         # They entered an account email and it didn't exist.
         if fail is not None:
             fail(_session, account)
     else:
         # Check the given password against the account.
         if password and bcrypt_sha256.verify(password,
                                              account.password):
             success(_session, account)
         else:
             fail(_session, account)
Example #31
0
 def _check_password(_session, password):
     if not isinstance(account, Account):
         # They entered an account email and it didn't exist.
         if fail is not None:
             fail(_session, account)
     else:
         # Check the given password against the account.
         if password and bcrypt_sha256.verify(password,
                                              account.password):
             success(_session, account)
         else:
             fail(_session, account)
Example #32
0
    def re_initialize():
        adminpassword = app.config['ADMINPASSWORD']
        epassword = request.form['epassword']
        password = base64.decodestring(epassword)
        if bcrypt_sha256.verify(password, adminpassword):
            flag = Flag.query.first()
            flag.addlmflag = 0
            flag.createkeyflag = 0
            flag.exportlmcertflag = 0
            flag.configIPflag = 0
            flag.restartflag = 0
            flag.configrouteflag = 0
            flag.importCAflag = 0
            flag.importsyscertflag = 0
            flag.initialUSBKeyflag = 0
            flag.importUSBKeyflag = 0
            db.session.add(flag)
            db.session.commit()
            sql2 = "truncate table terminallogs"
            DeleteData(sql2)
            sql3 = "delete from users"
            DeleteData(sql3)
            sql4 = "truncate table cipermachine"
            DeleteData(sql4)
            sql5 = "truncate table tree"
            DeleteData(sql5)
            sql6 = "truncate table lead_machine"
            DeleteData(sql6)
            sql7 = "truncate table equipments_status"
            DeleteData(sql7)
            sql8 = "truncate table prinvate_equipment_common_info"
            DeleteData(sql8)
            session.clear()

            dirPath = app.config['CERTIFICATE_FOLDER']
            if not os.path.isdir(dirPath):
                return
            files = os.listdir(dirPath)
            try:
                for file in files:
                    filePath = os.path.join(dirPath, file)
                    if os.path.isfile(filePath):
                        os.remove(filePath)
                    elif os.path.isdir(filePath):
                        removeDir(filePath)
                #os.rmdir(dirPath)
                #os.mkdir(dirPath)
            except Exception, e:
                print e

            return "1"
Example #33
0
def allianceauth_check_hash(password, hash, hash_type):
    """
    Python implementation of the AllianceAuth MumbleUser hash function
    :param password: Password to be verified
    :param hash: Hash for the password to be checked against
    :param hash_type: Hashing function originally used to generate the hash
    """
    if hash_type == 'sha1':
        return sha1(password).hexdigest() == hash
    elif hash_type == 'bcrypt-sha256':
        return bcrypt_sha256.verify(password, hash)
    else:
        warning("No valid hash function found for %s" % hash_type)
        return False
Example #34
0
def allianceauth_check_hash(password, hash, hash_type):
    """
    Python implementation of the AllianceAuth MumbleUser hash function
    :param password: Password to be verified
    :param hash: Hash for the password to be checked against
    :param hash_type: Hashing function originally used to generate the hash
    """
    if hash_type == 'sha1':
        return sha1(password).hexdigest() == hash
    elif hash_type == 'bcrypt-sha256':
        return bcrypt_sha256.verify(password, hash)
    else:
        warning("No valid hash function found for %s" % hash_type)
        return False
Example #35
0
def verifyUserPassword(userName, userPassword):
    retVal = None
    with lock:
        try:
            dataBase = TinyDB(dbFileName)
            userTable = dataBase.table('users')
            q = Query()
            r = userTable.search(q.userName == userName)
            if len(r) > 0:
                u = r[0]
                pw = u["userPassword"]
                if bcrypt_sha256.verify(userPassword, pw):
                    retVal = u["sessionID"]
        except:
            pass
    return retVal
Example #36
0
def login():
    try:
        username = request.json["username"]
        password = request.json["password"]

        user = User.query.filter_by(username=username).first()
        if user is not None:
            is_password_matched = bcrypt_sha256.verify(password, user.password)
            if is_password_matched is True:
                print 'Login successful'
                return jsonify(user.serialize), 200
            else:
                return jsonify({'error': 'Invalid credentials'}), 401

        return jsonify({'error': 'User do not exist'}), 400
    except KeyError as ke:
        return jsonify({'error': 'Attribute ' + ke.args[0] + ' missing!'}), 400
Example #37
0
	def validate(self):
		if not Form.validate(self):
			return False
	
		user = Users.query.filter_by(user = self.user.data).first()
		if user and bcrypt_sha256.verify(self.password.data, user.password):
			try:
				session.regenerate() # NO SESSION FIXATION FOR YOU
			except:
				pass # TODO: Some session objects don't implement regenerate :(
			session['username'] = user.user
			session['id'] = user.id
			session['nonce'] = sha512(os.urandom(10))
			db.session.close()
			return True
		else:
			db.session.close()
			return False
Example #38
0
def verify_api_token(connection: Connection,
                     *,
                     token: str,
                     email: str) -> bool:
    """
    Checks whether the supplied API token is valid for the specified user.

    :param connection: a SQLAlchemy Connection
    :param token: the API token
    :param email: the e-mail address of the user
    :return: whether the token is correct and not expired
    """
    try:
        auth_user = get_auth_user_by_email(connection, email)
    except UserDoesNotExistError:
        return False
    token_is_fresh = auth_user.expires_on.timetuple() >= localtime()
    not_blank = auth_user.token != ''
    token_matches = not_blank and bcrypt_sha256.verify(token, auth_user.token)

    return token_is_fresh and token_matches
Example #39
0
def admin_view():
    if request.method == 'POST':
        username = request.form.get('name')
        password = request.form.get('password')

        admin_user= Teams.query.filter_by(name=request.form['name'], admin=True).first()
        if admin_user and bcrypt_sha256.verify(request.form['password'], admin_user.password):
            try:
                session.regenerate() # NO SESSION FIXATION FOR YOU
            except:
                pass # TODO: Some session objects dont implement regenerate :(
            session['username'] = admin_user.name
            session['id'] = admin_user.id
            session['admin'] = True
            session['nonce'] = sha512(os.urandom(10))
            db.session.close()
            return redirect('/admin/graphs')

    if is_admin():
        return redirect('/admin/graphs')

    return render_template('admin/login.html')
Example #40
0
  def getUser(self, email, password):
    """ Given the user's login information, return the user """

    session = db.session
    ua = None
    try:
      ua = session.query(UserAuthentication)\
        .join(User)\
        .filter(UserAuthentication.provider == self.provider)\
        .filter(User.email == email)\
        .one()
    except NoResultFound:
      pass

    if not ua:
      return None

    user = ua.user

    if bcrypt_sha256.verify(password, ua.key):
      return user
    else:
      return None
Example #41
0
    def is_authenticated(self, admin_only=True):
        """Return whether the request has been authenticated."""
        # A logged-in user (or specifically Administrator) is authenticated.
        if self.r_handler.current_user is not None:
            not_an_admin_but_should_be = (
                admin_only and
                self.r_handler.current_user_model.role != 'administrator'
            )
            if not_an_admin_but_should_be:
                return False
            if self.request_method() not in {'GET', 'HEAD', 'OPTIONS'}:
                self._check_xsrf_cookie()
            return True

        # An Administrator can log in with a token.
        try:
            token = self.r_handler.request.headers['Token']
            email = self.r_handler.request.headers['Email']
        except KeyError:
            return False
        # Get the user's token hash and expiration time.
        try:
            user = (
                self.session
                .query(Administrator.token, Administrator.token_expiration)
                .join(Email)
                .filter(Email.address == email)
                .one()
            )
        except NoResultFound:
            return False
        if user.token is None:
            return False
        if user.token_expiration.timetuple() < localtime():
            return False
        return bcrypt_sha256.verify(token, user.token)
Example #42
0
 def verify( password, h):
     
     return bcrypt_sha256.verify(password, h)
Example #43
0
def verify_password(password, hashed_password):
    return bcrypt_sha256.verify(password, hashed_password)
Example #44
0
def profile():
    if authed():
        if request.method == "POST":
            errors = []

            name = request.form.get('name')
            email = request.form.get('email')
            schoolCode = request.form.get('schoolCode')
            website = request.form.get('website')
            affiliation = request.form.get('affiliation')
            country = request.form.get('country')

            user = Teams.query.filter_by(id=session['id']).first()

            if not get_config('prevent_name_change'):
                names = Teams.query.filter_by(name=name).first()
                name_len = len(request.form['name']) == 0

            emails = Teams.query.filter_by(email=email).first()
            valid_email = re.match("[^@]+@[^@]+\.[^@]+", email)

            if ('password' in request.form.keys() and not len(request.form['password']) == 0) and \
                    (not bcrypt_sha256.verify(request.form.get('confirm').strip(), user.password)):
                errors.append("Your old password doesn't match what we have.")
            if not valid_email:
                errors.append("That email doesn't look right")
            if not get_config('prevent_name_change') and names and name!=session['username']:
                errors.append('That team name is already taken')
            if emails and emails.id != session['id']:
                errors.append('That email has already been used')
            if not get_config('prevent_name_change') and name_len:
                errors.append('Pick a longer team name')
            if website.strip() and not validate_url(website):
                errors.append("That doesn't look like a valid URL")

            if len(errors) > 0:
                return render_template('profile.html', name=name, email=email, schoolCode=schoolCode, website=website,
                                       affiliation=affiliation, country=country, errors=errors)
            else:
                team = Teams.query.filter_by(id=session['id']).first()
                if not get_config('prevent_name_change'):
                    team.name = name
                if team.email != email.lower():
                    team.email = email.lower()
                    if get_config('verify_emails'):
                        team.verified = False
                session['username'] = team.name

                if 'password' in request.form.keys() and not len(request.form['password']) == 0:
                    team.password = bcrypt_sha256.encrypt(request.form.get('password'))
                team.schoolCode = schoolCode
                team.website = website
                team.affiliation = affiliation
                team.country = country
                db.session.commit()
                db.session.close()
                return redirect(url_for('views.profile'))
        else:
            user = Teams.query.filter_by(id=session['id']).first()
            name = user.name
            email = user.email
            schoolCode = user.schoolCode
            website = user.website
            affiliation = user.affiliation
            country = user.country
            prevent_name_change = get_config('prevent_name_change')
            confirm_email = get_config('verify_emails') and not user.verified
            return render_template('profile.html', name=name, email=email, schoolCode=schoolCode, website=website, affiliation=affiliation,
                                   country=country, prevent_name_change=prevent_name_change, confirm_email=confirm_email)
    else:
        return redirect(url_for('auth.login'))
Example #45
0
def profile():
    if authed():
        if request.method == "POST":
            errors = []

            name = request.form.get("name")
            email = request.form.get("email")
            website = request.form.get("website")
            affiliation = request.form.get("affiliation")
            country = request.form.get("country")

            user = Teams.query.filter_by(id=session["id"]).first()

            if not get_config("prevent_name_change"):
                names = Teams.query.filter_by(name=name).first()
                name_len = len(request.form["name"]) == 0

            emails = Teams.query.filter_by(email=email).first()
            valid_email = re.match("[^@]+@[^@]+\.[^@]+", email)

            if ("password" in request.form.keys() and not len(request.form["password"]) == 0) and (
                not bcrypt_sha256.verify(request.form.get("confirm").strip(), user.password)
            ):
                errors.append("Your old password doesn't match what we have.")
            if not valid_email:
                errors.append("That email doesn't look right")
            if not get_config("prevent_name_change") and names and name != session["username"]:
                errors.append("That team name is already taken")
            if emails and emails.id != session["id"]:
                errors.append("That email has already been used")
            if not get_config("prevent_name_change") and name_len:
                errors.append("Pick a longer team name")
            if website.strip() and not validate_url(website):
                errors.append("That doesn't look like a valid URL")

            if len(errors) > 0:
                return render_template(
                    "profile.html",
                    name=name,
                    email=email,
                    website=website,
                    affiliation=affiliation,
                    country=country,
                    errors=errors,
                )
            else:
                team = Teams.query.filter_by(id=session["id"]).first()
                if not get_config("prevent_name_change"):
                    team.name = name
                team.email = email
                session["username"] = team.name

                if "password" in request.form.keys() and not len(request.form["password"]) == 0:
                    team.password = bcrypt_sha256.encrypt(request.form.get("password"))
                team.website = website
                team.affiliation = affiliation
                team.country = country
                db.session.commit()
                db.session.close()
                return redirect("/profile")
        else:
            user = Teams.query.filter_by(id=session["id"]).first()
            name = user.name
            email = user.email
            website = user.website
            affiliation = user.affiliation
            country = user.country
            prevent_name_change = get_config("prevent_name_change")
            return render_template(
                "profile.html",
                name=name,
                email=email,
                website=website,
                affiliation=affiliation,
                country=country,
                prevent_name_change=prevent_name_change,
            )
    else:
        return redirect("/login")