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

pakhoosz changes #3

Open
wants to merge 6 commits into
base: testing_lanuch
Choose a base branch
from
Open
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
20 changes: 13 additions & 7 deletions OpenParsec.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
27E61AA8292994B500FF6563 /* ActivityIndicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27E61AA7292994B500FF6563 /* ActivityIndicator.swift */; };
27E61AAA2929B92200FF6563 /* MainView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27E61AA92929B92200FF6563 /* MainView.swift */; };
27ED36FF292D4F9800B1BE3D /* NetworkHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27ED36FE292D4F9800B1BE3D /* NetworkHandler.swift */; };
FC16A7AD29A97BDA00BB70A7 /* Shared.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC16A7AC29A97BDA00BB70A7 /* Shared.swift */; };
/* End PBXBuildFile section */

/* Begin PBXCopyFilesBuildPhase section */
Expand All @@ -48,7 +49,7 @@
27899AC5292FE2A9001ACA33 /* audio.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = audio.c; sourceTree = "<group>"; };
27899AC6292FE2A9001ACA33 /* audio.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = audio.h; sourceTree = "<group>"; };
27B8D563292DC7A000A324AD /* CParsec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CParsec.swift; sourceTree = "<group>"; };
27B8D56F292DCA5800A324AD /* ParsecSDK.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ParsecSDK.framework; path = "../../../../../Users/mike/Documents/Repositories/parsec-sdk/sdk/ios/ParsecSDK.framework"; sourceTree = "<group>"; };
27B8D56F292DCA5800A324AD /* ParsecSDK.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = ParsecSDK.framework; sourceTree = "<group>"; };
27E61A8E292965FC00FF6563 /* OpenParsec.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = OpenParsec.app; sourceTree = BUILT_PRODUCTS_DIR; };
27E61A91292965FC00FF6563 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
27E61A93292965FC00FF6563 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
Expand All @@ -61,6 +62,8 @@
27E61AA7292994B500FF6563 /* ActivityIndicator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ActivityIndicator.swift; sourceTree = "<group>"; };
27E61AA92929B92200FF6563 /* MainView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainView.swift; sourceTree = "<group>"; };
27ED36FE292D4F9800B1BE3D /* NetworkHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetworkHandler.swift; sourceTree = "<group>"; };
FC16A7AC29A97BDA00BB70A7 /* Shared.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Shared.swift; sourceTree = "<group>"; };
FC746E7A2981A920003D191A /* parsec.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = parsec.h; path = "../../parsec-sdk/sdk/parsec.h"; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand All @@ -78,6 +81,7 @@
27B8D56A292DC98B00A324AD /* Frameworks */ = {
isa = PBXGroup;
children = (
FC746E7A2981A920003D191A /* parsec.h */,
27B8D56F292DCA5800A324AD /* ParsecSDK.framework */,
);
path = Frameworks;
Expand Down Expand Up @@ -121,6 +125,7 @@
27B8D563292DC7A000A324AD /* CParsec.swift */,
271D14F8292E90EB00D7F1D6 /* ParsecView.swift */,
27899AC4292FE2A8001ACA33 /* OpenParsec-Bridging-Header.h */,
FC16A7AC29A97BDA00BB70A7 /* Shared.swift */,
);
path = OpenParsec;
sourceTree = "<group>";
Expand Down Expand Up @@ -205,6 +210,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
FC16A7AD29A97BDA00BB70A7 /* Shared.swift in Sources */,
27E61A92292965FC00FF6563 /* AppDelegate.swift in Sources */,
27E61AAA2929B92200FF6563 /* MainView.swift in Sources */,
271D14FD292EAA3600D7F1D6 /* ParsecGLKViewController.swift in Sources */,
Expand Down Expand Up @@ -358,15 +364,15 @@
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"OpenParsec/Preview Content\"";
DEVELOPMENT_TEAM = NMU32WR5KZ;
DEVELOPMENT_TEAM = 7EVW949E9Y;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = OpenParsec/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = io.github.AngelDTF.OpenParsec;
PRODUCT_BUNDLE_IDENTIFIER = io.github.LeaveNhA.OpenParsec;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "OpenParsec/OpenParsec-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
Expand All @@ -385,15 +391,15 @@
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"OpenParsec/Preview Content\"";
DEVELOPMENT_TEAM = NMU32WR5KZ;
DEVELOPMENT_TEAM = 7EVW949E9Y;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = OpenParsec/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = io.github.AngelDTF.OpenParsec;
PRODUCT_BUNDLE_IDENTIFIER = io.github.LeaveNhA.OpenParsec;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "OpenParsec/OpenParsec-Bridging-Header.h";
SWIFT_VERSION = 5.0;
Expand Down
2 changes: 1 addition & 1 deletion OpenParsec/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ enum ViewType

