Exemple #1
0
    def run(self, log: Log):
        self.init(log=log)

        if log.event_data[
                "AttributeLDAPDisplayName"] != "msDS-AllowedToActOnBehalfOfOtherIdentity":
            return

        # 只检测敏感计算机
        account = get_cn_from_dn(log.object_info.dn)
        domain = get_domain_from_dn(log.object_info.dn)
        if not self.account_info.computer_is_sensitive_by_name(
                account, domain=get_netbios_domain(domain)):
            return

        ldap = LDAPSearch(domain=domain)
        entry = ldap.search_by_cn(
            cn=account,
            attributes=["sid", "msDS-AllowedToActOnBehalfOfOtherIdentity"])
        if entry is None:
            return
        entry_sid = str(entry["sid"])

        sd = SR_SECURITY_DESCRIPTOR(entry.entry_attributes_as_dict[
            "msDS-AllowedToActOnBehalfOfOtherIdentity"][0])
        # 拥有特殊DACL权限的SID列表
        ace_list = []
        for ace in sd["Dacl"].aces:
            ace_list.append({
                "type_name": ace["TypeName"],
                "sid": ace['Ace']['Sid'].formatCanonical()
            })
        sid_list = list(map(lambda ace: ace["sid"], ace_list))
        sid_list = sorted(list(set(sid_list)))

        target_account_info = User({
            "user_name": account,
            "user_sid": entry_sid
        })

        # 查询历史委派记录
        record = self.delegation.find_res_constrained_delegation_by_name(
            name=account)
        # 不存在记录 则新建 并直接告警
        if not record:
            self.delegation.new_delegation_record(
                user=target_account_info,
                delegation_type=RES_BASED_CONSTRAINED_DELEGATION,
                allowed_to=sid_list)
            return self._generate_alert_doc(
                target_computer=account,
                target_user_name=target_account_info.user_name,
                target_user_sid=target_account_info.user_sid,
                add_allowed_sid=sid_list,
                old_allowed_sid=[])

        # 存在记录且不变,退出
        if sid_list == record["allowed_to"]:
            return

        # 存在记录 对比历史的sid 无新增 更新记录 退出
        new_sids = self._get_new_sid(new_list=sid_list,
                                     old_list=record["allowed_to"])
        if len(new_sids) == 0:
            self.delegation.update_delegation(
                sid=entry_sid,
                delegation_type=RES_BASED_CONSTRAINED_DELEGATION,
                allowed_to=sid_list)
            return

        # 存在记录 有新增 更新记录 告警
        if len(new_sids) > 0:
            self.delegation.update_delegation(
                sid=entry_sid,
                delegation_type=RES_BASED_CONSTRAINED_DELEGATION,
                allowed_to=sid_list)
            return self._generate_alert_doc(
                target_computer=account,
                target_user_name=target_account_info.user_name,
                target_user_sid=target_account_info.user_sid,
                add_allowed_sid=new_sids,
                old_allowed_sid=record["allowed_to"])
Exemple #2
0
def seed_db():
    from models.User import User
    from models.Store import Store
    from models.Product import Product
    from models.Customer import Customer
    from models.Order import Order
    from main import bcrypt
    from faker import Faker

    faker = Faker()
    users = []
    stores = []
    products = []
    customers = []

    for i in range(5):
        user = User()
        user.email = f"test{i+1}@test.com"
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        user.isAdmin = False
        db.session.add(user)
        users.append(user)

        db.session.commit()

        store = Store()
        store.storename = faker.bs()
        store.firstname = faker.first_name()
        store.lastname = faker.last_name()
        store.user_id = users[i].id
        db.session.add(store)
        stores.append(store)

        db.session.commit()

        for j in range(5):
            product = Product()
            product.title = faker.numerify(text="Duck ###")
            product.price = faker.random_int(min=5, max=200, step=5)
            product.store_id = stores[i].id
            db.session.add(product)
            products.append(product)

        db.session.commit()

        for j in range(5):
            customer = Customer()
            customer.firstname = faker.first_name()
            customer.lastname = faker.last_name()
            customer.email = faker.ascii_email()
            customer.phone = faker.phone_number()
            customer.store_id = stores[i].id
            db.session.add(customer)
            customers.append(customer)

            db.session.commit()

            for k in range(5):
                order = Order()
                order.order_placed = choice([True, False])
                order.customer_id = choice(customers).id
                db.session.add(order)

                db.session.commit()

                for m in range(3):
                    order.orders_products.append(choice(products))

                    db.session.commit()

        customers = []

    db.session.commit()

    print("Tables seeded")
    def testLogin(self):
        user = User(1, 'admin', 'usuario', '1234')
        result = user.login('usuario', '1234')

        self.assertNotEqual(result, False, 'Credenciales validas')
        self.assertEqual(result, True, 'Credenciales validas')
