14.2.1.3. Token Functions

This module 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

privacyidea.lib.token.add_tokeninfo(serial, info, value=None, value_type=None, user=None)[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 – The type of the value. If set to “password” the value

is stored encrypted :type value_type: basestring :param user: The owner of the tokens, that should be modified :type user: User object :return: the number of modified tokens :rtype: int

privacyidea.lib.token.assign_token(serial, user, pin=None, encrypt_pin=False, err_message=None)[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

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

privacyidea.lib.token.check_otp(serial, otpval)[source]

This function checks the OTP for a given serial number :param serial: :param otpval: :return:

privacyidea.lib.token.check_realm_pass(realm, passw, options=None, include_types=None, exclude_types=None)[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 for the check

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

Returns

tuple of bool and dict

privacyidea.lib.token.check_serial(serial)[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 – Seral number that is to be checked, if it can be used for

a new token. :type serial: string :result: bool and serial number :rtype: tuple

privacyidea.lib.token.check_serial_pass(serial, passw, options=None)[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(tokenobject_list, passw, user=None, options=None, allow_reset_all_tokens=False)[source]

this 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
  • tokenobject_list – list of identified tokens

  • passw – the provided passw (mostly 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.

Returns

tuple of success and optional response

Return type

(bool, dict)

privacyidea.lib.token.check_user_pass(user, passw, options=None)[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.copy_token_pin(serial_from, serial_to)[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, serial_to)[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, serial_to)[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_challenges_from_tokens(token_list, reply_dict, options=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)[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, key, user=None)[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

  • value – The value of the info

  • 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! :rtype: int

privacyidea.lib.token.enable_token(serial, enable=True, user=None)[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.gen_serial(tokentype=None, prefix=None)[source]

generate a serial for a given tokentype

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=None)[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. :return: The policy definition for the token or only for the scope.

privacyidea.lib.token.get_multi_otp(serial, count=0, epoch_start=0, epoch_end=0, curTime=None, timestamp=None)[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)

  • curTime (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, active=True)[source]

This returns the number of tokens in one realm. :param realm: The name of the realm :type realm: basestring :param active: If only active tokens should be taken into account :type active: bool :return: The number of tokens in the realm :rtype: int

privacyidea.lib.token.get_one_token(*args, **kwargs)[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.

privacyidea.lib.token.get_otp(serial, current_time=None)[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) – 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, only_first_realm=False)[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) – Wheather 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, otp='', window=10)[source]

Returns the serial for a given OTP value The tokenobject_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_token_by_otp(token_list, otp='', window=10)[source]

search the token in the token_list, that creates the given OTP value. The tokenobject_list would be created by get_tokens()

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

Tokenobject

privacyidea.lib.token.get_token_owner(serial)[source]

returns the user object, to which the token is assigned. the token is identified and retrieved by it’s 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_type(serial)[source]

Returns the tokentype of a given serial number. If the token does not exist or can not be deterimined, 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_tokenclass_info(tokentype, section=None)[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

dict - if nothing found an empty dict

Return type

dict

privacyidea.lib.token.get_tokens(tokentype=None, realm=None, assigned=None, user=None, serial=None, serial_wildcard=None, active=None, resolver=None, rollout_state=None, count=False, revoked=None, locked=None, tokeninfo=None, maxfail=None)[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.

  • realm (basestring) – get tokens of a realm. If None, all tokens are returned.

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

  • user (User Object) – Filter for the Owner of the token

  • 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 given resolver name

  • 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

Returns

A list of tokenclasses (lib.tokenclass).

Return type

list

privacyidea.lib.token.get_tokens_from_serial_or_user(serial, user, **kwargs)[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. :param serial: exact serial number or None :param user: a user object or None :param kwargs: additional argumens to get_tokens :return: a (possibly empty) list of tokens

privacyidea.lib.token.get_tokens_in_resolver(resolver)[source]

Return a list of the token ojects, 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=None, realm=None, assigned=None, user=None, serial=None, active=None, resolver=None, rollout_state=None, sortby=<sqlalchemy.orm.attributes.InstrumentedAttribute object>, sortdir='asc', psize=15, page=1, description=None, userid=None, allowed_realms=None, tokeninfo=None)[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

  • realm

  • 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

  • active

  • 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

Returns

dict with tokens, prev, next and count

Return type

dict

privacyidea.lib.token.get_tokens_paginated_generator(tokentype=None, realm=None, assigned=None, user=None, serial_wildcard=None, active=None, resolver=None, rollout_state=None, revoked=None, locked=None, tokeninfo=None, maxfail=None, psize=1000)[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

Returns

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

privacyidea.lib.token.import_token(serial, token_dict, default_hashlib=None, tokenrealms=None)[source]

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

Parameters
  • serial – The serial number of the token

  • token_dict

    A dictionary describing the token like: {“type”: …,

    ”description”: …, “otpkey”: …, “counter: …, “timeShift”: …}

  • default_hashlib

Returns

the token object

privacyidea.lib.token.init_token(param, user=None, tokenrealms=None, tokenkind=None)[source]

create a new token or update an existing token

Parameters
  • param (dict) – initialization parameters like: serial (optional) type (optionl, 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 object

privacyidea.lib.token.is_token_active(serial)[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, user)[source]

Check if the given user is the owner of the token with the given serial number :param serial: The serial number of the token :type serial: str :param user: The user that needs to be checked :type user: User object :return: Return True or False :rtype: bool

privacyidea.lib.token.lost_token(serial, new_serial=None, password=None, validity=10, contents='8', pw_len=16, options=None)[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 – The contents of the generated password. “C”: upper case

characters, “c”: lower case characters, “n”: digits and “s”: special characters, “8”: base58 :type contents: A string like “Ccn” :param pw_len: The length of the generated password :type pw_len: int :param options: optional values for the decorator passed from the upper API level :type options: dict

Returns

result dictionary

privacyidea.lib.token.remove_token(serial=None, user=None)[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, user=None)[source]

Reset the failcounter of a single token, or of all tokens of one user. :param serial: serial number (exact) :param user: :return: The number of tokens, that were resetted :rtype: int

privacyidea.lib.token.resync_token(serial, otp1, otp2, options=None, user=None)[source]

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

Parameters
  • serial (basestring) – token serial number (exact)

  • otp1 (basestring) – first OTP value

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

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

Returns

privacyidea.lib.token.revoke_token(serial, user=None)[source]

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

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

  • 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.set_count_auth(serial, count, user=None, max=False, success=False)[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 tokens to modify

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

  • max – True, if either count_auth_max or count_auth_success_max are

to be modified :type max: bool :param success: True, if either count_auth_success or count_auth_success_max are to be modified :type success: bool :return: number of modified tokens :rtype: int

privacyidea.lib.token.set_count_window(serial, countwindow=10, user=None)[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)[source]

Set the default values for the token with the given serial number (exact) :param serial: token serial :type serial: basestring :return: None

privacyidea.lib.token.set_description(serial, description, user=None)[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

number of modified tokens

Return type

int

privacyidea.lib.token.set_failcounter(serial, counter, user=None)[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, hashlib='sha1', user=None)[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, maxfail, user=None)[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, otplen=6, user=None)[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, pin, user=None, encrypt_pin=False)[source]

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

Parameters
  • pin (basestring) – The pin of the token

  • user – If the user is specified, the pins for all tokens of this

user will be set :type user: User object :param serial: If the serial is specified, the PIN for this very token will be set. (exact) :return: The number of PINs set (usually 1) :rtype: int

privacyidea.lib.token.set_pin_so(serial, so_pin, user=None)[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

Returns

The number of SO PINs set. (usually 1)

Return type

int

privacyidea.lib.token.set_pin_user(serial, user_pin, user=None)[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 (basestring) – The user PIN

Returns

The number of PINs set (usually 1)

Return type

int

privacyidea.lib.token.set_realms(serial, realms=None, add=False)[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

privacyidea.lib.token.set_sync_window(serial, syncwindow=1000, user=None)[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_validity_period_end(serial, user, end)[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, user, start)[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)[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, user=None)[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