Esempio n. 1
0
 def create_user(cls, email, password, admin=False):
     try:
         cls.create(email=email,
                    password=generate_password_hash(password),
                    is_admin=admin)
     except IntegrityError:
         raise ValueError("User already exists")
Esempio n. 2
0
	def __init__(self, name, age, email, password, best_friend=None, is_admin=False):
		self.name = name
		self.age = age
		self.email = email
		self.password = generate_password_hash(password)
		self.best_friend = best_friend
		self.is_admin = is_admin
Esempio n. 3
0
def signup():
    if request.method == "POST":
        emailz = request.form['email']
        pazz = request.form['password']
        veri = request.form['verify']
        # If password and verify fields match then create new BSON Document
        if len(pazz) > 6:
            if pazz == veri:
                pazz = generate_password_hash(pazz)
                new = Profile(email=emailz, password=pazz, vanity=emailz)
                #checks if email address is not in use
                try:
                    Profile.objects.get(email=emailz)
                # If the email address isn't taken
                except DoesNotExist:
                    #Checks if email address is the right format
                    try:
                        new.save()
                    # if email address not in right format
                    except (ValidationError, MultipleObjectsReturned):
                        return render_template('signup.html', eerror="Email is of incorrect format", verror="", perror="")
                    else:
                        session['email'] = emailz
                        flash('You were logged in')
                        return redirect('/MyAccount/')
                else: return render_template('signup.html', verror="", eerror="Email Address is already Taken", perror="")
            else: return render_template('signup.html', verror="Passwords do not match", eerror="", perror="", em=emailz)
        else: return render_template('signup.html', verror="", eerror="", perror="Password has to be at least 6 characters long", em=emailz)
    else: return render_template('signup.html', verror="",perror="",eerror="")
Esempio n. 4
0
    def create_new_user_from_email(first_name, last_name, email, password):
        if len(password) < PASSWORD_MIN_LENGTH:
            raise User.UserCreationError(
                    'Passwords must be at least 8 characters long.')

        user = User(
            email=email,
            first_name=first_name,
            join_date=datetime.datetime.now(),
            join_source=User.JoinSource.EMAIL,
            last_name=last_name,
            password=bcrypt.generate_password_hash(
                    password, rounds=BCRYPT_ROUNDS),
        )

        try:
            user.save()
        except me.base.ValidationError as e:
            if 'email' in e.errors:
                raise User.UserCreationError('Oops, that email is invalid.')
            raise
        except me.queryset.NotUniqueError as e:
            raise User.UserCreationError('That email is already signed up.'
                    ' (Maybe you already signed up with Facebook?)')

        return user
Esempio n. 5
0
def index():
    if login.current_user.is_authenticated():
        return login.redirect('/dashboard')

    # Create the forms
    sign_up_form = forms.SignUpForm()
    sign_in_form = forms.SignInForm()

    if flask.request.method == 'POST' and sign_up_form.validate_on_submit():
        new_user = models.User(
           first_name=sign_up_form.first_name.data,
           last_name=sign_up_form.last_name.data,
           email=sign_up_form.email.data,
           password=bcrypt.generate_password_hash(sign_up_form.password.data),
        )

        db.session.add(new_user)
        db.session.commit()

        return flask.redirect(flask.url_for('dashboard'))

    if flask.request.method == 'POST' and sign_in_form.validate_on_submit():
        user = models.User.query.filter(
            models.User.email == sign_in_form.user_email.data).first()
        login.login_user(user)
        if (bcrypt.check_password_hash(user.password,
                sign_in_form.user_password.data)):
            return flask.redirect(flask.url_for('dashboard'))

    return flask.render_template('home.epy', sign_up_form=sign_up_form,
        sign_in_form=sign_in_form, user=login.current_user)
Esempio n. 6
0
def register():
	"""
	An admin user already logged is allowed to register new usernames
	the new usernames cannot be changed at the moment nor can they be
	deleted unless done from command line
	
	Registeration is not through ajax requests it's through proper form
	POST request
	"""
	if request.method == "POST":
		username = request.form["username"]
		password = request.form["password"]
		confirm = request.form["confirm"]
		if confirm == password:
			passhash = generate_password_hash(password)
			new_user = {'username':username, 'password':passhash}
			check_insert = users.insert(new_user)
			if check_insert:
				return redirect(url_for('show_profiles'))
			else:
				#not done and error occured
				flash("For some reason it didn't work, try again")
		else:
			#dont proceed
			flash("Please enter the password same twice")
	return render_template('register.html')
