Exemplo n.º 1
0
def register(bot, update, args):
	""" Responsible for registering a new user.
	    Test cases handled : 1. Check whether correct number of credentials are entered.
				 2. Check whether this chat id is already registered.
				 3. Check whether the credentials are correct by logging in the college website.
	    Adds the data to database. Note password has to go through enc() which handles encrpytion.
	    Replies either with error_messages or success_message based on outcome. """ 

	chat_id = update.message.chat_id
	try:
		reg_num, pwd = args
	except ValueError:
		logger.info("Incorrect number of credentials by %s",chat_id)
		error_message = "Hmmm.. Is the format correct? It should be in the form : Try again typing\n */register RegisterNo Password*"
		reply(bot,update,error_message)
		return
	reg_status = db.is_registered(chat_id)
	if (reg_status):
		error_message = "Already registered with registration number : {}!\n Use */unregister* to unregister".format(reg_status)
		reply(bot,update,error_message)
		return
	try:
		name = scraper.scrape(reg_num,pwd,'check_registration')
	except:
		error_message = "Are you sure you entered the correct registration/password?"
		reply(bot,update,error_message)
		return
	db.register(chat_id,reg_num,enc(pwd))
	logger.info("Registered %s (%s)",name,reg_num)
	success_message = "Registered *" + name + "*!"
	success_message += "\n\n Delete the message you sent for registering to ensure no one else reads it"
	reply(bot,update,success_message)
	return
Exemplo n.º 2
0
def register(theme):
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        db.register(form.username.data, form.password.data)
        flash(Config.messages["register_success"])
        return redirect(url_for('login'))

    page = Config.pages["register"]
    return render_template("register.jinja", page=page, form=form, theme=theme)
Exemplo n.º 3
0
def register():
    username = request.args["Username"]
    password = request.args['Password']
    blog = request.args['Blog']

    if db.isUser(username):
        flash("user already exists")
        return render_template('form.html', error=True)

    elif db.isUser(username) == False:
        db.register(username, blog, password, "Read")
        return render_template('form.html')
Exemplo n.º 4
0
def add_user(email, password, first_name, last_name, address, city, state,
             zipcode):
    db.connect()
    user = User(email=email,
                password=password,
                first_name=first_name,
                last_name=last_name,
                address=address,
                city=city,
                state=state,
                zipcode=zipcode)
    db.register(user)
    print("You were successfully registered!")
Exemplo n.º 5
0
def registration():
    if request.method == "GET":
        return flask.render_template('registration.html', cities=db.retrieveCities(), states=db.retrieveStates())

    if request.method == "POST":
        insertedUser = request.form['username']
        insertedPass = request.form['password']
        confirmedPass = request.form['confpassword']
        insertedEmail = request.form['email']
        insertedType = request.form['usertype']
        if not insertedUser or not insertedPass or not insertedEmail or not insertedType: return flask.render_template('registration.html', cities=db.retrieveCities(), states=db.retrieveStates(), error="Please Complete All Fields")
        if insertedPass != confirmedPass: return flask.render_template('registration.html', error="Passwords Do Not Match")

        #ensure username and email not already taken
        if db.existsUsername(insertedUser): return flask.render_template('registration.html', cities=db.retrieveCities(), states=db.retrieveStates(), error="Username Already Exists")
        elif db.existsEmail(insertedEmail): return flask.render_template('registration.html', cities=db.retrieveCities(), states=db.retrieveStates(), error="Email Already Exists")

        #parse city official info
        city = request.form['city'].replace('+', ' ')
        state = request.form['state'].replace('+', ' ')
        title = request.form['title']
        if insertedType == 'City Official':
            if not city or not state or not title: return flask.render_template('registration.html', cities=db.retrieveCities(), states=db.retrieveStates(), error="Please fill out all City Official Fields")
            if not db.existsCityState(city, state): return flask.render_template('registration.html', cities=db.retrieveCities(), states=db.retrieveStates(), error="Invalid City State Combination")

        #add to DB
        accepted = db.register(insertedUser, insertedEmail, insertedPass, insertedType)
        if accepted and insertedType == 'City Official': db.addCityOfficial(insertedUser, city, state, title)
        if not accepted: return flask.render_template('registration.html', cities=db.retrieveCities(), states=db.retrieveStates(), error="Registration Failure")
        return flask.redirect('login')
