Пример #1
0
 def get(self):
   key = self.config['webapp2_extras.sessions']['secret_key']
   redirect_url = str(self.request.get('redirect'))
   if self.me is not None:
     token = str(self.request.get('token'))
     xsrfutil.validate_token(key, token, self.me.user_id(), action_id=redirect_url)
     self.auth.unset_session()
   self.redirect(redirect_url)
Пример #2
0
 def get(self):
   key = self.config['webapp2_extras.sessions']['secret_key']
   redirect_url = str(self.request.get('redirect'))
   if self.me is not None:
     token = str(self.request.get('token'))
     xsrfutil.validate_token(key, token, self.me.user_id(), action_id=redirect_url)
     self.auth.unset_session()
   # Avoid data: URI redirects.
   if not redirect_url.startswith(('http://', 'https://', '/')):
     self.abort(404)
     return
   self.redirect(redirect_url)
Пример #3
0
    def exchange_for_user_credential(self, query_args, user=None):
        """Exchange params from Gloebit authorization for Gloebit credential.

        Accessing the Gloebit authorization URL results in a redirection (after
        the user authorizes access) to the merchant's redirect URI, with a code
        provided as a query-arg.  This function provides the second step of the
        authorization by exchanging the code for a Gloebit credential.

        Args:
          query_arg: dictionary, Query arguments from redirection request.

        Returns:
          An Oauth2Credentials object for authorizing Gloebit requests.
        """
        self.ready_flow (None, user)

        # Need better checks here.  If we have a secret key and a user, then
        # we need to expect a state and throw an error if we did not get one.
        #
        if user and 'state' in query_args:
            if not xsrfutil.validate_token(self.secret_key,
                                           query_args['state'],
                                           user):
                raise CrossSiteError

        http = httplib2.Http()
        if not CHECK_SSL_CERT:
            http.disable_ssl_certificate_validation = True
        credential = self.flow.step2_exchange(query_args['code'], http=http)

        return credential
Пример #4
0
def auth_return(request):

  if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'],
                                 request.user):
    return  HttpResponseBadRequest()
  credential = FLOW.step2_exchange(request.REQUEST)
  storage = Storage(CredentialsModel, 'id_user', request.user, 'credential')
  storage.delete()
  storage = Storage(CredentialsModel, 'id_user', request.user, 'credential')
  storage.put(credential)

  userP = userProfile.objects.get(user=request.user)
  if userP.id_drive_folder is None:
  	try:
		storage = Storage(CredentialsModel, 'id_user', request.user, 'credential')
		credential = storage.get()
		http = httplib2.Http()
		http = credential.authorize(http)
		drive_service = build('drive', 'v2', http=http, developerKey="hbP6_4UJIKe-m74yLd8tQDfT")

		body = {
          'title': 'Soft System Manager',
          'mimeType': "application/vnd.google-apps.folder"
        }
		folder = drive_service.files().insert(body = body).execute()
		userP.id_drive_folder = folder.get('id')
		userP.save()
	except:
		return redirect('vista_logout')

  return HttpResponseRedirect("/principal")