Esempio n. 7
0
 def create_user(cls, username, password, admin=False):
     try:
         cls.create(username=username,
                    password=generate_password_hash(password),
                    is_admin=admin)
     except IntegrityError:
         ValueError("User already exists.")
Esempio n. 8
0
def editUser(form):
    if form.validate_on_submit():
        session = DBSession()
        user = session.query(User).filter(User.id == current_user.id).update({
            'title':
            form.title.data,
            'fname':
            form.fname.data,
            'lname':
            form.lname.data,
            'username':
            form.username.data,
            'email':
            form.email.data,
            'password':
            generate_password_hash(form.newpassword.data),
            'address':
            form.address.data,
            'state':
            form.state.data,
            'is_Admin':
            False
        })
        if user is not None:
            session.commit()
            return redirect(url_for('editaccount'))
    return render_template('editaccount.html', form=form)
Esempio n. 9
0
    def create_new_user_from_email(first_name, last_name, email, password):
        if len(password) < PASSWORD_MIN_LENGTH:
            raise User.UserCreationError(
                'Passwords must be at least 8 characters long.')

        user = User(
            email=email,
            first_name=first_name,
            join_date=datetime.datetime.now(),
            join_source=User.JoinSource.EMAIL,
            last_name=last_name,
            password=bcrypt.generate_password_hash(password,
                                                   rounds=BCRYPT_ROUNDS),
        )

        try:
            user.save()
        except me.base.ValidationError as e:
            if 'email' in e.errors:
                raise User.UserCreationError('Oops, that email is invalid.')
            raise
        except me.queryset.NotUniqueError as e:
            raise User.UserCreationError(
                'That email is already signed up.'
                ' (Maybe you already signed up with Facebook?)')
        return user
Esempio n. 10
0
    def save(self, **kwargs):
        print kwargs.get('username')
        self.username = kwargs.get('username', self.username)
        password = kwargs.get('password', self.password)
        self.password = generate_password_hash(
            password) if password != self.password else password
        self.email = kwargs.get('email', self.email)
        self.first_name = kwargs.get('first_name', self.first_name)
        self.last_name = kwargs.get('last_name', self.last_name)
        birthday = kwargs.get('birthday', self.birthday)
        self.birthday = datetime.strptime(
            birthday, '%Y-%m-%dT%H:%M:%S.%fZ') if type(birthday) == type(
                unicode('')) else birthday
        self.gender = kwargs.get('gender', self.gender)
        self.address = kwargs.get('address', self.address)
        self.coordinates = kwargs.get('coordinates', self.coordinates)
        self.is_staff = kwargs.get('is_staff', self.is_staff)
        self.is_active = kwargs.get('is_active', self.is_active)
        date_joined = kwargs.get('date_joined', self.date_joined)
        self.date_joined = datetime.strptime(
            date_joined, '%Y-%m-%dT%H:%M:%S.%fZ') if type(date_joined) == type(
                unicode('')) else date_joined
        friends = kwargs.get('friends', self.friends)
        new_friends = []
        for f in friends:
            if isinstance(f, int):
                new_friends.append(User.query.filter_by(id=f).first())
            else:
                new_friends.append(f)
        self.friends = new_friends

        self.image = kwargs.get('image', self.image)
Esempio n. 11
0
	def __init__(self, username, email, password, joined_at=None, is_admin=False):
		self.username = username
		self.email = email
		self.password = generate_password_hash(password)
		if joined_at == None:
			self.joined_at = datetime.datetime.now()
		self.is_admin = is_admin
Esempio n. 12
0
    def create_user(self,
                    fname,
                    lname,
                    username,
                    email,
                    password,
                    address,
                    state,
                    title,
                    is_Admin=False):
        try:
            session = DBSession()
            myFirstUser = User(title=title,
                               fname=fname,
                               lname=lname,
                               username=username,
                               email=email,
                               password=generate_password_hash(password),
                               address=address,
                               state=state,
                               is_Admin=is_Admin)

            session.add(myFirstUser)
            session.commit()

        except IntegrityError:
            # recreate the session and re-add your object
            session = DBSession()
            session.add(User)
            raise ValueError('user Already Exist !')
Esempio n. 13
0
 def create_user(cls, user, password, admin=False):
     try:
         cls.create(user=user,
                    password=generate_password_hash(password),
                    is_admin=admin)
     except IntegrityError:
         raise ValueError("Username already in use")
Esempio n. 14
0
 def create_user(cls, email, password):
     try:
         with DATABASE.transaction():
             cls.create(email=email,
                        password=generate_password_hash(password))
     except IntegrityError:
         raise ValueError("User already exists")