Exemplo n.º 6
0
def register():
    if request.method=='GET':
	return render_template('register.html')
    else:
	data = dict(request.form)
	repassword = data.pop('repassword')
        conditions = [ "%s='%s'" %  (k,v[0]) for k,v in data.items()]

	if data['password'][0]!=repassword[0]:
	    errmsg = 'The two passwords you typed do not match'
	    return render_template('register.html',result = errmsg)
        try:
            db.register(conditions)
            return render_template('register_ok.html')
	except:
            errmsg = "insert failed" 
            return render_template("register.html",result=errmsg)
Exemplo n.º 7
0
def register():
    if request.method == 'GET':
        return render_template('register.html')
    else:
        data = dict(request.form)
        repassword = data.pop('repassword')
        conditions = ["%s='%s'" % (k, v[0]) for k, v in data.items()]

        if data['password'][0] != repassword[0]:
            errmsg = 'The two passwords you typed do not match'
            return render_template('register.html', result=errmsg)
        try:
            db.register(conditions)
            return render_template('register_ok.html')
        except:
            errmsg = "insert failed"
            return render_template("register.html", result=errmsg)
Exemplo n.º 8
0
def register():
    username            = input("Username: "******"Password: "******"Account create sucessfully!\n")
        print("Please choose command 'log' to login into your account")
    else:
        print("Username already exists, please try a different username or login.\n")
Exemplo n.º 9
0
def registerUser():
    if request.method == "POST":
        user = request.form.get('username')
        password = request.form.get('password')

        status, message = register(user, password)

        data = {'status': status, 'message': message}

        return Response(json.dumps(data))
    else:
        return 403
Exemplo n.º 10
0
def register():
    if request.method == 'GET':
        form = RegisterForm()
        return render_template('register.html', form = form)
    else:
        form = RegisterForm()
        if form.validate_on_submit():
            name = form.name.data
            password = form.password.data
            if db.register(name, password):
                return redirect('/')
        return render_template('register.html', form = form)
def register():
    if 'user' in session:
        return redirect(url_for('home',loggedin=True))
    elif request.method == "GET":
        return render_template("register.html",message = "")
    else:
        button = request.form['button'].encode("utf8")
        if button == "Register":
            if db.register(request.form['user'], request.form['pass']):
                session['user'] = request.form['user']
                return redirect(url_for('home',loggedin=True))
            else:
                return render_template("register.html", message = "User already exists. Please login.")
Exemplo n.º 12
0
def cadastro():

    dados = request.get_json(force=True)

    if dados['nome'] != '' and dados['senha'] != '':

        cur = conn.cursor()

        if db.register(dados, cur):
            db.applyCommit(conn)
            return jsonify({"message": "OK"}), 201
        #end if
    #end if
    return jsonify({"message": "Failed"})
Exemplo n.º 13
0
def oshietai():
    if request.method == 'POST':
        item_ids = request.form.getlist('teach_cat')
        item_ids = list(map(int, item_ids))
        print(item_ids)

        # 教えたい側のdbから対応するユーザーidをとってくる
        uid = db.register(item_ids)
        item_names = db.get_item_names(item_ids)
        # 別のページに移動
        return render_template('thanks.html',
                               user_id=uid,
                               item_names=item_names)

    return render_template("checkbox.html", items=db.get_items())
Exemplo n.º 14
0
def register():
    username = request.form['username']
    password = request.form['password']
    address = request.form['address']
    if len(username) < 3:
        flash('Username must be at least 3 characters, try again.')
        return redirect('/')
    elif len(password) < 3:
        flash('Password must be at least 3 characters, try again.')
        return redirect('/')
    try:
        suggest = api.suggest(
            address)  #list of suggestions based on user input
        address = suggest[0]  #sets address to first in suggestions
    except:
        flash('Invalid location, try again.')
        return redirect('/')

    if not db.isUser(username):
        db.register(username, password, address)
        flash('Account successfully created!')
    else:
        flash('Username already taken, try again.')
    return redirect('/')
Exemplo n.º 15
0
def register():
    if 'user' in session:
        return redirect(url_for('home', loggedin=True))
    elif request.method == "GET":
        return render_template("register.html", message="")
    else:
        button = request.form['button'].encode("utf8")
        if button == "Register":
            if db.register(request.form['user'], request.form['pass']):
                session['user'] = request.form['user']
                return redirect(url_for('home', loggedin=True))
            else:
                return render_template(
                    "register.html",
                    message="User already exists. Please login.")
Exemplo n.º 16
0
def regcheck():

    # Getting form data
    if request.method == 'POST':
        form = request.form
        username = form['username']
        password = form['password']

        # Registering User
        try:
            result = db.register(username, password)

            if result:
                # Account creation successful
                message = {
                    "message_type":
                    "success",
                    "message_info":
                    "{0}'s account has been created!".format(username)
                }
                return render_template('login.html', message=message)

            else:
                # Username has been taken
                message = {
                    "message_type":
                    "error",
                    "message_info":
                    "The username {0} has been taken!".format(username)
                }

                return render_template('register.html', message=message)

        except:
            return redirect('/register')

    else:
        return redirect('/register')
