Esempio n. 1
0
 def post(self):    
     email     = self.get_argument("email",None)
     password  = self.get_argument("password",None)        
     import hashlib
     errMsg = None
     if email is None:
         errMsg = "Email不能为空"
         return self.render('login.html',user=self.currentUserInfo(),errMsg=errMsg)
     if password is None:
         errMsg = "Email不能为空"
         return self.render('login.html',user=self.currentUserInfo(),errMsg=errMsg)
     
     user_key = hashlib.md5(email).hexdigest()
     user = User()
     user_data = user.getDetail(user_key)
     
     if user_data is None:            
         errMsg = "用户不存在"
     else:
         if hashlib.md5(password).hexdigest() != user_data['password']:
             errMsg = "用户名或密码不正确"      
         else:
             urlname = user_data['nickname']                
             self.set_secure_cookie('user_email',user_data['email'])
             self.set_secure_cookie('user_nickname',urlname)
             self.set_secure_cookie('user_urlname',urlname)
             self.set_secure_cookie('user_key',user_key)
             self.set_secure_cookie('user_avatar',user_data['avatar'])
             #print "login succ!"
             return self.redirect('/')
             
     self.render('login.html',user=self.currentUserInfo(),errMsg=errMsg)
Esempio n. 2
0
    def parseTriggerFields(self):
        if not self.request.body:
            raise InvalidTriggerFieldsException()

        body = json.loads(self.request.body)
        if IFTTT_PARAM_TRIGGERFIELDS_KEY not in body:
            raise InvalidTriggerFieldsException()

        triggerFields = body[IFTTT_PARAM_TRIGGERFIELDS_KEY]
        if not triggerFields or \
        IFTTT_TRIGGER_FIELD_SHOW_SPOILERS_KEY not in triggerFields or \
        IFTTT_TRIGGER_FIELD_SHOW_NSFW_KEY not in triggerFields:
            raise InvalidTriggerFieldsException()

        username      = triggerFields[IFTTT_TRIGGER_FIELD_USERNAME_KEY]
        show_spoilers = ('yes' == triggerFields[IFTTT_TRIGGER_FIELD_SHOW_SPOILERS_KEY])
        show_nsfw     = ('yes' == triggerFields[IFTTT_TRIGGER_FIELD_SHOW_NSFW_KEY])

        # Create user if it doesn't already exist
        self.user = User.all().filter('steam_username =', username).get()
        if self.user is None:
            if is_valid_username(username):
                self.user = User(
                    steam_username      = username,
                    steam_show_spoilers = show_spoilers,
                    steam_show_nsfw     = show_nsfw
                )
                self.user.put()
            else:
                raise InvalidTriggerFieldsException()
Esempio n. 3
0
def get_groups():
    appid = request.appid
    uid = request.uid

    groups = Group.get_groups(g._db, appid, uid)
    fields = request.args.get("fields", '')

    fields = fields.split(",")
    for obj in groups:
        gid = obj['id']
        if "members" in fields:
            members = Group.get_group_members(g._db, gid)
            for m in members:
                name = User.get_user_name(g.rds, appid, m['uid'])
                m['name'] = name if name else ''
                if not m.get('nickname'):
                    m['nickname'] = ""
                    
            obj['members'] = members
     
        if "quiet" in fields:
            q = User.get_group_do_not_disturb(g.rds, appid, uid, gid)
            obj['do_not_disturb'] = bool(q)
        
    resp = {"data":groups}
    return make_response(200, resp)
Esempio n. 4
0
 def get(self,key):
     user      = User()
     userInfo = UserInfo()
     avatar =Avatar()
     user.delete(key)
     userInfo.delete(key)
     avatar.delete(key)
Esempio n. 5
0
def unbind_device_token():
    rds = g.rds
    appid = request.appid
    uid = request.uid
    obj = json.loads(request.data)

    device_token = obj.get("apns_device_token", "")
    pushkit_device_token = obj.get("pushkit_device_token", "")
    ng_device_token = obj.get("ng_device_token", "")
    xg_device_token = obj.get("xg_device_token", "")
    xm_device_token = obj.get("xm_device_token", "")
    hw_device_token = obj.get("hw_device_token", "")
    gcm_device_token = obj.get("gcm_device_token", "")
    jp_device_token = obj.get("jp_device_token", "")

    if not device_token and not pushkit_device_token \
       and not ng_device_token and not xg_device_token \
       and not xm_device_token and not hw_device_token \
       and not gcm_device_token and not jp_device_token:
        raise ResponseMeta(400, "invalid param")


    User.reset_user_device_token(rds, appid, uid,
                                 device_token, pushkit_device_token,
                                 ng_device_token, xg_device_token, 
                                 xm_device_token, hw_device_token,
                                 gcm_device_token, jp_device_token)

    return make_json_response({"success":True}, 200)
