Exemple #1
0
def add_new_hashed_password(user_id: int, new_password: str) -> str:
    if not validate_new_hash_password(user_id, new_password):
        raise PasswordDiffException()
    hashed_password = hash_password(new_password)
    repo.add_new_hash_password(user_id, hashed_password)
    repo.delete_old_password(user_id)
    return hashed_password
Exemple #2
0
def login():
    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))

    form = LoginForm(csrf_enabled=False)

    if form.validate_on_submit():
        session['remember_me'] = form.remember_me.data

        # Login from user database
        user = User.query.filter_by(email=form.email.data,
                                    password=hash_password(
                                        form.password.data)).first()

        #             print "found ", user
        #             print "email ", form.email.data
        #             print "pwhash ", hash_password(form.password.data)

        if user:
            setup_user_session(user, form.remember_me.data)
            return redirect(request.args.get('next') or url_for('game_list'))

        else:
            session['user_id'] = None
            flash('User not found with that id/password.')

    # If there were validation errors, flash them to the view
    flash_errors(form)

    return render_template("/login.html", title="Login", form=form)
def create_user(data):
    """
    input:
        - username: string
        - password: string
    output:
        - return error if username is existed
        - if username is not existed
            - create new salt
            - hash password
            --> create new user (username, hashed password, salt)
    """
    username = data["username"]
    password = data["password"]

    user = db.session.query(UserModel).filter(
        UserModel.username == username).first()
    if user:
        return jsonify({"message": "Existed username"}), 400

    salt = create_salt()
    hashed_password = hash_password(password + salt)

    new_user = UserModel(username, hashed_password, salt)
    db.session.add(new_user)
    db.session.commit()

    token = encode(new_user).decode("UTF-8")
    return jsonify({"access_token": token}), 201
Exemple #4
0
    def password(self, password):
        pass_pattern = r'^.{6,}$'
        match = re.match(pass_pattern, password)
        if not match:
            raise InvalidUserInputError(msg='Password too short')

        passhash = hash_password(password)
        self._password = passhash
def create_dummy_user(username, password):
    user = db.session.query(UserModel).filter(
        UserModel.username == username).first()
    if not user:
        salt = create_salt()
        hashed_password = hash_password(password + salt)

        new_user = UserModel(username, hashed_password, salt)

        token = jwt.encode({"user": username}, secret_key).decode("UTF-8")

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

        return token
    if user.password != hash_password(password + user.salt):
        return 401
    return jwt.encode({"user": username}, secret_key).decode("UTF-8")
Exemple #6
0
def user_signup_format(data):
	return {
		"id": str(helpers.generate_uuid()),
		"username" : str(data['username']),
		"display_name" : str(data['display_name']),
		"password" : helpers.hash_password(str(data['password'])),
		"intrests" : data['intrests'],
		"gravatar" : None,
		"is_active" : True, 
		"date_of_birth" :None,
		"created_at" : str(datetime.datetime.now()),
		"updated_at" : str(datetime.datetime.now())
	}
Exemple #7
0
def room(name):
    path_to_timer_json = server.config['DB_PATH'] + '/{}.json'.format(name)

    if request.method == 'GET':
        try:
            f = open(path_to_timer_json, 'r')
            json_from_db = json.load(f)
            f.close()
            return json_from_db
        except FileNotFoundError:
            return jsonify('There is no json at {}'.format(path_to_timer_json))

    elif request.method == 'POST':
        json_from_post = request.get_json()
        try:
            f = open(path_to_timer_json, 'r')
            json_from_db = json.load(f)
            f.close()
            if json_from_db['password'] == helpers.hash_password(
                    json_from_post['password']):
                timer_obj = helpers.Timer(json_from_post['duration'],
                                          json_from_post['is_playing'],
                                          json_from_post['start_time'],
                                          json_from_post['password'])
                json_to_db = timer_obj.json_repr()
                f = open(path_to_timer_json, 'w')
                json.dump(json_to_db, f)
                f.close()
                del (timer_obj)
                return redirect(url_for('room', name=name))
            else:
                f.close()
                return jsonify(
                    'Unable to edit timer at {}, admin password incorrect'.
                    format(url_for('room', name=name)))
        except FileNotFoundError:
            f = open(path_to_timer_json, 'w')
            timer_obj = helpers.Timer(json_from_post['duration'],
                                      json_from_post['is_playing'],
                                      json_from_post['start_time'],
                                      json_from_post['password'])
            json_to_db = timer_obj.json_repr()
            json.dump(json_to_db, f)
            f.close()
            return redirect(url_for('room', name=name))
    else:
        return redirect(url_for('index'))