Exemplo n.º 17
0
 def install_one_default_driver(self):
     db.clear()
     self.default_db = db.register(self.make_driver("connect_default_only"))
Exemplo n.º 18
0
 def install_two_drivers(self):
     db.clear()
     self.first_db = db.register(self.make_driver("connect_two_first"),
                                 db_name="first")
     self.second_db = db.register(self.make_driver("connect_two_second"),
                                  db_name="second")
Exemplo n.º 19
0
 def install_one_default_driver(self):
     db.clear()
     self.default_db = db.register(self.make_driver("connect_default_only"))
Exemplo n.º 20
0
 def install_one_driver(self):
     db.clear()
     self.only_db = db.register(self.make_driver("connect_one_only"),
                                db_name="only")
Exemplo n.º 21
0
def register(data):
    return db.register(data["username"], data["password"], data["mail"])
Exemplo n.º 22
0
    def run(self):
        #locks for thread which will be used for thread synchronization,break the lock
        #when curent peer(which send request to server) succesfully login or logout
        self.lock = threading.Lock()
        print("Connection from : " + self.ip + " : " + str(self.port))
        print("IP Connected: " + self.ip)

        #handle request from another peer to the server thread
        while True:
            try:
                #waits for incoming message from  peers to registry
                #message form: list with 3 element, first is request type,
                #second is user name, thirst is password
                message = self.tcpClientSocket.recv(1024).decode().split()

                logging.info("Received from " + self.ip + " : " +
                             str(self.port) + " -> " + " ".join(message))
                if len(message) == 0:
                    break
                #Register Message
                if message[0] == 'JOIN':
                    #If the username is exist
                    if db.is_account_exists(message[1]):
                        response = "account already exist"
                        print("From-> " + self.ip + " : " + str(self.port) +
                              " " + response)
                        logging.info("Send to " + self.ip + " : " +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                    else:
                        #If not, create an account
                        db.register(message[1], message[2])
                        response = 'successfully register'
                        logging.info("Send to " + self.ip + " : " +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                #Login Message
                elif message[0] == 'LOGIN':
                    #Handle login using non-exist account
                    if not db.is_account_exists(message[1]):
                        response = "account not exist"
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                    #If account exist, but already online
                    elif db.is_account_online(message[1]):
                        response = 'account is online'
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                    #account exist and not online, handle password
                    else:
                        truePass = db.get_password(message[1])
                        #password correct
                        if truePass == message[2]:
                            self.username = message[1]
                            self.lock.acquire()
                            try:
                                tcpThreads[self.username] = self
                            finally:
                                self.lock.release()

                            db.user_login(message[1], self.ip, str(message[3]))
                            #login succes, so create server thread for this peer,
                            # also set timer for this thread
                            response = 'succesfully login'
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                            self.tcpClientSocket.send(response.encode())
                            self.ServerThread = ServerThread(
                                self.username, self.tcpClientSocket)
                            self.ServerThread.start()
                            self.ServerThread.timer.start()
                        else:
                            response = "incorect password"
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                            self.tcpClientSocket.send(response.encode())

                #param :type. username of logout account
                elif message[0] == 'LOGOUT':
                    #user is online =>removes from online_peers list

                    if len(message) > 1 and message[
                            1] is not None and db.is_account_online(
                                message[1]):
                        db.user_logout(message[1])
                        self.lock.acquire()
                        try:
                            if message[1] in tcpThreads:
                                del tcpThreads[message[1]]
                        finally:
                            self.lock.release()
                        print(self.ip + ":" + str(self.port) +
                              " is logged out")
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " ->  is logout")
                        self.tcpClientSocket.close()
                        self.ServerThread.timer.cancel()
                        break

                    else:
                        self.tcpClientSocket.close()
                        break

            #find online friend
                elif message[0] == 'CHECKONL':
                    if db.is_account_exists(
                            message[1]) and db.is_account_online(message[1]):
                        ListOnlineFriends = db.get_online_friends(message[1])
                        if len(ListOnlineFriends) == 0:
                            response = 'No firend of you are online now'
                        else:
                            response = "list of online friends are "
                            for i in ListOnlineFriends:
                                response += i + " "
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())

                #param: type,username(peer want to add),username(of peer being added)
                elif message[0] == 'ADDFRIEND':
                    if len(message) > 1 and message[1] and message[
                            2] and db.is_account_exists(
                                message[2]) and db.is_account_online(
                                    message[1]):
                        response = db.insert_friend_request(
                            message[2], message[1])
                        if response == 'AlreadyFriend':
                            response = 'You and ' + message[
                                1] + " are already friend"
                        elif response == 'AlreadyAskFriendRequest':
                            response = 'You have sent a request for ' + message[
                                2]
                        else:
                            response = "your request is successfully sending to " + message[
                                2]
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                    else:
                        response = 'user does not exist'
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                # param: type,username (peer THAT ACCEPT),username(peer being ACCEPTED)
                elif message[0] == 'ACCEPTFRIEND':
                    if len(message) > 1 and message[1] and message[
                            2] and db.is_account_exists(
                                message[2]) and db.is_account_online(
                                    message[1]):
                        if db.accept_friend_request(
                                message[1], message[2]) == 'NotInRequest':
                            response = message[2] + "not in your request list"

                        else:
                            db.make_friend(message[1], message[2])
                            response = "accept successfull you and " + message[
                                2] + " are friend"
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                    else:
                        response = 'user does not exist'
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())

                elif message[0] == 'VIEWREQUESTFRIEND':
                    if len(message) > 1 and db.is_account_online(message[1]):
                        ListReFriend = db.get_request_friend(message[1])
                        if len(ListReFriend) == 0:
                            response = "You have no request"
                        else:
                            response = "list of request friends are "
                            for i in ListReFriend:
                                response += i + " "
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                    else:
                        response = 'NotLoginYet'
                        self.tcpClientSocket.send(response.encode())

                elif message[0] == "SEARCH":
                    # checks if an account with the username exists
                    if db.is_account_exists(message[1]):
                        # checks if the account is online
                        # and sends the related response to peer
                        if db.is_account_online(message[1]):
                            peer_info = db.get_peer_ip_port(message[1])
                            response = "search-success " + peer_info[
                                0] + ":" + peer_info[1]
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                            self.tcpClientSocket.send(response.encode())
                        else:
                            response = "search-user-not-online"
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                            self.tcpClientSocket.send(response.encode())
                    # enters if username does not exist
                    else:
                        response = "search-user-not-found"
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())

                elif message[0] == 'CHECKFRIEND':
                    if db.is_account_exists(
                            message[1]) and db.is_account_exists(message[2]):
                        if db.is_account_online(
                                message[1]) and db.is_account_online(
                                    message[2]):
                            if db.Is_Friend(message[1], message[2]):
                                response = 'YES'
                            else:
                                response = 'NO'
                            self.tcpClientSocket.send(response.encode())
                        else:
                            response = 'NOTONL'
                            self.tcpClientSocket.send(response.encode())
                    else:
                        response = 'NOTEX'
                        self.tcpClientSocket.send(response.encode())

            except OSError as oErr:
                pass
