Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: basic auth #6

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion .github/workflows/analyze.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ jobs:
- uses: actions/checkout@v2
- uses: subosito/flutter-action@main
with:
flutter-version: 3.0.1
flutter-version: 3.0.4
cache: true
- run: flutter pub get
- name: Analyze the code
Expand All @@ -19,3 +19,19 @@ jobs:
fatal-warnings: true
annotate: true
annotate-only: false
Coverage:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: subosito/flutter-action@main
with:
flutter-version: 3.0.4
cache: true
- name: Run tests and generate coverage
run: |
flutter pub get
flutter test --coverage
- name: Upload to Codecov
uses: codecov/codecov-action@v2
with:
file: ./coverage/lcov.info
10 changes: 5 additions & 5 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- uses: actions/checkout@v2
- uses: subosito/flutter-action@main
with:
flutter-version: 3.0.1
flutter-version: 3.0.4
cache: true
- name: Build
run: flutter build appbundle
Expand All @@ -30,7 +30,7 @@ jobs:
- uses: actions/checkout@v2
- uses: subosito/flutter-action@main
with:
flutter-version: 3.0.1
flutter-version: 3.0.4
cache: true
- name: Build
run: flutter build apk
Expand All @@ -47,10 +47,10 @@ jobs:
- uses: actions/checkout@v2
- uses: subosito/flutter-action@main
with:
flutter-version: 3.0.1
flutter-version: 3.0.4
cache: true
- name: Build
run: |
run: |
flutter build ios --no-codesign
- name: Upload File
uses: actions/upload-artifact@v2
Expand Down Expand Up @@ -78,7 +78,7 @@ jobs:
- uses: actions/checkout@v2
- uses: subosito/flutter-action@main
with:
flutter-version: 3.0.1
flutter-version: 3.0.4
cache: true
- name: Install dependencies
if: ${{ runner.os == 'Linux' }}
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,5 @@ app.*.map.json
/android/app/debug
/android/app/profile
/android/app/release

coverage/lcov.info
2 changes: 1 addition & 1 deletion .gitpod.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
FROM gitpod/workspace-full-vnc:2022-05-17-12-26-08
SHELL ["/bin/bash", "-c"]
ENV ANDROID_HOME=$HOME/androidsdk \
FLUTTER_VERSION=3.0.1-stable \
FLUTTER_VERSION=3.0.4-stable \
QTWEBENGINE_DISABLE_SANDBOX=1
ENV PATH="$HOME/flutter/bin:$ANDROID_HOME/emulator:$ANDROID_HOME/tools:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$PATH"

Expand Down
3 changes: 3 additions & 0 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,8 @@ linter:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule

analyzer:
errors:
todo: ignore
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
3 changes: 3 additions & 0 deletions lib/src/api/api.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export 'api_http_client.dart';
export 'api_response.dart';
export 'code.dart';
108 changes: 108 additions & 0 deletions lib/src/api/api_http_client.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import 'package:http/http.dart' as http;
import 'package:lipoic/src/api/api_response.dart';
import 'package:lipoic/src/config/config.dart';

class HttpClient {
final String baseUrl;
final http.Client _client;

HttpClient({required this.baseUrl, http.Client? client})
: _client = client ?? http.Client();

/// Development environment client
factory HttpClient.dev() =>
HttpClient(baseUrl: 'https://lipoic-test-server.herokuapp.com');

// TODO: change the url to api.lipoic.org
/// Production environment client
factory HttpClient.prod() =>
HttpClient(baseUrl: 'https://lipoic-server.herokuapp.com');

Future<Response<T>> _request<T>(
{required String method,
required String path,
Map<String, dynamic>? query,
Object? body,
String? token,
Map<String, String> headers = const {}}) async {
token ??= appConfig.token;
final Uri uri =
Uri.parse(baseUrl + (path.startsWith('/') ? path : '/$path')).replace(
query: query?.entries
.where((e) => e.value != null)
.map((e) => '${e.key}=${e.value}')
.join('&'));

final http.Response response;
headers.addAll({
'Content-Type': 'application/json',
'Accept': 'application/json',
if (token != null) 'Authorization': 'Bearer $token',
'User-Agent': 'RPMTW-Application',
});

if (method == 'GET') {
response = await _client.get(uri, headers: headers);
} else if (method == 'POST') {
response = await _client.post(uri, headers: headers, body: body);
} else if (method == 'PATCH') {
response = await _client.patch(uri, headers: headers, body: body);
} else if (method == 'DELETE') {
response = await _client.delete(uri, headers: headers, body: body);
} else {
throw Exception('Invalid method: $method');
}

return Response.fromJson(response.body);
}

Future<Response<T>> get<T>(String path,
{Map<String, dynamic>? query,
String? token,
Map<String, String> headers = const {}}) =>
_request<T>(
method: 'GET',
path: path,
query: query,
token: token,
headers: headers);

Future<Response<T>> post<T>(String path,
{Map<String, dynamic>? query,
Object? body,
String? token,
Map<String, String> headers = const {}}) =>
_request<T>(
method: 'POST',
path: path,
query: query,
body: body,
token: token,
headers: headers);

Future<Response<T>> patch<T>(String path,
{Map<String, dynamic>? query,
Object? body,
String? token,
Map<String, String> headers = const {}}) =>
_request<T>(
method: 'PATCH',
path: path,
query: query,
body: body,
token: token,
headers: headers);

Future<Response<T>> delete<T>(String path,
{Map<String, dynamic>? query,
Object? body,
String? token,
Map<String, String> headers = const {}}) =>
_request<T>(
method: 'DELETE',
path: path,
query: query,
body: body,
token: token,
headers: headers);
}
55 changes: 55 additions & 0 deletions lib/src/api/api_response.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import 'dart:convert';

