def authorize(request): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES) flow.redirect_uri = '{0}/MyResources/oauth2callback'.format( '{scheme}://{host}'.format(host=request.get_host(), scheme=request.META.get('HTTP_X_FORWARDED_PROTO', 'http'))) authorization_url, state = flow.authorization_url( # Enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Enable incremental authorization. Recommended as a best practice. include_granted_scopes='true') # Store the state so the callback can verify the auth server response. try: session_state = Session.objects.get(session_key='state') session_state.session_data = state session_state.save() except Exception: session_state = Session(session_key='state', session_data=state, expire_date=zone.replace(year=2025)) session_state.save() session['state'] = state return redirect(authorization_url)
def save(self, must_create=False,schema = None): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ if schema == None: # add schema import inspect fx = inspect.stack() error_detail = "" for x in fx: error_detail += "\n\t {0}, line {1}".format(fx[1], fx[2]) raise ( Exception( "can not call ''{1}'' without schema in '{0}'.\nDetail:\n{2}".format( __file__, "db.save", error_detail ))) obj = Session( session_key=self._get_or_create_session_key(), session_data=self.encode(self._get_session(no_load=must_create)), expire_date=self.get_expiry_date() ) using = router.db_for_write(Session, instance=obj) try: with transaction.atomic(using=using): obj.save(force_insert=must_create, using=using, schema = schema) except IntegrityError: if must_create: raise CreateError raise
def save_session(self, app, session, response): try: domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) httponly = self.get_cookie_secure(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) response.set_cookie(app.session_cookie_name, session['key'], expires=expires, httponly=httponly, domain=domain, path=path, secure=secure) try: obj = DjangoSession.objects.get(session_key=session['key']) except DjangoSession.DoesNotExist: obj = DjangoSession(session_key=session['key']) obj.session_data = pickle.dumps(dict(session)) obj.expire_date = expires or (datetime.now() + timedelta(days=30)) obj.save() finally: close_old_connections()
def save(self, must_create=False, schema=None): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ if schema == None: # add schema import inspect fx = inspect.stack() error_detail = "" for x in fx: error_detail += "\n\t {0}, line {1}".format(fx[1], fx[2]) raise (Exception( "can not call ''{1}'' without schema in '{0}'.\nDetail:\n{2}". format(__file__, "db.save", error_detail))) obj = Session(session_key=self._get_or_create_session_key(), session_data=self.encode( self._get_session(no_load=must_create)), expire_date=self.get_expiry_date()) using = router.db_for_write(Session, instance=obj) try: with transaction.atomic(using=using): obj.save(force_insert=must_create, using=using, schema=schema) except IntegrityError: if must_create: raise CreateError raise
def save(self, must_create=False): obj = Session(session_key=self._get_or_create_session_key(), session_data=self.encode( self._get_session(no_load=must_create)), expire_date=self.get_expiry_date()) using = router.db_for_write(Session, instance=obj) sid = transaction.savepoint(using=using) try: obj.save(force_insert=must_create, using=using) except IntegrityError: if must_create: transaction.savepoint_rollback(sid, using=using) raise CreateError raise data = self.encode(self._get_session(no_load=must_create)) formated_cookie = pickle.loads( base64.decodestring(data).split(":", 1)[1]) for k in formated_cookie: if type(formated_cookie[k]) is long: formated_cookie[k] = int(formated_cookie[k]) formated_cookie = json.dumps(formated_cookie) if redis.VERSION[0] >= 2: self.server.setex( self.get_real_stored_key(self._get_or_create_session_key()), self.get_expiry_age(), formated_cookie) else: self.server.set( self.get_real_stored_key(self._get_or_create_session_key()), formated_cookie) self.server.expire( self.get_real_stored_key(self._get_or_create_session_key()), self.get_expiry_age())
def test_configauth_delete_sessions(self): session = Session( session_key="session_key", expire_date=datetime.utcnow() + timedelta(days=1), ) session.save() call_command("configauth", rbac_url="") self.assertFalse(Session.objects.all().exists())
def save_session(self, app, session, response): try: obj = DjangoSession.objects.get(session_key=session['key']) except DjangoSession.DoesNotExist: obj = DjangoSession(session_key=session['key']) obj.session_data = json.dumps(dict(session, fix_imports=True)) obj.expire_date = get_datetime_now() + timedelta(days=365) obj.save() close_old_connections()
def test_session_backend(self): from django.contrib.sessions.backends.db import SessionStore from django.contrib.sessions.models import Session from pymongo.objectid import ObjectId Session.objects.all().delete() session = Session(session_key=str(ObjectId())) session.save() self.assertEqual(Session.objects.count(), 1) session.save() self.assertEqual(Session.objects.count(), 1) session.expire_date = datetime.datetime.now() self.assertEqual(Session.objects.count(), 1)
def testRemoveExpiredUsers(self): # Users wihout usable passwords who don't have a current session record should be removed. u1 = User.objects.create_user(username_from_session("dummy"), "") u2 = User.objects.create_user("dummy2", "") s = Session(session_key="dummy", session_data="", expire_date=datetime.datetime.now() + datetime.timedelta(1)) s.save() c = remove_expired_users.Command() c.handle() users = User.objects.all() self.assertEqual(1, len(users)) self.assertEqual(u1, users[0])
def testRemoveExpiredUsers(self): # Users wihout usable passwords who don't have a current session record should be removed. u1 = User.objects.create_user(username_from_session('dummy'), '') u2 = User.objects.create_user('dummy2', '') s = Session( session_key='dummy', session_data='', expire_date=datetime.datetime.now() + datetime.timedelta(1) ) s.save() c = remove_expired_users.Command() c.handle() users = User.objects.all() self.assertEqual(1, len(users)) self.assertEqual(u1, users[0])
def storetosessiontable(credentials): cred_dict = {'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes} try: session_ = Session.objects.get(session_key='credentials') session_.session_data = cred_dict session.expire_date = zone.replace(year=2025) session_.save() except Exception: session_ = Session(session_data=cred_dict, expire_date=zone.replace(year=2025), session_key='credentials') session_.save()
def do_login(login,moi_password,username): try: user=User.objects.get(username=username) except User.DoesNotExist: return None salt="salt" hasher=PBKDF2PasswordHasher() hashed_pass=make_password(moi_password,salt,hasher) if user.password==hashed_pass: session=Session() session.key=get_secret_key() session.user=user session.expires=datetime.now()+timedelta(days=5) session.expire_date=datetime.now()+timedelta(days=5) session.save() else: return None return session.key
def change_server_time(time): if SimulationTime.session is None: #Create a new session s = SessionStore(session_key='') s.save() old_s = Session.objects.get(session_key=s.session_key) #Copy it to a column with an id fixed new_session = Session(session_key=settings.SESSION_ID_SIMU, session_data=old_s.session_data, expire_date=old_s.expire_date) new_session.save() #Change the current date session_dictionary = SessionStore(session_key=settings.SESSION_ID_SIMU) SimulationTime.session = session_dictionary SimulationTime.session['current_date'] = time SimulationTime.session.save()
def save(self, must_create=False): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ obj = Session(session_key=self._get_or_create_session_key(), session_data=self.encode( self._get_session(no_load=must_create)), expire_date=self.get_expiry_date()) using = router.db_for_write(Session, instance=obj) try: with transaction.atomic(using=using): obj.save(force_insert=must_create, using=using) except IntegrityError: if must_create: raise CreateError raise
def save(self, must_create=False): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ obj = Session(session_key=self.session_key, session_data=self.encode( self._get_session(no_load=must_create)), expire_date=self.get_expiry_date()) sid = transaction.savepoint() try: obj.save(force_insert=must_create) except IntegrityError: if must_create: transaction.savepoint_rollback(sid) raise CreateError raise
def save(self, must_create=False): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ obj = Session( session_key=self._get_or_create_session_key(), session_data=self.encode(self._get_session(no_load=must_create)), expire_date=self.get_expiry_date() ) using = router.db_for_write(Session, instance=obj) try: with transaction.atomic(using=using): obj.save(force_insert=must_create, using=using) except IntegrityError: if must_create: raise CreateError raise
def save(self, must_create=False): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ obj = Session( session_key = self.session_key, session_data = self.encode(self._get_session(no_load=must_create)), expire_date = self.get_expiry_date() ) sid = transaction.savepoint() try: obj.save(force_insert=must_create) except IntegrityError: if must_create: transaction.savepoint_rollback(sid) raise CreateError raise
def _updateSessionExpiryDate(session: Session): """Used to update the given session's expiry date. If there are less than 30 days for the session to expire, this function will add another 30 days to the session's expiry date. :param session: The session whose expiry date is to be checked. :type session: Session. """ # Calculate the difference between the current time and the # expiry date of the session key. difference: timedelta = session.expire_date - timezone.now() # Add another 30 days if the number of days before the # expiry of the session is less than 30. if abs(difference.days) < 30: session.expire_date += timedelta(days=30) # Save this information. session.save()
def save(self, must_create=False): obj = Session( session_key=self._get_or_create_session_key(), session_data=self.encode(self._get_session(no_load=must_create)), expire_date=self.get_expiry_date() ) using = router.db_for_write(Session, instance=obj) sid = transaction.savepoint(using=using) try: obj.save(force_insert=must_create, using=using) except IntegrityError: if must_create: transaction.savepoint_rollback(sid, using=using) raise CreateError raise data = self.encode(self._get_session(no_load=must_create)) formated_cookie = pickle.loads(base64.decodestring(data).split(":",1)[1]) for k in formated_cookie: if type(formated_cookie[k]) is long: formated_cookie[k] = int(formated_cookie[k]) formated_cookie = json.dumps(formated_cookie) if redis.VERSION[0] >= 2: self.server.setex( self.get_real_stored_key(self._get_or_create_session_key()), self.get_expiry_age(), formated_cookie ) else: self.server.set( self.get_real_stored_key(self._get_or_create_session_key()), formated_cookie ) self.server.expire( self.get_real_stored_key(self._get_or_create_session_key()), self.get_expiry_age() )
def get_or_set_action_info( session: Session, payloadclass, action_info: Optional[ActionPayload] = None, initial_values: Optional[Dict] = None, ) -> Optional[ActionPayload]: """Get (from the session object) or create an ActionPayload object. First check if one is given. If not, check in the session. If there is no object in the session, create a new one with the initial values. :param session: HTTP session object :param payloadclass: class to use to create a action_info object. :param action_info: ActionInfo object just in case it is present. :param initial_values: A dictionary to initialize the class if required :return: Existing,newly created ActionInfo object, or None """ if action_info: # Already exists, no need to create a new one return action_info action_info = session.get(action_session_dictionary) if action_info: return payloadclass(action_info) if not initial_values: # Nothing found in the session and no initial values given. return None # Create the object with the given class action_info = payloadclass(initial_values) session[action_session_dictionary] = action_info.get_store() session.save() return payloadclass(initial_values)
def save(self, must_create=False): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ #print "save has been called" if self.session_key is None: return self.create() obj = Session(session_key=self._get_or_create_session_key(), session_data=self.encode( self._get_session(no_load=must_create)), expire_date=self.get_expiry_date()) using = router.db_for_write(Session, instance=obj) sid = transaction.savepoint(using=using) try: obj.save(force_insert=must_create, using=using) except IntegrityError: if must_create: transaction.savepoint_rollback(sid, using=using) raise CreateError raise
def test_demo(self): s = Session() from datetime import datetime s.expire_date = datetime.now() s.save() s.delete()
def test_configauth_delete_sessions(self): session = Session(session_key='session_key', expire_date=datetime.utcnow() + timedelta(days=1)) session.save() call_command('configauth', candid_url='') self.assertFalse(Session.objects.all().exists())
def add_error_message(session: Session, message): messages = session.get(ERROR_MESSAGES_SESSION_KEY, []) messages += [message] session[ERROR_MESSAGES_SESSION_KEY] = messages session.save()
def add_success_message(session: Session, message): messages = session.get(SUCCESS_MESSAGES_SESSION_KEY, []) messages += [message] session[SUCCESS_MESSAGES_SESSION_KEY] = messages session.save()