Exemplo n.º 1
0
def main():
    """docstring for main"""
    username_list = {}

    data = file("data/petster-hamster/ent.petster-hamster")
    for item in data.readlines():
        if not item.startswith("%"):
            res = INFO_PATTERN.findall(item)
            info = dict(zip(KEYS, res))
            username_list[info["id"]] = info["username"]
            user = User(info)
            user.add()
    data.close()

    data = file("data/petster-hamster/out.petster-hamster")
    for item in data.readlines():
        # print repr(item)
        # raw_input()
        if not item.startswith("%"):
            uid1, uid2 = item.strip().split(" ")
            # print repr(uid1), repr(uid2)
            # raw_input()
            username1 = username_list[uid1]
            username2 = username_list[uid2]
            user1 = User.get(username1)
            user2 = User.get(username2)
            user1.follow(username2)
            user2.follow(username1)
    data.close()
Exemplo n.º 2
0
 def get(self, username):
     """Loads user's properties. If logged user is admin it loads also non public properties"""
     if auth.is_admin():
         properties = User.get_private_properties()
     else:
         properties = User.get_public_properties()
     traveler_key = getattr(g.user_db,'fellow_traveler',None)
     if traveler_key:
         traveler = traveler_key.get()
         future=False
     else:
         traveler = model.FellowTraveler.create_or_update(
                 name=g.user_db.name,
                 email=g.user_db.email,
                 avatar_url=g.user_db.avatar_url,
                 parent=g.user_db.key,
                 added_by=g.user_db.key)
         traveler_key =traveler.put()
         traveler.key = traveler_key
         g.user_db.fellow_traveler = traveler_key
         future = g.user_db.put_async()
     db_dict = g.user_db.to_dict(include=properties)
     db_dict["fellow_traveler"] = traveler.to_dict(include=model.FellowTraveler.get_public_properties())
     if future:
         future.get_result()
     return db_dict
Exemplo n.º 3
0
def fake_db():
    userMap={}
    groupMap={}
    for i in range(10):
        user = User("user%s"%i,"*****@*****.**"%i)
        user.password="******"
        db.session.add(user)
        db.session.commit()
        userMap[user.id]=user;
        
    for i in range(5):
        userid = random.choice(userMap.keys())
        group = Group(userid, "group%s"%i)
        group.describe = "".join([chr(random.choice(range(65,90))) for i in range(10)])
        db.session.add(group)
        db.session.commit()
        groupMap[group.id]=group

    db.session.commit()

    for userid,user in userMap.items():
        group=random.choice(groupMap.values());
        group.add_member(userid)

    for groupid,group in groupMap.items():
        user=random.choice(userMap.values());
        group.add_member(user.id)
            
    return dict();
Exemplo n.º 4
0
    def initialize(self, request, response):
        self.current='home'
        webapp.RequestHandler.initialize(self, request, response)
        os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
        from model import User,Blog
        self.blog = Blog.getBlog()
        self.login_user = users.get_current_user()
        self.is_login = (self.login_user != None)
        self.loginurl=users.create_login_url(self.request.uri)
        self.logouturl=users.create_logout_url(self.request.uri)
        self.is_admin = users.is_current_user_admin()

        if self.is_admin:
            self.auth = 'admin'
            self.author=User.all().filter('email =',self.login_user.email()).get()
            if not self.author:
                self.author=User(dispname=self.login_user.nickname(),email=self.login_user.email())
                self.author.isadmin=True
                self.author.user=self.login_user
                self.author.put()
        elif self.is_login:
            self.author=User.all().filter('email =',self.login_user.email()).get()
            if self.author:
                self.auth='author'
            else:
                self.auth = 'login'
        else:
            self.auth = 'guest'

        try:
            self.referer = self.request.headers['referer']
        except:
            self.referer = None

        self.template_vals = {'self':self,'blog':self.blog,'current':self.current}
Exemplo n.º 5
0
def profile_get(username):
    """
    Show user's profile with at most recent 10 tweets

    :param username: username of the user
    :type username: string
    :rtype: profile page of the user

    Note:
        Need to check whether authenticated or not
        if so add an profile edit button
        if not follow button or followed status

        Use 'action' param to judge whether to update profile or password
        if it is 'profile', show profile update form
        if it is 'password', show password update form
    """
    user = User.get(username)
    ownername = request.get_cookie('username', secret=COOKIES_SECRET)
    owner = User.get(ownername)
    action = request.GET.get('action', '')
    if ownername == username:
        if action == 'profile':
            return template('profile_update', user=user)
        elif action == 'password':
            return template('password_update', user=user)
    tweets = user.get_tweets()
    isfollow = owner.isfollow(username)
    return template('profile', user=user, owner=owner, tweets=tweets,
        isfollow=isfollow)
Exemplo n.º 6
0
    def post(self):
        name = self.request.get('name')
        phone = self.request.get('phone')
        current_password = self.request.get('current_password')
        new_password = self.request.get('new_password')
        verify_new_password = self.request.get('verify_new_password')

        if self.request.get('change_account'):
            self.user.populate(name=name, phone=phone)
            self.save_user_and_reload()

        elif self.request.get('change_password'):
            password_errors = {}
            try:
                User.get_by_auth_password(self.user.username, current_password)
            except InvalidPasswordError as e:
                password_errors['current_password'] = u'현재 비밀번호가 맞지 않습니다.'
            if new_password != verify_new_password:
                password_errors['verify_password'] = u'비밀번호와 비밀번호 확인이 다릅니다.'

            if not password_errors:
                self.user.set_password(new_password)
                self.save_user_and_reload()
            else:
                self.render('account.html', user=self.user, password_errors=password_errors)
Exemplo n.º 7
0
def register():
    if request.method == 'GET':
        return render_template('register.html', page='signup')
    elif request.method == 'POST':
        username = request.form.get('username', None)
        nickname = request.form.get('nickname', None)
        password = request.form.get('password', None)
        password_again = request.form.get('password_again', None)

        if username is None or nickname is None or password is None or password_again is None:
            flash(u'请检查输入是否为空', 'danger')
            return redirect(url_for('register'))
        password, password_again, username, nickname = unicode(password), unicode(password_again), unicode(username), unicode(nickname)

        # 1. 用户名是否存在
        user = User.query.filter_by(username=username).first()
        if user:
            flash(u'该用户名已被注册', 'danger')
            return redirect(url_for('register'))
        # 2. 密码输入不一致
        if password != password_again:
            flash(u'两次密码输入不一致', 'danger')
            return redirect(url_for('register'))

        proc_password = utils.encrypt_password(password, salt=config.SALT)
        User.add(User(username, proc_password, nickname))
        flash(u'注册成功', 'success')
        return redirect(url_for('login'))
 def set_up(self):
     u = User()
     path = u.path(self.id)
     try:
         os.remove(path)
     except Exception, e:
         pass
Exemplo n.º 9
0
 def get(self, username):
     """Loads user's properties. If logged user is admin it loads also non public properties"""
     if auth.is_admin():
         properties = User.get_private_properties()
     else:
         properties = User.get_public_properties()
     return g.user_db.to_dict(include=properties)
