17.2.1.17. Token Functions

This package contains all top level token functions. It depends on the models, lib.user and lib.tokenclass (which depends on the tokenclass implementations like lib.tokens.hotptoken)

This is the middleware/glue between the HTTP API and the database.

The implementation is split across submodules (query, otp, attributes, lifecycle, auth, tokengroups, importexport, misc); every public name is re-exported here so from privacyidea.lib.token import X keeps working.

class privacyidea.lib.token.TokenExportResult(successful_tokens: list[dict], failed_tokens: list[str])[source]

Result of a bulk token export operation.

failed_tokens: list[str]
successful_tokens: list[dict]
class privacyidea.lib.token.TokenImportResult(successful_tokens: list[str], updated_tokens: list[str], failed_tokens: list[str | None])[source]
failed_tokens: list[str | None]
successful_tokens: list[str]
updated_tokens: list[str]
privacyidea.lib.token.add_tokeninfo(serial: str, info: str, value: Any = None, value_type: str | None = None, user: User | None = None) → int[source]

Sets a token info field in the database. The info is a dict for each token of key/value pairs.

Parameters:
  • serial (basestring) – The serial number of the token

  • info – The key of the info in the dict

  • value – The value of the info

  • value_type (basestring) – The type of the value. If set to “password” the value is stored encrypted

  • user (User object) – The owner of the tokens, that should be modified

Returns:

the number of modified tokens

Return type:

int

privacyidea.lib.token.assign_token(serial: str, user: User, pin: str | None = None, encrypt_pin: bool = False, error_message: str | None = None) → bool[source]

Assign token to a user. If the PIN is given, the PIN is reset.

Parameters:
  • serial (basestring) – The serial number of the token

  • user (User object) – The user, to whom the token should be assigned.

  • pin (basestring) – The PIN for the newly assigned token.

  • encrypt_pin (bool) – Whether the PIN should be stored in an encrypted way

  • error_message (basestring) – The error message, that is displayed in case the token is already assigned

privacyidea.lib.token.assign_tokengroup(serial: str, tokengroup: str | None = None, tokengroup_id: int | None = None) → bool[source]

Assign a new tokengroup to a token

Parameters:
  • serial – The serial number of the token

  • tokengroup – The name of the tokengroup

  • tokengroup_id – alternatively the id of the tokengroup

Returns:

True

privacyidea.lib.token.challenge_text_replace(message: str, user: User | None, token_obj: TokenClass, additional_tags: dict | None = None) → str[source]
privacyidea.lib.token.check_otp(serial: str, otpval: str) → tuple[bool, dict][source]

This function checks the OTP for a given serial number, without a PIN. The token has to be usable as for any other authentication (not revoked, active, within its validity period, below its fail counter), a wrong value increases the fail counter and a correct one is counted as a successful authentication.

Parameters:
  • serial

  • otpval

Returns:

tuple of result and dictionary containing a message if the verification failed, and the authentication event of an unusable token

Return type:

tuple(bool, dict)

privacyidea.lib.token.check_realm_pass(realm: str, passw: str, options: dict | None = None, include_types: list | str | None = None, exclude_types: list | str | None = None) → tuple[bool, dict][source]

This function checks, if the given passw matches any token in the given realm. This can be used for the 4-eyes token. Only tokens that are assigned are tested.

The options dictionary may contain a key/value pair ‘exclude_types’ or ‘include_types’ with the value containing a list of token types to exclude/include from/in the search.

It returns the res True/False and a reply_dict, which contains the serial number of the matching token.

Parameters:
  • realm – The realm of the user

  • passw – The password containing PIN+OTP

  • options (dict) – Additional options that are passed to the tokens

  • include_types (list or str) – List of token types to use

  • exclude_types (list or str) – List to token types not to use

Returns:

tuple of bool and dict

privacyidea.lib.token.check_serial(serial: str) → tuple[bool, str][source]

This checks, if the given serial number can be used for a new token. it returns a tuple (result, new_serial) result being True if the serial does not exist, yet. new_serial is a suggestion for a new serial number, that does not exist, yet.

Parameters:

serial (str) – Serial number to check if it can be used for a new token.

Result:

result of check and (new) serial number

Return type:

tuple(bool, str)

privacyidea.lib.token.check_serial_pass(serial: str, passw: str, options: dict | None = None) → tuple[bool, dict][source]

This function checks the otp for a given serial

If the OTP matches, True is returned and the otp counter is increased.

The function tries to determine the user (token owner), to derive possible additional policies from the user.

Parameters:
  • serial (basestring) – The serial number of the token

  • passw (basestring) – The password usually consisting of pin + otp

  • options (dict) – Additional options. Token specific.

Returns:

tuple of result (True, False) and additional dict

Return type:

tuple

privacyidea.lib.token.check_token_list(token_object_list: list[TokenClass], passw: str, user: User | None = None, options: dict | None = None, allow_reset_all_tokens: bool = False) → tuple[bool, dict][source]

Takes a list of token objects and tries to find the matching token for the given passw. It also tests * if the token is active or * the max fail count is reached, * if the validity period is ok…

This function is called by check_serial_pass, check_user_pass and check_yubikey_pass.