import 'package:lipoic/src/api/code.dart';

class Response<T> {
final Code code;
final String message;
final T? data;

const Response({
required this.code,
required this.message,
this.data,
});

Map<String, dynamic> toMap() {
return {
'code': code.value,
'message': message,
'data': data,
};
}

factory Response.fromMap(Map<String, dynamic> map) {
return Response<T>(
code: Code.values.firstWhere((value) => value == map['code']),
message: map['message'],
data: map['data'] != null
? T.noSuchMethod(
Invocation.method(const Symbol('fromMap'), map['data']))
: null,
);
}

String toJson() => json.encode(toMap());

factory Response.fromJson(String source) =>
Response.fromMap(json.decode(source));

@override
String toString() => 'Response(code: $code, message: $message, data: $data)';

@override
bool operator ==(Object other) {
if (identical(this, other)) return true;

return other is Response<T> &&
other.code == code &&
other.message == message &&
other.data == data;
}

@override
int get hashCode => code.hashCode ^ message.hashCode ^ data.hashCode;
}
35 changes: 35 additions & 0 deletions lib/src/api/code.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// ignore_for_file: constant_identifier_names

/// Lipoic API response code.
/// Also see https://api-docs.lipoic.org/router/data/code/struct.Code.html
enum Code {
/// OK.
OK(200),

/// Resource not found.
NotFound(404),

/// OAuth auth code error.
OAuthCodeError(1),

/// OAuth get user info error.
OAuthGetUserInfoError(2),

/// User not found error.
LoginUserNotFoundError(3),

/// Input password error.
LoginPasswordError(4),

/// This email is already registered.
SignUpEmailAlreadyRegistered(5),

/// This code is invalid.
VerifyEmailError(6),

/// This token is invalid.
AuthError(7);

const Code(this.value);
final int value;
}
3 changes: 3 additions & 0 deletions lib/src/config/config_storage.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,7 @@ class ConfigStorage {

bool get init => ConfigHelper.get('init') ?? false;
set init(bool value) => ConfigHelper.set('init', value);

String? get token => ConfigHelper.get('token');
set token(String? value) => ConfigHelper.set('token', value);
}
9 changes: 8 additions & 1 deletion pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ packages:
name: convert
url: "https://pub.dartlang.org"
source: hosted
version: "3.0.1"
version: "3.0.4"
crypto:
dependency: transitive
description:
Expand Down Expand Up @@ -268,6 +268,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.3"
http:
dependency: "direct main"
description:
name: http
url: "https://pub.dartlang.org"
source: hosted
version: "0.13.4"
http_multi_server:
dependency: transitive
description:
Expand Down
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ dependencies:
font_awesome_flutter: ^10.1.0
hive: ^2.2.1
path_provider: ^2.0.10
http: ^0.13.4

dev_dependencies:
flutter_test:
Expand Down
17 changes: 17 additions & 0 deletions test/config/config_helper_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:lipoic/src/config/config.dart';

void main() {
setUpAll(() {
return ConfigHelper.init();
});

test('set value', () {
const key = 'key';
const value = 'value';

ConfigHelper.set(key, value);

expect(ConfigHelper.get(key), value);
});
}
1 change: 0 additions & 1 deletion test/widget_test.dart

This file was deleted.