Esempio n. 6
0
 def POST(self, request):
     body = request.values.get('Body')
     if not body:
         body = request.get_json()['Body']
         
     print("received message %s" % body)
 
     phone = request.values.get('From')
     if not phone:
         phone = request.get_json()['From']
 
     credentials = User.credentials(phone)
     
     try:
         sender = User.login(*credentials)
     except (ResourceRequestBadRequest, KeyError):
         return ('', 401)
     
     # Languages
     if body.startswith('add'):
         return self._add_language(sender, body, request)
     elif body.startswith('remove'):
         return self._remove_language(sender, body, request)
     
     # Pen Pals
     elif body.startswith('report'):
         return self._report_pen_pal(sender, body, request)
     elif body.startswith('swap'):
         return self._swap_pen_pal(sender, body, request)
     
     # Messages
     else:
         return self._queue_message(sender, body, request)
Esempio n. 7
0
def group_member_setting(gid, memberid):
    appid = request.appid
    uid = request.uid

    if uid != memberid:
        raise ResponseMeta(400, "setting other is forbidden")

    obj = json.loads(request.data)
    if obj.has_key('quiet'):
        User.set_group_do_not_disturb(g.rds, appid, uid, gid, obj['quiet'])
    elif obj.has_key('do_not_disturb'):
        User.set_group_do_not_disturb(g.rds, appid, uid, gid, obj['do_not_disturb'])
    elif obj.has_key('nickname'):
        Group.update_nickname(g._db, gid, uid, obj['nickname'])
        v = {
            "group_id":gid,
            "timestamp":int(time.time()),
            "nickname":obj['nickname'],
            "member_id":uid
        }
        op = {"update_member_nickname":v}
        send_group_notification(appid, gid, op, None)        
    else:
        raise ResponseMeta(400, "no action")

    resp = {"success":True}
    return make_response(200, resp)
Esempio n. 8
0
    def deleteToken(self, args):
        self._start(args)
        print('Delete token: please authenticate...')
        
        while True:
            admin_username = raw_input('Enter admin username: '******'Enter admin password: '******'Please sign in using administrator credentials.')
            elif not User.users().get(username=admin_username).authenticate(admin_password): #Db.instance().authenticate_user(admin_username, admin_password):
                print("Username/password don't match.")
            else:
                break

        username = raw_input('Enter username for token to delete: ')
        user = User.users().get(username=username)
        if user:
            token = Token.tokens().get_token_for_user(user=user)
            if token:
                token.delete()
                print('Deleted token belonging to %s.' % username)
            else:
                print('%s has no tokens to delete.' % username)
        else:
            print('%s has no tokens to delete.' % username)
Esempio n. 9
0
    def createUser(self, args):
        self._start(args)

        while True:
            username = raw_input('Enter email address: ')
            if User.users().get(username=username):
                print('Username already exists. Please pick another username.')
            else:
                break
            print('username: %s' % username)
        while True:
            is_admin = raw_input('Admininstrative user? (y/N): ')
            if (len(is_admin) == 0) or (is_admin.upper() == 'N'):
                admin = False
                break
            elif is_admin.upper() == 'Y':
                admin = True
                break
        while True:
            password_1 = getpass.getpass('Enter password: '******'Re-enter password: '******'Passwords do not match.')
            else:
                break

        user = User(username, password_1, admin)
        user.save()
        # Db.instance().insert_user(username, password_1, admin)
        print('Successfully created user %s' % username)
Esempio n. 10
0
	def get(self):
		template_params={}
		contact_user_email= self.request.get('contact_user_email')
		nick_name= self.request.get('nick_name')
		user = None
		if self.request.cookies.get('our_token'):    #the cookie that should contain the access token!
			user = User.checkToken(self.request.cookies.get('our_token'))
		if not user:
			html = template.render("web/templates/index.html", {})
			self.response.write(html)
			return
		userCon= User.checkIfUesr(contact_user_email)
		if userCon is None:
			return
#		contactlist= Contact.getAllContactsPerUser(user)
#		for c in contactlist:
#			if c..contact_user_email is contact_user_email:
#				return
		contact=Contact()
		contact.contact_user_email=contact_user_email
		contact.nick_name=nick_name
		contact.user=user.key
		contact.put()
		self.response.set_cookie('our_token', str(user.key.id()))
		self.response.write(json.dumps({'status':'OK'}))
		return
Esempio n. 11
0
    def createToken(self, args):
        self._start(args)
        # Do a check to see if any admins exist before proceeding.
        print('Create token: please authenticate...')
        
        while True:
            admin_username = raw_input('Enter admin username: '******'Enter admin password: '******'Please sign in using administrator credentials.')
            elif not User.users().get(username=admin_username).authenticate(admin_password):
                print("Username/password don't match.")
            else:
                break

        username = raw_input('Enter username to create a token for: ')
        user = User.users().get(username=username)
        if user:
            try:
                token = Token(user=user)
                token.save()
                print(str('Token %s created for %s' % (token.token, username)))
            except Exception as e:
                print("EXCEPTION **** %s" % e)
                print('A token already exists for %s. Doing nothing.' % username)
        else:
            print('A user with username %s does not exist.' % username)
Esempio n. 12
0
def users():
    form = NewUserForm()

    if form.validate_on_submit():
        email, name = form.email.data, form.name.data
        user = User(email, name)

        db.session.add(user)
        db.session.commit()
        app.logger.info('%s manually created new user with email %s and id: %s',
                        current_user.id, email, user.id)

        code = user.login_code(app.config['SECRET_KEY'])
        msg = Message('Welcome to the EMF website',
                      sender=app.config['CONTACT_EMAIL'],
                      recipients=[email])
        msg.body = render_template('emails/manually-added-user.txt',
                                   user=user, code=code)
        mail.send(msg)

        flash('Created account for: %s' % name)
        return redirect(url_for('.users'))

    users = User.query.order_by(User.id).options(joinedload(User.permissions)).all()
    return render_template('admin/users/users.html', users=users, form=form)