Пример #5
0
def oauth2callback(request):
    t = request.session.get(TEMP_USER_SESSION_ID)
    if not t:
        return redirect_to_login_page()

    state = request.REQUEST['state']
    if not xsrfutil.validate_token(settings.SECRET_KEY, state, t):
        return HttpResponseBadRequest()

    try:
        credential = _get_flow(request).step2_exchange(request.REQUEST)
    except FlowExchangeError:
        return HttpResponseRedirect(reverse(login))

    if credential.invalid:
        return HttpResponseRedirect(reverse(login))

    http = httplib2.Http()
    http = credential.authorize(http)
    _h, c = http.request('https://www.googleapis.com/oauth2/v1/userinfo')
    data = simplejson.loads(c)

    user, _created = get_model().objects.get_or_create(
        email=data['email'],
        defaults=dict(
            name=data.get('name') or data['email'].split('@')[0],
        )
    )
    user.name = data.get('given_name') or user.name
    user.surname = data.get('family_name', '')

    try:
        user.save()
    except ValidationError, e:
        return redirect_to_login_page(e.messages[0])
  def _IsXsrfTokenWellFormedAndNotExpired(user_email, action_id, xsrf_token):
    """Determine if the submitted xsrf token is well-formed and has not expired.

    By well-formed, we mean if the the submitted xsrf token can be decoded and
    will match the generated xsrf token using the same criteria (i.e. check
    forgery).

    The xsrfutil validate_token() method enforces a default token timeout of
    1 hour (60 seconds).

    Args:
      user_email: String email address of the form [email protected].
      action_id: String identifier of the action for which authorization
                 is requested.
      xsrf_token: A string of the xsrf token.

    Returns:
      A boolean, True if the token is well-formed and has not expired.
          Otherwise, False.
    """
    is_xsrf_token_well_formed_and_not_expired = xsrfutil.validate_token(
        key=appengine.xsrf_secret_key(), token=xsrf_token,
        user_id=user_email, action_id=action_id)
    _LOG.debug('Is xsrf token well-formed and not expired for %s: %s',
               user_email, is_xsrf_token_well_formed_and_not_expired)
    return is_xsrf_token_well_formed_and_not_expired
Пример #7
0
def auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'], request.user):
        return  HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.REQUEST)
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("/")
Пример #8
0
def oauth_callback(request):
    if not xsrfutil.validate_token(
            settings.SECRET_KEY, request.REQUEST['state'], request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.REQUEST)
    http = httplib2.Http()
    http = credential.authorize(http)

    user_info_service = build(
        serviceName='oauth2', version='v2',
        http=http)

    user_info = user_info_service.userinfo().get().execute()
    try:
        user = User.objects.get(username=user_info['id'])
    except ObjectDoesNotExist:
        user = None

    if not user:
        user = User.objects.create_user(
            user_info['id'], user_info['email'], '')
        user.first_name = user_info['name']
        user.save()
        storage = Storage(CredentialsModel, 'id', user, 'credential')
        storage.put(credential)
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    if user is not None:
        login(request, user)
        return redirect('/')

    else:
        # Return an 'invalid login' error message.
        return render_to_response('gmail/thread.html', {
                                  'threads': 'Try again later some problem',
                                  })
Пример #9
0
def auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET.get('state')), request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.GET.get('code'))
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("/api/create")
Пример #10
0
def auth_return(request):
    
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'],
                                   request.user):
      return  HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.REQUEST)
    
    user_info = get_user_info(credential)
    google_email = user_info.get('email')
    firstName = user_info.get('given_name')
    lastName = user_info.get('family_name')
    
    emailEnding = google_email.split("@")[1]
    userName = "******"+google_email.split("@")[0]
    
    if User.objects.filter(username=userName):
        # Make sure that the e-mail is unique.
        user = User.objects.get(username=userName)
        #userInfo = UserInfo.objects.get(user=user)
    else:
        if 'alvaradoisd.net' in emailEnding:
            if 'student' in emailEnding:
                bTeacher = False
            else:
                bTeacher = True
            
            user = User.objects.create(
                username = userName,
                first_name = firstName,
                last_name = lastName,
                email = google_email,
                password = '******',
            )
            
            userInfo = UserInfo.objects.create(
                user = user,
                teacher = bTeacher,
                readOnly = False,
            )
        else:
            return HttpResponse('Please sign in with your Alvarado ISD account.')
    
    
    if user:
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        
    if UserInfo.objects.filter(user=user):
        userInfo = UserInfo.objects.get(user=user)
    else:
        userInfo = UserInfo.objects.create(
            user = user,
            teacher = bTeacher,
            readOnly = False,
        )
    
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect('/dashboard/')
Пример #11
0
def auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'], request.user):
        return  HttpResponseBadRequest()
    credential = settings.FLOW.step2_exchange(request.REQUEST)
    storage = Storage(Credential, 'id', request.user, 'credential')
    storage.put(credential)
    mail_box=MiliBox.objects.create(name="MiliBox", user=request.user)
    return HttpResponseRedirect("/")
