Ejemplo n.º 1
0
    def is_login(sk):
        """This method is used to verify if at least one administrator has been setup."""
        try:
            conn = Connect(host=HOST, user=USER, password=PASSWORD, database=DATABASE)
        except ConnectionError as e:
            print(e)
            return False

        cur = conn.cursor()

        query = "SELECT * FROM `administrator`"

        try:
            cur.execute(query)
        except errors.ProgrammingError as e:
            print(e)
            return False

        conn.close()

        response = cur.fetchall()

        if response:
            b = Bcrypt()

            try:
                return b.check_password_hash(request.cookies['admin_session'], sk)
            except KeyError as e:
                return False
        else:
            return True
Ejemplo n.º 2
0
    def auth_admin(self):
        """Authenticate administrator trying to login."""
        try:
            conn = Connect(host=HOST, user=USER, password=PASSWORD, database=DATABASE)
        except ConnectionError as e:
            print(e)
            return False

        cur = conn.cursor()

        query = "SELECT `password` FROM `administrator` WHERE `user_name` = '{}'".format(self.user_name)

        try:
            cur.execute(query)
        except errors.ProgrammingError as e:
            print(e)
            return False

        response = cur.fetchall()

        conn.close()

        bcrypt = Bcrypt()

        try:
            return bcrypt.check_password_hash(response[0][0], self.password)
        except IndexError:
            return False
Ejemplo n.º 3
0
    def admin_index(self):
        bcrypt = Bcrypt(app)
        """For GET requests, display the login form. For POSTS, login the current user
        by processing the form."""

        form = LoginForm()
        next = request.args.get('next')
        if form.validate():
            user = User.query.filter(
                User.username == form.username.data).first()

            if user:
                a = bcrypt.generate_password_hash(form.password.data)
                if bcrypt.check_password_hash(user.password,
                                              form.password.data):
                    user.authenticated = True
                    db.session.add(user)
                    db.session.commit()
                    login_user(user, remember=True, force=True)
                    next = request.args.get('next')
                    print("You have successfully logged in")
                    return redirect(next or url_for('admin.admin_index'))
                else:
                    print "bad password"
            else:
                print "user mismatch"
        return self.render('admin/index.html', form=form)
Ejemplo n.º 4
0
def login():

	if request.method == "GET":

		next_redirect = request.args.get("next", False)

		return render_template("public/login.html",
			next=next_redirect)

	else:

		errs = []

		password = request.form.get("password", "")
		email = request.form.get("email", "")
		next = request.form.get("next", "")

		try:
			bc = Bcrypt(None)
			conn = db.get_db()

			sql_query = "SELECT * FROM users WHERE email = %s;"
			sql_data = (escape(email), )

			cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
			cur.execute( sql_query, sql_data )
			user = cur.fetchone()
			cur.close()

			if user == None:
				errs.append("No User Found.")

			else:

				if bc.check_password_hash(user["password"], password):

					# add user to the session
					tools.setCookie( email, user["username"], user["userid"] )

					# return the errors and redirect path
					redirect_url = "/welcome/"

					if next:
						redirect_url = next

					return redirect("/welcome/")

				else:
					print "bad pass"
					errs.append("Incorrect Password.")

		except Exception, e:
			print e
			errs.append("Unable to sign in at this time.")

		return render_template("public/login.html",
			next=next,
			errors=errs,
			email=email)
Ejemplo n.º 5
0
def login():

    if request.method == "GET":

        next_redirect = request.args.get("next", False)

        return render_template("public/login.html", next=next_redirect)

    else:

        errs = []

        password = request.form.get("password", "")
        email = request.form.get("email", "")
        next = request.form.get("next", "")

        try:
            bc = Bcrypt(None)
            conn = db.get_db()

            sql_query = "SELECT * FROM users WHERE email = %s;"
            sql_data = (escape(email), )

            cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
            cur.execute(sql_query, sql_data)
            user = cur.fetchone()
            cur.close()

            if user == None:
                errs.append("No User Found.")

            else:

                if bc.check_password_hash(user["password"], password):

                    # add user to the session
                    tools.setCookie(email, user["username"], user["userid"])

                    # return the errors and redirect path
                    redirect_url = "/welcome/"

                    if next:
                        redirect_url = next

                    return redirect("/welcome/")

                else:
                    print "bad pass"
                    errs.append("Incorrect Password.")

        except Exception, e:
            print e
            errs.append("Unable to sign in at this time.")

        return render_template("public/login.html",
                               next=next,
                               errors=errs,
                               email=email)