Parameters:
  • token_object_list – list of identified tokens

  • passw – the provided password, can be just the PIN or PIN+OTP

  • user – the identified use - as class object

  • options – additional parameters, which are passed to the token

  • allow_reset_all_tokens – If set to True, the policy reset_all_user_tokens is evaluated to reset all user tokens accordingly. Note: This parameter is used in the decorator. # TODO not good

Returns:

tuple of success and optional response

Return type:

(bool, dict)

privacyidea.lib.token.check_user_pass(user: User, passw: str, options: dict | None = None) → tuple[bool, dict][source]

This function checks the otp for a given user. It is called by the API /validate/check

If the OTP matches, True is returned and the otp counter is increased.

Parameters:
  • user (User object) – The user who is trying to authenticate

  • passw (basestring) – The password usually consisting of pin + otp

  • options (dict) – Additional options. Token specific.

Returns:

tuple of result (True, False) and additional dict

Return type:

tuple

privacyidea.lib.token.convert_token_objects_to_dicts(tokens: list[TokenClass], user: User | None, user_role: str = 'user', allowed_realms: list[str] | None = None, hidden_token_info: list[str] | None = None) → list[dict][source]

Convert a list of token objects to a list of dictionaries. Additionally, checks whether the requesting user is allowed to see the token information. If not it is reduced to the tokens serial.

Parameters:
  • tokens (list) – A list of token objects

  • user (User object) – The user object performing the request

  • user_role (str) – The role of the logged-in user

  • allowed_realms – A list of the realms the admin is allowed to see, None if the admin is allowed to see all realms

  • hidden_token_info – List of token-info keys to remove from the results

Returns:

A list of dictionaries

Return type:

list

privacyidea.lib.token.copy_token_pin(serial_from: str, serial_to: str) → bool[source]

This function copies the token PIN from one token to the other token. This can be used for workflows like lost token.

In fact the PinHash and the PinSeed are transferred

Parameters:
  • serial_from (basestring) – The token to copy from

  • serial_to (basestring) – The token to copy to

Returns:

True. In case of an error raise an exception

Return type:

bool

privacyidea.lib.token.copy_token_realms(serial_from: str, serial_to: str) → None[source]

Copy the realms of one token to the other token

Parameters:
  • serial_from – The token to copy from

  • serial_to – The token to copy to

Returns:

None

privacyidea.lib.token.copy_token_user(serial_from: str, serial_to: str) → bool[source]

This function copies the user from one token to the other token. In fact the user_id, resolver and resolver type are transferred.

Parameters:
  • serial_from (basestring) – The token to copy from

  • serial_to (basestring) – The token to copy to

Returns:

True. In case of an error raise an exception

Return type:

bool

privacyidea.lib.token.create_challenge(serial: str, transaction_id: str = None, challenge: str = '', data: dict | None = None, session: str = '', validitytime: int = 120) → Challenge[source]

Create a new challenge and persist it - to Redis if available, to the DB otherwise.

This is the single entry point for challenge creation. When the challenge cache is enabled (PI_REDIS_URL set and PI_REDIS_CACHE_CHALLENGES on), the challenge is written to Redis only and the SQL INSERT is skipped. If the cache is off or Redis fails, the challenge falls back to the database so it is never silently lost.

Always returns a Challenge instance. On the cache path that instance is the in-memory object used to build the Redis payload; it is not added to the SQL session, so its .id is None and it must not be save()-ed or mutated by the caller. Use transaction_id for identity - it’s the only stable identifier across both backends. To read the challenge back (from whichever backend holds it) use get_challenges().

The stored data always also records the conditional-access attempt_id of the request creating the challenge, so that a later request answering it logs its authentication events under the same attempt - see continue_attempt(). The challenge is the natural carrier for that: it is exactly what the client hands back, and it is created here in one place.

Parameters:
  • serial – Serial number of the token this challenge belongs to

  • transaction_id – Transaction id of the challenge. A new one is generated if None.

  • challenge – The challenge string

  • data – Challenge data dict. Pass None or {} for no data.

  • session – Session string

  • validitytime – Validity period in seconds (default: 120)

Returns:

The created Challenge object

privacyidea.lib.token.create_challenges_from_tokens(token_list: list[TokenClass], reply_dict: dict, options: dict | None = None) → None[source]

Get a list of active tokens and create challenges for these tokens. The reply_dict is modified accordingly. The transaction_id and the messages are added to the reply_dict.

Parameters:
  • token_list – The list of the token objects, that can do challenge response

  • reply_dict – The dictionary that is passed to the API response

  • options – Additional options. Passed from the upper layer

Returns:

None

privacyidea.lib.token.create_tokenclass_object(db_token: Token) → TokenClass | None[source]

(was createTokenClassObject) create a token class object from a given type If a tokenclass for this type does not exist, the function returns None.

Parameters:

db_token (database token object) – the database referenced token

Returns:

instance of the token class object

Return type:

tokenclass object

privacyidea.lib.token.delete_tokeninfo(serial: str, key: str, user: User | None = None) → int[source]

Delete a specific token info field in the database.

Parameters:
  • serial (basestring) – The serial number of the token

  • key – The key of the info in the dict

  • user (User object) – The owner of the tokens, that should be modified

Returns:

the number of tokens matching the serial and user. This number also includes tokens that did not have the token info key set in the first place!

Return type:

int

