Example #1
0
def setup_server(server):
    server.users = [User('u1'), User('u2'), User('u3')]
    conn1 = Connection('uuid1', None)
    conn2 = Connection('uuid2', None)
    conn3 = Connection('uuid3', None)

    server.users[0].login(conn1)
    server.users[1].login(conn2)
    server.users[2].login(conn3)
    server.connections = [conn1, conn2, conn3]
Example #2
0
 def login(request, response, duration):
     """ Login page """
     User.init()
     if Sessions.check(request.getCookie(b"session")) == False:
         if User.check(request.params.get(b"loginuser", b""),
                       request.params.get(b"loginpassword", b"")):
             response.setCookie(b"session", Sessions.create(duration),
                                duration)
         else:
             return PasswordPage.loginPage(
                 None if request.params.get(b"loginpassword", None) ==
                 None else b"Wrong user or password")
     return None
Example #3
0
    def create(self):
        name_file = "/Users/yveslym/Desktop/portfolio/MOB2/trip-planner/name.txt"
        domain_file = "/Users/yveslym/Desktop/portfolio/MOB2/trip-planner/domain.txt"
        country_file = "/Users/yveslym/Desktop/portfolio/MOB2/trip-planner/country.txt"

        open_country_file = open(country_file).read().split()
        open_name_file = open(name_file).read().split()
        open_domain_file = open(domain_file).read().split()

        country = open_country_file[random.randint(0,
                                                   len(open_country_file) - 1)]
        fname = open_name_file[random.randint(0, len(open_name_file) - 1)]
        lname = open_name_file[random.randint(0, len(open_name_file) - 1)]
        domain_name = open_domain_file[random.randint(
            0,
            len(open_domain_file) - 1)]

        uname = fname + lname
        mail = fname + '.' + lname + '@' + domain_name

        user = User()
        user.first_name = fname
        user.last_name = lname
        user.email = mail
        user.country = country
        user.password = '******'
        user.username = uname
        return (user)
Example #4
0
    def test_assosiations(self):
        u1 = User(username="******", email='*****@*****.**')
        db.session.add(u1)
        db.session.commit()
        self.assertEqual(u1.username, "testaaja")

        i1 = Ingredient(name="testiaines1", amount=200, unit="g")
        db.session.add(i1)
        db.session.commit()
        self.assertEqual(i1.name, "testiaines1")
        self.assertEqual(i1.amount, 200)
        self.assertEqual(i1.unit, "g")

        recipe = Recipe(name="testiresepti1", user_id=u1.id)
        db.session.add(recipe)
        db.session.commit()
        self.assertEqual(recipe.name, "testiresepti1")

        test_recipe = Recipe.query.get(1)
        ingredient = Ingredient.query.get(1)
        test_recipe.ingredients.append(ingredient)
        db.session.commit()
        print(str(test_recipe.ingredients[0]))

        print(str(ingredient.recipe[0]))
Example #5
0
	async def USER(self):
		""" Ftp command USER """
		if User.getUser() == b"":
			await self.sendResponse(230, b"User Logged In.")
		else:
			self.user = self.path[1:]
			await self.sendResponse(331, b"User known, enter password")
Example #6
0
	async def PASS(self):
		""" Ftp command PASS """
		self.password = self.path[1:]
		if User.check(self.user, self.password):
			await self.sendResponse(230, b"Logged in.")
		else:
			await self.sendResponse(430, b"Invalid username or password")
Example #7
0
 def change(request, response):
     """ Change the password page """
     User.init()
     newPassword = request.params.get(b"newpassword", None)
     if newPassword != None:
         res = User.change(request.params.get(b"user", b""),
                           request.params.get(b"currentpassword", b""),
                           request.params.get(b"newpassword"),
                           request.params.get(b"renewpassword"))
         if res == True:
             return [Br(), AlertSuccess(text=b"Password changed")]
         elif res == None:
             return PasswordPage.changePage(alert=b"Passwords not equals")
         else:
             return PasswordPage.changePage(alert=b"Wrong user or password")
     else:
         return PasswordPage.changePage()
Example #8
0
def fill_database(clients, predictions):
    '''
    fill the database that Flask will use.
    '''
    for i, client in enumerate(clients):
        user = User(id=client, clv=predictions[i])
        db.session.add(user)
    db.session.commit()