Exemplo n.º 10
0
    def get(self):
        verification_code = self.request.get("code")
        args = dict(client_id=Constants.FACEBOOK_APP_ID, redirect_uri=self.request.path_url)
        if self.request.get("code"):
            args["client_secret"] = Constants.FACEBOOK_APP_SECRET
            args["code"] = self.request.get("code")
            response = cgi.parse_qs(urllib.urlopen(
                "https://graph.facebook.com/oauth/access_token?" +
                urllib.urlencode(args)).read())
            access_token = response["access_token"][-1]

            # Download the user profile and cache a local instance of the
            # basic profile info
            profile = json.load(urllib.urlopen(
                "https://graph.facebook.com/me?" +
                urllib.urlencode(dict(access_token=access_token))))
            user = User(key_name=str(profile["id"]), id=str(profile["id"]),
                        name=profile["name"], access_token=access_token,
                        profile_url=profile["link"])
            user.put()
            functions.set_cookie(self.response, "fb_user", str(profile["id"]),
                       expires=time.time() + 30 * 86400)
            self.redirect("/")
        else:
            self.redirect(
                "https://graph.facebook.com/oauth/authorize?" +
                urllib.urlencode(args))
Exemplo n.º 11
0
    def post(self):
        email = self.request.get('email', '')
        password = self.request.get('password', '')
        other_username = self.request.get('other-user')

        logging.info('%s, %s' % (email, other_username))

        user = User.user_from_email(email)

        if not user:
            logging.info('not a valid email address')
            self.render('error.html', **{'error_msg': 'You cannot do this'})
            return
        if not self.validate_user(user, password):
            logging.info('username password fail')
            self.render('error.html', **{'error_msg': 'You cannot do this'})
            return
        if not user.admin:
            logging.info('Need to be admin to login as other user')
            self.render('error.html', **{'error_msg': 'You cannot do this'})
            return

        other_user = User.user_from_name(other_username)
        logging.info('Other user: %s' % other_user)

        if not other_user:
            logging.info('cannot find other user')
            self.render('error.html', **{'error_msg': "Can't find other user"})
            return

        self.set_cookie(other_user)
        self.redirect('/user/%d' % other_user.key.id())
