Ejemplo n.º 1
0
 def get(self, part, uid):
     mUser = db.get_user(uid)
     cUid = self.get_secure_cookie('user')
     user = db.get_user(cUid)
     posts = db.get_post_by_id(uid)
     replys = db.get_reply_by_id(uid)
     if part == 'reply':
         posts = []
     elif part == 'post':
         replys = []
     self.render(
             't_member.html', title='Ran - Member',
             user=user, replys=replys, posts=posts,
             mUser=mUser,
             )
Ejemplo n.º 2
0
Archivo: app.py Proyecto: hmac/msg
def authenticate_message(form):
    keyB = auth.decrypt(b64d(form['key']))
    payload = b64d(form['payload'])
    payload = auth.aes_decrypt(payload, keyB)
    payload = json.loads(payload)
    sender, recipient, body, keyA, sig, keyA2 = payload['sender'], payload['recipient'], payload['body'], payload['key'], payload['signature'], payload['sender_key']
    sender_user = db.get_user(sender)
    recipient_user = db.get_user(recipient)
    if not (sender_user and recipient_user):
        return (False,)
    sig = b64d(sig)
    if auth.verify(key_for(sender), sender+recipient+body, sig):
        return (True, (sender, recipient, body, keyA, keyA2))
    else:
        return (False,())
Ejemplo n.º 3
0
def process_register_email(message):
    try:
        if not re.match(r"[^@]+@[^@]+\.[^@]+", message.text):
            bot.reply_to(message, 'Email incorrecto. Vuelve a introducirlo.')
            bot.register_next_step_handler(msg, process_register_email)
        else:
            user = db.get_user(message.from_user.id)[0]
            emails = [] if 'emails' not in user else user['emails']
            registered = False
            for email in emails:
                if email['email'] == message.text:
                    registered = True
                    break
            if not registered:
                emails += [{
                        'email': message.text,
                        'urls': [{
                            'url': '',
                        }],
                }]
                db.register_emails(user['id'], emails)
                bot.reply_to(message, 'Registrado!')
            else:
                bot.reply_to(message, 'Este email ya lo has registrado. Se ignora.')
    except Exception, e:
        bot.reply_to(message, 'ERROR')
def finishquest():
    if 'questid' in request.args:
        db.add_plays(session['usern'], 1)
        ret = {'num_quests':db.get_user(session['usern'])[1]}
        return jsonify(**ret)
    ret = {'error':'questid missing'}
    return jsonify(**ret)
Ejemplo n.º 5
0
def process_delete_email(message):
    markup = types.ReplyKeyboardHide(selective=False)
    try:
        if not re.match(r"[^@]+@[^@]+\.[^@]+", message.text):
            bot.reply_to(message, 'Email incorrecto.')
            bot.register_next_step_handler(msg, process_delete_email)
        else:
            user = db.get_user(message.from_user.id)[0]
            emails = [] if 'emails' not in user else user['emails']
            registered = False
            new_emails = []
            for email in emails:
                if email['email'] == message.text:
                    registered = True
                else:
                    new_emails += [email]
            if registered:
                db.register_emails(user['id'], new_emails)
            else:
                bot.reply_to(message, 'Este email no está registrado. Se ignora.')
            bot.reply_to(message, 'Se ha borrado dicho dicho email.', reply_markup=markup)
    except Exception, e:
        HSHBOT_ADMIN_ID = int(os.environ['HSHBOT_ADMIN_ID'])
        if HSHBOT_ADMIN_ID:
            bot.send_message(HSHBOT_ADMIN_ID, 'ERROR', reply_markup=markup)
Ejemplo n.º 6
0
def user_notes(username):
	profile_user = db.get_user(username)
	if profile_user is None:
		abort(404)
	return render_template('notes.html',
							notes=reversed(db.get_notes_by_author(username)),
							profile_user=profile_user)
Ejemplo n.º 7
0
    def post(self, location_id):
        """
            This handler is a bit more complex - handles the actions that can 
            be taken at this location. For instance:
            
            - extort
            - take control
            - leave guards
            - battle
        """
        user_id = self.get_secure_cookie("user_id")
        user = db.get_user(user_id)
                    
        location = db.get_or_create_location_by_id(location_id)
        action = self.get_argument("action")

        if action == "take-control":
            # TODO: Do an additional check to make sure this isn't owned
            # by someone else and there are no guards here.
            location["owner"] = { "name" : user["name"], "user_id" : user["id"] }
            db.save_location(location)
        elif action == "extort" and location["owner"]["user_id"] == user["id"]:
            inventory = db.get_inventory_for_user(user)
            extortion_value = 5 * location["checkins"]
            inventory["money"] += extortion_value
            db.save_inventory(inventory)
            
            location["last_extort_time"] = datetime.datetime.now()
            db.save_location(location)
            
        self.redirect("/location/%s" % location_id)
Ejemplo n.º 8
0
 def on_fetch_location(self, response):
     """ 
         Callback invoked when we get location data. Lazily check to see if
         we already have an entry in MongoDB about this location or not. If
         not, create one.
     """
     user_id = self.get_secure_cookie("user_id")
     user = db.get_user(user_id)
     
     location = json.loads(response.body)
     location_data = db.get_or_create_location_by_id(location["id"])
     
     # Lazy get this
     location_data["checkins"] = location["checkins"]
     db.save_location(location_data)
     
     inventory = db.get_inventory_for_user(user)
     
     # power is a function of checkins * something
     self.render("templates/location.html",
         datetime=datetime,
         location=location, 
         data=location_data, 
         current_user=user,
         inventory=inventory)    