def check_login(member_id, password):
    try:
        # Create Database Connection
        conn = database_connect()
        cursor = conn.cursor()
        # Find the users data
        cursor.execute(
            """SELECT member_id, title, given_names, family_name, country_name, place_name,
            (CASE
                WHEN member_id IN (Select * from athlete) THEN 'athlete'
                WHEN member_id IN (Select * from staff) THEN 'staff'
                WHEN member_id IN (Select * from official) THEN 'official'
                ELSE 'No category'
            END) AS user_type, pass_word
            FROM member
            INNER JOIN country USING (country_code)
            INNER JOIN place ON member.accommodation = place.place_id
            WHERE member_id=%s""", (member_id, ))
        user_data = cursor.fetchone()  # Retrieve Query result
    finally:
        cursor.close()  # Close Curosr
        conn.close()

    if user_data is None:  # INVALID USERNAME
        return None

    # Password check
    # people with empty passwords don't get any hahsing
    # Note: it is currently impossible to enter an empty password with the current form so these users cannot login.
    if (are_passwords_hashed()):
        print('logging in using hashed password')
        if not (password == '' and user_data[7] == ''):
            from flask.ext.bcrypt import Bcrypt
            bc = Bcrypt(None)
            password_hashed = bytes(user_data[7], 'utf8')
            if not bc.check_password_hash(password_hashed,
                                          password):  # INVALID PASSWORD
                return ()
    else:  #compare unhashed passwords
        if (password != user_data[7]):
            return None

    tuples = {
        'member_id': user_data[0],
        'title': user_data[1],
        'first_name': user_data[2],
        'family_name': user_data[3],
        'country_name': user_data[4],
        'residence': user_data[5],
        'member_type': user_data[6]
    }
    return tuples
Ejemplo n.º 7
0
def check_old_password(pwdhash, password):
    """Check the old password hash from :func:`password_hash`.

    .. versionadded:: 1.1.0

    :param str pwdhash: Hash from :func:`password_hash` to check
    :param str password: Password in plaintext
    :return: password match
    :rtype: bool
    """
    from flask.ext.bcrypt import Bcrypt
    app.config['BCRYPT_LOG_ROUNDS'] = 12
    bcrypt = Bcrypt(app)
    return bcrypt.check_password_hash(pwdhash, password)
Ejemplo n.º 8
0
def check_old_password(pwdhash, password):
    """Check the old password hash from :func:`password_hash`.

    .. versionadded:: 1.1.0

    :param str pwdhash: Hash from :func:`password_hash` to check
    :param str password: Password in plaintext
    :return: password match
    :rtype: bool
    """
    from flask.ext.bcrypt import Bcrypt
    app.config['BCRYPT_LOG_ROUNDS'] = 12
    bcrypt = Bcrypt(app)
    return bcrypt.check_password_hash(pwdhash, password)
Ejemplo n.º 9
0
	def login(self):
		print '***** login'
		email    = request.form['email']
		password = request.form['password']

		results = self.models['User'].get_user_by_email(email)
		if results == []:
			flash('Bad password or email', 'error')
			return redirect('/')
        
		app = Flask(__name__)
		bcrypt = Bcrypt(app)
		if bcrypt.check_password_hash(results[0]['pw_hash'], password):
			session['id']    = results[0]['id']
			session['fname'] = results[0]['fname']
			session['lname'] = results[0]['lname']
			session['email'] = results[0]['email']
			print '*** session id: {}'.format(session['id'])
			return redirect('/articles')
		else:
			flash('Bad password or email', 'error')
			return redirect('/')
Ejemplo n.º 10
0
    def login(self):
        print '***** login ////////////////////////'
        email = request.form['email']
        password = request.form['password']

        results = self.models['User'].get_user_by_email(email)
        if results == []:
            flash('Bad password or email', 'error')
            return redirect('/')

        app = Flask(__name__)
        bcrypt = Bcrypt(app)
        if bcrypt.check_password_hash(results[0]['pw_hash'], password):
            session['id'] = results[0]['id']
            session['fname'] = results[0]['fname']
            session['lname'] = results[0]['lname']
            session['email'] = results[0]['email']
            print '*** session id: {}'.format(session['id'])
            print 'sending to show_stories//////////////////'
            return redirect('/show_stories')
        else:
            flash('Bad password or email', 'error')
            return redirect('/')
from pymongo import MongoClient
from flask.ext.bcrypt import Bcrypt

app = Flask(__name__, static_url_path='/static')
mongo = MongoClient()
bcrypt = Bcrypt(app)

