Exemplo n.º 1
0
def register():
	newUser = request.get_json()
	if UserModel.find_by_username(newUser['username']):
		return {'message':'Username already exists'}, 400
	user = UserModel(newUser['username'],hash_password(newUser['password']))
	user.save_to_db()
	return jsonify({'message':'User created successfully'})
Exemplo n.º 2
0
 def register_account(cls, username, password, email):
     hashed_password = security.hash_password(password)
     account = Account(username=username,
                       hashed_password=hashed_password,
                       email=email)
     account.put()
     return account
Exemplo n.º 3
0
def consumer_edit(request):
    consumer = DBSession.query(Consumer).get(int(request.matchdict['id']))
    if DBSession.query(User).filter(User.email == request.json['email']).filter(User.id != consumer.id).one_or_none():
        request.response.status = 403
        return {'msg' :  MESSAGES['email']}
    consumer.email = request.json['email']
    consumer.password = hash_password(request.json['password'])
    consumer.first_name = request.json['first_name']
    consumer.second_name = request.json['second_name']
    consumer.languages = request.json['languages']
    consumer.gender = request.json['gender']
    if 'interests' in request.json.keys():
        old_interests = set(map(lambda x: x.id, consumer.interests))
        new_interests = set(request.json['interests'])
        to_remove = old_interests.difference(new_interests)
        to_add = new_interests.difference(old_interests)
        try:
            if len(to_remove):
                DBSession.execute(consumer_interests.delete()
                        .where(and_(consumer_interests.c.consumer_id == consumer.id, consumer_interests.c.course_category_id.in_(to_remove))))
            if len(to_add):
                DBSession.execute(consumer_interests.insert(), [
                    {'consumer_id': consumer.id, 'course_category_id': x} for x in to_add
                ])
        except SQLAlchemyError as e:
            LOG.exception(e.message)
            request.response.status = 500
            return {'msg' :  MESSAGES['db'], 'err' : e.message}
    DBSession.flush()
    request.response.status = 200
    return {'msg' : MESSAGES['ok']}   
Exemplo n.º 4
0
def user():
    url = __check_login('user')
    if url: return redirect(url)
    usererrors = []
    userform = UserForm(prefix="user")
    user = get_user(session['email'])
    if request.method == 'GET':
        # Add default values
        userform.email.data = user.email
        userform.first_name.data = user.short_name
        userform.last_name.data = user.family_name
        userform.alias.data = user.alias
    elif userform.validate_on_submit(): 
        if (validate_login(session['email'], userform.password.data)):
            # Update info
            user.email = userform.email.data
            user.short_name = userform.first_name.data 
            user.family_name = userform.last_name.data
            user.full_name = userform.first_name.data + " " + userform.last_name.data
            user.alias = userform.alias.data if userform.alias.data != "" else None
            if (userform.new_password.data):
                user.password = hash_password(userform.new_password.data)
            save_user(user)
            flash(_(u'Information updated'))
        else:
            usererrors.append(_(u'Invalid password'))
    if userform.errors:
        for key, value in userform.errors.items():
            usererrors.append(key + ': ' + value[0])

    return render_template('user.html', userform=userform, usererrors=usererrors)
Exemplo n.º 5
0
def create_tables():
    for sql in create_tables_SQL:
        process_sql(sql)

    if not process_sql("Select * FROM LoginTbl"):
        pwdhash = security.hash_password('password')
        process_sql("INSERT INTO LoginTbl VALUES (?, ?)",
                    parameters=('admin', pwdhash))
Exemplo n.º 6
0
 def post(self):
     newUser = UserRegister.parser.parse_args()
     if UserModel.find_by_username(newUser['username']):
         return {'message': 'Username already exists'}, 400
     user = UserModel(newUser['username'],
                      hash_password(newUser['password']), newUser['email'])
     user.save_to_db()
     return {'message': 'User created successfully'}
Exemplo n.º 7
0
    def post(self):
        data = UserRegister.parser.parse_args()
        if UserModel.find_by_username(data['username']):
            return {"message": "A user with that username already exists"}, 400

        user = UserModel(data['username'], hash_password(data['password']))
        user.save_to_db()

        return {"message": "User created successfully."}, 201
