authenticate method

Future<OdooSession> authenticate(
  1. String db,
  2. String login,
  3. String password
)

Authenticates user for given database. This call receives valid session on successful login which we be reused for future RPC calls.

Implementation

Future<OdooSession> authenticate(
    String db, String login, String password) async {
  final params = {'db': db, 'login': login, 'password': password};
  const headers = {'Content-type': 'application/json'};
  final uri = Uri.parse('$baseURL/web/session/authenticate');
  final body = json.encode({
    'jsonrpc': '2.0',
    'method': 'call',
    'params': params,
    'id': sha1.convert(utf8.encode(DateTime.now().toString())).toString()
  });
  try {
    if (_inRequestStreamActive) _inRequestStreamController.add(true);
    final response = await httpClient.post(uri, body: body, headers: headers);

    var result = json.decode(response.body);
    if (result['error'] != null) {
      if (result['error']['code'] == 100) {
        // session expired
        _setSessionId('');
        final err = result['error'].toString();
        throw OdooSessionExpiredException(err);
      } else {
        // Other error
        final err = result['error'].toString();
        throw OdooException(err);
      }
    }
    // Odoo 11 sets uid to False on failed login without any error message
    if (result['result'].containsKey('uid')) {
      if (result['result']['uid'] is bool) {
        throw OdooException('Authentication failed');
      }
    }

    _sessionId = OdooSession.fromSessionInfo(result['result']);
    // It will notify subscribers
    _updateSessionIdFromCookies(response, auth: true);

    if (_inRequestStreamActive) _inRequestStreamController.add(false);
    return _sessionId!;
  } catch (e) {
    if (_inRequestStreamActive) _inRequestStreamController.add(false);
    rethrow;
  }
}