Exemple #4
0
    def update(self, analysisResult=AnalysisResult()):
        """
        (AnalysisResult) -> (AnalysisResult)
        update analysis_result table
        """
        session = self.session_factory()
        analysisResultDB = session.query(AnalysisResultDB).filter_by(
            id=analysisResult.id).first()
        dic = {}
        if (analysisResultDB.idAnalysis != analysisResult.analysis.id):
            dic['idAnalysis'] = analysisResult.analysis.id
        if (analysisResultDB.idDisease != analysisResult.disease.id):
            dic['idDisease'] = analysisResult.disease.id
        if (analysisResultDB.score != analysisResult.score):
            dic['score'] = analysisResult.score
        if (analysisResultDB.frame != analysisResult.frame):
            dic['frame'] = analysisResult.frame
        if (dic != {}):
            session.query(AnalysisResultDB).filter_by(
                id=analysisResult.id).update(dic)
            session.commit()
            session.flush()
            session.refresh(analysisResultDB)

        return AnalysisResult(
            analysisResultDB.id,
            Analysis(
                analysisResultDB.analysis.id,
                Image(
                    analysisResultDB.analysis.image.id,
                    Disease(
                        analysisResultDB.analysis.image.disease.id,
                        Plant(
                            analysisResultDB.analysis.image.disease.plant.id,
                            analysisResultDB.analysis.image.disease.plant.
                            scientificName, analysisResultDB.analysis.image.
                            disease.plant.commonName),
                        analysisResultDB.analysis.image.disease.scientificName,
                        analysisResultDB.analysis.image.disease.commonName),
                    analysisResultDB.analysis.image.url,
                    analysisResultDB.analysis.image.description,
                    analysisResultDB.analysis.image.source,
                    analysisResultDB.analysis.image.size),
                Classifier(
                    analysisResultDB.analysis.classifier.id,
                    Plant(
                        analysisResultDB.analysis.classifier.plant.id,
                        analysisResultDB.analysis.classifier.plant.
                        scientificName,
                        analysisResultDB.analysis.classifier.plant.commonName),
                    analysisResultDB.analysis.classifier.tag,
                    analysisResultDB.analysis.classifier.path),
                user=User(id=analysisResultDB.analysis.user.id,
                          idType=analysisResultDB.analysis.user.idType,
                          email=analysisResultDB.analysis.user.email,
                          username=analysisResultDB.analysis.user.username)),
            Disease(
                analysisResultDB.disease.id,
                Plant(analysisResultDB.disease.plant.id,
                      analysisResultDB.disease.plant.scientificName,
                      analysisResultDB.disease.plant.commonName),
                analysisResultDB.disease.scientificName,
                analysisResultDB.disease.commonName), analysisResultDB.score,
            analysisResultDB.frame)
Exemple #5
0
from models.CategoryBudget import CategoryBudget
from models.User import User
from session import session

# ADD USERS
# ------------------------------

user_names = ["Zbyszek", "Krzysiek", "Mariola"]
user_list = []

for i in range(len(user_names)):
    salt = os.urandom(32)
    # Test users' passwords == "test"
    key = hashlib.pbkdf2_hmac('sha256', "test".encode('utf-8'), salt, 100000)
    # append user instance
    user_list.append(User(name=user_names[i], salt=salt, key=key))

# Zapisz do bazy
session.add_all(user_list)
session.commit()

# ADD BUDGETS
# ------------------------------

budget_list = []

for user_instance in session.query(User).order_by(User.id):
    budget_list.append(
        Budget(name="Budżet użytkownika {}".format(user_instance.name),
               user_id=user_instance.id))
Exemple #6
0
    def get_all(rootNode):
        results = rootNode.find_elements_by_class_name("userContentWrapper")
        return [PollPostRepresentation(node) for node in results]

class Post(RepresentedObject):
    InFeed = InFeedRepresentation
    def __init__(self, rep=None, user=None, time=None, content=None):
        self.user = user
        self.time = time
        self.content = content
        super().__init__(rep)

    def __eq__(self, otherPost):
        return self.user == otherPost.user and self.time == otherPost.time and self.content == otherPost.content

class PollPost(Post):
    PostInFeed = PollPostRepresentation
    def __init__(self, rep=None, user=None, time=None, content=None, poll=None):
        self.poll = poll
        super().__init__(rep=rep, user=user, time=time, content=content)

    def __eq__(self, otherPost):
        return super() == otherPost and self.poll == otherPost.poll


if __name__ == "__main__":
    user = User(name="Michelle Saavedra")
    posterUser = User(name="Garrett Baca")
    poll = Poll(votes=dict({"Patrick": ["Michelle", "Richard"]}), poster=posterUser)
    pollPost = PollPost(user=user, time=333352352, content="Some facebook post content", poll=poll)
    print(encode(pollPost))
Exemple #7
0
from pony.orm import db_session
from app import db
from models.Book import Book, Review
from models.Location import Location
from models.User import User, UserSchema

