Exemple #1
0
def reset_password(login_name):
    con, c = dbconnect.connect()
    if validate_email(login_name):
        query = " SELECT * FROM user WHERE user_email = %s "
    else:
        query = " SELECT * FROM user WHERE user_name = %s "
    con, c = dbconnect.connect()
    c.execute(query, (login_name,))
    row = c.fetchall()
    if len(row) == 0:
        dbconnect.close(con, c)
    else:
        row = row[0]
        new_password = random_password()
        new_pass_hash = generate_password_hash(new_password)

        uid = row[0]
        email = row[1]
        username = row[2]
        query = " UPDATE user SET user.pass_hash = %s WHERE user.user_id = %s "
        c.execute(query, (new_pass_hash, uid))
        con.commit()
        dbconnect.close(con, c)

        html_msg = render_template("resetpassword.html", username=username, new_password=new_password)
        from run import send_mail
        send_mail("Walk With Me New Password", [email], html_msg)

    return jsonify({"Status": 1, "Message": "New password has been sent to your email address if the account exist."})
Exemple #2
0
    def password(self, plaintext):
        """
        Sets the user's password, converting the plain text argument to a hashed password.

        :param plaintext: the plain text being entered by the user, to be hased
        "
        """
        self._password = generate_password_hash(plaintext)
 def create_user(cls, email, password):
     try:
         cls.create(
         email=email,
         password=generate_password_hash(password)
         )
     except:
         print "exception error"
Exemple #4
0
 def create_user(cls, username,email, password, admin=False):
     try:
         cls.create(
         username=username,
         email = email,
         password = generate_password_hash(password),
         is_admin=admin)
     except IntegrityError:
         raise ValueError('User already exists')
	def create_user(cls, username, email, password):
		try:
			with db.transaction():
				cls.create(
					username=username,
					email=email,
					password=generate_password_hash(password)
				)
		except IntegrityError:
			raise ValueError("User already exists")
Exemple #6
0
    def set_password(self, plaintext, rounds=12):
        """Sets the password for the user. The password hash is created with the
        Bcrypt python library (http://www.mindrot.org/projects/py-bcrypt/).

        Args:
            plaintext: The plaintext password to hash
            rounds: Number of rounds to use for the bcrypt hashing
        """
        password_hash = generate_password_hash(plaintext, rounds)
        self.password = unicode(password_hash)
Exemple #7
0
    def create_user(cls,name, email,password):
        try:
            cls.create(
                name=name,
                email=email,
                password=generate_password_hash(password)
            )

        except IntegrityError:
            raise ValueError('user already exists')
Exemple #8
0
 def create_user(cls, username, email, password, admin=False):
     try:
         with DATABASE.transaction():
             cls.create(
                 username=username,
                 email=email,
                 password=generate_password_hash(password),
                 is_admin=admin)
     except IntegrityError:
         raise ValueError("User already exists")
Exemple #9
0
 def add(cls, email, first_name, last_name, password):
     try:
         with DB.transaction():
             cls.create(
                 email=email,
                 first_name=first_name,
                 last_name=last_name,
                 password=generate_password_hash(password)
             )
     except IntegrityError:
         raise ValueError("User with that email already exists")
Exemple #10
0
    def set_password(self, plaintext, rounds=12):
        """Sets the password for the user. The password hash is created with the
        Bcrypt python library (http://www.mindrot.org/projects/py-bcrypt/).

        Args:
            plaintext: The plaintext password to hash
            rounds: Number of rounds to use for the bcrypt hashing
        """
        password_hash = generate_password_hash(plaintext, rounds)
        if isinstance(password_hash, six.binary_type):
            password_hash = codecs.decode(password_hash, 'utf-8')
        self.password = password_hash
    def save(self):
        if self.username and self.password:
            password = generate_password_hash(self.password).decode('utf-8')
            db = get_db()
            cursor = db.cursor()

            cursor.execute(
                'INSERT INTO users (username, password) VALUES (%s, %s)',
                (self.username, password)
            )

            db.commit()