Esempio n. 15
0
	def create_user(cls, user, password, admin=False):
		try:
			cls.create(
				user=user,
				password=generate_password_hash(password),
				is_admin=admin)
		except IntegrityError:
			raise ValueError("Username already in use")
Esempio n. 16
0
def change_user_password(pk_id, old_password, new_password):
    """Edit a user. Old password is required."""
    user = User.get(User.id == pk_id)

    if check_password_hash(user.password, old_password):
        user.update(password=generate_password_hash(new_password)).execute()
    else:
        raise PermissionError("Invalid password.")
Esempio n. 17
0
 def create_user(cls, email, password):
     try:
         cls.create(
             email=email,
             password=generate_password_hash(password)
         )
     except IntegrityError:
         raise ValueError('Email unavailable.')
Esempio n. 18
0
 def __init__(self, fullname, username, email, address, phone_number, password):
     self.fullname = fullname
     self.username = username
     self.email = email
     self.address = address
     self.phone_number = phone_number
     self.password = generate_password_hash(password)
     self.created = datetime.datetime.now()
Esempio n. 19
0
def add_user(username, password, email):
    pw_hash = generate_password_hash(password)
    try:
        uid = mongo.db.users.insert({'username': username, 'hash': pw_hash,
                                     'email': email})
        return True
    except pymongo.errors.DuplicateKeyError:
        return False
Esempio n. 20
0
 def update_model(self, form, model):
     existing_password = model.password
     password = form.password.data
     updated = super(UserModelView, self).update_model(form, model)
     if password != existing_password:
         model.password = generate_password_hash(password) if password else None
         model.save()
     return updated
Esempio n. 21
0
def create_user(**kwargs):
    """Takes arguments and create a new user.
    :param kwargs:
    """
    db.connect()
    User.create(first_name=kwargs['first_name'], second_name=kwargs['second_name'],
                phone=kwargs['phone'], role=kwargs['role'], username=kwargs['username'],
                password=generate_password_hash(kwargs['password']), email=kwargs['email'])
Esempio n. 22
0
def change_user_password(pk_id, old_password, new_password):
    """Edit a user. Old password is required."""
    user = User.get(User.id == pk_id)

    if check_password_hash(user.password, old_password):
        user.update(password=generate_password_hash(new_password)).execute()
    else:
        raise PermissionError("Invalid password.")
 def create_user(cls, email, password):
     try:
         cls.create(
             email=email,
             password=generate_password_hash(password)
         )
     except IntegrityError:
         raise ValueError
Esempio n. 24
0
 def create_user(cls, email, password, admin=False):
     try:
         cls.create(
             email=email,
             password=generate_password_hash(password),
             is_admin=admin)
     except IntegrityError:
        raise ValueError("User already exists")
Esempio n. 25
0
 def create_user(cls, username, password, admin=False):
     try:
         with database.transaction():
             return cls.create(
                 username=username,
                 password=generate_password_hash(password),
                 is_admin=admin)
     except IntegrityError:
         raise ValueError("User already exists")
Esempio n. 26
0
def bcryptbenchmark():
    "Test number of rounds"
    # Chance the number of rounds (second argument) until it takes between
    # 0.25 and 0.5 seconds to run.
    from flask.ext.bcrypt import generate_password_hash
    import time
    duration = 0
    i = 4
    while duration < 0.25:
        start = time.time()
        generate_password_hash('password1', i)
        end = time.time()
        duration = end - start
        i += 1
    print("(" + str(duration) + " secounds)")
    print("please copy the next line into config.py")
    print("")
    print("BCRYPT_LOG_ROUNDS=" + str(i))
Esempio n. 27
0
 def create_user(cls, username, email, password, is_admin=False):
     try:
         cls.create(
             username=username,
             email=email,
             password=generate_password_hash(password)
         )
     except IntegrityError:
         raise ValueError("User already exists.")
Esempio n. 28
0
 def create_user(cls, username, email, password, admin=False):
     try:
         user_record = cls.create(username=username,
                    email=email,
                    password=generate_password_hash(password),
                    is_admin=admin)
     except IntegrityError:
         raise ValueError("User already exists")
     return user_record
Esempio n. 29
0
 def __init__(self, full_name, username, email, password):
     self.full_name = full_name
     self.username = username
     self.email = email
     self.password = generate_password_hash(password)
     self.createdtime = datetime.datetime.now()
     self.updatedtime = datetime.datetime.now()
     self.deleted = 0
     self.id_type_user = 5