privacyidea.lib.token.enable_token(serial: str | None, enable: bool = True, user: User | None = None) → int[source]

Enable or disable a token, or all tokens of a single user. This can be checked with is_token_active.

Enabling an already active token will return 0.

Parameters:
  • serial (basestring) – The serial number of the token

  • enable (bool) – False is the token should be disabled

  • user (User object) – all tokens of the user will be enabled or disabled

Returns:

Number of tokens that were enabled/disabled

Return type:

privacyidea.lib.token.export_tokens(tokens: list[TokenClass], export_user: bool = True) → TokenExportResult[source]

Export a list of tokens.

privacyidea.lib.token.gen_serial(tokentype: str, prefix: str = None) → str[source]

Generate a serial for a given token type.

The serial consists of the token type prefix and a randomly generated string of characters. By default, the random string contains 8 characters.

If no prefix is given, it is determined by the token class prefix.

The generation of the random part of the serial is determined by the PI_TOKEN_SERIAL_RANDOM setting in the config file. The default is to calculate a two-part serial with the first 4 characters containing the current token count at the time of the generation and the next 4 characters containing a random hexadecimal value. This severely limits the number of generated serials since for every count value only 164 possible values for the random part exist. Specific count values are only ever reused if tokens are deleted.

Setting PI_TOKEN_SERIAL_RANDOM to True enables to completely generate the random string with 4 random digits and the rest using the Base32 character table (See RFC 4648 Section 6) thus allowing more than 1010 different serials.

Due to the required uniqueness of the serial, each generated serial is checked if it already exists in the database. If the number of possibilities for generated serials decreases, this can lead to excessive queries on the database.

Parameters:
  • tokentype (str) – the token type prefix is done by a lookup on the tokens

  • prefix (str) – A prefix to the serial number

Returns:

serial number

Return type:

str

privacyidea.lib.token.get_dynamic_policy_definitions(scope: str | None = None) → dict[source]

This returns the dynamic policy definitions that come with the new loaded token classes.

Parameters:

scope – an optional scope parameter. Only return the policies of this scope. If the scope is not defined, an empty dictionary is returned.

Returns:

The policy definition for the token or only for the scope.

privacyidea.lib.token.get_multi_otp(serial: str, count: int = 0, epoch_start: int = 0, epoch_end: int = 0, current_time: datetime | None = None, timestamp: int | None = None) → dict[source]

This function returns a list of OTP values for the given Token. Please note, that the tokentype needs to support this function.

Parameters:
  • serial (basestring) – the serial number of the token

  • count – number of the next otp values (to be used with event or time based tokens)

  • epoch_start – unix time start date (used with time based tokens)

  • epoch_end – unix time end date (used with time based tokens)

  • current_time (datetime) – Simulate the servertime

  • timestamp (int) – Simulate the servertime (unix time in seconds)

Returns:

dictionary of otp values

Return type:

dictionary

privacyidea.lib.token.get_num_tokens_in_realm(realm: str, active: bool = True) → int[source]

This returns the number of tokens in one realm.

Parameters:
  • realm (basestring) – The name of the realm

  • active (bool) – If only active tokens should be taken into account

Returns:

The number of tokens in the realm

Return type:

int

privacyidea.lib.token.get_one_token(*args: Any, silent_fail: bool = False, **kwargs: Any) → TokenClass | None[source]

Fetch exactly one token according to the given filter arguments, which are passed to get_tokens. Raise ResourceNotFoundError if no token was found. Raise ParameterError if more than one token was found.

Parameters:

silent_fail – Instead of raising an exception we return None silently

Returns:

Token object

Return type:

privacyidea.lib.tokenclass.TokenClass

privacyidea.lib.token.get_otp(serial: str, current_time: datetime | None = None) → tuple[source]

This function returns the current OTP value for a given Token. The tokentype needs to support this function. if the token does not support getting the OTP value, a -2 is returned. If the token could not be found, ResourceNotFoundError is raised.

Parameters:
  • serial – serial number of the token

  • current_time (datetime.datetime) – a fake servertime for testing of TOTP token

Returns:

tuple with (result, pin, otpval, passw)

Return type:

tuple

privacyidea.lib.token.get_realms_of_token(serial: str, only_first_realm: bool = False) → list[str] | str | None[source]

This function returns a list of the realms of a token

Parameters:
  • serial (basestring) – the exact serial number of the token

  • only_first_realm (bool) – Whether we should only return the first realm

Returns:

list of the realm names

Return type:

list

privacyidea.lib.token.get_serial_by_otp(token_list: list[TokenClass], otp: str = '', window: int = 10) → str | None[source]

Returns the serial for a given OTP value The token_list would be created by get_tokens()

Parameters:
  • token_list (list of token objects) – the list of token objects to be investigated

  • otp – the otp value, that needs to be found

  • window (int) – the window of search

Returns:

the serial for a given OTP value and the user

Return type:

basestring

privacyidea.lib.token.get_serial_by_otp_list(token_list: list, otp_list: list, window: int = 10, counter: int = None) → list[str][source]

Returns a list of serials for a given list of OTP values The tokenobject_list would be created by get_tokens()

Parameters:
  • token_list – the list of token objects to be investigated

  • otp_list – a list of otp values, that need to be found

  • window – the window of search

  • counter – the counter value to be used for the OTP calculation, if None the actual counter of the token is used