Esempio n. 13
0
 def get(self):
     uname = self.get_current_user()
     user = User.get_user_by_name(uname)
     order = get_order()
     story = Story.get_by_porder(order)
     sid = self.get_argument("sid",None)
     if sid is not None:
         story=Story.get_by_sid(sid)
     article = Article.get_all_Astory(200)
     usedStory = Story.get_all_story()
     temp = []
     for one in usedStory:
         if one.porder > 0 and one.porder <= order:
             temp.append(one)
     usedStory = temp
     reArticles = Article.get_all(200)
     Rarticle = sorted(reArticles,BaseHandler.rank)
     Ruser = User.get_all_user(100)
     if len(Rarticle) > 6:
         Rarticle=Rarticle[:6]
     if len(usedStory)>3:
         usedStory=usedStory[:3]
     if len(Ruser)>9:
         Ruser=Ruser[:9]
     self.render("story.html",user=user,Rarticle=Rarticle,Article=article,usedStory=usedStory,Ruser=Ruser,story=story)
Esempio n. 14
0
def index():
    if not g.user.is_super_admin():
        abort(403)
    form = FrameworkOrderForm(request.form)
    if request.method == 'POST' and form.validate():
        order = FrameworkOrder.add(group=Group.get(form.group.data),
                                   agents=Agent.gets(form.agents.data),
                                   description=form.description.data,
                                   money=int(
                                       round(float(form.money.data or 0))),
                                   client_start=form.client_start.data,
                                   client_end=form.client_end.data,
                                   reminde_date=form.reminde_date.data,
                                   direct_sales=User.gets(
                                       form.direct_sales.data),
                                   agent_sales=User.gets(form.agent_sales.data),
                                   contract_type=form.contract_type.data,
                                   creator=g.user,
                                   contract_status=2,
                                   contract=request.values.get('contract'),
                                   create_time=datetime.now())
        order.add_comment(g.user, u"导入了框架订单")
        flash(u'导入框架订单成功', 'success')
        return redirect(order.info_path())
    else:
        form.client_start.data = datetime.now().date()
        form.client_end.data = datetime.now().date()
        form.reminde_date.data = datetime.now().date()
    return tpl('insert_framework_order.html', form=form)
Esempio n. 15
0
def register_user():
	email = request.form['email']
	password = request.form['password']

	User.register(email, password)

	return render_template('profile.html', email=session['email'])
Esempio n. 16
0
    def _is_admin(self):
        """ check for admin rights of this user 
            1. in the current session object
            2. then in the curretn google user
            
        """
        
        # if already authed as an admin - then must have the person record already so carry on
        if self._req.sesh().can_edit():
            return True
        
        # not currently an admin and hit an admin url so check or get gae admin user
        google_user = users.get_current_user()
        
        # no google user then revert to normal redirect back to blog
        if not google_user: 
            return False

        # if we got here then we must have good google admin but no exisstng admin session    
        
        # make sure this google admin is given an authenticated admin session
        self._req.sesh().set_authenticated(google_user.user_id(), 'admin', google_user.email())
        
        # create user
        user = User(self._req.sesh())
        user.create_new_user(google_user.user_id(), 'admin', google_user.email())

        return True
        
        
Esempio n. 17
0
    def _do_login(self, response):
        username = self.get_argument("username", None)
        password = self.get_argument("password", None)
        if not username or not password:
            # do something
            self.flash.error = "You must enter a username and password to proceed. Please try again."
            return 
        pw = hashlib.sha1(password).hexdigest()
        username = User.normalize(username)
        user = User.lookup(username)
        #check the password.
        if not user or user['password'] != pw:
            # do something
            self.flash.error = "Login not valid"
            return
        # check if user is suspended.
        if user.is_suspended() :
            self.flash.error = "Sorry the account you specified has been suspended."
            return    
        user.history.last_login = datetime.datetime.utcnow()
        Mongo.db.ui['users'].update({'_id': username}, {
                                                    '$set' : {'history.last_login': user.history.last_login},
                                                    '$inc' : {'history.num_logins' : 1}
                                                    })        
        #add to the session.
        self.session['username'] = user._id
        #check keep_logged_in
        if self.get_argument("keep_logged_in", False) == "on" :
            self.session['keep_logged_in'] = True
            
        self.set_current_user(user)
#        self.session['current_user']= user._id
        self.flash.notice = "Welcome, %s" % user._id
        self.write(username)
        self.finish("finished")
Esempio n. 18
0
 def post(self):
     _id = self.get_argument("u_id", None)
     User.updateUser(_id,0)
     self.finish("finished")  
     
     
     
