Skip to content

Commit

Permalink
Merge pull request #459 from APPSCHOOL1-REPO/Feat/#442-Simple-Encrypt…
Browse files Browse the repository at this point in the history
…ion-Team

Feat/#442 simple encryption team
  • Loading branch information
ValseLee authored Jul 13, 2023
2 parents de1569a + 138756d commit 8247b0f
Show file tree
Hide file tree
Showing 16 changed files with 163 additions and 70 deletions.
16 changes: 15 additions & 1 deletion GitSpace/Sources/Models/Chat.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ struct Chat: Identifiable, Codable {
let joinedMemberIDs: [String] // 채팅방에 참여한 유저 ID 리스트
var lastContent: String // 마지막 메세지 내용
var lastContentDate: Date // 마지막 메세지 날짜
let knockContent: String // 노크 메세지 내용
var knockContent: String // 노크 메세지 내용
let knockContentDate: Date // 노크 메세지 날짜
var unreadMessageCount: [String : Int] // 읽지 않은 메시지 갯수 (userID : 읽지 않은 메시지 갯수)

Expand Down Expand Up @@ -75,4 +75,18 @@ struct Chat: Identifiable, Codable {
unreadMessageCount: [:]
)
}

static func encodedChat(with chat: Chat) -> Chat {
var encodedChat: Chat = chat
encodedChat.knockContent = chat.knockContent.asBase64 ?? ""
encodedChat.lastContent = chat.lastContent.asBase64 ?? ""
return encodedChat
}