Пример #12
0
def auth_return(request):
    ans = xsrfutil.validate_token(settings.SECRET_KEY, str(request.REQUEST['state']), request.user)
    if not ans:
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.REQUEST)
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect(reverse('contactos:registrar_recordatorio'))
Пример #13
0
    def test_token_too_old_explicit_current_time(self):
        token_time = 123456789
        curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS + 1

        key = user_id = None
        token = base64.b64encode(_to_bytes(str(token_time)))
        self.assertFalse(xsrfutil.validate_token(key, token, user_id,
                                                 current_time=curr_time))
Пример #14
0
def auth_return(request):
  if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'],
                                 request.user):
    return  HttpResponseBadRequest()
  credential = FLOW.step2_exchange(request.REQUEST)
  storage = Storage(Credentials, 'id', request.user, 'credential')
  storage.put(credential)
  # TODO this shouldn't be hardcoded
  return HttpResponseRedirect("/POSTman/index")
Пример #15
0
 def validate_token(self):
     """
         validates that the token is authentic
     """
     return xsrfutil.validate_token(
                settings.SECRET_KEY, 
                self.request.REQUEST['state'],
                self.request.user
            )
Пример #16
0
def oauth2callback(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'], request.user):
        return  HttpResponseBadRequest()

    credential = FLOW.step2_exchange(request.REQUEST)
    storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    #print(credential.to_json())
    return HttpResponseRedirect("/")
Пример #17
0
def OAuthReturn(request):
    master = f.get_youtube_master()
    if not xsrfutil.validate_token(settings.SECRET_KEY.encode('latin1'), request.REQUEST['state'].encode('latin1'),
                                   master):
        return HttpResponseBadRequest()
    credential = f.get_flow().step2_exchange(request.REQUEST)
    storage = Storage(CredentialsYoutubeModel, 'id', master, 'credential')
    storage.put(credential)
    return redirect('spamusic:index')
Пример #18
0
def auth_return(request):
  if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']),
                                 request.user):
    return HttpResponseBadRequest()
  FLOW = models.FlowModel.objects.get(id=request.user).flow
  credential = FLOW.step2_exchange(request.GET)
  storage = Storage(models.CredentialsModel, 'id', request.user, 'credential')
  storage.put(credential)
  return HttpResponseRedirect(reverse('app_home'))
Пример #19
0
    def obtain_credential(cls, request):

        if not xsrfutil.validate_token(settings.SECRET_KEY, request.GET['state'], request.user):
            return False

        credential = cls.FLOW.step2_exchange(request.GET)
        storage = Storage(CredentialsModel, 'id', request.user, 'credential')
        storage.put(credential)

        return True
Пример #20
0
def auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'], None):
        return  HttpResponseBadRequest()
    try:
        credentials = get_flow().step2_exchange(request.REQUEST)
        Storage().put(credentials)
        messages.success(request, u'Asociada cuenta de publicación')
    except Error:
        messages.error(request, u'Autorización no concedida')
    return HttpResponseRedirect(reverse("config_plugin"))
Пример #21
0
    def test_token_too_old_implicit_current_time(self):
        token_time = 123456789
        curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS + 1

        key = user_id = None
        token = base64.b64encode(_to_bytes(str(token_time)))
        with mock.patch('oauth2client.xsrfutil.time') as time:
            time.time = mock.MagicMock(name='time', return_value=curr_time)
            self.assertFalse(xsrfutil.validate_token(key, token, user_id))
            time.time.assert_called_once_with()
