Beispiel #1
0
def signup(request):
    form_login = AuthenticationForm()
    form = SignUpForm(request.POST)
    if form.is_valid():
        form.save()
        username = form.cleaned_data.get('username')
        raw_password = form.cleaned_data.get('password1')
        user = authenticate(username=username, password=raw_password)
        login(request, user)
        send_email_from_template("new user", user.email,
                                 context={
                                     'user': user,
                                     'role': form.cleaned_data['role'],
                                     'organization': form.cleaned_data['organization_name']
                                 },
                                 enqueued=True,
                                 user=user,
                                 upfile=None)
        return redirect(reverse_lazy('index'))
    # else:
    #    form = SignUpForm()
    return render(request, 'registration/login.html',
                  {'form_signup': form,
                   'form': form_login})
Beispiel #2
0
 def get_absolute_url(self):
     """ Renvoyer l'URL d'accès à la ressource """
     return reverse_lazy('forum:label-view', kwargs={'slug': self.slug})
Beispiel #3
0
 def get_success_url(self):
     return reverse_lazy(
         'laboratory:objectview_list',
         args=(self.lab,)) + "?type_id=" + self.get_object().type
Beispiel #4
0
class StudentUpdate(UpdateView):
    form_class = StudentForm
    model = Student
    success_url = reverse_lazy('notice_list')
Beispiel #5
0
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'm@0ep8f(w8_u*$0)&8da_u)7g(&v*_bqh(gl*f7bfv*gx-rrbr'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

#소셜로그인이 끝난 뒤 이동할 메인페이지 주소를 저장하는 변수를 등록
#setting.py와 같은 웹서버 로드가 완전히 되지 않은 공간에서 별칭 기반의 URL검색을 사용하려면 reverse_lazy 함수를 사용해야함
LOGIN_REDIRECT_URL = reverse_lazy('main')
#비로그인 상태에서 로그인이 필요한 기능을 사용했을 때 로그인페이지를 띄우기 위해 로그인 페이지의 URL을 등록하는 변수
LOGIN_URL = reverse_lazy("cl:signin")

