예제 #1
0
def parseCreation(jpost):
	if not isValid_Creation(jpost):
		# print "Creation update went wrong. Not updated."
		return False

	responders = list(set(jpost["responders"]))  # removes duplicates
	# make sure all responders exist in database
	inviteUsers(responders)

	netid = jpost["netid"]

	# print(responders[0]);
	title = jpost["title"]
	# remove quotations from titles
	title = title.replace("'", "")
	title = title.replace('"', '')
	creatorId = db.getUser(netid).uid
	respondingIds = str([db.getUser(responder).uid for responder in responders])
	creationDate = jpost["creationDate"]

	meeting = db.createMeeting(title, creatorId, respondingIds, creationDate)
	db.createResponse(meeting.mid, creatorId, str(jpost["response"]))

	sendCreationEmail(title, netid, responders)
	
	if db.getNotRespondedNetids(meeting.mid) == []:
		db.updateMeeting(meeting.mid, allResponded=True)
	return True
예제 #2
0
    def __init__(self, username):
        avatar.ConchUser.__init__(self)
        self.username = username
        self.listeners={}
        self.pubkey = PublicKeyCredentialsChecker.instance.getKey(username)
        self.isannon =  PublicKeyCredentialsChecker.instance.isAnnon(username) 

        self.channelLookup.update({
                'session':session.SSHSession,
                'direct-tpcip': openConnectForwardingClient
        })
        
        if self.isannon:
            if config["ANNONYMOUS_TIMEOUT"] > 0:
                repeater=LoopingCall(AnnonTimeout, user=self)
                repeater.kw['loop']=repeater
                repeater.start(config["ANNONYMOUS_TIMEOUT"]*MINUTES, now=False)
        
        if not database.getUser(key=self.pubkey):
            database.createUser(key=self.pubkey, 
                                username=self.username, 
                                enabled=not self.isannon)
        # log user logged in
        database.updateUserLastLogin(key=self.pubkey)
        ForwardUser.loggedin[self]=time()
 def load(self):
   data = database.getUser(self)
   if data:
     self.username = data['username']
     self.tags = data['tags']
     self.followed = data['followed']
     self.untagged = data['untagged']
예제 #4
0
 def event_JOIN(self, packet):
     if not packet['name']:
         return self.kick('Invalid Nickname!')
     if packet['version'] != self.server.version:
         return self.kick("Protocol mismatch! (You have %s and we have %s)" % (packet['version'], self.server.version))
     if self.server.findByName(packet['name'].lower()):
         return self.kick('A user with that name is already joined!')
     self.cid = self.server.addClient(self)
     if self.cid != -1:
         self.player = Player(eid=self.cid, name=packet['name'], pos=self.server.worlds[1].start.dump())
         self.hasConnected = True #This is really used for rmv objects. Dont move it plz!
         obj = database.getUser(self, packet['hash'])
         if type(obj) is str:
             self.kick(obj)
         elif obj is not None:
             self.dbid = obj.id
             self.player.pos = Location().loads(obj.pos)
             for world in self.server.worlds.values():
                 self.send({'action':'WORLD', 'obj':world.dump()})
             self.send({'action':'JOIN', 'id':self.cid, 'obj':self.player.dump(), 'hash':obj.hashkey})
             self.waitForInfo = True
         else:
             self.kick('Join Error!')
     else:
         return self.kick('Server is full!')
예제 #5
0
def isValid_Creation(jpost):
	creationFields   = ["category",
						"title", 
						"netid", 
						"response", 
						"responders", 
						"creationDate"]

	for key in creationFields:
		if key not in jpost:
			return False

	if not isinstance(jpost["title"], basestring):
		return False
	if not isinstance(jpost["netid"], basestring):
		return False
	if not datetimes_isValid(jpost["response"]):
		return False
	if not responders_isValid(jpost["responders"]):
		return False
	if not date_isValid(jpost["creationDate"]):
		return False

	if len(jpost["title"]) > 120:
		return False
	if db.getUser(jpost["netid"]) is None:
		return False
		
	# print "creation ok"
	return True