Пример #22
0
def auth_return(request):
    user = request.user
    if not xsrfutil.validate_token(
            settings.SECRET_KEY, str(request.GET['state']), user):
        return HttpResponseBadRequest()
    FLOW = FlowModel.objects.get(id=user).flow
    credential = FLOW.step2_exchange(request.GET)
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("/oauth2")
Пример #23
0
def oauth2callback(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']), request.user):
        return  HttpResponseBadRequest()

    credential = FLOW.step2_exchange(request.GET)
    storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    #print(credential.to_json())
    redirect_url = request.session['redirect_uri_after_step2']
    return HttpResponseRedirect(redirect_url)
Пример #24
0
def auth_required(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY,
                                   request.REQUEST['state'],
                                   request.user):
        return HttpResponseBadRequest('Who are you? Access Denied!')

    try:
        credential = FLOW.step2_exchange(request.REQUEST)
    except FlowExchangeError, e:
        return HttpResponseBadRequest('Access Denied:' + e.message)
Пример #25
0
def callback(request):
	"""Callback from Google OAuth2"""
	try:
		if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'], request.user):
			return HttpResponseBadRequest()
		credential = FLOW.step2_exchange(request.REQUEST)
		storage = Storage(GCal, 'id', request.user.service_provider, 'credential')
		storage.put(credential)
	except FlowExchangeError:
		return HttpResponseRedirect(reverse('myreservations_calendar'))
	return HttpResponseRedirect(reverse(edit))
Пример #26
0
def auth_return(request):
    print ("in authentication return")
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'],
                                   request.user):
        return  HttpResponseBadRequest()
    print ("before exchange the credential")
    credential = FLOW.step2_exchange(request.REQUEST)
    print ("After exchange credential")
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("/")
Пример #27
0
def auth_return(request):
    state = request.REQUEST['state']
    user = str(request.user)

    if not xsrfutil.validate_token(SECRET_KEY, str(state), user):
        return HttpResponseBadRequest()

    credential = FLOW.step2_exchange(request.REQUEST)
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect('/admin')
Пример #28
0
def auth_return(request):
    print "xxxxxxxxxxxxPSTATE " , request.REQUEST['state']
    print "xxxxxxxxxxxxU ", request.user
    print "xxxxxxxxxxxxS ", settings.SECRET_KEY
    print "xxxxxxxxxxxxV ", xsrfutil.validate_token(
            settings.SECRET_KEY, request.REQUEST['state'], request.user)
    print "xxxxxxxxxxxxG ", xsrfutil.generate_token(settings.SECRET_KEY,
                                                   request.user)


    if not xsrfutil.validate_token(
            settings.SECRET_KEY, str(request.REQUEST['state']), request.user):
        return HttpResponseBadRequest()


    credential = FLOW.step2_exchange(request.REQUEST)
    storage = Storage(CredentialsModel, 'id', request.user, 'credential')

    storage.put(credential)
    return HttpResponseRedirect("/")
Пример #29
0
def oauth2callback(request):
    if not xsrfutil.validate_token(
        settings.SECRET_KEY.encode("utf-8"),
        request.GET.get("state").encode("utf-8"),
        request.user.username.encode("utf-8"),
    ):
        return HttpResponse("Bad Request")
    credential = FLOW.step2_exchange(request.REQUEST)
    storage = Storage(CredentialsModel, "id", request.user, "credential")
    storage.put(credential)
    return redirect("/")
Пример #30
0
def auth_return(request):
  # use dummy_user
  user = dummy_user

  if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'],
                                user):
    return  http.HttpResponseBadRequest()
  credential = FLOW.step2_exchange(request.REQUEST)
  storage = Storage(gcal_models.CredentialsModel, 'id', user, 'credential')
  storage.put(credential)
  return http.HttpResponseRedirect('/')
Пример #31
0
    def test_success(self):
        token_time = 123456789
        # Make sure it isn't too old.
        curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS - 1

        key = object()
        user_id = object()
        action_id = object()
        token = base64.b64encode(_to_bytes(str(token_time)))
        with mock.patch('oauth2client.xsrfutil.generate_token',
                        return_value=token) as gen_tok:
            self.assertTrue(
                xsrfutil.validate_token(key,
                                        token,
                                        user_id,
                                        current_time=curr_time,
                                        action_id=action_id))
            gen_tok.assert_called_once_with(key,
                                            user_id,
                                            action_id=action_id,
                                            when=token_time)