Esempio n. 19
0
def log_in_route(request):
    """
    Log in user.
    """

    name = request['params'].get('name') or ''
    name = name.lower()

    user = User.get(name=name)
    if not user:
        user = User.get(email=request['params'].get('name'))
    if not user:
        return 404, {
            'errors': [{
                'name': 'name',
                'message': c('no_user'),
            }],
            'ref': 'FYIPOI8g2nzrIEcJYSDAfmti'
        }
    if not user.is_password_valid(request['params'].get('password')):
        return 400, {
            'errors': [{
                'name': 'password',
                'message': c('no_match'),
            }],
            'ref': 'UwCRydZ7Agi7LYKv9c1y07ft'
        }
    return _log_in(user)
Esempio n. 20
0
def transfer(ticket_id):
    try:
        ticket = current_user.tickets.filter_by(id=ticket_id).one()
    except NoResultFound:
        return redirect(url_for('tickets.main'))

    if not ticket or not ticket.paid or not ticket.type.is_transferable:
        return redirect(url_for('tickets.main'))

    form = TicketTransferForm()

    if form.validate_on_submit():
        assert ticket.user_id == current_user.id
        email = form.email.data

        if not User.does_user_exist(email):
            new_user = True

            # Create a new user to transfer the ticket to
            to_user = User(email, form.name.data)
            db.session.add(to_user)
            db.session.commit()

        else:
            new_user = False
            to_user = User.query.filter_by(email=email).one()

        ticket.transfer(from_user=current_user, to_user=to_user)

        app.logger.info('Ticket %s transferred from %s to %s', ticket,
                        current_user, to_user)

        # Alert the users via email
        code = to_user.login_code(app.config['SECRET_KEY'])

        msg = Message("You've been sent a ticket to EMF 2016!",
                      sender=app.config.get('TICKETS_EMAIL'),
                      recipients=[to_user.email])
        msg.body = render_template('emails/ticket-transfer-new-owner.txt',
                            to_user=to_user, from_user=current_user,
                            new_user=new_user, code=code)

        if feature_enabled('ISSUE_TICKETS'):
            attach_tickets(msg, to_user)

        mail.send(msg)
        db.session.commit()

        msg = Message("You sent someone an EMF 2016 ticket",
                      sender=app.config.get('TICKETS_EMAIL'),
                      recipients=[current_user.email])
        msg.body = render_template('emails/ticket-transfer-original-owner.txt',
                            to_user=to_user, from_user=current_user)

        mail.send(msg)

        flash("Your ticket was transferred.")
        return redirect(url_for('tickets.main'))

    return render_template('ticket-transfer.html', ticket=ticket, form=form)
Esempio n. 21
0
def index():
    if not g.user.is_super_leader():
        abort(403)
    salers = User.sales()
    if request.method == 'POST':
        f_saler = int(request.values.get('f_saler', 0))
        t_saler = int(request.values.get('t_saler', 0))
        if not f_saler or not t_saler:
            flash(u'请选择正确的员工', 'danger')
            return tpl('/account/turnover/index.html', salers=salers)
        f_user = User.get(f_saler)
        t_user = User.get(t_saler)
        client_orders = ClientOrder.all()
        douban_orders = DoubanOrder.all()
        for k in client_orders:
            if f_user in k.salers and t_user not in k.replace_sales:
                k.replace_sales = k.replace_sales + [t_user]
                k.save()
            if k.creator == f_user and t_user not in k.replace_sales:
                k.replace_sales = k.replace_sales + [t_user]
                k.save()
        for k in douban_orders:
            if f_user in k.salers and t_user not in k.replace_sales:
                k.replace_sales = k.replace_sales + [t_user]
                k.save()
            if k.creator == f_user and t_user not in k.replace_sales:
                k.replace_sales = k.replace_sales + [t_user]
                k.save()
        flash(u'成功', 'success')
    return tpl('/account/turnover/index.html', salers=salers)
Esempio n. 22
0
def signup():
    if current_user.is_authenticated():
        return redirect(url_for('tickets'))
    form = SignupForm(request.form, next=request.args.get('next'))

    if request.method == 'POST' and form.validate():
        user = User(form.email.data, form.name.data)
        user.set_password(form.password.data)
        db.session.add(user)
        try:
            db.session.commit()
        except IntegrityError, e:
            app.logger.warn('Adding user raised %r, assuming duplicate email', e)
            flash("This email address %s is already in use. Please log in, or reset your password if you've forgotten it." % (form.email.data))
            return redirect(url_for('login'))
        login_user(user)

        # send a welcome email.
        msg = Message("Welcome to Electromagnetic Field",
                sender=app.config['TICKETS_EMAIL'],
                recipients=[user.email])
        msg.body = render_template("welcome-email.txt", user=user)
        mail.send(msg)

        return redirect(form.next.data or url_for('tickets'))
Esempio n. 23
0
def add_group_member(gid):
    appid = request.appid
    obj = json.loads(request.data)
    inviter = None
    if type(obj) is dict:
        if 'members' in obj:
            members = obj['members']
            inviter = obj.get('inviter')
        else:
            members = [obj]
    else:
        members = obj

    if len(members) == 0:
        return ""
    
    group = Group.get_group(g._db, gid)
    if not group:
        raise ResponseMeta(400, "group non exists")
    
    # 支持members参数为对象数组
    memberIDs = map(lambda m:m['uid'] if type(m) == dict else m, members)
    
    g._db.begin()
    for member_id in memberIDs:
        try:
            Group.add_group_member(g._db, gid, member_id)
            # 可能是重新加入群
            User.reset_group_synckey(g.rds, appid, member_id, gid)
        except umysql.SQLError, e:
            #1062 duplicate member
            if e[0] != 1062:
                raise
