login method

Future<UserDto> login(
  1. String username,
  2. String password
)

Authenticates a user with NTUT Portal credentials.

Sets the JSESSIONID cookie in the app.ntut.edu.tw domain for subsequent authenticated requests. This session cookie is shared across all services.

Returns user profile information including name, email, and avatar filename.

Throws an Exception if login fails due to invalid credentials.

Implementation

Future<UserDto> login(String username, String password) async {
  final response = await _portalDio.post(
    'login.do',
    queryParameters: {'muid': username, 'mpassword': password},
  );

  final body = jsonDecode(response.data);
  if (!body['success']) {
    throw Exception('Login failed. Please check your credentials.');
  }

  final String? passwordExpiredRemind = body['passwordExpiredRemind'];

  // Normalize empty strings to null for consistency
  String? normalizeEmpty(String? value) =>
      value?.isNotEmpty == true ? value : null;

  return (
    name: normalizeEmpty(body['givenName']),
    avatarFilename: normalizeEmpty(body['userPhoto']),
    email: normalizeEmpty(body['userMail']),
    passwordExpiresInDays: passwordExpiredRemind != null
        ? int.tryParse(passwordExpiredRemind)
        : null,
  );
}