Skip to content

Commit

Permalink
Merge pull request #102 from kookmin-sw/feature/fe/#85-loginAPItest
Browse files Browse the repository at this point in the history
[FE] auth_service 테스트 완료
  • Loading branch information
kevinmj12 authored Apr 27, 2024
2 parents b8e6d30 + bebff66 commit 465e4db
Show file tree
Hide file tree
Showing 7 changed files with 124 additions and 89 deletions.
16 changes: 16 additions & 0 deletions front/capstone_front/lib/models/api_fail_response.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class ApiFailResponse {
final bool success;
final String message;
final String code;

ApiFailResponse({
required this.success,
required this.message,
required this.code,
});

ApiFailResponse.fromJson(Map<String, dynamic> json)
: success = json['success'] as bool,
message = json['message'] as String,
code = json['code'] as String;
}
11 changes: 0 additions & 11 deletions front/capstone_front/lib/models/api_response.dart

This file was deleted.

16 changes: 16 additions & 0 deletions front/capstone_front/lib/models/api_success_response.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class ApiSuccessResponse {
final bool success;
final String message;
final Map<String, dynamic> response;

ApiSuccessResponse({
required this.success,
required this.message,
required this.response,
});

ApiSuccessResponse.fromJson(Map<String, dynamic> json)
: success = json['success'] as bool,
message = json['message'] as String,
response = json['response'];
}
13 changes: 11 additions & 2 deletions front/capstone_front/lib/screens/login/login_screen.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'package:capstone_front/services/auth_service.dart';
import 'package:capstone_front/services/login_service.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:firebase_auth/firebase_auth.dart';
Expand Down Expand Up @@ -58,12 +59,20 @@ class _LoginScreenState extends State<LoginScreen> {
'${_userInfo[0]}@kookmin.ac.kr', _userInfo[1]);
switch (result) {
case "success":
makeToast("로그인에 성공하였습니다");
await storage.write(key: 'isLogin', value: 'true');
await storage.write(
key: 'userEmail',
value: '${_userInfo[0]}@kookmin.ac.kr');
context.go('/');
var uuid = await storage.read(key: 'uuid');
var isLogined = await AuthService.signIn({
"uuid": uuid,
"email": '${_userInfo[0]}@kookmin.ac.kr',
});
if (isLogined) {
makeToast("로그인에 성공하였습니다");
context.go('/');
}

case "email":
makeToast("이메일이 인증되지 않았습니다");
case "invalid-credential":
Expand Down
60 changes: 26 additions & 34 deletions front/capstone_front/lib/screens/signup/signup_service.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import 'dart:convert';
import 'dart:ui';

import 'package:capstone_front/models/api_success_response.dart';
import 'package:capstone_front/screens/signup/college_department.dart';
import 'package:capstone_front/screens/signup/signup_email_screen.dart';
import 'package:capstone_front/screens/signup/signup_util.dart';
Expand All @@ -17,6 +19,7 @@ import 'package:provider/provider.dart';
late UserCredential credential;

Map<String, String> userInfo = {
'uuid': '',
'id': '',
'pw': '',
'pwRe': '',
Expand All @@ -29,45 +32,33 @@ Map<String, String> userInfo = {
int selectedPageIndex = 0;

Future<String> signup() async {
try {
// UserCredential credential =
// await FirebaseAuth.instance.createUserWithEmailAndPassword(
// email: '${userInfo['id']}@kookmin.ac.kr',
// password: userInfo['pw']!,
// );
// await credential.user!.sendEmailVerification();

// TODO 우리 서버에 signup 요청 여기서
// signupInfo 에는 실제 유저에게 입력받은 정보가 들어가야함

// final Map<String, dynamic> signupInfo = {
// // "uuid": credential.user!.uid,
// "uuid": 'messi',
// "email": '[email protected]',
// "name": 'jihun',
// "country": 'korea',
// "phoneNumber": '010-8276-8291',
// "major": "sw",
// };
// var response = AuthService.signUp(signupInfo);

// response의 결과에 따라 성공, 실패, 이유 띄워야함
Map<String, dynamic> userData = {
'uuid': userInfo['uuid'],
'email': "${userInfo['id']}@kookmin.ac.kr",
'name': userInfo['name'],
'country': userInfo['country'],
'phoneNumber': '010-8276-8291',
'major': userInfo['department'],
};

var isSucceed = await AuthService.signUp(userData);
if (isSucceed) {
return 'success';
} on FirebaseAuthException catch (e) {
return e.code;
} catch (e) {
return e.toString();
}
throw Exception('there is something problem while signup');
}

Future<String> sendEmailAuth(String email, String pw) async {
FlutterSecureStorage storage = const FlutterSecureStorage();

try {
credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: '${userInfo['id']}@kookmin.ac.kr',
password: userInfo['pw']!,
);

userInfo['uuid'] = credential.user!.uid;
await storage.write(key: 'uuid', value: credential.user!.uid);
await credential.user?.sendEmailVerification();

return "success";
Expand All @@ -77,15 +68,16 @@ Future<String> sendEmailAuth(String email, String pw) async {
}

Future<String> isEmailAuth(String email, String pw) async {
FlutterSecureStorage storage = const FlutterSecureStorage();
try {
// UserCredential credential = await FirebaseAuth.instance
// .signInWithEmailAndPassword(email: email, password: pw);
User? user = credential.user;
await user!.reload();
user = FirebaseAuth.instance.currentUser;

// User? user = credential.user;
// await user!.reload();
// user = FirebaseAuth.instance.currentUser;
if (credential.user!.emailVerified) {
// user = credential.user;
if (user!.emailVerified) {
user = credential.user;
userInfo['uuid'] = user!.uid;
await storage.write(key: 'uuid', value: user.uid);
return "success";
} else {
return "email";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,8 @@ class _SignupPasswordScreenState extends State<SignupPasswordScreen> {
await sendEmailAuth(userInfo['id']!, userInfo['pw']!);
// 파이어베이스에 계정 생성 완료, 인증 메일 전송 완료
if (result == "success") {
print(userInfo['id']);
print(userInfo['pw']);
print(userInfo['name']);
print(userInfo['studentNum']);
print(userInfo['college']);
print(userInfo['department']);
print(userInfo['country']);

// Todo: 서버로 회원가입된 내역 전송
// 우리 서버로 회원가입 요청
await signup();

showDialog(
context: context,
Expand Down
86 changes: 53 additions & 33 deletions front/capstone_front/lib/services/auth_service.dart
Original file line number Diff line number Diff line change
@@ -1,28 +1,20 @@
import 'dart:convert';

import 'package:capstone_front/models/api_fail_response.dart';
import 'package:capstone_front/models/api_success_response.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;
import 'package:crypto/crypto.dart';

class AuthService {
static String baseUrl = dotenv.get('BASE_URL');
static final List<int> key = base64Decode(dotenv.get('HMAC_SECRET'));

static Future<Map<String, dynamic>> signUp(
Map<String, dynamic> userInfo) async {
static Future<bool> signUp(Map<String, dynamic> userInfo) async {
var hmacSha256 = Hmac(sha256, key);
final url = Uri.parse('$baseUrl/user/signup');

var dummy = {
"uuid": "string",
"email": "aㅁ[email protected]",
"name": "string",
"country": "string",
"phoneNumber": "010-8276-8291",
"major": "string"
};

// var json = jsonEncode(dummy);
var json = jsonEncode(userInfo);
var bytes = utf8.encode(json);
var digest = hmacSha256.convert(bytes);
Expand All @@ -37,18 +29,19 @@ class AuthService {
body: json,
);

final String decodedBody = utf8.decode(response.bodyBytes);
final Map<String, dynamic> res = jsonDecode(decodedBody);

if (response.statusCode != 201) {
final String decodedBody = utf8.decode(response.bodyBytes);
final ApiFailResponse apiFailResponse = jsonDecode(decodedBody);
print('Request failed with status: ${response.statusCode}.');
print('Request failed with status: ${response.body}');
print('Request failed with status: ${apiFailResponse.message}');
return false;
}

return res;
return true;
}

static Future<Map<String, dynamic>> signIn(Map<String, dynamic> info) async {
static Future<bool> signIn(Map<String, dynamic> info) async {
FlutterSecureStorage storage = const FlutterSecureStorage();
var hmacSha256 = Hmac(sha256, key);
final url = Uri.parse('$baseUrl/user/signin');

Expand All @@ -67,35 +60,62 @@ class AuthService {
);

final String decodedBody = utf8.decode(response.bodyBytes);
final Map<String, dynamic> res = jsonDecode(decodedBody);

if (response.statusCode != 200) {
print('Request failed with status: ${response.statusCode}.');
print('Request failed with status: ${response.body}');
final Map<String, dynamic> jsonMap = jsonDecode(decodedBody);
if (response.statusCode == 200) {
final ApiSuccessResponse apiSuccessResponse =
ApiSuccessResponse.fromJson(jsonMap);
await storage.write(
key: 'accessToken',
value: apiSuccessResponse.response['accessToken'],
);
await storage.write(
key: 'refreshToken',
value: apiSuccessResponse.response['refreshToken'],
);
} else {
final ApiFailResponse apiFailResponse = ApiFailResponse.fromJson(jsonMap);
print(response.statusCode);
print(apiFailResponse.message);
throw Exception("fail to get toekns");
}

return res;
return true;
}

static Future<Map<String, dynamic>> reissue(
Map<String, dynamic> refreshTokenObj) async {
static void reissue() async {
FlutterSecureStorage storage = const FlutterSecureStorage();

final url = Uri.parse('$baseUrl/auth/reissue');
final refreshToken = storage.read(key: 'refreshToken');

final response = await http.post(
url,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(refreshTokenObj),
body: jsonEncode({
"refreshToekn": refreshToken,
}),
);

final String decodedBody = utf8.decode(response.bodyBytes);
final Map<String, dynamic> res = jsonDecode(decodedBody);

if (response.statusCode != 200) {
print('Request failed with status: ${response.statusCode}.');
final Map<String, dynamic> jsonMap = jsonDecode(decodedBody);
if (response.statusCode == 200) {
final ApiSuccessResponse apiSuccessResponse =
ApiSuccessResponse.fromJson(jsonMap);
await storage.write(
key: 'accessToken',
value: apiSuccessResponse.response['accessToken'],
);
await storage.write(
key: 'refreshToken',
value: apiSuccessResponse.response['refreshToken'],
);
} else {
final ApiFailResponse apiFailResponse = ApiFailResponse.fromJson(jsonMap);
print(response.statusCode);
print(apiFailResponse.message);
throw Exception("fail to reissue");
}

return res;
}
}

0 comments on commit 465e4db

Please sign in to comment.