Esempio n. 24
0
 def from_user(self, receivers=None, text=None, *_):
     if receivers is None:
         return ERR_NORECIPIENT(self.command, self.actor)
     if text is None:
         return ERR_NOTEXTTOSEND(self.actor)
     resp = []
     # TODO: check for ERR_TOOMANYTARGETS
     for receiver in receivers.split(','):
         if Channel.exists(receiver):
             users = [user
                      for user in Channel.get(receiver).users
                      if user is not self.user]
             resp.append(M(
                 ActorCollection(users),
                 self.command, str(receiver), text,
                 prefix=str(self.user)))
         elif User.exists(receiver):
             resp.append(M(
                 Actor.by_user(User.get(receiver)),
                 self.command, str(receiver), text,
                 prefix=str(self.user)))
         # TODO: Implement wildcards
         # TODO: check for ERR_WILDTOPLEVEL, RPL_AWAY, ERR_NOTOPLEVEL
         else:
             resp.append(ERR_NOSUCHNICK(receiver, self.actor))
     return resp
Esempio n. 25
0
def client_orders_distribute():
    if request.method == 'POST':
        order_id = request.values.get('order_id', '')
        operator = request.values.get('operater_ids', '')
        order = ClientOrder.get(order_id)
        if operator:
            operater_users = User.gets(operator.split(','))
            to_users = operater_users
            for k in order.medium_orders:
                k.operaters = operater_users
                k.save()
        else:
            for k in order.medium_orders:
                k.operaters = []
                k.save()
            to_users = []
        if to_users:
            context = {"to_users": to_users + [g.user],
                       "operater_users": operater_users,
                       "action_msg": u'分配执行人员',
                       "info": '',
                       "order": order}
            outsource_distribute_signal.send(
                current_app._get_current_object(), context=context)
        return redirect(url_for('outsource.client_orders_distribute'))

    orders = [k for k in ClientOrder.query.all() if k.medium_orders and k.contract != '']
    operaters = User.gets_by_team_type(
        TEAM_TYPE_OPERATER) + User.gets_by_team_type(TEAM_TYPE_OPERATER_LEADER)
    return display_orders(orders, 'client_orders_distribute.html', title=u"客户订单分配", operaters=operaters)
Esempio n. 26
0
 def getUserObject(self, user = None):
     
     from google.appengine.api import users
     from models.user import User
     
     if user == None:
         user = users.get_current_user()
     
     userId = self.getUserId(user)
     if not userId:
         return None
     
     query = User.all()
     query.filter("id =", userId)
     userObject = query.get()
     
     if userObject == None:
         if type(user) == users.User:
             userObject = User(
                 id = userId,
                 username = user.nickname().split('@')[0],
                 name = user.nickname().split('@')[0]
             )
         else:
             userObject = User(
                 id = userId,
                 username = userId,
                 name = userId
             )
         userObject.put()
     
     return userObject
Esempio n. 27
0
 def get(self):
     uname = self.get_current_user()
     user = User.get_user_by_name(uname)
     order = get_order()
     card = Card.get_by_porder(order)
     cid = self.get_argument("cid",None)
     if cid is not None:
         card=Card.get_by_cid(cid)
     article = Article.get_all_Acard(200)
     usedCard = Card.get_all_card()
     temp = []
     for one in usedCard:
         if 0 < one.porder and one.porder <= order:
             temp.append(one)
     usedCard = temp
     reArticles = Article.get_all(200)
     Rarticle = sorted(reArticles,BaseHandler.rank)
     if len(Rarticle) > 6:
         Rarticle = Rarticle[:6]
     Ruser = User.get_all_user(100)
     if len(Ruser)>9:
         Ruser = Ruser[:9]
     if len(usedCard)>3:
         usedCard = usedCard[:3]
     self.render("card.html",user=user,Rarticle=Rarticle,Article=article,usedCard=usedCard,Ruser=Ruser,card=card)
Esempio n. 28
0
def group_member_setting(gid, memberid):
    appid = request.appid
    uid = memberid

    group = Group.get_group(g._db, gid)
    if not group:
        raise ResponseMeta(400, "group non exists")
    
    obj = json.loads(request.data)
    if obj.has_key('do_not_disturb'):
        User.set_group_do_not_disturb(g.rds, appid, uid, gid, obj['do_not_disturb'])
    elif obj.has_key('nickname'):
        Group.update_nickname(g._db, gid, uid, obj['nickname'])
        v = {
            "group_id":gid,
            "group_name":group['name'],
            "timestamp":int(time.time()),
            "nickname":obj['nickname'],
            "member_id":uid
        }
        op = {"update_member_nickname":v}
        send_group_notification(appid, gid, op, None)
    elif obj.has_key('mute'):
        mute = 1 if obj['mute'] else 0
        Group.update_mute(g._db, gid, uid, mute)
        content = "%d,%d,%d" % (gid, memberid, mute)
        publish_message(g.rds, "group_member_mute", content)
    else:
        raise ResponseMeta(400, "no action")

    resp = {"success":True}
    return make_response(200, resp)