Returns:

a list of serials for the given OTP values and the user

privacyidea.lib.token.get_settable_tokeninfo_keys(keys: Iterable[str]) → set[str][source]

Of the given token info keys, those that some token type declares settable through POST /token/set, see TokenClass.settable_tokeninfo_keys. Used to tell such a parameter apart from an unrelated one.

The token classes are resolved once for the whole set of keys, so checking several keys does not rebuild the class registry per key. The declarations are class attributes that do not change at runtime.

Parameters:

keys – The token info keys to check

Returns:

The subset of keys that some token type allows to be set

privacyidea.lib.token.get_token_by_otp(token_list: list[TokenClass], otp: str = '', window: int = 10) → TokenClass | None[source]

Search the token in the token_list, that creates the given OTP value.

Parameters:
  • token_list (list of token objects) – the list of token objects to be investigated

  • otp (basestring) – the otp value, that needs to be found

  • window (int) – the window of search

Returns:

The token, that creates this OTP value

Return type:

TokenClass

privacyidea.lib.token.get_token_owner(serial: str) → User | None[source]

returns the user object, to which the token is assigned. the token is identified and retrieved by its serial number

If the token has no owner, None is returned

Wildcards in the serial number are ignored. This raises ResourceNotFoundError if the token could not be found.

Parameters:

serial (basestring) – serial number of the token

Returns:

The owner of the token

Return type:

User object or None

privacyidea.lib.token.get_token_owner_keys(resolvers: list[str] | None = None, user_ids: list[str] | None = None) → set[tuple[str, str, str]][source]

Return the (realm, resolver, user id) triples that own at least one token.

A user of a resolver shared by several realms only owns a token in the realm it was assigned in, so a caller holding the user records of one realm can tell which of them own a token there. Tokens that are not assigned do not contribute, and neither do revoked ones, which can never be used again. A disabled token does, as it can be enabled again, and so does every token type. An assignment without a realm - a token given to a user that has none - yields the empty realm and therefore matches no user of any realm.

A failing query is not caught as in _read_page_rows(): a set missing the triples of one chunk would silently report their users as owning no token.

Parameters:
  • resolvers – Only return the triples of these resolvers. None returns the triples of every resolver, an empty list returns nothing.

  • user_ids – Only return the triples of these user ids, however many. None returns the triples of every user, an empty list returns nothing.

Returns:

A set of (lowercase realm name, resolver name, user id) triples

privacyidea.lib.token.get_token_owner_without_lookup(serial: str) → User[source]

The owner of a token as far as the database knows it, without asking the user store: a user object with the realm and the resolver of the owner, but without a login name or user ID. For an owner that can not be looked up, e.g. because the resolver of the owner was deleted, while the realm of the owner is still what the policies are matched against. An empty user object if the token has no owner.

Parameters:

serial – serial number of the token

Returns:

the owner without the information of the user store

privacyidea.lib.token.get_token_type(serial: str) → str[source]

Returns the tokentype of a given serial number. If the token does not exist or can not be determined, an empty string is returned.

Parameters:

serial (string) – the serial number of the to be searched token

Returns:

tokentype

Return type:

string

privacyidea.lib.token.get_token_types()[source]

Return a simple list of the type names of the tokens. :return: list of tokentypes like ‘hotp’, ‘totp’… :rtype: list

privacyidea.lib.token.get_tokenclass_info(tokentype: str, section: str | None = None) → dict[source]

return the config definition of a dynamic token

Parameters:
  • tokentype (basestring) – the tokentype of the token like “totp” or “hotp”

  • section (basestring) – subsection of the token definition - optional

Returns:

dictionary with the configuration definition of the token. If the token type is not found, an empty dictionary is returned

Return type:

dict

privacyidea.lib.token.get_tokeninfo(serial: str, info: str) → str | None[source]

get a token info field in the database.

Parameters:
  • serial (basestring) – The serial number of the token

  • info – The key of the info in the dict

privacyidea.lib.token.get_tokens(tokentype: str | None = None, token_type_list: list[str] | None = None, realm: str | None = None, assigned: bool | None = None, user: User | None = None, serial: str | None = None, serial_wildcard: str | None = None, active: bool | None = None, resolver: str | None = None, userid: str | None = None, rollout_state: str | None = None, count: bool = False, revoked: bool | None = None, locked: bool | None = None, tokeninfo: dict | None = None, maxfail: bool | None = None, all_nodes: bool = False) → list[TokenClass] | int[source]

(was getTokensOfType) This function returns a list of token objects of a * given type, * of a realm * or tokens with assignment or not * for a certain serial number or * for a User

E.g. thus you can get all assigned tokens of type totp.

