getMessage() ); } // Store the encrypted values and the IV. Settings\set_user_data( $user_id, 'user_token', array( 'token' => $encrypted, 'iv' => $iv, ) ); return $encrypted; } /** * Retrieve the unencrypted Airstory token for the current user. * * @throws Exception When OpenSSL fails to decrypt a token. * * @param int $user_id The ID of the user to retrieve the token for. * @return string|WP_Error Either the unencrypted Airstory token for the current user, an empty * string if no token exists, or a WP_Error if we're unable to decrypt. */ function get_token( $user_id ) { // Verify the user actually exists. if ( ! get_user_by( 'ID', $user_id ) ) { return ''; } $encrypted = Settings\get_user_data( $user_id, 'user_token', false ); // Return early if either meta value is empty. if ( ! isset( $encrypted['token'], $encrypted['iv'] ) ) { return ''; } try { $token = openssl_decrypt( $encrypted['token'], get_cipher_algorithm(), AUTH_KEY, null, $encrypted['iv'] ); if ( false === $token ) { throw new Exception(); } } catch ( Exception $e ) { return new WP_Error( 'airstory-decryption', __( 'Unable to decrypt Airstory token', 'airstory' ), $e->getMessage() ); } // Extra sanitization on the now-unencrypted value. return sanitize_text_field( $token ); } /** * Clear a user's token. * * @param int $user_id The user ID to clear token-related user meta for. * @return bool Were the relevant user meta entries deleted? */ function clear_token( $user_id ) { return Settings\set_user_data( $user_id, 'user_token', null ); }