Exemple #12
0
def change_password(uid, new_password):
    if not is_strong_password(new_password):
        return jsonify({"Status": 0, "Message": "Your password is to weak, please try again."})

    new_pass_hash = generate_password_hash(new_password)
    con, c = dbconnect.connect()
    query = " UPDATE user SET user.pass_hash = %s WHERE user.user_id = %s "
    c.execute(query, (new_pass_hash, uid))
    con.commit()
    dbconnect.close(con, c)

    return jsonify({"Status": 1, "Message": "Password changed successfully, please login again."})
    def test_hashed_password_is_not_plaintext(self):
        """
        Check that the password is not plain text when we try to, for example, reset it.

        Check other aspects of changing User object's password
        """
        user = User("xXx_Supa_Saiyan_xXx", "password1", "*****@*****.**", False, False)
        user.password = "******"
        self.assertNotEqual(user.password, "password1", "password not reset, password is plain text")
        self.assertNotEqual(user.password, generate_password_hash("password1"), "password not reset")
        self.assertNotEqual(user.password, "dogsname", "password is plain text")
        self.assertTrue(user.check_password("dogsname"), "password not changed successfully")
 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'))
Exemple #15
0
def reset_password(username):
    import random
    import string
    from app.models.Mailgun_Internal import mailgun_send_message

    str_length = 10
    password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(str_length))
    user = User.query.filter_by(username=username).first()
    if user is None:
        return False
    else:
        user.password = generate_password_hash(password).decode('utf8')
        mailgun_send_message(None, username, "Password Reset", password, "PW_Reset")
        db.session.commit()
        return True
Exemple #16
0
def signup():
    if request.method == 'GET':
        return render_template('signin.html')
    username = request.form['username']
    password = request.form['password']
    confirm = request.form['confirm-password']
    if confirm != password:
        resp = jsonify({'status': 412, 'message': 'Las contraseñas ingresadas no coinciden'})
        resp.status_code = 412
        return resp
    password_hash = generate_password_hash(password, BCrypt_iterations)
    new_user = User.User(username, password_hash, 'reviewer')
    session.add(new_user)
    try:
        session.commit()
	login_user(new_user)
	return redirect(url_for('mapa'))
#        return jsonify({'status': 200, 'message': 'OK'})
    except Exception as e:
        return jsonify({'status': 500, 'message': 'El usuario no se puedo añadir'})
Exemple #17
0
def CreateEmployer():
	name = request.form['username']
	employer = models.Employers(
		fname = request.form['first_name'],
		mname = request.form['middle_name'],
		lname = request.form['last_name'],
		street1 = request.form['street1'],
	    street2 = request.form['street2'],
	    city = request.form['city'],
	    state = request.form['state'],
	    zipcode = request.form['zipcode'],
	    email = request.form['email'],
	    username = request.form['username'],
	    bestmethod = request.form['demo-priority'],
	    _password = generate_password_hash(request.form['password'],12),
	    phone = request.form['phone']
	)
	db.session.add(employer)
	db.session.commit()
	session['username'] = request.form['username']
	user_name = escape(session['username'])
	return render_template('LandingPage.html',name=user_name)
Exemple #18
0
def register():
    error = None
    form = RegisterForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            new_user = User(
                form.email.data,
                bcrypt.generate_password_hash(form.password.data),
                confirmed=False,
            )
            try:
                db.session.add(new_user)
                db.session.commit()

            except IntegrityError:
                error = 'כתובת הדוא"ל הזו כבר קיימת באתר.'
                return render_template('register.html', form=form, error=error)

            token = generate_confirmation_token(new_user.email)
            confirm_url = url_for('notifier.confirmed_email',token=token,_external=True)

            session['logged_in'] = True
            session['user_id'] = new_user.id
            session['user_email'] = new_user.email

            client = sendgrid.SendGridClient(SENDGRID_KEY)
            conf_mail = sendgrid.Mail()
            conf_mail.add_to(new_user.email)
            conf_mail.set_from(NOTIFIER_MAIL_ADDRESS)
            conf_mail.set_subject(MAIL_SUBJECT)
            conf_mail.set_html(render_template('user/activate.html',confirm_url=confirm_url))
            client.send(conf_mail)

            flash(u'תודה שנרשמת. כעת ניתן להתחבר לאתר')
            return redirect(url_for('notifier.feeds_editor'))
        else:
            print(form.errors)
    return render_template("register.html", form=form, error=error)
