Python get current user

60 Python code examples are found related to " get current user". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: platform_windows.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
def get_current_user(self):
        """Returns the effective user name running this process.

        The effective user may not be the same as the initiator of the process if the process has escalated its
        privileges.

        @return: The name of the effective user running this process.
        @rtype: str
        """
        # As a little hack, we pretend anyone that has administrative privilege is running as
        # the local user 'Administrators' (note the 's').  This will result in us setting the configuration file
        # to be owned by 'Administrators' which is the right thing to do.
        if win32com.shell.shell.IsUserAnAdmin():
            return self.__local_administrators
        else:
            return win32api.GetUserNameEx(win32api.NameSamCompatible) 
Example 2
Source File: utils.py    From Kathara with GNU General Public License v3.0 6 votes vote down vote up
def get_current_user_info():
    def passwd_info():
        import pwd
        user_id = os.getuid()

        # It's root, take the real user from env variable
        if user_id == 0:
            # If it's a sudoer, take the SUDO_UID and use it as user_id variable
            # If not, keep using the user_id = 0
            real_user_id = os.environ.get("SUDO_UID")

            if real_user_id:
                user_id = int(real_user_id)

        return pwd.getpwuid(user_id)

    return exec_by_platform(passwd_info, lambda: None, passwd_info)


# Formatting Functions 
Example 3
Source File: tutorial004.py    From fastapi with MIT License 6 votes vote down vote up
def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = TokenData(username=username)
    except PyJWTError:
        raise credentials_exception
    user = get_user(fake_users_db, username=token_data.username)
    if user is None:
        raise credentials_exception
    return user 
Example 4
Source File: authentication.py    From django-gateone with GNU General Public License v3.0 6 votes vote down vote up
def get_current_user(self):
        """Tornado standard method--implemented our way."""
        expiration = self.settings.get('auth_timeout', "14d")
        # Need the expiration in days (which is a bit silly but whatever):
        expiration = (
            float(total_seconds(convert_to_timedelta(expiration)))
            / float(86400))
        user_json = self.get_secure_cookie(
            "gateone_user", max_age_days=expiration)
        if not user_json: return None
        #print user_json
        user = tornado.escape.json_decode(user_json)
        # Add the IP attribute
        #print user
        user['ip_address'] = self.request.remote_ip
        #print user
        return user 
Example 5
Source File: __init__.py    From ldapdomaindump with MIT License 6 votes vote down vote up
def getCurrentUserGroups(self, username, domainsid=None):
        self.connection.search(self.root, '(&(objectCategory=person)(objectClass=user)(sAMAccountName=%s))' % username, attributes=['cn', 'memberOf', 'primaryGroupId'])
        try:
            groups = self.connection.entries[0]['memberOf'].values
            if domainsid is not None:
                groups.append(self.getGroupDNfromID(domainsid, self.connection.entries[0]['primaryGroupId'].value))
            return groups
        except LDAPKeyError:
            #No groups, probably just member of the primary group
            if domainsid is not None:
                primarygroup = self.getGroupDNfromID(domainsid, self.connection.entries[0]['primaryGroupId'].value)
                return [primarygroup]
            else:
                return []
        except IndexError:
            #The username does not exist (might be a computer account)
            return []

    #Check if the user is part of the Domain Admins or Enterprise Admins group, or any of their subgroups 
Example 6
Source File: __init__.py    From CTFd with Apache License 2.0 6 votes vote down vote up
def get_current_user():
    if authed():
        user = Users.query.filter_by(id=session["id"]).first()

        # Check if the session is still valid
        session_hash = session.get("hash")
        if session_hash:
            if session_hash != hmac(user.password):
                logout_user()
                if request.content_type == "application/json":
                    error = 401
                else:
                    error = redirect(url_for("auth.login", next=request.full_path))
                abort(error)

        return user
    else:
        return None 
Example 7
Source File: custom_request_handler.py    From zoe with Apache License 2.0 6 votes vote down vote up
def get_current_user(self):
        """Get the user making the request from one of several possible locations."""
        auth_header = self.request.headers.get('Authorization')
        if self.get_secure_cookie('zoe'):  # cookie auth
            username = tornado.escape.xhtml_escape(self.get_secure_cookie('zoe'))
            user = self.api_endpoint.user_by_name(username)
        elif auth_header is not None and auth_header.startswith('Basic '):  # basic auth
            auth_decoded = base64.decodebytes(bytes(auth_header[6:], 'ascii')).decode('utf-8')
            username, password = auth_decoded.split(':', 2)
            user = BaseAuthenticator().full_auth(username, password)
        else:
            user = None

        if user is None:
            raise ZoeAuthException('Invalid username or password')
        if not user.enabled:
            raise ZoeAuthException('User has been disabled by the administrator')

        return user 