Esempio n. 29
0
 def post(self):
     email = self.request.get('email'),
     User.create_user(email, unique_properties=['email'],
                     password_raw=self.request.get('password'),
                     email=email,
                     name= self.request.get('name'),
                     image= self.request.get('image'))
Esempio n. 30
0
 def get(self, param):
     """ => user.list """
     swbkuerzel = self.get_current_user()
     #self.write("get (param): " + str(param))
     user = User(swbkuerzel)
     self.render("user_list.html", users=user.find_all())
     self.flush()
Esempio n. 31
0
 def test_roles_and_permissions(self):
     Role.insert_roles()
     u = User(email='*****@*****.**', password='******')
     self.assertTrue(u.can(Permission.WRITE_ARTICLE))
     self.assertFalse(u.can(Permission.MODERATE_COMMENT))
Esempio n. 32
0
def delete_user():
    """Remove a user"""
    user_id = int(input("Please enter your user id: "))
    User.remove(user_id)
    print(f"User removed")
Esempio n. 33
0
 def make_user(self, data, **kwargs):
     from models.user import User
     return User(**data)
Esempio n. 34
0
 def test_base_model_input_dict(self):
     """Test if able to add attiributes using dictionary"""
     attributes = {"id": "1"}
     self.user1 = User(**attributes)
     self.assertEqual(attributes['id'], self.user1.id)
Esempio n. 35
0
class TestUser(unittest.TestCase):
    """User uuid testing"""
    def setUp(self):
        """Set up User Objects for testing"""
        self.user1 = User()
        time.sleep(1)
        self.user2 = User()
        User.email = ''
        User.password = ''
        User.first_name = ''
        User.last_name = ''

    def test_uuid(self):
        """Test that UUID was created"""
        self.assertTrue(hasattr(self.user1, 'id'))

    def test_uniq_uuid(self):
        """Test that the UUIDs created are unique"""
        self.assertNotEqual(self.user1.id, self.user2.id)

    def test_user_model(self):
        """Test that object created is of User"""
        self.assertIsInstance(self.user1, User)

    def test_user_model_BaseModel(self):
        """Test that object created is of BaseModel"""
        self.assertIsInstance(self.user1, BaseModel)

    def test_uuid_str(self):
        """Test that id is of type string"""
        self.assertIsInstance(self.user1.id, str)

    def test_created_at(self):
        """Test that objects are created with datetime"""
        self.assertNotEqual(self.user1.created_at, self.user2.created_at)

    def test_create_update_equal(self):
        """Test that created_at and updated_at or equal upon creation"""
        self.assertEqual(self.user1.created_at, self.user1.updated_at)

    def test_create_update_not_equal(self):
        """Test that created_at datetime is not the same as updated_at"""
        self.user1.updated_at = datetime.now()
        self.assertNotEqual(self.user1.created_at, self.user1.updated_at)

    def test_created_at_exists(self):
        """Test the created_at datetime object exists"""
        self.assertTrue(hasattr(self.user1, 'created_at'))

    def test_updated_at_exists(self):
        """Test that updated_at datetime object exists"""
        self.assertTrue(hasattr(self.user1, 'updated_at'))

    def test_created_at_datetime(self):
        """Test that created_at is a datetime object"""
        self.assertTrue(isinstance(self.user1.created_at, datetime))

    def test_updated_at_datetime(self):
        """Test that updated_at is a datetime object"""
        self.assertTrue(isinstance(self.user1.updated_at, datetime))

    def test_class_attribute_set(self):
        """Test if class attributes are set"""
        self.assertEqual(User.first_name, '')
        self.assertEqual(User.last_name, '')
        self.assertEqual(User.email, '')
        self.assertEqual(User.password, '')

    def test_base_model_input_dict(self):
        """Test if able to add attiributes using dictionary"""
        attributes = {"id": "1"}
        self.user1 = User(**attributes)
        self.assertEqual(attributes['id'], self.user1.id)

    def test_class_attribute_id(self):
        """Test class attribute id"""
        self.assertTrue(hasattr(self.user1, 'id'))
        self.assertTrue(isinstance(self.user1.id, str))

    def test_class_attribute_set(self):
        """Test if class attributes are set"""
        self.assertEqual(self.user1.first_name, '')
        self.assertEqual(self.user1.last_name, '')
        self.assertEqual(self.user1.email, '')
        self.assertEqual(self.user1.password, '')

    def test_class_attribute_first_name(self):
        """Test class attribute first name"""
        self.assertTrue(hasattr(self.user1, 'first_name'))
        User.first_name = ''
        self.assertTrue(isinstance(self.user1.first_name, str))
        self.assertEqual(self.user1.first_name, '')

    def test_class_attribute_last_name(self):
        """Test class attribute last name"""
        self.assertTrue(hasattr(self.user1, 'last_name'))
        User.last_name = ''
        self.assertTrue(isinstance(self.user1.last_name, str))
        self.assertEqual(self.user1.last_name, '')

    def test_class_attribute_email(self):
        """Test class attribute email"""
        self.assertTrue(hasattr(self.user1, 'email'))
        User.email = ''
        self.assertTrue(isinstance(self.user1.email, str))
        self.assertEqual(self.user1.email, '')

    def test_class_attribute_password(self):
        """Test class attribute password"""
        self.assertTrue(hasattr(self.user1, 'password'))
        User.password = ''
        self.assertTrue(isinstance(self.user1.password, str))
        self.assertEqual(self.user1.password, '')

    def test_to_dict_attr(self):
        """ created_at, updated_at values """
        time_format = "%Y-%m-%dT%H:%M:%S.%f"
        dictionary = self.user1.to_dict()
        self.assertEqual(dictionary["created_at"],
                         self.user1.created_at.strftime(time_format))
        self.assertEqual(dictionary["updated_at"],
                         self.user1.updated_at.strftime(time_format))
        self.assertEqual(dictionary["__class__"], 'User')
        self.assertEqual(type(dictionary["created_at"]), str)
        self.assertEqual(type(dictionary["updated_at"]), str)

    def test_str(self):
        """Test output string of the objects"""
        string = "[{}] ({}) {}".format(self.user1.__class__.__name__,
                                       self.user1.id, self.user1.__dict__)
        self.assertEqual(str(self.user1), string)

    def tearDown(self):
        """Tear down Amenity Objects for testing"""
        del self.user1
        del self.user2
        User.email = ''
        User.password = ''
        User.first_name = ''
        User.last_name = ''