struct ContentView:View
{
@State var curView:ViewType = .login
@State var curView:ViewType = .main

let defaultTransition = AnyTransition.move(edge:.trailing)

Expand Down
168 changes: 118 additions & 50 deletions OpenParsec/LoginView.swift
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
import SwiftUI
import os

struct LoginView:View
{
var controller:ContentView?

@State var inputEmail:String = ""
@State var inputPassword:String = ""
@State var isLoading:Bool = false
@State var inputTFA:String = ""
@State var isTFAOn:Bool = false
@State private var presentTFAAlert = false
@State var isLoading:Bool = false
@State var showAlert:Bool = false
@State var alertText:String = ""

init(_ controller:ContentView?)
{
self.controller = controller
}

var body:some View
var body:some View
{
ZStack()
{
Expand All @@ -25,47 +29,52 @@ struct LoginView:View
.edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)

// Login controls
VStack(spacing:8)
{
HStack(spacing:2)
{
Image("IconTransparent")
.resizable()
.aspectRatio(contentMode: .fit)
Image("LogoShadow")
.resizable()
.aspectRatio(contentMode: .fit)
.padding([.top, .bottom, .trailing])
}
.frame(height:80)
TextField("Email", text: $inputEmail)
.padding()
.background(Rectangle().fill(Color("BackgroundField")))
.cornerRadius(8)
.disableAutocorrection(true)
.autocapitalization(/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/)
.keyboardType(.emailAddress)
.textContentType(.emailAddress)
SecureField("Password", text: $inputPassword)
.padding()
.background(Rectangle().fill(Color("BackgroundField")))
.cornerRadius(8)
.disableAutocorrection(true)
.autocapitalization(/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/)
.textContentType(.password)
Button(action:authenticate)
{
ZStack()
{
Rectangle()
.fill(Color("AccentColor"))
.cornerRadius(8)
Text("Login")
.foregroundColor(.white)
}
.frame(height:54)
}
}
VStack{
VStack(spacing:8)
{
HStack(spacing:2)
{
Image("IconTransparent")
.resizable()
.aspectRatio(contentMode: .fit)
Image("LogoShadow")
.resizable()
.aspectRatio(contentMode: .fit)
.padding([.top, .bottom, .trailing])
}
.frame(height:80)
TextField("Email", text: $inputEmail)
.padding()
.background(Rectangle().fill(Color("BackgroundField")))
.cornerRadius(8)
.disableAutocorrection(true)
.autocapitalization(/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/)
.keyboardType(.emailAddress)
.textContentType(.emailAddress)
SecureField("Password", text: $inputPassword)
.padding()
.background(Rectangle().fill(Color("BackgroundField")))
.cornerRadius(8)
.disableAutocorrection(true)
.autocapitalization(/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/)
.textContentType(.password)
}
VStack(spacing: 8){
Button(action:authenticate)
{
ZStack()
{
Rectangle()
.fill(Color("AccentColor"))
.cornerRadius(8)
Text("Login")
.foregroundColor(.white)
}
.frame(height:54)
}
}
}

.padding()
.frame(maxWidth:400)
.disabled(isLoading) // Disable when loading
Expand Down Expand Up @@ -98,7 +107,26 @@ struct LoginView:View
{
Alert(title:Text(alertText))
}
.alert("Login", isPresented: $presentTFAAlert, actions: {
SecureField("TFA Code:", text: $inputTFA)
Button("Enter", action: authenticate)
Button("Cancel", role: .cancel, action: {})
}, message: {
Text("Please enter your TFA code from your Authentication app.")
})
}

func saveToKeychain(data: Data, key: String) {
let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecValueData as String: data]
let status = SecItemAdd(query as CFDictionary, nil)
guard status == errSecSuccess else {
print("Error saving to Keychain: \(status)")
return
}
print("Data saved to Keychain.")
}

func authenticate()
{
Expand All @@ -123,7 +151,8 @@ struct LoginView:View
request.httpBody = try? JSONSerialization.data(withJSONObject:
[
"email":inputEmail,
"password":inputPassword
"password":inputPassword,
"tfa": inputTFA
], options:[])

let task = URLSession.shared.dataTask(with:request)
Expand All @@ -134,24 +163,63 @@ struct LoginView:View
let statusCode:Int = (response as! HTTPURLResponse).statusCode
let decoder = JSONDecoder()

print("Login Informations:")
print(statusCode)
print(String(data:data, encoding:.utf8)!)

if statusCode == 201 // 201 Created
{
NetworkHandler.clinfo = try? decoder.decode(ClientInfo.self, from:data)
// store it and recover it from the next app opening, so people won't swear
NetworkHandler.clinfo = try? decoder.decode(ClientInfo.self, from:data)

saveToKeychain(data: data, key: GLBDataModel.shared.SessionKeyChainKey)

if let c = controller
{
let l = Logger(subsystem: "io.github.LeaveNhA.OpenParsec",
category: "main")
let dataEncoded:String = String(decoding: data, as: UTF8.self)
c.setView(.main)
l.info("+++++++")
l.info("Login successed!")
if #available(iOS 14.0, *) {
l.info("\(dataEncoded)")
} else {
// Fallback on earlier versions
}
if #available(iOS 14.0, *) {
l.info("\(response)")
} else {
// Fallback on earlier versions
}
if #available(iOS 14.0, *) {
l.info("\(error)")
} else {
// Fallback on earlier versions
}
l.info("-------")
}
}
else if statusCode >= 400 // 4XX client errors
{
let info:ErrorInfo = try! decoder.decode(ErrorInfo.self, from:data)

alertText = "Error: \(info.error)"
showAlert = true

do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let dict = json as? [String: Any], let isTFARequired = dict["tfa_required"] as? Bool {
print("Code output:")
print(dict)
if isTFARequired{
presentTFAAlert = true
}
else {
alertText = "Error: \(info)"
showAlert = true
}
}
} catch {
print("Error on trying JSON Serialization on error data!")
}
}
}
}
Expand Down
40 changes: 36 additions & 4 deletions OpenParsec/MainView.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import SwiftUI
import Security
import ParsecSDK