Exemplo n.º 23
0
    def POST(self, action):
        if action == "upload_photo":
            # this is to prevent IE from downloading the JSON.
            web.header("Content-Type", "text/plain")
        else:
            web.header("Content-Type", "application/json")
        set_no_cache()

        # check if we have the action
        if action not in self.POST_ACTIONS:
            return error.wrong_action()

        # get the input data if we have the spec
        if action in self.VALIDATE_SPECS:
            d = get_input(self.VALIDATE_SPECS[action])

        # act
        if action == "register":
            return jsond(db.register(d.uid, d.email, d.password))
        elif action == "login":
            u = db.checkLogin(d.uid, d.password)
            if u:
                session.uuid = str(u["_id"])
                return jsond({"uid": u["uid"]})
            else:
                return error.wrong_login()

        # check login
        uuid = session.get("uuid", None)
        if not uuid:
            return error.not_logged_in()

        if action == "follow":
            return jsond(db.follow(uuid, d.uid))

        elif action == "unfollow":
            return jsond(db.unfollow(uuid, d.uid))

        elif action == "publish":
            req = spec.extract(self.EXTRACT_SPECS["publish_request"], d)
            return jsond(db.publish(uuid, **req))

        elif action == "remove":
            req = spec.extract(self.EXTRACT_SPECS["remove_request"], d)
            return jsond(db.remove(uuid, **req))

        elif action == "update_profile":
            u = db.update_profile(uuid, d)
            return jsond(spec.extract(self.EXTRACT_SPECS["current_user"], u))

        elif action == "upload_photo":
            try:
                d = web.input(photo={})
                if "photo" in d:
                    u = db.get_user(uuid)
                    photo.resize_save(u["uid"], d.photo.file)
                    if db.update_photo(uuid, True).has_key("success"):
                        return jsond({"success": 1})
                return error.photo_upload_failed()
            except Exception, e:
                traceback.print_exc()
                return error.photo_upload_failed()