Exemplo n.º 8
0
def create_user(db: Session, user: UserCreate) -> User:
    """ Create a new entry in the database user table """
    user_data = user.dict()
    user_data["password"] = hash_password(user.password)
    db_user = User(**user_data)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
Exemplo n.º 9
0
def registration(cursor, data):
    data.update({'registration_time': utility.get_date_time(),
                 'reputation': 0,
                 'hashed_pw': security.hash_password(data['password'])})
    cursor.execute(
        sql.SQL('''
                INSERT INTO users (user_name, hashed_pw, reputation, registration_time)
                VALUES (%(username)s, %(hashed_pw)s, %(reputation)s, %(registration_time)s);
        '''), data
    )
Exemplo n.º 10
0
def create_new_acc() -> bool:
    os.chdir('TheFourth')
    files = os.listdir('notes')
    for i in range(3):
        try:
            new_login = input("Придумайте логин аккаунта(без пробелов):")
            if ' ' in new_login:
                i += 1
            elif len(new_login) < 1:
                i += 1
            elif len(new_login) > 100:
                i += 1
            elif new_login in files:
                i += 1
            else:
                break
            if i == 3:
                os.chdir('..')
                return False
        except BaseException:
            print("Проблемы с логином")
    for i in range(3):
        try:
            new_password = input("Придумайте пароль аккаунта(без пробелов):")
            if ' ' in new_password:
                i += 1
            elif len(new_login) < 1:
                i += 1
            elif len(new_login) > 30:
                i += 1
            else:
                choise = True
                break
            if i == 3:
                os.chdir('..')
                return False
        except BaseException:
            print("Проблемы с паролем")
    if choise is True:
        os.chdir('notes')
        os.mkdir(new_login)
        os.chdir(new_login)
        master_key = security.master_key(new_password)
        encode_key = security.encrypt(security.secret_key(), master_key)
        mainfile = open("maininf.conf", 'w')
        mainfile.write(new_login + ' ' + security.hash_password(new_password))
        mainfile.close()
        encodefile = open("encodeinf.conf", 'wb')
        encodefile.write(encode_key)
        encodefile.close()
        os.chdir('..')
        os.chdir('..')
        os.chdir('..')
        return True
    return False
Exemplo n.º 11
0
    def post(self):
        """Register a new user."""
        req_body = request.get_json()

        not_found = []
        required_fields = ("email", "password")
        for field in required_fields:
            if field not in req_body.keys():
                not_found.append(field)

        if not_found:
            return (
                f"Required field(s) not found:"
                f" {', '.join(field for field in not_found)}",
                400,
            )

        # Check if email is valid
        user_email = req_body["email"]
        try:
            validate_email(user_email)
        except ValidationError:
            return "Incorrect format for field: email", 400

        # Check if password is secure enough
        user_password = req_body["password"]
        try:
            validate_password(user_password)
        except ValidationError:
            return (
                "Password is not secure enough: include at least one uppercase,"
                " one lowercase, one number and one symbol, and keep it between"
                " 12 and 255 characters long. Whitespace is not allowed.",
                400,
            )

        salt = generate_random_salt()
        hashed_password = hash_password(user_password, salt)

        # noinspection PyArgumentList
        new_user = User(
            email=user_email,
            password=hashed_password,
            salt=str(salt, encoding=ENCODING),
        )
        db.session.add(new_user)

        try:
            db.session.commit()
        except IntegrityError:
            return {}, 409

        apikey = get_or_create_api_key(new_user)

        return apikey, 201
Exemplo n.º 12
0
 def login_query(self, form):
     """Login if credentials match"""
     if not form:
         return None
     username = form.get("username")
     hashed_password = hash_password(form.get("password"))
     result = self._is_user(username, hashed_password)
     if result:
         return {"username": username, "secret": hashed_password}
     else:
         return None
Exemplo n.º 13
0
def create_list():
    params = request.get_json()

    user.name = params['name']
    user.email = params['email']
    user.password = hash_password(params['password'])

    db.session.add(user)
    db.session.commit()

    return jsonify(user)
Exemplo n.º 14
0
    def add_user(self, new_user, request):
        root = firstpyramid.root_factory(request)

        root['users'].update({
            new_user['username']: {
                'password': hash_password(new_user['password']),
                'name': new_user['name']
            }
        })

        transaction.commit()