Пример #32
0
    def _IsXsrfTokenWellFormedAndNotExpired(self, current_user, xsrf_token):
        """Determine if the submitted xsrf token is well-formed and has not expired.

    By well-formed, we mean if the the submitted xsrf token can be decoded and
    will match the generated xsrf token using the same criteria (i.e. check
    forgery).

    Args:
      current_user: Appengine user object of the current user.
      xsrf_token: A string of the xsrf token.

    Returns:
      A boolean, true if the token is well-formed and has not expired.
          Otherwise, false.
    """
        is_xsrf_token_well_formed_and_not_expired = xsrfutil.validate_token(
            appengine.xsrf_secret_key(), xsrf_token, current_user.user_id())
        _LOG.debug('Is xsrf token well-formed and not expired for %s: %s',
                   current_user.nickname(),
                   is_xsrf_token_well_formed_and_not_expired)
        return is_xsrf_token_well_formed_and_not_expired
Пример #33
0
def _parse_state_value(state, user):
    """Parse the value of the 'state' parameter.

  Parses the value and validates the XSRF token in the state parameter.

  Args:
    state: string, The value of the state parameter.
    user: google.appengine.api.users.User, The current user.

  Raises:
    InvalidXsrfTokenError: if the XSRF token is invalid.

  Returns:
    The redirect URI.
  """
    uri, token = state.rsplit(':', 1)
    if not xsrfutil.validate_token(
            xsrf_secret_key(), token, user.user_id(), action_id=uri):
        raise InvalidXsrfTokenError()

    return uri
Пример #34
0
def _ValidateToken(token, user):
  """Validates an XSRF token generated by GenerateXsrfToken."""
  return xsrfutil.validate_token(
      _GetSecretKey(), token, user_id=user.user_id(), action_id='')
Пример #35
0
def auth_return(request):
    if not xsrfutil.validate_token(
            settings.SECRET_KEY, str(request.REQUEST['state']), request.user):
        return HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.REQUEST)

    user_info = get_user_info(credential)
    google_email = user_info.get('email')
    firstName = user_info.get('given_name')
    lastName = user_info.get('family_name')
    google_id = user_info.get('id')
    googlePlus = user_info.get('link')
    language = user_info.get('locale')
    googleAvatar = user_info.get('picture')
    gender = user_info.get('gender')

    emailEnding = google_email.split("@")[1]
    userName = "******" + google_email.split("@")[0] + emailEnding[:1]

    if User.objects.filter(email=google_email):
        user = User.objects.get(email=google_email)
    else:
        #check for duplicate usernames and iterate to unique
        if User.objects.filter(username=userName):
            countUsernames = User.objects.filter(username=userName).count()
            userName = userName + str(countUsernames)
        user = User.objects.create(
            username=userName,
            first_name=firstName,
            last_name=lastName,
            email=google_email,
            password=userName + google_id[:5],
        )

    #Update the User model with changes in google
    if not user.first_name:
        user.first_name = firstName
        user.last_name = lastName
        user.save()

    #Check to see if a google account has been setup yet
    if not GoogleUserInfo.objects.filter(google_id=google_id):
        newGoogleUser = GoogleUserInfo.objects.create(
            user=user,
            google_id=google_id,
            googlePlus=googlePlus,
            language=language,
            googleAvatar=googleAvatar,
            gender=gender,
        )

    #check to see if user is logged in
    if user:
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)

    request.session['user_id'] = user.id
    request.session.set_expiry(604800)  #Time is in Seconds, this equals 7 days
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    storage.put(credential)

    return redirect(settings.LOGIN_SUCCESS)