Exemplo n.º 24
0
    def data_received(self, data):
        self.data += data
        # print(chat[self.item]['name'])
        if chat[self.item]['name'] == '':
            if b'login' in self.data:
                x = str(self.data).split(' ')
                # print(x)
                if len(x) == 3 and 'login' in x[0]:  # 处理登录
                    username = x[1]
                    password = x[2]
                    if (db.login(username, password)):
                        chat[self.item]['name'] = username
                        print(chat[self.item]['name'] + ' login')
                        self.transport.write(b'login seccessful')
                    else:
                        self.transport.write(b'username or password not right')

            if b'register' in self.data:  # 处理用户注册
                x = str(self.data).split(' ')
                # print(x)
                if len(x) == 3 and 'register' in x[0]:

                    username = x[1]
                    password = x[2]
                    if (db.register(username, password)):
                        chat[self.item]['name'] = username
                        self.transport.write(b'register seccessful')
                    else:
                        self.transport.write(b'register bad')
                else:
                    print('register bad')

        if chat[self.item]['name'] == '':
            self.transport.write(b'please login  ')
        else:
            if self.data.endswith(b'$'):
                if b':' in self.data:  # 判断是否私聊
                    siliao = self.data.decode()
                    people = siliao.split(':')
                    # print(people[0])
                    # print(chat)
                    for i in chat.keys():
                        try:
                            if chat[i]['name'] == str(people[0]):
                                message = "{}-->".format(
                                    chat[self.item]['name']) + people[1]
                                chat[i]['message'].append(message.encode())
                        except:
                            pass
                else:
                    answer = self.data
                    # chat[self.item]['message'].append(chat[self.item]['name'].encode()+b' : '+answer)
                    # print(chat)
                    chat['all']['message'].append(
                        chat[self.item]['name'].encode() + b' : ' + answer)
            else:
                for i in chat['all']['message']:
                    self.transport.write(i)
                for i in chat[self.item]['message']:
                    self.transport.write(i)
                    print(i + b'\n')
        # print(self.data)

        self.data = b''
Exemplo n.º 25
0
    def run(self):
        # locks for thread which will be used for thread synchronization
        self.lock = threading.Lock()
        print("Connection from: " + self.ip + ":" + str(port))
        print("IP Connected: " + self.ip)

        while True:
            try:
                # waits for incoming messages from peers
                message = self.tcpClientSocket.recv(1024).decode().split()
                logging.info("Received from " + self.ip + ":" +
                             str(self.port) + " -> " + " ".join(message))
                #   JOIN    #
                if message[0] == "JOIN":
                    # join-exist is sent to peer,
                    # if an account with this username already exists
                    if db.is_account_exist(message[1]):
                        response = "join-exist"
                        print("From-> " + self.ip + ":" + str(self.port) +
                              " " + response)
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                    # join-success is sent to peer,
                    # if an account with this username is not exist, and the account is created
                    else:
                        db.register(message[1], message[2])
                        response = "join-success"
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                #   LOGIN    #
                elif message[0] == "LOGIN":
                    # login-account-not-exist is sent to peer,
                    # if an account with the username does not exist
                    if not db.is_account_exist(message[1]):
                        response = "login-account-not-exist"
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                    # login-online is sent to peer,
                    # if an account with the username already online
                    elif db.is_account_online(message[1]):
                        response = "login-online"
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                    # login-success is sent to peer,
                    # if an account with the username exists and not online
                    else:
                        # retrieves the account's password, and checks if the one entered by the user is correct
                        retrievedPass = db.get_password(message[1])
                        # if password is correct, then peer's thread is added to threads list
                        # peer is added to db with its username, port number, and ip address
                        if retrievedPass == message[2]:
                            self.username = message[1]
                            self.lock.acquire()
                            try:
                                tcpThreads[self.username] = self
                            finally:
                                self.lock.release()

                            db.user_login(message[1], self.ip, message[3])
                            # login-success is sent to peer,
                            # and a udp server thread is created for this peer, and thread is started
                            # timer thread of the udp server is started
                            response = "login-success"
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                            self.tcpClientSocket.send(response.encode())
                            self.udpServer = UDPServer(self.username,
                                                       self.tcpClientSocket)
                            self.udpServer.start()
                            self.udpServer.timer.start()
                        # if password not matches and then login-wrong-password response is sent
                        else:
                            response = "login-wrong-password"
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                            self.tcpClientSocket.send(response.encode())
                #   LOGOUT  #
                elif message[0] == "LOGOUT":
                    # if user is online,
                    # removes the user from onlinePeers list
                    # and removes the thread for this user from tcpThreads
                    # socket is closed and timer thread of the udp for this
                    # user is cancelled
                    if len(message) > 1 and message[
                            1] is not None and db.is_account_online(
                                message[1]):
                        db.user_logout(message[1])
                        self.lock.acquire()
                        try:
                            if message[1] in tcpThreads:
                                del tcpThreads[message[1]]
                        finally:
                            self.lock.release()
                        print(self.ip + ":" + str(self.port) +
                              " is logged out")
                        self.tcpClientSocket.close()
                        self.udpServer.timer.cancel()
                        break
                    else:
                        self.tcpClientSocket.close()
                        break
                #   SEARCH  #
                elif message[0] == "SEARCH":
                    # checks if an account with the username exists
                    if db.is_account_exist(message[1]):
                        # checks if the account is online
                        # and sends the related response to peer
                        if db.is_account_online(message[1]):
                            peer_info = db.get_peer_ip_port(message[1])
                            response = "search-success " + peer_info[
                                0] + ":" + peer_info[1]
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                            self.tcpClientSocket.send(response.encode())
                        else:
                            response = "search-user-not-online"
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                            self.tcpClientSocket.send(response.encode())
                    # enters if username does not exist
                    else:
                        response = "search-user-not-found"
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
            except OSError as oErr:
                logging.error("OSError: {0}".format(oErr))