Exemple #19
0
def activate_user(user_id, data):
    log("User is activated", "HIGH", "PASS")
    val_num(user_id)
    val_num(data.get('accessToken'))
    val_alpha_num(data.get('username'))
    username = data.get('username')
    username = username.replace(" ", "")
    result = users.query.filter(users.userID == user_id).one()
    if result.activated == "False":
        if result.email == data.get('email'):
            if data.get('password') == data.get('repassword'):
                if data.get('accessToken') == result.accessToken:
                    pw_hash = generate_password_hash(data.get('password')).decode('utf-8')
                    result.password = pw_hash
                    result.access = "True"
                    result.activated = "True"
                    result.userName = username
                    db.session.add(result)
                    db.session.commit()
                    return {'message': 'User successfully activated'}
    else:
        log("User triggered error activation failed", "HIGH", "FAIL")
        return {'message': 'User could not be activated'}
Exemple #20
0
def register():
    """
    Create a new user. Check if name exists first.
    :return:
    """
    if request.method == 'POST':
        cur = g.db.execute('SELECT name FROM users WHERE name = ?', [request.form['name']])
        if cur.fetchone() is None and request.form['name'] is not None and request.form['password'] is not None:
            cur = g.db.execute('INSERT INTO users (name, password) VALUES (?, ?)',
                               [request.form['name'], generate_password_hash(request.form['password'])])
            g.db.commit()
            result = cur.lastrowid
            if result > 0:
                session['logged_in'] = True
                session['user_name'] = request.form['name']
                return redirect(url_for('home.home'))
            else:
                error = 'Something went wrong'
                return render_template('login.html', error=error)
        else:
            return render_template('login.html', error="That name is taken")
    else:
        return render_template('login.html')
Exemple #21
0
def register(value):
    email = value["email"]
    username = value["username"]
    password = value["password"]
    age = int(value["age"])
    gender = value["gender"]
    if validate_email(email, check_mx=MX_VERIFY, verify=FULL_VERIFY) == False:  # Only checking domain has SMTP Server
        return jsonify({"Status": 0, "Message": "Please enter a valid email address."})
    if not is_safe_username(username):
        return jsonify({"Status": 0, "Message": "Please enter a valid username."})
    if not is_strong_password(password):
        return jsonify({"Status": 0, "Message": "Your password is to weak, please try again."})

    con, c = dbconnect.connect()
    query = " SELECT user_id FROM user WHERE user_email = %s "
    if c.execute(query, (email,)) != 0:
        dbconnect.close(con, c)
        return jsonify({"Status": 0, "Message": "Email address has already been taken."})
    query = " SELECT user_id FROM user WHERE user_name = %s "
    if c.execute(query, (username,)) != 0:
        dbconnect.close(con, c)
        return jsonify({"Status": 0, "Message": "Username has already been taken."})

    pass_hash = generate_password_hash(password)

    query = " INSERT INTO user(user_email,user_name,pass_hash,age,gender) VALUES (%s,%s,%s,%s,%s);"

    c.execute(query, (email, username, pass_hash, age, gender))
    con.commit()
    dbconnect.close(con, c)

    html_msg = render_template("welcome.html", username=username)

    from run import send_mail
    send_mail("Welcome to Walk With Me", [email], html_msg)

    return jsonify({"Status": 1, "Message": "Registration successful! Please login."})
Exemple #22
0
def register():
	if g.user is not None and g.user.is_authenticated:
		return redirect(url_for('index'))
	error = None
	if request.method == 'POST':
		if not request.form['username']:
			error = 'You have to enter a username'
		elif not request.form['email'] or \
				'@' not in request.form['email']:
			error = 'You have to enter a valid email address'
		elif not request.form['password']:
			error = 'You have to enter a password'
		elif request.form['password'] != request.form['password2']:
			error = 'The two passwords do not match'
		elif User.query.filter_by(username = request.form['username']).first() is not None:
			error = 'The username is already taken'
		else:
			user = User(request.form['username'], request.form['email'],
							generate_password_hash(request.form['password']))
			db.session.add(user)
			db.session.commit()
			flash('You were successfully registered and can login now')
			return redirect(url_for('login'))
	return render_template('register.html', error=error)
