GC_Application_Passwords::create_new_application_password()
最后更新于:2021-11-26 09:13:38
GC_Application_Passwords::create_new_application_password( int$user_id, array$args=array())Creates a new application password.
参数
- $user_id
-
(int) (Required) User ID.
- $args
-
(array) (Optional) Information about the application password.
Default value: array()
响应
(array|GC_Error) The first key in the array is the new password, the second is its detailed information. A GC_Error instance is returned on error.
源文件
文件: gc-includes/class-gc-application-passwords.php
public static function create_new_application_password( $user_id, $args = array() ) {
if ( ! empty( $args['name'] ) ) {
$args['name'] = sanitize_text_field( $args['name'] );
}
if ( empty( $args['name'] ) ) {
return new GC_Error( 'application_password_empty_name', __( 'An application name is required to create an application password.' ), array( 'status' => 400 ) );
}
if ( self::application_name_exists_for_user( $user_id, $args['name'] ) ) {
return new GC_Error( 'application_password_duplicate_name', __( 'Each application name should be unique.' ), array( 'status' => 409 ) );
}
$new_password = gc_generate_password( static::PW_LENGTH, false );
$hashed_password = gc_hash_password( $new_password );
$new_item = array(
'uuid' => gc_generate_uuid4(),
'app_id' => empty( $args['app_id'] ) ? '' : $args['app_id'],
'name' => $args['name'],
'password' => $hashed_password,
'created' => time(),
'last_used' => null,
'last_ip' => null,
);
$passwords = static::get_user_application_passwords( $user_id );
$passwords[] = $new_item;
$saved = static::set_user_application_passwords( $user_id, $passwords );
if ( ! $saved ) {
return new GC_Error( 'db_error', __( 'Could not save application password.' ) );
}
$network_id = get_main_network_id();
if ( ! get_network_option( $network_id, self::OPTION_KEY_IN_USE ) ) {
update_network_option( $network_id, self::OPTION_KEY_IN_USE, true );
}
/**
* Fires when an application password is created.
*
* @since 5.6.0
*
* @param int $user_id The user ID.
* @param array $new_item The details about the created password.
* @param string $new_password The unhashed generated app password.
* @param array $args Information used to create the application password.
*/
do_action( 'gc_create_application_password', $user_id, $new_item, $new_password, $args );
return array( $new_password, $new_item );
}