wpLogin method

Future<WPUserLoginResponse> wpLogin({
  1. String? email,
  2. String? username,
  3. required String password,
  4. WPAuthType authType = WPAuthType.WpEmail,
  5. String? tokenExpiryAt,
  6. bool saveTokenToLocalStorage = true,
})

Sends a request to login a user with the email & password or username and password. Set authType to auth with email/username.

Returns a WPUserLoginResponse future. Throws an InvalidNonceException if nonce token is not valid InvalidEmailException if the email is not valid IncorrectPasswordException if the password is not valid InvalidUsernameException if the username is not valid Exception for any other reason.

Implementation

Future<WPUserLoginResponse> wpLogin(
    {String? email,
    String? username,
    required String password,
    WPAuthType authType = WPAuthType.WpEmail,
    String? tokenExpiryAt,
    bool saveTokenToLocalStorage = true}) async {
  // Get nonce from WordPress
  WPNonceResponse wpNonceResponse = await wpNonce();

  // Creates payload for login
  Map<String, dynamic> payload = {};
  if (username != null) payload["username"] = username;
  if (email != null) payload["email"] = email;
  payload["password"] = password;
  payload["nonce"] = wpNonceResponse.data?.nonce;
  if (tokenExpiryAt != null) payload["expiry"] = tokenExpiryAt;

  // send http request
  final json = await _http(
    method: "POST",
    url: _urlForRouteType(WPRouteType.UserLogin) +
        _getAuthQueryForType(authType),
    body: payload,
  );

  // return response
  if (_jsonHasBadStatus(json)) {
    return _throwExceptionForStatusCode(json);
  }
  WPUserLoginResponse wpUserLoginResponse =
      WPUserLoginResponse.fromJson(json);
  String? userToken = wpUserLoginResponse.data?.userToken;

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