Example 8
Source File: BaseHandler.py    From sprutio with GNU General Public License v3.0 6 votes vote down vote up
def get_current_user(self):
        redis = self.redis.get(threading.currentThread())
        secure_cookie = self.get_secure_cookie("token")

        if secure_cookie is None:
            return None

        auth_key = bytes.decode(secure_cookie)
        params = redis.get(auth_key)

        if params is None:
            return None

        params = json.loads(params)
        redis.expire(auth_key, server.REDIS_DEFAULT_EXPIRE)

        return params.get("user", None) 
Example 9
Source File: external.py    From InfraBox-cli with Apache License 2.0 6 votes vote down vote up
def get_current_user_token():
    try:
        config = local_config.get_config()

        current_remote = config['current_remote']
        if not current_remote:
            raise Exception('Current remote not set')

        current_user_token = config['remotes'][current_remote]['current_user_token']
        if current_user_token is None or not current_user_token:
            raise Exception('Current user token not found')

        return current_user_token
    except:
        logger.error('Could not load current user token. Please, log in.')
        exit(1) 
Example 10
Source File: anchore_auth.py    From anchore with Apache License 2.0 6 votes vote down vote up
def get_current_user_info(anchore_auth):
    """
    Return the metadata about the current user as supplied by the anchore.io service. Includes permissions and tier access.

    :return: Dict of user metadata
    """

    user_url = anchore_auth['client_info_url'] + '/' + anchore_auth['username']
    user_timeout = 60
    retries = 3
    result = requests.get(user_url, headers={'x-anchore-password': anchore_auth['password']})
    if result.status_code == 200:
        user_data = json.loads(result.content)
    else:
        raise requests.HTTPError('Error response from service: {}'.format(result.status_code))
    return user_data 
Example 11
Source File: utils.py    From JSON2Mantle with MIT License 6 votes vote down vote up
def get_current_user_name():
    """Gets the current user's name from Address Book
    """
    # if fails to import AddressBook, returns empty name
    if mock_user_name:
        return mock_user_name
    address_book = ab.ABAddressBook.sharedAddressBook()
    try:
        me_unique = address_book.meUniqueId()
    except:
        me_unique = None
    people = address_book.people()
    all_contacts = [ab_person_to_dict(person) for person in people]

    user_name = ''
    for c in all_contacts:
        if c['uid'] == me_unique:
            try:
                user_name = '{} {}'.format(
                    c['firstphonetic'], c['lastphonetic'])
            except:
                user_name = ''

    return user_name 
Example 12
Source File: oauth_api.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def get_current_user(_scope=None):
  """Returns the User on whose behalf the request was made.

  Args:
    _scope: The custom OAuth scope or an iterable of scopes at least one of
      which is accepted.

  Returns:
    User

  Raises:
    OAuthRequestError: The request was not a valid OAuth request.
    OAuthServiceFailureError: An unknown error occurred.
  """

  _maybe_call_get_oauth_user(_scope)
  return _get_user_from_environ() 
Example 13
Source File: __init__.py    From truckersmp-cli with MIT License 6 votes vote down vote up
def get_current_steam_user():
    """
    Get the current AccountName with saved login credentials.

    If successful this returns the AccountName of the user with saved credentials.
    Otherwise this returns None.

    This function depends on the package "vdf".
    """
    for path in File.loginusers_paths:
        try:
            with open(path) as f:
                login_vdf = vdf.parse(f)

            for info in login_vdf["users"].values():
                remember = "RememberPassword" in info and info["RememberPassword"] == "1"
                recent_uc = "MostRecent" in info and info["MostRecent"] == "1"
                recent_lc = "mostrecent" in info and info["mostrecent"] == "1"
                if remember and (recent_lc or recent_uc) and "AccountName" in info:
                    return info["AccountName"]
        except Exception:
            pass
    return None 
Example 14
Source File: auth.py    From freight with Apache License 2.0 6 votes vote down vote up
def get_current_user():
    """
    Return the currently authenticated user based on their active session.
    Will return a dummy user if in development mode.
    """
    if getattr(request, "current_user", NOT_SET) is NOT_SET:
        if current_app.config.get("DEV"):
            from freight.testutils.fixtures import Fixtures

            request.current_user = User.query.filter(User.name == "Freight").first()
            if not request.current_user:
                request.current_user = Fixtures().create_user(name="Freight")

        elif session.get("uid") is None:
            request.current_user = None
        else:
            request.current_user = User.query.get(session["uid"])
            if request.current_user is None:
                del session["uid"]
    return request.current_user 