Example #9
0
def new_user():
    json_data = request.get_json()

    if not json_data.has_key('params') or len(json_data.get('params')) == 0:
        return jsonify({"jsonrpc": "2.0", "result": False, "error": 'incorrect parameters'}), 400

    params = request.json.get('params')

    active = True
    new_user = True
    password = datetime.now().strftime('%Y%m%d%H%M%S')

    if params.has_key('email') and len(params['email']) != 0:
        email = params['email']
    else:
        email = None

    if params.has_key('last_name') and len(params['last_name']) != 0:
        last_name = params['last_name']
    else:
        last_name = None

    if params.has_key('first_name') and len(params['first_name']) != 0:
        first_name = params['first_name']
    else:
        first_name = None

    if params.has_key('display_name') and len(params['display_name']) != 0:
        display_name = params['display_name']
    else:
        display_name = None

    if email is None or len(email) < 5:
        return jsonify({"jsonrpc": "2.0", "result": False, "error": 'Email no cumple'}), 400
    lower_user_mail = email.lower()
    if User.query.filter_by(email=lower_user_mail).first() is not None:
        return jsonify({"jsonrpc": "2.0", "result": False, "error": 'Ya existe este usuario'}), 400
    new_user_db = User(email, password, display_name, first_name, last_name, active, new_user)

    new_user_db.add_role(Role.get_by_name('candidate'))
    db.session.add(new_user_db)
    db.session.commit()
    return jsonify({"jsonrpc": "2.0", "result": True, "id": new_user_db.id}), 201
Example #10
0
def get_user(user_id):
    if user_id not in users:
        controller = Controller()
        info = controller.get_user(user_id)
        enrolments = [t[0] for t in controller.get_enrolments(user_id)]
        if len(info) == 0:
            return None
        user = User(user_id, info[0][0], info[0][1], enrolments)
        users[user_id] = user
        return user
    else:
        return users[user_id]