# new database
db = mongo.tutorial

db.users.insert_one({"name": "Devin"})

# bcrypt

pw_hash = bcrypt.generate_password_hash('hunter2')
print bcrypt.check_password_hash(pw_hash, 'hunter2')

# db

'''

db.users.find(json_data)
db.users.insert_one(json_data)
db.users.remove(json_data)
db.users.update(json_data)

'''

# getting post

'''
Ejemplo n.º 12
0
 def verify_password(self, password):
     bcrypt = Bcrypt()
     return bcrypt.check_password_hash(self.password, password)
Ejemplo n.º 13
0
class Auth:
    GHOST = 0
    USER = 1
    ADMIN = 2
    SUPER_ADMIN = 3

    class Anonymous(AnonymousUserMixin):
        def __init__(self):
            self._id = None

        def get_id(self):
            return unicode('')

    def __init__(self):
        self.__login_manager = LoginManager()
        self.config = {}

    def init_app(self, app, config):
        print 'Attaching LoginManager to app.'
        self.__login_manager.init_app(app)
        self.__login_manager.anonymous_user = Auth.Anonymous
        self.config = config

        def load_user(user_id):
            if user_id == '':
                return None

            Users = Database['Users']
            try:
                return Users.User.find_one({'_id': ObjectId(user_id)})
            except:
                return None

        def unauthorized():
            return jsonify(error='Unauthorized'), HTTP_401_UNAUTHORIZED

        self.__login_manager.user_loader(load_user)
        self.__login_manager.unauthorized_handler(unauthorized)

        self.__bcrypt = Bcrypt(app)

    def login_manager(self):
        return self.__login_manager

    def require(self, user_level):
        def login_required(f):
            @wraps(f)
            def decorated_function(*args, **kwargs):
                if current_user.is_authenticated() and current_user.get_access_level() >= user_level:
                    return f(*args, **kwargs)
                return self.__login_manager.unauthorized()
            return decorated_function
        return login_required

    def login(self, user_object, password):
        if user_object is not None:
            if self.__bcrypt.check_password_hash(user_object['password'], password):
                if not login_user(user_object):
                    return resource_strings["USER_NOT_ACTIVATED"]
            else:
                return 'Invalid password'
        else:
            return 'Invalid email'
        return None

    def login_social(self, login_type, token):
        user_object = None

        try:
            user_object = SocialSignin.verify(login_type, token)
        except SocialSignin.Invalid as e:
            return str(e)

        login_user(user_object)

    def logout(self):
        logout_user()

    def hash_password(self, password):
        return self.__bcrypt.generate_password_hash(password)

    # decorator that protects other users from PUT/POST/DELETE on you stuff
    # user_id _must_ be passed in as 'user_id'
    def only_me(self, function):
        @wraps(function)
        def inner(*args, **kwargs):
            if kwargs['user_id'] != 'me':
                return '{}', HTTP_401_UNAUTHORIZED
            return function(*args, **kwargs)
        return inner
Ejemplo n.º 14
0
from flask import Flask
from flask.ext.bcrypt import Bcrypt

app = Flask(__name__)
bcrypt = Bcrypt(app)

# to generate bcrypt hash.
pw_hash = bcrypt.generate_password_hash('idfumg')

# to compare with an existing hash.
bcrypt.check_password_hash(pw_hash, 'idfumg')
Ejemplo n.º 15
0
 email = request.form['email']
 username = request.form['username']
 password = request.form['password']
 # run validations and if they are successful we can create the password hash with bcrypt
 pw_hash = bcrypt.generate_password_hash(password)
 # now we insert the new user into the database
 insert_query = "INSERT INTO users (email, username, pw_hash, created_at) VALUES (:email, :username, :pw_hash, NOW())"
 query_data = { 'email': email, 'username': username, 'pw_hash': pw_hash }
 mysql.query_db(insert_query, query_data)
 # redirect to success page

# check_password_hash
password = '******'
pw_hash = bcrypt.generate_password_hash(password)
test_password_1 = 'thisiswrong'
bcrypt.check_password_hash(pw_hash, test_password_1) # this will return false
test_password_2 = 'password'
bcrypt.check_password_hash(pw_hash, test_password_2) # this will return true

# login
@app.route('/login', methods=['POST'])
def login():
 email = request.form['email']
 password = request.form['password']
 user_query = "SELECT * FROM users WHERE email = :email LIMIT 1"
 query_data = { 'email': email }
 user = mysql.query_db(user_query, query_data) # user will be returned in a list
 if bcrypt.check_password_hash(user[0]['pw_hash'], password):
  # login user
 else:
  # set flash error message and redirect to login page
Ejemplo n.º 16
0
from flask import Flask
from flask.ext.bcrypt import Bcrypt

app = Flask(__name__)
bcrypt = Bcrypt(app)

pw_hash = bcrypt.generate_password_hash('insert awesome password here')
print pw_hash
print bcrypt.check_password_hash(pw_hash, 'insert awesome password here') # returns True
Ejemplo n.º 17
0
 def verify_password(self, password):
     bcrypt = Bcrypt()
     return bcrypt.check_password_hash(self.password, password)
Ejemplo n.º 18
0
class Auth:
    GHOST = 0
    USER = 1
    ADMIN = 2
    SUPER_ADMIN = 3

    class Anonymous(AnonymousUserMixin):
        def __init__(self):
            self._id = None

        def get_id(self):
            return unicode('')

    def __init__(self):
        self.__login_manager = LoginManager()
        self.config = {}

    def init_app(self, app, config):
        print 'Attaching LoginManager to app.'
        self.__login_manager.init_app(app)
        self.__login_manager.anonymous_user = Auth.Anonymous
        self.config = config

        def load_user(user_id):
            if user_id == '':
                return None

            Users = Database['Users']
            try:
                return Users.User.find_one({'_id': ObjectId(user_id)})
            except:
                return None

        def unauthorized():
            return jsonify(error='Unauthorized'), HTTP_401_UNAUTHORIZED

        self.__login_manager.user_loader(load_user)
        self.__login_manager.unauthorized_handler(unauthorized)

        self.__bcrypt = Bcrypt(app)

    def login_manager(self):
        return self.__login_manager

    def require(self, user_level):
        def login_required(f):
            @wraps(f)
            def decorated_function(*args, **kwargs):
                if current_user.is_authenticated(
                ) and current_user.get_access_level() >= user_level:
                    return f(*args, **kwargs)
                return self.__login_manager.unauthorized()

            return decorated_function

        return login_required

    def login(self, user_object, password):
        if user_object is not None:
            if self.__bcrypt.check_password_hash(user_object['password'],
                                                 password):
                if not login_user(user_object):
                    return resource_strings["USER_NOT_ACTIVATED"]
            else:
                return 'Invalid password'
        else:
            return 'Invalid email'
        return None

    def login_social(self, login_type, token):
        user_object = None

        try:
            user_object = SocialSignin.verify(login_type, token)
        except SocialSignin.Invalid as e:
            return str(e)

        login_user(user_object)

    def logout(self):
        logout_user()

    def hash_password(self, password):
        return self.__bcrypt.generate_password_hash(password)

    # decorator that protects other users from PUT/POST/DELETE on you stuff
    # user_id _must_ be passed in as 'user_id'
    def only_me(self, function):
        @wraps(function)
        def inner(*args, **kwargs):
            if kwargs['user_id'] != 'me':
                return '{}', HTTP_401_UNAUTHORIZED
            return function(*args, **kwargs)

        return inner
Ejemplo n.º 19
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bcrypt import Bcrypt
from momentjs import momentjs
from rendering_options import options

app = Flask(__name__)
app.config.from_object('config')
app.jinja_env.globals[
    'momentjs'] = momentjs  #Allow Jinja templates to use momentjs

for key, value in options.iteritems():
    app.jinja_env.globals[key] = value

# Tell Jinja to strip whitespace
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

db = SQLAlchemy(app)

#Generate an encrypter
bcrypt = Bcrypt(app)
'''
bcrypt has two essential functions:
pw_hash = bcrypt.generate_password_hash('some_string')
bcrypt.check_password_hash(pw_hash, 'some_string) returns True
'''

from app import views, models
Ejemplo n.º 20
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bcrypt import Bcrypt
from momentjs import momentjs
from rendering_options import options

app = Flask(__name__)
app.config.from_object('config')
app.jinja_env.globals['momentjs'] = momentjs #Allow Jinja templates to use momentjs

for key, value in options.iteritems():
	app.jinja_env.globals[key] = value

# Tell Jinja to strip whitespace
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

db = SQLAlchemy(app)

#Generate an encrypter
bcrypt = Bcrypt(app)
'''
bcrypt has two essential functions:
pw_hash = bcrypt.generate_password_hash('some_string')
bcrypt.check_password_hash(pw_hash, 'some_string) returns True
'''

from app import views, models