mirror of
https://github.com/SyncrowIOT/web.git
synced 2025-07-10 07:07:19 +00:00
dio and login functions
This commit is contained in:
@ -1,10 +1,14 @@
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:syncrow_web/pages/home/view/home_page.dart';
|
||||
import 'package:syncrow_web/pages/auth/view/login_page.dart';
|
||||
import 'package:syncrow_web/services/locator.dart';
|
||||
|
||||
void main() {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
initialSetup();
|
||||
runApp(const MyApp());
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
const MyApp({super.key});
|
||||
@override
|
||||
@ -23,7 +27,7 @@ class MyApp extends StatelessWidget {
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
|
||||
useMaterial3: true,
|
||||
),
|
||||
home: const HomePage(),
|
||||
home: const LoginPage(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -1,12 +1,41 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:syncrow_web/pages/auth/bloc/login_event.dart';
|
||||
import 'package:syncrow_web/pages/auth/bloc/login_state.dart';
|
||||
import 'package:syncrow_web/pages/auth/model/login_with_email_model.dart';
|
||||
import 'package:syncrow_web/pages/auth/model/token.dart';
|
||||
import 'package:syncrow_web/pages/auth/model/user_model.dart';
|
||||
import 'package:syncrow_web/services/auth_api.dart';
|
||||
import 'package:syncrow_web/utils/snack_bar.dart';
|
||||
|
||||
class LoginBloc extends Bloc<LoginEvent, LoginState> {
|
||||
LoginBloc() : super(LoginInitial()) {
|
||||
on<LoginButtonPressed>(_onPress);
|
||||
on<LoginButtonPressed>(_login);
|
||||
}
|
||||
|
||||
|
||||
final TextEditingController emailController = TextEditingController();
|
||||
final TextEditingController passwordController = TextEditingController();
|
||||
|
||||
String fullName = '';
|
||||
String email = '';
|
||||
String forgetPasswordEmail = '';
|
||||
String signUpPassword = '';
|
||||
String newPassword = '';
|
||||
String maskedEmail = '';
|
||||
String otpCode = '';
|
||||
|
||||
final loginFormKey = GlobalKey<FormState>();
|
||||
final signUpFormKey = GlobalKey<FormState>();
|
||||
final checkEmailFormKey = GlobalKey<FormState>();
|
||||
final createNewPasswordKey = GlobalKey<FormState>();
|
||||
static Token token = Token.emptyConstructor();
|
||||
static UserModel? user;
|
||||
|
||||
bool isPasswordVisible = false;
|
||||
bool showValidationMessage = false;
|
||||
|
||||
void _onPress(LoginButtonPressed event, Emitter<LoginState> emit) async {
|
||||
emit(LoginLoading());
|
||||
await Future.delayed(const Duration(seconds: 2));
|
||||
@ -16,4 +45,167 @@ class LoginBloc extends Bloc<LoginEvent, LoginState> {
|
||||
emit(const LoginFailure(error: 'Invalid credentials'));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/////////////////////////////////////VALIDATORS/////////////////////////////////////
|
||||
String? passwordValidator(String? value) {
|
||||
if (value != null) {
|
||||
if (value.isEmpty) {
|
||||
return 'Please enter your password';
|
||||
}
|
||||
if (value.isNotEmpty) {
|
||||
if (!RegExp(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$')
|
||||
.hasMatch(value)) {
|
||||
return 'Password must contain at least:\n - one uppercase letter.\n - one lowercase letter.\n - one number. \n - special character';
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String? fullNameValidator(String? value) {
|
||||
if (value == null) return 'Full name is required';
|
||||
|
||||
final withoutExtraSpaces = value.replaceAll(RegExp(r"\s+"), ' ').trim();
|
||||
|
||||
if (withoutExtraSpaces.length < 2 || withoutExtraSpaces.length > 30) {
|
||||
return 'Full name must be between 2 and 30 characters long';
|
||||
}
|
||||
|
||||
// Test if it contains anything but alphanumeric spaces and single quote
|
||||
|
||||
if (RegExp(r"/[^ a-zA-Z0-9-\']/").hasMatch(withoutExtraSpaces)) {
|
||||
return 'Only alphanumeric characters, space, dash and single quote are allowed';
|
||||
}
|
||||
|
||||
final parts = withoutExtraSpaces.split(' ');
|
||||
|
||||
if (parts.length < 2) return 'Full name must contain first and last names';
|
||||
|
||||
if (parts.length > 3) return 'Full name can at most contain 3 parts';
|
||||
|
||||
if (parts.any((part) => part.length < 2 || part.length > 30)) {
|
||||
return 'Full name parts must be between 2 and 30 characters long';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String? reEnterPasswordCheck(String? value) {
|
||||
passwordValidator(value);
|
||||
if (signUpPassword == value) {
|
||||
return null;
|
||||
} else {
|
||||
return 'Passwords do not match';
|
||||
}
|
||||
}
|
||||
|
||||
String? reEnterPasswordCheckForgetPass(String? value) {
|
||||
passwordValidator(value);
|
||||
if (newPassword == value) {
|
||||
return null;
|
||||
} else {
|
||||
return 'Passwords do not match';
|
||||
}
|
||||
}
|
||||
|
||||
String? emailAddressValidator(String? value) {
|
||||
if (value != null && value.isNotEmpty && value != "") {
|
||||
if (checkValidityOfEmail(value)) {
|
||||
return null;
|
||||
} else {
|
||||
return 'Please enter a valid email';
|
||||
}
|
||||
} else {
|
||||
return 'Email address is required';
|
||||
}
|
||||
}
|
||||
|
||||
bool checkValidityOfEmail(String? email) {
|
||||
if (email != null) {
|
||||
return RegExp(
|
||||
r"^[a-zA-Z0-9]+([.!#$%&'*+/=?^_`{|}~-]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([.-]?[a-zA-Z0-9]+)*\.[a-zA-Z0-9]{2,}$")
|
||||
.hasMatch(email);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
String maskEmail(String email) {
|
||||
final emailParts = email.split('@');
|
||||
if (emailParts.length != 2) return email;
|
||||
|
||||
final localPart = emailParts[0];
|
||||
final domainPart = emailParts[1];
|
||||
|
||||
if (localPart.length < 3) return email;
|
||||
|
||||
final start = localPart.substring(0, 2);
|
||||
final end = localPart.substring(localPart.length - 1);
|
||||
|
||||
final maskedLocalPart = '$start******$end';
|
||||
return '$maskedLocalPart@$domainPart';
|
||||
}
|
||||
|
||||
_login(LoginButtonPressed event, Emitter<LoginState> emit) async {
|
||||
emit(LoginLoading());
|
||||
try {
|
||||
if (event.username.isEmpty ||event.password.isEmpty) {
|
||||
CustomSnackBar.displaySnackBar('Please enter your credentials');
|
||||
emit(const LoginFailure(error: 'Something went wrong'));
|
||||
return;
|
||||
}
|
||||
|
||||
token = await AuthenticationAPI.loginWithEmail(
|
||||
model: LoginWithEmailModel(
|
||||
email: event.username,
|
||||
password: event.password,
|
||||
),
|
||||
);
|
||||
} catch (failure) {
|
||||
emit( LoginFailure(error: failure.toString()));
|
||||
return;
|
||||
}
|
||||
if (token.accessTokenIsNotEmpty) {
|
||||
debugPrint('token: ${token.accessToken}');
|
||||
FlutterSecureStorage storage = const FlutterSecureStorage();
|
||||
await storage.write(key: Token.loginAccessTokenKey, value: token.accessToken);
|
||||
|
||||
const FlutterSecureStorage().write(
|
||||
key: UserModel.userUuidKey,
|
||||
value: Token.decodeToken(token.accessToken)['uuid'].toString()
|
||||
);
|
||||
|
||||
user = UserModel.fromToken(token);
|
||||
emailController.clear();
|
||||
passwordController.clear();
|
||||
emit(LoginSuccess());
|
||||
} else {
|
||||
emit(const LoginFailure(error: 'Something went wrong'));
|
||||
}
|
||||
}
|
||||
|
||||
// signUp() async {
|
||||
// emit(LoginLoading());
|
||||
// final response;
|
||||
// try {
|
||||
// List<String> userFullName = fullName.split(' ');
|
||||
// response = await AuthenticationAPI.signUp(
|
||||
// model: SignUpModel(
|
||||
// email: email.toLowerCase(),
|
||||
// password: signUpPassword,
|
||||
// firstName: userFullName[0],
|
||||
// lastName: userFullName[1]),
|
||||
// );
|
||||
// } catch (failure) {
|
||||
// emit(AuthLoginError(message: failure.toString()));
|
||||
// return;
|
||||
// }
|
||||
// if (response) {
|
||||
// maskedEmail = maskEmail(email);
|
||||
// await sendOtp();
|
||||
// } else {
|
||||
// emit(AuthLoginError(message: 'Something went wrong'));
|
||||
// }
|
||||
// }
|
||||
|
||||
}
|
||||
|
23
lib/pages/auth/model/login_with_email_model.dart
Normal file
23
lib/pages/auth/model/login_with_email_model.dart
Normal file
@ -0,0 +1,23 @@
|
||||
class LoginWithEmailModel {
|
||||
final String email;
|
||||
final String password;
|
||||
|
||||
LoginWithEmailModel({
|
||||
required this.email,
|
||||
required this.password,
|
||||
});
|
||||
|
||||
factory LoginWithEmailModel.fromJson(Map<String, dynamic> json) {
|
||||
return LoginWithEmailModel(
|
||||
email: json['email'],
|
||||
password: json['password'],
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'email': email,
|
||||
'password': password,
|
||||
};
|
||||
}
|
||||
}
|
29
lib/pages/auth/model/signup_model.dart
Normal file
29
lib/pages/auth/model/signup_model.dart
Normal file
@ -0,0 +1,29 @@
|
||||
class SignUpModel {
|
||||
final String email;
|
||||
final String password;
|
||||
final String firstName;
|
||||
final String lastName;
|
||||
|
||||
SignUpModel(
|
||||
{required this.email,
|
||||
required this.password,
|
||||
required this.firstName,
|
||||
required this.lastName});
|
||||
|
||||
factory SignUpModel.fromJson(Map<String, dynamic> json) {
|
||||
return SignUpModel(
|
||||
email: json['email'],
|
||||
password: json['password'],
|
||||
firstName: json['firstName'],
|
||||
lastName: json['lastName']);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'email': email,
|
||||
'password': password,
|
||||
'firstName': firstName,
|
||||
'lastName': lastName,
|
||||
};
|
||||
}
|
||||
}
|
69
lib/pages/auth/model/token.dart
Normal file
69
lib/pages/auth/model/token.dart
Normal file
@ -0,0 +1,69 @@
|
||||
import 'dart:convert';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:syncrow_web/utils/const.dart';
|
||||
|
||||
class Token {
|
||||
static const String loginAccessTokenKey = 'accessToken';
|
||||
static const String loginRefreshTokenKey = 'refreshToken';
|
||||
final String accessToken;
|
||||
final String refreshToken;
|
||||
final String sessionId;
|
||||
final int iat;
|
||||
final int exp;
|
||||
|
||||
Token.emptyConstructor()
|
||||
: accessToken = '',
|
||||
refreshToken = '',
|
||||
sessionId = '',
|
||||
iat = 0,
|
||||
exp = 0;
|
||||
|
||||
bool get accessTokenIsNotEmpty => accessToken.isNotEmpty;
|
||||
|
||||
bool get refreshTokenIsNotEmpty => refreshToken.isNotEmpty;
|
||||
|
||||
bool get isNotEmpty => accessToken.isNotEmpty && refreshToken.isNotEmpty;
|
||||
|
||||
Token(
|
||||
this.accessToken,
|
||||
this.refreshToken,
|
||||
this.sessionId,
|
||||
this.iat,
|
||||
this.exp,
|
||||
);
|
||||
|
||||
Token.refreshToken(this.refreshToken)
|
||||
: accessToken = '',
|
||||
sessionId = '',
|
||||
iat = 0,
|
||||
exp = 0;
|
||||
|
||||
factory Token.fromJson(Map<String, dynamic> json) {
|
||||
//save token to secure storage
|
||||
var storage = const FlutterSecureStorage();
|
||||
storage.write(
|
||||
key: loginAccessTokenKey,
|
||||
value: json[loginAccessTokenKey] ?? '');
|
||||
storage.write(
|
||||
key: loginRefreshTokenKey,
|
||||
value: json[loginRefreshTokenKey] ?? '');
|
||||
//create token object ?
|
||||
return Token(
|
||||
json[loginAccessTokenKey] ?? '',
|
||||
json[loginRefreshTokenKey] ?? '', '', 0, 0);
|
||||
}
|
||||
|
||||
Map<String, String> refreshTokenToJson() =>
|
||||
{loginRefreshTokenKey: refreshToken};
|
||||
|
||||
Map<String, String> accessTokenToJson() => {loginAccessTokenKey: accessToken};
|
||||
|
||||
static Map<String, dynamic> decodeToken(String accessToken) {
|
||||
final parts = accessToken.split('.');
|
||||
if (parts.length != 3) {
|
||||
throw Exception('invalid access token');
|
||||
}
|
||||
final payload = decodeBase64(parts[1]);
|
||||
return json.decode(payload);
|
||||
}
|
||||
}
|
66
lib/pages/auth/model/user_model.dart
Normal file
66
lib/pages/auth/model/user_model.dart
Normal file
@ -0,0 +1,66 @@
|
||||
import 'package:syncrow_web/pages/auth/model/token.dart';
|
||||
|
||||
class UserModel {
|
||||
static String userUuidKey = 'userUuid';
|
||||
final String? uuid;
|
||||
final String? email;
|
||||
final String? name;
|
||||
final String? photoUrl;
|
||||
|
||||
final String? phoneNumber;
|
||||
|
||||
final bool? isEmailVerified;
|
||||
|
||||
final bool? isAgreementAccepted;
|
||||
|
||||
UserModel({
|
||||
required this.uuid,
|
||||
required this.email,
|
||||
required this.name,
|
||||
required this.photoUrl,
|
||||
required this.phoneNumber,
|
||||
required this.isEmailVerified,
|
||||
required this.isAgreementAccepted,
|
||||
});
|
||||
|
||||
factory UserModel.fromJson(Map<String, dynamic> json) {
|
||||
return UserModel(
|
||||
uuid: json['id'],
|
||||
email: json['email'],
|
||||
name: json['name'],
|
||||
photoUrl: json['photoUrl'],
|
||||
phoneNumber: json['phoneNumber'],
|
||||
isEmailVerified: json['isEmailVerified'],
|
||||
isAgreementAccepted: json['isAgreementAccepted'],
|
||||
);
|
||||
}
|
||||
|
||||
//uuid to json
|
||||
|
||||
//from token
|
||||
factory UserModel.fromToken(Token token) {
|
||||
Map<String, dynamic> tempJson = Token.decodeToken(token.accessToken);
|
||||
|
||||
return UserModel(
|
||||
uuid: tempJson['uuid'].toString(),
|
||||
email: tempJson['email'],
|
||||
name: null,
|
||||
photoUrl: null,
|
||||
phoneNumber: null,
|
||||
isEmailVerified: null,
|
||||
isAgreementAccepted: null,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': uuid,
|
||||
'email': email,
|
||||
'name': name,
|
||||
'photoUrl': photoUrl,
|
||||
'phoneNumber': phoneNumber,
|
||||
'isEmailVerified': isEmailVerified,
|
||||
'isAgreementAccepted': isAgreementAccepted,
|
||||
};
|
||||
}
|
||||
}
|
27
lib/pages/auth/model/verify_code.dart
Normal file
27
lib/pages/auth/model/verify_code.dart
Normal file
@ -0,0 +1,27 @@
|
||||
class VerifyPassCode {
|
||||
static const String verificationPhone = 'phone';
|
||||
static const String verificationPassCode = 'passCode';
|
||||
static const String verificationAgent = 'agent';
|
||||
static const String verificationDeviceId = 'deviceId';
|
||||
|
||||
final String phone;
|
||||
final String passCode;
|
||||
final String agent;
|
||||
final String deviceId;
|
||||
|
||||
VerifyPassCode(
|
||||
{required this.phone, required this.passCode, required this.agent, required this.deviceId});
|
||||
|
||||
factory VerifyPassCode.fromJson(Map<String, dynamic> json) => VerifyPassCode(
|
||||
phone: json[verificationPhone],
|
||||
passCode: json[verificationPassCode],
|
||||
agent: json[verificationAgent],
|
||||
deviceId: json[verificationDeviceId]);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
verificationPhone: phone,
|
||||
verificationPassCode: passCode,
|
||||
verificationAgent: agent,
|
||||
verificationDeviceId: deviceId,
|
||||
};
|
||||
}
|
@ -6,6 +6,7 @@ import 'package:syncrow_web/pages/auth/bloc/login_bloc.dart';
|
||||
import 'package:syncrow_web/pages/auth/bloc/login_event.dart';
|
||||
import 'package:syncrow_web/pages/auth/bloc/login_state.dart';
|
||||
import 'package:syncrow_web/pages/home/view/home_page.dart';
|
||||
import 'package:syncrow_web/utils/style.dart';
|
||||
|
||||
class LoginWebPage extends StatelessWidget {
|
||||
const LoginWebPage({super.key});
|
||||
@ -13,9 +14,6 @@ class LoginWebPage extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
// appBar: AppBar(
|
||||
// title: const Text('Login'),
|
||||
// ),
|
||||
body: BlocProvider(
|
||||
create: (context) => LoginBloc(),
|
||||
child: BlocConsumer<LoginBloc, LoginState>(
|
||||
@ -130,24 +128,7 @@ class LoginWebPage extends StatelessWidget {
|
||||
width: MediaQuery.sizeOf(context).width * 0.2,
|
||||
child: TextFormField(
|
||||
controller: _usernameController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Email',
|
||||
labelStyle: const TextStyle(color: Colors.white),
|
||||
hintText: 'username@gmail.com',
|
||||
hintStyle: const TextStyle(color: Colors.grey),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
borderSide: const BorderSide(color: Colors.white),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
borderSide: const BorderSide(color: Colors.white),
|
||||
),
|
||||
filled: true,
|
||||
fillColor: Colors.white,
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
vertical: 16.0, horizontal: 12.0),
|
||||
),
|
||||
decoration: textBoxDecoration()!.copyWith(hintText: 'Email'),
|
||||
style: const TextStyle(color: Colors.black),
|
||||
),
|
||||
),
|
||||
@ -169,24 +150,7 @@ class LoginWebPage extends StatelessWidget {
|
||||
width: MediaQuery.sizeOf(context).width * 0.2,
|
||||
child: TextFormField(
|
||||
controller: _passwordController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Password',
|
||||
labelStyle: const TextStyle(color: Colors.white),
|
||||
hintText: 'Password',
|
||||
hintStyle: const TextStyle(color: Colors.grey),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
borderSide: const BorderSide(color: Colors.white),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
borderSide: const BorderSide(color: Colors.white),
|
||||
),
|
||||
filled: true,
|
||||
fillColor: Colors.white,
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
vertical: 16.0, horizontal: 12.0),
|
||||
),
|
||||
decoration: textBoxDecoration()!.copyWith(hintText: 'Password' ,),
|
||||
style: const TextStyle(color: Colors.black),
|
||||
),
|
||||
),
|
||||
|
@ -73,7 +73,9 @@ class TreeWidget extends StatelessWidget {
|
||||
child: GraphView(
|
||||
graph: state.graph,
|
||||
algorithm: BuchheimWalkerAlgorithm(
|
||||
state.builder, TreeEdgeRenderer(state.builder)),
|
||||
state.builder,
|
||||
TreeEdgeRenderer(state.builder)
|
||||
),
|
||||
paint: Paint()
|
||||
..color = Colors.green
|
||||
..strokeWidth = 1
|
||||
@ -136,14 +138,50 @@ Widget rectangleWidget(String text, Node node, BuildContext blocContext) {
|
||||
);
|
||||
},
|
||||
child: Container(
|
||||
padding: EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
boxShadow: [
|
||||
BoxShadow(color: Colors.blue[100]!, spreadRadius: 1),
|
||||
],
|
||||
),
|
||||
child: Text(text)
|
||||
width: MediaQuery.of(blocContext).size.width*0.2,
|
||||
margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
|
||||
padding: EdgeInsets.all(20.0),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(10.0),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.grey.withOpacity(0.5),
|
||||
spreadRadius: 2,
|
||||
blurRadius: 5,
|
||||
offset: Offset(0, 3), // changes position of shadow
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const SizedBox(
|
||||
child: Icon(
|
||||
Icons.location_on,
|
||||
color: Colors.blue,
|
||||
size: 40.0,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10.0),
|
||||
SizedBox(
|
||||
child: Text(
|
||||
text,
|
||||
style: const TextStyle(
|
||||
fontSize: 24.0,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
Container(
|
||||
child: const Icon(
|
||||
Icons.add_circle_outline,
|
||||
color: Colors.grey,
|
||||
size: 24.0,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
10
lib/services/api/api_links_endpoints.dart
Normal file
10
lib/services/api/api_links_endpoints.dart
Normal file
@ -0,0 +1,10 @@
|
||||
abstract class ApiEndpoints {
|
||||
static const String baseUrl = 'https://syncrow.azurewebsites.net';
|
||||
// static const String baseUrl = 'http://100.107.182.63:4001'; //Localhost
|
||||
|
||||
////////////////////////////////////// Authentication ///////////////////////////////
|
||||
|
||||
static const String signUp = '$baseUrl/authentication/user/signup';
|
||||
static const String login = '$baseUrl/authentication/user/login';
|
||||
|
||||
}
|
76
lib/services/api/http_interceptor.dart
Normal file
76
lib/services/api/http_interceptor.dart
Normal file
@ -0,0 +1,76 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'dart:async';
|
||||
import 'package:syncrow_web/services/api/network_exception.dart';
|
||||
import 'package:syncrow_web/utils/snack_bar.dart';
|
||||
import 'api_links_endpoints.dart';
|
||||
|
||||
class HTTPInterceptor extends InterceptorsWrapper {
|
||||
List<String> headerExclusionList = [];
|
||||
|
||||
List<String> headerExclusionListOfAddedParameters = [
|
||||
ApiEndpoints.login,
|
||||
];
|
||||
@override
|
||||
void onResponse(Response response, ResponseInterceptorHandler handler) async {
|
||||
if (await validateResponse(response)) {
|
||||
super.onResponse(response, handler);
|
||||
} else {
|
||||
handler.reject(DioException(requestOptions: response.requestOptions, response: response));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
|
||||
var storage = const FlutterSecureStorage();
|
||||
// var token = await storage.read(key: Token.loginAccessTokenKey);
|
||||
// if (checkHeaderExclusionListOfAddedParameters(options.path)) {
|
||||
// options.headers.putIfAbsent(HttpHeaders.authorizationHeader, () => "Bearer $token");
|
||||
// }
|
||||
// options.headers['Authorization'] = 'Bearer ${'${token!}123'}';
|
||||
super.onRequest(options, handler);
|
||||
}
|
||||
|
||||
@override
|
||||
void onError(DioException err, ErrorInterceptorHandler handler) async {
|
||||
ServerFailure failure = ServerFailure.fromDioError(err);
|
||||
if (failure.toString().isNotEmpty) {
|
||||
CustomSnackBar.displaySnackBar(failure.toString());
|
||||
}
|
||||
var storage = const FlutterSecureStorage();
|
||||
// var token = await storage.read(key: Token.loginAccessTokenKey);
|
||||
// if (err.response?.statusCode == 401 && token != null) {
|
||||
// await AuthCubit.get(NavigationService.navigatorKey.currentContext!).logout();
|
||||
// }
|
||||
super.onError(err, handler);
|
||||
}
|
||||
|
||||
/// Validates the response and returns true if it is successful (status code 2xx).
|
||||
Future<bool> validateResponse(Response response) async {
|
||||
if (response.statusCode != null) {
|
||||
if (response.statusCode! >= 200 && response.statusCode! < 300) {
|
||||
// If the response status code is within the successful range (2xx),
|
||||
// return true indicating a successful response.
|
||||
return true;
|
||||
} else {
|
||||
// If the response status code is not within the successful range (2xx),
|
||||
// return false indicating an unsuccessful response.
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// If the response status code is null, return false indicating an unsuccessful response.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
checkHeaderExclusionListOfAddedParameters(String path) {
|
||||
bool shouldAddHeader = true;
|
||||
|
||||
for (var urlConstant in headerExclusionListOfAddedParameters) {
|
||||
if (path.contains(urlConstant)) {
|
||||
shouldAddHeader = false;
|
||||
}
|
||||
}
|
||||
return shouldAddHeader;
|
||||
}
|
||||
}
|
134
lib/services/api/http_service.dart
Normal file
134
lib/services/api/http_service.dart
Normal file
@ -0,0 +1,134 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:syncrow_web/services/api/api_links_endpoints.dart';
|
||||
import 'package:syncrow_web/services/api/http_interceptor.dart';
|
||||
import 'package:syncrow_web/services/locator.dart';
|
||||
|
||||
class HTTPService {
|
||||
final Dio client = serviceLocator.get<Dio>();
|
||||
|
||||
// final navigatorKey = GlobalKey<NavigatorState>();
|
||||
|
||||
String certificateString = "";
|
||||
|
||||
static Dio setupDioClient() {
|
||||
Dio client = Dio(
|
||||
BaseOptions(
|
||||
baseUrl: ApiEndpoints.baseUrl,
|
||||
receiveDataWhenStatusError: true,
|
||||
followRedirects: false,
|
||||
connectTimeout: const Duration(seconds: 30),
|
||||
receiveTimeout: const Duration(seconds: 30),
|
||||
),
|
||||
);
|
||||
|
||||
client.interceptors.add(serviceLocator.get<HTTPInterceptor>());
|
||||
return client;
|
||||
}
|
||||
|
||||
Future<T> get<T>({
|
||||
required String path,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
required T Function(dynamic) expectedResponseModel,
|
||||
bool showServerMessage = true,
|
||||
}) async {
|
||||
try {
|
||||
final response = await client.get(
|
||||
path,
|
||||
queryParameters: queryParameters,
|
||||
);
|
||||
return expectedResponseModel(response.data);
|
||||
} catch (error) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<T> post<T>(
|
||||
{required String path,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
Options? options,
|
||||
dynamic body,
|
||||
bool showServerMessage = true,
|
||||
required T Function(dynamic) expectedResponseModel}) async {
|
||||
try {
|
||||
final response = await client.post(
|
||||
path,
|
||||
data: body,
|
||||
queryParameters: queryParameters,
|
||||
options: options,
|
||||
);
|
||||
return expectedResponseModel(response.data);
|
||||
} catch (error) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<T> patch<T>(
|
||||
{required String path,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
dynamic body,
|
||||
required T Function(dynamic) expectedResponseModel}) async {
|
||||
try {
|
||||
final response = await client.patch(
|
||||
path,
|
||||
data: body,
|
||||
queryParameters: queryParameters,
|
||||
);
|
||||
return expectedResponseModel(response.data);
|
||||
} catch (error) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<T> put<T>(
|
||||
{required String path,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
dynamic body,
|
||||
required T Function(dynamic) expectedResponseModel}) async {
|
||||
try {
|
||||
final response = await client.put(
|
||||
path,
|
||||
data: body,
|
||||
queryParameters: queryParameters,
|
||||
);
|
||||
return expectedResponseModel(response.data);
|
||||
} catch (error) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<T> download<T>(
|
||||
{required String path,
|
||||
required String savePath,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
required T Function(dynamic) expectedResponseModel}) async {
|
||||
try {
|
||||
final response = await client.download(
|
||||
path,
|
||||
savePath,
|
||||
onReceiveProgress: (current, total) {},
|
||||
);
|
||||
|
||||
return expectedResponseModel(response.data);
|
||||
// return expectedResponseModel(response.data);
|
||||
} catch (error) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<T> delete<T>({
|
||||
required String path,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
required T Function(dynamic) expectedResponseModel,
|
||||
bool showServerMessage = true,
|
||||
}) async {
|
||||
try {
|
||||
final response = await client.delete(
|
||||
path,
|
||||
queryParameters: queryParameters,
|
||||
);
|
||||
return expectedResponseModel(response.data);
|
||||
} catch (error) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
11
lib/services/api/my_http_overrides.dart
Normal file
11
lib/services/api/my_http_overrides.dart
Normal file
@ -0,0 +1,11 @@
|
||||
import 'dart:io';
|
||||
|
||||
// We use this class to skip the problem of SSL certification and solve the Image.network(url) issue
|
||||
class MyHttpOverrides extends HttpOverrides {
|
||||
@override
|
||||
HttpClient createHttpClient(SecurityContext? context) {
|
||||
return super.createHttpClient(context)
|
||||
..badCertificateCallback =
|
||||
(X509Certificate cert, String host, int port) => true;
|
||||
}
|
||||
}
|
74
lib/services/api/network_exception.dart
Normal file
74
lib/services/api/network_exception.dart
Normal file
@ -0,0 +1,74 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
abstract class Failure {
|
||||
final String errMessage;
|
||||
|
||||
Failure(this.errMessage);
|
||||
}
|
||||
|
||||
class ServerFailure extends Failure {
|
||||
ServerFailure(super.errMessage);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return errMessage;
|
||||
}
|
||||
|
||||
factory ServerFailure.fromDioError(DioException dioError) {
|
||||
switch (dioError.type) {
|
||||
case DioExceptionType.connectionTimeout:
|
||||
return ServerFailure("Connection timeout with the Server.");
|
||||
case DioExceptionType.sendTimeout:
|
||||
return ServerFailure("Send timeout with the Server.");
|
||||
|
||||
case DioExceptionType.receiveTimeout:
|
||||
return ServerFailure("Receive timeout with the Server.");
|
||||
|
||||
case DioExceptionType.badCertificate:
|
||||
return ServerFailure("Bad certificate!");
|
||||
|
||||
case DioExceptionType.badResponse:
|
||||
{
|
||||
// var document = parser.parse(dioError.response!.data.toString());
|
||||
// var message = document.body!.text;
|
||||
return ServerFailure.fromResponse(
|
||||
dioError.response!.statusCode!, dioError.response?.data['message'] ?? "Error");
|
||||
}
|
||||
case DioExceptionType.cancel:
|
||||
return ServerFailure("The request to ApiServer was canceled");
|
||||
|
||||
case DioExceptionType.connectionError:
|
||||
return ServerFailure("No Internet Connection");
|
||||
|
||||
case DioExceptionType.unknown:
|
||||
return ServerFailure("Unexpected Error, Please try again!");
|
||||
|
||||
default:
|
||||
return ServerFailure("Unexpected Error, Please try again!");
|
||||
}
|
||||
}
|
||||
|
||||
factory ServerFailure.fromResponse(int? statusCode, dynamic responseMessage) {
|
||||
switch (statusCode) {
|
||||
case 401:
|
||||
case 403:
|
||||
return ServerFailure(responseMessage);
|
||||
case 400:
|
||||
List<String> errors = [];
|
||||
if (responseMessage is List) {
|
||||
for (var error in responseMessage) {
|
||||
errors.add(error);
|
||||
}
|
||||
} else {
|
||||
return ServerFailure(responseMessage);
|
||||
}
|
||||
return ServerFailure(errors.join('\n'));
|
||||
case 404:
|
||||
return ServerFailure("");
|
||||
case 500:
|
||||
return ServerFailure(responseMessage);
|
||||
default:
|
||||
return ServerFailure("Opps there was an Error, Please try again!");
|
||||
}
|
||||
}
|
||||
}
|
@ -1 +1,29 @@
|
||||
class AuthAPI {}
|
||||
import 'package:syncrow_web/pages/auth/model/token.dart';
|
||||
import 'api/api_links_endpoints.dart';
|
||||
import 'api/http_service.dart';
|
||||
|
||||
class AuthenticationAPI {
|
||||
|
||||
|
||||
static Future<Token> loginWithEmail({required var model}) async {
|
||||
final response = await HTTPService().post(
|
||||
path: ApiEndpoints.login,
|
||||
body: model.toJson(),
|
||||
showServerMessage: false,
|
||||
expectedResponseModel: (json) => Token.fromJson(json['data']));
|
||||
return response;
|
||||
}
|
||||
|
||||
// static Future<bool> signUp({required SignUpModel model}) async {
|
||||
// final response = await HTTPService().post(
|
||||
// path: ApiEndpoints.signUp,
|
||||
// body: model.toJson(),
|
||||
// showServerMessage: false,
|
||||
// expectedResponseModel: (json) => json['statusCode'] == 201);
|
||||
// return response;
|
||||
// }
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
13
lib/services/locator.dart
Normal file
13
lib/services/locator.dart
Normal file
@ -0,0 +1,13 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:syncrow_web/services/api/http_interceptor.dart';
|
||||
import 'package:syncrow_web/services/api/http_service.dart';
|
||||
|
||||
final GetIt serviceLocator = GetIt.instance;
|
||||
//setupLocator() // to search for dependency injection in flutter
|
||||
initialSetup() {
|
||||
serviceLocator.registerSingleton<HTTPInterceptor>(HTTPInterceptor());
|
||||
//Base classes
|
||||
|
||||
serviceLocator.registerSingleton<Dio>(HTTPService.setupDioClient());
|
||||
}
|
21
lib/utils/const.dart
Normal file
21
lib/utils/const.dart
Normal file
@ -0,0 +1,21 @@
|
||||
import 'dart:convert';
|
||||
|
||||
String decodeBase64(String str) {
|
||||
//'-', '+' 62nd char of encoding, '_', '/' 63rd char of encoding
|
||||
String output = str.replaceAll('-', '+').replaceAll('_', '/');
|
||||
switch (output.length % 4) {
|
||||
// Pad with trailing '='
|
||||
case 0: // No pad chars in this case
|
||||
break;
|
||||
case 2: // Two pad chars
|
||||
output += '==';
|
||||
break;
|
||||
case 3: // One pad char
|
||||
output += '=';
|
||||
break;
|
||||
default:
|
||||
throw Exception('Illegal base64url string!"');
|
||||
}
|
||||
|
||||
return utf8.decode(base64Url.decode(output));
|
||||
}
|
7
lib/utils/navigation_service.dart
Normal file
7
lib/utils/navigation_service.dart
Normal file
@ -0,0 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class NavigationService {
|
||||
static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
|
||||
static GlobalKey<ScaffoldMessengerState>? snackbarKey =
|
||||
GlobalKey<ScaffoldMessengerState>();
|
||||
}
|
@ -1,5 +1,3 @@
|
||||
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
|
||||
@ -15,7 +13,7 @@ class ResponsiveLayout extends StatelessWidget {
|
||||
}else{
|
||||
return desktopBody;
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
40
lib/utils/snack_bar.dart
Normal file
40
lib/utils/snack_bar.dart
Normal file
@ -0,0 +1,40 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:syncrow_web/utils/navigation_service.dart';
|
||||
|
||||
class CustomSnackBar {
|
||||
static displaySnackBar(String message) {
|
||||
final key = NavigationService.snackbarKey;
|
||||
if (key != null) {
|
||||
final snackBar = SnackBar(content: Text(message));
|
||||
key.currentState?.clearSnackBars();
|
||||
key.currentState?.showSnackBar(snackBar);
|
||||
}
|
||||
}
|
||||
|
||||
static greenSnackBar(String message) {
|
||||
final key = NavigationService.snackbarKey;
|
||||
BuildContext? currentContext = key?.currentContext;
|
||||
if (key != null && currentContext != null) {
|
||||
final snackBar = SnackBar(
|
||||
padding: const EdgeInsets.all(16),
|
||||
backgroundColor: Colors.green,
|
||||
content: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
|
||||
const Icon(
|
||||
Icons.check_circle,
|
||||
color: Colors.white,
|
||||
size: 32,
|
||||
),
|
||||
const SizedBox(
|
||||
width: 8,
|
||||
),
|
||||
Text(
|
||||
message,
|
||||
style: Theme.of(currentContext).textTheme.bodySmall!.copyWith(
|
||||
fontSize: 14, fontWeight: FontWeight.w500, color: Colors.green),
|
||||
)
|
||||
]),
|
||||
);
|
||||
key.currentState?.showSnackBar(snackBar);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,10 +1,9 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'color_manager.dart';
|
||||
|
||||
InputDecoration? textBoxDecoration = InputDecoration(
|
||||
InputDecoration? textBoxDecoration({bool suffixIcon = false}) => InputDecoration(
|
||||
focusColor: ColorsManager.grayColor,
|
||||
suffixIcon: const Icon(Icons.search),
|
||||
suffixIcon:suffixIcon? const Icon(Icons.search):null,
|
||||
hintText: 'Search',
|
||||
filled: true, // Enable background filling
|
||||
fillColor: Colors.grey.shade200, // Set the background color
|
||||
|
@ -1,5 +1,3 @@
|
||||
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:syncrow_web/utils/color_manager.dart';
|
||||
import 'package:syncrow_web/utils/style.dart';
|
||||
@ -44,7 +42,7 @@ class MenuSidebar extends StatelessWidget {
|
||||
const SizedBox(height: 20,),
|
||||
TextFormField(
|
||||
controller: TextEditingController(),
|
||||
decoration:textBoxDecoration
|
||||
decoration:textBoxDecoration(suffixIcon: true)
|
||||
),
|
||||
Container(height: 100,)
|
||||
],
|
||||
|
Reference in New Issue
Block a user