Example #11
0
	def getlogin(self, b=None):
		result = b
		if self.state == 0:
			self.socket.write(b"%s\r\nTelnet connected to %s\r\n%s\r\n"%(b"*"*30, useful.tobytes(sys.platform), b"*"*30))
			if User.isEmpty():
				self.state = 3
			else:
				self.socket.write(b"Username:"******"\r\nPassword:"******""
					self.login = b""
					self.socket.write(b" Logging success\r\n%s\r\n"%(b"*"*30))
				else:
					self.state = 1
					self.socket.write(b" Logging failed\r\n\r\nUsername:"******""
					self.login = b""
			elif b[0] == 0x7F:
				if len(self.password) >= 1:
					self.password = self.password[:-1]
			else:
				self.password += bytes([b[0]])
		return result
Example #12
0
    def changePage(alert=None):
        """ Change the password page """
        if User.isEmpty():
            part = [
                Edit(text=b"Create user name", name=b"user"),
            ]
        else:
            part = [\
             Edit(text=b"Enter user name",          name=b"user"),
             Edit(text=b"Current password",   type=b"password", name=b"currentpassword")]

        part += [\
         Edit(text=b"New password",     type=b"password", name=b"newpassword"),
         Edit(text=b"Repeat new password",     type=b"password", name=b"renewpassword")]

        return PasswordPage.getDialog(part, b"Change password", alert)
Example #13
0
	async def treatCommand(self):
		""" Treat ftp command """
		if self.quit == False:
			try:
				command = useful.tostrings(self.command)
				if hasattr(self, command):
					callback = getattr(self, command)
					
					if not self.command in [b"USER",b"PASS"]:
						if User.check(self.user, self.password):
							await callback()
						else:
							await self.sendResponse(430, b"Invalid username or password")
					else:
						await callback() 
				else:
					await self.unsupportedCommand()
			except Exception as err:
				await self.sendError(err)
Example #14
0
 def test_get_password(self):
     user = User(password='******')
     with self.assertRaises(AttributeError):
         user.password
Example #15
0
 def test_verify_password(self):
     user = User(password='******')
     self.assertTrue(user.verify_password('123'))
     self.assertFalse(user.verify_password('321'))
Example #16
0
def addUser(userId, userName, userAge):
    user = User(userId, userName, userAge)
    db.session.add(user)
    db.session.commit()
Example #17
0
if sys.argv[1] == 'userconfirmed':
    users = User.query.filter_by(confirmed=True)
    for user in users:
        print(user.id, user.nama, user.email, user.registered_date, user.token)

if sys.argv[1] == 'addadmin':
    username = "******"
    email = "admin"
    password = "******"

    if username and email and password:
        user = User(nama=username,
                    email=email,
                    alamat="WEW",
                    sekolah="",
                    jenis_kelamin="1",
                    kategori="",
                    kab_kota="",
                    provinsi="",
                    password=password,
                    role='admin')

        user.confirm_user()
        user.generate_token()
        db.session.add(user)
        db.session.commit()
        print('admin created!')

if sys.argv[1] == 'listadmin':
    admins = User.query.filter_by(role='admin')
    for admin in admins:
        print(admin.nama, admin.email, admin.password, admin.role)
Example #18
0
 def test_create_user(self):
     user = User()
     self.assertTrue(user is not None)
Example #19
0
from server import User, db

db.drop_all()
db.create_all()

admin = User(username='******')
guest = User(username='******')

db.session.add(admin)
db.session.add(guest)
db.session.commit()

print User.query.all()
    salary=5.00,
    image_path="sweep_garage",
    status="not-completed")

roll_over = Chore(title="Roll Over",
                  description="Do a barrel roll!",
                  salary=100.00,
                  image_path="roll_over",
                  status="not-completed")

# Create child objects
maggie = User(username="******",
              password="******",
              is_child=1,
              user_stage=2,
              full_name="Maggie Simpson",
              children=[],
              chores=[
                  mow_lawn, empty_dishwasher, roll_over, vacuum_family_room,
                  clean_bathrooms, take_dog_for_walk, get_an_A, sweep_garage
              ])
lisa = User(username="******",
            password="******",
            is_child=1,
            user_stage=2,
            full_name="Lisa Simpson",
            children=[],
            chores=[
                mow_lawn, empty_dishwasher, roll_over, vacuum_family_room,
                clean_bathrooms, take_dog_for_walk, get_an_A, sweep_garage
            ])
bart = User(username="******",
Example #21
0
from server import db, User

db.drop_all()
db.create_all()
db.session.add(
    User(name='admin',
         password=
         b'$2b$10$MuqRlqo2SC97TU3Z6BmBBe7vrs9ARVBBOv3WmfjquY9MXwbyshxfy',
         admin=True))
db.session.add(
    User(
        name='bra',
        password=b'$2b$10$9kmb6L0/J6MxBp8HK2EJ3eE/rgx.HC1pjIvO3YPVZwfn2h1yGslXS'
    ))
db.session.commit()
Example #22
0
from server import db, User, Category, Video
db.drop_all()
db.create_all()
#db.session.add(User(name='admin', password=b'$2b$10$MuqRlqo2SC97TU3Z6BmBBe7vrs9ARVBBOv3WmfjquY9MXwbyshxfy', admin=True, email='*****@*****.**'))
db.session.add(
    User(name='bra',
         password=
         b'$2b$10$9kmb6L0/J6MxBp8HK2EJ3eE/rgx.HC1pjIvO3YPVZwfn2h1yGslXS',
         email='*****@*****.**'))
db.session.commit()
nutrition = Category(name='Nutrition')
psychology = Category(name='Psychology')
video1 = Video(link='https://www.youtube.com/embed/KD-FmeueFUo')
video1.categories.append(nutrition)
video2 = Video(link='https://www.youtube.com/embed/p79D6u-6pN4')
video2.categories.append(nutrition)
video3 = Video(link='https://www.youtube.com/embed/K3ksKkCOgTw')
video3.categories.append(nutrition)
video5 = Video(link='https://www.youtube.com/embed/Or_spxqqtTQ')
video5.categories.append(nutrition)
video6 = Video(link='https://www.youtube.com/embed/fR3NxCR9z2U')
video6.categories.append(nutrition)
video7 = Video(link='https://www.youtube.com/embed/kb146Y1igTQ')
video7.categories.append(nutrition)
video4 = Video(link='https://www.youtube.com/embed/l128tW1H5a8')
video4.categories.append(psychology)
db.session.add(nutrition)
db.session.add(psychology)
db.session.add(video1)
db.session.add(video2)
db.session.add(video3)
def find_user(token, graph_api_user, with_friends=True, retrieved_time=datetime.utcnow(), with_picture=False):
    """Retrieve a User resource from the Graph API.

Args:
   graph_api_user (str): The URL of the user node within the Graph API

Returns:
   dict.  A User resource.
   """

    # Start to explore the Graph
    # user = facebook.get('/' + graph_api_user)
    user = graph_api_get(token, '/' + graph_api_user)

    # Retrieve the admin groups
    # accounts = facebook.get('/' + graph_api_user + '/accounts')
    accounts = graph_api_get(token, '/' + graph_api_user + '/accounts')

    if 'gender' in user.data:
        gender = user.data['gender']
    else:
        gender = None

    # Calculate the age
    if 'birthday' in user.data:
        user.data['age'] = user.data['birthday']
        current_date = datetime.utcnow()

        # If only a month and day are specified, do not attempt to calculate the age of the user
        if re.match(r'\d{2}/\d{2}$', user.data['birthday']):
            age = None
        else:
            birth_date = datetime.strptime( user.data['birthday'], '%m/%d/%Y' )
            age = abs((current_date - birth_date).days / 365)
    else:
        age = None

    # Formatting for the hometown
    if 'hometown' in user.data:
        user.data['hometown_name'] = user.data['hometown']['name']
    else:
        user.data['hometown_name'] = ''

    # Formatting for the location
    if 'location' in user.data:
        user.data['location_name'] = user.data['location']['name']
    else:
        user.data['location_name'] = ''

    admin = is_admin(user.data['id'])

    if with_picture:

        # Picture URL
        # picture = facebook.get('/' + graph_api_user + '/picture?redirect=false&type=large')
        picture = graph_api_get(token, '/' + graph_api_user + '/picture?redirect=false&type=large')
        picture_url = picture.data['data']['url']

        # Download the picture
        h = httplib2.Http()
        (resp_headers, picture_resp) = h.request(picture_url, "GET")

        # os.path.dirname(__file__)
        picture_file = open('tmp/user_picture.jpg', 'wb')
        picture_file.write(picture_resp)
        picture_file.close()
    else:
        picture_url = 'http://facebook.com'

    # Serialize the User
    # Only retrieve the User as its been serialized
    # user_objects = User.objects(facebook_id=user.data['id'])
    user_objects = User.objects(facebook_id=user.data['id'],retrieved_time=retrieved_time)
    if len(user_objects) > 1:
        raise Exception("More than one User serialized for %s" % user_objects.facebook_id)
    elif len(user_objects) < 1:
        user_object = User(facebook_id=user.data['id'],
                           name=user.data['name'],
                           age=age,
                           gender=gender,
                           hometown_name=user.data['hometown_name'],
                           location_name=user.data['location_name'],
                           friends=[],
                           admin=admin,
                           picture_url=picture_url,
                           retrieved_time=retrieved_time
                           )

        if with_picture:
            user_object.picture.put('tmp/user_picture.jpg')

        user_object.save()
    else:
        user_object = user_objects.first()
        user_object.facebook_id = user.data['id']
        user_object.age = age
        user_object.gender = gender
        user_object.hometown_name = user.data['hometown_name']
        user_object.location_name = user.data['location_name']
        user_object.admin=admin
        user_object.picture_url=picture_url

        if with_picture:
            user_object.picture.replace('tmp/user_picture.jpg')

        user_object.save()

    if with_picture:
        os.remove('tmp/user_picture.jpg')

    # Retrieve the friends
    if with_friends:
        friends = find_friends(token, user.data['id'], retrieved_time)
        user_object.friends = friends
        user_object.save()

    return user_object
Example #24
0
 def test_set_password(self):
     user = User(password='******')
     self.assertTrue(user.hashed_pass is not None)
def download():
    """Download an export of Graph API data for any given User

    """

    downloaded_resources = []

    users = []
    posts = []
    friendships = []
    publishings = []
    comments = []

    # Retrieve all shares left for posts by friends
    sharedposts = []
    # Retrieve all users who liked the post by this friend
    likes = []
    # Retrieve all reactions to the post by this friend
    reactions = []

    user = None

    token = get_facebook_oauth_token()
    if token:

        user = facebook.get('/me')
        if not is_admin(user.data['id']):
            return redirect(url_for('index'))

        min_date_str = request.args.get('min_date', None)
        max_date_str = request.args.get('max_date', None)

        # Filter for posts
        if min_date_str is not None and max_date_str is not None:
            min_date_str = re.sub(r'\.\d{3}Z$', '', min_date_str)
            max_date_str = re.sub(r'\.\d{3}Z$', '', max_date_str)

            min_date = datetime.strptime(min_date_str, '%Y-%m-%dT%H:%M:%S')
            max_date = datetime.strptime(max_date_str, '%Y-%m-%dT%H:%M:%S')
        else:
            min_date = datetime(1, 1, 1)
            max_date = datetime.utcnow()

        graph_api_user = request.args.get('user', None)

        if graph_api_user is not None:
            # Start to explore the Graph
            # graph_users = [ find_user(token, graph_api_user, retrieved_time=retrieved_time) ]
            graph_users = User.objects(facebook_id=user.data['id'])

#            graph_users = []
#            for graph_user in User.objects(facebook_id=user.data['id']):
#                graph_users.append(graph_user)
        else:
            # Retrieve serialized User resources
            graph_users = User.objects()

#            graph_users = []
#            for graph_user in User.objects():
#                graph_users.append(graph_user)

        post_users = {}

        for this_user in graph_users:
            if not this_user.facebook_id in downloaded_resources:
                users.append(this_user)
                downloaded_resources.append(this_user.facebook_id)

                # Retrieve the friends
                friends = this_user.friends

                for friend in friends:
                    if not friend.facebook_id in downloaded_resources:

                        # Add the friend as a user
                        users.append(friend)
                        downloaded_resources.append(friend.facebook_id)

                    # Add the friendship
                    friendships.append({'User A ID': this_user.facebook_id, 'User B ID': friend.facebook_id})

                # Retrieve the posts
                # user_posts = find_posts(token, this_user, '/' + str(this_user.facebook_id) + '/feed', min_date, max_date, retrieved_time)
                user_posts = Post.objects(user=this_user)

#                user_posts = []
#                for user_post in Post.objects(user=user):
#                    user_posts.append(user_post)



                for post in user_posts:
                    if not post.facebook_id in downloaded_resources:

                        posts.append(post)
                        downloaded_resources.append(post.facebook_id)

                        if post.user is not None:
                            post_users[post.user.facebook_id] = post.user

                            # Add the publishings
                            publishings.append({ 'User ID': post.user.facebook_id, 'Post ID': post.facebook_id })

                        # Graph API version 2.6 or later required
                        post_comments = find_comments(token, post, min_date, max_date)
                        comments.extend(post_comments)

                        post_sharedposts = find_sharedposts(post, min_date, max_date)

                        # Temporarily concatenate all comments and shares
                        comments.extend(sharedposts)

    else:

        return redirect(url_for('index'))

    workbook = xlsxwriter.Workbook('tmp/socialmemories.xlsx')

    users_worksheet = workbook.add_worksheet('Users')
    posts_worksheet = workbook.add_worksheet('Posts')
    friendships_worksheet = workbook.add_worksheet('Friendships')
    publishings_worksheet = workbook.add_worksheet('Publishings')
    comments_worksheet = workbook.add_worksheet('Comments')

    denorm_posts_worksheet = workbook.add_worksheet('Denormalized Posts')

    # Create the classifier
    # Naive Bayes is performant (if not that accurate)
    human_names = [(name, 'male') for name in names.words('male.txt')] + [(name, 'female') for name in names.words('female.txt')]
    features = [({'name': name}, gender) for (name, gender) in human_names]
    training_set = features[500:]
    test_set = features[:500]

    classifier = NaiveBayesClassifier.train(training_set)

    export_users(csv, users, users_worksheet, classifier)
    export_posts(csv, posts, posts_worksheet, denorm_posts_worksheet, post_users, classifier)
    export_comments(csv, comments, comments_worksheet)
    export_friendships(csv, friendships, friendships_worksheet)
    export_publishings(csv, publishings, publishings_worksheet)

    workbook.close()

    return send_file('tmp/socialmemories.xlsx', as_attachment=True)
Example #26
0
from server import db, User

db.create_all()
u1 = User(username='******', password='******')
db.session.add(u1)
db.session.commit()
Example #27
0
 def test_verify_password(self):
     user = User(password='******')
     self.assertTrue(user.verify_password('123'))
     self.assertFalse(user.verify_password('321'))