How to get AutoRefreshingAuthClient from AuthClient without any service account (Google Auth)

Viewed 165

I need an AutoRefreshingAuthClient to use gsheet to play with authenticated users Google Sheet. I can get AuthClient using google_sign_in package.

So, How can I get AutoRefreshingAuthClient from AuthClient in a flutter application without any service account?

The reason I don't want to use a Service Account is, If I use a Service Account, all files are saved into this Service Account. But, I want to read, write and use Google Sheet from the authenticated user's account.

1 Answers

I ended up using googleapis instead. Seems like gsheets was made to work specifically with Service Accounts so even if you create a valid AutoRefreshingAuthClient it'll check to see if it's a Service Account.

Here's how I did it with the SheetsApi (The GoogleAuthClient class was found after a lot of searching on GitHub and multiple users had the same thing):

    import 'package:http/http.dart' as http;
    
    class GoogleAuthClient extends http.BaseClient {
      final Map<String, String> _headers;
    
      final http.Client _client = new http.Client();
    
      GoogleAuthClient(this._headers);
    
      Future<http.StreamedResponse> send(http.BaseRequest request) {
        return _client.send(request..headers.addAll(_headers));
      }
    }
    
    final client = GoogleAuthClient((await _googleSignIn.currentUser.authHeaders));
    
    _SheetApi = sheets.SheetsApi(client);

There is as decent amount of overhead on our side with SheetsApi compared to GSheets. Like appending rows or simply naming your Spreadsheet requires more lines of code and/or objects:


    // Sheet creation
    sheets.Spreadsheet request = sheets.Spreadsheet.fromJson({
    'properties': {
        'title': "$title",
      },
    });
    sheets.Spreadsheet sh =  getSheetApi().spreadsheets.create(request));
    
    // Add first row
    List<String> row = [...];
    getSheetApi().spreadsheets.values.append(createSheetRows([columns]), sh.spreadsheetId, "Sheet1!$startLetter:$endLetter",
              valueInputOption: 'USER_ENTERED');

...

 static sheets.ValueRange createSheetRows(List<List<String>> row){
    return sheets.ValueRange.fromJson({
      "values": row,
      "majorDimension": "ROWS"
    });
 }

 static sheets.ValueRange createSheetRow(List<String> row){
    return createSheetRows([row]);
 }

Related