wpLogin method

Future<WPUserLoginResponse> wpLogin({
  1. String? login,
  2. String? email,
  3. String? username,
  4. required String password,
  5. int? expiresIn,
  6. String? deviceName,
  7. bool saveTokenToLocalStorage = true,
})

Sends a request to login a user.

Pass the user's username or email as login. For convenience you can pass email or username instead; the server accepts either in the same field. If more than one is set, login is used first, then email, then username.

expiresIn optionally asks for a shorter token lifetime in seconds (the site maximum still applies). deviceName is shown to admins when they list tokens. When saveTokenToLocalStorage is true the user and token are stored on the device.

Returns a WPUserLoginResponse future. Throws an InvalidCredentialsException if the login details are wrong, LoginBlockedException if another plugin (e.g. two-factor) stopped the login, PrivilegedUserException if the account may not use the API, TooManyAttemptsException if rate limited, InvalidParamsException if a parameter is missing or invalid.

Implementation

Future<WPUserLoginResponse> wpLogin(
    {String? login,
    String? email,
    String? username,
    required String password,
    int? expiresIn,
    String? deviceName,
    bool saveTokenToLocalStorage = true}) async {
  // Creates payload for login
  Map<String, dynamic> payload = {
    "login": login ?? email ?? username,
    "password": password,
  };
  if (expiresIn != null) payload["expires_in"] = expiresIn;
  if (deviceName != null) payload["device_name"] = deviceName;

  // send http request
  final Map<String, dynamic> json = await _http(
    method: "POST",
    url: _urlForRouteType(WPRouteType.UserLogin),
    body: payload,
  );

  WPUserLoginResponse wpUserLoginResponse =
      WPUserLoginResponse.fromJson(json);
  String? userToken = wpUserLoginResponse.data?.token;

  if (userToken != null && saveTokenToLocalStorage) {
    WpUser wpUser = WpUser.fromWPUserLoginResponse(wpUserLoginResponse);
    await WPJsonAPI.wpLogin(wpUser);
  }
  return wpUserLoginResponse;
}