Protection against add already added account & checkmark next to actual checked account

This commit is contained in:
Pengwius 2021-03-07 23:32:51 +01:00
parent 321a62a650
commit b0ccdd48cc
9 changed files with 119 additions and 97 deletions

View file

@ -15,7 +15,7 @@ public func apiRequest(endpointURL: String) -> URLRequest {
request.httpMethod = "GET"
let keychain = Keychain()
let id = keychain["acctualStudentId"] ?? ""
let id = keychain["actualStudentId"] ?? ""
let account = keychain[id] ?? "[]"
let data = Data(account.utf8)

View file

@ -11,6 +11,7 @@ import Combine
import os
import KeychainAccess
import SwiftyJSON
import SwiftUI
@available (iOS 14, macOS 11, watchOS 7, tvOS 14, *)
public class Sdk {
@ -142,69 +143,92 @@ public class Sdk {
completionHandler(parsedError)
} else {
let keychain = Keychain()
let allAccountsCheck: String! = keychain["allAccounts"] ?? "[]"
let receiveValueJSON = try! JSON(data: data)
// Get private key
guard let privateKeyRawData = self.certificate.getPrivateKeyData(format: .DER),
let privateKeyString = String(data: privateKeyRawData, encoding: .utf8)?
.split(separator: "\n")
.dropFirst()
.dropLast()
.joined()
.data(using: .utf8) else {
return
}
let privateKeyStringString = String(decoding: privateKeyString, as: UTF8.self)
let fingerprint = self.certificate.getCertificateFingerprint().lowercased()
let saveAccount = """
{
"acctualStudent": "0",
"privateKeyString": "\(privateKeyStringString)",
"fingerprint": "\(fingerprint)",
"deviceModel": "\(deviceModel)",
"account": {
"UserName": "\(receiveValueJSON["Envelope"]["UserName"])",
"RestURL": "\(receiveValueJSON["Envelope"]["RestURL"])",
"UserLogin": "\(receiveValueJSON["Envelope"]["UserLogin"])",
"LoginId": "\(receiveValueJSON["Envelope"]["LoginId"])"
//parsing allAccounts to array
var allAccountsArray: [String] = []
if(allAccountsCheck != "[]"){
let data = Data(allAccountsCheck.utf8)
do {
let ids = try JSONSerialization.jsonObject(with: data) as! [String]
for id in ids {
let student = keychain[id]
let data = Data(student!.utf8)
let accountParsed = try! JSON(data: data)
allAccountsArray.append("\(accountParsed["account"]["UserLogin"])")
}
}
"""
keychain["\(receiveValueJSON["Envelope"]["LoginId"])"] = "\(saveAccount)"
let allAccounts = keychain["allAccounts"] ?? "[]"
let data = Data(allAccounts.utf8)
do {
var array = try JSONSerialization.jsonObject(with: data) as! [String]
array.append("\(receiveValueJSON["Envelope"]["LoginId"])")
keychain["allAccounts"] = "\(array)"
} catch {
print(error)
}
keychain["acctualStudentId"] = "\(receiveValueJSON["Envelope"]["LoginId"])"
let endpointURL: String = "\(receiveValueJSON["Envelope"]["RestURL"])api/mobile/register/hebe"
let apiResponseRequest = apiRequest(endpointURL: endpointURL)
let session = URLSession.shared
session.dataTask(with: apiResponseRequest) { (data, response, error) in
if let error = error {
// Handle HTTP request error
} catch {
print(error)
} else if let data = data {
// Handle HTTP request response
let responseBody = String(data: data, encoding: String.Encoding.utf8)
keychain["acctualStudentHebe"] = "\(responseBody!)"
} else {
// Handle unexpected error
}
}.resume()
}
if allAccountsArray.contains("\(receiveValueJSON["Envelope"]["UserName"])") {
keychain["accountExist"] = "true"
} else {
// Get private key
guard let privateKeyRawData = self.certificate.getPrivateKeyData(format: .DER),
let privateKeyString = String(data: privateKeyRawData, encoding: .utf8)?
.split(separator: "\n")
.dropFirst()
.dropLast()
.joined()
.data(using: .utf8) else {
return
}
let privateKeyStringString = String(decoding: privateKeyString, as: UTF8.self)
let fingerprint = self.certificate.getCertificateFingerprint().lowercased()
let saveAccount = """
{
"actualStudent": "0",
"privateKeyString": "\(privateKeyStringString)",
"fingerprint": "\(fingerprint)",
"deviceModel": "\(deviceModel)",
"account": {
"UserName": "\(receiveValueJSON["Envelope"]["UserName"])",
"RestURL": "\(receiveValueJSON["Envelope"]["RestURL"])",
"UserLogin": "\(receiveValueJSON["Envelope"]["UserLogin"])",
"LoginId": "\(receiveValueJSON["Envelope"]["LoginId"])"
}
}
"""
keychain["\(receiveValueJSON["Envelope"]["LoginId"])"] = "\(saveAccount)"
let allAccounts = keychain["allAccounts"] ?? "[]"
let data = Data(allAccounts.utf8)
do {
var array = try JSONSerialization.jsonObject(with: data) as! [String]
array.append("\(receiveValueJSON["Envelope"]["LoginId"])")
keychain["allAccounts"] = "\(array)"
} catch {
print(error)
}
keychain["actualStudentId"] = "\(receiveValueJSON["Envelope"]["LoginId"])"
keychain["actualAccountEmail"] = "\(receiveValueJSON["Envelope"]["UserName"])"
let endpointURL: String = "\(receiveValueJSON["Envelope"]["RestURL"])api/mobile/register/hebe"
let apiResponseRequest = apiRequest(endpointURL: endpointURL)
let session = URLSession.shared
session.dataTask(with: apiResponseRequest) { (data, response, error) in
if let error = error {
// Handle HTTP request error
print(error)
} else if let data = data {
// Handle HTTP request response
let responseBody = String(data: data, encoding: String.Encoding.utf8)
keychain["actualStudentHebe"] = "\(responseBody!)"
} else {
// Handle unexpected error
}
}.resume()
}
completionHandler(nil)
}
})