Exemplo n.º 15
0
def register():
    """Create user, add to the database."""

    # submit button disabled if any field is left blank
    # cleared form in component after fetch to resolve infinite loop

    data = request.get_json()
    username = data.get('username')
    fname = data.get('fname')
    user_region = data.get('user_region')
    password = data.get('password')
    confirm_password = data.get('confirm_password')

    # check if a user is logged in, if so redirect to /garden
    current_user = session.get('user_id')
    if current_user is not None:
        flash("You're already logged in!")
        return jsonify({'response': 'success'})

    # check if username exists in db, if so redirect to /register
    user = crud.get_user_by_username(username)
    if user:
        flash("Username is already registered, please try another name.")
        return jsonify({'response': 'failed'})

    # if passwords entered don't match, redirect to /register
    if password != confirm_password:
        flash("Passwords do not match, please try again.")
        return jsonify({'response': 'failed'})

    # if password, encrypt
    if password is not None:
        hashed = hash_password(password)

        # create new user in db
        new_user = crud.create_user(username=username,
                                    fname=fname,
                                    password_hash=hashed,
                                    user_region=user_region)

        # create garden in db associated with new user
        new_usergarden = crud.create_user_garden(user_id=new_user.user_id)

        # save user_id, user_region, usergarden_id and fname to session
        session['usergarden_id'] = new_usergarden.usergarden_id
        session['user_id'] = new_user.user_id
        session['user_region'] = new_user.user_region
        session['fname'] = new_user.fname

        flash(f"Welcome, { fname }!")

        # redirect to /garden
        return jsonify({'response': 'success'})
Exemplo n.º 16
0
def provider_edit(request):
    provider = DBSession.query(Provider).get(int(request.matchdict['id']))
    if DBSession.query(User).filter(User.email == request.json['email']).filter(User.id != provider.id).one_or_none():
        request.response.status = 403
        return {'msg' :  MESSAGES['email']}
    provider.email = request.json['email']
    provider.password = hash_password(request.json['password'])
    provider.name = request.json['name']
    provider.website = request.json['website']
    provider.about = request.json['about']
    DBSession.flush()
    request.response.status = 200
    return {'msg' : MESSAGES['ok']} 
Exemplo n.º 17
0
    def patch(self, user):
        """Edit individual fields on a user. Non-admins can only edit some fields on
        their own account.
        """

        req_data = request.get_json()
        invalid_fields = []
        modified = 0
        for key in req_data:
            if not hasattr(user, key) or key in ("id", "salt"):
                invalid_fields.append(key)
                continue

            if not invalid_fields:
                if key == "email":
                    new_email = req_data[key]
                    try:
                        validate_email(new_email)
                    except ValidationError:
                        return "Invalid format for email address.", 400
                    user.email = new_email
                    modified += 1
                elif key == "password":
                    new_password = req_data[key]
                    try:
                        validate_password(new_password)
                    except ValidationError:
                        return "New password is not secure enough or too long.", 400
                    new_salt = generate_random_salt()
                    user.password = hash_password(new_password, new_salt)
                    user.salt = new_salt
                    modified += 1
                elif key == "lemmas":
                    lemma_refs = req_data[key]
                    if isinstance(lemma_refs[0], int):
                        lemma_filter = Lemma.id.in_(lemma_refs)
                    else:
                        lemma_filter = Lemma.content.in_(lemma_refs)
                    lemmas = Lemma.query.filter(lemma_filter)
                    user.lemmas.extend(lemmas)
                    modified += 1

        if invalid_fields:
            return f"Invalid fields: {', '.join(invalid_fields)}", 400

        if not modified:
            return "No valid field specified.", 400

        db.session.commit()

        return {}, 204
Exemplo n.º 18
0
def write_bd(login: str) -> Tuple[str, str]:
    password = input("Введите пароль\n")
    hash_salt = sec.hash_password(password)
    flag = True
    while flag:
        try:
            dir_name = str(random.randint(0, 1000))
            os.mkdir(dir_name)
            flag = False
            break
        except Exception:
            pass
    str0 = f'{login}|{hash_salt}|{dir_name}\n'
    return str0, dir_name
