def test_switch_user_message_handler(self): user_id = 1 handler_code1 = "handler1" handler_code2 = "handler2" self.server.set_message_handler(self.message_handler, handler_code1, default=True) # handler is not setted self.assertRaises(MessageHandlerNotSettedException, self.server.switch_user_message_handler, user_id, handler_code2) # set special handler for user self.server.set_message_handler(self.message_handler, handler_code2) self.server.switch_user_message_handler(user_id, handler_code2) self.assertEqual( User.objects(user_id=str(user_id)).first().next_handler, handler_code2) # set default handler for user self.server.switch_user_message_handler(user_id, None) self.assertEqual( User.objects(user_id=str(user_id)).first().next_handler, handler_code1)
def saveUser(self, _param): """ 保存用户信息 @param _param: @return: """ flag_add = True user = User.objects.filter( pk=_param['id']).first() if _param.get('id', None) else None if user: flag_add = False if user and User.objects.exclude(pk=_param['id']).filter( username=_param['username']).count(): raise ex(u'该用户名已经存在!') if not user: if _param.get('username', None) and User.objects.filter( username=_param['username']): raise ex(u'该用户名已经存在!') user = User() dic2obj(user, [ 'username', 'truename', 'name', 'email', 'phone', 'department_id', 'role_id' ], _param) if _param.get('password', ''): user.password = _param['password'] user.save() self.logAtion(ActionLog.ACTION_MODIFY, User, user.id)
def signup(): user = User() form = UserForm() if form.validate_on_submit(): form.populate_obj(user) user.save(force_insert=True) flash('Your account have been created') return redirect(url_for('index')) return render_template('index.html', form=form)
def setUp(self): self.client = Client() self.user1 = User(username="******", first_name="Fa", password="******") self.user1.save() self.user2 = User(username="******", first_name="Fa", password="******") self.user2.save()
def submit(request): try: email = request.POST.get('email') locale_id = request.POST.get('locale_id') user = User(email=email.lower(), locale_id_id=locale_id, active=True) user.save() return HttpResponseRedirect(reverse('subscription:submitted')) except IntegrityError as err: log_error(err) return HttpResponseRedirect(reverse('subscription:nosubmit'))
def init_data(): """Fish data for project""" if prompt_bool('Do you want to kill your db?'): db.drop_all() try: db.create_all() except: pass user = User.query.filter(User.email=='*****@*****.**').first() if user is None: user = User(username='******', email='*****@*****.**', password='******') user.save()
def home(): print "config.AUTHENTICATE {}".format(config.AUTHENTICATE) if config.AUTHENTICATE: return render_template('index.html', login_form=LoginForm(), create_form=CreateAccountForm()) else: email = 'default' password = '******' access_key_id = config.AWS_ID secret_access_key = config.AWS_KEY aws_bucket_name = config.AWS_BUCKET_NAME next_backend_global_host = config.NEXT_BACKEND_GLOBAL_HOST if not User.objects(email=email): user = User(email=email, access_key_id=access_key_id, secret_access_key=secret_access_key, aws_bucket_name=aws_bucket_name, next_backend_global_host=next_backend_global_host) user.set_password(password) user.save() else: user = User.objects(email=email).first() login_user(user, remember=True) return redirect(url_for('dashboard._dashboard'))
def test_delete_user(self): self.user3 = User(username="******", first_name="Ryan", password="******") self.user3.save() user_detail = self.client.get('/users/%s/' % self.user3.pk) u_json_string = json.loads(user_detail.content.decode('utf-8')) self.assertEqual(user_detail.status_code, 200) user_delete = self.client.delete('/users/%s/' % self.user3.pk) self.assertEqual(user_delete.status_code, 204) user_detail = self.client.get('/users/%s/' % self.user3.pk) u_json_string = json.loads(user_detail.content.decode('utf-8')) self.assertEqual(user_detail.status_code, 404)
def changePassword(self, password, newpassword): ''' 修改用户密码 @param password: @param newpassword: @return: ''' if not newpassword: raise ex(u'新密码不能为空') user = self.get_me() if user and user.password == User.pwdhash(password, user.salt): user.password = User.pwdhash(newpassword, user.salt) user.save() else: raise ex(u'原密码不正确!')
def post(self): """ Handles the HTTP POST requests (overriding :meth:`MethodView.post`) . If the form was correctly filled and the user password validates (through :meth:`~base.models.User.check_password`), calls :func:`flask.ext.login.login_user`, emits a flash message of success and redirects the request to the `next` parameter or the home page if not specified. Otherwise, emits errors as flash messages and renders the login page again. :return: On error, renders the login page, but redirects to value of `next` or home page on success. """ form = LoginForm() if not form.validate_on_submit(): flash(self._messages['invalid_data']) return render_template('login.html', form=form) user = User.get_by_email(form.email.data) if user and user.check_password(form.password.data): login_user(user) flash(self._messages['success']) else: flash(self._messages['invalid_auth']) return redirect(url_for('base.login')) return redirect(request.args.get('next') or url_for('base.front_page'))
def POST(cls): name = request.form.get("login") password = request.form.get("password") context = cls.get_context() if not User.try_login(name, password): flash("Invalid password or username!", "error") return render_template(cls.template, **context), cls.status
def signup(): vals = dict(request.form) for key, val in vals.items(): vals[key] = val[0] email = vals.get('email') username = vals.get('username') user_db = User.query.filter_by(username=username).first() email_db = User.query.filter_by(email=email).first() if not user_db and not email_db: user = User(email=email, username=username, password=generate_password_hash(vals.get('password'))) db.session.add(user) db.session.commit() return json.dumps({ 'status': 'success', 'msg': 'Sign up successful! Please login now.' }) else: response = {'status': 'failed', 'msg': ''} if user_db: response['msg'] += 'This username already exists. ' if email_db: response['msg'] += 'This email already exists. ' return json.dumps(response)
def add_user(): username = request.form["username"] if User.query.filter_by(username=username).count() > 0: return jsonify(Msg(False, gettext("User exists."))) password = request.form["password"] user = User(username, password) db.session.add(user) db.session.commit() return jsonify(Msg(True, gettext("User added Successfully.")))
def login(self, request): username = request.data.get("username", None) password = request.data.get("password", None) try: ca = User.login(username, password) serializer = UserAuthSerializer(ca) cache_for_admin_login(serializer) return Response(serializer.data) except ObjectDoesNotExist: raise BusinessValidationError(error_const.BUSINESS_ERROR.ADMIN_LOGIN_FAIL)
def get_object(self, queryset=None): obj = super().get_object(queryset=queryset) if obj.is_deleted: raise User.DoesNotExist("未查询到用户: %s" % self.model._meta.object_name) # opt_log self.opt_logger.info(User.objects.get(pk=self.kwargs.get('user_id')), content='更新用户', action='更新用户') return obj
def get(self): user = User('Test Name', '*****@*****.**') db.session.add(user) try: db.session.commit() except Exception as e: db.session.rollback() app.logger.debug(e) return TODOS
def POST(cls, *args, **kwargs): new_user = User() form = request.form new_user.nickname = form.get('nickname') new_user.password_hash = generate_password_hash(form.get('password')) new_user.image_url = form.get('image_url') new_user.about = form.get('about') new_user.footer_text = form.get('footer') new_user.email = form.get('email') db.session.add(new_user) db.session.commit() return cls.GET(*args, **kwargs)
def login(): login_form = LoginForm(request.form) if login_form.validate_on_submit(): user = User.objects(email=login_form.email.data).first() if user and user.check_password(login_form.password.data): login_user(user) return redirect(request.args.get("next") or url_for('dashboard._dashboard')) else: flash("Login failed.", "login_error") # login is not valid return redirect('#create') return render_template('index.html', login_form=login_form, create_form=CreateAccountForm())
def setUp(self): self.db = base.db self.db.create_all() self.client = self.app.test_client() u = User(username='******', email='*****@*****.**', password='******') bm = Bookmark(user=u, url="http://www.example.com", tags="one,two,three") self.db.session.add(u) self.db.session.add(bm) self.db.session.commit() self.client.post(url_for('auth.login'), data=dict(username='******', password='******'))
def __init__(self): global _player if _player is not None: raise "Player was initialized!" random.seed(time.clock()) print("Starting player...") self.vlcInstance = vlc.Instance( "--live-caching=0 --network-caching=0 --norm-buff-size=8") self.vlcPlayer = self.vlcInstance.media_player_new() self.vlcEvents = self.vlcPlayer.event_manager() self.vlcEvents.event_attach(vlc.EventType.MediaPlayerEndReached, self.songFinished) self.vlcEvents.event_attach(vlc.EventType.MediaPlayerEncounteredError, self.songCorrupted) self.vlcEvents.event_attach(vlc.EventType.MediaStateChanged, self.mediaStateChanged) # Import old DJPajton playlist if Song.objects.count() == 0 and os.path.isfile('music4you.playlist'): with open("music4you.playlist", "r") as f: playlist = json.loads(f.read()) for item in playlist: print("Item: {}".format(item)) song = Song() song.id = int(item['id']) song.date = item['addedDate'] song.active = (bool(item['deleted']) == False) song.url = item['url'] song.title = item['title'] try: user = User.objects.get(login=item['addedLogin']) except: user = User() user.active = False user.type = USER_TYPE_SKYPE user.login = item['addedLogin'] user.displayName = user.login user.save() song.user = user song.save() #self.vlcPlayer.audio_set_volume(100) if Song.objects.count() == 0: return
class KitTestCase(TestCase): def create_app(self): return AppFactory(TestingConfig).get_app(__name__) def setUp(self): db.create_all() self.user = User(username='******', email='*****@*****.**', password='******') self.user.save() def tearDown(self): db.session.remove() db.drop_all() def assertContains(self, response, text, count=None, status_code=200, msg_prefix=''): """ Asserts that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected), and that ``text`` occurs ``count`` times in the content of the response. If ``count`` is None, the count doesn't matter - the assertion is true if the text occurs at least once in the response. """ if msg_prefix: msg_prefix += ": " self.assertEqual(response.status_code, status_code, msg_prefix + "Couldn't retrieve content: Response code was %d" " (expected %d)" % (response.status_code, status_code)) real_count = response.data.count(text) if count is not None: self.assertEqual(real_count, count, msg_prefix + "Found %d instances of '%s' in response" " (expected %d)" % (real_count, text, count)) else: self.assertTrue(real_count != 0, msg_prefix + "Couldn't find '%s' in response" % text)
def app_add_user(): try: app_add_user = User(**request.form) db.session.merge(app_add_user) db.session.commit() return json.dumps({'success': True}), 200, { 'ContentType': 'application/json' } except Exception as e: print(e) return json.dumps({'success': False}), 400, { 'ContentType': 'application/json' }
def load_user(user_id): """ We need to provide a :meth:`~flask.ext.login.LoginManager.user_loader` callback to the login manager. This callback is used to reload the user object from the user ID stored in the session. It should return `None` (**not raise an exception**) if the ID is not valid. (In that case, the ID will manually be removed from the session and processing will continue.) This is done by calling :meth:`~base.models.User.get_by_id`) , :param user_id: the unicode ID of a user :return:the corresponding user object """ return User.get_by_id(user_id)
def post(self): form = LoginForm() if not form.validate_on_submit(): flash(self._messages['invalid_form']) return render_template('login.html', form=form) user = User.get_by_email(form.email.data) if user and user.check_password(form.password.data): login_user(user) flash(self._messages['success']) else: flash(self._messages['invalid_auth']) return redirect(url_for('base.login')) return redirect(request.args.get('next') or url_for('base.front_page'))
def test_handle_postback(self, mock_obj): handler_code = "handler" sender_id = 1 postback = {"payload": handler_code} # message handler not setted up self.assertRaises(PostbackHandlerUndefinedException, self.server.handle_postback, postback, sender_id) # handle message self.server.set_postback_handler(self.message_handler, handler_code) self.server.handle_postback(postback, sender_id) self.assertEqual( User.objects(user_id=str(sender_id)).first().next_handler, "special_handler")
def login(): form = LoginForm() if form.validate_on_submit(): try: user = User.get(User.user_username == form.username.data) if user.user_password == form.password.data: #user.is_authenticated = True login_user(user) session['username'] = request.form['username'] flash("You're now logged in!") return redirect(url_for('index')) else: flash("Error on password or username") except: flash("Error !!,You should start again") return render_template('login.html', form=form)
def form_valid(self, form): # Create a user, but remember to set inactive! user = User() user.username = form.cleaned_data['email'] user.email = form.cleaned_data['email'] user.is_active = False try: user.save() except IntegrityError: form.add_error('email', gettext('Shop with this email already exists.')) return super(ShopRegisterView, self).form_invalid(form) self.object = form.save(commit=False) self.object.postcode = Postcode.objects.get( postcode=form.cleaned_data['postcode_special']) self.object.user = user self.object.save() current_site = get_current_site(self.request) context = { 'shopname': self.object.name, 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } html_message = render_to_string('emails/account_activation.html', context) txt_message = render_to_string('emails/account_activation.txt', context) email = EmailMultiAlternatives(gettext('FOODBEE - Confirm email'), txt_message) email.from_email = settings.DEFAULT_FROM_EMAIL email.to = [self.object.email] email.attach_alternative(html_message, "text/html") email.content_subtype = 'html' email.mixed_subtype = 'related' with open('base/static/base/img/fb_logo.png', mode='rb') as f: image = MIMEImage(f.read()) image.add_header('Content-ID', "<Foodbee_logo_long.png>") email.attach(image) email.send() return super().form_valid(form)
def test_handle_message(self, mock_obj): message = {'text': "test"} sender_id = 1 handler_code = "handler" # message handler not setted up self.assertRaises(MessageHandlerNotSettedException, self.server.handle_message, message, sender_id) # handle message self.server.set_message_handler(self.message_handler, handler_code, default=True) self.server.handle_message(message, sender_id) self.assertEqual( User.objects(user_id=str(sender_id)).first().next_handler, "special_handler")
def login(self, username, password): """ 用户登录 @param username: @param password: @return: """ user = User.objects.filter(username=username).first() if user and user.password == User.pwdhash(password, user.salt): if user.status == User.STATUS_CANCELED: raise ex(u'该用户已被锁定无法登陆') self.session_set('me', user.get_json()) self.logAtion(ActionLog.ACTION_LOGIN) logingoto = self.session_get_once('logingoto') return obj2dic(user, ['id', 'username', 'token'], {'goto': logingoto or '/xadmin/'}) else: raise ex(u'用户名或密码错误')
def create(): create_form = CreateAccountForm(request.form) if create_form.validate_on_submit(): print "form data",create_form.new_email.data new_email = create_form.new_email.data new_password = create_form.new_password.data confirm_password = create_form.confirm_password.data print User.objects() if User.objects(email=new_email).count() == 0: if new_password == confirm_password: # Set the hashed password on the user. user = User(email=new_email) user.set_password(new_password) user.save() login_user(user, remember=True) return redirect(url_for('dashboard._dashboard')) else: flash("Passwords don't match!", "create_error") return redirect('#create') else: flash("Username exists!", "create_error") return redirect('#create') # login form is not valid return render_template('index.html', login_form=LoginForm(), create_form=create_form)
def force_lookup(self): "Lookup users who were not included in the original crawl." for user in User.get_all(): if ( user.lookup_done or user.protected or user._id not in self.scores or user.local_prob==1 ): continue state, rfs, ats = self.scores.split(user._id) reasons = [ user.utc_offset == settings.utc_offset, log_score(rfs,ats) >= settings.non_local_cutoff, user.local_prob == .5, ] if sum(reasons)>=2: logging.info("force %s - %d for %r", user.screen_name, user._id, reasons) self._send_job(user._id,rfs,ats,True)
def run(self): while True: jobs = [] for x in xrange(100): try: # reserve blocks to wait when x is 0, but returns None for 1-99 j = self.stalk.reserve(0 if x else None) except beanstalkc.DeadlineSoon: break if j is None: break jobs.append(j) bodies = [LookupJobBody.from_job(j) for j in jobs] try: users =self.twitter.user_lookup([b._id for b in bodies]) except ResourceNotFound: logging.info("no profile for %r",[b._id for b in bodies]) continue logging.info("looking at %r"%[getattr(u,'screen_name','') for u in users]) for job,body,user in zip(jobs,bodies,users): if user is None: logging.info("no profile for %d",body._id) job.delete() continue try: self.twitter.sleep_if_needed() logging.info("look at %s",user.screen_name) if (not body.force) and User.in_db(user._id): job.delete() continue self.crawl_user(user,body.force) user.save() job.delete() except: logging.exception("exception for job %s"%job.body) job.bury() logging.info("api calls remaining: %d",self.twitter.remaining)
def login(request): try: body = json.loads(request.body) user = User.by_login(body['login']) if user.auth.password == hex_hash(body['password']): # 200 r = HttpResponse() r.set_cookie("user_id", user.id, 24 * 60 * 60, domain=settings.SESSION_COOKIE_DOMAIN) r.set_cookie("login", user.auth.login, 24 * 60 * 60, domain=settings.SESSION_COOKIE_DOMAIN) return r # 403 return HttpResponseForbidden() except ObjectDoesNotExist: # 404 return HttpResponseNotFound()
def init_user(): if User.query.count() == 0: db.session.add(User('admin', 'admin')) db.session.commit()
def setUp(self): db.create_all() self.user = User(username='******', email='*****@*****.**', password='******') self.user.save()
def load_user(user_id): return User.get_by_id(user_id)
def produce(self): Model.database = MongoDB(name=self.db_name, host=settings.db_host) endtime = datetime.utcnow() return User.find(User.next_crawl_date < endtime, sort=User.next_crawl_date, timeout=False)
def load_user(userid): users = User.objects(email=userid) if len(users) >0: return users[0] return None