예제 #1
1
class LongPasswordsTestCase(BasicTestCase):

    def setUp(self):
        app = flask.Flask(__name__)
        app.config['BCRYPT_LOG_ROUNDS'] = 6
        app.config['BCRYPT_HASH_IDENT'] = '2b'
        app.config['BCRYPT_HANDLE_LONG_PASSWORDS'] = True
        self.bcrypt = Bcrypt(app)

    def test_long_password(self):
        """Test the work around bcrypt maximum password length."""

        # Create a password with a 72 bytes length
        password = '******' * 72
        pw_hash = self.bcrypt.generate_password_hash(password)
        # Ensure that a longer password **do not** yield the same hash
        self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'A' * 80))
예제 #2
0
파일: user.py 프로젝트: RahyabGroup/PyCore
 def password_change(self, new_password):
     from pyclaim.domain.aggregates.token.model.token import Token
     self.user_name = user_reader.user_name_get_by_id(self._id)
     bcrypt = Bcrypt(None)
     password_hash = bcrypt.generate_password_hash(new_password)
     self.password = password_hash
     user_writer.password_change(self._id, password_hash)
     Token.remove_by_user_id(self._id)
예제 #3
0
class BasicTestCase(unittest.TestCase):

    def setUp(self):
        app = flask.Flask(__name__)
        app.config['BCRYPT_LOG_ROUNDS'] = 6
        app.config['BCRYPT_HASH_IDENT'] = '2b'
        self.bcrypt = Bcrypt(app)

    def test_is_string(self):
        pw_hash = self.bcrypt.generate_password_hash('secret')
        if PY3:
            self.assertTrue(isinstance(pw_hash, bytes))
        else:
            self.assertTrue(isinstance(pw_hash, str))

    def test_custom_rounds(self):
        password = '******'
        pw_hash1 = self.bcrypt.generate_password_hash(password, 5)
        self.assertNotEqual(password, pw_hash1)

    def test_check_hash(self):
        pw_hash = self.bcrypt.generate_password_hash('secret')
        # check a correct password
        self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'secret'))
        # check an incorrect password
        self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'hunter2'))
        # check unicode
        pw_hash = self.bcrypt.generate_password_hash(u'\u2603')
        self.assertTrue(self.bcrypt.check_password_hash(pw_hash, u'\u2603'))
        # check helpers
        pw_hash = generate_password_hash('hunter2')
        self.assertTrue(check_password_hash(pw_hash, 'hunter2'))

    def test_check_hash_unicode_is_utf8(self):
        password = u'\u2603'
        pw_hash = self.bcrypt.generate_password_hash(password)
        # check a correct password
        self.assertTrue(self.bcrypt.check_password_hash(pw_hash, b'\xe2\x98\x83'))

    def test_rounds_set(self):
        self.assertEqual(self.bcrypt._log_rounds, 6)

    def test_unicode_hash(self):
        password = u'東京'
        h = generate_password_hash(password).decode('utf-8')
        self.assertTrue(check_password_hash(h, password))
예제 #4
0
파일: user.py 프로젝트: RahyabGroup/PyCore
 def password_remember(user_name):
     from pyclaim.domain.aggregates.token.model.token import Token
     user = User.get_by_user_name(user_name)
     new_password = str(randint(10000000, 99999999))
     bcrypt = Bcrypt(None)
     password_hash = bcrypt.generate_password_hash(new_password)
     user.password = new_password
     user_writer.password_change(user._id, password_hash)
     Token.remove_by_user_id(user._id)
     return user
예제 #5
0
    def create_sysadmin(role_claim_type):
        from pyclaim.domain.aggregates.user.model.user import User
        from pyclaim.domain.aggregates.user.model.claim import Claim
        from pyclaim.domain.aggregates.user.app.v1_0.rest.assembler import user_writer, user_reader

        try:
            user_id = "560121abcbf62c13d4567f0d"
            if not user_reader.exist_id(user_id):
                from pyclaim.domain.aggregates.user.model.status import Status
                sysadmin_user_name = "*****@*****.**"
                sysadmin = User()
                sysadmin._id = user_id
                sysadmin.user_name = sysadmin_user_name
                sysadmin.status = Status.activated
                bcrypt = Bcrypt(None)
                password_hash = bcrypt.generate_password_hash(sysadmin_user_name)
                sysadmin.password = password_hash
                sysadmin_claim = Claim()
                sysadmin_claim.claim_type_id = role_claim_type._id
                sysadmin_claim.value = "SYSADMIN"
                sysadmin.claims.append(sysadmin_claim)
                user_writer.create(sysadmin)

            super_user_id = "580e04a33ae7280ae09d93a5"
            if not user_reader.exist_id(super_user_id):
                from pyclaim.domain.aggregates.user.model.status import Status
                super_admin_user_name = "*****@*****.**"
                super_admin = User()
                super_admin._id = user_id
                super_admin.user_name = super_admin_user_name
                super_admin.status = Status.activated
                bcrypt = Bcrypt(None)
                password_hash = bcrypt.generate_password_hash("M0t@n@w3b")
                super_admin.password = password_hash
                super_admin_claim = Claim()
                super_admin_claim.claim_type_id = role_claim_type._id
                super_admin_claim.value = "SYSADMIN"
                super_admin.claims.append(super_admin_claim)
                user_writer.create(super_admin)
        except Exception as ex:
            pass
예제 #6
0
class BasicTestCase(unittest.TestCase):

    def setUp(self):
        app = flask.Flask(__name__)
        app.config['BCRYPT_LOG_ROUNDS'] = 6
        app.config['BCRYPT_HASH_IDENT'] = '2b'
        app.config['BCRYPT_HANDLE_LONG_PASSWORDS'] = False
        self.bcrypt = Bcrypt(app)

    def test_is_string(self):
        pw_hash = self.bcrypt.generate_password_hash('secret')
        if PY3:
            self.assertTrue(isinstance(pw_hash, bytes))
        else:
            self.assertTrue(isinstance(pw_hash, str))

    def test_custom_rounds(self):
        password = '******'
        pw_hash1 = self.bcrypt.generate_password_hash(password, 5)
        self.assertNotEqual(password, pw_hash1)

    def test_check_hash(self):
        pw_hash = self.bcrypt.generate_password_hash('secret')
        # check a correct password
        self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'secret'))
        # check an incorrect password
        self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'hunter2'))
        # check unicode
        pw_hash = self.bcrypt.generate_password_hash(u'\u2603')
        self.assertTrue(self.bcrypt.check_password_hash(pw_hash, u'\u2603'))
        # check helpers
        pw_hash = generate_password_hash('hunter2')
        self.assertTrue(check_password_hash(pw_hash, 'hunter2'))

    def test_check_hash_unicode_is_utf8(self):
        password = u'\u2603'
        pw_hash = self.bcrypt.generate_password_hash(password)
        # check a correct password
        self.assertTrue(self.bcrypt.check_password_hash(pw_hash, b'\xe2\x98\x83'))

    def test_rounds_set(self):
        self.assertEqual(self.bcrypt._log_rounds, 6)

    def test_unicode_hash(self):
        password = u'東京'
        h = generate_password_hash(password).decode('utf-8')
        self.assertTrue(check_password_hash(h, password))

    def test_long_password(self):
        """Test bcrypt maximum password length.

        The bcrypt algorithm has a maximum password length of 72 bytes, and
        ignores any bytes beyond that."""

        # Create a password with a 72 bytes length
        password = '******' * 72
        pw_hash = self.bcrypt.generate_password_hash(password)
        # Ensure that a longer password yields the same hash
        self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'A' * 80))