Ejemplo n.º 9
0
def checkOAuthUser(request,code):
	try:
		service  = oauth.get_service(code)
		response = service.people().get(userId='me').execute()
		oauth_id = response["id"]		
		domain   = response["domain"]
		emails   = response["emails"]		
		username = emails[0]["value"]
		name     = response["displayName"]
		print response		
		print username
		if domain=="travelyaari.com":			
			user=db.get_user(username,None,oauth_id,name)						
			request.user=user
			getAuthorizedLinks(request)
			print request.allowed_links
			return True
		else:
			request.msg="INVALID_DOMAIN"	
			return False
	except Exception as ex:
		print ex

		request.msg="AUTHENTICATION_FAILED"
		print request.msg
		return False
Ejemplo n.º 10
0
def handle_checkall(message):
    _logger.info("/checkall")
    user = db.get_user(message.from_user.id)[0]
    emails = [] if 'emails' not in user else user['emails']
    if not emails:
        bot.reply_to(message, 'No has registrado emails todavía. Utiliza /newemail para ello.')
    flag_update_urls = False
    for email in emails:
        urls = [] if 'urls' not in email else email['urls']
        urls_data = [url['url'] for url in urls]
        json_data = check_email(email['email'])
        lines = show_data(json_data)
        if lines:
            bot.reply_to(message, "%s con resultados..." % email['email'])
            for line in lines:
                registered = False
                if line[1] in urls_data:
                    registered = True
                    break
                if not registered:
                    urls += [{'url': line[1]}]
                    flag_update_urls =True
                line_str = ' '.join(line)
                bot.send_message(user['id'], line_str)
            email['urls'] = urls
        else:
            bot.send_message(user['id'], "%s Todo OK!" % email['email'])
    if flag_update_urls:
        db.register_emails(user['id'], emails)
Ejemplo n.º 11
0
 def get(self):
     uid = self.get_secure_cookie('user')
     user = db.get_user(uid)
     posts = db.get_friends_post(uid)
     self.render(
             't_friends.html', title='Ran - Friends',
             user=user, posts=posts,
             )
Ejemplo n.º 12
0
 def GET(self):
     user = db.get_user(session.uid)
     threads = db.get_threads(session.uid)
     html = render.forum(tr.text[db.get_lang(session.uid)],
                         threads[::-1],
                         user['isadm'],
                         session.page_data)
     return html
Ejemplo n.º 13
0
    def load_data(self, name):
        """Load data in from db"""

        data = db.get_user(name)
        self.title = data["title"]
        self.gold = data["gold"]
        self.link_karma = data["link_karma"]
        self.comment_karma = data["comment_karma"]
Ejemplo n.º 14
0
def handle_delemails(message):
    _logger.info("/delemails")
    user = db.get_user(message.from_user.id)[0]
    if user['emails'] != []:
        db.register_emails(user['id'], [])
        bot.reply_to(message, 'Se han borrado todos los emails registrados.')
    else:
        bot.reply_to(message, 'No has registrado emails todavía. Utiliza /newemail para ello.')
    return False
Ejemplo n.º 15
0
 def get(self):
     searchKey = self.get_argument('searchInput')
     cUid = self.get_secure_cookie('user')
     user = db.get_user(cUid)
     posts = db.get_post_by_key(searchKey)
     self.render(
             't_search.html', title='Ran - Search',
             posts=posts, user=user,
             )
Ejemplo n.º 16
0
def check_username_occupied(username):
    '''
    If the username has been occupied, return True;
    else return False.
    '''
    if not db.get_user(username):
        return True
    else:
        return False
Ejemplo n.º 17
0
 def open(self):
     self.user = get_user(self.cookies)
     if self.user is None:
         self.close()
         return
     self.socket_id = str(uuid4())
     print "NEW SOCKET: ", self.socket_id
     self.state = "idle"
     self.write_message(json.dumps({ "username": self.user.username}))
Ejemplo n.º 18
0
def handle_start(message):
    _logger.info("/start")
    bot.reply_to(message, "Welcome!")
    users = db.get_user(message.from_user.id)
    if users.count() == 0:
        db.register_user(
            message.from_user.id,
            message.from_user.first_name,
            message.from_user.last_name,
            message.from_user.username)
Ejemplo n.º 19
0
def get_user_info(username):
    user = db.get_user(username)
    if user is None:
        return {'error': 'Invalid username!'}
    res = dict()
    res['username'] = user.username
    res['display'] = user.display
    res['info'] = user.info
    res['image'] = user.image
    return res