Parameters:
  • tokentype (basestring) – The type of the token. If None, all tokens are returned.

  • token_type_list (list) – A list of token types. If None or empty, all token types are returned.

  • realm (basestring) – get tokens of a realm. If None, all tokens are returned. Accepts a single realm name, a wildcard pattern (e.g. realm*), or a comma-separated list of realm names where each entry may contain * wildcards (e.g. realm1,realm2 or staff*,students*). If allowed_realms is not None, the queried realms must overlap with allowed_realms, otherwise no matching tokens will be found.

  • assigned (bool) – Get either assigned (True) or unassigned (False) tokens. If None, gets all tokens.

  • user (User Object) – Filter for the Owner of the token. The realm, the resolver and the user id of the user are applied independently, hence a user object carrying only a realm lists the tokens of all users of that realm. Note that a user object with only a resolver is empty (User.is_empty ignores the resolver) and therefore does not filter at all. A realm that does not exist matches nothing, and a login name that can not be resolved to a user id raises a UserError.

  • serial (basestring) – The exact serial number of a token

  • serial_wildcard (basestring) – A wildcard to match token serials

  • active (bool) – Whether only active (True) or inactive (False) tokens should be returned

  • resolver (basestring) – filter for the resolver of the token owner (case-insensitive and allows “*” as wildcard)

  • userid (basestring) – filter for the user id of the token owner, i.e. the identifier the resolver reports for the user (case-sensitive and allows “*” as wildcard)

  • rollout_state – returns a list of the tokens in the certain rollout state. Some tokens are not enrolled in a single step but in multiple steps. These tokens are then identified by the DB-column rollout_state.

  • count (bool) – If set to True, only the number of the result and not the list is returned.

  • revoked (bool) – Only search for revoked tokens or only for not revoked tokens

  • locked (bool) – Only search for locked tokens or only for not locked tokens

  • tokeninfo (dict) – Return tokens with the given tokeninfo. The tokeninfo is a key/value dictionary

  • maxfail – If only tokens should be returned, which failcounter reached maxfail

  • all_nodes (bool) – If True, ignore node specific realm configurations (default: False)

Returns:

A list of lib.tokenclass objects.

Return type:

list or int

privacyidea.lib.token.get_tokens_from_serial_or_user(serial: str | None, user: User | None, **kwargs: Any) → list[TokenClass][source]

Fetch tokens, either by (exact) serial, or all tokens of a single user. In case a serial number is given, check that exactly one token is returned and raise a ResourceNotFoundError if that is not the case. In case a user is given, the result can also be empty.

Parameters:
  • serial – exact serial number or None

  • user – a user object or None

  • kwargs – additional arguments to get_tokens

Returns:

a (possibly empty) list of tokens

Return type:

list

privacyidea.lib.token.get_tokens_in_resolver(resolver: str) → list[TokenClass][source]

Return a list of the token objects, that contain this very resolver

Parameters:

resolver (basestring) – The resolver, the tokens should be in

Returns:

list of tokens with this resolver

Return type:

list of token objects

privacyidea.lib.token.get_tokens_paginate(tokentype: str | None = None, token_type_list: list[str] | None = None, realm: str | None = None, assigned: bool | None = None, user: ~privacyidea.lib.user.User | None = None, serial: str | None = None, active: bool | None = None, resolver: str | None = None, rollout_state: str | None = None, sortby: ~typing.Any = <sqlalchemy.orm.attributes.InstrumentedAttribute object>, sortdir: str = 'asc', psize: int = 15, page: int = 1, description: str | None = None, userid: str | None = None, allowed_realms: list[str] | None = None, tokeninfo: dict | None = None, hidden_tokeninfo: list[str] | None = None, container_serial: str | None = None) → dict[source]

This function is used to retrieve a token list, that can be displayed in the Web UI. It supports pagination. Each retrieved page will also contain a “next” and a “prev”, indicating the next or previous page. If either does not exist, it is None.

Parameters:
  • tokentype

  • token_type_list – A list of token types

  • realm – A realm the token is assigned to, a wildcard pattern, or a comma-separated list of realm names (each entry may contain * wildcards). If allowed_realms is not None, it must contain this realm, otherwise no matching tokens will be found.

  • assigned (bool) – Returns assigned (True) or not assigned (False) tokens

  • user (User object) – The user, whose token should be displayed

  • serial – a pattern for matching the serial or a comma separated list of exact serials

  • active – Returns active (True) or inactive (False) tokens

  • resolver (basestring) – A resolver name, which may contain “*” for filtering.

  • userid (basestring) – A userid, which may contain “*” for filtering.

  • rollout_state

  • sortby (A Token column or a string.) – Sort by a certain Token DB field. The default is Token.serial. If a string like “serial” is provided, we try to convert it to the DB column.

  • sortdir (basestring) – Can be “asc” (default) or “desc”

  • psize (int) – The size of the page

  • page (int) – The number of the page to view. Starts with 1 ;-)

  • allowed_realms (list) – A list of realms, that the admin is allowed to see

  • tokeninfo – Return tokens with the given tokeninfo. The tokeninfo is a key/value dictionary

  • description (str) – Take the description of the token into the query

  • hidden_tokeninfo (list) – List of token-info keys to remove from the results

  • container_serial (basestring) – The serial number of a container

Returns:

dict with tokens, prev, next and count

Return type:

dict

privacyidea.lib.token.get_tokens_paginated_generator(tokentype: str | None = None, realm: str | None = None, assigned: bool | None = None, user: User | None = None, serial_wildcard: str | None = None, active: bool | None = None, resolver: str | None = None, rollout_state: str | None = None, revoked: bool | None = None, locked: bool | None = None, tokeninfo: dict | None = None, maxfail: bool | None = None, psize: int = 1000) → Iterator[list[TokenClass]][source]

Fetch chunks of psize tokens that match the filter criteria from the database and generate lists of token objects. See get_tokens for information on the arguments.