db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():
    schema = UserSchema()
    lhmurphy = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
        image='https://pbs.twimg.com/profile_images/1095848308361302021/RZrejye3.jpg'
    )
    elle = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
        image='https://media.licdn.com/dms/image/C5603AQHX0omHmh7fWQ/profile-displayphoto-shrink_800_800/0?e=1565222400&v=beta&t=5pP3yPblEgMO-XljaArDpTJJblOqk0dy5L28S3qbWGQ'
    )
    hugo = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
        image='https://media.licdn.com/dms/image/C4E03AQFsE6plNPRwsg/profile-displayphoto-shrink_800_800/0?e=1565222400&v=beta&t=6TGy4Oli2Yc5LRLDCPKuuk850vNQiEUnyVW-g08ocjc'
    )

    amsterdam = Location(name='Amsterdam')
Exemple #8
0
from db.JSONProvider import JSONProvider
from models.User import User
from models.Hotel import Hotel
from models.Route import Route
from models.Waybill import Waybill

jsonP = JSONProvider('', 'test.json')

u1 = User('Иванович', 'Иван', 'Иванов', 'г. Москва, ул. Ленина, д 123, кв 10',
          '9169761398', '1')
u2 = User('Поручникова', 'Юлия', 'Владимировна',
          'г. Санкт-Петербург, ул. Маркса, д 24, кв 30', '9057525924', '2')
u3 = User('Жирнов', 'Евгений', 'Борисович',
          'г. Томск, ул. Октябрьская, д 7, кв 17', '9169284356', '3')
jsonP.appendItem('User', u1)
jsonP.appendItem('User', u2)
jsonP.appendItem('User', u3)

h1 = Hotel('Сокол', 6300, 'Россия, Крым', '4')
h2 = Hotel('Саванна', 7000, 'США, Джорджия', '5')
h3 = Hotel('Джунгли', 5600, 'Индия, Нью-Дели', '6')
jsonP.appendItem('Hotel', h1)
jsonP.appendItem('Hotel', h2)
jsonP.appendItem('Hotel', h3)

r1 = Route('Жаркий Крым', 2, 'Умеренно-континентальный', h1, '7')
r2 = Route('Дикая Саванна', 4, 'Субэкваториальный', h2, '8')
r3 = Route('Индийские джунгли', 1, 'Субтропический', h3, '9')
r4 = Route('Русское Чёрное море', 4, 'Умеренно-континентальный', h1, '10')
jsonP.appendItem('Route', r1)
jsonP.appendItem('Route', r2)
Exemple #9
0
def get_poll_obj(d):
    votes = dict()
    for k, v in d.items():
        votes[k] = [User(name=n) for n in v]
    return Poll(votes=votes)
Exemple #10
0
# -*- coding: utf-8 -*-
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler

from models.User import User
from models.Request import Request
from models.Product import Product


class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2', )


users = [
    User(0, 'Rafael Cruz', 'rafael', '123', 100.00),
    User(1, 'Bruno', 'bruno', '456', 50.00),
    User(2, 'Atendente 01', 'atendente', '111', 0)
]

menu = [Product(0, 'Pão', 10), Product(1, 'Vinho', 20)]

requests = []

# Create server
with SimpleXMLRPCServer(('localhost', 8000),
                        requestHandler=RequestHandler) as server:
    server.register_introspection_functions()

    def login(username, password):
        for user in users:
            if username == user.username and password == user.password:
Exemple #11
0
def addUser():
    jdata = request.get_json()
    user = User(**jdata)
    id = userService.addUser(user)
    return Response(json.dumps(id), status=200, content_type="application/json")
Exemple #12
0
 def login(self):
     username = self.__user.get_username()
     password = self.__user.get_password()
     user = User()
     result = user.get({"username": username, "password": password})
     return result.__len__() > 0