예제 #6
0
    def __init__(self, username):
        avatar.ConchUser.__init__(self)
        self.username = username
        self.listeners = {}
        self.pubkey = PublicKeyCredentialsChecker.instance.getKey(username)
        self.isannon = PublicKeyCredentialsChecker.instance.isAnnon(username)

        self.channelLookup.update({
            'session': session.SSHSession,
            'direct-tpcip': openConnectForwardingClient
        })

        if self.isannon:
            if config["ANNONYMOUS_TIMEOUT"] > 0:
                repeater = LoopingCall(AnnonTimeout, user=self)
                repeater.kw['loop'] = repeater
                repeater.start(config["ANNONYMOUS_TIMEOUT"] * MINUTES,
                               now=False)

        if not database.getUser(key=self.pubkey):
            database.createUser(key=self.pubkey,
                                username=self.username,
                                enabled=not self.isannon)
        # log user logged in
        database.updateUserLastLogin(key=self.pubkey)
        ForwardUser.loggedin[self] = time()
예제 #7
0
    def requestAvatarId(self, credentials):
        print "requestAvatarId", credentials.username
        user = database.getUser(key=credentials.blob)
        if user:
            if not user['enabled']:
                return failure.Failure(
                    error.ConchError("User account not enabled"))

            if not credentials.signature:
                return failure.Failure(error.ValidPublicKey())

            pubKey = keys.Key.fromString(credentials.blob).keyObject
            if keys.verifySignature(pubKey, credentials.signature,
                                    credentials.sigData):
                print "login as %s" % credentials.username
                database.updateUserName(credentials.blob, credentials.username)
                return credentials.username
            else:
                return failure.Failure(error.ConchError("Incorrect signature"))

        elif config['ALLOW_ANNONYMOUS']:
            print "login as ANONYMOUS"
            user = "".join(Random().sample(string.letters, 30))
            self.annons[user] = credentials.blob
            return user

        return failure.Failure(error.ConchError("Not allowed"))
예제 #8
0
    def requestAvatarId(self, credentials):
        print "requestAvatarId", credentials.username
        user = database.getUser(key=credentials.blob)
        if user:
            if not user['enabled']:
                return failure.Failure(
                               error.ConchError("User account not enabled"))
            
            if not credentials.signature:
                return failure.Failure(error.ValidPublicKey())
            
            pubKey = keys.Key.fromString(credentials.blob)
            if pubKey.verify(credentials.signature,
                    credentials.sigData):
                print "login as %s" % credentials.username
                database.updateUserName(credentials.blob, credentials.username)
                return credentials.username
            else:
                return failure.Failure(
                    error.ConchError("Incorrect signature"))

        elif config['ALLOW_ANNONYMOUS']:
            print "login as ANONYMOUS"
            user = "".join(Random().sample(string.letters,30))
            self.annons[user] = credentials.blob
            return user
        
        return failure.Failure(error.ConchError("Not allowed"))
예제 #9
0
def signup():
    if request.method == "GET":
        return render_template("signup.html")
    else:
        email = request.form['email']
        pword = request.form['pword']

        if email == '' or email.find('@') != -1:
            return render_template("signup.html", msg = 'Please enter your stuy.edu email')
        if len(pword) < 8:
            return render_template("signup.html", msg = 'Please enter a password that is at least 8 characters long')
        m = sha256()
        m.update(pword)
        passwordHash = m.hexdigest()

        print "password hashed"

        message = database.addUser(email, passwordHash)

        print "user added to database"
        if (message == ''):
            user = database.getUser(email)
            data = urlencode({'email': user['email'], '_id': user['_id']})
            activateLink = website_url + '/activate?%s' %(data)

            s = smtplib.SMTP('smtp.gmail.com', 587)
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login(ourEmail, ourPassword)

            #Sets up the multipart object
            message = MIMEMultipart()
            message['Subject'] = 'Getting started with StuyBooks'
            message['From'] = ourEmail
            message['To'] = email + '@stuy.edu'

            text = '''
            Hello,

            Thanks for signing up with StuyBooks!
            Click on this link to activate your account: %s
            If you did not register for StuyBooks, contact us at %s

            Disclaimer: Stuy-books is a platform to meet and trade with other students. Stuy-books and associates are not liable for any damages, infringements, or other inappropriate usage of our service. Please be respectful of others. Any violation of school regulation can and will be reported to the administration. Thank you.

            Sincerely,
            Team JASH''' %(activateLink , ourEmail)
            #Attaches the message
            message.attach(MIMEText(text, 'plain'))

            s.sendmail(ourEmail, email + '@stuy.edu', message.as_string())
            s.close()

            return render_template("signup.html", msg = "A confirmation email has been sent to " + email + '@stuy.edu')

        return render_template("signup.html", msg = message)