Note that individual lists may contain less than psize elements if a token entry has an invalid type.

Parameters:
  • psize – Maximum size of chunks that are fetched from the database

  • assigned (bool or None) – Whether the token is assigned to a user

Returns:

This is a generator that generates non-empty lists of token objects.

privacyidea.lib.token.import_token(serial: str, token_dict: dict, tokenrealms: list | None = None) → TokenClass[source]

This function is used during the import of a PSKC file.

Parameters:
  • serial (str) – The serial number of the token

  • token_dict (dict) –

    A dictionary describing the token like

    {
      "type": ...,
      "description": ...,
      "otpkey": ...,
      "counter: ...,
      "timeShift": ...
    }
    

  • tokenrealms (list) – List of realms to set as realms of the token

Returns:

the token object

privacyidea.lib.token.import_tokens(tokens: list[dict], update_existing_tokens: bool = True, assign_to_user: bool = True) → TokenImportResult[source]

Import a list of token dictionaries.

Parameters:
  • tokens – list of dict with token information

  • update_existing_tokens – If True, existing tokens will be updated with the new data.

  • assign_to_user – If True, the user from the token data will be assigned to the token.

Returns:

list of token objects

privacyidea.lib.token.init_token(param: dict, user: User = None, tokenrealms: list[str] = None, tokenkind: str = None) → TokenClass[source]

Create a new token or update an existing token with the specified parameters.

Parameters:
  • param (dict) –

    initialization parameters like

    {
        "serial": ..., (optional)
        "type": ...., (optional, default=hotp)
        "otpkey": ...
    }
    

  • user (User Object) – the token owner

  • tokenrealms (list) – the realms, to which the token should belong

  • tokenkind – The kind of the token, can be “software”, “hardware” or “virtual”

Returns:

token object or None

Return type:

TokenClass

privacyidea.lib.token.is_settable_tokeninfo_key(key: str) → bool[source]

Whether any token type declares the given token info key as settable through POST /token/set, see TokenClass.settable_tokeninfo_keys. Use get_settable_tokeninfo_keys() to check several keys at once.

Parameters:

key – The token info key to check

Returns:

True if some token type allows the key to be set

privacyidea.lib.token.is_token_active(serial: str) → bool[source]

Return True if the token is active, otherwise false Raise ResourceError if the token could not be found.

Parameters:

serial (basestring) – The serial number of the token

Returns:

True or False

Return type:

bool

privacyidea.lib.token.is_token_owner(serial: str, user: User) → bool[source]

Check if the given user is the owner of the token with the given serial number

Parameters:
  • serial (str) – The serial number of the token

  • user (User object) – The user that needs to be checked

Returns:

Return True or False

Return type:

bool

privacyidea.lib.token.list_tokengroups(tokengroup: str | None = None) → list[TokenTokengroup][source]

Return a list of tokens that are assigned to a certain tokengroup If no tokengroup is specified, all groups/tokens are returned.

:param tokengroup. The name of the token group :return:

privacyidea.lib.token.lost_token(serial: str, new_serial: str | None = None, password: str | None = None, validity: int = 10, contents: str = '8', pw_len: int = 16, options: dict | None = None) → dict[source]

This is the workflow to handle a lost token. The token <serial> is lost and will be disabled. A new token of type password token will be created and assigned to the user. The PIN of the lost token will be copied to the new token. The new token will have a certain validity period.

Parameters:
  • serial – Token serial number

  • new_serial – new serial number

  • password – new password

  • validity (int) – Number of days, the new token should be valid

  • contents (str) –

    The contents of the generated password. Can be a string like "Ccn".

    • ”C”: upper case characters

    • ”c”: lower case characters

    • ”n”: digits

    • ”s”: special characters

    • ”8”: base58

  • pw_len (int) – The length of the generated password

  • options (dict) – optional values for the decorator passed from the upper API level

Returns:

result dictionary

Return type:

dict

privacyidea.lib.token.regenerate_enroll_url(serial: str, request: Request, g: Any) → str | None[source]

Performs a rollover for the token with the given serial number and returns the new enroll URL. Loads the configurations from the policies.

Returns None if the token type does not support enrollment URLs.

privacyidea.lib.token.remove_token(serial: str | None = None, user: User | None = None) → int[source]

remove the token that matches the serial number or all tokens of the given user and also remove the realm associations and all its challenges

Parameters:
  • user (User object) – The user, who’s tokens should be deleted.

  • serial (basestring) – The serial number of the token to delete (exact)

Returns:

The number of deleted token

Return type:

int

privacyidea.lib.token.reset_token(serial: str | None, user: User | None = None) → int[source]

Reset the failcounter of a single token, or of all tokens of one user.

Parameters:
  • serial – serial number (exact)

  • user

Returns:

The number of tokens, that were reset

Return type:

int

privacyidea.lib.token.resync_token(serial: str, otp1: str, otp2: str, options: dict | None = None, user: User | None = None) → bool[source]

Resynchronize the token of the given serial number and user by searching the otp1 and otp2 in the future otp values.

Parameters:
  • serial (str) – token serial number (exact)

  • otp1 (str) – first OTP value

  • otp2 (str) – second OTP value, directly after the first

  • options (dict) – additional options like the servertime for TOTP token

  • user (User object) – The user, who’s token should be resynced