def create_new_register(email, fullname, password, **kwargs) -> Register:
    phone_number = string_utils.normalize_phone_number(kwargs.get('phone_number'))
    validate_register(email, phone_number, fullname, password)

    existed_user = user_service.find_one_by_email_or_phone_number(email, phone_number)
    if existed_user: raise UserExistsException()

    existed_pending_register = find_one_by_email_or_phone_number(email, phone_number)
    if existed_pending_register: raise RegisterBeforeException()

    return repo.create_new_register(
        email=email,
        fullname=fullname,
        phone_number=phone_number,
        password=hash_password(password),
        gender=kwargs.get('gender') or 1,
        address=kwargs.get('address') or ''
    )
def auth(data):
    """
    input:
        - username
        - password
    output:
        - token
    """
    username = data["username"]
    password = data["password"]

    user = db.session.query(UserModel).filter(
        UserModel.username == username).first()

    if not user or hash_password(password + user.salt) != user.password:
        return jsonify({"message": "Invalid username or password"}), 401

    token = encode(user).decode("UTF-8")
    return jsonify({"access_token": token}), 200
Exemple #10
0
def signup():
    del g.user

    form = SignupForm()

    if form.validate_on_submit():
        # Create a new user and organization
        user = User(givenname=form.givenname.data,
                    surname=form.surname.data,
                    email=form.email.data,
                    created_by=form.email.data,
                    updated_by=form.email.data,
                    created_at=int(time.time()),
                    updated_at=int(time.time()))
        user.password = hash_password(form.password.data)
        if form.accept_tos.data:
            user.tos_agree = int(time.time())

        db.session.add(user)

        try:
            db.session.commit()

            flash(
                "Welcome!  Please check your email for a confirmation message."
            )
            return redirect(url_for('game_list'))

        except IntegrityError as e:
            reason = e.message

            flash(reason)

    for field, errors in form.errors.items():
        for error in errors:
            flash(u"Error in the %s field - %s" %
                  (getattr(form, field).label.text, error))

    return render_template("signup.html", title="Registration", form=form)
Exemple #11
0
    def test2_creating_new_room(self):
        '''Ensures that new rooms can be created via POST request'''
        from app.helpers import hash_password
        ep = self.root_endpoint
        pw = 'password123'
        hashed_password = hash_password(pw)

        r = send_get_to_room_url(ep, 'new_room')
        self.assertEqual(
            type(r.json()), type(''),
            'room already exists at this location, did you remember to kill the server?'
        )

        t = Timer(duration=400, is_playing=False, start_time=0, password=pw)

        self.assertEqual(t.password, hashed_password,
                         "Timer object isn't hashing passwords properly")

        j = t.json_repr()
        j['password'] = pw
        r = send_post_to_room_url(ep, 'new_room', j)

        self.assertEqual(
            r.status_code, 200,
            'expected status code 200, got {} instead'.format(r.status_code))
        self.assertEqual(
            r.headers['content-type'], 'application/json',
            'Expected "application/json" in header, got {} instead'.format(
                r.headers['content-type']))

        r_dict = r.json()

        self.assertEqual(
            r_dict["password"], t.password,
            "Expected response JSON Password to be \n {}".format(t.password) +
            "\n Was \n {} \n instead".format(r_dict["password"]))
Exemple #12
0
def change_password(user, new_password) -> User:
    password_hash = hash_password(new_password)
    user.password = password_hash
    return save(user)