Example 15
Source File: deps.py    From full-stack-fastapi-postgresql with MIT License 6 votes vote down vote up
def get_current_user(
    db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)
) -> models.User:
    try:
        payload = jwt.decode(
            token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
        )
        token_data = schemas.TokenPayload(**payload)
    except (jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )
    user = crud.user.get(db, id=token_data.sub)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user 
Example 16
Source File: controller_client.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def get_current_user(self):
        """
        Get the logged in user.
        """
        url = "{}/users/me".format(self.base_url)
        return self.request("GET", url) 
Example 17
Source File: common.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def get_current_user():
        user_model = getattr(flask.g, "token", None)
        user_model = getattr(user_model, "user", None)
        if not user_model:
            LOG.warning("Cannot find authenticated user model")
            raise exceptions.Forbidden

        return user_model 
Example 18
Source File: users.py    From smartsheet-python-sdk with Apache License 2.0 5 votes vote down vote up
def get_current_user(self, include=None):
        """Get the currently authenticated User.
        Returns:
            UserProfile
        """
        _op = fresh_operation('get_current_user')
        _op['method'] = 'GET'
        _op['path'] = '/users/me'
        _op['query_params']['include'] = include

        expected = 'UserProfile'
        prepped_request = self._base.prepare_request(_op)
        response = self._base.request(prepped_request, expected, _op)

        return response 
Example 19
Source File: models.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_current_user_orders(cls):
        if current_user.is_authenticated:
            orders = (
                cls.query.filter_by(user_id=current_user.id)
                .order_by(Order.id.desc())
                .all()
            )
        else:
            orders = []
        return orders 
Example 20
Source File: api.py    From hepdata with GNU General Public License v2.0 5 votes vote down vote up
def get_records_subscribed_by_current_user():
    subscriptions = Subscribers.query.filter(Subscribers.subscribers.contains(current_user)).all()
    if subscriptions:
        records = [get_record_contents(x.publication_recid) for x in subscriptions]
        return list(filter(partial(is_not, None), records))

    else:
        return [] 
Example 21
Source File: current_user.py    From sal with Apache License 2.0 5 votes vote down vote up
def get_current_user():
    try:
        return _user.value
    except Exception:
        return None 
Example 22
Source File: persons_service.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_current_user_raw():
    """
    Return person from its auth token (the one that does the request) as an
    active record.
    """
    return get_person_by_email_raw(get_jwt_identity()) 
Example 23
Source File: web.py    From teleport with Apache License 2.0 5 votes vote down vote up
def get_current_user(self):
        """Override to determine the current user from, e.g., a cookie.

        This method may not be a coroutine.
        """
        return None 
Example 24
Source File: site.py    From karura with Apache License 2.0 5 votes vote down vote up
def get_current_user(self):
        user = self.get_secure_cookie(self.COOKIE_NAME)
        if user:
            user = tornado.escape.xhtml_escape(user)
        return user 
Example 25
Source File: handlers.py    From doufen with MIT License 5 votes vote down vote up
def get_current_user(self):
        """
        获取当前用户,没有则返回None
        """
        if not hasattr(self, '_current_user'):
            try:
                self._current_user = db.Account.get_default().user
            except (db.Account.DoesNotExist, db.User.DoesNotExist):
                self._current_user = None

        return self._current_user 
Example 26
Source File: auth_helper.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
def get_current_user(request):
        # FIXME(jd) should have domain but should not break existing :(
        user_id = request.headers.get("X-User-Id", "")
        project_id = request.headers.get("X-Project-Id", "")
        return user_id + ":" + project_id 
Example 27
Source File: users.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
def getCurrentUser(self):
        infoMsg = "fetching current user"
        logger.info(infoMsg)

        query = queries[Backend.getIdentifiedDbms()].current_user.query

        if not kb.data.currentUser:
            kb.data.currentUser = unArrayizeValue(inject.getValue(query))

        return kb.data.currentUser 
Example 28
Source File: auth.py    From zeus with Apache License 2.0 5 votes vote down vote up
def get_current_user(fetch=True) -> Optional[User]:
    rv = getattr(g, "current_user", None)
    if not rv and fetch:
        rv = get_user_from_request()
        g.current_user = rv
        with sentry_sdk.configure_scope() as scope:
            scope.user = {"id": str(rv.id), "email": rv.email} if rv else None
    return rv 
