Skip to content

Commit

Permalink
fix login with cookie
Browse files Browse the repository at this point in the history
stop displaying the encoded auth
  • Loading branch information
lamarios committed Sep 14, 2024
1 parent ef350ee commit 2d3c12f
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 48 deletions.
67 changes: 34 additions & 33 deletions lib/service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ class Service {
return db.getSettings(useProxySettingName)?.value == 'true';
}

Future<ServerRequest> buildUrl(
Future<ServerRequest> buildRequest(
String baseUrl, {
Map<String, String>? pathParams,
Map<String, String?>? query,
Expand Down Expand Up @@ -163,7 +163,7 @@ class Service {
if (forceJson) {
headers['Content-Type'] = 'application/json';
}

print(headers);
return ServerRequest(uri: uri, headers: headers);
} catch (err) {
log.severe('Couldn\'t build url', err);
Expand All @@ -174,10 +174,9 @@ class Service {
handleErrors(Response response) {}

Future<Video> getVideo(String videoId) async {
var req = await buildUrl(urlGetVideo, pathParams: {':id': videoId});
req.headers['Content-Type'] = 'application/json; charset=utf-16';
final response = await http.get(req.uri,
headers: {'Content-Type': 'application/json; charset=utf-16'});
var req = await buildRequest(urlGetVideo,
pathParams: {':id': videoId}, utf16: true);
final response = await http.get(req.uri, headers: req.headers);

var video = Video.fromJson(handleResponse(response));
await DeArrow.processVideos([video]);
Expand All @@ -187,12 +186,14 @@ class Service {
}

Future<String> loginWithCookies(
String serverUrl, String username, String password) async {
String serverUrl, String username, String password,
{Map<String, String>? headers}) async {
try {
String url = '$serverUrl/login?type=invidious';
var map = {'email': username, 'password': password};

final response = await http.post(Uri.parse(url), body: map);
final response =
await http.post(Uri.parse(url), body: map, headers: headers);
if (response.statusCode == 302 &&
response.headers.containsKey('set-cookie')) {
// we have a cookie to parse
Expand Down Expand Up @@ -258,7 +259,7 @@ class Service {
query.putIfAbsent('type', () => type);
}

var req = await buildUrl(urlGetTrending, query: query);
var req = await buildRequest(urlGetTrending, query: query);
final response = await http.get(req.uri, headers: req.headers);

Iterable i = handleResponse(response);
Expand All @@ -268,7 +269,7 @@ class Service {
}

Future<List<VideoInList>> getPopular() async {
var req = await buildUrl(urlGetPopular);
var req = await buildRequest(urlGetPopular);
final response = await http.get(req.uri, headers: req.headers);
Iterable i = handleResponse(response);
var list = List<VideoInList>.from(i.map((e) => VideoInList.fromJson(e)));
Expand All @@ -283,7 +284,7 @@ class Service {
SearchDate date = SearchDate.any,
SearchDuration duration = SearchDuration.any}) async {
String countryCode = db.getSettings(browsingCountry)?.value ?? 'US';
final req = await buildUrl(urlSearch, query: {
final req = await buildRequest(urlSearch, query: {
'q': Uri.encodeQueryComponent(query),
'type': type?.name,
'page': page?.toString() ?? '1',
Expand Down Expand Up @@ -322,7 +323,7 @@ class Service {
Future<UserFeed> getUserFeed(
{int? maxResults, int? page, bool saveLastSeen = true}) async {
// for background service to be able to use
final req = await buildUrl(urlGetUserFeed,
final req = await buildRequest(urlGetUserFeed,
query: {
'max_results': maxResults?.toString(),
'page': page?.toString()
Expand Down Expand Up @@ -396,7 +397,7 @@ class Service {

Future<SearchSuggestion> getSearchSuggestion(String query) async {
if (query.isEmpty) return SearchSuggestion(query, []);
var request = await buildUrl(urlSearchSuggestions,
var request = await buildRequest(urlSearchSuggestions,
query: {"q": Uri.encodeQueryComponent(query)});
final response = await http.get(request.uri, headers: request.headers);
SearchSuggestion search =
Expand Down Expand Up @@ -443,7 +444,7 @@ class Service {

Future<bool> subscribe(String channelId) async {
if (!await isLoggedIn()) return false;
final req = await buildUrl(urlAddDeleteSubscriptions,
final req = await buildRequest(urlAddDeleteSubscriptions,
pathParams: {":ucid": channelId}, authenticated: true);

final response = await http.post(req.uri, headers: req.headers);
Expand All @@ -459,7 +460,7 @@ class Service {
Future<bool> unSubscribe(String channelId) async {
if (!await isLoggedIn()) return false;

final req = await buildUrl(urlAddDeleteSubscriptions,
final req = await buildRequest(urlAddDeleteSubscriptions,
pathParams: {":ucid": channelId}, authenticated: true);

final response = await http.delete(req.uri, headers: req.headers);
Expand All @@ -483,7 +484,7 @@ class Service {
Future<List<Subscription>> getSubscriptions() async {
if (!await isLoggedIn()) return [];

var req = await buildUrl(urlGetSubscriptions, authenticated: true);
var req = await buildRequest(urlGetSubscriptions, authenticated: true);

final response = await http.get(req.uri, headers: req.headers);
Iterable i = handleResponse(response);
Expand All @@ -500,7 +501,7 @@ class Service {
if (sortBy != null) queryStr.putIfAbsent('sort_by', () => sortBy);
if (source != null) queryStr.putIfAbsent('source', () => source);

var req = await buildUrl(urlGetComments,
var req = await buildRequest(urlGetComments,
pathParams: {':id': videoId}, query: queryStr);
final response = await http.get(req.uri, headers: req.headers);
return VideoComments.fromJson(handleResponse(response));
Expand All @@ -509,7 +510,7 @@ class Service {
Future<Channel> getChannel(String channelId) async {
// sometimes the api gives the channel with /channel/<channelid> format
channelId = channelId.replaceAll("/channel/", '');
var req = await buildUrl(urlGetChannel,
var req = await buildRequest(urlGetChannel,
pathParams: {':id': channelId}, utf16: true);

final response = await http.get(req.uri, headers: req.headers);
Expand All @@ -529,7 +530,7 @@ class Service {
String channelId, String? continuation,
{bool saveLastSeen = true,
ChannelSortBy sortBy = ChannelSortBy.newest}) async {
final req = await buildUrl(urlGetChannelVideos,
final req = await buildRequest(urlGetChannelVideos,
pathParams: {':id': channelId},
query: {
'continuation': continuation,
Expand All @@ -552,7 +553,7 @@ class Service {

Future<VideosWithContinuation> getChannelStreams(
String channelId, String? continuation) async {
final req = await buildUrl(urlGetChannelStreams,
final req = await buildRequest(urlGetChannelStreams,
pathParams: {':id': channelId},
query: {'continuation': continuation},
utf16: true);
Expand All @@ -567,7 +568,7 @@ class Service {

Future<VideosWithContinuation> getChannelShorts(
String channelId, String? continuation) async {
final req = await buildUrl(urlGetChannelShorts,
final req = await buildRequest(urlGetChannelShorts,
pathParams: {':id': channelId},
query: {'continuation': continuation},
utf16: true);
Expand All @@ -582,7 +583,7 @@ class Service {

Future<List<Playlist>> getUserPlaylists({bool postProcessing = true}) async {
try {
var req = await buildUrl(urlGetUserPlaylists, authenticated: true);
var req = await buildRequest(urlGetUserPlaylists, authenticated: true);

final response = await http.get(req.uri, headers: req.headers);
Iterable i = handleResponse(response);
Expand All @@ -600,7 +601,7 @@ class Service {

Future<ChannelPlaylists> getChannelPlaylists(String channelId,
{String? continuation}) async {
final req = await buildUrl(urlGetChannelPlaylists,
final req = await buildRequest(urlGetChannelPlaylists,
pathParams: {':id': channelId}, query: {'continuation': continuation});

final response = await http.get(req.uri, headers: req.headers);
Expand All @@ -612,7 +613,7 @@ class Service {
}

Future<String?> createPlayList(String name, String type) async {
var req = await buildUrl(urlPostUserPlaylists,
var req = await buildRequest(urlPostUserPlaylists,
authenticated: true, forceJson: true);

Map<String, String> body = {
Expand All @@ -629,7 +630,7 @@ class Service {
}

Future<void> addVideoToPlaylist(String playListId, String videoId) async {
var req = await buildUrl(urlPostUserPlaylistVideo,
var req = await buildRequest(urlPostUserPlaylistVideo,
pathParams: {":id": playListId}, authenticated: true, forceJson: true);

Map<String, String> body = {
Expand All @@ -642,7 +643,7 @@ class Service {
}

Future<void> deleteUserPlaylist(String playListId) async {
var req = await buildUrl(urlDeleteUserPlaylist,
var req = await buildRequest(urlDeleteUserPlaylist,
pathParams: {":id": playListId}, authenticated: true, forceJson: true);

final response = await http.delete(req.uri, headers: req.headers);
Expand All @@ -651,7 +652,7 @@ class Service {

Future<void> deleteUserPlaylistVideo(
String playListId, String indexId) async {
final req = await buildUrl(urlDeleteUserPlaylistVideo,
final req = await buildRequest(urlDeleteUserPlaylistVideo,
pathParams: {':id': playListId, ':index': indexId},
authenticated: true,
forceJson: true);
Expand All @@ -661,7 +662,7 @@ class Service {
}

Future<List<String>> getUserHistory(int page, int maxResults) async {
final req = await buildUrl(urlGetClearHistory,
final req = await buildRequest(urlGetClearHistory,
query: {'page': page.toString(), 'max_results': maxResults.toString()},
authenticated: true,
forceJson: true);
Expand All @@ -688,22 +689,22 @@ class Service {
}

Future<void> clearUserHistory() async {
var req = await buildUrl(urlGetClearHistory,
var req = await buildRequest(urlGetClearHistory,
authenticated: true, forceJson: true);

final response = await http.delete(req.uri, headers: req.headers);
handleResponse(response);
}

Future<void> deleteFromUserHistory(String videoId) async {
var req = await buildUrl(urlAddDeleteHistory,
var req = await buildRequest(urlAddDeleteHistory,
pathParams: {':id': videoId}, authenticated: true, forceJson: true);
final response = await http.delete(req.uri, headers: req.headers);
handleResponse(response);
}

Future<void> addToUserHistory(String videoId) async {
var req = await buildUrl(urlAddDeleteHistory,
var req = await buildRequest(urlAddDeleteHistory,
pathParams: {':id': videoId}, authenticated: true, forceJson: true);

final response = await http.post(req.uri, headers: req.headers);
Expand Down Expand Up @@ -747,7 +748,7 @@ class Service {

Future<Playlist> getPublicPlaylists(String playlistId,
{int? page, bool saveLastSeen = true}) async {
final req = await buildUrl(urlGetPublicPlaylist,
final req = await buildRequest(urlGetPublicPlaylist,
pathParams: {':id': playlistId}, query: {'page': page?.toString()});

final response = await http.get(req.uri, headers: req.headers);
Expand All @@ -765,7 +766,7 @@ class Service {
}

Future<Playlist> getUserPlaylist(String playlistId) async {
final req = await buildUrl(urlGetUserPlaylist,
final req = await buildRequest(urlGetUserPlaylist,
pathParams: {':id': playlistId}, authenticated: true);

final response = await http.get(req.uri, headers: req.headers);
Expand Down
7 changes: 6 additions & 1 deletion lib/settings/states/server_settings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ class ServerSettingsCubit extends Cubit<ServerSettingsState> {

Future<void> logInWithCookie(String username, String password) async {
var s = state.server.copyWith();
String cookie = await service.loginWithCookies(s.url, username, password);
String cookie = await service.loginWithCookies(s.url, username, password,
headers: s.customHeaders);
s = s.copyWith(sidCookie: cookie);
await db.upsertServer(s);
if (s.inUse) {
Expand Down Expand Up @@ -106,4 +107,8 @@ class ServerSettingsState with _$ServerSettingsState {
const factory ServerSettingsState(
{required Server server,
@Default(false) bool canDelete}) = _ServerSettingsState;

const ServerSettingsState._();

bool get hasBasicAuth => server.customHeaders.containsKey("Authorization");
}
8 changes: 5 additions & 3 deletions lib/settings/states/server_settings.freezed.dart
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,10 @@ class __$$ServerSettingsStateImplCopyWithImpl<$Res>

/// @nodoc
class _$ServerSettingsStateImpl implements _ServerSettingsState {
class _$ServerSettingsStateImpl extends _ServerSettingsState {
const _$ServerSettingsStateImpl(
{required this.server, this.canDelete = false});
{required this.server, this.canDelete = false})
: super._();

@override
final Server server;
Expand Down Expand Up @@ -151,10 +152,11 @@ class _$ServerSettingsStateImpl implements _ServerSettingsState {
this, _$identity);
}

abstract class _ServerSettingsState implements ServerSettingsState {
abstract class _ServerSettingsState extends ServerSettingsState {
const factory _ServerSettingsState(
{required final Server server,
final bool canDelete}) = _$ServerSettingsStateImpl;
const _ServerSettingsState._() : super._();

@override
Server get server;
Expand Down
29 changes: 18 additions & 11 deletions lib/settings/views/screens/manage_single_server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ class ManageSingleServerScreen extends StatelessWidget {
leading: server.authToken?.isNotEmpty ?? false
? const Icon(Icons.check)
: const Icon(Icons.token),
enabled: !isLoggedIn,
enabled: !isLoggedIn && !state.hasBasicAuth,
title: Text(locals.tokenLogin),
value: Text(server.authToken?.isNotEmpty ?? false
? locals.loggedIn
Expand Down Expand Up @@ -222,16 +222,23 @@ class ManageSingleServerScreen extends StatelessWidget {
],
),
tiles: [
...state.server.customHeaders.keys
.map((k) => SettingsTile(
title: Text(k),
description: Text(
state.server.customHeaders[k] ?? ''),
trailing: IconButton(
icon: const Icon(Icons.delete),
onPressed: () => cubit.removeHeader(k),
),
)),
...state.server.customHeaders.keys.map((k) {
String value =
state.server.customHeaders[k] ?? '';
if (k == 'Authorization') {
value = value.replaceAll(
value.replaceAll("Basic ", ""), "········");
}

return SettingsTile(
title: Text(k),
description: Text(value),
trailing: IconButton(
icon: const Icon(Icons.delete),
onPressed: () => cubit.removeHeader(k),
),
);
}),
SettingsTile(
title: Text(locals.addBasicAuth),
leading: const Icon(Icons.key),
Expand Down

0 comments on commit 2d3c12f

Please sign in to comment.