예제 #10
0
def conversation_handler(bot, update):
    """Handler function to call the correct function depending on the estimated intent
    of the message.
    @param {Bot} bot
    @param {update} update"""
    currentTime = int(time())
    message = update.message.text
    intent = identify_intent(message)
    userDetails = getUser(update.message.chat.id)

    class Person:
        def __init__(self):
            self.id = userDetails['UserID']
            self.first_name = userDetails['FirstName']
            self.last_name = userDetails.get('LastName', '')
            self.age = userDetails.get('Age', 0)
            self.context = userDetails.get('Context', 0)
            self.stage = userDetails.get('Stage', 0)
            self.last_message = userDetails.get('LastMessage', 0)
            self.suggested_film = userDetails.get('SuggestedFilm', 0)
            self.suggested_film_index = userDetails.get(
                'SuggestedFilmIndex', 0)
            self.previous_context = userDetails.get('PreviousContext', 0)
            self.previous_stage = userDetails.get('PreviousStage', 0)
            favouriteGenres = getFavouriteGenres(userDetails['UserID'])
            for genre in favouriteGenres:
                if genre.get('Order', 0) == 1:
                    self.favouriteGenre = genre.get('Name', 0)
                elif genre.get('Order', 0) == 2:
                    self.secondFavouriteGenre = genre.get('Name', 0)
                elif genre.get('Order', 0) == 3:
                    self.thirdFavouriteGenre = genre.get('Name', 0)

    User = Person()
    db.setLastMessage(User.id, currentTime)
    NewConversation = calculate_if_new_conversation(User, intent, currentTime)
    db.insertMessage(User.id, message, currentTime, intent, User.context,
                     User.stage, NewConversation)
    if User.context == contexts['InitialUserRegistration']:
        registrationHandler(bot, update, User)
    elif User.context == contexts['FilmReview']:
        filmReviewHandler(bot, update, User)
    elif intent == 1:
        greetingsMessage(bot, update)
    elif intent == 2:
        moodMessage(bot, update)
    elif User.context == contexts['FilmSuggestion'] or intent == 3:
        FilmSuggestionHandler(bot, update, User)
    else:
        bot.send_message(chat_id=update.message.chat_id,
                         text="Sorry I don't understand what you said.")
        bot.send_message(
            chat_id=update.message.chat_id,
            text=
            "I currently can suggest films, review films and talk about my day!"
        )
예제 #11
0
def searchForBook(query):
    '''
    Looks up a list book given a simple search query (no logical operators)
    Args:
        query (string)
    Returns:
        A list of books with that name/author
    '''
    db = client['books-database']
    books = db['books'] #collection

    #parse query to find relevant results
    results = []
    query = query.strip(',')
    query = query.split(' ')
    for j in range(len(query)): #goes through query

        # goes through database to find books with query[j] in substring value
        cursor = books.find( {'bookName':
                              { '$regex' : '(?i).*' + query[j] + '.*' } } )
        for b in cursor:
            if not b in results:
                results.append( b )
                #break; #goes to next book

        cursor = books.find( {'author':
                      { '$regex' : '(?i).*' + query[j] + '.*' } } )
        for b in cursor:
            if not b in results:
                results.append( b )
                #break; #goes to next book

        cursor = books.find( {'isbn':
                              { '$regex' : '.*' + query[j] + '.*' } } )
        for b in cursor:
            if not b in results:
                results.append( b )
                #break; #goes to next book

    #deletes non-available entries
    results = [ book for book in results if book['status'] == 'available' ]

    # set confidence values for each user based on book
    # set's a book's rating based on user's current rating
    for i in results:
        user = database.getUser( i['email'] )
        currentRating = confidence( i )
        user['rating'] = currentRating
        i['search_priority'] = currentRating

    # sort results based on confidence values
    quick_sort( results )

    print results

    return results