Exemplo n.º 26
0
    def run(self):
        # locking the thread 
        self.lock = threading.Lock()
        print("Connection from: " + self.IPAddr + ":" + str(self.portAddr))
        print("IP Connected: " + self.IPAddr)
        
        while True:
            try:
                # message incoming from the peer
                message = self.tcpClientSocket.recv(1024).decode().split()
                # if JOIN recieved  #
                if message[0] == "JOIN":
                    # if account exists 
                    # then account-exists is send as reponse
                    if db.is_account_exist(message[1]):
                        response = "account-exist"
                        self.tcpClientSocket.send(response.encode())
                    
                    # if account doesn't exists
                    # account created and account success message is sent
                    else:
                        db.register(message[1], message[2], " ".join(message[3:])) #messagep[3] status
                        response = "account-success"
                        self.tcpClientSocket.send(response.encode())
                # if CHANGE recieved  #
                elif message[0] == "CHANGE":
                    # if account exist 
                    # status changed mssg is sent 
                    if db.is_account_exist(message[1]):
                        db.update_status(message[1]," ".join(message[2:]))
                        response = "status-changed"
                        self.tcpClientSocket.send(response.encode())
                # if GET recieved  #
                elif message[0] == "GET":
                    # if account exists
                    # current status is sent as mssg
                    if db.is_account_exist(message[1]):
                        status = db.get_status(message[1])
                        self.tcpClientSocket.send(status.encode())
                # if LOGIN recieved  #
                elif message[0] == "LOGIN":
                    # if no account exist with the given username 
                    # flag is sent to the peer
                    if not db.is_account_exist(message[1]):
                        response = "Account-not-exist"
                        self.tcpClientSocket.send(response.encode())
                    # if an account is already online with given username
                    # flag is sent
                    elif db.is_account_online(message[1]):
                        response = "Account-online"
                        self.tcpClientSocket.send(response.encode())
                    # if an account is log in successfully 
                    # extracts the password from the string
                    else:
                        # checks the password from looking into database
                        retrievedPass = db.get_password(message[1])
                        if retrievedPass == message[2]:
                            self.username = message[1]
                            self.lock.acquire()
                            try:
                                tcpThreads[self.username] = self
                            finally:
                                self.lock.release()

                            db.user_login(message[1], self.IPAddr, message[3])
                            # login-success is sent to the peer and udp thread is started to 
                            # watch the time
                            response = "Account-success"
                            self.tcpClientSocket.send(response.encode())
                            # udp server created
                            self.udpServer = UDPServer(self.username, self.tcpClientSocket)
                            # udp server started 
                            self.udpServer.start()
                            # start the timer of udp
                            self.udpServer.timer.start()
                        # if wrong password then flag is sent
                        else:
                            response = "Wrong-password" 
                            self.tcpClientSocket.send(response.encode())
                #   if LOGOUT recieved  #
                elif message[0] == "LOGOUT":
                    # if user logouts removes usre from the online list of peer
                    # thread removed from the list and socket is closed
                    # timer udp thread cancels 
                    if len(message) > 1 and message[1] is not None and db.is_account_online(message[1]):
                        db.user_logout(message[1])
                        # lock acquired 
                        self.lock.acquire()
                        try:
                            if message[1] in tcpThreads:
                                # removes thread form the list
                                del tcpThreads[message[1]]
                        finally:
                            # lock released
                            self.lock.release()
                        self.tcpClientSocket.close()
                        self.udpServer.timer.cancel()
                        break
                    else:
                        self.tcpClientSocket.close()
                        break
                #   if SEARCH recieved  #
                elif message[0] == "SEARCH":
                    # checks for accounts existsence
                    if db.is_account_exist(message[1]):
                        # if account is online search success is send
                        if db.is_account_online(message[1]):
                            peer_info = db.get_peer_ip_port(message[1])
                            response = "Success " + peer_info[0] + ":" + peer_info[1]
                            self.tcpClientSocket.send(response.encode())
                        # else user not online is send
                        else:
                            response = "User-not-online"
                            self.tcpClientSocket.send(response.encode())
                    # if no user with given name is found serach user not found is sent
                    else:
                        response = "User-not-found"
                        self.tcpClientSocket.send(response.encode())
            except OSError as oErr:
                pass 