Exemple #13
0
def seed_db():
    from models.Album import Album
    from models.Artist import Artist
    from models.User import User
    from models.Track import Track
    from models.Playlist import Playlist
    from models.SeasonalD import SeasonalD
    from models.Album_Artist_Association import album_artist_association_table as aaat
    from models.User_Playlist_Association import user_playlist_association_table as upat

    from main import bcrypt
    from faker import Faker
    import random
    faker = Faker()

    #Initial Setup
    users = []

    art_alb_association_pairs = []
    alb_tra_association_pairs = []
    tra_pla_association_pairs = []
    usr_pla_association_pairs = []

    count_art_alb = [0] * 10
    count_alb_art = [0] * 10

    count_alb_tra = [0] * 10
    count_tra_alb = [0] * 10

    count_tra_pla = [0] * 10
    count_pla_tra = [0] * 10

    count_pla_usr = [0] * 10
    count_usr_pla = [0] * 10

    #Association Lists SETUP + Counts
    for i in range(1, 11):

        usr_int = random.randint(1, 10)
        pla_int = random.randint(1, 10)
        art_int = random.randint(1, 10)
        alb_int = random.randint(1, 10)
        tra_int = random.randint(1, 10)

        #Append Association List - Albums and Artists - don't enter duplicates
        while (art_int, alb_int) in art_alb_association_pairs:
            art_int = random.randint(1, 10)
            alb_int = random.randint(1, 10)

        #Append Association List - Users and Playlists - don't enter duplicates
        while (usr_int, pla_int) in usr_pla_association_pairs:
            usr_int = random.randint(1, 10)
            pla_int = random.randint(1, 10)

        #Add count both directions
        count_usr_pla[usr_int - 1] += 1
        count_pla_usr[pla_int - 1] += 1

        count_art_alb[art_int - 1] += 1
        count_alb_art[alb_int - 1] += 1

        art_alb_association_pairs.append((art_int, alb_int))
        usr_pla_association_pairs.append((usr_int, pla_int))

    #Seasonal Discounts
    for i in range(1, 5):
        seasonald = SeasonalD()
        seasonsname = {1: "Summer", 2: "Autumn", 3: "Spring", 4: "Winter"}

        seasonsfloat = {1: 15.0, 2: 20.0, 3: 25.0, 4: 30.0}

        seasonald.seasonald_title = seasonsname[i]
        seasonald.seasonald_offer = seasonsfloat[i]
        db.session.add(seasonald)
    db.session.commit()

    #Users/Playlists
    for i in range(1, 11):
        user = User()
        playlist = Playlist()

        playlist.playlist_title = faker.unique.catch_phrase()

        user.email = f"test{i}@test.com"
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        user.seasonal_offer = faker.random_int(min=1, max=4)

        db.session.add(user)
        db.session.add(playlist)
        users.append(user)

    db.session.commit()

    #Tracks
    for i in range(1, 11):
        track = Track()
        track.track_title = faker.unique.catch_phrase()
        track.track_duration = faker.random_int(min=120, max=480)
        db.session.add(track)

    db.session.commit()

    #for i in enumerate(SeasonalD().id):
    # seasonald = SeasonalD()
    #  seasonald.seasonald_title = seasonsname[seasonald.id]
    #  seasonald.seasonald_offer = seasonsfloat[seasonald.id]
    #  db.session.commit()

    #playlist = db.session.query(Playlist).filter(Playlist.id==i+1).one()
    #Seasonal Discounts Update!
    #seasonald.seasonald_title = seasonsname[seasonald.id]
    #seasonald.seasonald_offer = seasonsfloat[seasonald.id]
    #db.session.commit()

    #Seasonal Discounts Update!
    #seasonald.seasonald_title = seasonsname[seasonald.id]
    #seasonald.seasonald_offer = seasonsfloat[seasonald.id]
    #db.session.commit()

    #Artists/Albums
    for i in range(1, 11):
        artist = Artist()
        album = Album()
        artist.user_id = random.choice(users).id
        artist.artist_name = faker.unique.name()
        album.album_title = faker.unique.catch_phrase()

        db.session.add(artist)
        db.session.add(album)

    db.session.commit()

    #FINAL COUNTS
    #Count Artist's Albums
    print(f'art_count: {count_art_alb}')
    for i, val in enumerate(count_art_alb):
        print(f'ind: {i} val: {val}')
        artist = db.session.query(Artist).filter(Artist.id == i + 1).one()
        artist.artist_s_albums_count = val
        db.session.commit()

    #Count Album's Artists
    print(f'alb_count: {count_alb_art}')
    for i, val in enumerate(count_alb_art):
        print(f'ind: {i} val: {val}')
        album = db.session.query(Album).filter(Album.id == i + 1).one()
        album.album_s_artists_count = val
        db.session.commit()

    #Count Album's Tracks
    print(f'pla_count: {count_pla_usr}')
    for i, val in enumerate(count_pla_usr):
        print(f'ind: {i} val: {val}')
        playlist = db.session.query(Playlist).filter(Playlist.id == i +
                                                     1).one()
        playlist.playlist_s_users_count = val
        db.session.commit()

    #Count User's playlists
    print(f'usr_count: {count_usr_pla}')
    for i, val in enumerate(count_usr_pla):
        print(f'ind: {i} val: {val}')
        user = db.session.query(User).filter(User.id == i + 1).one()
        user.user_s_playlists_count = val
        db.session.commit()

    #Count Playlist's Users
    print(f'pla_count: {count_pla_usr}')
    for i, val in enumerate(count_pla_usr):
        print(f'ind: {i} val: {val}')
        playlist = db.session.query(Playlist).filter(Playlist.id == i +
                                                     1).one()
        playlist.playlist_s_users_count = val
        db.session.commit()

    #create association tables
    db.session.execute(aaat.insert().values(art_alb_association_pairs))
    db.session.execute(upat.insert().values(usr_pla_association_pairs))
    db.session.commit()

    print("Tables seeded")
Exemple #14
0
from pony.orm import db_session
from app import db
from models.Product import Product
from models.Category import Category
from models.User import User, UserSchema