Exemplo n.º 12
0
 def testPassword(self):
     # Valid passwords
     password = '******'
     self.assertTrue(User.isPasswordValid(password), 'Misqualified valid password: '******'111wr311111'
     self.assertTrue(User.isPasswordValid(password), 'Misqualified valid password: '******'asdasdawdas'
     self.assertTrue(User.isPasswordValid(password), 'Misqualified valid password: '******'1234567'
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: '******''
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: '******' '
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: '******'12 3 4567'
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: '******'asdasdasd;'
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: '******'asdasdasd\''
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: '******'asdasdasd"'
     self.assertFalse(User.isPasswordValid(password), 'Misqualified invalid password: ' + password)
              
Exemplo n.º 13
0
Arquivo: xmpp.py Projeto: mizhi/tictic
    def text_message(self, message):
        email = extract_email(message.sender)

        try:
            sender = users.User(email)
        except users.UserNotFoundError as e:
            message.reply("You don't seem to have an account that I can find.")

        appuser = User.all().filter("info = ", sender).get()

        if not appuser:
            appuser = User(info = sender)
            appuser.put()

        try:
            datum = parser.parse(message.body)
        except parser.ParseException as e:
            message.reply("I couldn't understand you. (Message was: {msg})".format(msg = e.message))

        variable = Variable.all().filter("name = ", datum["variable"]).get()
        if not variable:
            variable = Variable(name = datum["variable"], user = appuser)
            variable.put()

        value = Value(value = datum["value"], variable = variable)
        value.put()

        message.reply("I've logged variable {variable} as being {value}".format(sender = email,
                                                                                variable = datum["variable"],
                                                                                value = datum["value"]))
Exemplo n.º 14
0
def view_movie(id):
    #id = movie.id
    user_id = g.user_id
    if g.user_id:
        movie = Movie.search_movie(id)
        ratings = Rating.search_rating(movie.id, user_id.id)
        beratement = None
        if ratings == None:
            ratings = movie.ratings
            rating_nums = []
            user_rating =None
            for r in ratings:
                rating_nums.append(r.rating)
            avg_rating = float(sum(rating_nums))/len(rating_nums)
            prediction = User.predict_rating(movie.id, user_id.id)
            the_eye = db_session.query(User).filter_by(email="*****@*****.**").one()
            eye_rating = db_session.query(Rating).filter_by(user_id = the_eye.id, movie_id = id).first()
            if not eye_rating:
                eye_rating = User.predict_rating(movie.id, the_eye.id)
                print eye_rating
            else:
                eye_rating = eye_rating.rating
            if prediction:
                difference = abs(eye_rating - prediction)
                messages = [ "I suppose you don't have such bad taste after all.",
                "I regret every decision that I've ever made that has brought me to listen to your opinion.",
                "Words fail me, as your taste in movies has clearly failed you.",
                "That movie is great. For a clown to watch. Idiot.",]
                beratement = messages[int(difference)]
            return render_template("view_movie.html", movie=movie, average=avg_rating, user_rating=user_rating, prediction=prediction, ratings = ratings, beratement=beratement)
        else:
            return render_template("view_movie.html", movie = movie, ratings=ratings)
    return render_template("")
Exemplo n.º 15
0
    def populate(self):
        # clear the existing cache
        for x in range(0, len(self)):
            self.pop()

        if self.location != 'global':
            location = Location.get(self.location)
            if location.is_region:
                hubs = location.has_hubs
                profile_select = User.select(AND(IN(User.q.homeplaceID, hubs),
                    User.q.public_field==1,
                    User.q.active==1,
                    User.q.description != u"",
                    User.q.modified > datetime.datetime.now() - datetime.timedelta(days=365))).orderBy('modified').reversed()[:30]
            else:
                profile_select = User.select(AND(User.q.homeplaceID==location,
                    User.q.public_field==1,
                    User.q.active==1,
                    User.q.description != u"",
                    User.q.modified > datetime.datetime.now() - datetime.timedelta(days=365))).orderBy('modified').reversed()[:30]
        else:
            profile_select = User.select(AND(User.q.public_field==1,
                    User.q.active==1,
                    User.q.description != u"",
                    User.q.modified > datetime.datetime.now() - datetime.timedelta(days=365))).orderBy('modified').reversed()[:30]
        for profile in profile_select:
            cache_obj = self.objectcache_factory(profile)
            self.append(cache_obj)
Exemplo n.º 16
0
def load_users():
    """Load users from user.csv into database."""
    # open file
    user_csv = open("user.csv")
    # Iterate through the lines
    # This will put the data into a list
    for line in user_csv:
        line_list = line.strip().split("|")
        # Another for loop to iterate through
        for i in range(len(line_list)):
            line_list[i] = line_list[i].strip()
        user_id, email, password, street_address, zipcode, first_name, last_name, admin = line_list[0], line_list[1], \
                                                                                          line_list[2], line_list[3], \
                                                                                          line_list[4], line_list[5], \
                                                                                          line_list[6], line_list[7]

        print "EMAIL: {}, PASSWORD: {}, STREET_ADDRESS: {}, ZIPCODE: {}, FIRST {}, LAST {}".format(email, password,
                                                                                                   street_address,
                                                                                                   zipcode, first_name,
                                                                                                   last_name)

        user = User(user_id=user_id, email=email, street_address=street_address, zipcode=zipcode, first_name=first_name,
                    last_name=last_name, admin=admin)
        user.hash_password(password)

        db.session.add(user)
    db.session.commit()
Exemplo n.º 17
0
def login():
    """Log in page"""

    name = request.form.get('name')
    email = request.form.get('email')
    image = request.form.get('image')

    user = User.query.filter_by(email=email).first()

    if user:
        user_id = user.user_id
        session['user_id']=user_id
        session['name']=name
        session['image']=image
       
        return "%s is in session" %(name)

    if not user:
        User.add_user(email=email, name=name, image=image)
        session['user_id']=user_id
        session['name']=name
        session['image']=image
       
        return "%s is in session" %(name)

    else:
        return None
Exemplo n.º 18
0
async def api_register_user(*, email, name, passwd):
    '''
    这个函数其实是用来注册用户的。
    '''
    if not name or not name.strip():
        raise APIValueError('name')
    if not email or not _RE_EMAIL.match(email):
        raise APIValueError('email')
    if not passwd or not _RE_SHA1.match(passwd):
        raise APIValueError('passwd')
    uid = next_id()
    sha1_passwd = '%s:%s' % (uid, passwd)
    user = User(
        id=uid,
        name=name.strip(),
        email=email,
        passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(),
        image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest()
    )

    await user.save()
    # make session cookie:
    r = web.Response()
    # 登陆的时候要创建cookie信息
    r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)
    user.passwd = '******'
    r.content_type = 'application/json'
    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
    return r
Exemplo n.º 19
0
def login_telnet(frame,username):
    user = User(username)
    user.init_user_info()
    frame.session.update(user.dict)
    frame.session['_user'] = user
    frame.session['username'] = username
    return user
Exemplo n.º 20
0
def insert_user(user_json):
  #print "INSERT USER"
  #print user_json
 
  user_string = json.loads(user_json)
  userAddress = Address(number = user_string["number"],
                    street = user_string["street"],
                    postalCode = user_string["postalCode"],
                    city = user_string["city"],
                    province = user_string["province"])

  #print "pizzaId: " + user_string["pizzaId"]
  
  userOrder = Order(qty = int(user_string["quantity"]),
								size = int(user_string["pizzaSize"]),
                pizza_type = int(user_string["pizzaId"]))   
  userAddress.put()
  userOrder.put()
  user = User(name = user_string["name"],
              phoneNumber = user_string["phoneNumber"],
              email = user_string["email"],
              addressId = userAddress.key(), 
              orderId = userOrder.key())  

  user.put()
  return user.key();
Exemplo n.º 21
0
def confirm_new_user():
    """Creates new user"""

    # flash=[]
    # It gets email and password from the POST param
    user_email = request.form.get("email")

    user_password = request.form.get("password")

    name = request.form.get("name")

    #It checks if user already exists or email is invalid
    confirmed_user = User.get_user_by_email(user_email)

    # is_valid = validate_email(user_email,verify=True)

    # EMAIL_RE.search(user_email)
    if True:

        if not confirmed_user:
            User.create_user_by_email_password(user_email, user_password, name)
            flash("You successfully created an account!")
            return redirect('/')
        else:
            flash("You already have an account")
            return render_template('error.html',url='homepage.html')

    else:
        flash("The email that you entered is invalid")
        # return render_template('error.html',url='homepage.html')

    return render_template('error.html',url='homepage.html')
Exemplo n.º 22
0
def api_register_user(*,email,name,passwd):
	logging.info('comming into register post users')
	if not name or not name.strip():
		raise APIValueError('name')
	if not name or not _RE_EMAIL.match(email):
		raise APIValueError('email')
	if not passwd or not _RE_SHA1.match(passwd):
		raise APIValueError('passwd')
	users = yield from User.findAll('email=?',[email])

	if len(users) > 0 :
		raise APIError('register:failed','email','Email is already in use.')
	uid = next_id()
	sha1_passwd = '%s:%s' %(uid,passwd)
	user = User(id=uid,name=name.strip(),email=email,passwd=hashlib.sha1(
		sha1_passwd.encode('utf-8')).hexdigest(),image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest())
	yield from user.save()

	#make session cookie from here:
	r = web.Response()
	r.set_cookie(COOKIE_NAME,user2cookie(user,86400),max_age=86400,httponly=True)

	user.passwd = '******'
	r.content_type = 'application/json'
	r.body = json.dumps(user,ensure_ascii=False).encode('utf-8')

	return r 
Exemplo n.º 23
0
    def game_on_game_in_progress(self, g):
        for player in g.players:
            self.send_message(player.name, message.game.in_progress, server=g.server.name, password=g.password, \
                              ip=g.server.address[0], port=g.server.address[1])
            
            user = User.find_or_create_by_nick(player.name)
            if not user.games_played: user.games_played = 0
            user.games_played += 1
            user.save()
        
        user = User.find_or_create_by_nick(g.owner)
        if not user.games_admined: user.games_admined = 0
        user.games_admined += 1
        user.save()
        
        game_mode = "highlander" if g.is_highlander else "%sv%s" % (g.max_players / 2, g.max_players / 2)
        team_groups = (g.get_class_groups() if g.is_highlander else g.get_team_groups())
        team_groups = dict(map(lambda k: (str(k), team_groups[k]), team_groups))
        game = Game(created_at=datetime.datetime.now(), mode=game_mode, server=g.server.name, \
                    map=g.map, admin=g.owner, teams=team_groups)
        game.save()

        #self.set_topic_game_inprogress()
        self.game_end()

        self.send_message(message.game.sent_password)
Exemplo n.º 24
0
	def get(self):
		if(not isUserAdmin(self)):
			self.session[LOGIN_NEXT_PAGE_KEY] = self.URL
			self.redirect("/")
			return
		pageText=self.request.get("page")
		pageSize=20
		actualPage=0
		if (pageText!=None and pageText!=""):
			actualPage=int(pageText)-1
		orderByText=self.request.get("order")
		if (orderByText==None or orderByText==""):
			orderByText='familyName'
		userCount=User.all().count()
		roles=Role.all().order("name")
		usersToDisplay=User.all().order(orderByText).run(offset=actualPage*pageSize, limit=pageSize)
		pages=[]
		corrector=1
		if (userCount/pageSize) * pageSize == userCount:
			corrector=0
		for i in range(0,userCount/pageSize + corrector):
			pages.append(i+1)
		template_values={
			'page':actualPage+1,
			'pages':pages,
			'userList':usersToDisplay,
			'order':orderByText,
			'roles':roles
		}
		if actualPage < userCount/ pageSize - 1 - corrector:
			template_values["nextPage"]=actualPage + 2
		if actualPage > 0:
			template_values["nextPage"]=actualPage
		template = jinja_environment.get_template('templates/userList.html')
		self.printPage("Felhasznalok", template.render(template_values), False, False)
Exemplo n.º 25
0
 def get(self, user_email):
   flow = createFlow(self, user_email)
   credentials = StorageByKeyName(CredentialsModel, user_email, 'credentials').get()
   force = self.request.get('force')
   if force and force == 'true':
       self.redirect(flow.step1_get_authorize_url()) 
       return
   
   if credentials:
     user = User.get_by_key_name(user_email)
     if not user or not user.is_oauth_complete:
       ctxIO = ContextIO(consumer_key=settings.CONTEXTIO_OAUTH_KEY, 
                         consumer_secret=settings.CONTEXTIO_OAUTH_SECRET)
       current_account = ctxIO.post_account(email=user_email)
       user = User.get_or_insert(key_name = user_email, 
                                 user_ctx_id=current_account.id,
                                 email=user_email)
       refresh_token = credentials.refresh_token
       try:
         if not refresh_token:
           raise Exception('no refresh token')
         current_account.post_source(email=user_email,
                                            username=user_email,
                                            server='imap.gmail.com',
                                            provider_refresh_token=refresh_token,
                                            provider_consumer_key=settings.APPENGINE_CONSUMER_KEY)
       except Exception as e:
         logging.error(str(e))
         self.redirect(flow.step1_get_authorize_url())
       user.is_oauth_complete = True
       user.put()
     self.response.out.write(r"""<html><head><script type="text/javascript">window.close();</script></head><body><div id="sbi_camera_button" class="sbi_search" style="left: 0px; top: 0px; position: absolute; width: 29px; height: 27px; border: none; margin: 0px; padding: 0px; z-index: 2147483647; display: none;"></div></body></html>""")
   else:
     logging.info('redirect')
     self.redirect(flow.step1_get_authorize_url()) 
Exemplo n.º 26
0
    def initialize(self, request, response):
        webapp.RequestHandler.initialize(self, request, response)
        os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
        from model import g_blog, User

        self.blog = g_blog
        self.login_user = users.get_current_user()
        self.is_login = self.login_user != None
        self.loginurl = users.create_login_url(self.request.uri)
        self.logouturl = users.create_logout_url(self.request.uri)
        self.is_admin = users.is_current_user_admin()

        if self.is_admin:
            self.auth = "admin"
            self.author = User.all().filter("email =", self.login_user.email()).get()
            if not self.author:
                self.author = User(dispname=self.login_user.nickname(), email=self.login_user.email())
                self.author.isadmin = True
                self.author.user = self.login_user
                self.author.put()
        elif self.is_login:
            self.author = User.all().filter("email =", self.login_user.email()).get()
            if self.author:
                self.auth = "author"
            else:
                self.auth = "login"
        else:
            self.auth = "guest"

        try:
            self.referer = self.request.headers["referer"]
        except:
            self.referer = None

        self.template_vals = {"self": self, "blog": self.blog, "current": self.current}
Exemplo n.º 27
0
def api_register(*, name, email, passwd):
    r = web.Response()
    if not name or not name.strip():
        raise APIValueError('name')
    if not email or not _RE_EMAIL.match(email):
        raise APIValueError('email')
    if not passwd or not _RE_SHA1.match(passwd):
        raise APIValueError('passwd')
    users = yield from User.findAll('email=?', [email])
    if len(users) > 0:
        result =  APIResult(0, '', 'Email is already in use.')
    else:
        sha1_passwd = '%s:%s' % ('hearain', passwd)
        user = User(name=name.strip(),
                    email=email,
                    password=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(),
                    logo='http://www.gravatar.com/avatar/%s?d=wavatar&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest()
                    )
        id = yield from user.save()
        #设置session
        config['_session'][user.email] = user2cookie(user, 86400)
        setWebCookie(r, 'user', config['_session'][user.email])
        setWebCookie(r, 'email', user.email)
        setWebCookie(r, 'id', id)
        setWebCookie(r, 'name', user.name)
        result = APIResult(1, '', '')
    return jsonResult(r, result)
Exemplo n.º 28
0
def syncdb():
    from lib.util import find_subclasses
    from model import db, User, Distribution, Category, Page
    
    models = find_subclasses(db.Model)
    for model in models:
        if model.table_exists():
            model.drop_table()
        model.create_table()
        logging.info('created table:%s' % model._meta.db_table)
    
    Distribution.create(name = '免费配送', price = 0)
    Distribution.create(name = '上门自提', price = 0)
    Category.create(name = '积分商品', slug = 'credit', order = 1)
    Category.create(name = '搭配购买', slug = 'acc', order = 2)
    Category.create(name = '慕斯蛋糕', slug = 'mousse', order = 3)
    Category.create(name = '巧克力蛋糕', slug = 'chocolate', order = 4)
    Category.create(name = '乳酪蛋糕', slug = 'cheese', order = 5)
    Category.create(name = '乳脂奶油蛋糕', slug = 'creambutter', order = 6)
    Category.create(name = '冰淇淋蛋糕', slug = 'icecream', order = 7)
    Page.create(name = '吉米的厨房', slug = 'aboutus', content = '')
    Page.create(name = '包装展示', slug = 'bzzs', content = '')
    Page.create(name = '订购说明', slug = 'dgsm', content = '')
    Page.create(name = '如何收货', slug = 'rhsh', content = '')
    Page.create(name = '付款方式', slug = 'fkfs', content = '')
    Page.create(name = '配送范围', slug = 'psfw', content = '')
    User.create(mobile = 'root', password = User.create_password('111111'), group = 9)
    
    logging.info('superuser - username:root password:111111')
Exemplo n.º 29
0
class Single:
  def __init__(self, client):
    self.model = User(client, bcrypt)

  def on_get(self, req, resp, user_id):
    if authorize_as(req.auth, 'developer'):
      resource = self.model.find(user_id)
      if resource != None:
        resp.body = dumps(resource)
      else:
        resp.status = HTTP_404
    else:
      raise HTTPUnauthorized('unautharized', 'unautharized')

  def on_put(self, req, resp, user_id):
    try:
      if(authorize_as(req.auth, 'developer')):
        is_dev = True
    except:
      is_player = authorize_as(req.auth, 'player')
      is_dev = False
      if not is_player:
        raise HTTPUnauthorized('unautharized', 'unautharized')

    body = loads(req.stream.read().decode('utf-8'))
    resource = self.model.update(body, user_id, is_dev)
    if resource.modified_count == 1:
      resp.status = HTTP_204
    else:
      raise HTTPBadRequest('failed to update resource',
                           'a resource with id: ' + user_id + ' was not found')
Exemplo n.º 30
0
def authorized(resp):
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    # Save token to the session for the immediately following gmail request
    session['gmail_token'] = (resp['access_token'], )
    # Check if that user already exists in the db
    gmail_user = gmail.get('userinfo')
    try:
        postal_user = (db_session.query(User)
                                 .filter_by(email_address=gmail_user.data['email'])
                                 .one())
        # Choosing to just update the token the db
        postal_user.save_new_token(resp['access_token'])
        session['user_email'] = gmail_user.data['email']
        session['user_id'] = postal_user.id
    except sqlalchemy.orm.exc.NoResultFound, e:
        # If a new user, save them to the db
        postal_user = User(name=gmail_user.data['name'],
                           email_address=gmail_user.data['email'],
                           access_token=resp['access_token'])
        postal_user.save()
        session['user_email'] = gmail_user.data['email']
        session['user_id'] = postal_user.id
Exemplo n.º 31
0
 def get_user_by_email(self, email_address):
     user = self.collection.find_one({'email_address': email_address})
     if user is None:
         return None
     target_user = User(user)
     return target_user
Exemplo n.º 32
0
 def get_user_by_id(self, user_id):
     user = self.collection.find_one({'_id': user_id})
     if user is None:
         return None
     target_user = User(user)
     return target_user
Exemplo n.º 33
0
 def admin_user(self):
     return User.get_by_email("*****@*****.**")
Exemplo n.º 34
0
def user_from_username(username):
    try:
        user = User.select().where(User.username == username).get()
        return user
    except User.DoesNotExist:
        return False
Exemplo n.º 35
0
    def authenticate(self,
                     auth_type,
                     email=None,
                     password=None,
                     facebook_access_token=None):
        """Takes various kinds of credentials (email/password, google
        account) and logs you in.

        Returns:
          User entity             the user has been successfully authenticated
          'credentials_invalid'   either because a password is wrong or no
                                  account exists for those credentials
          'credentials_missing'   looked for credentials but didn't find any of
                                  the appropriate kind.
          'email_not_found'       the user authenticated through a third party,
                                  but they didn't have an email address.
          'email_exists:[auth_type]'  the supplied credentials are invalid AND
                                      a user with the same email exists with
                                      another auth type.
        """
        # fetch matching users
        if auth_type == 'own':
            if email is None or password is None:
                return 'credentials_missing'
            auth_id = User.get_auth_id(auth_type, email.lower())

        elif auth_type in ['google', 'facebook']:
            user_kwargs, error = self.get_third_party_auth(
                auth_type, facebook_access_token)
            if error:
                return error
            elif not user_kwargs:
                return 'credentials_missing'
            auth_id = user_kwargs['auth_id']

        # Fetch 2 b/c that's sufficient to detect multiple matching users.
        user_results = (User.query(User.deleted == False,
                                   User.auth_id == auth_id).order(
                                       User.created).fetch(2))

        # interpret the results of the query
        num_matches = len(user_results)
        if num_matches is 0:
            # Make it easy for devs to become admins.
            if (auth_type == 'google'
                    and app_engine_users.is_current_user_admin()):
                return self.register('google')
            # If a user with this email already exists, advise the client.
            # This step isn't necessary with google or facebook auth_types, b/c
            # we always try to register right after if logging in fails, and
            # register takes care of this part.
            if auth_type == 'own':
                matching_user = User.query(User.deleted == False,
                                           User.email == email).get()
                if matching_user:
                    return 'email_exists:' + matching_user.auth_type
            # no users with that auth_id, invalid log in
            return 'credentials_invalid'
        elif num_matches > 1:
            logging.error(u"More than one user matches auth info: {}.".format(
                user_kwargs))
            # We'll let the function pass on and take the first of multiple
            # duplicate users, which will be the earliest-created one.

        # else num_matches is 1, the default case, and we can assume there was
        # one matching user
        user = user_results[0]

        # For direct authentication, PERTS is in charge of checking their
        # credentials, so validate the password.
        if auth_type == 'own':
            # A user-specific salt AND how many "log rounds" (go read about key
            # stretching) should be used is stored IN the user's hashed
            # password; that's why it's an argument here.
            # http://pythonhosted.org/passlib/
            if not sha256_crypt.verify(password, user.hashed_password):
                # invalid password for this email
                return 'credentials_invalid'

        # If we got this far, all's well, log them in and return the matching
        # user
        self.log_in(user)
        return user
Exemplo n.º 36
0
    # Create our data schema and default objects if needed
    seed_once(app)

    # Tell our sparklebot which user to post messages as and which room
    # to frequent
    default_room = db.session.query(Room).get(1)
    print "1:" + str(default_room.as_json())

    # Get the sparklebot user object, creating it if need be
    sparklebot_check = User.query.filter(User.name == sparklebot_name)
    print "2:" + str(sparklebot_check)
    if not sparklebot_check.first():
        print "3:" + str(sparklebot_check.first())
        # print "\n\n\nCREATING SPARKLE BOT DB USER\n\n\n"
        # Create the user
        db.session.add(User(sparklebot_name))
        db.session.commit()
    sparklebot_user = sparklebot_check.first()
    print "4:" + str(sparklebot_user.as_json())

    sparklebot.set_user_id(sparklebot_user.user_id)
    print "5:" + str(sparklebot_check)
    # Add the user to the room if needed
    if not default_room.contains_user(sparklebot_user.user_id):
        print "\n\n\nADDING SPARKLE BOT TO DEFAULT ROOM\n\n\n"
        db.session.add(default_room.join_room(sparklebot_user))
        db.session.commit()

    # Right now, we only have one room and one user in that room

    print "\n    HEREEEEE!\n\n"
Exemplo n.º 37
0
def create_user(email, password):
    new_user = User(email=email, password=password)
    db.session.add(new_user)
    db.session.commit()
    return new_user
Exemplo n.º 38
0
def set_reminder_phone_num(phone_num):

    phone_num = User(phone_num=phone_num)

    db.session.add(phone_num)
    db.session.commit()
Exemplo n.º 39
0
def set_reminder_first_name(first_name):

    first_name = User(first_name=first_name)

    db.session.add(first_name)
    db.session.commit()
Exemplo n.º 40
0
 def delete(self, user_id):
     user = User.find_by_id(user_id)
     if user:
         user.delete()
     return {'message': 'User deleted.'}
Exemplo n.º 41
0
def add_user(name, secret_word):
    """Add a user to the DB."""
    user = User(username=name)
    user.hash_password(secret_word)
    session.add(user)
    session.commit()
Exemplo n.º 42
0
os.system('dropdb joyride')
os.system('createdb joyride')
connect_to_db(server.app)
db.create_all()

fake = Faker()  #initiate a faker object
#Create 10 fake users
for i in range(10):
    email = f'user{i}@test.com'
    password = '******'
    first_name = f'test{i}'
    last_name = f'test{i}'
    fake_user = User(first_name=first_name,
                     last_name=last_name,
                     password=password,
                     email=email,
                     phone_num='4088893883')
    db.session.add(fake_user)
    db.session.commit()
    #For each user create 10 fake rides
    for _ in range(10):
        start_loc = f'teststart{_}'
        end_loc = f'testend{_}'
        fake_rides = Ride(driver_id=fake_user.user_id,
                          seats=randint(1, 4),
                          date=fake.date_time_between_dates(
                              datetime_start=datetime(2020, 9, 1),
                              datetime_end=datetime(2021, 5, 1)),
                          start_loc=start_loc,
                          end_loc=end_loc,
Exemplo n.º 43
0
 def add_user_from_request(self, user):
     new_user = User(name=user['name'],
                     password=user['password'],
                     age=user['age'],
                     gender=user['gender'])
     self.repo.add_user(new_user)
Exemplo n.º 44
0
def registration():
    if request.method == "POST":
        username = request.form.get("username")
        email = request.form.get("email")
        password = request.form.get("password")
        repeat = request.form.get("repeat")

        # check email valid
        is_valid = check_email(email)
        if not is_valid:
            flash("Email is not a valid email", "warning")
            return redirect(url_for("user.registration"))

        if password != repeat:
            flash("Password and repeat did not match!", "warning")
            return redirect(url_for("user.registration"))

        # check if email is already taken:
        user = User.query.filter_by(email=email).first()
        if user:
            flash("Email is already taken", "warning")
            return redirect(url_for("user.registration"))

        # check if username is already taken in Database!
        user = User.query.filter_by(username=username).first()
        if user:
            flash("Username is already taken", "warning")
            return redirect(url_for('user.registration'))

        password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
        session_cookie = str(uuid.uuid4())

        session_expiry_datetime = datetime.datetime.now() + datetime.timedelta(
            seconds=COOKIE_DURATION)

        user = User(username=username,
                    email=email,
                    password_hash=password_hash,
                    session_cookie=session_cookie,
                    session_expiry_datetime=session_expiry_datetime)
        db.session.add(user)
        db.session.commit()
        flash("Registration Successful!", "success")

        # send registration confirmation email
        msg = Message(subject="WebDev Blog - Registration Successful",
                      sender=SENDER,
                      recipients=[email],
                      bcc=[SENDER])
        msg.body = f"Hi {username}!\n" \
                   f"Welcome to our WebDev Flask site!\n" \
                   f"Visit us: {HOST_ADDR}\n" \
                   f"Enjoy!"
        mail.send(msg)

        # set cookie for the browser
        response = make_response(redirect(url_for('main.index')))
        response.set_cookie(WEBSITE_LOGIN_COOKIE_NAME,
                            session_cookie,
                            httponly=True,
                            samesite='Strict')
        return response

    elif request.method == "GET":
        return render_template("registration.html",
                               user=request.user,
                               active0="active")
Exemplo n.º 45
0
def inlinequery_handler(bot, update, chat_data):
    query = update.inline_query.query.lower()

    # TODO: remove or enhance eventually, this is potentially very spammy
    # Statistic.of(update, 'inlinequery', '"{}"'.format(query), Statistic.DETAILED)

    user = User.from_update(update)
    results_list = list()

    input_given = len(query.strip()) > 0
    query_too_short = 0 < len(query.strip()) < SEARCH_QUERY_MIN_LENGTH

    too_many_results = False
    cat_results = []
    bot_results = []

    if input_given:
        # query category results
        cat_results = search.search_categories(query)

        if not query_too_short:
            # query bot results
            bot_results = list(search.search_bots(query))
            if len(bot_results) > MAX_BOTS:
                bot_results = bot_results[:MAX_BOTS]
                too_many_results = True

    # query for new bots
    if query == messages.NEW_BOTS_INLINEQUERY.lower() or query == 'new':
        results_list.append(new_bots_article())
        bot.answerInlineQuery(update.inline_query.id, results=results_list)
        return

    if query in CONTRIBUTING_QUERIES:
        results_list.append(
            InlineQueryResultArticle(
                id=uuid4(),
                title='Contributing',
                input_message_content=InputTextMessageContent(
                    message_text=messages.CONTRIBUTING, parse_mode="Markdown"),
            ))
        bot.answerInlineQuery(update.inline_query.id,
                              results=results_list,
                              cache_time=600)
        return

    if query in EXAMPLES_QUERIES:
        results_list.append(
            InlineQueryResultArticle(
                id=uuid4(),
                title='Examples',
                input_message_content=InputTextMessageContent(
                    message_text=messages.EXAMPLES, parse_mode="Markdown"),
            ))
        bot.answerInlineQuery(update.inline_query.id,
                              results=results_list,
                              cache_time=600)
        return

    if query in (const.DeepLinkingActions.RULES, '#rules'):
        results_list.append(
            InlineQueryResultArticle(
                id=uuid4(),
                title='@BotListChat Rules',
                input_message_content=InputTextMessageContent(
                    message_text=messages.BOTLISTCHAT_RULES,
                    parse_mode="Markdown",
                    disable_web_page_preview=True),
            ))
        bot.answerInlineQuery(update.inline_query.id,
                              results=results_list,
                              cache_time=600)
        return

    if query == const.DeepLinkingActions.FAVORITES and user.has_favorites:
        results_list.append(favorites_article(user))
        bot.answerInlineQuery(update.inline_query.id,
                              results=results_list,
                              cache_time=0,
                              is_personal=True)
        return

    msg, reply_markup, key = botlistchat.get_hint_message_and_markup(query)
    if msg is not None:
        results_list.append(hint_article(msg, reply_markup, key))
        bot.answerInlineQuery(update.inline_query.id,
                              results=results_list,
                              cache_time=600)
        return

    invalid_search_term = query_too_short and not cat_results
    if invalid_search_term:
        results_list.append(query_too_short_article())

    results_available = cat_results or bot_results
    if results_available:
        if len(bot_results) > 1:
            results_list.append(
                all_bot_results_article(bot_results, too_many_results))
        for c in cat_results:
            results_list.append(category_article(c))
        for b in bot_results:
            results_list.append(bot_article(b))

        if len(bot_results) > 0:
            bot.answerInlineQuery(
                update.inline_query.id,
                results=results_list,
                switch_pm_text="See all results"
                if too_many_results else "Search in private chat",
                switch_pm_parameter=util.encode_base64(query),
                cache_time=0,
                is_personal=True)
        else:
            bot.answerInlineQuery(update.inline_query.id,
                                  results=results_list,
                                  cache_time=0,
                                  is_personal=True)
    else:
        if user.has_favorites:
            results_list.append(favorites_article(user))
        results_list.append(new_bots_article())
        categories = Category.select_all()
        for c in categories:
            results_list.append(category_article(c))

        if invalid_search_term or not input_given:
            bot.answerInlineQuery(update.inline_query.id,
                                  results=results_list,
                                  cache_time=0,
                                  is_personal=True)
        else:
            bot.answerInlineQuery(
                update.inline_query.id,
                results=results_list,
                switch_pm_text="No results. Contribute a bot?",
                switch_pm_parameter='contributing',
                cache_time=0,
                is_personal=True)
Exemplo n.º 46
0
from __future__ import print_function
from model import Session, User, Topic, UsernameTaken

session = Session()

# Create a user.
try:
    user = User.create(session, "foobar")
except UsernameTaken:
    print("username is already taken")

# Get a user by id.
user = User.get_by_id(session, 1)
print(user)

# Create a new topic
user = User.get_by_id(session, 1)
topic = Topic.create(session, user, "albatross for sale")
print(topic)

# Upvote a topic
user = User.get_by_id(session, 1)
topic = Topic.get_by_id(session, 1)
topic.upvote(session, user)
print(topic)

Exemplo n.º 47
0
    def get_third_party_auth(self, auth_type, facebook_access_token=None):
        """Wrangle and return authentication data from third parties.

        Args:
            auth_type: str, either 'google', or 'facebook'
            facebook_access_token: str, returned by the facebook javasript sdk
                when user logs in.
        Returns tuple of:
            dictionary of user information, which will always contain
                the key 'auth_id', or None if no third-party info is found.
            error as a string
        """
        if auth_type == 'google':
            gae_user = app_engine_users.get_current_user()
            if not gae_user:
                logging.info("No google login found.")
                return (None, 'credentials_missing')
            # Get user first and last names from nickname
            first_name = None
            last_name = None
            if gae_user.nickname():
                nickname = gae_user.nickname()
                if ' ' in nickname:
                    first_name = nickname.split(' ')[0]
                    last_name = nickname.split(' ')[1]
                else:
                    if '@' in nickname:
                        first_name = nickname.split('@')[0]
                    else:
                        first_name = nickname
            # Combine fields in user keyword arguments
            user_kwargs = {
                'auth_id': User.get_auth_id(auth_type, gae_user.user_id()),
                'email': gae_user.email(),
                'google_id': gae_user.user_id(),
                'first_name': first_name,
                'last_name': last_name,
            }
        elif auth_type == 'facebook':
            fb_api = Facebook(config.facebook_app_id)
            fb_api.set_access_token(facebook_access_token)
            me = fb_api.get_myself()

            if me:
                if not hasattr(me, 'email'):
                    # Facebook users might not have an email address, or they
                    # might refuse to share it with us. We can't move forward
                    # without a way to contact them, so treat it as if their
                    # credentials were missing.
                    logging.warning("Found fb user, but they had no email.")
                    return (None, 'email_not_found')

                user_kwargs = {
                    'auth_id': User.get_auth_id(auth_type, me.id),
                    'email': me.email,
                    'facebook_id': me.id,
                    'first_name': me.first_name,
                    'last_name': me.last_name,
                }
            else:
                # The connection between PERTS and facebook is expired or has
                # been used with the GraphAPI already.
                logging.error("Facebook connection expired.")
                return (None, 'credentials_missing')

        return (user_kwargs, None)
Exemplo n.º 48
0
 def get(self):
     users = db_User.get_all_users()
     return json.jsonify(users)
Exemplo n.º 49
0
    def register(self,
                 auth_type,
                 first_name=None,
                 last_name=None,
                 email=None,
                 password=None,
                 facebook_access_token=None,
                 should_subscribe=True):
        """Logs in users and registers them if they're new.

        Returns:
          User entity                 registration successful
          'credentials_missing'       looked for credentials but didn't find
                                      any of the appropriate kind.
          'email_exists:[auth_type]'  a user with that email already exists,
                                      with the specified auth type. In rare
                                      cases, we may know the email exists
                                      already, but not be able to query
                                      for it (gotta love eventual consistency),
                                      in which case the auth type will be
                                      'unknown'.
        """
        if auth_type not in config.auth_types:
            raise Exception("Bad auth_type: {}.".format(auth_type))
        if auth_type == 'own':
            if None in [email, password]:
                return 'credentials_missing'
            creation_kwargs = {
                'first_name': first_name,
                'last_name': last_name,
                'email': email,
                'auth_id': User.get_auth_id(auth_type, email),
                'hashed_password': util.hash_password(password),
            }

        # These are the third party identity providers we currently know
        # how to handle. See util_handlers.BaseHandler.get_third_party_auth().
        elif auth_type in ['google', 'facebook']:
            creation_kwargs, error = self.get_third_party_auth(
                auth_type, facebook_access_token)
            if error:
                return error
            elif not creation_kwargs:
                return 'credentials_missing'

        # Make it easy for devs to become admins.
        if auth_type == 'google' and app_engine_users.is_current_user_admin():
            creation_kwargs['is_admin'] = True

        # Pass through subscription parameter
        # Currently defaults true (planning to change later)
        creation_kwargs['should_subscribe'] = should_subscribe

        email = creation_kwargs['email']

        # Try to register the user. If a user with the same email already
        # exists, we'll get a DuplicateUser exception.
        try:
            user = User.create(**creation_kwargs)
        except DuplicateUser:
            # Attempt to retrieve the user entity which already exists.
            user = User.query(User.email == email).get()
            logging.info('Exception case with UserRegister')
            return 'email_exists:' + (user.auth_type if user else 'unknown')

        logging.info("BaseHandler created user: {}".format(user))

        # Registration succeeded; set them up.
        user.put()

        self.log_in(user)

        short_name = user.first_name if user.first_name else ''
        if user.first_name and user.last_name:
            full_name = user.first_name + ' ' + user.last_name
        else:
            full_name = user.username

        # Send them an email to confirm that they have registered.
        mandrill.send(
            to_address=email,
            subject="Welcome to Mindset Kit",
            template="signup_confirmation.html",
            template_data={
                'short_name': short_name,
                'full_name': full_name,
                'user': user,
                'domain': os.environ['HOSTING_DOMAIN']
            },
        )

        logging.info(u'BaseHandler.register()')
        logging.info(u"Sending an email to: {}.".format(email))

        return user
Exemplo n.º 50
0
 def get_all_users(self):
     users = self.collection.find()
     target_users = []
     for user in users:
         target_users.append(User(user))
     return target_users
Exemplo n.º 51
0
def load_user(id):
    return User.select().where(User.id == id).get()
Exemplo n.º 52
0
 def validate_username(self, username):
     user_count = User.select(fn.Count(
         User.username)).where(User.username == username.data).scalar()
     if user_count == 1:
         raise ValidationError(
             'There is already a user with that username.')
Exemplo n.º 53
0
 def validate_email(self, email):
     user_count = User.select(fn.Count(
         User.email)).where(User.email == email.data).scalar()
     if user_count == 1:
         raise ValidationError('There is already a user with that email.')
Exemplo n.º 54
0
def create_entry():
    # create pagination
    page, per_page, offset = get_page_args(page_parameter='page',
                                           per_page_parameter='per_page')
    total = User.query.count()
    pagination_entries = get_entries(offset=offset, per_page=per_page)
    pagination = Pagination(page=page,
                            per_page=per_page,
                            total=total,
                            css_framework='bootstrap4')

    # create forms
    form = CreateEntryForm()

    print("CREATE ENTRY REQ METHOD: " + request.method)
    # getting ip adress
    if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
        ip_address = request.environ['REMOTE_ADDR']
    else:
        # if behind a proxy
        ip_address = request.environ['HTTP_X_FORWARDED_FOR']

    try:
        resp = requests.get(
            'http://ip-api.com/json/{}'.format(ip_address)).json()
        if resp["status"] == "success":
            form.ip_address.data = resp["city"] + \
                " "+resp["regionName"]+" "+resp["country"]
        else:
            form.ip_address.data = "CANT VERIFY"
    except Exception as e:
        form.ip_address.data = "CANT VERIFY"

    print("Going in")

    if form.ip_address.data != "CANT VERIFY":
        try:
            form.coordinates.data = str(get_coordinates(form.ip_address.data))
        except:
            form.coordinates.data = "CANT VERIFY"
    else:
        form.coordinates.data = "CANT VERIFY"

    # for map
    map_entries = get_entries_for_map()

    mymap = Map(identifier="view-side",
                lat=map_entries[0][1].split(" ")[0],
                lng=map_entries[0][1].split(" ")[1],
                markers=[{
                    "icon":
                    "http://maps.google.com/mapfiles/ms/icons/red-dot.png",
                    "lat": float(coord[1].split(" ")[0]),
                    "lng": float(coord[1].split(" ")[1]),
                    "infobox": str(coord[0])
                } for coord in map_entries],
                style="height:400px;width:100%;margin:0;")

    if request.method == 'POST':
        if form.validate():
            print("IT WORKS")

            info = User(form.city.data.lower(), form.state.data.lower(),
                        form.age.data, str(form.symptoms.data),
                        form.ip_address.data.lower(), form.tested.data,
                        form.in_contact.data, form.coordinates.data)
            db.session.add(info)
            db.session.commit()
            return redirect('/')
        else:
            flash('Failed to post. Try to submit info again.')
    return render_template("create_entry.htm",
                           form=form,
                           entries=pagination_entries,
                           page=page,
                           per_page=per_page,
                           pagination=pagination,
                           mymap=mymap)
Exemplo n.º 55
0
def send_bot_details(bot, update, chat_data, item=None):
    is_group = util.is_group_message(update)
    cid = update.effective_chat.id
    user = User.from_update(update)
    first_row = list()

    if item is None:
        if is_group:
            return

        try:
            text = update.message.text
            bot_in_text = re.findall(settings.REGEX_BOT_IN_TEXT, text)[0]
            item = Bot.by_username(bot_in_text)

        except Bot.DoesNotExist:
            update.message.reply_text(
                util.failure(
                    "This bot is not in the @BotList. If you think this is a mistake, see the /examples for /contributing."
                ))
            return

    if item.approved:
        # bot is already in the botlist => show information
        txt = item.detail_text
        if item.description is None and not Keyword.select().where(
                Keyword.entity == item).exists():
            txt += ' is in the @BotList.'
        btn = InlineCallbackButton(captions.BACK_TO_CATEGORY,
                                   CallbackActions.SELECT_BOT_FROM_CATEGORY,
                                   {'id': item.category.id})
        first_row.insert(0, btn)
        first_row.append(
            InlineKeyboardButton(captions.SHARE,
                                 switch_inline_query=item.username))

        # if cid in settings.MODERATORS:
        first_row.append(
            InlineKeyboardButton("📝 Edit",
                                 callback_data=util.callback_for_action(
                                     CallbackActions.EDIT_BOT,
                                     {'id': item.id})))
    else:
        txt = '{} is currently pending to be accepted for the @BotList.'.format(
            item)
        if cid in settings.MODERATORS:
            first_row.append(
                InlineKeyboardButton("🛃 Accept / Reject",
                                     callback_data=util.callback_for_action(
                                         CallbackActions.APPROVE_REJECT_BOTS,
                                         {'id': item.id})))

    if is_group:
        reply_markup = InlineKeyboardMarkup([])
    else:
        buttons = [first_row]
        favorite_found = Favorite.search_by_bot(user, item)
        if favorite_found:
            buttons.append([
                InlineKeyboardButton(captions.REMOVE_FAVORITE_VERBOSE,
                                     callback_data=util.callback_for_action(
                                         CallbackActions.REMOVE_FAVORITE, {
                                             'id': favorite_found.id,
                                             'details': True
                                         }))
            ])
        else:
            buttons.append([
                InlineKeyboardButton(captions.ADD_TO_FAVORITES,
                                     callback_data=util.callback_for_action(
                                         CallbackActions.ADD_TO_FAVORITES, {
                                             'id': item.id,
                                             'details': True
                                         }))
            ])
        reply_markup = InlineKeyboardMarkup(buttons)
    reply_markup, callback = botlistchat.append_delete_button(
        update, chat_data, reply_markup)

    # Should we ever decide to show thumbnails *shrug*
    # if os.path.exists(item.thumbnail_file):
    #     preview = True
    #     photo = '[\xad]({})'.format('{}/thumbnail/{}.jpeg'.format(
    #         settings.API_URL,
    #         item.username[1:]
    #     ))
    #     log.info(photo)
    #     txt = photo + txt
    # else:
    #     preview = False

    msg = bot.formatter.send_or_edit(cid,
                                     txt,
                                     to_edit=util.mid_from_update(update),
                                     reply_markup=reply_markup)
    callback(msg)
    Statistic.of(update, 'view-details', item.username, Statistic.ANALYSIS)
    return CallbackStates.SHOWING_BOT_DETAILS
Exemplo n.º 56
0
import random
from model import db, Donor, Donation, User
from passlib.hash import pbkdf2_sha256

db.connect()

# This line will allow you "upgrade" an existing database by
# dropping all existing tables from it.
db.drop_tables([Donor, Donation, User])

db.create_tables([Donor, Donation, User])

alice = Donor(name="Alice")
alice.save()

bob = Donor(name="Bob")
bob.save()

charlie = Donor(name="Charlie")
charlie.save()

donors = [alice, bob, charlie]

for x in range(30):
    Donation(donor=random.choice(donors), value=random.randint(100,
                                                               10000)).save()

User(name='admin', password=pbkdf2_sha256.hash("password")).save()
Exemplo n.º 57
0
 def get(self, user_id):
     user = User.find_by_id(user_id)
     if user:
         return user.json()
     return {'message': 'User not found.'}, 400
Exemplo n.º 58
0
def example_data():
    """Create example data for the test database."""
    Dislike.query.delete()
    Stargazer.query.delete()
    Watcher.query.delete()
    Follower.query.delete()
    Contributor.query.delete()
    RepoLanguage.query.delete()
    Language.query.delete()
    Repo.query.delete()
    Account.query.delete()
    User.query.delete()

    jane = User(user_id="1",
                login="******",
                name="Jane",
                last_crawled=datetime.datetime.now(),
                last_crawled_depth=2)
    alex = User(user_id="2",
                login="******",
                name="Alex",
                last_crawled=(datetime.datetime.now() -
                              datetime.timedelta(weeks=6)),
                last_crawled_depth=2)
    kelly = User(user_id="3", login="******", name="Kelly")
    db.session.add_all([jane, alex, kelly])
    db.session.commit()

    jane_account = Account(user_id="1", access_token="abc123")
    db.session.add(jane_account)
    db.session.commit()

    py_repo = Repo(repo_id="1",
                   name="python-repo",
                   description="A Python repository",
                   owner_id="1",
                   last_crawled=datetime.datetime.now(),
                   last_crawled_depth=2,
                   url="https://github.com/jhacks/python-repo",
                   stargazers_count=2)
    js_repo = Repo(repo_id="2",
                   name="js-repo",
                   description="A Javascript repository",
                   owner_id="1",
                   last_crawled=(datetime.datetime.now() -
                                 datetime.timedelta(weeks=6)),
                   last_crawled_depth=1,
                   url="https://github.com/jhacks/js-repo",
                   stargazers_count=1)
    db.session.add_all([py_repo, js_repo])
    db.session.commit()

    astar = Stargazer(repo_id="1", user_id="2")
    kstar = Stargazer(repo_id="1", user_id="3")
    kstar_js = Stargazer(repo_id="2", user_id="3")
    a_dislike_js = Dislike(repo_id="2", user_id="2")
    # k_dislike_js = Dislike(repo_id="2", user_id="3")
    db.session.add_all([astar, kstar, kstar_js, a_dislike_js])
    db.session.commit()

    kwatch = Watcher(repo_id="1", user_id="3")
    a_j_follow = Follower(user_id="1", follower_id="2")
    k_j_follow = Follower(user_id="1", follower_id="3")
    j_a_follow = Follower(user_id="2", follower_id="1")
    db.session.add_all([kwatch, a_j_follow, k_j_follow, j_a_follow])
    db.session.commit()

    jcon = Contributor(repo_id="1", user_id="1")
    kcon = Contributor(repo_id="1", user_id="3")
    db.session.add_all([jcon, kcon])
    db.session.commit()

    # python = Topic(topic_id="1", topic_name="python")
    # api = Topic(topic_id="2", topic_name="api")
    # db.session.add_all([python, api])
    # db.session.commit()

    # py_rep1 = RepoTopic(topic_id="1", repo_id="1")
    # api_rep1 = RepoTopic(topic_id="2", repo_id="1")
    # db.session.add_all([py_rep1, api_rep1])
    # db.session.commit()

    py_lang = Language(language_id="1", language_name="python")
    c_lang = Language(language_id="2", language_name="c")
    db.session.add_all([py_lang, c_lang])
    db.session.commit()

    py_lang_rep1 = RepoLanguage(language_id="1",
                                repo_id="1",
                                language_bytes=5000)
    c_lang_rep1 = RepoLanguage(language_id="2",
                               repo_id="1",
                               language_bytes=100)
    db.session.add_all([py_lang_rep1, c_lang_rep1])
    db.session.commit()
Exemplo n.º 59
0
from flask import Flask, render_template, request, redirect, url_for
from model import User
# from wtforms import StringField, Form, SubmitField
# from wtforms.validators import DataRequired
import quickstart
import sqlite3
db = 'challenge.db'
conn = sqlite3.connect(db)
c = conn.cursor()

application = app = Flask(__name__)
elias = User.get_recent_user_from_id("2")


@app.route('/', methods=['GET', 'POST'])
def index():
    elias = User.get_recent_user_from_id("2")
    #load the homepage
    if request.method == 'POST':
        print(request.form)
        if 'Dosed' in request.form:
            elias.just_dosed()
            #reset days to 0 and store in database
        elif 'Meds' in request.form:
            try:
                elias.reup(int(request.form['Meds']))
            except:
                pass
        elif 'Schedule' in request.form:
            quickstart.main()
    return render_template('home.html',
Exemplo n.º 60
0
def add_user(username, password):
    new = User(username=username, password=password)
    session.add(new)
    session.commit()