Exemplo n.º 27
0
 def install_two_drivers(self):
     db.clear()
     self.first_db = db.register(self.make_driver("connect_two_first"),
                                 db_name="first")
     self.second_db = db.register(self.make_driver("connect_two_second"),
                                  db_name="second")
Exemplo n.º 28
0
    def POST(self, action):
        if action == 'upload_photo':
            # this is to prevent IE from downloading the JSON.
            web.header('Content-Type', 'text/plain')
        else:
            web.header('Content-Type', 'application/json')
        set_no_cache()

        # check if we have the action
        if action not in self.POST_ACTIONS:
            return error.wrong_action()

        # get the input data if we have the spec
        if action in self.VALIDATE_SPECS:
            d = get_input(self.VALIDATE_SPECS[action])

        # act
        if action == 'register':
            return jsond(db.register(d.uid, d.email, d.password))
        elif action == 'login':
            u = db.checkLogin(d.uid, d.password)
            if u:
                session.uuid = str(u['_id'])
                return jsond({'uid': u['uid']})
            else:
                return error.wrong_login()

        # check login
        uuid = session.get('uuid', None)
        if not uuid:
            return error.not_logged_in()

        if action == 'follow':
            return jsond(db.follow(uuid, d.uid))

        elif action == 'unfollow':
            return jsond(db.unfollow(uuid, d.uid))

        elif action == 'publish':
            req = spec.extract(self.EXTRACT_SPECS['publish_request'], d)
            return jsond(db.publish(uuid, **req))

        elif action == 'remove':
            req = spec.extract(self.EXTRACT_SPECS['remove_request'], d)
            return jsond(db.remove(uuid, **req))

        elif action == 'update_profile':
            u = db.update_profile(uuid, d)
            return jsond(spec.extract(self.EXTRACT_SPECS['current_user'], u))

        elif action == 'upload_photo':
            try:
                d = web.input(photo={})
                if 'photo' in d:
                    u = db.get_user(uuid)
                    photo.resize_save(u['uid'], d.photo.file)
                    if db.update_photo(uuid, True).has_key('success'):
                        return jsond({'success': 1})
                return error.photo_upload_failed()
            except Exception, e:
                traceback.print_exc()
                return error.photo_upload_failed()
Exemplo n.º 29
0
def register(login: str, password: str):
    try:
        db.register(login, password)
    except db.UserAlreadyExists:
        print('User with this login already exists.')
Exemplo n.º 30
0
 def install_one_driver(self):
     db.clear()
     self.only_db = db.register(self.make_driver("connect_one_only"),
                                db_name="only")
Exemplo n.º 31
0
 def testB(self):
     result = db.register(tests.username, tests.password)
     self.assertFalse(result)
