def create_admin(session):
     admin_exist = session.query(User).filter(
         User.username == 'admin').scalar() is not None
     if not admin_exist:
         user = User('admin')
         user.update(VarConfig.get()["password"])
         session.add(user)
    def register_new_user(self, request):
        register_form = request.json if request.is_json else request.form
        register_dict = dict(register_form)
        form_register_fields = ["firstName", 'lastName', 'email', 'password', 'sectorId']
        form_valid_res = form_is_full(register_dict, form_register_fields)

        if form_valid_res.isSuccess:
            firstName = register_dict["firstName"]
            lastName = register_dict['lastName']
            email = register_dict['email']
            password = register_dict['password']
            sectorId = register_dict['sectorId']

            user = User(firstName=firstName, lastName=lastName, email=email, password=password, sectorId=sectorId)

            if user_is_valid(user).isSuccess:
                if password_is_valid(user.password).isSuccess:
                    if sector_id_is_valid(user.sectorId).isSuccess:
                        password_encrypt = PasswordEncryption.hash_salt(password=password, salt=None)
                        user.password = password_encrypt
                        if DAL.save_new_user_to_db(user) and DAL.save_user_password_history_to_db(user):
                            return AuthorizationResult(isSuccess=True, Message="User created successfully. ")
                    else:
                        return sector_id_is_valid(user.sectorId)
                else:
                    return password_is_valid(user.password)
            else:
                return AuthorizationResult(isSuccess=False, Message="User created failed. ")
        else:
            return form_valid_res
Exemplo n.º 3
0
    def add_user(self, user_request):
        name = user_request['name']
        description = user_request['description']
        user = User(name=name, description=description)
        created_user = self.user_model.save(user)

        return created_user
Exemplo n.º 4
0
def verify_user_by_email(email, password):
    with get_mysql_connection().cursor() as cursor:
        sql = "SELECT * FROM User WHERE email = %s AND password = '******'"
        cursor.execute(sql, email)
        result = cursor.fetchone()
        if result:
            return User(**result)
Exemplo n.º 5
0
def get_user_by_email(email):
    with get_mysql_connection().cursor() as cursor:
        sql = "SELECT * FROM User WHERE email = %s"
        cursor.execute(sql, email)
        result = cursor.fetchone()
        if result:
            return User(**result)
Exemplo n.º 6
0
def get_user_by_id(user_id):
    with get_mysql_connection().cursor() as cursor:
        sql = "SELECT * FROM User WHERE id = " + str(user_id)
        cursor.execute(sql)
        result = cursor.fetchone()
        if result:
            return User(**result)
 def get_users_query(self):
     all_users = self.users_df
     all_users_arr = CommonUsed.dfToArrayOfJsonWithoutIdx(all_users)
     Users = []
     for user in all_users_arr:
         Users.append(User.from_dict(user))
     return Users  # returns list of entities
Exemplo n.º 8
0
 def post(self):
     username = self.request.get('username')
     password = self.request.get('password')
     user = User.get_by_name(username)
     if user.count() == 0:
         self.display_error(username)
     else:
         if pw.valid_pw(username, password, user[0].password):
             self.set_secure_cookie('name', str(username))
             self.redirect('/blog/welcome')
         else:
             self.display_error(username)
Exemplo n.º 9
0
 def create_admin_user(session, *args):
     attributes = args[0]
     user = User()
     user.update(attributes)
     user.set_role(session.query(UserRole).filter(UserRole.label == attributes["role"]).one())
     session.add(user)
     return user
Exemplo n.º 10
0
 def create_privileged_user(session, *args):
     attributes = args[0]
     payload = args[1]
     if User.is_admin(attributes):
         user = User()
         user.set_role(session.query(UserRole).filter(UserRole.label == attributes["role"]).one())
         user.update(attributes)
         session.add(user)
         return user
     else:
         raise AuthError
Exemplo n.º 11
0
 def create_user(session, *args):
     attributes = args[0]
     user = User()
     user.set_role(session.query(UserRole).filter(
         UserRole.label == UserRole.get_clearance(0)).one())
     user.update(attributes)
     session.add(user)
     return user