Esempio n. 30
0
 def create_user(cls, username, email, password, admin=False):
     """Secure user creation in the database"""
     try:
         cls.create(username=username,
                    email=email,
                    password=generate_password_hash(password),
                    is_admin=True)
     except IntegrityError:
         raise ValueError("User already exists")
Esempio n. 31
0
    def post(self):
        data = request.get_json()

        hashed_password = generate_password_hash(data['password'])
        user = User(data['email'], hashed_password)
        db.session.add(user)
        db.session.commit()

        return user
Esempio n. 32
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")
Esempio n. 33
0
    def post(self):
        data = request.get_json()

        hashed_password = generate_password_hash(data['password'])
        user = User(data['email'], hashed_password)
        db.session.add(user)
        db.session.commit()

        return user
Esempio n. 34
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("Usuario ya Existe")
Esempio n. 35
0
 def create_user(cls, email, password):
     try:
         with DATABASE.transaction():
             cls.create(
                 email=email,
                 password=generate_password_hash(password)
             )
     except IntegrityError:
         raise ValueError("User already exists.")
Esempio n. 36
0
 def register_user(cls, email, password):
     try:
         user = AppUser.get(AppUser.email == email)
     except DoesNotExist:
         raise ValueError('User not created by admin')
     if user.password is not None:
         raise ValueError('User already registered')
     user.password = generate_password_hash(password)
     user.save()
Esempio n. 37
0
	def create_user(cls, username, email, password, admin, position):
		try:
			cls.create(
				username=username,
				email=email,
				password=generate_password_hash(password),
				is_admin=admin,
				position=position)
		except IntegrityError:
			raise ValueError("User already exists")
Esempio n. 38
0
 def update_user(cls, user_id, username=None, email=None, password=None):
     user_record = cls.get(id=user_id)
     if username:
         user_record.username = username
     if email:
         user_record.email = email
     if password:
         user_record.password = generate_password_hash(password)
     user_record.save()
     return user_record
Esempio n. 39
0
 def create_user(cls, username, password, admin=False):
   try:
     cls.create(
       #email = email,
       username = username,
       password = generate_password_hash(password),
       is_admin = admin
       )
   except IntegrityError:
     raise ValueError("User with the same email exists!")
Esempio n. 40
0
 def create_user(cls, username, email, password, admin = False): #cls instead of self
     try:
         cls.create(
         username = username,
         email = email,
         password = generate_password_hash(password),
         is_admin = admin
         )
     except IntegrityError:
         raise ValueError("User already exists")
Esempio n. 41
0
 def create_user(cls, username, email, password, admin=False):
     try:
         with DATABASE.transaction():    # transaction says, try this thing out, if it works - awesome, if not, remove whatever you just did
             cls.create(
                 username=username,
                 email=email,
                 password=generate_password_hash(password),
                 is_admin=admin)
     except IntegrityError:
         raise ValueError('User already exists')
Esempio n. 42
0
 def create_user(cls, email, password, admin=False, confirmed=True):
     try:
         cls.create(
             email=email,
             password=generate_password_hash(password),
             is_admin=admin,
             confirmed=confirmed,
         )
     except IntegrityError:
         raise ValueError('User already exists')
Esempio n. 43
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("Username or email already exists")
 def create_user(cls, username, email, password, admin=False):
     """Secure user creation in the database"""
     try:
         cls.create(
             username = username,
             email = email,
             password = generate_password_hash(password),
             is_admin = True)
     except IntegrityError:
         raise ValueError("User already exists")
Esempio n. 45
0
    def nuevo(cls, usuario, email, password, admin=False, puntos=0):
    	try:
    		cls.create(
	    		usuario=usuario,
	    		email=email,
	    		puntos=puntos,
	    		password=generate_password_hash(password),
	    		es_admin=admin
	    	)
    	except IntegrityError:
    		raise ValueError("El usuario ya existe")
Esempio n. 46
0
	def create_user(cls, username, email, password, name, department, is_admin=False): # CREATE user 
		try:
			with DATABASE.transaction():
				cls.create(
					username = username,
					email = email, 
					password = generate_password_hash(password), # encripting the password for security 
					name = name,
					department = department)

		except IntegrityError: raise ValueError("User already exists")
Esempio n. 47
0
 def create_user(cls, username, email, password, admin=False):
     try:
         with DATABASE.transaction():
             # transaction: if it works, awesome, keep going
             # if not, remove whatever thing you just did.
             cls.create(username=username,
                        email=email,
                        password=generate_password_hash(password),
                        is_admin=admin)
     except IntegrityError:
         raise ValueError("User already exists")