Пример #36
0
 def _check_validation_token(self, user, token):
     return xsrfutil.validate_token(settings.SECRET_KEY, token, user)
    def testGenerateAndValidateToken(self):
        """Test generating and validating a token."""
        token = xsrfutil.generate_token(TEST_KEY,
                                        TEST_USER_ID_1,
                                        action_id=TEST_ACTION_ID_1,
                                        when=TEST_TIME)

        # Check that the token is considered valid when it should be.
        self.assertTrue(
            xsrfutil.validate_token(TEST_KEY,
                                    token,
                                    TEST_USER_ID_1,
                                    action_id=TEST_ACTION_ID_1,
                                    current_time=TEST_TIME))

        # Should still be valid 15 minutes later.
        later15mins = TEST_TIME + 15 * 60
        self.assertTrue(
            xsrfutil.validate_token(TEST_KEY,
                                    token,
                                    TEST_USER_ID_1,
                                    action_id=TEST_ACTION_ID_1,
                                    current_time=later15mins))

        # But not if beyond the timeout.
        later2hours = TEST_TIME + 2 * 60 * 60
        self.assertFalse(
            xsrfutil.validate_token(TEST_KEY,
                                    token,
                                    TEST_USER_ID_1,
                                    action_id=TEST_ACTION_ID_1,
                                    current_time=later2hours))

        # Or if the key is different.
        self.assertFalse(
            xsrfutil.validate_token('another key',
                                    token,
                                    TEST_USER_ID_1,
                                    action_id=TEST_ACTION_ID_1,
                                    current_time=later15mins))

        # Or the user ID....
        self.assertFalse(
            xsrfutil.validate_token(TEST_KEY,
                                    token,
                                    TEST_USER_ID_2,
                                    action_id=TEST_ACTION_ID_1,
                                    current_time=later15mins))

        # Or the action ID...
        self.assertFalse(
            xsrfutil.validate_token(TEST_KEY,
                                    token,
                                    TEST_USER_ID_1,
                                    action_id=TEST_ACTION_ID_2,
                                    current_time=later15mins))

        # Invalid when truncated
        self.assertFalse(
            xsrfutil.validate_token(TEST_KEY,
                                    token[:-1],
                                    TEST_USER_ID_1,
                                    action_id=TEST_ACTION_ID_1,
                                    current_time=later15mins))

        # Invalid with extra garbage
        self.assertFalse(
            xsrfutil.validate_token(TEST_KEY,
                                    token + b'x',
                                    TEST_USER_ID_1,
                                    action_id=TEST_ACTION_ID_1,
                                    current_time=later15mins))

        # Invalid with token of None
        self.assertFalse(
            xsrfutil.validate_token(TEST_KEY,
                                    None,
                                    TEST_USER_ID_1,
                                    action_id=TEST_ACTION_ID_1))
 def test_token_non_integer(self):
     key = user_id = None
     token = base64.b64encode(b'abc' + xsrfutil.DELIMITER + b'xyz')
     self.assertFalse(xsrfutil.validate_token(key, token, user_id))
 def test_token_not_valid_base64(self):
     key = user_id = None
     token = b'a'  # Bad padding
     self.assertFalse(xsrfutil.validate_token(key, token, user_id))
 def test_no_token(self):
     key = token = user_id = None
     self.assertFalse(xsrfutil.validate_token(key, token, user_id))