Ejemplo n.º 20
0
 def post(self):
     """
         Allows a user to make purchases. In the case of armor or weapons, we
         simply increment the number of items a user has.
         
         In the case of mobsters, we append to the current list of mobsters in the
         player's inventory because each mobster has its own state.
     """
     user_id = self.get_secure_cookie("user_id")
     user = db.get_user(user_id)
     inventory = self.get_inventory_for_user(user)
     
     action = self.get_argument("action")
     item_id = self.get_argument("id")
     
     # Probably could have collapsed armor and weapons into a single
     # type and used a field to designate type.
     if action == "buy-weapon":
         # User already has item, increment quantity
         weapon = items.weapons[item_id]
         if item_id in inventory["weapons"].keys():
             inventory["weapons"][item_id]["quantity"] += 1
         else:
             inventory["weapons"][item_id] = {
                 "name" : weapon["name"],
                 "quantity" : 1
             }
     elif action == "buy-armor":
         armor = items.armor_list[item_id]
         if item_id in inventory["armor"].keys():
             inventory["armor"][item_id]["quantity"] += 1
         else:
             inventory["armor"][item_id] = {
                 "name" : armor["name"],
                 "quantity" : 1
             }
     elif action == "recruit-mobster":
         # We are recruiting someone to our gang. We persist this data
         # differently because we have to store the state of each mobster.
         mobster_prototype = items.mobsters[item_id]
         
         # We create a new instance of a mobster to track state
         mobster_instance = {
             "name" : mobster_prototype["name"],
             "image_url" : mobster_prototype["image_url"],
             "level" : mobster_prototype["level"],
             "hp" : mobster_prototype["base_hitpoints"],
             # We may want to modify this later with bonuses
             "damage" : mobster_prototype["base_damage"]
         }
         inventory["mobsters"].append(mobster_instance)
         
     db.save_inventory(inventory)
     self.redirect("/store")
Ejemplo n.º 21
0
def build_user_recommendations(user_id):
    """
    Oh boy. Gets recommendations for user based off other users who share
    the same sources.
    """
    NUM_RECOMMENDATIONS = 1
    user = db.get_user(user_id)
    if not user:
        print "REC: ERROR: User not found, no recommendations"
        return []
    user_sources = user[0]["sources"]

    if not user_sources:
        other_sources = get_most_popular_sources(user_sources)
        return db.update_user_recommendations(user_id,other_sources)

    other_sources = Counter()
    for s in user_sources:
        tmp_source = db.get_source_by_id(s)
        if not tmp_source:
            continue
        source_users = tmp_source[0]["users"]
        for u in source_users:
            if u == user[0]["user_id"]:
                continue
            tmp_user = db.get_user(u)
            if not tmp_user:
                continue 
            other_user_sources = tmp_user[0]["sources"]
            for j in other_user_sources:
                if j not in user_sources:
                        # if j not in other_sources it will automatically be 0
                        other_sources[j] += 1

    # if after all that we have no recommendations or we don't have many,
    # just get most popular sources
    other_sources = [i[0] for i in other_sources.most_common()]
    if len(other_sources) < NUM_RECOMMENDATIONS:
        other_sources = get_most_popular_sources(user_sources)
    # update user recs and return the db add query boolean.   
    return db.update_user_recommendations(user_id,other_sources)
Ejemplo n.º 22
0
def get_username(request):
	if "username" in request.session:
		username=request.session["username"]
		if username.strip()!='':
			user=db.get_user(username.strip())
			if user:			
				request.username=user.username
				request.user=user
				getAuthorizedLinks(request)
				return username
			else:
				return None
Ejemplo n.º 23
0
 def get(self):
     uid = self.get_secure_cookie('user')
     user = db.get_user(uid)
     sections = db.get_sections()
     forum = db.get_forum()
     wealthList = db.get_wealth_list()
     warning = self.get_argument('warning', None)
     self.render(
             't_config.html', title='Ran - Config',
             user=user, setions=sections, forum=forum,
             warning=warning, wealthList=wealthList,
             )
Ejemplo n.º 24
0
 def get(self):
     user_id = self.get_secure_cookie("user_id")
     lat = self.get_argument("lat")
     lon = self.get_argument("lon")
     user = db.get_user(user_id)
     
     url = API["places"] % { "lat" : lat, 
                             "lon" : lon,
                             "distance" : 1000,
                             "access_token" : user["access_token"] }
     
     client = httpclient.AsyncHTTPClient()
     client.fetch(url, self.on_fetch_places)
Ejemplo n.º 25
0
 def get(self):
     sections = db.get_sections()
     forum = db.get_forum()
     wealthList = db.get_wealth_list()
     uid = self.get_secure_cookie('user')
     if uid:
         user = db.get_user(uid)
     self.render(
             't_new.html', title='Ran - New',
             sections=sections, forum=forum, user=user,
             wealthList=wealthList,
             )
     pass
Ejemplo n.º 26
0
 def get(self):
     pid = self.get_argument('pid')
     uid = self.get_secure_cookie('user')
     user = db.get_user(uid)
     replys = db.get_replys(pid)
     post = db.get_post_topic(pid)
     att = db.get_att(pid)
     forum = db.get_forum()
     wealthList = db.get_wealth_list()
     self.render(
             't_topic.html', title='Ran - Topic',
             user=user, forum=forum, replys=replys,
             post=post, wealthList=wealthList, att=att,
             )
def register():
    if 'usern' in session:
        return redirect('/')
    if request.method == 'GET':
        return render_template('register.html',error="")
    else:
        usern = request.form['usern']
        passw = request.form['passw']
        if db.get_user(usern):
            return render_template('register.html', error='Username already exists')    
        else:
            db.add_user(usern, passw)
            session['usern'] = usern
            return redirect('/')