예제 #12
0
def getUser(name, create=True):
    dbEntry = database.getUser(name)
    if not dbEntry:
        if not create:
            return userState(None)
        # Create a new database entry for us
        dbEntry = database.createUser(name)
        if not dbEntry:
            raise AssertionError(
                "User still doesn't exist after just creating it????")
    return userState(dbEntry)
예제 #13
0
def login():
    data = request.get_json()
    username = data['username']
    password = data['password']

    result = userLogin(username, password)

    if result:
        session['user_id'] = result[0]
        uName = getUser(session['user_id'])
        return {'errcode': 0, 'errmsg': '登陆成功', 'temp': uName}, 200

    return {'errcode': 401, 'errmsg': '用户不存在或密码错误'}, 401
예제 #14
0
def isValid_Response(jpost):
	responseFields   = ["category", "mid", "netid", "response"]

	for key in responseFields:
		if key not in jpost:
			return False

	if not isinstance(jpost["mid"], int):
		return False
	if not isinstance(jpost["netid"], basestring):
		return False
	if not datetimes_isValid(jpost["response"]):
		return False

	if db.getUser(jpost["netid"]) is None:
		return False		
	if db.getMeeting(jpost["mid"]) is None:
		return False
	if db.getResponse(jpost["mid"], db.getUser(jpost["netid"]).uid) is not None:
		return False
		
	# print "response ok"
	return True
예제 #15
0
def get_user_name():
    name = request.args.get('name')
    limit = request.args.get('limit')
    offset = request.args.get('offset')

    if limit is not None and not function.isInt(limit):
        return jsonify({"error": "limit is not an integer"}), 400
    if offset is not None and not function.isInt(offset):
        return jsonify({"error": "offset is not an integer"}), 400

    data = database.getUser(name, limit, offset)
    if data is not None:
        return jsonify(data), 200
    else:
        return jsonify({"error": "No results found"}), 404
예제 #16
0
def forgot():
    if request.method == 'GET':
        return render_template("forgot.html")
    else:

        email = request.form.get('email')
        if email == None:
            return render_template("forgot.html", msg = 'You must enter your email!')
        if database.getUser(email) == None:
            return render_template("forgot.html", msg = 'That is an invalid email!')

        randomGen = os.urandom(64).encode('base-64') #just for something random
        database.setReset(email, randomGen)

        data = urlencode(randomGen)
        link = website_url + '/change?reset=%s' %(data)

        s = smtplib.SMTP('smtp.gmail.com', 587)
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(ourEmail, ourPassword)

        #Sending the seller an email
        message = MIMEMultipart('alternative')
        message['Subject'] = 'Reset password'
        message['From'] = ourEmail
        message['To'] = email

        text = '''Hello,\n\nYou indicated that you have forgotten your password.\nClick on this link to reset your password: %s\n\nYours,\nTeam JASH''' %(email, link)
        html = '''
        <html>
            <body>
                <p>Hello,<br><br>
                You indicated that you have forgotten your password.<br>
                <a href=%s>Click to reset</a> <br><br>
                Yours,<br>
                Team JASH
        ''' %(link)

        textcomp = MIMEText(text, 'plain')
        htmlcomp = MIMEText(html, 'html')
        message.attach(textcomp)
        message.attach(htmlcomp)
        s.sendmail(ourEmail, email, message.as_string())
        s.close()

        return redirect(url_for('home'))
예제 #17
0
def parseResponse(jpost):
	if not isValid_Response(jpost):
		# print "Response update went wrong. Not updated."
		return False

	mid = jpost["mid"]

	netid = jpost["netid"]
	# This is not actually the creator id this is the respondedid
	creatorId = db.getUser(netid).uid

	db.createResponse(mid, creatorId, str(jpost["response"]))
	if db.getNotRespondedNetids(mid) == []:
		db.updateMeeting(mid, allResponded=True)
		sendAllRespondedEmail(db.getMeeting(mid).title, db.getUserFromId(db.getMeeting(mid).creatorId).netid)
	return True