Exemple #23
0
 def evaluate_password(self, key, value):
     return generate_password_hash(value)
Exemple #24
0
import datetime
def hashpw(password):
    return generate_password_hash(password, 10).decode('utf-8')
 def _set_password(self, plaintext):
     self._password = generate_password_hash(plaintext, 12)
     if PY3:
         self._password = str(self._password, 'utf-8')
Exemple #27
0
 def _set_password(self, plaintext):
     self._password = generate_password_hash(plaintext)
Exemple #28
0
 def generate_pw_hash(self):
     self.password = generate_password_hash(password=self.password).decode('utf-8')
 def test_unicode_hash(self):
     password = u'東京'
     h = generate_password_hash(password).decode('utf-8')
     self.assertTrue(check_password_hash(h, password))
Exemple #30
0
 def hash_password(password):
     return generate_password_hash(password)
Exemple #31
0
 def __init__(self, username, password):
     self.password = generate_password_hash(password)
     self.username = username
Exemple #32
0
 def save_new_password(self, new_password):
     self.password = generate_password_hash(new_password)
     self.is_active = True
Exemple #33
0
class User(UserMixin, db.Model):

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True)
    email = db.Column(db.String(64), unique=True, index=True)
    password = db.Column(
        db.String(128),
        default=generate_password_hash('snsflaskapp')
    )
    picture_path = db.Column(db.Text)
    # 有効か無効かのフラグ
    is_active = db.Column(db.Boolean, unique=False, default=False)
    create_at = db.Column(db.DateTime, default=datetime.now)
    update_at = db.Column(db.DateTime, default=datetime.now)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    @classmethod
    def select_user_by_email(cls, email):
        return cls.query.filter_by(email=email).first()

    def validate_password(self, password):
        return check_password_hash(self.password, password)

    def create_new_user(self):
        db.session.add(self)

    @classmethod
    def select_user_by_id(cls, id):
        return cls.query.get(id)
    
    def save_new_password(self, new_password):
        self.password = generate_password_hash(new_password)
        self.is_active = True
    
    # UserConnectと紐づけます outer join
    @classmethod
    def search_by_name(cls, username, page=1):
        user_connect1 = aliased(UserConnect) # from_user_id: 検索相手のID、to_user_id: ログインユーザのIDでUserConnectに紐づける
        user_connect2 = aliased(UserConnect) # to_user_id: 検索相手のID、from_user_id: ログインユーザのIDでUserConnectに紐づける
        return cls.query.filter(
            cls.username.like(f'%{username}%'),
            cls.id != int(current_user.get_id()),
            cls.is_active == True
        ).outerjoin(
            user_connect1,
            and_(
                user_connect1.from_user_id == cls.id,
                user_connect1.to_user_id == current_user.get_id()
            )
        ).outerjoin(
            user_connect2,
            and_(
                user_connect2.from_user_id == current_user.get_id(),
                user_connect2.to_user_id == cls.id
            )
        ).with_entities(
            cls.id, cls.username, cls.picture_path,
            user_connect1.status.label("joined_status_to_from"),
            user_connect2.status.label("joined_status_from_to")
        ).order_by(cls.username).paginate(page, 50, False)
    
    @classmethod
    def select_friends(cls):
        return cls.query.join(
            UserConnect,
            or_(
                and_(
                    UserConnect.to_user_id == cls.id,
                    UserConnect.from_user_id == current_user.get_id(),
                    UserConnect.status == 2
                ),
                and_(
                    UserConnect.from_user_id == cls.id,
                    UserConnect.to_user_id == current_user.get_id(),
                    UserConnect.status == 2
                )
            )
        ).with_entities(
            cls.id, cls.username, cls.picture_path
        ).all()

    @classmethod
    def select_requested_friends(cls):
        return cls.query.join(
            UserConnect,
            and_(
                UserConnect.from_user_id == cls.id,
                UserConnect.to_user_id == current_user.get_id(),
                UserConnect.status == 1
            )
        ).with_entities(
            cls.id, cls.username, cls.picture_path
        ).all()

    @classmethod
    def select_requesting_friends(cls):
        return cls.query.join(
            UserConnect,
            and_(
                UserConnect.from_user_id == current_user.get_id(),
                UserConnect.to_user_id == cls.id,
                UserConnect.status == 1
            )
        ).with_entities(
            cls.id, cls.username, cls.picture_path
        ).all()