Ejemplo n.º 28
0
 def get(self):
     """ 
         Fetches the purchasable items from the datastore and renders
         them to the user via HTML.
     """
     user_id = self.get_secure_cookie("user_id")
     user = db.get_user(user_id)
     inventory = db.get_inventory_for_user(user)
             
     self.render("templates/store.html",
         inventory=inventory,
         mobsters=items.mobsters,
         weapons=items.weapons,
         armor_list=items.armor_list)
Ejemplo n.º 29
0
def login():
	if g.user:
		return redirect(url_for('notes'))
	error = None
	if request.method == 'POST':
		user = db.get_user(request.form['username'])
		if user is None:
			error = 'Invalid username'
		elif not check_password_hash(user['pw_hash'], request.form['password']):
			error = 'Invalid password'
		else:
			#flash('You were logged in')
			session['user_id'] = db.get_userid_by_name(user['username'])
			return redirect(url_for('notes'))
	return render_template('login.html', error=error)
Ejemplo n.º 30
0
def handle_emails(message):
    _logger.info("/emails")
    user = db.get_user(message.from_user.id)[0]
    emails = [] if 'emails' not in user else user['emails']
    emails_str = ''
    for email in emails:
        emails_str += email['email'] + "\n"
    if emails_str:
        bot.reply_to(message, emails_str)
    else:
        bot.reply_to(
            message,
            "No has registrado emails todavía. Utiliza /newemail para ello."
        )
    return False
Ejemplo n.º 31
0
def authenticate(username, password):
    print(username, password)
    return db.get_user(username, password)
Ejemplo n.º 32
0
from db import get_user
from users import User

if __name__ == "__main__":

    while True:
        name = input("ユーザー名を入力してください。: ")

        user_ = get_user(name)
        if user_:
            user = User(user_["id"], user_["name"], user_["age"])
            break

    print(user.name + "でログインしました。")

    tweet = input("ツイートしてください。: ")

    print("===ツイート内容===")
    print(user.name + "さん:" + tweet)
Ejemplo n.º 33
0
def logik(call):
    user = db.get_user(call.message.chat.id)
    key = types.InlineKeyboardMarkup()
    if call.message:

        params = call.data.split("_")

        if call.data == "setting":
            bot.edit_message_text(text="Настройки",
                                  chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  reply_markup=get_setting())
        if call.data == "menu":
            bot.edit_message_text(text="Сделайте выбор",
                                  chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  reply_markup=menu())
        if call.data == "select_gender":
            for g in db.Gender.select():
                key.add(
                    types.InlineKeyboardButton(text=g.name,
                                               callback_data="setgender_" +
                                               g.id))
            bot.edit_message_text(text="Сделайте выбор",
                                  chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  reply_markup=key)
        if call.data == "select_age":
            for g in db.Age.select():
                key.add(
                    types.InlineKeyboardButton(text=g.name,
                                               callback_data="setage_" + g.id))
            bot.edit_message_text(text="Сделайте выбор",
                                  chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  reply_markup=key)
        if call.data == "select_gender_chat":
            for g in db.Gender.select():
                key.add(
                    types.InlineKeyboardButton(text=g.name,
                                               callback_data="setgenderchat_" +
                                               g.id))
            bot.edit_message_text(text="Сделайте выбор",
                                  chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  reply_markup=key)
        if call.data == "select_age_chat":
            for g in db.Age.select():
                key.add(
                    types.InlineKeyboardButton(text=g.name,
                                               callback_data="setagechat_" +
                                               g.id))
            bot.edit_message_text(text="Сделайте выбор",
                                  chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  reply_markup=key)

        if params[0] == "setgender":
            user.gender = params[1]
            user.save()
            bot.edit_message_text(text="Изменения успешно. \n Настройки",
                                  chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  reply_markup=get_setting())
        if params[0] == "setage":
            user.age = params[1]
            user.save()
            bot.edit_message_text(text="Изменения успешно. \n Настройки",
                                  chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  reply_markup=get_setting())
        if params[0] == "setgenderchat":
            user.s_gender = params[1]
            user.save()
            bot.edit_message_text(text="Изменения успешно. \n Настройки",
                                  chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  reply_markup=get_setting())
        if params[0] == "setagechat":
            user.s_age = params[1]
            user.save()
            bot.edit_message_text(text="Изменения успешно",
                                  chat_id=call.message.chat.id,
                                  message_id=call.message.message_id,
                                  reply_markup=get_setting())
Ejemplo n.º 34
0
def load_user(username):  # checks if the username entered exists or not
    print(username)
    print(get_user(username))
    return get_user(username)[0]
Ejemplo n.º 35
0
 def get_current_user(self):
     username = self.get_secure_cookie('username')
     return db.get_user(self.application.db, username)
Ejemplo n.º 36
0
def fetch_user(username, password):
    user = get_user(username, password)
    return User(user[1], password, id=user[0])
Ejemplo n.º 37
0
#!/usr/bin/python3.7
import db
import base
import session

images = db.get_all_images()

data = session.get_session_data()
if data is None:
    print("Location: login.py")

user = db.get_user(data['user_id'])

if user[4] != 2:
    print("Location: upload.py")

print("Content-type:text/html")
print("")
base.start_html()
for image in images:
    print('<img src="../../images/%s" width=100 height=100>' % image[1])
    print('<p>%s : viewed %d times</p>' % (image[1], image[2]))
