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

Simplye 188 #3

Merged
merged 21 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
c1cd834
- started on passkey login
Kaappihullu Feb 1, 2024
b97d862
- started on passkey login
Kaappihullu Feb 7, 2024
308b9cb
- started on passkey login
Kaappihullu Feb 7, 2024
ce6268d
- fixed crash when you try to login.
Kaappihullu Feb 8, 2024
7f3a67c
Passkey logic - incomplete
Kaappihullu Feb 22, 2024
b0c2870
Passkey logic - incomplete
Kaappihullu Feb 26, 2024
a7902c9
Passkey logic - incomplete
Kaappihullu Feb 28, 2024
5ff67dd
Passkey logic - should work now, cannot test it without circulation u…
Kaappihullu Feb 29, 2024
fd2ac9f
Passkey logic - should work now, cannot test it without circulation u…
Kaappihullu Feb 29, 2024
083fa2b
Merge remote-tracking branch 'github/simplye-188' into simplye-188
Kaappihullu Mar 1, 2024
5ec9ad2
Merge remote-tracking branch 'github/simplye-188' into simplye-188
Kaappihullu Mar 1, 2024
e65f7c5
Merge remote-tracking branch 'github/simplye-188' into simplye-188
Kaappihullu Mar 1, 2024
c329251
Merge remote-tracking branch 'github/simplye-188' into simplye-188
Kaappihullu Mar 1, 2024
c76ed19
fixes to unit-testing.yml
Kaappihullu Mar 1, 2024
db1d2b9
fixes to unit-testing.yml
Kaappihullu Mar 1, 2024
5122b82
fixes to unit-testing.yml
Kaappihullu Mar 1, 2024
e46a34f
fixes to unit-testing.yml
Kaappihullu Mar 1, 2024
129e77b
fixes to unit-testing.yml
Kaappihullu Mar 4, 2024
4d88938
fixes to unit-testing.yml
Kaappihullu Mar 5, 2024
a4b6c25
fixes to unit-testing.yml, removed password fields from settings tab
Kaappihullu Mar 5, 2024
ca92c20
fixes to unit-testing.yml
Kaappihullu Mar 6, 2024
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
40 changes: 22 additions & 18 deletions .github/workflows/unit-testing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,31 @@ jobs:
run: sudo xcode-select -switch /Applications/Xcode_15.0.1.app
- name: Checkout main repo and submodules
uses: actions/checkout@v3
with:
submodules: true
token: ${{ secrets.CI_GITHUB_ACCESS_TOKEN }}
- name: Checkout Certificates
uses: actions/checkout@v3
with:
repository: ThePalaceProject/mobile-certificates
token: ${{ secrets.CI_GITHUB_ACCESS_TOKEN }}
path: ./mobile-certificates
- name: Checkout Adobe RMSDK
uses: actions/checkout@v3
with:
repository: ThePalaceProject/mobile-drm-adeptconnector
token: ${{ secrets.CI_GITHUB_ACCESS_TOKEN }}
path: ./mobile-drm-adeptconnector
- name: Uncompress Adobe RMSDK
run: ./scripts/setup-repo-drm.sh
- name: Set up repo for nonDRM build
run: exec ./scripts/setup-repo-nodrm-github.sh
env:
BUILD_CONTEXT: ci
# with:
# submodules: true
# token: ${{ secrets.CI_GITHUB_ACCESS_TOKEN }}
# - name: Checkout Certificates
# uses: actions/checkout@v3
# with:
# repository: ThePalaceProject/mobile-certificates
# token: ${{ secrets.CI_GITHUB_ACCESS_TOKEN }}
# path: ./mobile-certificates
# - name: Checkout Adobe RMSDK
# uses: actions/checkout@v3
# with:
# repository: ThePalaceProject/mobile-drm-adeptconnector
# token: ${{ secrets.CI_GITHUB_ACCESS_TOKEN }}
# path: ./mobile-drm-adeptconnector
# - name: Uncompress Adobe RMSDK
# run: ./scripts/setup-repo-drm.sh
# env:
# BUILD_CONTEXT: ci
- name: Build non-Carthage 3rd party dependencies
run: ./scripts/build-3rd-party-dependencies.sh
run: ./scripts/build-3rd-party-dependencies.sh --no-private
env:
BUILD_CONTEXT: ci
- name: Build Palace without DRM support
Expand Down
77 changes: 39 additions & 38 deletions Palace.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions Palace/Accounts/User/TPPCredentials.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,11 @@ extension TPPCredentials: Codable {
case .token:
let additionalInfo = try values.nestedContainer(keyedBy: TokenKeys.self, forKey: .associatedTokenData)
let token = try additionalInfo.decode(String.self, forKey: .authToken)
let expirationDate = try additionalInfo.decode(Date.self, forKey: .expirationDate)
let expirationDate = try? additionalInfo.decode(Date.self, forKey: .expirationDate)

let barcodePinInfo = try values.nestedContainer(keyedBy: BarcodeAndPinKeys.self, forKey: .associatedBarcodeAndPinData)
let barcode = try barcodePinInfo.decode(String.self, forKey: .barcode)
let pin = try barcodePinInfo.decode(String.self, forKey: .pin)
let barcode = try? barcodePinInfo.decode(String.self, forKey: .barcode)
let pin = try? barcodePinInfo.decode(String.self, forKey: .pin)
self = .token(authToken: token, barcode: barcode, pin: pin, expirationDate: expirationDate)

case .barcodeAndPin:
Expand Down
31 changes: 24 additions & 7 deletions Palace/Accounts/User/TPPUserAccount.swift
Original file line number Diff line number Diff line change
Expand Up @@ -361,16 +361,29 @@ private enum StorageKey: String {
}

var authTokenHasExpired: Bool {
guard let credentials = credentials,
case let TPPCredentials.token(authToken: token) = credentials,
let expirationDate = token.expirationDate, expirationDate > Date()
else {
return true

if let credentials = credentials {
if case let TPPCredentials.token(authToken: token) = credentials {
if let expirationDate = token.expirationDate {
return expirationDate > Date()
}else{//no expiration date, will ask user to re-login when token is no longer accepted
return false
}
}
}
return false

return false
}


var authTokenExpirationDate: Date?{
if let credentials = credentials {
if case let TPPCredentials.token(authToken: token) = credentials {
return token.expirationDate
}
}
return nil
}

var patronFullName: String? {
if let patron = patron,
let name = patron["name"] as? [String:String]
Expand Down Expand Up @@ -457,6 +470,10 @@ private enum StorageKey: String {
func setAuthToken(_ token: String, barcode: String?, pin: String?, expirationDate: Date?) {
credentials = .token(authToken: token, barcode: barcode, pin: pin, expirationDate: expirationDate)
}

func setEKirjastoToken(_ token: String){

}

@objc(setCookies:)
func setCookies(_ cookies: [HTTPCookie]) {
Expand Down
6 changes: 0 additions & 6 deletions Palace/AppInfrastructure/TPPAppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
import Foundation
import FirebaseCore
import FirebaseDynamicLinks
import GoogleSignIn

@main
class TPPAppDelegate: UIResponder, UIApplicationDelegate {

Expand Down Expand Up @@ -141,10 +139,6 @@ class TPPAppDelegate: UIResponder, UIApplicationDelegate {
return true
}

if GIDSignIn.sharedInstance.handle(url){
return true
}

return false
}

Expand Down
2 changes: 1 addition & 1 deletion Palace/Catalog/TPPCatalogGroupedFeed.m
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ @interface TPPCatalogGroupedFeed ()

@property (nonatomic) NSArray *lanes;
@property (nonatomic) NSURL *openSearchURL;
@property (nonatomic) NSString *title;
@property (nonatomic,readwrite) NSString *title;
@property (nonatomic) NSArray<TPPCatalogFacet *> *entryPoints;


Expand Down
6 changes: 3 additions & 3 deletions Palace/EkirjastoConfig/Ekirjasto-Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>org.thepalaceproject.palace</string>
<string>fi.kansalliskirjasto.e-kirjasto</string>
<key>CFBundleURLSchemes</key>
<array>
<string>PalaceApp</string>
Expand All @@ -40,6 +40,8 @@
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>LSApplicationCategoryType</key>
<string></string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
Expand Down Expand Up @@ -108,8 +110,6 @@
</array>
<key>UIUserInterfaceStyle</key>
<string>Automatic</string>
<key>LSApplicationCategoryType</key>
<string></string>
<key>UIWhitePointAdaptivityStyle</key>
<string>UIWhitePointAdaptivityStyleReading</string>
</dict>
Expand Down
5 changes: 4 additions & 1 deletion Palace/MyBooks/MyBooksDownloadCenter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,10 @@ import OverdriveProcessor
if userAccount.hasCredentials() || !(loginRequired ?? false) {
processDownloadWithCredentials(for: book, withState: state, andRequest: initedRequest)
} else {
requestCredentialsAndStartDownload(for: book)
EkirjastoLoginViewController.show {
self.processDownloadWithCredentials(for: book, withState: state, andRequest: initedRequest)
}
//requestCredentialsAndStartDownload(for: book)
}
}

Expand Down
107 changes: 95 additions & 12 deletions Palace/Network/TPPNetworkExecutor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,79 @@ extension TPPNetworkExecutor: TPPRequestExecuting {

if let authDefinition = TPPUserAccount.sharedAccount().authDefinition, authDefinition.isSaml {
resultTask = performDataTask(with: req, completion: completion)
} else if !TPPUserAccount.sharedAccount().authTokenHasExpired && req.isTokenAuthorized && TPPUserAccount.sharedAccount().authTokenExpirationDate == nil {

resultTask = performDataTask(with: req) { result in
switch result{
case .failure(let error, let response):
if req.hasRetried {
completion(result)
}else{
var updatedRequest = req
updatedRequest.hasRetried = true
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 401 {
self.authenticateWithToken(TPPUserAccount.sharedAccount().authToken!) { status in
if status == 401 {
EkirjastoLoginViewController.show {
if let token = TPPUserAccount.sharedAccount().authToken {
updatedRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
self.executeRequest(updatedRequest, completion: completion)
}else{
completion(result)
}

}
}else if status == 200 {

if let token = TPPUserAccount.sharedAccount().authToken {
updatedRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
self.executeRequest(updatedRequest, completion: completion)
}else{
completion(result)
}
}else {
completion(result)
}
}
}
}else{
completion(result)
}
}

case .success(_, _):
completion(result)
}
}
} else if !TPPUserAccount.sharedAccount().authTokenHasExpired || !req.isTokenAuthorized || req.hasRetried {
if req.hasRetried {
let error = NSError(domain: TPPErrorLogger.clientDomain, code: TPPErrorCode.invalidCredentials.rawValue, userInfo: [NSLocalizedDescriptionKey: "Unauthorized HTTP after token refresh attempt"])
completion(NYPLResult.failure(error, nil))
} else {
resultTask = performDataTask(with: req, completion: completion)
resultTask = performDataTask(with: req, completion: { result in

if case .failure(let error, let response) = result {
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 401 {
self.authenticateWithToken(TPPUserAccount.sharedAccount().authToken!) { status in
if status == 401 {
EkirjastoLoginViewController.show {
self.executeRequest(req, completion: completion)
}
}else if status == 200 {
self.executeRequest(req, completion: completion)
}else{
completion(result)
}
}
}
}
}else {
completion(result)
}

})
}
} else {
handleTokenRefresh(for: req, completion: completion)
Expand All @@ -114,7 +181,6 @@ extension TPPNetworkExecutor: TPPRequestExecuting {
}
private func performDataTask(with request: URLRequest,
completion: @escaping (_: NYPLResult<Data>) -> Void) -> URLSessionDataTask {
print("request url: \(request.url)")
let task = urlSession.dataTask(with: request)
responder.addCompletion(completion, taskID: task.taskIdentifier)
Log.info(#file, "Task \(task.taskIdentifier): starting request \(request.loggableString)")
Expand Down Expand Up @@ -337,43 +403,60 @@ extension TPPNetworkExecutor {
}
}

func authenticateWithToken(_ token: String){
let currentAccount = AccountsManager.shared.currentAccount
func authenticateWithToken(_ token: String, completion: ((Int?)->Void)? = nil){
var currentAccount = AccountsManager.shared.currentAccount
if currentAccount?.authenticationDocument == nil {
currentAccount = AccountsManager.shared.accounts().first
}
let authenticationDocument = currentAccount?.authenticationDocument
let authentication = authenticationDocument?.authentication?.first(where: { $0.type == "http://e-kirjasto.fi/authtype/ekirjasto"})

let link = authentication?.links?.first(where: {$0.rel == "authenticate"})

var request = URLRequest(url: URL(string:link!.href)!)
request.httpMethod = "POST"
print("token \(token)")
request.setValue(
"Bearer \(token)",
forHTTPHeaderField: "Authorization"
)
print("access token \(token)")
URLSession.shared.dataTask(with: request){ data, response, error in
print("auth error: \(error.debugDescription))")
print("auth result: \(String(bytes: data!.bytes, encoding: .utf8))")

if(data != nil){
let json = try? JSONSerialization.jsonObject(with: data!)
let jsonRoot = json as? [String: Any]
let accessToken = jsonRoot!["access_token"] as! String

let sharedAccount = TPPUserAccount.sharedAccount()
let accessToken = jsonRoot?["access_token"] as? String

if let accessToken = accessToken {
let sharedAccount = TPPUserAccount.sharedAccount()
sharedAccount.setAuthToken(accessToken,barcode: nil, pin: nil, expirationDate: nil)
}else{
print("authenticateWithToken error: \(String(describing: error?.localizedDescription)) data: \(String(describing: String(data:data!,encoding: .utf8)))")
}

sharedAccount.setAuthToken(accessToken,barcode: nil, pin: nil, expirationDate: nil)

}
if let httpResponse = response as? HTTPURLResponse {
completion?(httpResponse.statusCode)
}else{
completion?(nil)
}


}.resume()

}

func userInfo(_ complete: (String?)->(Void)){

//let (data, _) = try await URLSession.shared.data(for: request)
}

func revokeToken(_ sessionId: String? = nil){

}

func executeTokenRefresh(username: String, password: String, completion: @escaping (Result<TokenResponse, Error>) -> Void) {
let account = TPPUserAccount.sharedAccount()
guard let tokenURL = TPPUserAccount.sharedAccount().authDefinition?.tokenURL else {
Log.error(#file, "Unable to refresh token, missing credentials")
completion(.failure(NSError(domain: "Unable to refresh token, missing credentials", code: 401)))
Expand Down
1 change: 1 addition & 0 deletions Palace/Network/TPPNetworkResponder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ extension TPPNetworkResponder: URLSessionDataDelegate {
}

private func handleNetworkError(_ networkError: Error, for task: URLSessionTask, currentTaskInfo: TPPNetworkTaskInfo, logMetadata: [String: Any]) {
let response = task.response
currentTaskInfo.completion(.failure(networkError as TPPUserFriendlyError, task.response))
TPPErrorLogger.logNetworkError(
networkError,
Expand Down
Loading
Loading