static func decodedChat(with chat: Chat) -> Chat {
var decodedChat: Chat = chat
decodedChat.knockContent = chat.knockContent.decodedBase64String ?? ""
decodedChat.lastContent = chat.lastContent.decodedBase64String ?? ""
return decodedChat
}
}
16 changes: 14 additions & 2 deletions GitSpace/Sources/Models/Message.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// ChatCellModel.swift
// MessageCellModel.swift
// GitSpace
//
// Created by 원태영 on 2023/01/27.
Expand All @@ -11,7 +11,7 @@ import Foundation
struct Message : Identifiable, Codable {
let id: String // 메세지 ID
let senderID: String // 메세지 작성자 유저 ID
let textContent: String // 메세지 내용
var textContent: String // 메세지 내용
let imageContent: String? // 메세지에 첨부한 이미지
let sentDate: Date // 메세지 작성 날짜
let isRead: Bool // 수신 유저의 메세지 확인 여부
Expand All @@ -24,4 +24,16 @@ struct Message : Identifiable, Codable {

return dateFormatter.string(from: sentDate)
}

static func encodedMessage(with message: Message) -> Message {
var encodedMessage: Message = message
encodedMessage.textContent = message.textContent.asBase64 ?? ""
return encodedMessage
}

static func decodedMessage(with message: Message) -> Message {
var decodedMessage: Message = message
decodedMessage.textContent = message.textContent.decodedBase64String ?? ""
return decodedMessage
}
}
24 changes: 15 additions & 9 deletions GitSpace/Sources/ViewModels/ChatViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ extension ChatStore {
private func decodeNewChat(change: QueryDocumentSnapshot) -> Chat? {
do {
let newChat = try change.data(as: Chat.self)
return newChat
let decodedNewChat: Chat = .decodedChat(with: newChat)
return decodedNewChat
} catch {
print("Error-\(#file)-\(#function) : \(error.localizedDescription)")
}
Expand Down Expand Up @@ -122,7 +123,8 @@ extension ChatStore {
func addListener() {
listener = db
.collection(const.COLLECTION_CHAT)
.whereField(const.FIELD_JOINED_MEMBER_IDS, arrayContains: Utility.loginUserID)
.whereField(const.FIELD_JOINED_MEMBER_IDS,
arrayContains: Utility.loginUserID)
.addSnapshotListener { snapshot, error in

guard let snapshot else { return }
Expand Down Expand Up @@ -194,7 +196,8 @@ extension ChatStore {
do {
let chat: Chat = try document.data(as: Chat.self)
if let targetUserInfo = await UserStore.requestAndReturnUser(userID: chat.targetUserID) {
newChats.append(chat)
let decodedChat: Chat = .decodedChat(with: chat)
newChats.append(decodedChat)
targetUserInfoDict[chat.id] = targetUserInfo
}
} catch {
Expand All @@ -212,10 +215,11 @@ extension ChatStore {
do {
let pushedChat = try await doc.getDocument(as: Chat.self)
// FIXME: Chat의 targetUserName을 사용하지 않기 위해 UserStore의 UserInfo 요청 메서드 구현. 해당 메서드로 로직 대체 By. 태영

let decodedPushedChat: Chat = .decodedChat(with: pushedChat)

if let targetUserInfo = await UserStore.requestAndReturnUser(userID: pushedChat.targetUserID) {
targetUserInfoDict[pushedChat.id] = targetUserInfo
return pushedChat
return decodedPushedChat
}
return nil
} catch {
Expand All @@ -226,22 +230,24 @@ extension ChatStore {

// MARK: -Chat CRUD
func addChat(_ chat: Chat) async {
let encodedChat: Chat = .encodedChat(with: chat)
do {
try db.collection(const.COLLECTION_CHAT)
.document(chat.id)
.setData(from: chat.self)
.setData(from: encodedChat.self)
} catch {
print("Error-\(#file)-\(#function) : \(error.localizedDescription)")
}
}

func updateChat(_ chat: Chat) async {
let encodedChat: Chat = .encodedChat(with: chat)
do {
try await db.collection(const.COLLECTION_CHAT)
.document(chat.id)
.updateData([const.FIELD_LAST_CONTENT_DATE : chat.lastContentDate,
const.FIELD_LAST_CONTENT : chat.lastContent,
const.FIELD_UNREAD_MESSAGE_COUNT : chat.unreadMessageCount])
.updateData([const.FIELD_LAST_CONTENT_DATE : encodedChat.lastContentDate,
const.FIELD_LAST_CONTENT : encodedChat.lastContent,
const.FIELD_UNREAD_MESSAGE_COUNT : encodedChat.unreadMessageCount])
} catch {
print("Error-\(#file)-\(#function) : \(error.localizedDescription)")
}
Expand Down
64 changes: 49 additions & 15 deletions GitSpace/Sources/ViewModels/KnockHistory/KnockViewManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -192,11 +192,21 @@ extension KnockViewManager {
searchText: String,
userSelectedTab: String
) -> Bool {
if isSearching, userSelectedTab == Constant.KNOCK_RECEIVED { // 검색중 + 내 수신함
// 현재 내가 선택한 필터 옵션과 같아야 하고, 내 수신함에는 보낸 사람의 정보를 가져야 한다.
return knock.knockStatus == equalsToKnockStatus && knock.sentUserName.contains(searchText, isCaseInsensitive: true)
if isSearching,
userSelectedTab == Constant.KNOCK_RECEIVED {
// 검색중 + 내 수신함
// 현재 내가 선택한 필터 옵션과 같아야 하고, 내 수신함에는 보낸 사람의 정보를 가져야 한다.
return knock.knockStatus == equalsToKnockStatus &&
knock.sentUserName.contains(
searchText,
isCaseInsensitive: true
)
} else if isSearching, userSelectedTab == Constant.KNOCK_SENT { // 검색중 + 내 발신함
return knock.knockStatus == equalsToKnockStatus && knock.receivedUserName.contains(searchText, isCaseInsensitive: true)
return knock.knockStatus == equalsToKnockStatus &&
knock.receivedUserName.contains(
searchText,
isCaseInsensitive: true
)
} else if userSelectedTab == Constant.KNOCK_RECEIVED {
return knock.knockStatus == equalsToKnockStatus
} else if userSelectedTab == Constant.KNOCK_SENT {
Expand All @@ -205,7 +215,10 @@ extension KnockViewManager {
return false
}

public func sortedByDateValue(lhs: Knock, rhs: Knock) -> Bool {
public func sortedByDateValue(
lhs: Knock,
rhs: Knock
) -> Bool {
lhs.knockedDate.dateValue() > rhs.knockedDate.dateValue()
}
}
Expand All @@ -225,16 +238,34 @@ extension KnockViewManager {
snapshot.documentChanges.forEach { docDiff in
switch docDiff.type {
case .added:
if let newKnock = self.decodeKnockElementForListener(with: docDiff, currentUser: currentUser) {
self.appendKnockElementInTempList(newKnock: newKnock, currentUser: currentUser)
if let newKnock = self.decodeKnockElementForListener(
with: docDiff,
currentUser: currentUser
) {
self.appendKnockElementInTempList(
newKnock: newKnock,
currentUser: currentUser
)
}
case .modified:
if let diffKnock = self.decodeKnockElementForListener(with: docDiff, currentUser: currentUser) {
self.updateTempKnockList(diffKnock: diffKnock, currentUser: currentUser)
if let diffKnock = self.decodeKnockElementForListener(
with: docDiff,
currentUser: currentUser
) {
self.updateTempKnockList(
diffKnock: diffKnock,
currentUser: currentUser
)
}
case .removed:
if let removedKnock = self.decodeKnockElementForListener(with: docDiff, currentUser: currentUser) {
self.removeKnocksInTempKnockList(removedKnock: removedKnock, currentUser: currentUser)
if let removedKnock = self.decodeKnockElementForListener(
with: docDiff,
currentUser: currentUser
) {
self.removeKnocksInTempKnockList(
removedKnock: removedKnock,
currentUser: currentUser
)
}
}
}
Expand Down Expand Up @@ -268,6 +299,7 @@ extension KnockViewManager {

/**
1. 만들어진 노크를 DB에 등록합니다.
- Important: User Created Contents는 모두 Base String으로 콘솔에 저장됩니다.
*/
public func createKnockOnFirestore(knock: Knock) async -> Void {
let document = firebaseDatabase.document("\(knock.id)")
Expand All @@ -276,10 +308,10 @@ extension KnockViewManager {
try await document.setData([
"id": knock.id,
"knockedDate": knock.knockedDate,
"declineMessage": knock.declineMessage ?? "",
"declineMessage": knock.declineMessage?.asBase64 ?? "",
"knockCategory": knock.knockCategory,
"knockStatus": Constant.KNOCK_WAITING,
"knockMessage": knock.knockMessage,
"knockMessage": knock.knockMessage.asBase64 ?? "암호화",
"receivedUserName": knock.receivedUserName,
"sentUserName": knock.sentUserName,
"sentUserID": knock.sentUserID,
Expand Down Expand Up @@ -312,7 +344,8 @@ extension KnockViewManager {
let isKnockMessageEdited,
isKnockMessageEdited {
try await document.updateData([
"knockMessage": knock.knockMessage
// !!!: base String으로 콘솔 저장
"knockMessage": knock.knockMessage.asBase64 ?? ""
])
}

Expand All @@ -326,7 +359,8 @@ extension KnockViewManager {
case Constant.KNOCK_DECLINED:
try await document.setData([
"declinedDate": Timestamp(date: .now),
"declineMessage": declineMessage ?? "\(knock.receivedUserName) decided not to give you a decline message."
// !!!: base String으로 콘솔 저장
"declineMessage": declineMessage?.asBase64 ?? "\(knock.receivedUserName) decided not to give you a decline message."
], merge: true)

default:
Expand Down
14 changes: 9 additions & 5 deletions GitSpace/Sources/ViewModels/MessageViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ extension MessageStore {
for document in snapshot.documents {
do {
let message: Message = try document.data(as: Message.self)
newMessages.append(message)
let decodedMessage: Message = .decodedMessage(with: message)
newMessages.append(decodedMessage)
} catch {
print("Error-\(#file)-\(#function) : \(error.localizedDescription)")
}
Expand All @@ -95,28 +96,30 @@ extension MessageStore {

// MARK: - Message CRUD
func addMessage(_ message: Message, chatID: String) {
let encodedMessage: Message = .encodedMessage(with: message)
do {
try db
.collection(const.COLLECTION_CHAT)
.document(chatID)
.collection(const.COLLECTION_MESSAGE)
.document(message.id)
.setData(from: message.self)
.setData(from: encodedMessage.self)
} catch {
print("Error-\(#file)-\(#function) : \(error.localizedDescription)")
}
}

func updateMessage(_ message: Message, chatID: String) async {
let encodedMessage: Message = .encodedMessage(with: message)
do {
try await db
.collection(const.COLLECTION_CHAT)
.document(chatID)
.collection(const.COLLECTION_MESSAGE)
.document(message.id)
.updateData(
[const.FIELD_TEXT_CONTENT : message.textContent,
const.FIELD_SENT_DATE : message.sentDate])
[const.FIELD_TEXT_CONTENT : encodedMessage.textContent,
const.FIELD_SENT_DATE : encodedMessage.sentDate])
} catch {
print("Error-\(#file)-\(#function) : \(error.localizedDescription)")
}
Expand All @@ -143,7 +146,8 @@ extension MessageStore {
func fetchNewMessage(change : QueryDocumentSnapshot) -> Message? {
do {
let newMessage = try change.data(as: Message.self)
return newMessage
let decodedNewMessage: Message = .decodedMessage(with: newMessage)
return decodedNewMessage
} catch {
print("Error-\(#file)-\(#function) : \(error.localizedDescription)")
}
Expand Down
23 changes: 16 additions & 7 deletions GitSpace/Sources/ViewModels/TagViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,12 @@ final class TagViewModel: ObservableObject {
let id = document[const.FIELD_ID] as? String ?? ""
let tagName = document[const.FIELD_TAGNAME] as? String ?? ""
let repositories = document[const.FIELD_REPOSITORIES] as? [String] ?? []
self.tags.append( Tag(id: id, tagName: tagName, repositories: repositories) )
/// 이미 사용 중인 사용자들의 Tag 데이터는 약식 암호화가 적용되지 않아서 임시로 분기 처리함.
if let decodedTagName = tagName.decodedBase64String {
self.tags.append(Tag(id: id, tagName: decodedTagName, repositories: repositories))
} else {
self.tags.append(Tag(id: id, tagName: tagName, repositories: repositories))
}
}
} catch {
print("Error-\(#file)-\(#function): \(error.localizedDescription)")
Expand All @@ -43,14 +48,15 @@ final class TagViewModel: ObservableObject {
func registerTag(tagName: String) async -> Tag? {
do {
let tid = UUID().uuidString
guard let encodeTagName = tagName.asBase64 else { return nil }
try await database.collection(const.COLLECTION_USER_INFO)
.document(Auth.auth().currentUser?.uid ?? "")
.collection(const.COLLECTION_TAG)
.document(tid)
.setData([
const.FIELD_ID: tid,
const.FIELD_TAGNAME: tagName,
const.FIELD_REPOSITORIES: []
const.FIELD_TAGNAME: encodeTagName,
const.FIELD_REPOSITORIES: Array<String>()
])
return Tag(id: tid, tagName: tagName, repositories: [])
} catch {
Expand All @@ -73,7 +79,6 @@ final class TagViewModel: ObservableObject {
}
}

// FIXME: 수정 시나리오 완성 후 메서드 구현
/*
// MARK: Update Custom Tag
/// 특정 사용자 태그를 수정합니다.
Expand All @@ -96,9 +101,14 @@ final class TagViewModel: ObservableObject {
.getDocuments()
for document in snapshot.documents {
let id = document.data()[const.FIELD_ID] as? String ?? ""
let name = document.data()[const.FIELD_TAGNAME] as? String ?? ""
let tagName = document.data()[const.FIELD_TAGNAME] as? String ?? ""
let repositories = document.data()[const.FIELD_REPOSITORIES] as? [String] ?? []
tagNameList.append(Tag(id: id, tagName: name, repositories: repositories))
/// 이미 사용 중인 사용자들의 Tag 데이터는 약식 암호화가 적용되지 않아서 임시로 분기 처리함.
if let decodedTagName = tagName.decodedBase64String {
tagNameList.append(Tag(id: id, tagName: decodedTagName, repositories: repositories))
} else {
tagNameList.append(Tag(id: id, tagName: tagName, repositories: repositories))
}
}
return tagNameList
} catch {
Expand All @@ -125,7 +135,6 @@ final class TagViewModel: ObservableObject {
}
}

// FIXME: 정말 필요한 함수인지 확인하기
/*
// MARK: Update Repository Tag
/// 선택된 레포지토리의 태그를 수정합니다.
Expand Down
Loading

0 comments on commit 8247b0f

Please sign in to comment.