Esempio n. 36
0
def register():
    form = request.form

    u, result = User.register(form.to_dict())
    log('register post', result)
    return redirect(url_for('user.register_view', result=result))
Esempio n. 37
0
def load_user(user_id):
    return User.get_or_none(User.id == user_id)
 def current_user(self, request=None):
     """ returns a User instance based on a cookie value """
     cookie_val = self.session_cookie(request)
     user_id = self.user_id_for_session_id(cookie_val)
     return User.get(user_id)
Esempio n. 39
0
def user_details(user_id, **params):
    params["selected_user"] = User.get_user_by_id(user_id)
    return render_template_with_translations("admin/users/details.html", **params)
Esempio n. 40
0
 def user(self):
     u = User.find(id = self.user_id)
     return u
Esempio n. 41
0
 def validate_email(form, field):
     if User.does_user_exist(field.data):
         field.was_duplicate = True
         raise ValidationError("Account already exists")
Esempio n. 42
0
def user_detail(id):
    u = User.one(id=id)
    if u is None:
        abort(404)
    else:
        return render_template('profile.html', user=u)
#!/usr/bin/python3
"""
Test __str__() on User instance
"""
from models.user import User

user = User()
user.email = "*****@*****.**"
print(user)

user.first_name = "Bob"
user.last_name = "Dylan"
print(user)
Esempio n. 44
0
 def user(self):
     u = User.one(id=self.user_id)
     return u
Esempio n. 45
0
 def test_exists_false(self):
     User._exists = MagicMock(return_value=False)
     self.assertFalse(User.exists(username))
Esempio n. 46
0
 def test_create_istance2(self):
     """create a new instance"""
     new_user = User()
     self.assertIsInstance(new_user, BaseModel)
Esempio n. 47
0
 def test_init(self):
     u = User.new(username, password, email)
     self.assertEqual(u.username, username)
     self.assertEqual(u.email, email)
     self.assertNotEqual(u.hashed_password, password)
Esempio n. 48
0
def addUserFromUrl(first_name, age):
    Db.session.add(User(first_name=first_name, age=age))
    Db.session.commit()
    return redirect(url_for('index'))