Example 29
Source File: base.py    From mltshp with Mozilla Public License 2.0 5 votes vote down vote up
def get_current_user_object(self):
        """
        Return current user as an object rather than light hash we store
        in cookie.
        """
        current_user = self.get_current_user()
        if not current_user:
            return None
        return models.User.get("id = %s", current_user['id']) 
Example 30
Source File: obp.py    From Hello-OBP-DirectLogin-Python with Apache License 2.0 5 votes vote down vote up
def getCurrentUser():
    # Prepare headers
    response = requests.get(u"{0}/obp/{1}/users/current".format(BASE_URL, API_VERSION), headers=mergeHeaders(DL_TOKEN, CONTENT_JSON))
    return response.json()

# Create an user 
Example 31
Source File: pkb.py    From PerfKitBenchmarker with Apache License 2.0 5 votes vote down vote up
def GetCurrentUser():
  """Get the current user name.

  On some systems the current user information may be unavailable. In these
  cases we just need a string to tag the created resources with. It should
  not be a fatal error.

  Returns:
    User name OR default string if user name not available.
  """
  try:
    return getpass.getuser()
  except KeyError:
    return 'user_unknown' 
Example 32
Source File: SecurityService.py    From tm1py with MIT License 5 votes vote down vote up
def get_current_user(self, **kwargs) -> User:
        """ Get user and group assignments of this session

        :return: instance of TM1py.User
        """
        url = "/api/v1/ActiveUser?$select=Name,FriendlyName,Password,Type,Enabled&$expand=Groups"
        response = self._rest.GET(url, **kwargs)
        return User.from_dict(response.json()) 
Example 33
Source File: utils.py    From Kathara with GNU General Public License v3.0 5 votes vote down vote up
def get_current_user_home():
    def passwd_home():
        user_info = get_current_user_info()
        return user_info.pw_dir

    def default_home():
        return os.path.expanduser('~')

    return exec_by_platform(passwd_home, default_home, default_home) 
Example 34
Source File: tutorial005.py    From fastapi with MIT License 5 votes vote down vote up
def get_current_active_user(
    current_user: User = Security(get_current_user, scopes=["me"])
):
    if current_user.disabled:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user 
Example 35
Source File: client.py    From confluence-python-lib with MIT License 5 votes vote down vote up
def get_current_user(self):  # type: () -> User
        """
        Returns the user object for the current logged in user.

        :return: A full user object.
        """
        return self._get_single_result(User, 'user/current', {}, None) 
Example 36
Source File: __init__.py    From splitwise with MIT License 5 votes vote down vote up
def getCurrentUser(self):
        """ Gets the current authorized user's data

        Returns:
            :obj:`splitwise.user.CurrentUser`: CurrentUser object containing user data
        """
        content = self.__makeRequest(Splitwise.GET_CURRENT_USER_URL)
        content = json.loads(content)
        return CurrentUser(content["user"]) 
Example 37
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def get_current_user_recent_ips():
    if authed():
        return get_user_recent_ips(user_id=session["id"])
    else:
        return None 
Example 38
Source File: account.py    From Flask-Boost with MIT License 5 votes vote down vote up
def get_current_user():
    """Get current user."""
    if not 'user_id' in session:
        return None
    user = User.query.filter(User.id == session['user_id']).first()
    if not user:
        signout_user()
        return None
    return user 
Example 39
Source File: tornado.py    From skein with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_current_user_simple(self):
        """Authenticate the current user using simple auth.

        Returns
        -------
        user : str
            The current user name.
        """
        user = self.get_argument("user.name", "")
        if not user:
            self._raise_auth_required()
        return user 
Example 40
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def get_current_user_attrs():
    if authed():
        return get_user_attrs(user_id=session["id"])
    else:
        return None 
Example 41
Source File: tornado.py    From skein with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_current_user(self):
        """An implementation of ``get_current_user`` using kerberos.

        Calls out to ``get_current_user_kerberos``, override if you want to
        support multiple authentication methods.
        """
        return self.get_current_user_kerberos() 
Example 42
Source File: utils.py    From NordVPN-NetworkManager with GNU General Public License v3.0 5 votes vote down vote up
def get_current_user():
    username = os.getenv("SUDO_USER")
    if not username:
        username = str(getpass.getuser())

    return username 
Example 43
Source File: persons_service.py    From zou with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_current_user():
    """
    Return person from its auth token (the one that does the request) as a
    dictionary.
    """
    return get_person_by_email(get_jwt_identity()) 
Example 44
Source File: __init__.py    From CTFd with Apache License 2.0 5 votes vote down vote up
def get_current_user_type(fallback=None):
    if authed():
        user = get_current_user_attrs()
        return user.type
    else:
        return fallback 