View file

@ -12,17 +12,17 @@ import SwiftyJSON
@available (iOS 14, macOS 11, watchOS 7, tvOS 14, *)
public func getLuckyNumber() -> Int {
let keychain = Keychain()
let acctualStudent = keychain["acctualStudent"] ?? "{}"
let data: Data = Data(acctualStudent.utf8)
let acctualStudentJSON = try! JSON(data: data)
let Id = "\(acctualStudentJSON["ConstituentUnit"]["Id"])"
let actualStudent = keychain["actualStudent"] ?? "{}"
let data: Data = Data(actualStudent.utf8)
let actualStudentJSON = try! JSON(data: data)
let Id = "\(actualStudentJSON["ConstituentUnit"]["Id"])"
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let day = formatter.string(from: date)
let RestURL = "\(acctualStudentJSON["Unit"]["RestURL"])/mobile/school/lucky?constituentId=\(Id)&day=\(day)"
let RestURL = "\(actualStudentJSON["Unit"]["RestURL"])/mobile/school/lucky?constituentId=\(Id)&day=\(day)"
let apiResponseRequest = apiRequest(endpointURL: RestURL)

View file

@ -18,8 +18,8 @@ struct wulkanowyApp: App {
init() {
if(isLogged == true) {
let keychain = Keychain()
let acctualStudentId = "\(keychain["acctualStudentId"] ?? "0")"
let accountString = keychain[acctualStudentId]
let actualStudentId = "\(keychain["actualStudentId"] ?? "0")"
let accountString = keychain[actualStudentId]
let data: Data = Data(accountString!.utf8)
let account = try! JSON(data: data)
@ -34,7 +34,7 @@ struct wulkanowyApp: App {
} else if let data = data {
// Handle HTTP request response
let responseBody = String(data: data, encoding: String.Encoding.utf8)
keychain["acctualStudentHebe"] = "\(responseBody!)"
keychain["actualStudentHebe"] = "\(responseBody!)"
} else {
// Handle unexpected error
}

View file

@ -55,6 +55,10 @@ struct AccountManagerView: View {
return json
}
private func setActualAccount() {
print("setting...")
}
var body: some View {
VStack {
Form {
@ -62,19 +66,24 @@ struct AccountManagerView: View {
.font(.title)) {
ForEach(getStudentsNames(), id: \.self) { student in
HStack {
Text(student)
Button("\(student)") { setActualAccount() }
.foregroundColor(Color("customControlColor"))
let keychain = Keychain()
if("\(keychain["actualAccountEmail"] ?? "")" == student) {
Image(systemName: "checkmark.circle")
.foregroundColor(.green)
}
Spacer()
let image = Image(systemName: "pencil")
Button("\(image)") { openEditAccount() }
.sheet(isPresented: $showEditAccountModal, onDismiss: {
print(self.showEditAccountModal)
}) {
EditAccountView()
}
}
}.buttonStyle(BorderlessButtonStyle())
}
}
}.padding(.bottom)
}
Spacer()
Button("addAccount") {addAccount()}
.font(.headline)
@ -84,12 +93,12 @@ struct AccountManagerView: View {
.frame(maxWidth: .infinity)
.background(Color.accentColor.opacity(0.1))
.cornerRadius(12)
.buttonStyle(BorderlessButtonStyle())
.padding()
.sheet(isPresented: $showLoginModal, onDismiss: {
print(self.showLoginModal)
}) {
LoginView()
}
}) {
LoginView()
}
}
}
}

