def post(self): ''' Registra um novo usuário para ter acesso a API ''' parser = reqparse.RequestParser(bundle_errors=True) parser.add_argument('username', type=str, required=True, help='Nome do usuário para login') parser.add_argument('password', type=str, required=True, help='Senha do usuário') args = parser.parse_args(strict=True) if User.query.filter_by(username=args.username).first() is not None: abort(400, 'Já existe usuário com esse username.') user = User(username=args.username) user.hash_password(args.password) db.session.add(user) db.session.commit() return {'username': args.username}, 201
def ajax_sale_add(request): r_client = request.POST.get('client') r_task = request.POST.get('task') r_email = request.POST.get('email') r_password = request.POST.get('password') client = Client.objects.get(pk=int(r_client)) task = Task.objects.get(pk=int(r_task)) try: User.objects.get(email=r_email) except User.DoesNotExist: user = User(email=r_email, password=r_password, type=User.UserType.client) user.set_password(r_password) user.save() sale = Sale( user=user, city=client.city, manager=client.manager, moderator=client.moderator, legal_name=client.name, actual_name=client.name, legal_address=client.actual_address, password=r_password ) sale.save() task.status = 1 task.save() return HttpResponseRedirect(reverse('sale:update', args=(sale.id, ))) return_url = reverse('client:task-list') + '?error=1' return HttpResponseRedirect(return_url)
def post(self, request, *args, **kwargs): if request.method != 'POST': return HttpResponse('Use POST method', status=400) try: name = request.POST['name'] password = request.POST['password'] email = request.POST['email'] except KeyError: return HttpResponse('Fill in all fields', status=400) if name == '' or password == '' or email == '': return HttpResponse('Fill in all fields', status=400) if len(password) < 5: return HttpResponse('Password should be longer than 5 symbols', status=400) if not re.match(r"[^@]+@[^@]+\.[^@]+", email): return HttpResponse('Email is not valid', status=400) same_email_user_amount = User.objects.filter(email=email).count() if same_email_user_amount > 0: return HttpResponse('User with this email already exists', status=400) password_hash = self.authenticationManager.hash_password(password) new_user = User(name=name, password=password_hash, email=email) new_user.save() response = HttpResponse(status=200) self.authenticationManager.authenticate_response(response, new_user) return response
def actualizar_registro(cls, documento, nombres, apellidos, usuario, clave, role, rutas): existe_documento = cls.existe_documento(documento) if existe_documento and usuario: u = User.query(User.documento == documento).get() u.nombres = nombres u.apellidos = apellidos if clave: u.clave_hash = User.make_pw_hash(usuario, clave) elif u.usuario != usuario and not cls.existe_usuario(usuario) and clave: u.clave_hash = User.make_pw_hash(usuario, clave) u.usuario = usuario u.role = role u.put() rutasEliminar = cls.query_all_rutas(u.key) if rutasEliminar: for r in rutasEliminar: if r.usuario.get().usuario == u.usuario: r.key.delete() if rutas: for rut in rutas: ruta_key = ndb.Key(urlsafe=rut) rta = ruta_key.get() nueva_ruta = UserRuta(ruta=rta.key, usuario=u.key) nueva_ruta.put() return ["alert-success", "La actualización ha sido exitoso"] else: return ["alert-danger", "No se pudo completar la actualización"]
class TestEvents(TestCase): def setUp(self): print('START') self.author = User() self.author.username = '******' self.author.save() self.text = TextContent() self.text.text = 'Test text' self.text.save() def test_creation_by_signal(self): post = Post() post.author = self.author post.content = self.text post.name = 'Post_name' post.save() event = Event.objects.get(event_content_id=post.pk) self.assertEqual(event.event_content, post) self.assertEqual(event.event_content_id, post.pk) self.assertEqual(event.author, self.author) def tearDown(self): print('END')
def register_user(): user_data = request.get_json() user = User.query.filter_by(email=user_data.get('email')).first() if not user: try: #Set data to be entered into the user's table user = User(email=user_data.get('email'), password=user_data.get('password'), phone=user_data.get('phone')) #insert the data db.session.add(user) db.session.commit() # generate JWT token auth_token = user.encode_auth_token(user.id) responseObject = { 'status': 'success', 'message': 'Successfully registered.', 'auth_token': auth_token.decode() } return make_response(jsonify(responseObject)), 201 except Exception as e: responseObject = { 'status': 'fail', 'message': 'Some error occurred. Please try again.' } return make_response(jsonify(responseObject)), 401 else: responseObject = { 'status': 'fail', 'message': 'User already exists. Please Log in.', } return make_response(jsonify(responseObject)), 202
def user_login(create_new=False): data = request.get_json() if create_new is True: username = data.get('username') password = data.get('password') user_group = data.get('user_group') if user_group not in ['admin', 'staff']: user_group = 'staff' user = User.add_user(username, password, user_group) response = success_response({'user_created': True, '_id': user.id}) return jsonify(response) else: username = data.get('username') password = data.get('password') user = User.objects(name=username).first() if user is None: response = failure_response(400, 'username not found') return jsonify(response) else: if check_password_hash(user.password, password) is True: login_user(user) response = success_response({ 'login': '******', 'name': user.name, '_id': user.id }) return jsonify(response)
def import_users(filename): with open(filename, 'rt', encoding='utf-8') as csvfile: reader = csv.reader(csvfile, delimiter=',') user_list = list(reader) for i in user_list: u = User(name=i[0], descriptor=i[1]) u.save()
def test_sync_accounts_new_and_existing_accounts( user: User, successful_installation_response: object ) -> None: user_account = Account.objects.create( github_installation_id=1066615, github_account_login=user.github_login, github_account_id=user.github_id, github_account_type="User", ) AccountMembership.objects.create(user=user, account=user_account, role="member") # the user should get removed from this account when we sync. This tests # that our membership removal of installations a user no longer has access # to works. acme_corp_account = Account.objects.create( github_installation_id=79233, github_account_login="******", github_account_id=33803, github_account_type="Organization", ) AccountMembership.objects.create( user=user, account=acme_corp_account, role="member" ) assert Account.objects.count() == 2 assert AccountMembership.objects.filter(user=user).count() == 2 user.sync_accounts() assert Account.objects.filter( github_account_login__in=["recipeyak", "chdsbd", "ghost", "acme-corp"] ) assert ( Account.objects.count() == 4 ), "we should have a new account for recipeyak and chdsbd." assert ( AccountMembership.objects.filter(user=user) .exclude(account__github_account_login__in=["recipeyak", "chdsbd", "ghost"]) .count() == 0 ), "we should have removed acme-corp." assert ( AccountMembership.objects.filter( user=user, role="member", account__github_account_login="******" ).count() == 1 ) assert ( AccountMembership.objects.filter( user=user, role="admin", account__github_account_login="******" ).count() == 1 ) assert ( AccountMembership.objects.filter(user=user, account=acme_corp_account).exists() is False ), "the user should no longer be a member of the organization if is no longer returned from `/user/installations` endpoint." assert ( Account.objects.filter(id=acme_corp_account.id).exists() is True ), "account that we are no longer a member of should not be deleted."
def register(): data = request.json mobile, nickname, password = map(lambda x: data.get(x), ['mobile', 'username', 'password']) user = User(mobile=mobile, nickname=nickname, passwd=password) user_exist = User.query.filter_by(mobile=mobile).first() if user_exist: return jsonify({ 'code': '-1', 'data': '', 'msg': "user with this name and mobile existed" }) db.session.add(user) err = user.session_commit() if not err: user = User.query.filter_by(mobile=mobile, nickname=nickname).first() return jsonify({'code': '0', 'data': user.to_dict(), 'msg': 'success'}) else: err_data = { 'code': '-1', 'data': err, 'msg': "commit data to database error" } return jsonify(err_data)
def test_post(self, get_client_db): # POST client, _db, _ = get_client_db # Para login, não é necessário enviar header de autenticação clear_data(_db) # CENÁRIO 1 - OK user = User(username='******') user.hash_password('Senha') _db.session.add(user) _db.session.commit() data = {"username": "******", "password": "******"} response = client.post('/auth/login/', data=data) assert response.status_code == 200 key, _ = list(response.json.items())[0] assert key == 'token' # CENÁRIO 2 - Tentativa de login com usuário não cadastrado data = {"username": "******", "password": "******"} response = client.post('/auth/login/', data=data) assert response.status_code == 401 assert response.json['message'] == 'Username ou senha inválido' # CLEAN UP clear_data(_db)
def test_create_player_from_user(self): user = User(login='******') user.name = 'test_name' player = PlayerOrig.from_user(user=user) self.assertEqual(player.name, user.name) self.assertEqual(player.user, user) self.assertEqual(player.id, user.id)
def test_001_create_user(self): admin_user = User.add_user("admin_user", "test", "admin") staff_user = User.add_user('staff_user', 'test', 'staff') user = User.objects(name='admin_user').first() assert user.name == admin_user.name assert user.group == 'admin'
def delete_user(id): """``DELETE`` |API_URL_BASE|/user/:user_id Delete a user. Superuser can't be deleted. :param id: user id Response JSON: .. code-block:: javascript // success {$errors: null} // failed {$errors: {id: 'this is user does not exist.'}} Permission require: ``DELETE_USER`` """ try: User.get(User.id == id).delete_instance() except User.DoesNotExist: return {'id': '该用户ID不存在'} signals.event_emitted.send(current_app._get_current_object(), type='User: Delete', description='delete user(%s).' % id)
def put(self, user_id): """ PUT handler """ edit_user = User(**api.payload) edit_user.uuid = user_id edit_user.save()
def setUp(self): """Define the test variables.""" self.username = "******" self.email = "*****@*****.**" self.password = "******" self.user = User(username=self.username, email=self.email, password=self.password)
def get_user(request): return render_to_response('social/user.html', { 'user': User.get_mention_list(request.GET['comment_object']), 'arr_length': User.get_mention_list(request.GET['comment_object']).__len__() }, context_instance=RequestContext(request))
def init_db(): thing1 = User(name='thing1') thing2 = User(name='thing2') db.session.add(thing1) db.session.add(thing2) db.session.commit()
def setUp(self): User = get_user_model() self.cadastro = User( username='******', email='*****@*****.**', password='******', last_name='Saraiva Jr', ) self.cadastro.save()
def current_user(self): user = User() if 'username' in session: username = session['username'] user.username = username else: user.username = '******' user.password = '******' return user
def setUpClass(cls): cls.app = cls.create_app() cls.client = socketio.test_client(app=cls.app) cls.client.testing = True cls.http_client = cls.app.test_client() thing = User(name='thing') cls.valid_token = thing.encode_auth_token(1).decode('utf-8')
def change_password(): form = ChangePasswordForm(request.form) if form.validate_on_submit(): User.update( password = generate_password_hash(form.new_password.data), ).where(User.id == form.user_id.data).execute() flash('Password successfully changed') return redirect(url_for('user.index')) return render_template('user/change_password.html', form=form)
def setUp(self): print('START') self.author = User() self.author.username = '******' self.author.save() self.text = TextContent() self.text.text = 'Test text' self.text.save()
def test_encode_auth_token(self): user = User( email='*****@*****.**', password='******', registered_on=datetime.datetime.utcnow() ) db.session.add(user) db.session.commit() auth_token = user.encode_auth_token(user.id) self.assertTrue(isinstance(auth_token, bytes))
def test_helper_no_profile(self): u = User() u.first_name = "John" u.last_name = "Smith" u.save() self.assertEquals(False, helpers.user_has_profile(u)) p = Person() p.user = u p.save() self.assertEquals(True, helpers.user_has_profile(u))
def create(): form = CreateUserForm() if form.validate_on_submit(): User.create(first_name=form.data.get("first_name", ""), last_name=form.data.get("last_name", ""), username=form.data.get("username", ""), password=form.data.get("password", "")) flash("New user created") return redirect("users/create") return render_template("users/create.html", form=form)
def profile(request, browsing_data="def"): #browsing_data will represent the type of data the user want to see " likes, dislikes ,or comments" user = None if request.user.is_authenticated(): user = request.user else: return HttpResponseRedirect(reverse('index')) ids = [] liked_articles = [] disliked_articles = [] commented_articles = [] obj_contributions = Feedback.objects.filter(user=user, parent_id=None) contributions = obj_contributions.count voted_articles = ArticleRating.objects.filter(user=user) if browsing_data == "likes" or browsing_data == "def": liked_articles = User.profile_likes(user.username) elif browsing_data == "dislikes": disliked_articles = User.profile_dislikes(user.username) elif browsing_data == "comments": commented_ids = Feedback.objects.filter( user=user, parent_id=None).values('articledetails').distinct() for id in commented_ids: if id['articledetails'] != None: temp = ArticleDetails.objects.get(id=id['articledetails']) feedbacks = Feedback.objects.filter( articledetails_id=id['articledetails'], parent_id=None, user=user) commented_articles.append({ 'topic': temp.header.topic, 'name': temp.header.name, 'slug': temp.slug, 'feedbacks': feedbacks }) return render_to_response( 'profile.html', { 'voted_articles': voted_articles, 'contributions': contributions, 'profile': True, 'browsing_data': browsing_data, 'commented_articles': commented_articles, 'disliked_articles': disliked_articles, 'liked_articles': liked_articles, 'settings': settings, 'user': user }, RequestContext(request))
def post(self, request): user = User() form = UserForm(request.POST, instance=user) if form.is_valid(): user = form.save(commit=False) user.password = make_password(user.password) user.save() auth.login(request, user) return render(request, 'core/profile.html', self.get_context(form)) else: return render(request, 'core/register.html', self.get_context(form))
def test_eq(self): user = User(login='******') user._id = 1 user2 = User(login='******') player = PlayerOrig.from_user(user=user) player2 = PlayerOrig.from_user(user=user) self.assertEqual(player, player2) player3 = PlayerOrig.from_user(user=user2) self.assertNotEqual(player, player3) self.assertNotEqual(player3, player3) self.assertNotEqual(player3, None)
def add_user(auth, fields): user = authenticate(username=auth.get('username'), password=auth.get('password')) auth['tenant'] = user.site.login_base sites = _get_sites(fields.get('site')) if sites: fields['site'] = sites[0] user = User(**fields) user.os_manager = OpenStackManager(auth=auth, caller=user) user.save() return user
def upload_file(request): if request.method == 'POST': form = CreateUserForm(request.POST, request.FILES) if form.is_valid(): instance = User(avatar=request.FILES['file']) instance.save() return redirect('home') else: form = CreateUserForm() return render(request, 'registration/registration_form.html', {'form': form})
def register(self, request): if not configuration.ALLOW_REGISTER or configuration.LDAP_ENABLED: raise RegistrationNotAllowed() serialized = RegisterSerializer(data=request.data) serialized.is_valid(raise_exception=True) User.create_user( username=serialized.validated_data["username"], email=serialized.validated_data["email"], password=serialized.validated_data["password"], ) return Response({"status": "ok"})
def setUp(self): super().setUp() User.objects.delete() user = User( uuid=uuid4(), first_name='Chuck', last_name='Norris', email='*****@*****.**' ) user.password = '******' # It will be hashed user.save()
def add_user(auth, fields): user = authenticate(username=auth.get('username'), password=auth.get('password')) auth['tenant'] = user.site.login_base sites = _get_sites(fields.get('site')) if sites: fields['site'] = sites[0] user = User(**fields) user.os_manager = OpenStackManager(auth=auth, caller = user) user.save() return user
def setUpClass(cls): super().setUpClass() fake = Faker() # Setup test user user = User.objects.create( email='*****@*****.**', username='******', ) user.set_password('admin') user.save() notification = Notification.objects.create( head='Mail head', body='Mail body', place='Fake place', date=fake.future_datetime(end_date="+1d", tzinfo=pytz.UTC), creator=user, ) # -------------------------- # -----Setup other data ---- users = [] for _ in range(5): user = User( email=fake.free_email(), username=fake.name(), ) users.append(user) # LifeHack user.save() # OMG MySQL does not support returning ids bulk_create # If the model’s primary key is an AutoField it does not # retrieve and set the primary key attribute, as save() does, unless the database backend supports it ( # currently PostgreSQL). # user_objects = User.objects.bulk_create(users) notifications = [] for i in range(10): notification = Notification( head='Mail head', body='Mail body', place='Fake place', date=fake.future_datetime(end_date='+1d', tzinfo=pytz.UTC), creator=users[i % 5], ) notifications.append(notification) Notification.objects.bulk_create(notifications)
def create(self): nodetemplate = self.nodetemplate xos_args = self.get_xos_args() if not xos_args.get("site",None): raise Exception("Site name must be specified when creating user") user = User(**xos_args) user.save() self.postprocess(user) self.info("Created User '%s'" % (str(user), ))
def test_ne(self): user = User(login='******') user._id = 1 player = PlayerOrig.from_user(user=user) user2 = User(login='******') user2._id = 2 player2 = PlayerOrig.from_user(user=user2) user3 = User(login='******') player3 = PlayerOrig.from_user(user=user2) self.assertNotEqual(player, player2) self.assertNotEqual(player, player3)
def create(self): nodetemplate = self.nodetemplate xos_args = self.get_xos_args() if not xos_args.get("site", None): raise Exception("Site name must be specified when creating user") user = User(**xos_args) user.save() self.postprocess(user) self.info("Created User '%s'" % (str(user), ))
def UserRegHandler(request): NewAccount = Account() NewAccount.username = request.POST['username'].encode('utf-8') NewAccount.password = request.POST['password'].encode('utf-8') NewAccount.urtype = request.POST['urtype'].encode('utf-8') NewAccount.created = datetime.now() NewUser = User() NewUser.name = request.POST['name'].encode('utf-8') NewUser.mobile = request.POST['mobile'].encode('utf-8') # NewUser.address = request.POST['address'].encode('utf-8') NewUser.save() NewAccount.urid = NewUser.id NewAccount.save() return HttpResponse(NewAccount.id)
def create(self): xos_args = self.get_xos_args() if not xos_args.get("site",None): raise Exception("Site name must be specified when creating user") if ("firstname" not in xos_args) or ("lastname" not in xos_args): raise Exception("firstname and lastname must be specified when creating user") user = User(**xos_args) user.save() self.postprocess(user) self.info("Created User '%s'" % (str(user), ))
def select_by_user(user): if user.is_admin: qs = ControllerUser.objects.all() else: users = User.select_by_user(user) qs = ControllerUser.objects.filter(user__in=users) return qs
def system_users(): user = auth.is_logged_in(request) permission = auth.is_sys_admin(user) return listing(request, None, User.select(), 'system_users', 'system_manage_users', user=user)
def blog_user(user_id, blog_id): # Obtains user edit in blog context. user = auth.is_logged_in(request) blog = Blog.load(blog_id) permission = auth.is_blog_admin(user, blog) user_to_edit = User.find(user_id) return edit_user(user_to_edit, editing_user=user, context=blog_context, blog=blog)
def existe_usuario(cls, usuario): if usuario: if User.query(User.usuario == usuario).fetch(): return True else: return False else: return False
def existe_documento(cls, documento): if documento: if User.query(User.documento == documento).fetch(): return True else: return False else: return False
def site_user(user_id, site_id): # Obtains user edit in site context. user = auth.is_logged_in(request) site = Site.load(site_id) permission = auth.is_site_admin(user, site) user_to_edit = User.find(user_id) return edit_user(user_to_edit, editing_user=user, context=site_context, site=site)
def get_users_with_permission(level): permissions = Permission.select(Permission.user).where( Permission.permission == level) users_with_permissions = User.select().where( User.id << permissions) return users_with_permissions
def post(self): login = self.get_argument("login") password = self.get_argument("password") user = yield User.get_by_login_password(login=login, password=password) self.set_secure_cookie("user", self.get_argument("login")) self.get_user_from_cookies = lambda : self.get_argument("login") session = self.project_session session['current_user'] = user session.save() self.redirect(self.get_argument("next", default="/"))
def get_all_users(request): response_auth = requests.post('http://oll.tv/ispAPI/auth2/', data={ 'login': '******', 'password': '******' }) response_content = response_auth.json() #print response_content response_get_user_list = requests.post('http://oll.tv/ispAPI/getUserList/', data={ 'offset': '', 'hash': response_content['hash'] }) get_user_list_json = response_get_user_list.json() get_user_list = get_user_list_json['data'] num = 0 for i in get_user_list: num = num + 1 u = User(email=i['email'], account=i['account'], birth_date=i['birth_date'], gender=i['gender'], firstname=i['firstname'], lastname=i['lastname'], phone=i['phone'], region=i['region'], receive_news=i['receive_news'], index=['index'], status=i['active'], registration_date=i['reg_date'], oll_id=i['ID']) u.save() return render(request, 'olltv/get_all_users.html', locals())
def facebook_connect(self, user_data): try: # Logging in with Facebook user = User.objects.get(facebook_id=user_data['id']) user.tz_offset = user_data['timezone'] user.save() except User.DoesNotExist: # Creating new account with Facebook user = User() user.email = user_data['email'] user.facebook_id = user_data['id'] user.tz_offset = user_data['timezone'] user.display_name = '%s %s' % (user_data['first_name'], user_data['last_name']) user.set_password(random_string()) user.save() return user
def api_user_register(request): benchmark_start = time.time() response = prepare_response(request) status = 200 form = UserRegisterForm(request.POST) errors = get_validation_errors(form) if form.is_valid(): data = form.cleaned_data new_user = User(email=data['email']) new_user.set_password(data['password']) new_user.save() response['new_user_id'] = new_user.id status = 201 else: response['errors'] = errors status = 400 response['meta']['status'] = status benchmark_end = time.time() response['meta']['execution_time'] = benchmark_end - benchmark_start return build_response(response, status=status)
def author_context(fileinfo, original_page, tag_context, date_counter): if fileinfo is None: author_context = [original_page.author] else: author_context = [fileinfo.author] author_limiter = User.select().where(User.id == author_context) tag_context_next = tag_context.select().where(Page.user << author_limiter) return tag_context_next, date_counter
def post(self): login = self.request.get("login") clave = self.request.get("clave") u = User.login(login, clave) if u: self.login(u) self.redirect("/") else: msg_error = u'El usuario o contraseña es inválido' self.render("login.html", msg_error=msg_error) return
def authenticate(self, saml_authentication=None): if not saml_authentication: # Using another authentication method return None if saml_authentication.is_authenticated(): attributes = saml_authentication.get_attributes() user_changed = False try: user = User.objects.get(username=saml_authentication.get_attributes()['uid'][0]) except User.DoesNotExist: user = User(username=saml_authentication.get_attributes()['uid'][0]) user.set_unusable_password() user.username = attributes['uid'][0] map_fields = { 'realname': 'cn', 'email': 'mail' } # ensure realname for users from webid don't contain unverified note if 'cn' in attributes: attributes['cn'][0] = attributes['cn'][0].replace(' (unverified)', '') for field, samlfield in map_fields.items(): if getattr(user, field) != attributes[samlfield][0]: setattr(user, field, attributes[samlfield][0]) user_changed = True if user_changed: user.save() return user return None
def initialise_db(): # Create an ancestor for all of our Posts to ensure consistency when manipulating Posts blog_instance = Blog.query().get() if not blog_instance: blog_instance = Blog() blog_instance.put() # Create Users if not User.query().fetch(): User( username='******', password='******' # TODO - obfuscate this ).put()
def authenticate(request, username=None, password=None): """ Authenticate User, create Session token and return it's value in a Cookie :param username [STRING] :param password [PASSWORD] :return: 200 or 403 """ user = User.query(User.username == username, User.password == password).get() if user: response = render_to_response(ADMIN_PAGE, {}) response.set_cookie(AUTH_COOKIE_KEY, log_user_in(), max_age=SESSION_EXPIRY) return response else: return HttpResponseForbidden()
def post(self): username = self.get_body_argument('username') password = self.get_body_argument('password') password = User.password_hash(password) remember = self.get_body_argument('remember-me', None) expire = 30 if remember else 1 user = self.db.query(User).filter(User.name == username, User.pwd == password).first() if not user: redirect = self.get_argument('next', '/') self.redirect('/login?next=%s' % redirect) else: self.set_secure_cookie("user_id", str(user.id), expire) redirect = self.get_argument('next', '/user/dashboard?user_id=%d' % user.id) self.redirect(redirect)
def test_call_register_channel(self): ''' Test registration to a channel ''' u = User() u.username = "******" u.first_name = "sample_post" u.email = "*****@*****.**" u.set_password("123") u.save() ch1 = Channel() ch1.owner = u ch1.name = "PostSub" ch1.image = 'http://www.google.com' ch1.description = "A channel description" ch1.kind = PUBLIC ch1.hidden = False ch1.subscriptions = 0 ch1.save() sub1 = Subscriber() sub1.sub_type = 'type2' sub1.token = 'token2' sub1.device_id = 'devid5' sub1.save() resp = ask_subscribe_channel(ch1, sub1.device_id) self.assertEqual(resp, SubscribeResponse.SUBSCRIBED) test_user = User.objects.create_superuser('test_user', '*****@*****.**', 'password') self.client.login(username='******', password='******') data = { 'channel' : ch1.name, 'token' : sub1.token, 'browser' : 'chrome', 'device_id' : sub1.device_id } response = self.client.post(reverse('browser-registration'), json.dumps(data), sub1.token) self.assertTrue(response.status_code, 200)
def test_call_delete(self): ''' Test deleting of a registration of a device from a channel ''' u = User() u.username = "******" u.first_name = "sample_del" u.email = "*****@*****.**" u.set_password("123") u.save() ch1 = Channel() ch1.owner = u ch1.name = "DelSub" ch1.image = 'http://www.google.com' ch1.description = "A channel description" ch1.kind = PUBLIC ch1.hidden = False ch1.subscriptions = 0 ch1.save() sub1 = Subscriber() sub1.sub_type = 'type2' sub1.token = 'token2' sub1.device_id = 'devid6' sub1.save() resp = ask_subscribe_channel(ch1, sub1.device_id) self.assertEqual(resp, SubscribeResponse.SUBSCRIBED) test_user = User.objects.create_superuser('test_user', '*****@*****.**', 'password') self.client.login(username='******', password='******') response = self.client.delete(reverse('browser-get-registration', kwargs={'device_id': sub1.device_id, 'channel_name' : ch1.name})) self.assertEqual(response.status_code, 200) channels = SubscriberManager().get_device_subscriptions(sub1.device_id) sub_channel = next((x for x in channels if x == ch1.name.lower()), None) self.assertIsNone(sub_channel)
def ajax_client_add(request): r_incomingclient = request.POST.get('incomingclient') r_manager = request.POST.get('manager') r_incomingtask = request.POST.get('incomingtask') r_incomingcontact = request.POST.get('incomingcontact') r_date = request.POST.get('date') r_comment = request.POST.get('comment') r_email = request.POST.get('email') r_password = request.POST.get('password') incomingclient = IncomingClient.objects.get(pk=int(r_incomingclient)) incomingtask = IncomingTask.objects.get(pk=int(r_incomingtask)) if r_incomingcontact: incomingcontact = IncomingClientContact.objects.get(pk=int(r_incomingcontact)) else: incomingcontact = incomingtask.incomingclientcontact manager = Manager.objects.get(pk=int(r_manager)) try: User.objects.get(email=r_email) except User.DoesNotExist: user = User(email=r_email, password=r_password, type=3) user.set_password(r_password) user.save() client = Client( user=user, city=incomingclient.city, manager=incomingclient.manager, legal_name=incomingclient.name, actual_name=incomingclient.name, legal_address=incomingclient.actual_address ) client.save() incomingtask.status = 1 incomingtask.save() return HttpResponseRedirect(reverse('client:change', args=(client.id, ))) return_url = reverse('incoming:task-list') + '?error=1' return HttpResponseRedirect(return_url)