db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():
    schema = UserSchema()
    valeriux = User(username='******',
                    email='*****@*****.**',
                    password_hash=schema.generate_hash('pass'))

    schema = UserSchema()
    doris = User(username='******',
                 email='*****@*****.**',
                 password_hash=schema.generate_hash('pass'))

    Body_Care = Category(name='Body Care')
    Bath = Category(name='Bath')
    Hair_Care = Category(name='Hair Care')
    Hand_Feet = Category(name='Hair and Feet')

    Product(
        name='Acai Beautifying Dry Oil',
        images=[
            'https://www.naturabrasil.fr/product/image/large/50172170_1.jpg',
            'https://www.naturabrasil.fr/product/image/medium/50172119-huile-seche-ekos-castanha.jpg',
            'https://res.cloudinary.com/feelunique-com/image/upload/f_auto,t_product_listing/v1/live/product/main-image/79304/fchtpv1deft6vcazrlme.jpg'
Exemple #15
0
from pony.orm import db_session
from app import db
from models.Pool import Pool, PoolSchema, Comment, CommentSchema
from models.User import User, UserSchema

db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():
    schema = UserSchema()
    emma = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
        image=
        'https://pbs.twimg.com/profile_images/639532874740404225/EJlcwETM_400x400.jpg'
    )

    amy = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
        image=
        'https://pbs.twimg.com/profile_images/726724811293085696/cyQw1WFQ_400x400.jpg'
    )

    george = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
        image=
Exemple #16
0
from pony.orm import db_session
from app import db
from models.User import User, UserSchema
from models.Landmark import Landmark
from models.Story import Story

# We delete all tables in our database
db.drop_all_tables(with_all_data=True)
db.create_tables() # We create tables in our database