Returns:

result of the resync

Return type:

bool

privacyidea.lib.token.revoke_token(serial: str | None, user: User | None = None) → int[source]

Revoke a token, or all tokens of a single user.

Parameters:
  • serial (basestring) – The serial number of the token (exact)

  • user (User object) – all tokens of the user will be enabled or disabled

Returns:

Number of tokens that were enabled/disabled

Return type:

int

privacyidea.lib.token.set_count_auth(serial: str | None, count: int, user: User | None = None, max: bool = False, success: bool = False) → int[source]

The auth counters are stored in the token info database field. There are different counters that can be set:

count_auth -> max=False, success=False
count_auth_max -> max=True, success=False
count_auth_success -> max=False, success=True
count_auth_success_max -> max=True, success=True
Parameters:
  • count (int) – The counter value

  • user (User object) – The user owner of the tokens to modify

  • serial (basestring) – The serial number of the one token to modify (exact)

  • max (bool) – True, if either count_auth_max or count_auth_success_max are to be modified

  • success (bool) – True, if either count_auth_success or count_auth_success_max are to be modified

Returns:

number of modified tokens

Return type:

int

privacyidea.lib.token.set_count_window(serial: str | None, countwindow: int = 10, user: User | None = None) → int[source]

The count window is used during authentication to find the matching OTP value. This sets the count window per token.

Parameters:
  • serial (basestring) – The serial number of the token (exact)

  • countwindow (int) – the size of the window

  • user (User object) – The owner of the tokens, which should be modified

Returns:

number of modified tokens

Return type:

int

privacyidea.lib.token.set_defaults(serial: str) → None[source]

Set the default values for the token with the given serial number (exact)

Parameters:

serial (basestring) – token serial

Returns:

None

privacyidea.lib.token.set_description(serial: str | None, description: str, user: User | None = None, token: TokenClass | None = None) → bool[source]

Set the description of a token

Parameters:
  • serial (basestring) – The serial number of the token (exact)

  • description (str) – The description for the token

  • user (User object) – The owner of the tokens, which should be modified

Returns:

True. In case of an error raise an exception

Return type:

int

privacyidea.lib.token.set_failcounter(serial: str | None, counter: int, user: User | None = None) → int[source]

Set the fail counter of a token.

Parameters:
  • serial – The serial number of the token (exact)

  • counter – THe counter to which the fail counter should be set

  • user – An optional user

Returns:

Number of tokens, where the fail counter was set.

privacyidea.lib.token.set_hashlib(serial: str | None, hashlib: str = 'sha1', user: User | None = None) → int[source]

Set the hashlib in the tokeninfo. Can be something like sha1, sha256…

Parameters:
  • serial (basestring) – The serial number of the token (exact)

  • hashlib (basestring) – The hashlib of the token

  • user (User object) – The User, for who’s token the hashlib should be set

Returns:

the number of token infos set

Return type:

int

privacyidea.lib.token.set_max_failcount(serial: str | None, maxfail: int, user: User | None = None) → int[source]

Set the maximum fail counts of tokens. This is the maximum number a failed authentication is allowed.

Parameters:
  • serial (basestring) – The serial number of the token (exact)

  • maxfail (int) – The maximum allowed failed authentications

  • user (User object) – The owner of the tokens, which should be modified

Returns:

number of modified tokens

Return type:

int

privacyidea.lib.token.set_otplen(serial: str | None, otplen: int = 6, user: User | None = None) → int[source]

Set the otp length of the token defined by serial or for all tokens of the user. The OTP length is usually 6 or 8.

Parameters:
  • serial (basestring) – The serial number of the token (exact)

  • otplen (int) – The length of the OTP value

  • user (User object) – The owner of the tokens

Returns:

number of modified tokens

Return type:

int

privacyidea.lib.token.set_pin(serial: str | None, pin: str, user: User | None = None, encrypt_pin: bool = False) → int[source]

Set the token PIN of the token. This is the static part that can be used to authenticate.

Parameters:
  • pin (str) – The pin of the token

  • user (User object) – If the user is specified, the pins for all tokens of this user will be set

  • serial – If the serial is specified, the PIN for this very token will be set. (exact)

  • encrypt_pin (bool) – Whether the PIN should be stored in an encrypted way

Returns:

The number of PINs set (usually 1)

Return type:

int

privacyidea.lib.token.set_pin_so(serial: str, so_pin: str, user: User | None = None) → int[source]

Set the SO PIN of a smartcard. The SO Pin can be used to reset the PIN of a smartcard. The SO PIN is stored in the database, so that it could be used for automatic processes for User PIN resetting.

Parameters:
  • serial (basestring) – The serial number of the token (exact)

  • so_pin (basestring) – The Security Officer PIN

  • user (User object) – The user, for who’s token the SO PIN should be set

Returns:

The number of SO PINs set. (usually 1)

Return type:

int

privacyidea.lib.token.set_pin_user(serial: str, user_pin: str, user: User | None = None) → int[source]

This sets the user pin of a token. This just stores the information of the user pin for (e.g. an eTokenNG, Smartcard) in the database

Parameters:
  • serial (basestring) – The serial number of the token (exact)

  • user_pin (str) – The user PIN

  • user (User object) – The user, for who’s token the PIN should be set