Exemplo n.º 19
0
def provider_add(request):
    if DBSession.query(User).filter(User.email == request.json['email']).one_or_none():
        request.response.status = 403
        return {'msg' :  MESSAGES['email']}
    provider = Provider()
    provider.email = request.json['email']
    provider.password = hash_password(request.json['password'])
    provider.name = request.json['name']
    provider.website = request.json['website']
    provider.about = request.json['about']
    provider.group = 'provider'
    DBSession.add(provider)
    DBSession.flush()
    request.response.status = 200
    return {'provider_id' : provider.id}  
Exemplo n.º 20
0
def consumer_add(request):
    if DBSession.query(User).filter(User.email == request.json['email']).one_or_none():
        request.response.status = 403
        return {'msg' :  MESSAGES['email']}
    consumer = Consumer()
    consumer.email = request.json['email']
    consumer.password = hash_password(request.json['password'])
    consumer.first_name = request.json['first_name']
    consumer.second_name = request.json['second_name']
    consumer.languages = request.json['languages']
    consumer.gender = request.json['gender']
    consumer.group = 'consumer'
    DBSession.add(consumer)
    DBSession.flush()
    request.response.status = 200
    return {'consumer_id' : consumer.id}  
Exemplo n.º 21
0
def create_user():

    try:
        body = request.get_json()

        email = extract_field_from_body('email', body)
        password = extract_field_from_body('password', body)
        nickname = extract_field_from_body('nickname', body)

        if email == None:
            raise Exception('Field email is missing.')
        if password == None:
            raise Exception('Field password is missing.')
        if nickname == None:
            raise Exception('Field nickname is missing.')

        data = {
            'email': email,
            'password': security.hash_password(password),
            'nickname': nickname
        }

        code, res = io_service.post('/users', data)

        if code == 201:
            activation_token = generate_activation_token()

            data = {'user_id': res['id'], 'token': activation_token}

            io_service.post('/activation_tokens', data)

            data = {'email': email, 'token': activation_token}

            email_service.get('/', data)

            return Response(json.dumps(res),
                            status=201,
                            mimetype='application/json')

        return Response('Bad request.',
                        status=400,
                        mimetype='application/json')

    except Exception as e:
        return Response(str(e), status=400, mimetype='application/json')
Exemplo n.º 22
0
def register():
    if len(request.form['username']) == 0 or len(
            request.form['password']) == 0:
        return json.dumps({'error': 'username or password is empty'})

    if security.check_text_validity(request.form['username']):
        if not security.check_password_validity(request.form['password']):
            return json.dumps({'error': 'invalid character in password'})
        if data_manager.get_username(request.form['username']):
            return json.dumps({'error': 'username already exists'})

        password = security.hash_password(request.form['password'])
        user = data_manager.user_register(request.form['username'], password)
        print(user)
        session['username'] = user['username']
        session['user_id'] = user['id']
        return json.dumps({'redirect': True})
    return json.dumps({'error': 'invalid character in username'})
Exemplo n.º 23
0
def route_registration():
    if request.method == 'POST':

        username = request.form.get('username')
        if data_handler.get_data_by_username(username):
            return render_template('signup.html',
                                   usernametaken=True,
                                   registration=True)
        password = hash_password(request.form.get('password'))
        registration_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        data_handler.add_new_user(username, password, registration_date)

        user_id = str(data_handler.get_data_by_username(username)[0]["id"])

        response = make_response(redirect(url_for('route_list')))
        response.set_cookie('user_id', user_id)
        response.set_cookie('username', username)
        return response

    return render_template('signup.html', registration=True)
Exemplo n.º 24
0
    def post(self):
        """Log the user in, verifying and matching login data to an API key."""
        req_data = request.get_json()
        user = User.query.filter_by(email=req_data["username"]).first()

        # To prevent timing attacks, get fake data and effect normal check operations
        #  even if the user is not found. getattr() is used because user could be None.
        stored_password = getattr(user, "password", None)
        salt = getattr(user, "salt", "N/A")

        hashed_input = hash_password(req_data["password"], salt)

        if hashed_input == stored_password:
            apikey = get_or_create_api_key(user)

            return {"APIKey": apikey.key}, 200

        return (
            "Password is incorrect or the username entered is not registered.",
            401)