Example 45
Source File: _winconsole.py    From vistir with ISC License 5 votes vote down vote up
def get_current_user():
    fns = (_get_sid_from_registry, _get_sid_with_powershell)
    for fn in fns:
        result = fn()
        if result:
            return result
    return None 
Example 46
Source File: app_with_local_proxy.py    From web_develop with GNU General Public License v3.0 5 votes vote down vote up
def get_current_user():
    top = _user_stack.top
    if top is None:
        raise RuntimeError()
    return top 
Example 47
Source File: HubRestApi.py    From hub-rest-api-python with Apache License 2.0 5 votes vote down vote up
def get_current_user(self):
        url = self.config['baseurl'] + "/api/current-user"
        headers = {'Accept': 'application/vnd.blackducksoftware.user-4+json'}
        response = self.execute_get(url, custom_headers=headers)
        return response.json() 
Example 48
Source File: base.py    From magpie with MIT License 5 votes vote down vote up
def get_current_user(self):
        if self.settings.username is None and self.settings.pwdhash is None \
        or self.settings.username == '' and self.settings.pwdhash == '':
            return True

        return self.get_cookie('session', '') == self.settings.session 
Example 49
Source File: utils.py    From flask-jwt-extended with MIT License 5 votes vote down vote up
def get_current_user():
    """
    In a protected endpoint, this will return the user object for the JWT that
    is accessing this endpoint. This is only present if the
    :meth:`~flask_jwt_extended.JWTManager.user_loader_callback_loader` is
    being used. If the user loader callback is not being used, this will
    return `None`.
    """
    return getattr(ctx_stack.top, 'jwt_user', None) 
Example 50
Source File: handlers.py    From Computable with MIT License 5 votes vote down vote up
def get_current_user(self):
        user_id = self.get_secure_cookie(self.cookie_name)
        # For now the user_id should not return empty, but it could eventually
        if user_id == '':
            user_id = 'anonymous'
        if user_id is None:
            # prevent extra Invalid cookie sig warnings:
            self.clear_login_cookie()
            if not self.login_available:
                user_id = 'anonymous'
        return user_id 
Example 51
Source File: utils.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_enterprise_id_for_current_request_user_from_jwt():
    request = crum.get_current_request()
    decoded_jwt = get_decoded_jwt(request)
    if decoded_jwt:
        roles_claim = decoded_jwt.get('roles', [])
        for role_data in roles_claim:
            role_in_jwt, __, context_in_jwt = role_data.partition(':')
            if role_in_jwt == SYSTEM_ENTERPRISE_LEARNER_ROLE and context_in_jwt:
                return context_in_jwt

    return None 
Example 52
Source File: web.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def get_current_user(self) -> Any:
        """Override to determine the current user from, e.g., a cookie.

        This method may not be a coroutine.
        """
        return None 
Example 53
Source File: windows.py    From cloudbase-init with Apache License 2.0 5 votes vote down vote up
def get_current_user(self):
        """Get the user account name from the underlying instance."""
        buf_len = wintypes.ULONG(512)
        buf = ctypes.create_unicode_buffer(512)

        ret_val = secur32.GetUserNameExW(
            self.EXTENDED_NAME_FORMAT_SAM_COMPATIBLE,
            buf, ctypes.byref(buf_len))
        if not ret_val:
            raise exception.WindowsCloudbaseInitException(
                "GetUserNameExW failed: %r")

        return buf.value.split("\\") 
Example 54
Source File: session.py    From okcupyd with MIT License 5 votes vote down vote up
def get_current_user_profile(self):
        """Get the `okcupyd.profile.Profile` associated with the supplied
        username.

        :param username: The username of the profile to retrieve.
        """
        return self.get_profile(self.log_in_name) 
Example 55
Source File: client.py    From python-quickbooks with MIT License 5 votes vote down vote up
def get_current_user(self):
        """Get data from the current user endpoint"""
        url = self.current_user_url
        result = self.get(url)
        return result 
Example 56
Source File: server.py    From lpmc-site with MIT License 5 votes vote down vote up
def get_current_user(self):
		github_id = self.get_secure_cookie('github_id')
		if github_id is not None:
			return {
				'github_id': int(github_id),
				'is_mentor': int(self.get_secure_cookie('is_mentor')),
				'username': self.get_secure_cookie('username'),
				'avatar_url': self.get_secure_cookie('avatar_url'),
			} 
Example 57
Source File: app.py    From Flask-P2P with MIT License 5 votes vote down vote up
def get_current_user(self):
        if request.stream_id and self.users_by_stream[request.stream_id]:
            return self.users_by_stream[request.stream_id]

        return None