with db_session():
    schema = UserSchema()
    alikurtulus = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('sda')
    )

    Story(
     cityname='Lisbon',
     title='Lisbon was great holiday',
     user=alikurtulus,
     description="Lisbon is, in my opinion, one of the best cities to spend a weekend and a perfect place to experience one of Europe’s smaller capitals – but don’t let the word ‘smaller’ fool you! Lisbon packs a hefty punch with great places to see, eat and places to totally ‘let your hair down’…",
     date='12.08.2018',
     image='https://handluggageonly.co.uk/wp-content/uploads/2015/09/DSC02292.jpg'
    )
    Story(
     cityname='Madrid',
     title='Madrid was dream holiday',
     user=alikurtulus,
Exemple #17
0
from pony.orm import db_session
from app import db
from models.Event import Event
from models.Format import Format
from models.User import User, UserSchema


db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():
    schema = UserSchema()
    sensei = User(
        username='******',
        image='https://i.imgur.com/w7qm5UP.png',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pineapples')
    )


    five_a_side = Format(name='5-a-side')
    seven_a_side = Format(name='7-a-side')


    Event(
        name='Planet Futsal',
        image='https://i.imgur.com/jWd3gQb.jpg',
        venue='38 IBM Haruna St, Utako, Abuja',
        user=sensei,
        format=five_a_side,
        latitude=9.062720,
Exemple #18
0
from pony.orm import db_session
from app import db
from models.Trip import Trip
from models.Location import Location
from models.User import User, UserSchema

db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():
    #User
    schema = UserSchema()
    Kristian = User(username='******',
                    email='*****@*****.**',
                    password_hash=schema.generate_hash('pass'))

    # Trips
    trip_one = Trip(name="Trip One", user=Kristian)
    trip_two = Trip(name="Trip Two", user=Kristian)

    # Locations - Trip One
    location_one = Location(name="Clapham Junction",
                            postcode="SW111PW",
                            latitude=51.4652,
                            longitude=-0.1708,
                            trip=trip_one)
    location_two = Location(name="Vauxhall",
                            postcode="SW84ET",
                            latitude=51.4862,
                            longitude=-0.1229,
                            trip=trip_one)
Exemple #19
0
from pony.orm import db_session
from datetime import date

db.drop_all_tables(with_all_data=True)
db.create_tables()

avatar_1 = 'https://i.imgur.com/vjvpOox.jpg'
avatar_2 = 'https://i.imgur.com/iwYxNbB.jpg'
avatar_3 = 'https://i.imgur.com/GkO3ix0.jpg'
avatar_4 = 'https://i.imgur.com/p25szCt.jpg'
with db_session():

    schema = UserSchema()
    gabe = User(username='******',
                email='*****@*****.**',
                password_hash=schema.generate_hash('pass'),
                concession=True,
                avatar=avatar_1)
    violeta = User(username='******',
                   email='*****@*****.**',
                   password_hash=schema.generate_hash('pass'),
                   concession=False,
                   avatar=avatar_2)
    ade = User(username='******',
               email='*****@*****.**',
               password_hash=schema.generate_hash('pass'),
               concession=True,
               avatar=avatar_3)
    aiman = User(username='******',
                 email='*****@*****.**',
                 password_hash=schema.generate_hash('pass'),
Exemple #20
0
from pony.orm import db_session
from app import db
from models.User import User, UserSchema

db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():
    schema = UserSchema()
    elle = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
        own_postcode='se270rs',
        friend_postcode='se270rs',
        closest_station='West Norwood'
    )

    db.commit()
Exemple #21
0
    def search(self, analysisResult=AnalysisResult(), pageSize=10, offset=0):
        """
        (AnalysisResult, pageSize, offset) -> [AnalysisResult]
        search by analysisResult
        """
        session = self.session_factory()
        query = session.query(AnalysisResultDB).filter(
            or_(AnalysisResultDB.idAnalysis == analysisResult.analysis.id,
                AnalysisResultDB.idDisease == analysisResult.disease.id,
                AnalysisResultDB.score == analysisResult.score,
                AnalysisResultDB.frame == analysisResult.frame))
        content = query.slice(offset, pageSize).all()
        total = query.count()
        analysisResults = []
        for analysisResultDB in content:
            analysisResults.append(
                AnalysisResult(
                    analysisResultDB.id,
                    Analysis(
                        analysisResultDB.analysis.id,
                        Image(
                            analysisResultDB.analysis.image.id,
                            Disease(
                                analysisResultDB.analysis.image.disease.id,
                                Plant(
                                    analysisResultDB.analysis.image.disease.
                                    plant.id, analysisResultDB.analysis.image.
                                    disease.plant.scientificName,
                                    analysisResultDB.analysis.image.disease.
                                    plant.commonName), analysisResultDB.
                                analysis.image.disease.scientificName,
                                analysisResultDB.analysis.image.disease.
                                commonName),
                            analysisResultDB.analysis.image.url,
                            analysisResultDB.analysis.image.description,
                            analysisResultDB.analysis.image.source,
                            analysisResultDB.analysis.image.size),
                        Classifier(
                            analysisResultDB.analysis.classifier.id,
                            Plant(
                                analysisResultDB.analysis.classifier.plant.id,
                                analysisResultDB.analysis.classifier.plant.
                                scientificName, analysisResultDB.analysis.
                                classifier.plant.commonName),
                            analysisResultDB.analysis.classifier.tag,
                            analysisResultDB.analysis.classifier.path),
                        user=User(
                            id=analysisResultDB.analysis.user.id,
                            idType=analysisResultDB.analysis.user.idType,
                            email=analysisResultDB.analysis.user.email,
                            username=analysisResultDB.analysis.user.username)),
                    Disease(
                        analysisResultDB.disease.id,
                        Plant(analysisResultDB.disease.plant.id,
                              analysisResultDB.disease.plant.scientificName,
                              analysisResultDB.disease.plant.commonName),
                        analysisResultDB.disease.scientificName,
                        analysisResultDB.disease.commonName),
                    analysisResultDB.score, analysisResultDB.frame))

        return {'total': total, 'content': analysisResults}
Exemple #22
0
    description=
    u"Gain access to the internal New York Federal Reserve banking system, allowing you to transfer funds to/from accounts.",
)
dbsession.add(item)
dbsession.flush()

item = MarketItem(
    name=u"SWAT",
    price=3000,
    image=u"swat.png",
    description=
    u"Gain access to the internal police computer system, allowing you to insert fraudlent arrest warrents for other players.",
)
dbsession.add(item)
dbsession.flush()

# Game Levels
game_level = GameLevel(number=0, buyout=0)
dbsession.add(game_level)
dbsession.flush()

# Admin User Account
admin_user = User(handle=admin_handle)
admin_user.password = password
dbsession.add(admin_user)
dbsession.flush()

admin_permission = Permission(name=ADMIN_PERMISSION, user_id=admin_user.id)
dbsession.add(admin_permission)
dbsession.commit()
    def post(self):
        # get the staff details from the request sent by the client
        user_details = user_parser.parse_args()
        # check if the staff exists before registering them
        user_db_row = User.get_user_by_email(user_details['email'])
        if user_db_row:
            err_msg = f"{user_details['first_name']} {user_details['last_name']} already exists"
            response_msg = helper.make_rest_fail_response(err_msg)
            return make_response(response_msg, 409)

        # create user account
        user_uuid = uuid.uuid4()
        # Create temporary seven digit password
        temporary_pass = helper.create_user_password()
        new_user = User(user_uuid, user_details['email'], temporary_pass)
        new_user.save()

        # create user profile
        new_user_profile = UserProfile(new_user.id, user_details['first_name'],
                                       user_details['last_name'],
                                       user_details['phone'])
        new_user_profile.save()

        # get organization details from JWT, such as the role of the client enrolling the staff, and their UID
        uid = get_jwt_identity()

        # get user role
        claims = get_jwt_claims()
        role = claims['role']

        # role = 'BR'

        # get agency_id
        agency_id = staff_handler.get_agency_id(role, uid)

        # Add staff to the appropriate table: i.e BRStaff, TRStaff, IAStaff
        # We also assign the staff roles at this stage,
        # depending on the entities they operate under, i.e BRSTF, IASTF, TASTF
        self.add_staff(role, agency_id, new_user.id)

        # store staff permissions
        self.set_permissions(user_details['permissions'], new_user.id)

        # send email to with the activation details for the staff
        # Temporary password email
        email_template = helper.generate_temporary_password_template(
            application.config['LOGIN_ENDPOINT'], temporary_pass)
        subject = "Nexure Temporary Password"
        email_text = f"Follow {application.config['LOGIN_ENDPOINT']} to login and use {temporary_pass} as your temporary password"
        helper.send_email(user_details['email'], subject, email_template,
                          email_text)

        #  Generate a user account activation email
        confirmation_code = token_handler.user_account_confirmation_token(
            new_user.id)
        email_template = helper.generate_confirmation_template(
            application.config['CONFIRMATION_ENDPOINT'], confirmation_code)
        subject = "Please confirm your account"
        email_text = f"Use this link {application.config['CONFIRMATION_ENDPOINT']}/{confirmation_code}" \
                     f" to confirm your account"
        helper.send_email(user_details['email'], subject, email_template,
                          email_text)
        response = helper.make_rest_success_response(
            "Registration successful. Please check the staff email to activate your account."
        )
        return make_response(response, 200)
Exemple #24
0
from pony.orm import db_session
from app import db
from models.User import User, UserSchema
from models.Programme import Programme
from models.Exercise import Exercise
from models.ExerciseItem import ExerciseItem

db.drop_all_tables(with_all_data=True)
db.create_tables()

with db_session():

    schema = UserSchema()
    #seed user •••••••••••••••••••••••••••••••••••••••••••••••••••••••
    adam_p = User(name='adampond',
                  email='*****@*****.**',
                  password_hash=schema.generate_hash('pass'))

    poser_pete = User(name="Poser Pete",
                      email="*****@*****.**",
                      password_hash=schema.generate_hash('pass'))
    #seed exercises •••••••••••••••••••••••••••••••••••••••••••••••••••••••

    #arms
    bicep_curl = Exercise(name="Bicep Curl")
    tricep_pushdown = Exercise(name="Tricep Pushdown")

    #chest
    barbell_bench_press = Exercise(name="Barbell Bench Press")
    dumbbell_fly = Exercise(name="Dumbbell Fly")
Exemple #25
0
 def post(self):
     # data = parser.parse_args()
     data = request.data
     user_data = json.loads(data).get('user')
     new_user = User(**user_data)
     return new_user, 201
        if check_password(args.password, hashed):
            if args.new_pass is not None:
                if len(args.new_pass) >= 8:
                    user.set_password(args.new_pass)
                    print("Password changed")
                else:
                    print("Password too short")
            else:
                print("No new password entered")
        else:
            print("Wrong password")

    elif User.load_user_by_email(cur, args.username):
        print("User with this email exist")

    elif User.load_user_by_email(cur, args.username) is None:
        if len(args.password) >= 8:
            new_user = User()
            new_user.email = args.username
            new_user.username = args.username
            new_user.set_password(args.password)
            new_user.save_to_db(cur)
            print("You created new user with mail: ", new_user.email)
        else:
            print("Password is too short")

    else:
        print("I really don't know how did you get here")
else:
    parser.print_help()
Exemple #27
0
def initdb():
    db.create_all()
    db.session.add(User(username = "******", password = "******"))
    db.session.add(User(username = "******", password = "******"))
    db.session.commit()
    print("Initialized the database")
Exemple #28
0
def seed_db():
    from models.User import User
    from models.Profile import Profile
    from faker import Faker
    from main import bcrypt
    from models.Equipment import Equipment
    from models.EquipmentOrder import EquipmentOrder
    import random
    from random import seed
    from random import randint

    faker = Faker()
    profiles = []
    equipments = []

    categories = ["dumbells", "cardio", "machine", "yoga", "mobility"]

    for i in range(10):
        user = User()
        user.email = f"test{i}@test.com"
        user.password = bcrypt.generate_password_hash("123456").decode("utf-8")
        db.session.add(user)

    db.session.commit()

    for i in range(10):
        profile = Profile()
        profile.username = faker.name()
        profile.fname = faker.first_name()
        profile.lname = faker.last_name()
        profile.account_active = faker.boolean()
        profile.user_id = i + 1
        profiles.append(profile)
        db.session.add(profile)

    db.session.commit()

    for i in range(30):
        equipment = Equipment()
        equipment.equipment_name = faker.name()
        equipment.equipment_description = faker.catch_phrase()
        equipment.rented = random.choice([True, False])
        equipment.rentpw = randint(8, 120)
        equipment.owner_id = random.choice(profiles).profileid
        equipment.category = random.choice(categories)
        equipments.append(equipment)
        db.session.add(equipment)

    for i in range(30):
        equipment_order = EquipmentOrder()
        equipment_order.order_begin_date = faker.date_between(start_date='-1y',
                                                              end_date='today')
        equipment_order.order_return_date_estimate = faker.date_between(
            start_date='today', end_date='+1y')
        equipment_order.order_actual_return_date = faker.date_between(
            start_date='today', end_date='+1y')
        equipment_order.order_active = random.choice([True, False])
        equipment_order.equipment_id = randint(1, 29)
        # equipment_order.equipment_id = random.choice(equipments).id
        equipment_order.hirer_id = random.choice(profiles).profileid
        db.session.add(equipment_order)

    db.session.commit()
    print("Tables seeded")
Exemple #29
0
with db_session():

    schema = UserSchema()
    animation = Medium(name='Animation')
    music = Medium(name='Music')
    application = Medium(name='Application')
    illustration = Medium(name='Illustration')

    Hiro = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
        lookingforwork=True,
        photo=
        "https://66.media.tumblr.com/73d02ec8972950c826286b1b131c52cd/tumblr_oxtpvh44kI1w3debko1_1280.png",
        bio=
        """Hiro Protganoist creates media artworks and mixed media artworks. By parodying mass media by exaggerating certain formal aspects inherent to our contemporary society, Protganoist makes works that can be seen as self-portraits. Sometimes they appear idiosyncratic and quirky, at other times, they seem typical by-products of American superabundance and marketing.

    His media artworks often refers to pop and mass culture. Using written and drawn symbols, a world where light-heartedness rules and where rules are undermined is created. By manipulating the viewer to create confusion, he touches various overlapping themes and strategies. Several reoccurring subject matter can be recognised, such as the relation with popular culture and media, working with repetition, provocation and the investigation of the process of expectations.

    His works are saturated with obviousness, mental inertia, clichés and bad jokes. They question the coerciveness that is derived from the more profound meaning and the superficial aesthetic appearance of an image. By using popular themes such as sexuality, family structure and violence, he often creates several practically identical works, upon which thoughts that have apparently just been developed are manifested: notes are made and then crossed out again, ‘mistakes’ are repeated.

    His works are on the one hand touchingly beautiful, on the other hand painfully attractive. Again and again, the artist leaves us orphaned with a mix of conflicting feelings and thoughts."""
    )

    Molly = User(
        username='******',
        email='*****@*****.**',
        password_hash=schema.generate_hash('pass'),
        lookingforwork=True,
        photo="http://i.imgur.com/oU6Vc.jpg",
        bio=
Exemple #30
0
def init_default_content(p1, p2):
    user = db.session.query(User).filter(
        User.email == "*****@*****.**").first()
    user2 = db.session.query(User).filter(
        User.email == "*****@*****.**").first()
    if user is None and user2 is None:
        user = User(email="*****@*****.**",
                    password=p1,
                    first_name="user1",
                    last_name="beta",
                    birthday="2019-09-05")
        user2 = User(email="*****@*****.**",
                     password=p2,
                     first_name="user2",
                     last_name="beta",
                     birthday="2019-09-05")
        circle = Circle("Cercle Beta 1")
        db.session.commit()
        UserToCircle(user=user, circle=circle, privilege="ADMIN")
        UserToCircle(user=user2, circle=circle)
        db.session.commit()
        device = db.session.query(Device).filter(
            Device.username == "device1").first()
        if device is None:
            device = Device(name="Device beta 1")
            device.circle = circle
            device.username = "******"
            device.set_password("test")
            device.activate(device.key)
            db.session.commit()
        if len(circle.conversations) == 0:
            conversation = Conversation(device_access=True,
                                        name="Conversation avec device",
                                        circle=circle)
            conversation2 = Conversation(device_access=False,
                                         name="Conversation sans device",
                                         circle=circle)
            db.session.commit()
            if len(user.conversation_links) == 0:
                cl1 = UserToConversation(privilege="ADMIN",
                                         user=user,
                                         conversation=conversation)
                cl2 = UserToConversation(user=user2, conversation=conversation)
                db.session.commit()
                Message(content="Message conversation avec device from user1",
                        link=cl1,
                        conversation=conversation)
                Message(content="Message conversation avec device from user2",
                        link=cl2,
                        conversation=conversation)
                message3 = Message(
                    content="Message conversation avec device from device",
                    is_user=False,
                    conversation=conversation)
                message3.device = device
                db.session.commit()
            if len(user2.conversation_links) == 0:
                cl3 = UserToConversation(privilege="ADMIN",
                                         user=user,
                                         conversation=conversation2)
                cl4 = UserToConversation(user=user2,
                                         conversation=conversation2)
                db.session.commit()
                Message(content="Message conversation sans device from user1",
                        link=cl3,
                        conversation=conversation2)
                Message(content="Message conversation sans device from user2",
                        link=cl4,
                        conversation=conversation2)
        db.session.commit()