예제 #7
0
    def run(self):
        prod = input("Is this a production seed? [yes/no]" + "\n")

        if str(prod).lower() == "yes" and not self.check_safe():
            return

        bcrypt = Bcrypt(flask.current_app)
        db = SQLAlchemy(flask.current_app)

        # seed roles
        from users.models.role import Role

        admin_role = Role(
            name="administrator",
            display_name="Administrator",
            description="Can administrate site",
        )
        db.session.add(admin_role)

        writer_role = Role(
            name="writer", display_name="Writer", description="Can write posts for site"
        )
        db.session.add(writer_role)

        user_role = Role(name="user", display_name="User", description="Basic user")
        db.session.add(user_role)

        # seed user
        admin_username = flask.current_app.config["ADMIN_INIT_USERNAME"]
        admin_password = flask.current_app.config["ADMIN_INIT_PASSWORD"]
        admin_password_hashed = bcrypt.generate_password_hash(admin_password).decode(
            "utf-8"
        )
        admin_email = flask.current_app.config["ADMIN_INIT_EMAIL"]

        from users.models.user import User

        admin_user = User(
            username=admin_username,
            password=admin_password_hashed,
            email=admin_email,
            active=True,
            email_confirmed_at=datetime.datetime.now(),
        )

        admin_user.roles.append(admin_role)
        admin_user.roles.append(writer_role)

        db.session.add(admin_user)
        db.session.commit()
예제 #8
0
파일: user.py 프로젝트: RahyabGroup/PyCore
    def create(self):
        from pyclaim.domain.aggregates.claim_type.model.claim_type import ClaimType

        user_name_claim_type = ClaimType.get_by_name("USER_NAME")

        user_default_claim = Claim()
        user_default_claim.claim_type_id = user_name_claim_type._id
        user_default_claim.value = self.user_name
        self.claims.append(user_default_claim)

        self.status = Status.activated
        bcrypt = Bcrypt(None)
        password_hash = bcrypt.generate_password_hash(self.password)
        self.password = password_hash
        user_writer.create(self)
예제 #9
0
class AuthModule():
    def __init__(self, app, usersCollection):
        self.usersCollection = usersCollection
        self.bcrypt = Bcrypt(app)
        app.config['SECRET_KEY'] = SECRET
        app.config['JWT_AUTH_USERNAME_KEY'] = 'email'
        app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=7*24*60*60) # 7 days

    class User(object):
        def __init__(self, id, username, password, name):
            self.id = username
            self.username = username
            self.name = name
            self.password = password

        def __str__(self):
            return "User(id='%s')" % self.id

    def authenticate(self, username, password):
        user = list(self.usersCollection.find({"_id":username})).pop()
        if user and self.bcrypt.check_password_hash(user.get("password"), password):
            return self.User(user.get("_id"), user.get("_id"), user.get("password"), user.get("name"))
        return

    def identity(self, payload):
        user_id = payload['identity']
        user = list(self.usersCollection.find({"_id":user_id})).pop()
        return self.User(user.get("_id"), user.get("_id"), user.get("password"), user.get("name"))
    
    def registerUser(self, request):
        jsonData = request.json
        user = {
            '_id': jsonData['email'],
            'password': self.bcrypt.generate_password_hash(jsonData['password']),
            'name': jsonData['displayName']
        }
        id = self.usersCollection.insert_one(user).inserted_id
        return jsonify({'id':id})
예제 #10
0
        for key in self.__mapper__.c.keys():
            result[key] = getattr(self, key)
        return result


db.drop_all()
db.create_all()

#testing
tmpuser = User()
tmpuser.username="******"
pw = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
print "Username: "******"Password: "******"""Given *user_id*, return the associated User object.

    :param unicode user_id: user_id (email) user to retrieve
    """
    return User.query.get(user_id)


@app.route('/dashboard')
@login_required
def dashboard():
예제 #11
0

class userCheckForm(Form):
    textbox = TextAreaField('textbox', [
        validators.DataRequired(message="Enter User To Check Audit History"),
        validators.Length(max=20)
    ],
                            id='inputtext')


db.drop_all()
db.create_all()

adminToAdd = User(
    username='******',
    password=bcrypt.generate_password_hash('Administrator@1').decode('utf-8'),
    twofactor='12345678901',
    level='admin')
db.session.add(adminToAdd)
db.session.commit()


@login_manager.user_loader
def user_loader(username):
    return userCreds.query.get(username)


@app.route('/')
def home():
    if not session.get('logged_in'):
        # form = LoginForm()
from flask_bcrypt import Bcrypt

bcrypt = Bcrypt()

password = '******'

hashed_password = bcrypt.generate_password_hash(password=password)

print(hashed_password)

check = bcrypt.check_password_hash(hashed_password, 'wrongpassword')
print(check)
예제 #13
0
for y in range(1, 4):
    for i in range(1, 7):
        seat = Seat(row=y, number=i, hall_id=1, is_busy="")
        db.session.add(seat)

for y in range(1, 4):
    for i in range(1, 7):
        seat = Seat(row=y, number=i, hall_id=2, is_busy="")
        db.session.add(seat)

for y in range(1, 4):
    for i in range(1, 7):
        seat = Seat(row=y, number=i, hall_id=3, is_busy="")
        db.session.add(seat)

hashed_password = bcrypt.generate_password_hash("admin").decode(
    'utf-8')  # hash password for user
admin = User(username="******",
             email="*****@*****.**",
             password=hashed_password,
             role="Admin")
db.session.add(admin)

hashed_password = bcrypt.generate_password_hash("user1").decode(
    'utf-8')  # hash password for user
user_1 = User(username="******",
              email="*****@*****.**",
              password=hashed_password,
              role="User")
db.session.add(user_1)