base.finish_html()
Ejemplo n.º 38
0
def get_user(username):
    user = db.get_user(username)
    if user is not None:
        return jsonify(backenduser_to_safe_frontenduser(user))
    return jsonify(None)
Ejemplo n.º 39
0
    name = db.get_items_name(item_id)
    return name


def get_users_name(db, user_id):
    usersname = db.get_user_name(user_id)
    return usersname


if __name__ == "__main__":
    db = db.DB()
    print("****************Welcome to the Task Shop****************")
    print("Please login before continue.")
    username = input("Enter username: "******"Enter password: "******"admin":
            choice = get_admins_option()
            if choice == 1:
                items = db.get_items()
                for x in items:
                    print("Item Name: {} \t Item Price: {}".format(x[1], x[2]))
            if choice == 2:
                item_name = input("Enter product name: ")
                price = int(input("Enter price: "))
                add_product = db.insert_item(item_name, price, user[0])
                if add_product:
                    print("Product added successfully")
            if choice == 3:
Ejemplo n.º 40
0
password_change_error = "Password Change Error!"
user = None

params = cgi.FieldStorage()
if os.environ["REQUEST_METHOD"].upper() == "POST":
    username = params.getvalue("username")
    password = params.getvalue("password")
    password_repeat = params.getvalue("password_repeat")
    secret_question = params.getvalue("secret_question")
    secret_answer = params.getvalue("secret_answer")

    validation_error = False
    success = False

    user = db.get_user(username)

    if not user:
        password_change_error += "<br>User with username " + username + " does not exist!"
        validation_error = True

    elif not password_utils.verify_password(secret_answer, user[5]):
        password_change_error += "<br>Wrong secret answer!"
        validation_error = True

    if password != password_repeat:
        password_change_error += "<br>Passwords must match!"
        validation_error = True

    if validation_error == False:
        authentication.change_password(user[1], password)
Ejemplo n.º 41
0
def test_get_user(user_row):
    assert db.insert_user(*user_row) == True
    user = db.get_user(user_row[0])
    assert user is not None
    assert user == User(*user_row)
Ejemplo n.º 42
0
def get_me():
    user_id = get_jwt_identity()
    this_user = get_user(user_id)

    return jsonify(this_user.create_json())
Ejemplo n.º 43
0
def test_update_user_state(user_row):
    new_state = random.randint(0, 999)
    assert db.insert_user(*user_row) == True
    assert db.update_user_state(user_row[0], new_state) == True
    assert db.get_user(user_row[0]).state == new_state
Ejemplo n.º 44
0
 def test_get_user(user):
     assert bool(db.get_user(user.username)) == True
Ejemplo n.º 45
0
 def get_current_user(self):
     '''
     Same method as for the default tornado request handler
     '''
     username = self.get_secure_cookie('username')
     return db.get_user(self.application.db, username)
Ejemplo n.º 46
0
 def test_not_get_user():
     assert db.get_user(TestUsers.WRONG_USERNAME) == False
Ejemplo n.º 47
0
def register_status(update, context):
    result = bool(get_user(update.effective_user.id))
    reply_message = (messages.user_registered
                     if result else messages.user_not_registered)
    context.bot.send_message(chat_id=update.message.chat_id,
                             text=reply_message)
Ejemplo n.º 48
0
def handle_send_message_event(data):
    current_app.logger.info('Caught message from client.')
    user_id = get_jwt_identity()

    username = data['username']
    room_id = data['room']  # client must pass room id here
    message = data['text']
    
    try:
        image_id = data['image_id']
    except Exception as e:
        image_id = None

    if len(message) == 0 and not image_id:
        return None
    
    time_sent = time.time()
    data['time_sent'] = time_sent
    user = get_user(user_id)
    room = get_room(room_id)
    data['user_id'] = user_id
    # data['avatar_id'] = user.avatar
    data['room_name'] = room.name

    if user_id not in connected_sockets:
        current_app.logger.info('!!: {} tried to send a message without being connected to a room.'.format(username))

    room_member_ids = []
    room_member_objects = get_room_members(room_id)  # determine who should receive this message
    for db_item in room_member_objects:
        room_member_ids.append(str(db_item['_id']['user_id']))

    if user_id in room_member_ids:  # if the author/sender is in the room they are trying to send to
        current_app.logger.info("{} ({}) has sent message to the room {} at {}".format(user_id, username, room, time_sent))
        apns_targets = []

        for member in room_member_ids:  # for person in room
            member_id = get_user(member).ID
            if member_id in connected_sockets and len(connected_sockets[member_id]) != 0:
                target_socket_ids = connected_sockets[member_id]
                try:
                    for socket in target_socket_ids:
                        socketio.emit('receive_message', data, room=socket)  # emit to specific user
                        current_app.logger.info('Sent to {}'.format(socket))
                except TypeError as e:
                    current_app.logger.info('Failed to emit message to {}, connected on {}. They may not have an open '
                                            'connection. {}'.format(member_id, connected_sockets[member_id], e))
            else:  # send push notifications for anyone offline
                user_apn_tokens = get_apn(member)
                if not user_apn_tokens:
                    continue
                else:
                    apns_targets.extend(user_apn_tokens)
        # room_id, text, sender, bucket_number=0, image_id=None
        current_app.logger.info("Emitting APNS and storing message".format())
        apns_thread = threading.Thread(target=handle_apns_load, args=(apns_targets, data, room.is_dm))
        # current_app.logger.info("SAVING MESSAGE")
        db_thread = threading.Thread(target=save_message, args=(room_id, message, user_id, image_id))  # to db
        apns_thread.start()
        db_thread.start()
        current_app.logger.info("{} {}".format(apns_thread, db_thread))
    else:
        current_app.logger.info("{} not authorized to send to {}".format(username, room))
Ejemplo n.º 49
0
def load_user(username):
    return get_user(username)
Ejemplo n.º 50
0
def before_request():
    g.user = None
    if 'user_id' in session:
        g.user = db.get_user(session['user_id'])
Ejemplo n.º 51
0
def test_update_user_saved_state(user_row):
    new_saved_state = helpers.random_module_code()
    assert db.insert_user(*user_row) == True
    assert db.update_user_saved_state(user_row[0], new_saved_state) == True
    assert db.get_user(user_row[0]).saved_state == new_saved_state
Ejemplo n.º 52
0
def load_user(email):
    u = db.get_user(email)
    if not u:
        return None
    user = User(u[0], u[1], u[2])
    return user
Ejemplo n.º 53
0
def get_user(email):
    result = db.get_user(email)
    return jsonify({'email': result['email'], 'name': result['name']})
Ejemplo n.º 54
0
def postform():
    """Form POST endpoint for all form variations."""

    input = request.form
    mode = input["mode"]
    email = input["email"]
    passwd = input.get("passwd")
    token = input.get("token")

    u = db.get_user_by_email(email)

    errmsg = ""
    if not email:
        errmsg = "Email is missing"

    elif mode == "login":
        if not u or not account.check_password(u.password, passwd):
            errmsg = "Invalid login credentials"
        else:
            account.build_session(u, is_permanent=True)

            log.info(f"LOGIN OK {email}")

            # you should redirect to real ui...
            return redirect("/api/me")

    elif mode == "signup":
        if u:
            errmsg = f"Account exists already {email}"
        elif passwd != input.get("passwd2"):
            errmsg = f"Passwords differ"
        else:
            errmsg = account.check_password_validity(passwd)
            if not errmsg:
                # create new user
                u = db.User()
                u.email = email
                u.first_name = input["firstname"]
                u.last_name = input["lastname"]
                u.password = account.hash_password(passwd)
                u.role = 'editor'  # set default to what makes sense to your app
                u.save(force_insert=True)

                account.new_signup_steps(u)
                account.build_session(u, is_permanent=True)

                log.info(f"SIGNUP OK {email}")

                # you should redirect to real ui...
                return redirect("/api/me")

    elif mode == "forgot":
        # request a new password
        if u:
            # generate an expiring token and store in redis
            token = str(util.generate_token())
            data = {"uid": f"{u.id}", "ip": get_ip()}
            expire_secs = 60 * 60  # 1h
            red.set_keyval(token, data, expire_secs)

            # email the link to the user
            link = f"DOMAIN/auth/reset?token={token}"
            errmsg = f"Server should now send a reset email to {email}..."
            log.info(f"password reset link = {link}")

        else:
            errmsg = f"Unknown account {email}"

    elif mode == "reset":
        # reset a password
        data = red.get_keyval(token)
        if data:
            try:
                u = db.get_user(data["uid"])

                # extra security: make sure ip addresses match, only the
                # requester can use the link
                if get_ip() != data["ip"]:
                    errmsg = "Invalid IP"

                elif passwd != input.get("passwd2"):
                    errmsg = "Passwords differ"

                else:
                    # ok, reset the password
                    u.password = account.hash_password(passwd)
                    u.save()
                    account.build_session(u, is_permanent=True)

                    # security: disable link from further use
                    red.delete_key(token)

                    log.info(f"PASSWD RESET OK {email}")
                    return redirect("/api/me")

            except:
                log.error(f"no user {value}")
                errmsg = "Invalid token"
        else:
            errmsg = "Invalid token"

    if errmsg:
        log.warn(errmsg)

    return render_template('auth.html',
                           mode=mode,
                           email=email,
                           err=errmsg,
                           token=token)
Ejemplo n.º 55
0
def loadMsg(open_id, content):
    user = db.get_user(open_id)
    log_.info("处理消息:%s,用户:%s" % (content, user.name))
    if content == '查询自己':
        return open_id
    if user.level >= 1:
        try:
            if content == 'help':
                answer = "管理员命令:"
                for c in command:
                    answer += "\n===================\n" + c.cmd + ":\n" + c.info
                logVip(user.name, content, answer)
                return answer
            target_user_name = user.name
            for cd in command:
                if cd.cmd in content:
                    if cd.perm(user) == 0:
                        tk.send_to_manager("%s尝试使用管理员命令失败\n%s" %
                                           (user.name, content))
                        return "尝试使用管理员命令失败,请先联系客服获取权限"
                    print "管理员命令:" + content
                    current_user.name = user.name
                    current_user.open_id = user.open_id
                    cmdMsg = cd.func(content, user)
                    logVip(user.name, content, cmdMsg)
                    return cmdMsg
        except Exception as e:
            return e + "\nload msg error!"
    try:
        if content in check_list:
            return search_for_key(user, content)
        detail = re.split(r'[+|,|,|.|。| |*]+',
                          content)  #content.split('[+|,|,|.|。| |*]+')[1:]
        key_word = detail[0]
        if '号' not in key_word:
            key_word += '号'
        detail = detail[1:]
        msg = db.get_msg(key_word)
        #detail = content.split('[\+|\,|\,|\.|\。| |\*]+')[1:]
        answer = msg.answer['answer'] + "\n"
        #if user.level > 0:
        #    answer += "您是尊贵的L" + str(user.level)+ "用户,"
        retail_price = 0
        if msg.price[0].isdigit() and msg.price[0] != '0':
            retail_price = int(msg.price[0]) * 1.2
        else:
            retail_price = int(msg.price[9]) * 3
        answer += "建议零售价:%d\n=====================\n" % retail_price
        answer += "给您是:"
        if user.level == 9:
            for p in msg.price:
                answer += p + ","
        elif msg.price[user.level] == '0':
            answer += '未知,请询问客服'
        else:
            answer += msg.price[user.level]
        if len(detail) == 0:
            answer += "\n=====================\n图片:\n"
            if msg.answer['图片'] == '':
                print msg.answer['图片']
                answer += '管理员暂时未上传图片,请联系客服获取图片'
            else:
                answer += '图片将在1s后发送给您'
                timer = threading.Timer(1,
                                        tk.send_media,
                                        args=(msg.answer['图片'], open_id))
                timer.start()
            for t in db.title:
                answer += "\n=====================\n" + t + ":\n"
                answer += msg.answer[t]
        for d in detail:
            answer += "\n=====================\n" + d + "\n"
            if msg.answer.has_key(d):
                if t != '图片':
                    answer += msg.answer[t]
                elif msg.answer['图片'] == '':
                    answer += '管理员暂时未上传图片,请联系客服获取图片'
                else:
                    answer += '图片将在1s后发送给您'
                    timer = threading.Timer(1, tk.send_media)
                    timer.start()
            else:
                answer += "关键词错误"
    except Exception as Argument:
        try:
            if content == "subscribe":
                return subscribe_answer
            print Argument
            if user.level == 9:
                answer = "未触发任何指令,您是管理员,是否想执行管理员命令?获取指令信息回复help"
                answer += "正确命令格式为:\n例:110号:查询所有信息 \n110号+图片:查询110号基本信息和图片,并确保您所查询的号数存在"
            else:
                print Argument
                print "未知问题"
                answer = content + "\n我没有理解你的问题,现在正将这条信息转发给客服"
                answer += "正确命令格式为:\n例:110号:查询所有信息 \n110号+图片:查询110号基本信息和图片,并确保您所查询的号数存在"
                msg_f = user.name + "问您:\n" + content
                if user.uid == 9999:
                    msg_f += "\n该用户未成功放入数据库,请注意"
                tk.send_to_manager(msg_f)
            answer += "\n=======================\n"
            answer += "或是直接回复搜索指令关键词:"
            for l in check_list:
                answer += "[%s]" % l
        except Exception as e:
            print e
            log_.warning("消息处理错误:%s" % e)
            answer = e
    logVip(user.name, content, answer)
    return answer
Ejemplo n.º 56
0
def home():
    sess = b.request.session
    dbs = session_maker()
    user = db.get_user(dbs, sess.get('username', None))
    return b.template('home', username=user.username if user else None)
Ejemplo n.º 57
0
def authenticate(username, password):
    user = db.get_user(username)
    if (user and password_utils.verify_password(password, user[2])):
        return True, user[0]
    else:
        return False, None
Ejemplo n.º 58
0
    def post(self, slug):

        user = g.user
        username = user["username"]

        organisation = {}
        organisation["slug"] = slug

        set_active_org_project(slug)

        db_conn = db.get_database_connection()
        with db_conn.cursor() as cursor:
            sql = 'SELECT name, logo FROM organisation WHERE slug=%s'
            cursor.execute(sql, (slug, ))
            result = cursor.fetchone()

        organisation["logo"] = result["logo"]
        organisation["name"] = result["name"]

        with db_conn.cursor() as cursor:
            sql = 'SELECT username ,role FROM belongs_to WHERE slug=%s'
            cursor.execute(sql, (slug, ))
            result = cursor.fetchall()
        _member = []
        for rows in result:
            if rows is not None:
                _member.append(rows)
        organisation["members"] = _member

        with db_conn.cursor() as cursor:
            sql = 'SELECT project_id FROM project WHERE slug=%s'
            cursor.execute(sql, (slug, ))
            result = cursor.fetchall()

        _projects = []
        for rows in result:
            if rows is not None:
                _projects.append(rows["project_id"])
        organisation["projects"] = _projects

        username = request.form.get("username", None)
        if username:
            _username = db.get_user(username)
            if _username is not None:
                db_conn = db.get_database_connection()
                with db_conn.cursor() as cursor:
                    sql = 'SELECT slug, username FROM belongs_to WHERE username=%s and slug=%s'
                    cursor.execute(sql, (
                        username,
                        slug,
                    ))
                    result = cursor.fetchone()
                if result is not None:
                    flash("user is already working in the organisation",
                          "danger")
                    return render_template(
                        'organisation/view_organisation.html',
                        user=user,
                        organisation=organisation,
                        show_results=True)
                else:

                    with db_conn.cursor() as cursor:
                        cursor.execute(
                            "INSERT INTO belongs_to(username,slug,role) Values (%s, %s, %s)",
                            (username, slug, "Member"))
                        db_conn.commit()
                    with db_conn.cursor() as cursor:
                        sql = 'SELECT username, role FROM belongs_to WHERE slug=%s'
                        cursor.execute(sql, (slug, ))
                        result = cursor.fetchall()
                    _member = []
                    for rows in result:
                        if rows is not None:
                            _member.append(rows)
                    organisation["members"] = _member
                    return render_template(
                        'organisation/view_organisation.html',
                        user=user,
                        organisation=organisation,
                        show_results=True)

            else:
                flash("username does not exist", "danger")
                return render_template('organisation/view_organisation.html',
                                       user=user,
                                       organisation=organisation,
                                       show_results=True)

        else:
            flash("Enter username", "danger")
            return render_template('organisation/view_organisation.html',
                                   user=user,
                                   organisation=organisation,
                                   show_results=True)
Ejemplo n.º 59
0
def get_tweets(mps_file,
               mps_db,
               country="UK",
               context_free=False,
               start_date=datetime(2019, 2, 20, 0, 0, 0),
               end_date=datetime.now()):
    """
    retrieve the tweets of the MPs of each country
    :return:
    """
    # create json file to dump tweets
    dir_path = os.path.dirname(os.path.realpath(__file__))
    if country == "UK":
        fname = os.path.join(dir_path, 'json_files',
                             'tweets_%s_to_%s.json' % (start_date, end_date))
    else:  # if country == "GR"
        fname = os.path.join(dir_path, 'json_files',
                             'tweets_anndate_to_%s.json' % end_date)
    with open(fname, 'a'):
        os.utime(fname, None)

    # parse date columns to datetime
    dateparse = lambda x: pd.datetime.strptime(x, '%d/%m/%Y')
    # read mps csv file
    if country == "UK":
        # ip patching
        mps_file = os.path.join(dir_path, mps_file)
        mps = pd.read_csv(mps_file)
        politicians = mps[mps['Screen Name'].str.startswith('@')]
        users_tuples = zip(politicians['Screen Name'], politicians['Party'],
                           [start_date] * politicians.shape[0])
    else:  # if country == "GR"
        meps = pd.read_csv(mps_file,
                           parse_dates=['Announcement date'],
                           date_parser=dateparse)
        politicians = meps[meps['Screen Name'].str.startswith('@')]
        users_tuples = zip(politicians['Screen Name'], politicians['Party'], [
            ann_date.to_pydatetime()
            for ann_date in politicians['Announcement date']
        ])
    for username, party, start_datetime in users_tuples:
        while True:
            try:
                user = api.get_user(screen_name=username)
            except Exception, ex:
                print 'I just caught the exception: %s' % ex
                time.sleep(20)
                continue
            break

        print "Retrieve tweets from MP {} of {} party from {} to {}".format(
            username, party, start_datetime, end_date)
        # # if user exists in db continue
        # if db.get_user(user.id_str, mps_db): continue
        # save user in db
        db_user_id = db.get_user(user.id_str, mps_db) or db.save_user(
            user, mps_db, party, start_datetime, is_mp=True)

        if user.protected: continue
        statuses = []
        # retrieve most recent statuses
        max_id = None
        while True:
            while True:
                try:
                    tmp_statuses = api.user_timeline(screen_name=username,
                                                     count=100,
                                                     tweet_mode="extended",
                                                     max_id=max_id)
                except Exception, ex:
                    print 'I just caught the exception: %s' % ex
                    time.sleep(20)
                    continue
                break

            if max_id is not None:
                # remove duplicate tweet with the id == max_id, because we got it on the previous Search
                tmp_statuses = tmp_statuses[1:]

            for status in tmp_statuses:
                # if the status date is bigger than start date append it
                if start_datetime < status.created_at < end_date:
                    # save status in db
                    status_text = get_text(status._json)
                    if not db.get_tweet(status.id_str, database):
                        db.save_tweet(status,
                                      db_user_id,
                                      mps_db,
                                      text=status_text)
                        statuses.append(status._json)
                    if not context_free:
                        # get all the replies to this tweet and the replies of the replies recursively
                        for reply in get_replies(status):
                            ruser = reply.user
                            ruser_is_mp = "@{}".format(
                                ruser.screen_name) in politicians
                            ruser_party = mps.loc[mps['Screen Name'] == "@{}".format(ruser.screen_name)]["Party"] \
                                if ruser_is_mp else None
                            # save ruser
                            db_ruser_id = db.get_user(ruser.id_str, mps_db) or \
                                          db.save_user(ruser, mps_db, ruser_party, start_datetime, is_mp=ruser_is_mp)
                            # save the reply
                            if not db.get_tweet(reply.id_str, database):
                                print(
                                    "save reply {} from user {} who replies to {}"
                                    .format(reply.id, ruser.screen_name,
                                            reply.in_reply_to_status_id))

                                db.save_tweet(reply, db_ruser_id, mps_db)
                                statuses.append(reply._json)

            if len(tmp_statuses
                   ) == 0 or tmp_statuses[-1].created_at < start_datetime:
                break
            else:
                max_id = tmp_statuses[-1].id
Ejemplo n.º 60
0
def test_get_user_not_exists(user_row):
    assert db.get_user(user_row[0]) is None