Exemplo n.º 25
0
def reset(reset_key):
    user = get_user_by_reset_key(reset_key)
    if user is None:
        flash(_(u'Invalid password reset link'), 'error')
        return redirect(url_for('troikas'))
    resetform = ResetForm()
    reseterrors = []
    if resetform.validate_on_submit():
        user.password = hash_password(resetform.password.data)
        user.password_reset_key = None
        user.password_reset_expire = None
        session['email'] = user.email
        save_user(user)
        flash(_(u'Password reset successful, you were logged in'))
        return redirect(url_for('troikas'))
    if resetform.errors:
        for key, value in resetform.errors.items():
            reseterrors.append(key + ': ' + value[0])

    return render_template('reset.html', resetform=resetform, reseterrors=reseterrors)
Exemplo n.º 26
0
    def password(self, value):
        if len(value) < 6:
            raise Exception("Password must be at least 6 characters long")

        self.password_hash = unicode(security.hash_password(value))
Exemplo n.º 27
0
def change_password() -> bool:
    os.chdir('TheFourth')
    files = os.listdir('notes')
    for j in range(3):
        try:
            change_login = input("Введите логин аккаунта который изменяете:")
            if change_login in files:
                break
            else:
                j += 1
            if j == 3:
                os.chdir('..')
                return False
        except FileNotFoundError:
            print("Не найдено такого аккаунта")
    os.chdir('notes')
    os.chdir(change_login)
    with open("maininf.conf", 'r', encoding='utf-8') as change_file:
        method = change_file.readline().rstrip().split(' ')
        for i in range(3):
            try:
                change_pass = input("Введите пароль для данного аккаунта:")
                if security.check_password(method[1], change_pass) is True:
                    check = True
                    break
                else:
                    i += 1
                if i == 3:
                    os.chdir('..')
                    os.chdir('..')
                    os.chdir('..')
                    return False
            except BaseException:
                print("Проблемы с паролем")
    if check is True:
        for i in range(3):
            try:
                new_pass = input("Введите ваш новый пароль(без пробелов):")
                if ' ' in new_pass:
                    i += 1
                elif len(new_pass) < 1:
                    i += 1
                elif len(new_pass) > 30:
                    i += 1
                else:
                    choise = True
                    break
                if i == 3:
                    os.chdir('..')
                    os.chdir('..')
                    os.chdir('..')
                    return False
            except BaseException:
                print("Проблемы с паролем")
        if choise is True:
            with open('encodeinf.conf', 'rb') as encode_file:
                encode_key = encode_file.read()
            master_key = security.master_key(change_pass)
            new_master_key = security.master_key(new_pass)
            new_encode_key = security.decrypt(encode_key, master_key)
            new_encode_key = security.encrypt(new_encode_key, new_master_key)
            mainf = open("maininf.conf", 'w')
            mainf.write(change_login + ' ' + security.hash_password(new_pass))
            mainf.close()
            encodefile = open("encodeinf.conf", 'wb')
            encodefile.write(new_encode_key)
            encodefile.close()
            os.chdir('..')
            os.chdir('..')
            os.chdir('..')
            return True
    return False
Exemplo n.º 28
0
def change_password(username, password):
    pwdhash = security.hash_password(password)
    sql = "UPDATE LoginTbl SET PasswordHash = ? WHERE Username=?"
    process_sql(sql, parameters=(pwdhash, username))
Exemplo n.º 29
0
    def password(self, value):
        if len(value) < 6:
            raise Exception("Password must be at least 6 characters long")

        self.password_hash = unicode(security.hash_password(value))
Exemplo n.º 30
0
 def is_valid_password(self, password):
     hashed_password, salt = self.hashed_password.split(',')
     computed_hashed_password = security.hash_password(password, salt)
     return self.hashed_password == computed_hashed_password
Exemplo n.º 31
0
def add_user(username, password):
    pwdhash = security.hash_password(password)
    sql = "INSERT INTO LoginTbl (Username, PasswordHash) VALUES (?, ?)"
    process_sql(sql, parameters=(username, pwdhash))
Exemplo n.º 32
0
 def new(cls, username, password, email):
     hashed_password = security.hash_password(password)
     return cls.account.new(username=username,
                            hashed_password=hashed_password,
                            email=email)
Exemplo n.º 33
0
 def register_account(cls, username, password, email):
     hashed_password = security.hash_password(password)
     account = cls.new(username, hashed_password, email)
     return account.save()