Exemple #34
0
# benchmark.py

from flask_bcrypt import generate_password_hash

# Change the number of rounds (second argument) until it takes between
# 0.25 and 0.5 seconds to run.
generate_password_hash('password1', 12)
Exemple #35
0
 def set_password(self, password):
     self.password = generate_password_hash(password)
Exemple #36
0
from airflow import models, settings
from airflow.contrib.auth.backends.password_auth import PasswordUser
from airflow.models import Variable
from flask_bcrypt import generate_password_hash

# Get password from variables
password = Variable.get("user_password")

user = PasswordUser(models.User())
user.username = '******'
user.email = '*****@*****.**'
user._password = generate_password_hash(password, 12)

session = settings.Session()
session.add(user)
session.commit()
session.close()
exit()
 def call(self):
     self.user.password = generate_password_hash(self.new_password).decode('utf-8')
     db.session.commit()
     return self.user.password
Exemple #38
0
 def new_user(cls, username, password, created):
     cls.create(
         username=username,
         password=generate_password_hash(password),
         created=created,
     )
print("")

PY3 = version_info[0] == 3
args = sys.argv[1:]

REQUIRED_NUM_OF_ARGS = 1


def print_usage_str():
    print("""Usage: python airflow-gen-pwd-hash-from-local.py {plain_text_password}""")

print("Argument List: " + str(str(args)))
print("Argument Length: " + str(len(args)))

if len(args) != REQUIRED_NUM_OF_ARGS:
    print("Invalid number of Argument. Requires " + str(REQUIRED_NUM_OF_ARGS) + " number of Argument(s). " + str(len(args)) + " provided.")
    print_usage_str()
    exit(1)

pwd_plain_text = str(args[0]).strip()
print("Password Plain Text: " + str(pwd_plain_text))

pwd_hash = generate_password_hash(pwd_plain_text, 12)
if PY3:
    pwd_hash = str(pwd_hash, 'utf-8')

print("")
print("Password Hash: " + str(pwd_hash))

Exemple #40
0
def hashpw(password):
    return generate_password_hash(password, 10).decode('utf-8')
Exemple #41
0
 def password(self, user_pass):
     self.user_pass = generate_password_hash(user_pass)
Exemple #42
0
 def set_password(self, plain):
     self.password = generate_password_hash(plain, BCRYPT_LOG_ROUNDS)
Exemple #43
0
 def password(self, password):
     self.password_hash = generate_password_hash(password)
Exemple #44
0
 def add_user(self, email, passwd):
     passwd_hash = generate_password_hash(passwd).decode()
     query = "INSERT INTO users (email, passwd) VALUES (?, ?)"
     self.cur.execute(query, (email, passwd_hash))
     self.con.commit()
Exemple #45
0
 def hash_password(self):
     pwd_hash = flask_bcrypt.generate_password_hash(self.password)
     self.password = pwd_hash.decode('utf8')