#외부 웹 클라이언트가 웹서버에게 요청할 때 허용되는 도메인주소를 저장하는 변수
#웹서버에 접근할수 있는 도메인 주소는 12.0.0.1과 xxx.pythonanywhere.com으로만 요청할 수 있음
ALLOWED_HOSTS = ['127.0.0.1','.pythonanywhere.com']
#social_django에서 인증절차에 사용되는 클래스 등록
AUTHENTICATION_BACKENDS = (
    'social_core.backends.open_id.OpenIdAuth',
    #구글로그인 기능을 사용하기 위한 클래스 등록
    'social_core.backends.google.GoogleOpenId',
    'social_core.backends.google.GoogleOAuth2',
    'social_core.backends.google.GoogleOAuth',
    #구글로그인 정보를 django User모델클래스에 연동하기 위한 클래스 등록
    'django.contrib.auth.backends.ModelBackend',
Beispiel #6
0
    def test_clockin_delta_when_forgot_to_clockout_other_shift(self):

        position = mixer.blend('api.Position')
        starting_at = timezone.now() + timedelta(days=1)
        ending_at = starting_at + timedelta(minutes=90)
        self.test_clockinout_shift_many, _, __ = self._make_shift(
            venuekwargs={
                'latitude': -64,
                'longitude': 10
            },
            shiftkwargs=dict(status='OPEN', starting_at=starting_at, ending_at=ending_at, position=position, minimum_hourly_rate=14, minimum_allowed_rating = 3, maximum_allowed_employees=4, maximum_clockin_delta_minutes=15 ),
            employer=self.test_employer)
        (
            self.test_user_employee2,
            self.test_employee2,
            self.test_profile_employee2
        ) = self._make_user(
            'employee',
            employexkwargs=dict(
                minimum_hourly_rate = 10,
                rating=1,
                positions=[position.id],
                stop_receiving_invites=False,
            ),
            profilekwargs = dict(
                latitude = -64,
                longitude = 10
            ),
            userkwargs=dict(
                username='******',
                email='*****@*****.**',
                is_active=True,
            )
        ) 
        self.test_previous_shift, _, __ = self._make_shift(
            venuekwargs={
                'latitude': -64,
                'longitude': 10
            },
            shiftkwargs=dict(status='OPEN', starting_at=starting_at - timedelta(days=1), ending_at=ending_at- timedelta(days=1), position=position, minimum_hourly_rate=14, minimum_allowed_rating = 3, maximum_allowed_employees=4 ),
            employer=self.test_employer)

        mixer.blend(
            'api.ShiftEmployee',
            employee=self.test_employee2,
            shift=self.test_clockinout_shift_many,
        )
        mixer.blend(
            'api.ShiftEmployee',
            employee=self.test_employee2,
            shift=self.test_previous_shift,
        )
        self.client.force_login(self.test_user_employee2)
        mixer.blend(
            'api.ClockIn',
            employee=self.test_employee2,
            shift=self.test_previous_shift,
            author=self.test_profile_employee2,
            started_at=self.test_previous_shift.starting_at,
            latitude_in=-64,
            longitude_in=10,
            ended_at=None,
        )

        url = reverse_lazy('api:me-employees-clockins')


        payload = {
            'shift': self.test_clockinout_shift_many.id,
            'author': self.test_profile_employee2.id,
            'started_at': self.test_clockinout_shift_many.starting_at,
            'latitude_out': -64,
            'longitude_out': 10,
            'latitude_in': -64,
            'longitude_in': 10,
        }

        response = self.client.post(url, data=payload)
        print(response.content)
        self.assertEquals(response.status_code, 400)
Beispiel #7
0
 def get_success_url(self):
     return reverse_lazy(
         'laboratory:objectview_list',
         args=(self.lab,)) + "?type_id=" + self.get_object().type
Beispiel #8
0
 def get_success_url(self):
     return reverse_lazy('laboratory:furniture_update',
                         args=(self.lab, self.object.pk))
Beispiel #9
0
class PasswordResetTestSuite(TestCase, WithMakeUser):
    """
    Endpoint tests for password reset
    """
    PW_RESET_URL = reverse_lazy('api:password-reset-email')

    def setUp(self):
        self.test_user, *_ = self._make_user('employee',
                                             userkwargs=dict(
                                                 username='******',
                                                 email='*****@*****.**',
                                                 is_active=True,
                                             ))

    @patch('api.utils.email.requests')
    @override_settings(EMAIL_NOTIFICATIONS_ENABLED=True)
    def test_send_link_with_good_input_notify_enabled(self, mocked_requests):
        """
        Send password change email with good data
        """
        mocked_requests.post.return_value.status_code = 200

        payload = {
            'email': '*****@*****.**',
        }
        response = self.client.post(self.PW_RESET_URL,
                                    data=json.dumps(payload),
                                    content_type="application/json")

        self.assertEquals(response.status_code, 200,
                          'It should return a success response')
        self.assertEquals(mocked_requests.post.called, True,
                          'It should have called requests.post to send mail')

    @patch('api.utils.email.requests')
    @override_settings(EMAIL_NOTIFICATIONS_ENABLED=False)
    def test_send_link_with_good_input_notify_disabled(self, mocked_requests):
        """
        Send password change email (actually dont) with good data.
        """
        payload = {
            'email': '*****@*****.**',
        }
        response = self.client.post(self.PW_RESET_URL,
                                    data=json.dumps(payload),
                                    content_type="application/json")

        self.assertEquals(response.status_code, 200,
                          'It should return a success response')
        self.assertEquals(
            mocked_requests.post.called, False,
            'It should NOT have called requests.post to send mail')

    @patch('api.utils.email.requests')
    def test_change_pw_non_existing_user(self, mocked_requests):
        """
        Send password change email (actually dont) with good data.
        """
        payload = {
            'email': '*****@*****.**',
        }
        response = self.client.post(self.PW_RESET_URL,
                                    data=json.dumps(payload),
                                    content_type="application/json")

        self.assertEquals(response.status_code, 404,
                          'It should return an error response')

        self.assertEquals(
            mocked_requests.post.called, False,
            'It should NOT have called requests.post to send mail')

    @patch('api.utils.email.requests')
    def test_change_pw_no_mail(self, mocked_requests):
        """
        Send password change email (actually dont) with good data.
        """
        payload = {}
        response = self.client.post(self.PW_RESET_URL,
                                    data=json.dumps(payload),
                                    content_type="application/json")

        self.assertEquals(response.status_code, 400,
                          'It should return an error response')
        self.assertEquals(
            mocked_requests.post.called, False,
            'It should NOT have called requests.post to send mail')

    def test_reset_bad_token(self):
        """
        Try to reach the form with a bad token
        """

        payload = {
            'token': ':really-evil-token:',
        }

        response = self.client.get(
            self.PW_RESET_URL,
            data=payload,
        )

        self.assertEquals(response.status_code, 400,
                          'It should return an error response')

    def test_reset_kind_of_bad_token(self):
        """
        Try to reach the form with a bad token, good shape, bad data
        """

        jtw_payload = jwt_payload_handler(self.test_user)

        token = jwt_encode_handler(jtw_payload) + 'A=!'

        payload = {
            'token': token,
        }

        response = self.client.get(
            self.PW_RESET_URL,
            data=payload,
        )

        self.assertEquals(response.status_code, 400,
                          'It should return an error response')

    def test_reset_good_token(self):
        """
        Try to reach the form with a good token.
        """

        jtw_payload = jwt_payload_handler(self.test_user)

        token = jwt_encode_handler(jtw_payload)

        payload = {
            'token': token,
        }

        response = self.client.get(
            self.PW_RESET_URL,
            data=payload,
        )

        self.assertEquals(response.status_code, 200,
                          'It should return an error response')

    def test_reset_pw_bad_token(self):
        """
        Reset password with a bad token
        """

        payload = {
            'token': ':evil-token:',
            'new_password': '******',
            'repeat_password': '******',
        }

        response = self.client.put(self.PW_RESET_URL,
                                   data=json.dumps(payload),
                                   content_type="application/json")

        self.assertEquals(response.status_code, 400,
                          'It should return an error response')

    def test_reset_pw_kindof_good_token(self):
        """
        Reset password with a bad token
        """
        jtw_payload = jwt_payload_handler(self.test_user)

        token = jwt_encode_handler(jtw_payload)

        payload = {
            'token': token + 'A=!',
            'new_password': '******',
            'repeat_password': '******',
        }

        response = self.client.put(self.PW_RESET_URL,
                                   data=json.dumps(payload),
                                   content_type="application/json")

        self.assertEquals(response.status_code, 400,
                          'It should return an error response')

    def test_reset_pw_not_matching_pw(self):
        """
        Reset password with not maching password1/2
        """

        jtw_payload = jwt_payload_handler(self.test_user)

        token = jwt_encode_handler(jtw_payload)

        payload = {
            'token': token,
            'new_password': '******',
            'repeat_password': '******',
        }

        response = self.client.put(self.PW_RESET_URL,
                                   data=json.dumps(payload),
                                   content_type="application/json")

        self.assertEquals(response.status_code, 400,
                          'It should return an error response')

    def test_reset_pw_all_good(self):
        """
        Reset password with good input
        """

        jtw_payload = jwt_payload_handler(self.test_user)

        token = jwt_encode_handler(jtw_payload)

        payload = {
            'token': token,
            'new_password': '******',
            'repeat_password': '******',
        }

        response = self.client.put(self.PW_RESET_URL,
                                   data=json.dumps(payload),
                                   content_type="application/json")

        self.assertEquals(response.status_code, 204,
                          'It should return a success response')

    def test_missing_email_from_db(self):
        """
        Test if email dissapear from database
        """
        other_user, other_emp, other_pro = self._make_user(
            'employee',
            userkwargs=dict(
                username='******',
                email='*****@*****.**',
                is_active=True,
            ))

        jtw_payload = jwt_payload_handler(other_user)

        token = jwt_encode_handler(jtw_payload)

        for obj in (other_user, other_emp, other_pro):
            obj.delete()

        payload = {
            'token': token,
            'new_password': '******',
            'repeat_password': '******',
        }

        response = self.client.put(self.PW_RESET_URL,
                                   data=json.dumps(payload),
                                   content_type="application/json")

        self.assertEquals(response.status_code, 400,
                          'It should return an error response')
Beispiel #10
0
    def test_academy_id_member_with_two_roles(self):
        """Test /academy/:id/member"""
        roles = ['konan', 'pain']
        models = [
            self.generate_models(authenticate=True,
                                 role=roles[0],
                                 capability='read_member',
                                 profile_academy=True)
        ]

        models = models + [
            self.generate_models(authenticate=True,
                                 role=roles[1],
                                 capability='read_member',
                                 profile_academy=True,
                                 models={'academy': models[0]['academy']})
        ]
        url = reverse_lazy('authenticate:academy_id_member',
                           kwargs={'academy_id': 1})
        args = ','.join(roles)
        url = f'{url}?roles={args}'
        response = self.client.get(url)
        json = response.json()

        self.assertEqual(json, [{
            'academy': {
                'id': model['academy'].id,
                'name': model['academy'].name,
                'slug': model['academy'].slug,
            },
            'address':
            None,
            'created_at':
            datetime_to_iso_format(
                self.get_profile_academy(
                    model['profile_academy'].id).created_at),
            'email':
            None,
            'first_name':
            None,
            'id':
            model['profile_academy'].id,
            'last_name':
            None,
            'phone':
            '',
            'role': {
                'name': roles[model['profile_academy'].id - 1],
                'slug': roles[model['profile_academy'].id - 1],
            },
            'status':
            'INVITED',
            'user': {
                'email': model['user'].email,
                'first_name': model['user'].first_name,
                'id': model['user'].id,
                'last_name': model['user'].last_name,
                'github': None,
            },
        } for model in models])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_profile_academy_dict(),
                         [{
                             'academy_id': 1,
                             'address': None,
                             'email': None,
                             'first_name': None,
                             'id': 1 + index,
                             'last_name': None,
                             'phone': '',
                             'role_id': roles[index],
                             'status': 'INVITED',
                             'user_id': 2 + index,
                         } for index in range(0, 2)])