Exemplo n.º 12
0
    def post(self):
        username = self.request.get('username')
        password = self.request.get('password')
        verify = self.request.get('verify')
        email = self.request.get('email')

        params = dict(username = username,
            email = email)

        is_valid = True
        if password != verify:
            params['verify_error'] = 'Password and verify do not match'
            is_valid = False
        if not username:
            params['username_error'] = 'Fill username'
            is_valid = False
        if not password:
            params['password_error'] = 'Fill password'
            is_valid = False
        if not verify:
            params['verify_error'] = 'Fill verify'
            is_valid = False
        if email and User.get_by_email(email).count() == 1:
            params['email_error'] = 'Email already exists'
            is_valid = False

        if User.get_by_name(username).count() == 1:
            params['username_error'] = 'User already exists'
            is_valid = False

        if is_valid:
            User.register(username, password, email)
            self.set_secure_cookie('name', str(username))
            self.redirect('/blog/welcome')
        else:
            self.render('signup.html', **params)
    def get_googleplus_data(self, keyword, limit):
        mentionList = []

        activity = self.GPLUS.activities().search(query=keyword,
                                                  maxResults=20).execute()
        counter = 0
        while (True):

            nextToken = activity['nextPageToken']
            items = activity.get('items', [])
            for data in items:
                post = ' '.join(data['title'].strip().split())
                if post:
                    mention = Mention()
                    user = User()
                    #  print(TMPL % (data['actor']['displayName'],
                    #               data['published'], post) )
                    print(data)
                    print("----------------Post Info-----------------------")
                    mention.set_source('GooglePlus')

                    print("Post url: " + data["url"])
                    url = data["url"].split("/")
                    mention.set_status_id(url[-1])

                    print("Resharer Count: " +
                          str(data["object"]["resharers"]['totalItems']))
                    mention.set_reshare_count(
                        str(data["object"]["resharers"]['totalItems']))
                    print("Replies Count: " +
                          str(data["object"]["replies"]['totalItems']))
                    print("Plusoners Count: " +
                          str(data["object"]["plusoners"]['totalItems']))
                    print("Text: " + data["object"]['content'])
                    mention.set_text(data["object"]['content'])
                    for s in data['object']:
                        if s == 'attachments':
                            attachments = data["object"]['attachments']
                            for attachment in attachments:
                                print("attachments:" + attachment["url"])
                    print("----------------User Info-----------------------")
                    user.set_user_id(data['actor']["id"])
                    print("Diplay Name:" + data['actor']['displayName'])
                    user.set_display_name(data['actor']['displayName'])
                    user.set_display_picture(data['actor']['image']['url'])
                    print("Display Image:" + data['actor']['image']['url'])
                    print("Created at: " + data["published"])
                    m = moment.date(data["published"], '%Y-%m-%dT%H:%M:%SZ')
                    sql_format = m.format('YYYY-M-D H:mm:ss')
                    print(sql_format)
                    user.set_time(sql_format)
                    mention.set_user(user)
                    mentionList.append(mention)
                    counter = counter + 1
                    print("--------------------------------------------" +
                          str(counter))
                    if counter >= limit:
                        break
            if counter < limit:
                activity = self.GPLUS.activities().search(
                    query=keyword, maxResults=20,
                    pageToken=nextToken).execute()
            else:
                break
        return mentionList
    def get_data(self, tweets_list, mentionlist):

        for tweet in tweets_list:
            if (self.count < self.limit):
                mention = Mention()
                user = User()
                # print("----------------Post Info-----------------------")
                mention.set_source("Twitter")
                mention.set_reshare_count(str(tweet["retweet_count"]))
                mention.set_text(tweet['text'])
                # # print(json.dumps(tweet, sort_keys=True, indent=4))
                mention.set_status_id(tweet["id_str"])
                print("Tweet ID: " + tweet["id_str"])
                # print("Created at: " + tweet["created_at"])

                sql_format = datetime.strptime(tweet["created_at"],
                                               '%a %b %d %H:%M:%S %z %Y')
                user.set_time(sql_format.strftime('%Y-%m-%d %H:%M:%S'))
                # t=datetime.strptime(tweet["created_at"], '%a %b %d %H:%M:%S %z %Y')
                # t.strftime('%Y-%m-%d %H:%M:%S')
                # m = moment.date(tweet["created_at"], '%a %b %d %H:%M:%S %z %Y')
                # sql_format = m.format('YYYY-M-D H:mm:ss')
                # print(sql_format)

                # print("Tweet Language: " + tweet["lang"])

                if tweet["retweet_count"] != 0:
                    user.set_display_name(
                        tweet["retweeted_status"]["user"]["screen_name"])
                    user.set_display_picture(
                        tweet["retweeted_status"]['user']['profile_image_url'])

                    mention.set_status_id(str(tweet["retweeted_status"]['id']))
                    # print("----------------Retweeted User Info-----------------------")
                    user.set_user_id(
                        tweet["retweeted_status"]["user"]["id_str"])
                    # print("User Name: " + tweet["retweeted_status"]["user"]["name"])
                    # print("User Location: " + tweet["retweeted_status"]["user"]["location"])
                    user.set_total_post(
                        str(tweet["retweeted_status"]['user']
                            ['statuses_count']))
                    user.set_following_count(
                        str(tweet["retweeted_status"]['user']
                            ['friends_count']))
                    user.set_follower_count(
                        str(tweet["retweeted_status"]['user']
                            ['followers_count']))
                    user.set_total_likes(
                        str(tweet["retweeted_status"]['user']
                            ['favourites_count']))
                    # print("fav: " + str(tweet["retweeted_status"]['favorite_count']))

                    retweets = self.twitter.statuses.retweets._id(
                        _id=str(tweet["retweeted_status"]['id']))
                    retweeterlist = []
                    for retweet in retweets:
                        retweeter = User()
                        retweeter.set_display_name(
                            retweet["user"]["screen_name"])

                        #dt_str = datetime.datetime.strftime(retweet["created_at"], '%Y-%m-%d %H:%M:%S')

                        retweeter.set_time(retweet["created_at"])
                        retweeter.set_display_picture(
                            retweet["user"]["profile_image_url"])

                        retweeter.set_user_id(retweet["user"]["id_str"])
                        retweeter.set_total_post(
                            str(retweet['user']['statuses_count']))
                        retweeter.set_following_count(
                            str(retweet['user']['friends_count']))
                        retweeter.set_follower_count(
                            str(retweet['user']['followers_count']))
                        retweeter.set_total_likes(
                            str(retweet['user']['favourites_count']))
                        retweeterlist.append(retweeter)
                        # print(" - retweeted by %s" % (retweet["user"]["screen_name"]))
                        # print("retweet time:"  +retweet["created_at"] )
                    mention.set_resharer(retweeterlist)
                else:
                    # print("----------------User Info-----------------------")
                    user.set_user_id(tweet["user"]["id_str"])
                    # print("User Name: " + tweet["user"]["name"])
                    # print("User Location: " + tweet["user"]["location"])

                    user.set_display_picture(
                        tweet['user']['profile_image_url'])
                    user.set_display_name(tweet['user']['screen_name'])
                    user.set_total_post(str(tweet['user']['statuses_count']))
                    user.set_following_count(
                        str(tweet['user']['friends_count']))
                    user.set_follower_count(
                        str(tweet['user']['followers_count']))
                    user.set_total_likes(str(
                        tweet['user']['favourites_count']))

                mention.set_user(user)
                mentionlist.append(mention)
                self.count = self.count + 1
                print("<---------------------" + str(self.count) +
                      "---------------------------->")
            else:
                return mentionlist
        return mentionlist
Exemplo n.º 15
0
 def get_by_id(self, user_id):
     fetched_user = self.db.get_element_by_id(self.doc_type, user_id)
     return User(**fetched_user)
 def get_user_query(self, _id):
     signle_user = self.users_df.loc[self.users_df['id'] == _id]
     userDict = CommonUsed.rowToJson(signle_user)
     userEntity = User.from_dict(userDict)
     return userEntity  # returns entity
Exemplo n.º 17
0
 def create_user(self, username):
     self.user = User(username)
Exemplo n.º 18
0
 def __init__(self):
     self.devices = Device.allDevices()
     self.locations = Location.allLocations()
     self.users = User.allUsers()
     self.vehicles = Vehicle.allVehicles()
     self.entities = Entity.allEntities()