View file

@ -28,12 +28,12 @@ struct EditAccountView: View {
Button("Done") {done()}
.font(.headline)
.multilineTextAlignment(.center)
.padding(.horizontal)
.padding()
.frame(height: 55)
.frame(maxWidth: .infinity)
.background(Color.accentColor.opacity(0.1))
.cornerRadius(12)
}
}.padding()
}
}

View file

@ -14,8 +14,6 @@ struct DashboardView: View {
@AppStorage("isLogged") private var isLogged: Bool = false
init() {
let keychain = Keychain()
if(isLogged == true){
let luckyNumber = getLuckyNumber()

View file

@ -7,6 +7,7 @@
import SwiftUI
import KeychainAccess
import SwiftyJSON
enum AvailableEndpoints: String, CaseIterable {
case vulcan = "Vulcan"
@ -65,22 +66,12 @@ struct LoginView: View {
buttonValue = String(format: NSLocalizedString("invalidData", comment: "loginButton"))
}
} else {
print("success")
let keychain = Keychain()
let keyFingerprint = keychain["keyFingerprint"]
let allStudentsKeys = keychain["allStudentsKeys"] ?? "[]"
let data = Data(allStudentsKeys.utf8)
do {
let array = try JSONSerialization.jsonObject(with: data) as! [String]
if array.contains(keyFingerprint!) {
showingAlert.toggle()
} else {
success = true
}
} catch {
print(error)
if(keychain["accountExist"] == "true") {
showingAlert.toggle()
keychain["accountExist"] = "false"
}
print("success")
}
}
}

View file

@ -20,9 +20,9 @@ struct ChooseStudentView: View {
@State private var selectedStudent: String = ""
init() {
var responseBody = keychain["acctualStudentHebe"]
var responseBody = keychain["actualStudentHebe"]
while responseBody == nil {
responseBody = keychain["acctualStudentHebe"]
responseBody = keychain["actualStudentHebe"]
}
let data = Data(responseBody!.utf8)
@ -43,7 +43,7 @@ struct ChooseStudentView: View {
private func saveStudent() {
let responseBody = keychain["acctualStudentHebe"]
let responseBody = keychain["actualStudentHebe"]
let data = Data(responseBody!.utf8)
let json = try! JSON(data: data)
@ -56,7 +56,7 @@ struct ChooseStudentView: View {
let student = "\(json["Envelope"][i]["Login"]["DisplayName"])"
if(student == selectedStudent) {
//saving student
keychain["acctualStudent"] = "\(json["Envelope"][i])"
keychain["actualStudent"] = "\(json["Envelope"][i])"
break
}
i += 1