Beispiel #11
0
    def test_academy_id_member_with_github(self):
        """Test /academy/:id/member"""
        role = 'konan'
        model = self.generate_models(authenticate=True,
                                     role=role,
                                     capability='read_member',
                                     profile_academy=True,
                                     credentials_github=True)
        url = reverse_lazy('authenticate:academy_id_member',
                           kwargs={'academy_id': 1})
        response = self.client.get(url)
        json = response.json()

        profile_academy = self.get_profile_academy(1)

        self.assertEqual(
            json,
            [{
                'academy': {
                    'id': model['academy'].id,
                    'name': model['academy'].name,
                    'slug': model['academy'].slug,
                },
                'address': None,
                'created_at': datetime_to_iso_format(
                    profile_academy.created_at),
                'email': None,
                'first_name': None,
                'id': model['profile_academy'].id,
                'last_name': None,
                'phone': '',
                'role': {
                    'name': role,
                    'slug': role,
                },
                'status': 'INVITED',
                'user': {
                    'email': model['user'].email,
                    'first_name': model['user'].first_name,
                    'id': model['user'].id,
                    'last_name': model['user'].last_name,
                    'github': {
                        'avatar_url': None,
                        'name': None,
                        'username': None
                    },
                },
            }])
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.all_profile_academy_dict(), [{
            'academy_id': 1,
            'address': None,
            'email': None,
            'first_name': None,
            'id': 1,
            'last_name': None,
            'phone': '',
            'role_id': role,
            'status': 'INVITED',
            'user_id': 2,
        }])