예제 #18
0
def isValid_Preference(jpost):
	preferenceFields = ["category", "netid", "preferredTimes"]

	for key in preferenceFields:
		if key not in jpost:
			return False

	if not isinstance(jpost["netid"], basestring):
		return False
	if not daytimes_isValid(jpost["preferredTimes"]):
		return False

	if db.getUser(jpost["netid"]) is None:
		return False	

	# print "preference ok"
	return True
예제 #19
0
def parseDecision(jpost):
	if not isValid_Decision(jpost):
		# print "Final Time update went wrong. Not updated."
		return False

	mid = jpost["mid"]

	netid = jpost["netid"]
	creatorId = db.getUser(netid).uid
	finalTime = str(jpost["finalTime"])

	if db.getNotRespondedNetids(mid) == []:
		db.updateMeeting(mid, allResponded=True, scheduledTime=finalTime)
	else:
		db.updateMeeting(mid, scheduledTime=finalTime)
	# Doesn't necessarily work since the respondedNetids is everyone that responded, but not everyone invited
	sendFinalTimeEmail(db.getMeeting(mid).title, netid, db.getRespondedNetids(mid), jpost["finalTime"][0])
	return True
예제 #20
0
파일: login.py 프로젝트: CoreBB/CoreBB
def page():
    if "login" in session:
        return redirect("/")

    if request.method == "POST":
        username = request.form['username']
        password = protect(request.form['password'])

        check = database.getUser(username)
        if not check:
            flash("Username invalid")
            return redirect("/login/")
        elif check['password'] != password:
            flash("Password invalid")
            return redirect("/login/")
        else:
            session['login'] = username
            return redirect("/")


    return render_template("login.html")
예제 #21
0
def connect():
    data = {
        'username': '******',
        'password': '******',
        'account_id': '86444b4a-cb69-4078-96bd-c577e324e886'
    }
    js = json.dumps(data)

    resp = Response(js, status=200, mimetype='application/json')
    resp.headers['Link'] = 'https://api.truevault.com/v1/auth/login'
    list = database.getRecvEmail(db, "Kristina")
    print(list)
    recv_list = []
    for item in list:
        user = database.getUser(db, item["sender"])
        recv_list.append(
            Sent_Emails(user["name"], item["receiver"], item["document_id"],
                        item["provider"], item["subject"], item["vault_id"]))
    log_file = open("log.txt", "a")
    log_file.write("User viewed incoming mailbox at %s\n" %
                   datetime.datetime.now())
    return render_template('index.html', result=recv_list)
예제 #22
0
def isValid_MeetingDelete(jpost):
	meetingDeleteFields = ["category", "mid", "netid"]
	for key in meetingDeleteFields:
		if key not in jpost:
			return False

	if not isinstance(jpost["netid"], basestring):
		return False
	if not isinstance(jpost["mid"], int):
		return False

	if db.getUser(jpost["netid"]) is None:
		return False	

	# check if netid is the creator of the meeting
	meeting = db.getMeeting(jpost["mid"])
	if meeting is None:
		return False
	if meeting not in db.getUserCreatedMeetings(jpost["netid"]):
		return False

	# print "meeting deletion ok"
	return True
예제 #23
0
def isValid_Decision(jpost):
	decisionFields   = ["category", "mid", "netid", "finalTime"]

	for key in decisionFields:
		if key not in jpost:
			return False

	if not isinstance(jpost["mid"], int):
		return False
	if not isinstance(jpost["netid"], basestring):
		return False
	if len(jpost["finalTime"]) > 1:         # if more than 1 scheduled time
		return False
	if not datetimes_isValid(jpost["finalTime"]):
		return False
		
	if db.getUser(jpost["netid"]) is None:
		return False	
	if db.getMeeting(jpost["mid"]) is None:
		return False

	# print "decision ok"
	return True
예제 #24
0
 def getKey(self, username):
     if self.isAnnon(username):
         return self.annons[username]
     return database.getUser(username=username)[0]['key']
예제 #25
0
 def getKey(self, username):
     if self.isAnnon(username):
         return self.annons[username]
     return database.getUser(username=username)[0]['key']