struct MainView:View
Expand Down Expand Up @@ -28,8 +29,37 @@ struct MainView:View

init(_ controller:ContentView?)
{
self.controller = controller
self.controller = controller

restoreAndMoveWithOldSession()
}

func restoreAndMoveWithOldSession(){
if let data = loadFromKeychain(key: GLBDataModel.shared.SessionKeyChainKey) {
let decoder = JSONDecoder()

print("Retrieved data from Keychain: \(data).\nAnd restoring the session.")
NetworkHandler.clinfo = try? decoder.decode(ClientInfo.self, from:data)
print("Session restored and moved to the Main Page.")
}
}

func loadFromKeychain(key: String) -> Data? {
let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecReturnData as String: kCFBooleanTrue!,
kSecMatchLimit as String: kSecMatchLimitOne]
var item: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &item)
guard status == errSecSuccess else {
print("Error loading from Keychain: \(status)")
return nil
}
guard let data = item as? Data else {
return nil
}
return data
}

var body:some View
{
Expand Down Expand Up @@ -248,9 +278,11 @@ struct MainView:View
{
let info:HostInfoList = try! decoder.decode(HostInfoList.self, from:data)
hosts.removeAll()
info.data.forEach
{ h in
hosts.append(IdentifiableHostInfo(id:h.peer_id, hostname:h.name, user:h.user))
if let datas = info.data
{
datas.forEach { h in
hosts.append(IdentifiableHostInfo(id:h.peer_id, hostname:h.name, user:h.user))
}
}

let formatter = DateFormatter()
Expand Down
2 changes: 1 addition & 1 deletion OpenParsec/NetworkHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,6 @@ struct HostInfo:Decodable

struct HostInfoList:Decodable
{
var data:Array<HostInfo>
var data:Array<HostInfo>?
var has_more:Bool
}
Loading