Exemplo n.º 32
0
    def run(self):
        #locks for thread which will be used for thread synchronization,break the lock
        #when curent peer(which send request to server) succesfully login or logout
        self.lock = threading.Lock()
        print("Connection from : " + self.ip + " : " + str(self.port))
        print("IP Connected: " + self.ip)

        #handle request from another peer to the server thread
        while True:
            try:
                #waits for incoming message from  peers to registry
                #message form: list with 3 element, first is request type,
                #second is user name, thirst is password
                message = self.tcpClientSocket.recv(1024).decode().split()
                logging.info("Received from " + self.ip + " : " +
                             str(self.port) + " -> " + " ".join(message))
                #Register Message
                if message[0] == 'JOIN':
                    #If the username is exist
                    if db.is_account_exists(message[1]):
                        response = "account already exist"
                        print("From-> " + self.ip + " : " + str(self.port) +
                              " " + response)
                        logging.info("Send to " + self.ip + " : " +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                    else:
                        #If not, create an account
                        db.register(message[1], message[2])
                        response = 'successfully register'
                        logging.info("Send to " + self.ip + " : " +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                #Login Message
                elif message[0] == 'LOGIN':
                    #Handle login using non-exist account
                    if not db.is_account_exists(message[1]):
                        response = "account not exist"
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                    #If account exist, but already online
                    elif db.is_account_online(message[1]):
                        response = 'account is online'
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())
                    #account exist and not online, handle password
                    else:
                        truePass = db.get_password(message[1])
                        #password correct
                        if truePass == message[2]:
                            self.username = message[1]
                            self.lock.acquire()
                            try:
                                tcpThreads[self.username] = self
                            finally:
                                self.lock.release()

                            db.user_login(message[1], self.ip, self.port)
                            #login succes, so create server thread for this peer,
                            # also set timer for this thread
                            response = 'succesfully login'
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                            self.tcpClientSocket.send(response.encode())
                            self.ServerThread = ServerThread(
                                self.username, self.tcpClientSocket)
                            self.ServerThread.start()
                            self.ServerThread.timer.start()
                        else:
                            response = "incorect password"
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                            self.tcpClientSocket.send(response.encode())

                elif message[0] == 'LOGOUT':
                    #user is online =>removes from online_peers list

                    if len(message) > 1 and message[
                            1] is not None and db.is_account_online(
                                message[1]):
                        db.user_logout(message[1])
                        self.lock.acquire()
                        try:
                            if message[1] in tcpThreads:
                                del tcpThreads[message[1]]
                        finally:
                            self.lock.release()
                        print(self.ip + ":" + str(self.port) +
                              " is logged out")
                        self.tcpClientSocket.close()
                        self.ServerThread.timer.cancel()
                        break

                    else:
                        self.tcpClientSocket.close()
                        break

                #check if an arbitary user is online or not
                elif message[0] == 'CHECKONL':
                    if db.is_account_exists(message[1]):
                        if db.is_account_online(message[1]):
                            peer_info = db.get_peer_ip_port(message[1])
                            response = "search successfull " + peer_info[
                                0] + ":" + peer_info[1]
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                            self.tcpClientSocket.send(response.encode())

                        else:
                            response = 'user does not online'
                            logging.info("Send to " + self.ip + ":" +
                                         str(self.port) + " -> " + response)
                            self.tcpClientSocket.send(response.encode())

                    else:
                        response = "search-user-not-found"
                        logging.info("Send to " + self.ip + ":" +
                                     str(self.port) + " -> " + response)
                        self.tcpClientSocket.send(response.encode())

            except OSError as oErr:
                logging.error("OSError: {0}".format(oErr))
Exemplo n.º 33
0
def process(addr, msg):
    global RESPONSE
    print(addr + ":" + str(msg))

    j = json.loads(msg)

    try:
        if (j["type"] == "register"):
            username = j["from"]["username"]
            password = j["from"]["password"]
            db.register(username, password)
        elif (j["type"] == "check_available"):
            username = j["from"]["username"]
            RESPONSE = str(db.check_available(username))
            sthread = Thread(target=send)
            sthread.start()
            sthread.join()
        elif (j["type"] == "login"):
            username = j["from"]["username"]
            password = j["from"]["password"]
            ip = addr
            RESPONSE = db.login(username, password, ip)
            sthread = Thread(target=send)
            sthread.start()
            sthread.join()
        elif (j["type"] == "logout"):
            db.logout(j["from"]["id"])
        elif (j["type"] == "get_online"):
            id = j["from"]["id"]
            RESPONSE = db.get_online_list()
            result = []
            for i in RESPONSE:
                if (i.id != id):
                    line = {"userID": i.id, "username": i.username, "ip": i.ip}
                    result.append(line)

            RESPONSE = {"online_users": []}
            RESPONSE["online_users"] = result
            RESPONSE = json.dumps(RESPONSE)
            sthread = Thread(target=send)
            sthread.start()
            sthread.join()
        elif (j["type"] == "send_message"):
            f = j["from"]["username"]
            t = j["to"]["username"]
            m = j["message"]

            db.set_message(f, t, m)
        elif (j["type"] == "receive_message"):
            f = j["from"]["username"]
            t = j["to"]["username"]

            RESPONSE = db.get_message(f, t)
            sthread = Thread(target=send)
            sthread.start()
            sthread.join()
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)
        print(e)

    return 0