hashed_password = bcrypt.generate_password_hash("user2").decode(
예제 #14
0
@author: logan
"""

from Assignment_5 import db
# but we can also import the respective classes for each table
from Assignment_5 import User, Post
from flask_bcrypt import Bcrypt
import pandas as pd
bcrypt = Bcrypt()
db.create_all()
User.query.all()
user1 = User(name="Obiwan",
             surname="Kenobi",
             username="******",
             email="*****@*****.**",
             password=bcrypt.generate_password_hash(password="******"))

user2 = User(name="Yoda",
             surname="Master",
             username="******",
             email="*****@*****.**",
             password=bcrypt.generate_password_hash(password="******"))

db.session.add(user1)
db.session.add(user2)

db.session.commit()

post1 = Post(name="Super Quote",
             description="""Do. Or do not. There is no try.""",
             length=len("""Do. Or do not. There is no try."""),
예제 #15
0
def init_flask_app(static_folder, db_path, secret):
    app = Flask(__name__, static_folder=static_folder)
    login_manager = LoginManager()
    migrate = Migrate(app, db)
    bcrypt = Bcrypt(app)

    app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///" + db_path
    app.secret_key = secret
    app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024

    db.init_app(app)
    db.app = app
    login_manager.init_app(app)

    if not os.path.exists(db_path):

        print("Creates database")
        db.create_all()

        pw =bcrypt.generate_password_hash("p").decode("utf-8")

        db.session.add(User(uuid="admin", name="admin", password=pw, email="", gym="UnknowGym", role="ADMIN"))
        db.session.commit()


    @login_manager.user_loader
    def load_user(user_id):
        user = db.session.query(User).filter_by(name=user_id).first()
        if user is None:
            return None
        return UserClass(user_id)

    @app.route('/', methods=['GET'])
    def index():
        with open("privacy.html") as f:
            return f.read()
        return "JOHN"

    @app.route('/privacy', methods=['GET', 'POST'])
    def privacy():
        return app.send_static_file("privacy.html")

    @app.route('/add_rute', methods=['POST'])
    @login_required
    def upload():
        uuid = request.json['uuid']
        if db.session.query(Rute).filter_by(uuid=uuid).first() is not None:
            abort(400)

        name = request.json['name']
        image = request.json['image']
        author = request.json['author']
        sector = request.json['sector']
        gym = request.json['gym']
        date = request.json['date']
        edit = request.json['edit']
        date = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
        edit = datetime.strptime(edit, '%Y-%m-%d %H:%M:%S')
        grade = request.json.get('grade', 0)
        tag = request.json.get('tag', "[]")
        coordinates = request.json.get("coordinates", "[]")

        db.session.add(Rute(uuid=uuid, name=name, coordinates=coordinates, author=author, sector=sector, date=date, edit=edit, image=image, grade=grade, gym=gym, tag=tag))
        db.session.commit()

        return str(db.session.query(Rute).order_by(Rute.id.desc()).first().id)


    @app.route('/add_image/<string:uuid>', methods=['POST'])
    @login_required
    def upload_image(uuid):
        f = request.files['data']
        filename = os.path.join(app.static_folder, "{}.jpg".format(uuid))
        if os._exists(filename):
            abort(400)
        f.save(filename)
        db.session.add(Image(uuid=uuid, url=filename))
        db.session.commit()
        return "Succes"


    @app.route('/login', methods=['POST'])
    def login():
        username = request.json['username']
        password = request.json['password']#.decode('utf-8')

        user = db.session.query(User).filter_by(name=username).first()

        if user is None:
            abort(400)

        if not bcrypt.check_password_hash(user.password, password):
            abort(400)

        login_user(UserClass(username))

        return user.uuid


    @app.route('/logout', methods=['GET'])
    def logout():
        logout_user()
        return "Succes"


    @app.route("/complete", methods=['POST'])
    @login_required
    def complete():
        try:
            rute = request.json["rute"]
            user = request.json["user"]
            tries = request.json["tries"]
        except KeyError:
            abort(400)


        u = db.session.query(User).filter_by(uuid=user).first().id
        r = db.session.query(Rute).filter_by(uuid=rute).first().id
        complete = db.session.query(Complete).filter_by(user=u, rute=r).first()

        if complete is None:
            db.session.add(Complete(tries=tries,
                                    user = db.session.query(User).filter_by(uuid=user).first().id,
                                    rute = db.session.query(Rute).filter_by(uuid=rute).first().id
                                    ))
        else:
            complete.tries = tries


        db.session.commit()
        return "Succes"


    @app.route('/save_rute', methods=['POST'])
    @login_required
    def save_rute():

        uuid = request.json['uuid']

        coordinates = request.json['coordinates']
        edit = request.json['edit']
        edit = datetime.strptime(edit, '%Y-%m-%d %H:%M:%S')
        rute = db.session.query(Rute).filter_by(uuid=uuid).first()
        if rute is None:
            abort(400)
        rute.coordinates = coordinates
        if "name" in request.json:
            rute.name = request.json["name"]
        if "gym" in request.json:
            rute.gym = request.json["gym"]
        if 'grade' in request.json:
            rute.grade = request.json['grade']
        if 'sector' in request.json:
            rute.sector = request.json['sector']
        if 'tag' in request.json:
            rute.tag = request.json['tag']
        rute.edit = edit
        db.session.commit()
        return "Succes"


    @app.route('/add_user', methods=['POST'])
    def add_user():
        username = request.json['username']
        password = request.json['password']
        password = bcrypt.generate_password_hash(password).decode('utf-8')
        email= request.json['email']

        uuid = request.json['uuid']
        role = request.json.get('role', 'USER')

        if role not in ["USER", "ADMIN"]:
            abort(400)

        if db.session.query(User).filter_by(name=username).first():
            abort(400)

        db.session.add(User(uuid=uuid, name=username, password=password, email=email, role=role))
        db.session.commit()
        return "Succes"


    @app.route('/add_gym', methods=['POST'])
    @login_required
    def add_gym():
        name = request.json['name']
        uuid = request.json['uuid']
        sectors = request.json['sectors']
        tags = request.json['tags']
        admin = request.json['admin']

        if db.session.query(Gym).filter_by(name=name).first() is not None:
            abort(400)

        db.session.add(Gym(uuid=uuid, name=name, admin=admin, sectors=sectors, tags=tags))
        db.session.commit()
        return "Succes"


    @app.route('/save_gym', methods=['POST'])
    @login_required
    def save_gym():
        name = request.json['name']
        uuid = request.json['uuid']
        sectors = request.json['sectors']
        tags = request.json['tags']
        edit = request.json['edit']
        edit = datetime.strptime(edit, '%Y-%m-%d %H:%M:%S')

        gym = db.session.query(Gym).filter_by(uuid=uuid).first()
        if gym is None:
            abort(400)

        gym.name = name
        gym.sectors = sectors
        gym.tags = tags
        gym.edit = edit

        db.session.commit()
        return "Succes"


    @app.route('/check_username/<string:name>', methods=['POST'])
    def check_name(name):

        user = db.session.query(User).filter_by(name=name).first()
        if user is None:
            return "Success"
        else:
            abort(400)


    @app.route('/get_rutes', methods=['GET','POST'])
    @login_required
    def get_rutes():


        query = db.session.query(Rute)

        last_sync = '1900-02-13 22:25:33'
        if request.json and 'last_sync' in request.json:
            last_sync = request.json.get('last_sync')
            query = query.filter(Rute.edit > last_sync)

        if "gym" in request.headers:
            query = query.filter(Rute.gym == request.headers["gym"])


        r = {str(rute.id): {"author": rute.author,
                            "grade": rute.grade,
                            "date": str(rute.date),
                            "edit": str(rute.edit),
                            "coordinates": rute.coordinates,
                            "gym": rute.gym,
                            "sector": rute.sector,
                            "tag": rute.sector,
                            "name": rute.name,
                            "image": rute.image,
                            "uuid": rute.uuid,
                            "tag": rute.tag,
                            "status": rute.status,
                            "completes": [{
                                "user": u.uuid,
                                "tries": c.tries,
                                "date": str(c.date)
                            } for c,u in db.session.query(Complete,User).join(Complete, User.id == Complete.user).filter(Complete.rute == rute.id)]}
             for rute in query}

        r.update({"last_sync": str(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'))})
        return jsonify(r), 200


    @app.route('/download/<string:uuid>', methods=['GET', 'POST'])
    @login_required
    def download_image(uuid):

        img = db.session.query(Image).filter_by(uuid=uuid).first()
        if img is None:
            abort(400)
        expected_path = os.path.join(app.static_folder, os.path.basename(img.url))
        if not os.path.exists(expected_path):
            abort(400)
        return send_from_directory(app.static_folder, os.path.relpath(expected_path, app.static_folder))


    @app.route('/delete/<string:uuid>', methods=['GET','POST'])
    @login_required
    def delete_image(uuid):
        rute = db.session.query(Rute).filter_by(uuid=uuid).first()
        if rute is not None:
            rute.status = 1
            rute.edit = datetime.utcnow()
        db.session.commit()

        return "Succes", 200


    @app.route('/delete_gym/<string:uuid>', methods=['POST'])
    @login_required
    def delete_gym(uuid):
        gym = db.session.query(Gym).filter_by(uuid=uuid).first()
        if gym is not None:
            gym.status = 1
            gym.edit = datetime.utcnow()
        db.session.commit()

        return "Succes", 200


    @app.route('/delete_user/<string:uuid>', methods=['POST'])
    @login_required
    def delete_user(uuid):
        user = db.session.query(User).filter_by(uuid=uuid).first()
        if user is not None:
            user.status = 1
            user.edit = datetime.utcnow()
        db.session.commit()

        return "Succes", 200


    @app.route('/check_gymname/<string:name>', methods=['POST'])
    def check_gymname(name):

        gym = db.session.query(Gym).filter_by(name=name).first()
        if gym is None:
            return "Success"
        else:
            abort(400)


    @app.route('/get_gyms', methods=['GET'])
    @login_required
    def get_gyms():
        r = {gym.id: {"lat": gym.lat,
                      "date": str(gym.date),
                      "edit": str(gym.edit),
                      "status": gym.status,
                      "lon": gym.lon,
                      "name": gym.name,
                      "uuid": gym.uuid,
                      "admin": gym.admin,
                      "n_rutes": db.session.query(Rute).filter_by(gym=gym.uuid, status=0).count(),
                      "tags": gym.tags,
                      "sectors": gym.sectors}
             for gym in db.session.query(Gym)}
        return jsonify(r), 200


    @app.route('/get_gym/<string:uuid>', methods=['GET'])
    @login_required
    def get_gym(uuid):

        gym = db.session.query(Gym).filter_by(uuid=uuid).first()
        r = {uuid: {"lat": gym.lat,
                    "date": str(gym.date),
                    "edit": str(gym.edit),
                    "status": gym.status,
                    "lon": gym.lon,
                    "name": gym.name,
                    "uuid": gym.uuid,
                    "n_rutes": db.session.query(Rute).filter_by(gym=gym.uuid, status=0).count(),
                    "admin": gym.admin,
                    "tags": gym.tags,
                    "sectors": gym.sectors}}
        return jsonify(r), 200


    @app.route('/get_users', methods=['GET'])
    @login_required
    def get_users():
        r = {user.id: {"gym": user.gym,
                       "date": str(user.date),
                       "name": user.name,
                       "email": user.email,
                       #"password":   user.password,
                       "role": user.role,
                       "uuid": user.uuid}
             for user in db.session.query(User)}

        return jsonify(r), 200


    @app.route('/get_user/<string:uuid>', methods=['GET'])
    @login_required
    def get_user(uuid):

        user = db.session.query(User).filter_by(uuid=uuid).first()

        r = {user.id: {"gym": user.gym,
                       "date": str(user.date),
                       "name": user.name,
                       #"password": user.password,
                       "uuid": user.uuid,
                       "role": user.role,
                       "email": user.email}}

        return jsonify(r), 200


    @app.route('/get_comp/<int:pin>', methods=['GET'])
    def get_comp(pin):
        comp = db.session.query(competition.Competition).filter_by(pin=pin).first()
        if comp is None:
            abort(400)

        r = {"uuid": comp.uuid,
             "name": comp.name,
             "date": str(comp.date),
             "edit": str(comp.edit),
             "start": str(comp.start),
             "stop": str(comp.stop),
             "type": comp.type,
             "admins": comp.admins.split(","),
             "pin": comp.pin,
             "rutes": [rute.uuid for rute, _ in db.session.query(Rute, competition.CompetitionRutes).filter(
                 competition.CompetitionRutes.comp == comp.uuid).filter(competition.CompetitionRutes.rute == Rute.uuid).filter(Rute.status != 1)]
             }

        return jsonify(r), 200


    @app.route('/get_participated_comps/<string:user>', methods=['GET'])
    def get_participated_comps(user):
        comp = db.session.query(competition.CompetitionParticipation).filter_by(user=user)

        comps = list(set([c.comp for c in comp]))

        return jsonify(comps), 200


    @app.route('/get_comps', methods=['GET'])
    def get_comps():
        r = [{"uuid": comp.uuid,
              "name": comp.name,
              "date": str(comp.date),
              "edit": str(comp.edit),
              "start": str(comp.start),
              "stop": str(comp.stop),
              "type": comp.type,
              "admins": comp.admins.split(","),
              "pin": comp.pin,
              "rutes": [rute.uuid for rute, _ in db.session.query(Rute, competition.CompetitionRutes).filter(
                  competition.CompetitionRutes.comp == comp.uuid).filter(competition.CompetitionRutes.rute == Rute.uuid).filter(Rute.status != 1)]
              } for comp in db.session.query(competition.Competition)]
        #print(r)
        return jsonify(r), 200


    @app.route('/get_part', methods=['POST'])
    def get_participation():
        comp = request.json['comp']
        user = request.json['user']
        rute = request.json['rute']

        p = db.session.query(competition.CompetitionParticipation).filter_by(comp=comp, user=user, rute=rute).first()
        if p is None:
            tries = 0
            completed = 0
            date = "1970-01-01 00:00:00"
        else:
            tries = p.tries
            completed = p.completed
            date = str(p.date)

        r = {"user": user,
             "comp": comp,
             "rute": rute,
             "tries": tries,
             "completed": completed,
             "date": date}

        return jsonify(r), 200


    def parse_or_now(key, container):
        if key in container:
            return datetime.strptime(container[key],'%Y-%m-%d %H:%M:%S')
        else:
            return datetime.utcnow()


    @app.route('/update_part', methods=['POST'])
    def update_participation():
        comp = request.json['comp']
        user = request.json['user']
        rute = request.json['rute']
        tries = request.json['tries']
        date = parse_or_now("date", request.json)
        edit = parse_or_now("edit", request.json)
        completed = request.json['completed']

        part = db.session.query(competition.CompetitionParticipation).filter_by(comp=comp, user=user, rute=rute).first()
        if part is None:
            db.session.add(competition.CompetitionParticipation(comp=comp, user=user, rute=rute, tries=tries, completed=completed, date=date, edit=edit))
            db.session.commit()
        else:
            part.tries = tries
            part.completed = completed
            part.edit = edit
            db.session.commit()

        return "Success", 200


    @app.route('/add_rute_comp', methods=['POST'])
    def add_rute():
        comp = request.json['comp']
        rute = request.json['rute']
        date = parse_or_now("date", request.json)

        db.session.add(competition.CompetitionRutes(comp=comp, rute=rute, date=date))
        db.session.commit()

        return "Success", 200


    @app.route('/update_comp', methods=['POST'])
    def update_comp():
        uuid = request.json['uuid']
        name = request.json['name']
        date = parse_or_now("date", request.json)
        edit = parse_or_now("edit", request.json)
        start = parse_or_now("start", request.json)
        stop = parse_or_now("stop", request.json)
        type = request.json['type']
        admins = request.json['admins']

        comp = db.session.query(competition.Competition).filter_by(uuid=uuid).first()
        if comp is None:
            pin = randint(1000, 9999)
            while db.session.query(competition.Competition).filter_by(pin=pin).first():
                pin = randint(1000, 9999)
            db.session.add(competition.Competition(uuid=uuid, name=name, edit=edit, start=start, stop=stop, type=type, admins=admins, date=date, pin=pin))
            db.session.commit()
        else:
            pin = comp.pin
            comp.name = name
            comp.edit = edit
            comp.start = start
            comp.stop = stop
            comp.type = type
            comp.admins = admins
            db.session.commit()

        return "{}".format(pin), 200


    @app.route('/get_stats/<int:pin>', methods=['GET'])
    def get_stats(pin):
        comp = db.session.query(competition.Competition).filter_by(pin=pin).first()
        if comp is None:
            abort(400)

        r = [{"user": p.user,
              "rute": p.rute,
              "tries": p.tries,
              "date": str(p.date),
              "completed": p.completed} for p in db.session.query(competition.CompetitionParticipation).filter(
            competition.CompetitionParticipation.comp == comp.uuid)]

        return jsonify(r), 200

    return app
예제 #16
0
파일: api.py 프로젝트: ryuz4k1/splitApp
 def __generate_hash(self, password):
     bcrypt = Bcrypt()
     return bcrypt.generate_password_hash(password,
                                          rounds=10).decode("utf-8")
예제 #17
0
from application import views

#Ingredient
from application.ingredients import models
from application.ingredients import views

#User
from application.auth import models
from application.auth import views

#Recipe
from application.recipe import models
from application.recipe import views

from application.auth.models import User


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(user_id)


db.create_all()

#Populate the db with one admin account if user table is empty
if not User.query.first():
    user = User("admin",
                bcrypt.generate_password_hash("password1").decode("utf-8"),
                True)
    db.session.add(user)
    db.session.commit()
예제 #18
0
class AuthenticationController(FlaskView):
    def __init__(self):
        self.bcrypt = Bcrypt()
        self.tbs = TokenBlackListService()

    @route("/register", methods=["POST"])
    @inject("aus")
    def registers(self, aus: AppUserService):
        auth_user_json = request.json
        data, errors = AuthUser().load(auth_user_json)
        if bool(errors):
            return jsonify(errors)
        auth_user = aus.getOneByName(auth_user_json['username'])
        if 'username' in auth_user:
            return jsonify({
                "success": False,
                "message": "username already exist"
            })
        pw_hash = self.bcrypt.generate_password_hash(
            auth_user_json['password'])
        data['password'] = pw_hash.decode('utf8')
        aus.create(data)
        return jsonify({"success": True}), 201

    @route("/login", methods=["POST"])
    @inject("aus")
    def login(self, aus: AppUserService):
        auth_user_json = request.json
        data, errors = AuthUser().load(auth_user_json)
        if bool(errors):
            return jsonify(errors), 405

        auth_user = aus.getOneByName(auth_user_json['username'])
        if 'username' not in auth_user:
            return jsonify({
                "success": False,
                "message": "username not found"
            }), 400
        if self.bcrypt.check_password_hash(auth_user['password'],
                                           auth_user_json['password']):
            success, message = encode_auth_token()
            if not success:
                return jsonify({
                    "success": False,
                    "token": "Server error env_secret"
                })
            return jsonify({"success": True, "token": message})
        else:
            return jsonify({
                "success": False,
                "message": "Username or Password incorrect"
            }), 400

    @route("/logout", methods=["POST"])
    def logout(self):
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({"Error": "Authorization"})
        else:
            success, message = decode_auth_token(token)
            if not success:
                return jsonify({"Error": message})
            else:
                self.tbs.addToTokenBlackList(token)
                return jsonify({
                    "success": True,
                    "message": "Logout successful!"
                })
예제 #19
0
class AuthService(object):
    """ Class to handle the users authentication.
    The authentication method is JWT.
    """
    def __init__(self):
        self.crud_service = DependencyInjectionsService.get_instance(
        ).get_service(CrudService)
        self.query_manager = DependencyInjectionsService.get_instance(
        ).get_service(QueryManager)
        self.bcrypt = Bcrypt()

    def login(self, login, password):
        results = self.query_manager.search('users', {
            '$filter': {
                'login': login
            },
            '$size': 1
        })

        if len(results) != 1:
            raise AppException('Authentication failed', 401)
        user = results[0]

        if not self.bcrypt.check_password_hash(user['password'], password):
            raise AppException('Authentication failed', 401)

        token = self.generate_auth_token(user['id'])
        user['tokens'].append(token)

        self.query_manager.upsert('users', [user])

        return {'login': user['login'], 'token': token}

    def login_for_api(self, login):
        results = self.query_manager.search('users',
                                            {'$filter': {
                                                'login': login
                                            }})

        if len(results) != 1:
            raise AppException('Authentication failed', 401)

        token = self.generate_auth_token(user['id'])
        user['tokens'].append(token)

        self.query_manager.upsert('users', [user])

        return {'login': user['login'], 'token': token}

    def get_user_by_token(self, token):
        payload = jwt.decode(token,
                             DatabaseContext.PASSWORDS_SECRET_KEY,
                             algorithms=['HS256'])
        results = self.query_manager.search(
            'users', {'$filter': {
                'id': payload['sub'],
                'tokens': token
            }})

        if len(results) != 1:
            raise AppException('Authentication failed', 401)
        return results[0]

    def generate_auth_token(self, user_id):
        payload = {'iat': datetime.utcnow(), 'sub': user_id}
        return jwt.encode(payload,
                          DatabaseContext.PASSWORDS_SECRET_KEY,
                          algorithm='HS256').decode()

    def logout(self, token):
        payload = jwt.decode(token,
                             DatabaseContext.PASSWORDS_SECRET_KEY,
                             algorithms=['HS256'])
        results = self.query_manager.search(
            'users', {'$filter': {
                'id': payload['sub'],
                'tokens': token
            }})

        if len(results) != 1:
            raise AppException('Authentication failed', 401)
        user = results[0]

        user['tokens'].remove(token)
        self.query_manager.upsert('users', [user])

        return user

    def logout_all(self, token):
        payload = jwt.decode(token,
                             DatabaseContext.PASSWORDS_SECRET_KEY,
                             algorithms=['HS256'])
        results = self.query_manager.search(
            'users', {'$filter': {
                'id': payload['sub'],
                'tokens': token
            }})

        if len(results) != 1:
            raise AppException('Authentication failed', 401)
        user = results[0]

        user['tokens'].clear()
        self.query_manager.upsert('users', [user])

        return user

    def create_user(self, new_user):
        # FIXME check if login already exists
        user = {
            'id':
            str(uuid.uuid4()),
            'login':
            new_user['login'],
            'password':
            self.bcrypt.generate_password_hash(
                new_user['password'],
                DatabaseContext.BCRYPT_LOG_ROUNDS).decode(),
            'tokens': []
        }
        result = self.query_manager.upsert('users', [user])[0]
        return result
예제 #20
0
    p = random.choice(purpose)
    x = random.randint(50, 600)
    d = random.choice(df)
    s = random.choice(supplier)
    cur.execute(
        "INSERT INTO medicine(med_id,med_name,med_brandname,med_purpose,med_expiry,dosage_form,med_price,med_role,med_quantity,med_supplier) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
        (i, "med" + str(i), "brand" + str(i), str(p), str(date), str(d),
         str(x), "local", str(randint(10, 300)), str(s)))
    cur.execute(
        "INSERT INTO medicine(med_id,med_name,med_brandname,med_purpose,med_expiry,dosage_form,med_price,med_role,med_quantity,med_supplier) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
        (i, "med" + str(i), "brand" + str(i + 1), str(p), str(date1), str(d),
         str(x / 3), "generic", str(randint(10, 300)), str(s)))
bcrypt = Bcrypt(app)

for i in range(7, 13):
    hashed_pass = bcrypt.generate_password_hash("user" +
                                                str(i)).decode('utf-8')
    cur.execute(
        "INSERT INTO login(user_email, user_pass, user_first_name, user_last_name, user_address, user_category) VALUES(%s, %s, %s, %s, %s, %s)",
        ("user" + str(i) + "@gmail.com", hashed_pass, "User", str(i),
         "address" + str(i), "customer"))

for i in range(1, 7):
    hashed_pass = bcrypt.generate_password_hash("supplier" +
                                                str(i)).decode('utf-8')
    cur.execute(
        "INSERT INTO login(user_email, user_pass, user_first_name, user_last_name, user_address, user_category) VALUES(%s, %s, %s, %s, %s, %s)",
        ("supplier" + str(i) + "@gmail.com", hashed_pass, "Supplier" + str(i),
         str(i), "address" + str(i), "supplier"))

connection.commit()
cur.close()
from flask_bcrypt import Bcrypt

# Example for making a hashed password
bcrypt = Bcrypt()
hashed_password = bcrypt.generate_password_hash('password')

# Each call to the bcrypt function will generate a new hashed string
print(hashed_password)
bcrypt.generate_password_hash('otherpassword').decode('utf-8')

# Compare the hashed password against other password
corrent_password = False
corrent_password = bcrypt.check_password_hash(hashed_password, 'notpassword')
print(corrent_password)
corrent_password = bcrypt.check_password_hash(hashed_password, 'password')
print(corrent_password)
예제 #22
0
def create(db):

    from interNect.models import User, Post, Pending, Company
    from flask_bcrypt import Bcrypt
    db.create_all()

    bcrypt = Bcrypt()
    password = bcrypt.generate_password_hash('1234').decode('utf-8')

    user = User(username='******',
                email='*****@*****.**',
                password=password,
                lname="Aman",
                fname="aman",
                gender='male')
    u = User(username='******',
             email='*****@*****.**',
             password=password,
             lname="Aman",
             fname="aman",
             gender='male')

    c = Company(company_name="Google", email="*****@*****.**", password=password)
    company = Company(company_name="Microsoft",
                      email="*****@*****.**",
                      password=password)

    db.session.add(user)
    db.session.add(u)
    db.session.add(c)
    db.session.add(company)

    db.session.commit()
    post = Post(
        title="IT intern",
        content=
        "Our Software Engineering company known for innovative technology seeks a self-directed IT intern with a passion for technology, collaboration, and creative problem-solving. The intern will actively contribute to meaningful projects and work closely with a mentor and with senior leadership.",
        company_id=1)
    post2 = Post(
        title="Software Engineering Intern",
        content=
        "Our Company seeks an intern with experience in software design, coding and debugging. The intern will gain exciting real-world software engineering experience at a thriving company. We frequently work in small teams to solve problems, explore new technologies, and learn from one another. The ideal intern for this environment will be enthusiastic and collaborative.",
        company_id=2)
    post3 = Post(
        title="Manufacturing Intern Job",
        content=
        "Our Company, an intense and exciting company, is looking for interns to join our creative team of engineers working to develop systems and analysis for a wide variety of companies and industries. Our engineers are hard-working, smart, goal-oriented and creative, and they are looking for interns to train to participate in every level of system design and orientation. The interns hired for this position should expect to learn all facets of manufacturing, and will leave this position with invaluable skills and industry knowledge. Also, this internship program is highly regarded in our field, so successful participation will be a great addition to your resume.",
        company_id=2)
    post4 = Post(
        title="Graphic Design Intern",
        content=
        "Are you a student interested in building real-world graphic design experience with an award-winning team? We’re a forward-thinking advertising agency looking for a talented and knowledgeable designer with fresh, creative ideas and an excellent eye for detail. Come work for one of the area’s leading advertising agencies and learn from some of the best in the business.",
        company_id=2)
    post5 = Post(
        title="HR (Human Resources) Intern",
        content=
        "Fast-growing marketing agency seeks a personable and highly motivated HR intern to support the HR manager in day-to-day administrative tasks and activities. If you’re ready to kickstart your career in Human Resources and build real-world experience with recruiting, payroll, employee development, and the coordination of HR policies and procedures, this is the internship for you.",
        company_id=2)
    db.session.add(post)
    db.session.add(post2)
    db.session.add(post3)
    db.session.add(post4)
    db.session.add(post5)
    db.session.commit()
    print("\n")
    print(Post.query.all())
예제 #23
0
파일: user.py 프로젝트: RahyabGroup/PyCore
 def edit(self):
     bcrypt = Bcrypt(None)
     password_hash = bcrypt.generate_password_hash(self.password)
     self.password = password_hash
     user_writer.edit_main_info(self)
예제 #24
0
from flask import Flask, request, render_template
from mysqlconnection import MySQLConnector
# imports the Bcrypt module
# from flask.ext.bcrypt import Bcrypt
from flask_bcrypt import Bcrypt

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

password = '******'
pw_hash = bcrypt.generate_password_hash(password)
print pw_hash

mysql = MySQLConnector(app, 'my_database_here')
# this will load a page that has 2 forms one for registration and login
@app.route('/', methods=['GET'])
def index():
	return render_template('index.html')
	# we are going to add functions to create new users and login users

# generate password hash
@app.route('/create_user', methods=['POST'])
def create_user():
	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 }
예제 #25
0
 def insert(self,
            enrollment,
            rollno,
            name,
            phone_number,
            email,
            password,
            father_name,
            year_of_join,
            year_of_pass,
            programme,
            branch,
            section,
            gender,
            dob,
            temp_address,
            perm_address,
            identity_proof,
            phone_number_verification_status=False,
            email_verification_status=False):
     # THIS INSERT METHOD INPUTS NECESSARY DETAILS OF STUDENT THROUGH INPUT
     # PARAMETERS AND THEN INSERTS IT INTO DATABASE IF IT IS NOT PRESENT IN DB.
     #
     # DATA STRUCTURE OF INPUT PARAMETERS:-
     # ENROLLMENT --> STRING
     # ROLLNO --> INTEGER
     # NAME --> DICTIONARY
     # DOB --> DICTIONARY
     # PHONE_NUMBER --> STRING
     # EMAIL --> STRING
     # PASSWORD --> HASHED STRING
     # FATHER_NAME --> DICTIONARY
     # YEAR_OF_JOIN --> INTEGER
     # YEAR_OF_PASS --> INTEGER
     # PROGRAMME --> STRING
     # BRANCH --> STRING
     # SECTION --> STRING
     # GENDER --> STRING
     # DOB --> DICTIONARY
     # TEMP_ADDRESS --> STRING
     # PERM_ADDRESS --> STRING
     # IDENTITY_PROOF --> BINARY FILE
     # PHONE_NUMBER_VERIFICATION_STATUS --> BOOLEAN
     # EMAIL_VERIFICATION_STATUS --> BOOLEAN
     #
     # IMPORTANT POINTS:-
     # 1. ENROLLMENT IS THE PRIMARY KEY FOR THE STUDENTS PROFILE COLLECTION.
     # 2. COLLECTION NAME THAT IS GOING TO BE USED IS : STUDENT_PROFILE
     # 3. PASSWORD SHOULD BE ENCRYPTED FIRST BEFORE STORING IN DATABASE.
     #
     # CREATING DICTIONARY OF THE DOCUMENT THAT IS GOING TO INSERT IN DB.
     bcrypt = Bcrypt()
     hash_id = hash(str(enrollment) + str(email) + str(phone_number))
     # CHECKING THE PRESENCE OF DUPLICATE ENTRY IN DATABASE
     res = self.collection.find({'hash_id': hash_id})
     if res.count() > 0:
         log(f'[  INFO  ] For Hash ID - {hash_id} Duplicate Entry Found at {config.Provisional_Student_Profile_Collection} Collection in {config.Provisional_Student_DB}'
             )
         for document in res:
             status = self.fs.delete(document["identity_proof"])
             log(f'[  INFO  ] {status}')
         status = self.collection.delete_many({'hash_id': hash_id})
         log(f'[  INFO  ] {status}')
         log(f'[  INFO  ] Hash_ID - {hash_id} Removed Successfully from {config.Provisional_Student_Profile_Collection} Collection in {config.Provisional_Student_DB}'
             )
     document = {
         "hash_id": hash_id,
         "enrollment": enrollment,
         "rollno": rollno,
         "name": name,
         "phone_number": phone_number,
         "email": email,
         "password":
         bcrypt.generate_password_hash(password).decode('utf-8'),
         "father_name": father_name,
         "year_of_join": year_of_join,
         "year_of_pass": year_of_pass,
         "programme": programme,
         "branch": branch,
         "section": section,
         "gender": gender,
         "dob": dob,
         "temp_address": temp_address,
         "perm_address": perm_address,
         "identity_proof": self.fs.put(identity_proof),
         "phone_number_verification_status":
         phone_number_verification_status,
         "email_verification_status": email_verification_status
     }
     status = self.collection.insert_one(document)
     log(f'[  INFO  ] {status}')  # PRINTING STATUS OF RESULT OF QUERY
     log(f'[  INFO  ] Enrollment - {enrollment} Successfully Inserted at {config.Student_Profile_Collection} Collection in {config.Provisional_Student_DB}'
         )
     return 201
예제 #26
0
print "Creating database..."
db.create_all()
db.session.commit()


print "Admin username (empty for admin):",
username = raw_input()
if username == "":
    username = "******"

password = getpass("Admin password: "******"":
    password = getpass("Please enter a password: "******"admin",uri="admin")
db.session.add(inst)
# need to commit now for relationships to work
db.session.commit()

dept = Department(name="admin",uri="admin",institution=inst.id)
db.session.add(dept)
db.session.commit()

user = User(username=username, password=bcrypt.generate_password_hash(password), department=dept.id)
db.session.add(user)
db.session.commit()

print "All done."
예제 #27
0
def build_sample_db(app):
  """
  Populate a small db with some example entries.
  """

  import string
  import random
  from app.models import User, CoOp, Role, Loan, Transaction 

  with app.app_context():
    db.drop_all()
    db.create_all()

    bcrypt = Bcrypt(app)

    user_role = Role(name='member')
    super_user_role = Role(name='officer')
    db.session.add(user_role)
    db.session.add(super_user_role)
    db.session.commit()

    co_op_1 = CoOp(
      name='ABC',
      is_active=True,
      location='Seattle',
      interest=5,
      initial_balance=2000,
      expected_repayment=2200,
      current_balance=1500
    )

    co_op_2 = CoOp(
      name='DEF',
      is_active=True,
      location='New York',
      interest=5,
      initial_balance=4000,
      expected_repayment=4400,
      current_balance=35000
    )

    db.session.add(co_op_1)
    db.session.add(co_op_2)
    db.session.commit()

    # create password hash
    pw_hash = bcrypt.generate_password_hash('admin')
    pw_hash1 = bcrypt.generate_password_hash('12345')

    admin_user = User(
      first_name='Admin',
      last_name='User',
      email='admin',
      password=pw_hash,
      phone='254798745678',
      role_id=super_user_role.id,
      co_op_id=co_op_1.id
    )
    test_user = User(
      first_name='Test',
      last_name='User',
      email='*****@*****.**',
      password=pw_hash1,
      phone='254987654321',
      role_id=user_role.id,
      co_op_id=co_op_1.id
    )
    db.session.add(admin_user)
    db.session.add(test_user)
    db.session.commit()

    test_user_loan = Loan(
      user=test_user,
      initial_balance=2000,
      balance=2000,
      interest=2,
    )
    db.session.add(test_user_loan)
    db.session.commit()

  return
예제 #28
0
def user_register_api():
    '''
    This function takes POST http request with a URL of "/api/register". It firstly reads the user submitted username
    and password. It then connects to the database to check if there is already an existing username in the database.
    The function also checks whether the user provided all the necessary information; whether the format of the
    username and password are correct. If any of the above conditions failed, the function will return user with a
    formatted Json string including the error code and error message. If all the condition check passed, the function
    will create a new entry in the dataset and return a Json string with code 200 indicating request processed
    successfully.
    :return: Json string with status code and information string
    '''

    bcrypt = Bcrypt(webapp)
    # need to trim the user name
    username = request.form.get('username', "")
    password = request.form.get('password', "")

    # connect to database
    cnx = get_database()
    cursor = cnx.cursor()
    query = "SELECT COUNT(username) FROM user_info WHERE username = %s "
    cursor.execute(query, (username, ))
    results = cursor.fetchall()
    numberOfExistUser = results[0][0]

    if numberOfExistUser != 0:
        return http_response(409, "Error: User name already exist!")

    if username == "" or password == "":
        return http_response(400, "Error: All fields are required!")

    if re.findall(r'\s+', username) != []:
        return http_response(400, "Error: No space allowed in user name!")

    if (len(username) > 20
            or len(username) < 1) or not all(c in validUsernameChar
                                             for c in username):
        return http_response(
            400,
            "Error: Username violation, username must have length between 1 to 20, only letters and numbers allowed"
        )

    if len(password) > 16 or len(password) < 1:
        return http_response(400, "Error: Password length violation")

    ts = time.time()
    timestamp = datetime.datetime.fromtimestamp(ts).strftime(
        '%Y-%m-%d %H:%M:%S')

    password = bcrypt.generate_password_hash(password).decode("utf-8")

    query = ''' INSERT INTO user_info (username,password,create_date,active,upload_counter)
                           VALUES (%s,%s, %s,1,0)
        '''

    cursor.execute(query, (username, password, timestamp))
    cnx.commit()

    # Add error catch here for sql

    return http_response(200, "Registration succeed for the user: " + username)
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
logging.basicConfig(filename='app.log', level=logging.DEBUG)
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message_category = 'info'

from mitsubishi_hvac_controller.models import User, Setting, Power
db.create_all()
if len(db.session.query(User).all()) == 0:
    logging.info("Creating default admin user. Please change password ASAP.")
    hashed_password = bcrypt.generate_password_hash("admin").decode('utf-8')
    user = User(username="******",
                email="*****@*****.**",
                password=hashed_password)
    db.session.add(user)
    db.session.commit()

if len(db.session.query(Setting).all()) == 0:
    logging.info("Creating default settings.")
    setting = Setting(setting='default',
                      temp='21',
                      fan_mode='Speed2',
                      climate_mode='Hot',
                      vanne_horizontal_mode='Middle',
                      vanne_vertical_mode='Middle')
    db.session.add(setting)
# pip install flask-bcrypt
# import Bcrypt
from flask_bcrypt import Bcrypt

# create an instance of Brypt

bcrypt = Bcrypt()

my_password = '******'

# Create an hash key
my_hask_key = bcrypt.generate_password_hash(my_password)

print("haskey is {a}".format(a=my_hask_key))

# Check whether entered pass is true.

bcrypt_check = bcrypt.check_password_hash(my_hask_key, 'hello')
print("Password Check: {a}".format(a=bcrypt_check))

bcrypt_check = bcrypt.check_password_hash(my_hask_key, 'somepassword')
print("Password Check: {a}".format(a=bcrypt_check))
예제 #31
0
def sign_up_save():
    '''
    This function takes POST http request with a URL of "/signup/save". It firstly reads the user submitted username,
    password1 and password2. It then connects to the database to check if there is already an existing username in the
    database. The function also checks whether the user provided all the necessary information; whether the format of
    the username and password are correct and whether the two passwords match. If any of the above condition failed,
    the function will return user with "signup_index.html" with error message. If not, the function will insert the
    user provided information to the database and return "signup_succeed_index.html" page to user indicating the user
    has successfully created a new account.
    :return: "signup_index.html"  or "signup_succeed_index.html"
    '''

    bcrypt = Bcrypt(webapp)
    # need to trim the user name
    username = request.form.get('username', "")
    password1 = request.form.get('password1', "")
    password2 = request.form.get('password2', "")

    # connect to database
    cnx = get_database()
    cursor = cnx.cursor()
    query = "SELECT COUNT(username) FROM user_info WHERE username = %s "
    cursor.execute(query, (username,))
    results = cursor.fetchall()
    numberOfExistUser = results[0][0]

    if username == "" or password1 == "" or password2 == "":
        error_msg = "Error: All fields are required!"
        return render_template("signup_index.html", title="Sign Up", error_msg=error_msg,
                               username=username, password1=password1, password2=password2)

    if re.findall(r'\s+', username) != []:
        error_msg = "Error: No space allowed in user name!"
        return render_template("signup_index.html", title="Sign Up", error_msg=error_msg,
                               username=username, password1=password1, password2=password2)

    if numberOfExistUser != 0:
        error_msg = "Error: User name already exist!"
        return render_template("signup_index.html", title="Sign Up", error_msg=error_msg,
                               username=username, password1=password1, password2=password2)

    if not (password1 == password2):
        error_msg = "Error: Two passwords not matching!"
        return render_template("signup_index.html", title="Sign Up", error_msg=error_msg,
                               username=username, password1=password1, password2=password2)

    if (len(username) > 20 or len(username) < 1) or not all(c in validUsernameChar for c in username):
        print(len(username))
        error_msg = "Error: Username violation, username must have length between 1 to 20, only letters and numbers allowed"
        return render_template("signup_index.html", title="Sign Up", error_msg=error_msg,
                               username=username, password1=password1, password2=password2)

    if len(password1) > 16 or len(password1) < 1:
        error_msg = "Error: Password length violation"
        return render_template("signup_index.html", title="Sign Up", error_msg=error_msg,
                               username=username, password1=password1, password2=password2)

    ts = time.time()
    timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')

    password = bcrypt.generate_password_hash(password1).decode("utf-8")

    query = ''' INSERT INTO user_info (username,password,create_date,active)
                       VALUES (%s,%s, %s,1)
    '''

    cursor.execute(query, (username, password, timestamp))
    cnx.commit()

    # Add error catch here for sql

    return render_template("signup_succeed_index.html", title="Sign Up Succeed", username=username, password=password1)
예제 #32
0
from flask import Flask, request, redirect, render_template, session, flash
from flask_bcrypt import Bcrypt
from mysqlconnection import MySQLConnector
import re
import datetime

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

app.secret_key = "loginregistration"

mysql = MySQLConnector(app, 'friendface')

pwd_hash = (bcrypt.generate_password_hash('Codingdojo1'))
print(bcrypt.check_password_hash(pwd_hash, 'Codingdojo1'))
pwd_hash = (bcrypt.generate_password_hash('Codingdojo1'))
print(bcrypt.check_password_hash(pwd_hash, 'Codingdojo1'))
pwd_hash = (bcrypt.generate_password_hash('Codingdojo1'))
print(bcrypt.check_password_hash(pwd_hash, 'Codingdojo1'))

EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
SPACE_REGEX = re.compile(r'\S+')
NAME_REGEX = re.compile(r'^[a-zA-Z]+$')
PASSWORD_REGEX = re.compile(r'^[a-zA-Z0-9.+=_-]+$')
UPPER_CASE_REGEX = re.compile(r'[A-Z]')
NUMBER_REGEX = re.compile(r'[0-9]+')
ILLEGAL_REGEX = re.compile(r'[~`()+={}|\\:;\'\"<>,.?/]')

today = datetime.datetime.today().strftime("%Y-%m-%d")

예제 #33
0
import sqlite3
from flask_bcrypt import Bcrypt
import os

dir=(os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', '..')))

bcrypt = Bcrypt()
password = bcrypt.generate_password_hash('admin').decode('utf-8')
conn = sqlite3.connect(dir+"/data/dbf/nettemp.db")
c = conn.cursor()
c.execute("UPDATE users SET password=? WHERE username='******'", (password,))
conn.commit()
conn.close()
except:
    print('Please check your arango servier is running!')
    sys.exit(-1)
try:
    db = conn['project']

except:
    # create database if not existing on ArangoDB server
    db = conn.createDatabase(name='project')
    usersCollection = db.createCollection(name='users')

    # create the admin user
    admin = usersCollection.createDocument()
    admin['name'] = 'Administrator'
    admin['email'] = '*****@*****.**'
    admin['password'] = bcrypt.generate_password_hash('password').decode(
        'utf-8')
    admin['role'] = 'admin'
    admin['address'] = 'somewhere'
    admin['state'] = 'active'
    admin['_key'] = admin['email']
    admin['department'] = 'CS'
    admin.save()

    # create default departments
    departments = db.createCollection(name='departments')
    dep = departments.createDocument()
    dep['_key'] = 'CS'
    dep.save()
    dep = departments.createDocument()
    dep['_key'] = 'EE'
    dep.save()
class FeatureRequestModelTestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app()
        self.app_context = self.app.app_context()
        self.app_context.push()
        self.bcrypt = Bcrypt(self.app)
        db.create_all()
        self.test_user = User(
            'Will Smith', '*****@*****.**',
            self.bcrypt.generate_password_hash('testing123_$%').decode(
                'utf-8'))
        db.session.add(self.test_user)
        db.session.commit()
        self.test_client = Client("Company X", '*****@*****.**',
                                  'bio text goes here, bio text goes here', 1,
                                  '7176577957', self.test_user.id)
        db.session.add(self.test_client)
        db.session.commit()
        self.test_product = Product('Product-A', 'Product Desciption',
                                    self.test_client.id)
        db.session.add(self.test_product)
        db.session.commit()
        pa1 = ProductArea('Area1', self.test_product.id)
        pa2 = ProductArea('Area2', self.test_product.id)
        db.session.add(pa1)
        db.session.add(pa2)
        db.session.commit()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_context.pop()

    def test_request_values(self):
        a = ProductArea.query.filter_by(
            product_id=self.test_product.id).first()
        fr = FeatureRequest('Request title', 'request description',
                            datetime.utcnow(), datetime(2019, 8, 15), a.name,
                            self.test_product.id, self.test_client.id)
        db.session.add(fr)
        db.session.commit()
        q_fr = FeatureRequest.query.get(fr.id)
        self.assertEqual(q_fr.title, fr.title)
        self.assertEqual(q_fr.description, fr.description)
        self.assertEqual(q_fr.created_at, fr.created_at)
        self.assertEqual(q_fr.target_date, fr.target_date)
        self.assertEqual(q_fr.product_area, fr.product_area)
        self.assertEqual(q_fr.product_id, fr.product_id)
        self.assertEqual(q_fr.client_id, fr.client_id)

    def test_request_initial_state(self):
        a = ProductArea.query.filter_by(
            product_id=self.test_product.id).first()
        fr = FeatureRequest('Request title', 'request description',
                            datetime.utcnow(), datetime(2019, 8, 15), a.name,
                            self.test_product.id, self.test_client.id)
        db.session.add(fr)
        db.session.commit()
        q_fr = FeatureRequest.query.get(fr.id)
        self.assertEqual(q_fr.state.name, 'TODO')

    def test_requests_relationships(self):
        a = ProductArea.query.filter_by(
            product_id=self.test_product.id).first()
        fr = FeatureRequest('Request title', 'request description',
                            datetime.utcnow(), datetime(2019, 8, 15), a.name,
                            self.test_product.id, self.test_client.id)
        db.session.add(fr)
        db.session.commit()
        q_fr = FeatureRequest.query.get(fr.id)
        self.assertTrue(
            FeatureRequest.query.filter_by(
                product_id=self.test_product.id).count() == 1)
        self.assertEqual(q_fr.product, self.test_product)