Пример #41
0
def auth_return(request):
    
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'],
                                   request.user):
      return  HttpResponseBadRequest()
    credential = FLOW.step2_exchange(request.REQUEST)

    user_info = get_user_info(credential)
    google_email = user_info.get('email')
    firstName = user_info.get('given_name')
    lastName = user_info.get('family_name')
    google_id = user_info.get('id')
    googlePlus = user_info.get('link')
    googleAvatar = user_info.get('picture')
        
    emailEnding = google_email.split("@")[1]
    userName = "******"+google_email.split("@")[0]
    
    bTeacher = True
    if 'alvaradoisd.net' in emailEnding and 'student' in emailEnding:
        bTeacher = False
    
    if User.objects.filter(username=userName):
        # Make sure that the e-mail is unique.
        user = User.objects.get(username=userName)
    elif User.objects.filter(email=google_email):
        user = User.objects.get(email=google_email)
    else:
        if 'alvaradoisd.net' in emailEnding or not ALLOW_ONLY_USERS:
            user = User.objects.create(
                username = userName,
                first_name = firstName,
                last_name = lastName,
                email = google_email,
                password = userName+google_id[:5],
            )
        else:
            return HttpResponse('Please sign in with a Alvarado ISD account.')
    
    if not ClassUser.objects.filter(user=user):
        userInfo = ClassUser.objects.create(
            user = user,
	    teacher = bTeacher,
        )
    else:
        userInfo = ClassUser.objects.get(user=user)
        userInfo.teacher = bTeacher
        userInfo.save()
    
    #Update the User model with changes in google
    user.first_name = firstName
    user.last_name = lastName
    user.save()

    #Check to see if a google account has been setup yet
    if not GoogleUserInfo.objects.filter(google_id=google_id):
        newGoogleUser = GoogleUserInfo.objects.create(
            user = user,
            google_id = google_id,
            googlePlus = googlePlus,
            googleAvatar = googleAvatar,
        )
            
    
    #check to see if user is logged in
    if user:
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        
    request.session['user_id'] = user.id
    request.session.set_expiry(604800)
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect(settings.LOGIN_SUCCESS)
Пример #42
0
def auth_return(request):
    if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'],
                                   request.user):
      return  HttpResponseBadRequest('oops')
    credential = FLOW.step2_exchange(request.REQUEST)


    user_info = get_user_info(credential)
    google_email = user_info.get('email')
    firstName = user_info.get('given_name')
    lastName = user_info.get('family_name')
    google_id = user_info.get('id')
    googlePlus = user_info.get('link')
    language = user_info.get('locale')
    googleAvatar = user_info.get('picture')
    gender = user_info.get('gender')
        
    emailEnding = google_email.split("@")[1]
    userName = "******"+google_email.split("@")[0]
    
    if User.objects.filter(username=userName):
        # Make sure that the e-mail is unique.
        user = User.objects.get(username=userName)
        #userInfo = UserInfo.objects.get(user=user)
    elif User.objects.filter(email=google_email):
        user = User.objects.get(email=google_email)
    else:
        if 'alvaradoisd.net' in emailEnding:
            if 'student' in emailEnding:
                bTeacher = False
            else:
                bTeacher = True
            
            user = User.objects.create(
                username = userName,
                first_name = firstName,
                last_name = lastName,
                email = google_email,
                password = '******',
            )
            
            userInfo = UserInfo.objects.create(
                user = user,
                teacher = bTeacher,
            )
	    
            ClassUser.objects.create(
                user = user,
                teacher = bTeacher,
            )
	    
        else:
            return HttpResponse('Please sign in with your Alvarado ISD account.')
	
    #Update the User model with changes in google
    if not user.first_name:
	user.first_name = firstName
	user.last_name = lastName
	user.save()

    #Check to see if a google account has been setup yet
    if not GoogleUserInfo.objects.filter(google_id=google_id):
        newGoogleUser = GoogleUserInfo.objects.create(
            user = user,
            google_id = google_id,
            googlePlus = googlePlus,
            language = language,
            googleAvatar = googleAvatar,
            gender = gender,
        )
            
    
    #check to see if user is logged in
    if user:
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)
        
    request.session['user_id'] = user.id
    request.session.set_expiry(604800)
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    storage.put(credential)
    
    
    '''
    orgUnit = getUsersOrgUnit(user_info.get('email'))
    if orgUnit:
	pass
	#put this into students userInfo
    '''
    
    #return HttpResponseRedirect(settings.LOGIN_SUCCESS)
    #return HttpResponse('<script>window.close();</script>')
    return redirect('/dashboard/')
Пример #43
0
def token_is_valid(request):
    return xsrfutil.validate_token(settings.SECRET_KEY,
                                   request.REQUEST['state'], '')