Esempio n. 48
0
def add_user(username, password, email):
    pw_hash = generate_password_hash(password)
    try:
        res = r.table("users").insert({'id': genPrimaryKey64("%s%s" % (
            username, email)), 'username': username, 'hash': pw_hash, 'email': email}).run(rdb.conn)
        if res["inserted"] == 1:
            return True
        else:
            return False
    except Exception:
        return False
Esempio n. 49
0
def signup():
	if not app.config.get("ENABLE_SIGNUP", False):
		return abort(404)

	elif (request.method == "POST" and
		request.form["id"] and request.form["password"]):
		u = model.User(request.form["id"], generate_password_hash(request.form["password"]), common.generate_random_string(32))
		db.session.add(u)
		db.session.commit()
		return redirect(url_for("signin"))
	else:
		return render_template("signup.html")
Esempio n. 50
0
    def update_password(self, password):
        """Update user's password

        Takes in a raw password and automatically hashes it using and updates the user

        `password`: the user's new unhashed password
        """
        try:
            self.password = generate_password_hash(password)
            self.save()
        except Exception as e:
            raise e
Esempio n. 51
0
def dbfill():
    # if the admin user is not created, create one
    user = UserBasic.query.filter_by(email="*****@*****.**").first()
    if user is None:
        au = UserBasic(email="*****@*****.**", nickname="verdverm")
        bu = UserBasic(email="*****@*****.**", nickname="tony")
        db.session.add(au)
        db.session.add(bu)

        aa = UserAuth(user_id=1,
                      hpass=generate_password_hash("verdverm"),
                      role=USER.ADMIN,
                      status=USER.ACTIVE)
        db.session.add(aa)

        ba = UserAuth(user_id=2,
                      hpass=generate_password_hash("iassic"),
                      role=USER.USER,
                      status=USER.ACTIVE)
        db.session.add(ba)

        db.session.commit()
Esempio n. 52
0
def profile():
    form = forms.ChangePasswordForm()
    if form.validate_on_submit():
        user = models.User.get(models.User.email == form.email.data)
        if user:
            user.password = generate_password_hash(form.password.data)
            user.save()
            flash('Password successfully changed.', 'success')
            return redirect(url_for('profile'))
        else:
            flash('Password change was unsuccessful.', 'error')
            return redirect(url_for('profile'))
    return render_template('profile.html', form=form)
Esempio n. 53
0
 def create_user(cls,
                 username,
                 email,
                 password,
                 admin=False):  # cls instead of self
     # if user gets, say, halfway created, to go back
     with DATABASE.transaction():
         try:
             cls.create(username=username,
                        email=email,
                        password=generate_password_hash(password),
                        is_admin=admin)
         except IntegrityError:
             raise ValueError
Esempio n. 54
0
def change_pass(username, email, password):
    pw_hash = generate_password_hash(password)
    try:
        q = r.table("users").get(genPrimaryKey64("%s%s" %
                                                 (username, email))).update({
                                                     "hash":
                                                     pw_hash
                                                 }).run(rdb.conn)
        if q["replaced"]:
            return True
        else:
            return False
    except Exception as err:
        print err
        return False
Esempio n. 55
0
 def create_user(cls,
                 username,
                 email,
                 password,
                 teacher=False,
                 parent=False,
                 student=False):
     try:
         with DATABASE.transaction():
             cls.create(username=username,
                        email=email,
                        password=generate_password_hash(password),
                        is_teacher=teacher,
                        is_parent=parent,
                        is_student=student)
     except IntegrityError:
         raise ValueError("User already exists")
Esempio n. 56
0
    def create_user(
            cls,
            username='******',
            phone=775527640,
            email='*****@*****.**',
            account_type='supplier',
            password='******',
            address='77 Quorn Avenue, Mount Pleasant, Harare, Zimbabwe',
            profile='default.png'):

        cls.create(username=username,
                   phone=phone,
                   email=email,
                   profile=profile,
                   account_type=account_type,
                   password=generate_password_hash(password, 12),
                   address=address)
Esempio n. 57
0
def add_user(username, password, email):
    pw_hash = generate_password_hash(password)
    try:
        res = r.table("users").insert({
            'id':
            genPrimaryKey64("%s%s" % (username, email)),
            'username':
            username,
            'hash':
            pw_hash,
            'email':
            email
        }).run(rdb.conn)
        if res["inserted"] == 1:
            return True
        else:
            return False
    except Exception:
        return False