Beispiel #12
0
class AnularHora(DeleteView):
    model = ReservaServicio
    template_name = 'reserva/anular_reserva.html'
    success_url = reverse_lazy('listar_reservas')
Beispiel #13
0
    url(r'^local/', include(([
        url(r'^login/$', auth_views.LoginView.as_view(),
            {'template_name': 'registration/login.html',
             'authentication_form': forms.LoginForm},
            name="login"),

        url(r'^logout/$', auth_views.LogoutView.as_view(),
            {'template_name': 'registration/logout.html'},
            name="logout"),
    ], 'accounts'), namespace="local")),

    # and keep password resets separate from either (though technically local)
    url(r'^local/reset/', include(([
        url(r'^$', auth_views.PasswordResetView.as_view(
                success_url=reverse_lazy('accounts:reset:sent'),
                from_email=settings.DEFAULT_FROM_ADDR,
                email_template_name='registration/password_reset_email.txt'
            ),
            {'template_name': 'registration/reset_password.html'},
            name='start'
        ),
        url(r'^confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$',
            auth_views.PasswordResetConfirmView.as_view(success_url=reverse_lazy('accounts:reset:done')),
            {'template_name': 'registration/reset_password_form.html'},
            name='confirm'),
        url(r'^sent/$', auth_views.PasswordResetDoneView.as_view(),
            {'template_name': 'registration/reset_password_sent.html'},
            name='sent'),
        url(r'^done/$', auth_views.PasswordResetCompleteView.as_view(),
            {'template_name': 'registration/reset_password_finished.html'},
Beispiel #14
0
"""
from django.conf.urls import url, include
from django.contrib import admin
from laboratory import urls as laboratory_urls

from djreservation import urls as djreservation_urls
from academic.urls import urlpatterns as academic_urls
from ajax_select import urls as ajax_select_urls
from authentication.urls import urlpatterns as auth_urls
from django.conf import settings
from msds.urls import urlpatterns as msds_urls
from django.views.generic.base import RedirectView
from django.urls.base import reverse_lazy

urlpatterns = auth_urls + [
    url(r'^$', RedirectView.as_view(url=reverse_lazy(
        'msds:organilab_tree')), name='index'),
    url(r'^admin/', admin.site.urls),
    url(r'^', include(laboratory_urls, namespace='laboratory')),
    url(r'^ajax_select/', include(ajax_select_urls)),
    url(r'msds/', include(msds_urls, namespace='msds')),
    url(r'^ajax_select/', include(ajax_select_urls)),
    url(r'^weblog/', include('zinnia.urls', namespace='zinnia')),
    url(r'^comments/', include('django_comments.urls')),
]

if settings.FULL_APPS:
    from api import url as api_urls
    urlpatterns += [
        url(r'^api/', include(api_urls))
    ]
urlpatterns += djreservation_urls.urlpatterns
Beispiel #15
0
 def get_success_url(self):
     success_url = reverse_lazy('rent_create',
                                kwargs={'pk': self.object.address.id})
     return success_url
Beispiel #16
0
 def get_success_url(self):
     success_url = reverse_lazy('expense_create',
                                kwargs={'pk': self.object.pk})
     return success_url
Beispiel #17
0
 def get_success_url(self):
     return reverse_lazy('recipe-edit-mode', args=(self.object.recipe.id,))
Beispiel #18
0
 def get_success_url(self):
     return reverse_lazy('laboratory:list_shelf', args=(self.lab,))
Beispiel #19
0
DEBUG = True
#127.0.0.1 대신 사용할 외부 도메인 주소를 저장하는 변수
ALLOWED_HOST = ['.pythonanywhere.com']
'''
reverse 와 reverse_lazy 공통점
등록된 URL 의 별칭을 바탕으로 URL 문자열을 반환하는 함수
차이점- URL 문자열을 반환하는 시기
reverse : 함수 호출이 되자마자 등록된 URL 에서 찾음
reverse_lazy : 서버가 정상적으로 실행된 뒤에 URL 을 찾음
setting.py 는 웹서버 실행에 필요한 변수값을 읽는 단계이므로,
reverse_lazy 함수를 사용해야함
헷갈린다  -> 무조건 reverse_lazy함수사용
'''
#loin_required 데코레이터가 비로그인 상태의 클라이언트에게 전달할
#로그인 페이지 주소
LOGIN_URL = reverse_lazy('cl:signin')
#소셜로그인을 마친 후 이동할 페이지 주소
LOGIN_REDIRECT_URL = '/vote/'  #reverse_lazy('vote:index')

#social_django 어플리케이션으로 Google-plus 로그인에 사용되는
#ID와 보안 비밀을 저장하는 변수
SOCIAL_AUTH_GOOGLE_PLUS_KEY = '898722220883-ie5tngokjtlm2urap770u142r9rp2jen.apps.googleusercontent.com'
SOCIAL_AUTH_GOOGLE_PLUS_SECRET = 'CjR4twj7775rAC8TQlTU7x8H'

#로그인 처리에 사용되는 클래스를 등록하는 변수
#-> 소셜로그인과 장고의 Auth 어플리케이션의 User 모델클래스를 연동하기 위함
AUTHENTICATION_BACKENDS = (
    #구글로그인 사용하기 위한 클래스
    'social_core.backends.open_id.OpenIdAuth',
    'social_core.backends.google.GoogleOpenId',
    'social_core.backends.google.GoogleOAuth2',
Beispiel #20
0
 def get_success_url(self):
     return reverse_lazy('academic_procedure_list')
Beispiel #21
0
    def test_ical_events__with_two_and_venue__with_two_academies_slug(self):
        """Test /academy/cohort without auth"""
        event_kwargs = {'status': 'ACTIVE'}
        venue_kwargs = {
            'street_address': 'Street 2 #10-51',
            'city': 'Gaira',
            'state': 'Magdalena',
            'country': 'Colombia',
        }
        base = self.generate_models(academy=True)

        models = [
            self.generate_models(user=True,
                                 event=True,
                                 venue=True,
                                 event_kwargs=event_kwargs,
                                 venue_kwargs=venue_kwargs,
                                 models=base),
            self.generate_models(user=True,
                                 event=True,
                                 venue=True,
                                 event_kwargs=event_kwargs,
                                 venue_kwargs=venue_kwargs,
                                 models=base),
        ]

        base = self.generate_models(academy=True)

        models = models + [
            self.generate_models(user=True,
                                 event=True,
                                 venue=True,
                                 event_kwargs=event_kwargs,
                                 venue_kwargs=venue_kwargs,
                                 models=base),
            self.generate_models(user=True,
                                 event=True,
                                 venue=True,
                                 event_kwargs=event_kwargs,
                                 venue_kwargs=venue_kwargs,
                                 models=base),
        ]

        url = reverse_lazy('events:academy_id_ical_events')
        args = {
            'academy_slug':
            ','.join(list(dict.fromkeys([x.academy.slug for x in models])))
        }
        response = self.client.get(url + "?" + urllib.parse.urlencode(args))

        event1 = models[0]['event']
        event2 = models[1]['event']
        event3 = models[2]['event']
        event4 = models[3]['event']
        user1 = models[0]['user']
        user2 = models[1]['user']
        user3 = models[2]['user']
        user4 = models[3]['user']
        expected = '\r\n'.join([
            'BEGIN:VCALENDAR',
            'VERSION:2.0',
            'PRODID:-//BreatheCode//Academy Events (1\,2)//EN',
            'REFRESH-INTERVAL:PT15M',
            'X-WR-CALDESC:',
            f'X-WR-CALNAME:Academy - Events',
            # event
            'BEGIN:VEVENT',
            f'DTSTART;VALUE=DATE-TIME:{self.datetime_to_ical(event1.starting_at)}',
            f'DTEND;VALUE=DATE-TIME:{self.datetime_to_ical(event1.ending_at)}',
            f'DTSTAMP;VALUE=DATE-TIME:{self.datetime_to_ical(event1.created_at)}',
            f'UID:breathecode_event_{event1.id}',
            'LOCATION:Street 2 #10-51\, Gaira\, Magdalena\, Colombia',
            self.line_limit(
                f'ORGANIZER;CN="{user1.first_name} {user1.last_name}";ROLE=OWNER:MAILTO:{user1.email}'
            ),
            'END:VEVENT',
            # event
            'BEGIN:VEVENT',
            f'DTSTART;VALUE=DATE-TIME:{self.datetime_to_ical(event2.starting_at)}',
            f'DTEND;VALUE=DATE-TIME:{self.datetime_to_ical(event2.ending_at)}',
            f'DTSTAMP;VALUE=DATE-TIME:{self.datetime_to_ical(event2.created_at)}',
            f'UID:breathecode_event_{event2.id}',
            'LOCATION:Street 2 #10-51\, Gaira\, Magdalena\, Colombia',
            self.line_limit(
                f'ORGANIZER;CN="{user2.first_name} {user2.last_name}";ROLE=OWNER:MAILTO:{user2.email}'
            ),
            'END:VEVENT',
            # event
            'BEGIN:VEVENT',
            f'DTSTART;VALUE=DATE-TIME:{self.datetime_to_ical(event3.starting_at)}',
            f'DTEND;VALUE=DATE-TIME:{self.datetime_to_ical(event3.ending_at)}',
            f'DTSTAMP;VALUE=DATE-TIME:{self.datetime_to_ical(event3.created_at)}',
            f'UID:breathecode_event_{event3.id}',
            'LOCATION:Street 2 #10-51\, Gaira\, Magdalena\, Colombia',
            self.line_limit(
                f'ORGANIZER;CN="{user3.first_name} {user3.last_name}";ROLE=OWNER:MAILTO:{user3.email}'
            ),
            'END:VEVENT',
            # event
            'BEGIN:VEVENT',
            f'DTSTART;VALUE=DATE-TIME:{self.datetime_to_ical(event4.starting_at)}',
            f'DTEND;VALUE=DATE-TIME:{self.datetime_to_ical(event4.ending_at)}',
            f'DTSTAMP;VALUE=DATE-TIME:{self.datetime_to_ical(event4.created_at)}',
            f'UID:breathecode_event_{event4.id}',
            'LOCATION:Street 2 #10-51\, Gaira\, Magdalena\, Colombia',
            self.line_limit(
                f'ORGANIZER;CN="{user4.first_name} {user4.last_name}";ROLE=OWNER:MAILTO:{user4.email}'
            ),
            'END:VEVENT',
            'END:VCALENDAR',
            '',
        ])

        self.assertEqual(response.content.decode('utf-8'), expected)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
Beispiel #22
0
    def test_more_than_one_employee_clockout_on_the_same_shift(self):   
    #Se debe permitir que otro employee pueda hacer clockin a pesar que otro employee no han hecho clock out. 
        position = mixer.blend('api.Position')
        starting_at = timezone.now() + timedelta(days=1)
        ending_at = starting_at + timedelta(minutes=90)
        self.test_clockinout_shift_many, _, __ = self._make_shift(
            venuekwargs={
                'latitude': -64,
                'longitude': 10
            },
            shiftkwargs=dict(status='OPEN', starting_at=starting_at, ending_at=ending_at, position=position, minimum_hourly_rate=14, minimum_allowed_rating = 3, maximum_allowed_employees=4 ),
            employer=self.test_employer)
        (
            self.test_user_employee2,
            self.test_employee2,
            self.test_profile_employee2
        ) = self._make_user(
            'employee',
            employexkwargs=dict(
                minimum_hourly_rate = 10,
                rating=1,
                positions=[position.id],
                stop_receiving_invites=False,
            ),
            profilekwargs = dict(
                latitude = -64,
                longitude = 10
            ),
            userkwargs=dict(
                username='******',
                email='*****@*****.**',
                is_active=True,
            )
        ) 
        mixer.blend(
            'api.ShiftEmployee',
            employee=self.test_employee2,
            shift=self.test_clockinout_shift_many,
        )
        mixer.blend(
            'api.ClockIn',
            employee=self.test_employee,
            shift=self.test_clockinout_shift_many,
            author=self.test_profile_employee,
            started_at=self.test_clockinout_shift_many.starting_at,
            latitude_in=-64,
            longitude_in=10,
            ended_at=None,
        )
        self.client.force_login(self.test_user_employee2)
        mixer.blend(
            'api.ClockIn',
            employee=self.test_employee2,
            shift=self.test_clockinout_shift_many,
            author=self.test_profile_employee2,
            started_at=self.test_clockinout_shift_many.starting_at,
            latitude_in=-64,
            longitude_in=10,
            ended_at=None,
        )
        url = reverse_lazy('api:me-employees-clockins')


        payload = {
            'shift': self.test_clockinout_shift_many.id,
            'author': self.test_profile_employee2.id,
            'ended_at': self.test_clockinout_shift_many.ending_at,
            'latitude_out': -64,
            'longitude_out': 10,
            'latitude_in': -64,
            'longitude_in': 10,
        }

        response = self.client.post(url, data=payload)
        print(response.content)
        self.assertEquals(response.status_code, 201)

        count = Clockin.objects.filter(
            employee_id=self.test_employee2.id,
            shift_id=self.test_clockinout_shift_many.id,
        ).count()
        self.assertEquals(count, 1)
Beispiel #23
0
USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
MEDIA_ROOT = 'uploaded_media/'
MEDIA_URL = 'media/'

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = reverse_lazy('login')

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES':
    ('rest_framework.permissions.IsAuthenticated', )
}

CITIES_LIGHT_TRANSLATION_LANGUAGES = ['en']
CITIES_LIGHT_INCLUDE_CITY_TYPES = []

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "asgiref.inmemory.ChannelLayer",
        "ROUTING": "SCTF.routing.channel_routing",
    },
}
Beispiel #24
0
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf.urls import url

from demo.urls import urlpatterns as demourls
from django.views.generic.base import TemplateView
from django.contrib.auth.views import LoginView, LogoutView
from django.urls.base import reverse_lazy

urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name="index.html"), name="home"),
    url(r'^accounts/login/$', LoginView.as_view(),
        {'redirect_to': reverse_lazy('home')}, name='login'),
    url(r'^logout/$', LogoutView.as_view(next_page=reverse_lazy('home')),
        name='logout'),
    url('admin/', admin.site.urls),
]


urlpatterns += demourls
Beispiel #25
0
class ProjectUpdateView(LoginRequiredMixin, UpdateView):
    model = Flight
    form_class = FlightForm
    success_url = reverse_lazy('dashboard')
Beispiel #26
0
 def get_success_url(self, *args, **kwargs):
     redirect = reverse_lazy('laboratory:objectview_list', args=(
         self.lab,)) + "?type_id=" + self.object.type
     return redirect
Beispiel #27
0
class DeleteTask(DeleteView):
    model = Task
    template_name = "delete_task.html"
    success_url = reverse_lazy('tasks:show_user_tasks')
Beispiel #28
0
 def get_success_url(self):
     return reverse_lazy('laboratory:objectview_list',
                         args=(self.lab,))
Beispiel #29
0
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django': {
            'handlers': ['console', 'console_debug_false', 'mail_admins'],
            'level': 'INFO',
        },
        'django.server': {
            'handlers': ['django.server'],
            'level': 'INFO',
            'propagate': False,
        }
    }
}

COMPRESS_PRECOMPILERS = (('text/x-scss', 'django_libsass.SassCompiler'),)
COMPRESS_CSS_FILTERS = (
    # CssAbsoluteFilter is incredibly slow, especially when dealing with our _flags.scss
    # However, we don't need it if we consequently use the static() function in Sass
    # 'compressor.filters.css_default.CssAbsoluteFilter',
    'compressor.filters.cssmin.CSSCompressorFilter',
)

LOGIN_REDIRECT_URL = "/"
LOGIN_URL = reverse_lazy("users:login")
LOGOUT_URL = reverse_lazy("users:logout")
Beispiel #30
0
 def get_success_url(self):
     success_url = reverse_lazy('cap_rate_update',
                                kwargs={'pk': self.object.address.id})
     obj, created = Result.objects.update_or_create(
         address_id=self.object.address.id)
     return success_url
Beispiel #31
0
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"

AUTH_USER_MODEL = 'account.User'

from django.urls.base import reverse_lazy
LOGIN_URL = reverse_lazy('login')

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = ''  #자기이메일
EMAIL_HOST_PASSWORD = ''  #비밀번호
EMAIL_PORT = 587
EMAIL_USE_TLS = True
Beispiel #32
0
 def get_success_url(self):
     success_url = reverse_lazy('result_list')
     address = Address.objects.get(id=self.object.address.id)
     address.delete()
     return success_url
Beispiel #33
0
import os
from django.urls.base import reverse_lazy
#reverse_lazy와 reverse 공통점
#등록된 URL의 별칭을 바탕으로 URL을 반환하는 함수
#차이점 - URL을 반환하는 시기
#reverse : 함수 호출이 되자마자 등록된 URL에서 찾음
#reverse_lazy : 웹서버가 정상적으로 실행이 된 뒤에 등록된 URL에서 찾음

#헷갈리는 경우 모든 파이썬코드에서 reverse_lazy를 써도 무방함

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

#login_required 데코레이터가 띄우는 로그인 URL을 설정
LOGIN_URL = reverse_lazy('cl:signin')
#소셜로그인 완료 후 이동할 URL주소를 저장하는 변수-django기능
LOGIN_REDIRECT_URL = reverse_lazy('blog:index')

#social_django 어플리케이션의 설정값

#인증관련 모듈을 추가
AUTHENTICATION_BACKENDS = (
    #구글 로그인 처리 관련 파이썬 클래스 추가
    'social_core.backends.open_id.OpenIdAuth',
    'social_core.backends.google.GoogleOpenId',
    'social_core.backends.google.GoogleOAuth2',
    'social_core.backends.google.GooglePlusAuth',
    #소셜로그인 정보를 django의 User모델클래스에 저장하기 위한 클래스
    'django.contrib.auth.backends.ModelBackend'
    )
Beispiel #34
0
 def get_success_url(self):
     return reverse_lazy('laboratory:furniture_create', args=(self.lab,))
Beispiel #35
0
class DeletePoll(DeleteView):
    template_name = 'poll/delete_poll.html'
    model = Poll
    context_object_name = 'poll'
    success_url = reverse_lazy('index')
Beispiel #36
0
class DeleteChoice(DeleteView):
    template_name = 'choice/delete_choice.html'
    model = Choice
    context_object_name = 'choice'
    success_url = reverse_lazy('index')
Beispiel #37
0
    def test_clockout_having_clockin_past_shift(self):
        # Si ya hice clockin en otro shift y hice clockout, puedo hacer clockin in este shift.
        url = reverse_lazy('api:me-employees-clockins')

        mixer.blend(
            'api.ClockIn',
            employee=self.test_employee,
            shift=self.test_shift,
            author=self.test_profile_employee,
            started_at=self.test_shift.starting_at,
            latitude_in=-64,
            longitude_in=10,
            ended_at=None,
        )

        payload = {
            'shift': self.test_shift.id,
            'author': self.test_profile_employee.id,
            'ended_at': self.test_shift.ending_at,
            'latitude_out': -64,
            'longitude_out': 10,
        }

        response = self.client.post(url, data=payload)
        self.assertEquals(response.status_code, 201)

        count = Clockin.objects.filter(
            employee_id=self.test_employee.id,
            shift_id=self.test_shift.id,
        ).count()
        self.assertEquals(count, 1)

        
        # second shift clock in 
        second_shift_starting_at = timezone.now() + timedelta(hours=12)
        second_shift_ending_at = timezone.now() + timedelta(hours=20) 
 
        self.test_second_shift, _, __ = self._make_shift(
            venuekwargs={
                'latitude': -64,
                'longitude': 10
            },
            shiftkwargs={
                'status': SHIFT_STATUS_CHOICES[0][0],
                'maximum_clockin_delta_minutes': None,
                'maximum_clockout_delay_minutes': None,
                'starting_at': second_shift_starting_at,
                'ending_at': second_shift_ending_at
            },
            employer=self.test_employer)
        mixer.blend(
            'api.ShiftEmployee',
            employee=self.test_employee,
            shift=self.test_second_shift,
        )
        payload2 = {
            'shift': self.test_second_shift.id,
            'author': self.test_profile_employee.id,
            'started_at': second_shift_starting_at,
            'latitude_in': -64,
            'longitude_in': 10,
        }

        response = self.client.post(url, data=payload2)
        print(response.content)
        self.assertEquals(response.status_code, 201, 'You are able to clockin if you clock out the previous shift')
        response_json = response.json()
Beispiel #38
0
 def get_success_url(self, *args, **kwargs):
     redirect = reverse_lazy('laboratory:objectview_list', args=(
         self.lab,)) + "?type_id=" + self.object.type
     return redirect
Beispiel #39
0
    def test_delta_delay_retroactively(self):
        # If those two fields are updated for the company and retroactive == True then we need to update all the upcoming shifts as well, the same properties but in the shifts.
        #open and filled.

        #SHIFTS
        self.test_shift_filled, _, __ = self._make_shift(
            venuekwargs={
                'latitude': -64,
                'longitude': 10
            },
            shiftkwargs={
                'status': "FILLED",
                'maximum_clockin_delta_minutes': None,
                'maximum_clockout_delay_minutes': None,
                'starting_at': timezone.now(),
                'ending_at': timezone.now() + timedelta(hours=8)
            },
            employer=self.test_employer)    

        self.test_shift_open, _, __ = self._make_shift(
            venuekwargs={
                'latitude': -64,
                'longitude': 10
            },
            shiftkwargs={
                'status': "OPEN",
                'maximum_clockin_delta_minutes': None,
                'maximum_clockout_delay_minutes': None,
                'starting_at': timezone.now() + timedelta(days=1),
                'ending_at': timezone.now() + timedelta(days=1)
            },
            employer=self.test_employer)       

        self.test_shift_open2, _, __ = self._make_shift(
            venuekwargs={
                'latitude': -64,
                'longitude': 10
            },
            shiftkwargs={
                'status': "OPEN",
                'maximum_clockin_delta_minutes': None,
                'maximum_clockout_delay_minutes': None,
                'starting_at': timezone.now() + timedelta(days=2),
                'ending_at': timezone.now() + + timedelta(days=2)
            },
            employer=self.test_employer)       

        #updating delta and delay
        url_update_delta_delay = reverse_lazy('api:me-employer')
        self.client.force_login(self.test_user_employer)

        payload = {
            'maximum_clockin_delta_minutes': 30,
            'maximum_clockout_delay_minutes': 30,
            'retroactive': True
        }

        response = self.client.put(
            url_update_delta_delay,
            data=payload,
            content_type="application/json")

        self.assertEquals(
            response.status_code,
            200,
            'It should return a success response')


        url = reverse_lazy('api:me-employer-get-shifts')


        response2 = self.client.get(url, content_type="application/json")
        response_json2 = response.json()
        print(self.test_shift_filled)
        count = Shift.objects.filter(
            maximum_clockin_delta_minutes=30,
            maximum_clockout_delay_minutes=30
        ).count()

        self.assertEquals(
            count,
            6,
            'It must be six shift with 30 delay and delta minutes (3 shifts in the start and 3 inside the function)')
Beispiel #40
0
 def get_success_url(self):
     return reverse_lazy('laboratory:objectview_list',
                         args=(self.lab,))
Beispiel #41
0
@author: luisza
'''

from django.contrib.auth import views as auth_views
from django.conf.urls import url
from django.urls.base import reverse_lazy
from authentication.views import signup, OrgLoginView, PermissionDeniedView,\
    FeedbackView

urlpatterns = [

    url(r'^signup$', signup, name='signup'),
    url(r'^accounts/login/$', OrgLoginView.as_view(),
        {'template_name': 'registration/login.html'}, name='login'),
    url(r'^accounts/logout/$', auth_views.logout, {
        'next_page': reverse_lazy('index')},
        name='logout'),

    url(r'^permission_denied$', PermissionDeniedView.as_view(),
        name='permission_denied'),
    url(r'^feedback$', FeedbackView.as_view(), name='feedback'),

    # Password_reset
    url(r'^accounts/password_reset/$',
        auth_views.PasswordResetView.as_view(
            template_name='registration/password_reset_ss.html',
            email_template_name='registration/password_reset_email_ss.html',
            subject_template_name='registration/password_reset_subject_ss.txt',
            success_url='/accounts/password_reset_done/'),
        name='password_reset'),  # Set a sending e-mail on 'from_email'.
    url(r'^accounts/password_reset_done/$',