Returns:

The number of PINs set (usually 1)

Return type:

int

privacyidea.lib.token.set_realms(serial: str, realms: list | None = None, add: bool = False, allowed_realms: list | None = None) → None[source]

Set all realms of a token. This sets the realms new. I.e. it does not add realms. So realms that are not contained in the list will not be assigned to the token anymore.

If the token could not be found, a ResourceNotFoundError is raised.

Thus, setting realms=[] clears all realms assignments.

Parameters:
  • serial (basestring) – the serial number of the token (exact)

  • realms (list) – A list of realm names

  • add (bool) – if the realms should be added and not replaced

  • allowed_realms – A list of realms, that the admin is allowed to manage, None if all realms are allowed and an empty list if none is

privacyidea.lib.token.set_sync_window(serial: str | None, syncwindow: int = 1000, user: User | None = None) → int[source]

The sync window is the window that is used during resync of a token. Such many OTP values are calculated ahead, to find the matching otp value and counter.

Parameters:
  • serial (basestring) – The serial number of the token (exact)

  • syncwindow (int) – The size of the sync window

  • user (User object) – The owner of the tokens, which should be modified

Returns:

number of modified tokens

Return type:

int

privacyidea.lib.token.set_token_type_info(serial: str | None, info: dict, user: User | None = None) → list[str][source]

Write token info entries that a token class maintains but that change over the lifetime of a token, e.g. “remote.user” on a remote token or “phone” on an SMS token. They cannot be written through the generic token info endpoints, but an administrator who may modify the token may change them.

Only a key a token class declares as settable is written, see TokenClass.settable_tokeninfo_keys. The keys that carry the secret of a token are not settable, so a parameter cannot reach them, and neither can it reach a key of a different token type. A key that no token class declares settable raises a ParameterError.

Parameters:
  • serial – The serial number of the token

  • info – The entries to write, as {key: value}

  • user – The owner of the tokens that should be modified

Returns:

The keys that were written, listed once per token they were written to, so that the length is the number of entries written, the way the other setters of POST /token/set count the tokens they modified. The caller can audit exactly the entries that were written.

privacyidea.lib.token.set_tokengroups(serial: str, tokengroups: list[str] | None = None, add: bool = False) → None[source]

Set a list of tokengroups for one token

Parameters:
  • serial – The serial of the token

  • tokengroups – The list of tokengroups (names)

  • add – Whether the list of tokengropus should be added

Returns:

privacyidea.lib.token.set_validity_period_end(serial: str | None, user: User | None, end: str) → int[source]

Set the validity period for the given token.

Parameters:
  • serial – serial number (exact)

  • user

  • end (basestring) – Timestamp in the format DD/MM/YY HH:MM

privacyidea.lib.token.set_validity_period_start(serial: str | None, user: User | None, start: str) → int[source]

Set the validity period for the given token.

Parameters:
  • serial – serial number (exact)

  • user

  • start (basestring) – Timestamp in the format DD/MM/YY HH:MM

privacyidea.lib.token.token_exist(serial: str) → bool[source]

returns true if the token with the exact given serial number exists

Parameters:

serial – the serial number of the token

privacyidea.lib.token.unassign_token(serial: str | None, user: User | None = None) → int[source]

unassign the user from the token, or all tokens of a user

Parameters:
  • serial – The serial number of the token to unassign (exact). Can be None

  • user – A user whose tokens should be unassigned

Returns:

number of unassigned tokens

privacyidea.lib.token.unassign_tokengroup(serial: str, tokengroup: str | None = None, tokengroup_id: int | None = None) → bool[source]

Removes a tokengroup from a token

Parameters:
  • serial – The serial number of the token

  • tokengroup – The name of the tokengroup

  • tokengroup_id – alternatively the id of the tokengroup

Returns:

True in case of success

privacyidea.lib.token.update_token_from_export(token_data: dict) → str[source]

Write an entry of a token export, e.g. the YAML export of the token janitors, to the existing token with the same serial. This re-encrypts the secrets of the token with the current encryption key.

The entry is written like an import writes it (TokenClass.import_token), not through the enrollment update of the token type: the OTP key, the OTP length and the description are stored, and of the token info only the entries that are stored encrypted (marked “<key>.type: password”), so they are encrypted with the current key. The other token info entries are not written back: TAN lists, use counters and the like may have changed since the export. The OTP counter, the fail counter, the token kind, the active flag and the rollout state are kept; the OTP counter takes the counter of the entry if that is higher. The owner of the entry is ignored. A revoked token is re-encrypted as well.

Not re-encrypted, because the export does not contain them in clear text: the PIN of an mOTP token and PINs that are stored encrypted.

Parameters:

token_data – the entry of the export

Returns:

the serial of the updated token

Raises:
  • ParameterError – if the entry has no serial or its counter is not a number

  • ValueError – if the OTP length of the entry is not a number

  • ResourceNotFoundError – if there is no token with the serial of the entry

privacyidea.lib.token.weigh_token_type(token_obj: TokenClass) → int[source]

This method returns a weight of a token type, which is used to sort the tokentype list. Other weighing functions can be implemented.

The Push token weighs the most, so that it will be sorted to the end.

Parameters:

token_obj – token object

Returns:

weight of the tokentype

Return type:

int