예제 #26
0
# Sample time strings
sample1 = "[{'date': '04-22-2017', 'time': '9:00am'}, {'date': '04-23-2017', 'time': '10:00am'}, {'date': '04-24-2017', 'time': '11:30am'}, {'date': '04-25-2017', 'time': '12:30pm'}, {'date': '04-26-2017', 'time': '1:00pm'}, {'date': '04-23-2017', 'time': '9:00am'}, {'date': '04-22-2017', 'time': '10:00am'}, {'date': '04-22-2017', 'time': '11:30am'}, {'date': '04-23-2017', 'time': '11:30am'}, {'date': '04-22-2017', 'time': '12:30pm'}, {'date': '04-23-2017', 'time': '12:30pm'}, {'date': '04-24-2017', 'time': '12:30pm'}, {'date': '04-22-2017', 'time': '1:00pm'}, {'date': '04-23-2017', 'time': '1:00pm'}, {'date': '04-24-2017', 'time': '1:00pm'}, {'date': '04-25-2017', 'time': '1:00pm'}]"
sample2 = "[{'date': '04-22-2017', 'time': '9:00am'}, {'date': '04-23-2017', 'time': '10:00am'}, {'date': '04-24-2017', 'time': '11:30am'}, {'date': '04-25-2017', 'time': '12:30pm'}, {'date': '04-26-2017', 'time': '1:00pm'}]"
sample3 = "[{'date': '04-23-2017', 'time': '10:00am'}, {'date': '04-24-2017', 'time': '11:30am'}, {'date': '04-23-2017', 'time': '11:30am'}, {'date': '04-23-2017', 'time': '12:30pm'}, {'date': '04-24-2017', 'time': '12:30pm'}, {'date': '04-23-2017', 'time': '1:00pm'}, {'date': '04-24-2017', 'time': '1:00pm'}]"

sample4 = "[{'date': '04-22-2017', 'time': '9:00am'}, {'date': '04-22-2017', 'time': '10:00am'}, {'date': '04-22-2017', 'time': '11:30am'}, {'date': '04-22-2017', 'time': '12:30pm'}, {'date': '04-22-2017', 'time': '1:00pm'}, {'date': '04-23-2017', 'time': '9:00am'}, {'date': '04-23-2017', 'time': '10:00am'}, {'date': '04-23-2017', 'time': '11:30am'}, {'date': '04-23-2017', 'time': '12:30pm'}, {'date': '04-23-2017', 'time': '1:00pm'}]"
sample5 = "[{'date': '04-22-2017', 'time': '9:00am'}, {'date': '04-22-2017', 'time': '10:00am'}, {'date': '04-22-2017', 'time': '11:30am'}, {'date': '04-22-2017', 'time': '12:30pm'}]"
sample6 = "[{'date': '04-22-2017', 'time': '10:00am'}, {'date': '04-22-2017', 'time': '11:30am'}, {'date': '04-23-2017', 'time': '1:00pm'}]"

## Create users ###########################################
db.createUser('hsolis', 'Hector', 'Solis')
db.createUser('gwan', 'Gerry')
db.createUser('bargotta')

hector = db.getUser('hsolis')
gerry = db.getUser('gwan')
aaron = db.getUser('bargotta')

## Create meetings  ########################################

db.createMeeting('test1', hector.uid, "[2, 3]", "04-21-2017")
db.createMeeting('test2', hector.uid, "[2, 3]", "04-21-2017")
db.createMeeting('test3', gerry.uid, "[1, 3]", "04-21-2017")
db.createMeeting('test4', gerry.uid, "[1, 3]", "04-21-2017")
db.createMeeting('test5', aaron.uid, "[2]", "04-21-2017")

## Create responses  ################################################################

db.createResponse(1, hector.uid, sample1)
db.createResponse(2, hector.uid, sample4)
예제 #27
0
def inviteUsers(responders):
	for netid in responders:
		if db.getUser(netid) == None:
			db.createUser(netid)
예제 #28
0
 def get(self):
     user_id = request.args.get('user_id')
     data = getUser(user_id)
     print "data: " + str(data)
     return data, 200
예제 #29
0
def getUserInfo(my_database):
    email = raw_input("Enter email address: ")
    print database.getUser(my_database, email)