Exemple #46
0
def create_objects():
    session = Session()

    user = User(username='******',
                firstName='admin',
                lastName='admin',
                email='*****@*****.**',
                phone='+38099',
                userAuthStatus=UserStatus.notSignedIn,
                password=generate_password_hash('admin'))

    user2 = User(username='******',
                 firstName='admin',
                 lastName='admin',
                 email='*****@*****.**',
                 phone='+380990',
                 userAuthStatus=UserStatus.notSignedIn,
                 password=generate_password_hash('admin'))

    user3 = User(username='******',
                 firstName='admin',
                 lastName='admin',
                 email='*****@*****.**',
                 phone='+380940',
                 userAuthStatus=UserStatus.notSignedIn,
                 password=generate_password_hash('admin'))

    wallet13 = Wallet(
        name='MyFirstWallet',
        balance=10000,
        currency=Currency.USD,
        owner=user3,
    )

    wallet23 = Wallet(
        name='MySecondWallet',
        balance=100,
        currency=Currency.UAH,
        owner=user3,
    )

    wallet1 = Wallet(
        name='MyWallet',
        balance=10000,
        currency=Currency.USD,
        owner=user,
    )

    wallet2 = Wallet(
        name='MySecoWallet',
        balance=100,
        currency=Currency.UAH,
        owner=user,
    )

    session.add(user)
    session.add(user2)
    session.add(wallet1)
    session.add(wallet2)

    session.add(user3)
    session.add(wallet13)
    session.add(wallet23)

    session.commit()
Exemple #47
0
 def post(self):
     user = _user_parser.parse_args()
     user["password"] = generate_password_hash(user["password"], 12)
     new_user = UserModel().create(user)
     return str(new_user['_id'])
Exemple #48
0
 def __init__(self, **kwargs):
     self.username = kwargs.get('username')
     self.email = kwargs.get('email')
     self.password = generate_password_hash(kwargs.get('password'),
                                            10).decode()
Exemple #49
0
 def set_password(self, password):
     self.password = generate_password_hash(password).decode('UTF-8')
Exemple #50
0
def send_mail(recipient, subject, body):
    msg = MIMEMultipart()
    msg['From'] = app.config['EMAIL_SENDER']
    msg['To'] = recipient
    msg['Subject'] = subject
    message = body
    msg.attach(MIMEText(message))
    mailserver = smtplib.SMTP(app.config['SMTP_URL'], app.config['SMTP_PORT'])
    mailserver.ehlo()
    mailserver.starttls()
    mailserver.ehlo()
    mailserver.login(app.config['SMTP_USER'], app.config['SMTP_USER'])
    mailserver.sendmail(app.config['EMAIL_SENDER'], recipient, msg.as_string())
    mailserver.quit()


from api import routes

if app.config['DEBUG']:
    from api import models
    with models.pony.orm.db_session:
        admin = models.User.get(email='*****@*****.**')
        if admin is None:
            print(generate_password_hash('admin').decode("utf-8"))
            admin = models.User(
                email='*****@*****.**',
                password=generate_password_hash('admin').decode("utf-8"),
                active=True,
                admin=True)
            models.pony.orm.commit()
Exemple #51
0
 def _set_password(self, plaintext):
     self._password = generate_password_hash(plaintext, 12)
     if PY3:
         self._password = str(self._password, 'utf-8')
Exemple #52
0
 def password(self, plaintext):
     """Sets password for the user"""
     self._password = generate_password_hash(plaintext, 12)
     if PY3:
         self._password = str(self._password, 'utf-8')
Exemple #53
0
 def set_password(self, password):
     """Set the user password."""
     self.password_hash = generate_password_hash(password).decode("utf-8")
 def password(self, password):
     self.password_hash = flask_bcrypt.generate_password_hash(
         password).decode('utf-8')
Exemple #55
0
 def hash_password(self):
     self.password = generate_password_hash(self.password).decode('utf8')
Exemple #56
0
	def __init__(self, nickname, email, password, verified):
		self.nickname  = nickname
		self.email     = email
		self.password  = generate_password_hash(password)
		self.verified  = verified
Exemple #57
0
 def _set_password(self, plaintext):
     self._password = generate_password_hash(plaintext, BCRYPT_LOG_ROUNDS)
Exemple #58
0
 def __init__(self, email, username, password):
     self.email = email
     self.username = username
     self.password = generate_password_hash(password)
Exemple #59
0
def hash_password(password):
    return generate_password_hash(password).decode('utf8')
 def __init__(self, username, email, password, is_admin=False):
     self.username = username
     self.email = email
     self.password = generate_password_hash(password)
     self.is_admin = is_admin