Esempio n. 49
0
    def profile(username):
        if 'user' in session:
            infos = {}
            if session['user'] == username:
                infos['is_user_me'] = True
            else:
                infos['is_user_me'] = False
                infos['stalker'] = session['user']
                victim = User.find_by('username', username)
                if victim == None:
                    return redirect(url_for('profile_not_exists'))
                if victim.is_complete() == False:
                    return redirect(url_for('profile_not_complete'))

                stalker = User.find_by('username', infos['stalker'])
                if View.find_both('stalker_id', stalker.getId(), 'victim_id',
                                  victim.getId()) == None:
                    view = {}
                    view['stalker_id'] = stalker.getId()
                    view['victim_id'] = victim.getId()
                    View.create(view)
                    notif = {}
                    notif['user_id'] = victim.getId()
                    notif[
                        'message'] = "Vu : <a href='/profile/" + stalker.getUserName(
                        ) + "'>" + stalker.getUserName(
                        ) + "</a> vous a rendu visite."
                    Notification.create_if(notif, stalker.getId())
                    score = int(victim.getPopScore()) + 1
                    victim.modif('pop_score', str(score))
                    # if no Fakers
                    # victim.modif('pop_score', str(View.howMany('victim_id', victim.getId())))
                    victim.save()

            auth = User.find_by('username', username)

            infos['username'] = auth.getUserName()
            infos['first_name'] = auth.getFirstName()
            infos['last_name'] = auth.getLastName()
            infos['email'] = auth.getEmail()
            infos['age'] = auth.getAge()
            if auth.getSex() == '1':
                infos['sex'] = "Homme"
            elif auth.getSex() == '2':
                infos['sex'] = "Femme"
            else:
                infos['sex'] = auth.getSex()
            if auth.getOrientation() == '0':
                infos['orientation'] = "H**o"
            elif auth.getOrientation() == '1':
                infos['orientation'] = "Hetero"
            else:
                infos['orientation'] = "Bi"
            infos['bio'] = html.unescape(auth.getBio())
            infos['interests'] = UsersInterest.getAllInterests(auth.getId())
            infos['main_picture'] = auth.getMainPicture()
            infos['pop_score'] = auth.getPopScore()
            infos['location'] = auth.getLocation()
            infos['last_connexion'] = auth.getLastConnexion()
            infos['status'] = auth.getStatus()

            picture = Picture.where('user_id', auth.getId())
            infos['picture_1'] = Picture.fillInInfos(auth.getId(), '1')
            infos['picture_2'] = Picture.fillInInfos(auth.getId(), '2')
            infos['picture_3'] = Picture.fillInInfos(auth.getId(), '3')
            infos['picture_4'] = Picture.fillInInfos(auth.getId(), '4')
            infos['picture_5'] = Picture.fillInInfos(auth.getId(), '5')

            # Put in first ELSE at the top
            if infos['is_user_me'] == False:
                stalker = User.find_by('username', infos['stalker'])
                infos['has_liked'] = Like.exists('stalker_id', stalker.getId(),
                                                 'victim_id', auth.getId())
                infos['he_liked_me'] = Like.exists('stalker_id',
                                                   auth.getId(), 'victim_id',
                                                   stalker.getId())

                infos['has_blocked'] = Block.exists('by_id', stalker.getId(),
                                                    'blocked_id', auth.getId())
                nb_picture = Picture.howMany('user_id', stalker.getId())
                if nb_picture == 0:
                    infos['stalker_can_like'] = False
            infos['nb_like'] = Like.howMany('victim_id', auth.getId())

            all_views = View.where('victim_id', auth.getId())
            join_infos_views = []
            for item in all_views:
                join_infos_views = join_infos_views + User.join(
                    'users', 'views', 'id', 'stalker_id',
                    str(item['stalker_id']))
            infos['all_views'] = join_infos_views

            all_likes = Like.where('victim_id', auth.getId())
            join_infos_likes = []
            for item in all_likes:
                join_infos_likes = join_infos_likes + User.join(
                    'users', 'likes', 'id', 'stalker_id',
                    str(item['stalker_id']))
            infos['all_likes'] = join_infos_likes

            error = session.get('error')
            session['error'] = None

            tags = [
                '#tag', '#bouffe', '#lol', '#cherchedesepérémentqqun',
                '#lovecats'
            ]

            return render_template('profile.html',
                                   infos=infos,
                                   error=error,
                                   tags=tags)
        else:
            return redirect(url_for('accueil'))
Esempio n. 50
0
 def test_exists_true(self):
     User._exists = MagicMock(return_value=True)
     self.assertTrue(User.exists(username))
def get_stats():
    '''get_stats() - get number of User'''
    return jsonify(users=User.count())
Esempio n. 52
0
 def tearDown(self) -> None:
     for eventid in self.event_ids:
         Event.delete_event_by_id(eventid)
     User.delete_user_by_email(self.useremail)
     User.delete_user_by_email(self.user2.email)
Esempio n. 53
0
 def test_to_dict(self):
     """to_dict testing"""
     dic = User()
     self.assertIsInstance(dic.to_dict(), dict)
Esempio n. 54
0
from models.user import User
from models.likes import Like
from models.dislikes import Dislike
from models.matches import Match

with app.app_context():
    db.drop_all()
    db.create_all()

    lara = User(
        email="*****@*****.**",
        first_name="lara",
        last_name="lara",
        password="******",
        dob="1994-12-18",
        gender="female",
        gender_pref="male",
        age_pref_max=29,
        age_pref_min=22,
        image_1=
        'https://upload.wikimedia.org/wikipedia/en/thumb/3/3b/SpongeBob_SquarePants_character.svg/1200px-SpongeBob_SquarePants_character.svg.png',
        # has_seen = [2]
    )

    laura = User(email="*****@*****.**",
                 first_name="laura",
                 last_name="laura",
                 password="******",
                 dob="1994-12-18",
                 gender="female")

    karen = User(
Esempio n. 55
0
 def test_constructor_sets_fields_correctly(self):
     user = User("maija", "Ahlie8oh")
     self.assertEqual(user.username, "maija")
     assert check_password_hash(user.password_hash, "Ahlie8oh")
Esempio n. 56
0
 def test_id(self):
     """ id testing """
     u = User()
     u1 = User()
     self.assertNotEqual(u.id, u1.id)
Esempio n. 57
0
 def test_set_password_updates_password_hash(self):
     user = User("maija", "Ahlie8oh")
     user.set_password("Ahlie8ohe")
     assert check_password_hash(user.password_hash, "Ahlie8ohe")
Esempio n. 58
0
 def setUp(self):
     """setup"""
     self.user = User()
Esempio n. 59
0
 def on_close():
     User.free(current_user)
Esempio n. 60
0
 def test_check_password_incorrect(self):
     user = User("maija", "Ahlie8oh")
     assert not user.check_password("ahlie8oh")