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

Swift 2.0 #33

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion AeroGearOAuth2.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,8 @@
4833045919AF1635002F8DA9 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0600;
LastSwiftUpdateCheck = 0700;
LastUpgradeCheck = 0700;
ORGANIZATIONNAME = aerogear;
TargetAttributes = {
4833046119AF1635002F8DA9 = {
Expand Down Expand Up @@ -485,6 +486,7 @@
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
Expand Down Expand Up @@ -562,6 +564,7 @@
INFOPLIST_FILE = AeroGearOAuth2/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "org.aerogear.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
Expand All @@ -580,6 +583,7 @@
INFOPLIST_FILE = AeroGearOAuth2/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "org.aerogear.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
};
Expand All @@ -600,6 +604,7 @@
);
INFOPLIST_FILE = AeroGearOAuth2Tests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "org.aerogear.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
Expand All @@ -617,6 +622,7 @@
);
INFOPLIST_FILE = AeroGearOAuth2Tests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "org.aerogear.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "";
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0600"
LastUpgradeVersion = "0700"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
Expand Down Expand Up @@ -48,6 +48,8 @@
ReferencedContainer = "container:AeroGearOAuth2.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
Expand All @@ -57,6 +59,7 @@
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
Expand Down
2 changes: 1 addition & 1 deletion AeroGearOAuth2/AccountManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ public class AccountManager {
*/
public class func addAccount(config: Config, moduleClass: OAuth2Module.Type) -> OAuth2Module {
var myModule:OAuth2Module
myModule = moduleClass(config: config)
myModule = moduleClass.init(config: config)
// TODO check accountId is unique in modules list
sharedInstance.modules[myModule.oauth2Session.accountId] = myModule
return myModule
Expand Down
10 changes: 5 additions & 5 deletions AeroGearOAuth2/FacebookOAuth2Module.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,15 @@ public class FacebookOAuth2Module: OAuth2Module {
var accessToken: String? = nil
var expiredIn: String? = nil

var charSet: NSMutableCharacterSet = NSMutableCharacterSet()
let charSet: NSMutableCharacterSet = NSMutableCharacterSet()
charSet.addCharactersInString("&=")
let array = unwrappedResponse.componentsSeparatedByCharactersInSet(charSet)
for (index, elt) in enumerate(array) {
for (index, elt) in array.enumerate() {
if elt == "access_token" {
accessToken = array[index+1]
}
}
for (index, elt) in enumerate(array) {
for (index, elt) in array.enumerate() {
if elt == "expires" {
expiredIn = array[index+1]
}
Expand Down Expand Up @@ -117,8 +117,8 @@ public class FacebookOAuth2Module: OAuth2Module {
return
}
if let unwrappedResponse = responseObject as? String {
var data = unwrappedResponse.dataUsingEncoding(NSUTF8StringEncoding)
var json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(0), error: nil)
let data = unwrappedResponse.dataUsingEncoding(NSUTF8StringEncoding)
let json: AnyObject? = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
var openIDClaims: FacebookOpenIDClaim?
if let unwrappedResponse = json as? [String: AnyObject] {
openIDClaims = FacebookOpenIDClaim(fromDict: unwrappedResponse)
Expand Down
2 changes: 1 addition & 1 deletion AeroGearOAuth2/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>org.aerogear.$(PRODUCT_NAME:rfc1034identifier)</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
Expand Down
12 changes: 6 additions & 6 deletions AeroGearOAuth2/KeycloakOAuth2Module.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ public class KeycloakOAuth2Module: OAuth2Module {
completionHandler(nil, nil, error)
return
}
var accessToken = response as? String
let accessToken = response as? String
if let accessToken = accessToken {
var token = self.decode(accessToken)
let token = self.decode(accessToken)
if let decodedToken = token {
openIDClaims = OpenIDClaim(fromDict: decodedToken)
}
Expand Down Expand Up @@ -105,19 +105,19 @@ public class KeycloakOAuth2Module: OAuth2Module {

var stringtoDecode: String = toDecode.stringByReplacingOccurrencesOfString("-", withString: "+") // 62nd char of encoding
stringtoDecode = stringtoDecode.stringByReplacingOccurrencesOfString("_", withString: "/") // 63rd char of encoding
switch (count(stringtoDecode.utf16) % 4) {
switch (stringtoDecode.utf16.count % 4) {
case 2: stringtoDecode = "\(stringtoDecode)=="
case 3: stringtoDecode = "\(stringtoDecode)="
default: // nothing to do stringtoDecode can stay the same
println()
print("")
}
let dataToDecode = NSData(base64EncodedString: stringtoDecode, options: .allZeros)
let dataToDecode = NSData(base64EncodedString: stringtoDecode, options: [])
let base64DecodedString = NSString(data: dataToDecode!, encoding: NSUTF8StringEncoding)

var values: [String: AnyObject]?
if let string = base64DecodedString {
if let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) {
values = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as? [String : AnyObject]
values = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? [String : AnyObject]
}
}
return values
Expand Down
4 changes: 2 additions & 2 deletions AeroGearOAuth2/OAuth2Module.swift
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public class OAuth2Module: AuthzModule {

// calculate final url
let params = "?scope=\(config.scope)&redirect_uri=\(config.redirectURL.urlEncode())&client_id=\(config.clientId)&response_type=code"
let url = NSURL(string:http.calculateURL(config.baseURL, url:config.authzEndpoint).absoluteString! + params)
let url = NSURL(string:http.calculateURL(config.baseURL, url:config.authzEndpoint).absoluteString + params)
if let url = url {
if self.webView != nil {
self.webView!.targetURL = url
Expand Down Expand Up @@ -318,7 +318,7 @@ public class OAuth2Module: AuthzModule {
func parametersFromQueryString(queryString: String?) -> [String: String] {
var parameters = [String: String]()
if (queryString != nil) {
var parameterScanner: NSScanner = NSScanner(string: queryString!)
let parameterScanner: NSScanner = NSScanner(string: queryString!)
var name:NSString? = nil
var value:NSString? = nil

Expand Down
2 changes: 1 addition & 1 deletion AeroGearOAuth2/OAuth2Session.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public protocol OAuth2Session {
/**
The access token's expiration date.
*/
var accessTokenExpirationDate: NSDate? {get set}
var accessTokenExpirationDate: NSDate? {get set}

/**
The refresh token's expiration date.
Expand Down
2 changes: 1 addition & 1 deletion AeroGearOAuth2/OpenIDClaim.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import Foundation
/**
Standard claims as described in spec: http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
*/
public class OpenIDClaim: Printable {
public class OpenIDClaim: CustomStringConvertible {
/// Subject - Identifier for the End-User at the Issuer.
public var sub: String?
/// End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.
Expand Down
52 changes: 26 additions & 26 deletions AeroGearOAuth2/TrustedPersistantOAuth2Session.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,26 +72,26 @@ public class KeychainWrap {
:param: value string value of the token.
*/
public func save(key: String, tokenType: TokenType, value: String) -> Bool {
var dataFromString: NSData? = value.dataUsingEncoding(NSUTF8StringEncoding)
let dataFromString: NSData? = value.dataUsingEncoding(NSUTF8StringEncoding)
if (dataFromString == nil) {
return false
}

// Instantiate a new default keychain query
var keychainQuery = NSMutableDictionary()
let keychainQuery = NSMutableDictionary()
if let groupId = self.groupId {
keychainQuery[kSecAttrAccessGroup as String] = groupId
}
keychainQuery[kSecClass as String] = kSecClassGenericPassword
keychainQuery[kSecAttrService as String] = self.serviceIdentifier
keychainQuery[kSecAttrAccount as String] = key + "_" + tokenType.rawValue
//TODO with Xcode7/swift2/ios9 use @available new feature
if "".respondsToSelector(Selector("containsString:")) == true { // iOS8
keychainQuery[kSecAttrAccessible as String] = kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
} else { //iOS7
keychainQuery[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly

if #available(iOS 8.0, *) {
keychainQuery[kSecAttrAccessible as String] = kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
} else { //ios7
keychainQuery[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
}

// Search for the keychain items
let statusSearch: OSStatus = SecItemCopyMatching(keychainQuery, nil)

Expand All @@ -101,19 +101,19 @@ public class KeychainWrap {
let attributesToUpdate = NSMutableDictionary()
attributesToUpdate[kSecValueData as String] = dataFromString!

var statusUpdate: OSStatus = SecItemUpdate(keychainQuery, attributesToUpdate)
let statusUpdate: OSStatus = SecItemUpdate(keychainQuery, attributesToUpdate)
if (statusUpdate != errSecSuccess) {
println("tokens not updated")
print("tokens not updated")
return false
}
} else { // revoked token or newly installed app, clear KC
return self.resetKeychain()
}
} else if(statusSearch == errSecItemNotFound) { // if new, add
keychainQuery[kSecValueData as String] = dataFromString!
var statusAdd: OSStatus = SecItemAdd(keychainQuery, nil)
let statusAdd: OSStatus = SecItemAdd(keychainQuery, nil)
if(statusAdd != errSecSuccess) {
println("tokens not saved")
print("tokens not saved")
return false
}
} else { // error case
Expand All @@ -130,29 +130,29 @@ public class KeychainWrap {
:param: tokenType type of token: access, refresh.
*/
public func read(userAccount: String, tokenType: TokenType) -> String? {
var keychainQuery = NSMutableDictionary()
let keychainQuery = NSMutableDictionary()
if let groupId = self.groupId {
keychainQuery[kSecAttrAccessGroup as String] = groupId
}
keychainQuery[kSecClass as String] = kSecClassGenericPassword
keychainQuery[kSecAttrService as String] = self.serviceIdentifier
keychainQuery[kSecAttrAccount as String] = userAccount + "_" + tokenType.rawValue
keychainQuery[kSecReturnData as String] = true
//TODO with Xcode7/swift2/ios9 use @available new feature
if "".respondsToSelector(Selector("containsString:")) == true { // iOS8
if #available(iOS 8.0, *) {
keychainQuery[kSecAttrAccessible as String] = kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
} else { //iOS7
} else {
keychainQuery[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
}

var dataTypeRef: Unmanaged<AnyObject>?
// Search for the keychain items
let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)
let status: OSStatus = withUnsafeMutablePointer(&dataTypeRef) { SecItemCopyMatching(keychainQuery as CFDictionaryRef, UnsafeMutablePointer($0)) }

if (status == errSecItemNotFound) {
println("\(tokenType.rawValue) not found")
print("\(tokenType.rawValue) not found")
return nil
} else if (status != errSecSuccess) {
println("Error attempting to retrieve \(tokenType.rawValue) with error code \(status) ")
print("Error attempting to retrieve \(tokenType.rawValue) with error code \(status) ")
return nil
}

Expand All @@ -164,7 +164,7 @@ public class KeychainWrap {
// Convert the data retrieved from the keychain into a string
contentsOfKeychain = NSString(data: retrievedData, encoding: NSUTF8StringEncoding) as? String
} else {
println("Nothing was retrieved from the keychain. Status code \(status)")
print("Nothing was retrieved from the keychain. Status code \(status)")
}

return contentsOfKeychain
Expand All @@ -182,7 +182,7 @@ public class KeychainWrap {
}

func deleteAllKeysForSecClass(secClass: CFTypeRef) -> Bool {
var keychainQuery = NSMutableDictionary()
let keychainQuery = NSMutableDictionary()
keychainQuery[kSecClass as String] = secClass
let result:OSStatus = SecItemDelete(keychainQuery)
if (result == errSecSuccess) {
Expand All @@ -208,7 +208,7 @@ public class TrustedPersistantOAuth2Session: OAuth2Session {
*/
public var accessTokenExpirationDate: NSDate? {
get {
var dateAsString = self.keychain.read(self.accountId, tokenType: .ExpirationDate)
let dateAsString = self.keychain.read(self.accountId, tokenType: .ExpirationDate)
if let unwrappedDate:String = dateAsString {
return NSDate(dateString: unwrappedDate)
} else {
Expand All @@ -217,7 +217,7 @@ public class TrustedPersistantOAuth2Session: OAuth2Session {
}
set(value) {
if let unwrappedValue = value {
let result = self.keychain.save(self.accountId, tokenType: .ExpirationDate, value: unwrappedValue.toString())
self.keychain.save(self.accountId, tokenType: .ExpirationDate, value: unwrappedValue.toString())
}
}
}
Expand All @@ -231,7 +231,7 @@ public class TrustedPersistantOAuth2Session: OAuth2Session {
}
set(value) {
if let unwrappedValue = value {
let result = self.keychain.save(self.accountId, tokenType: .AccessToken, value: unwrappedValue)
self.keychain.save(self.accountId, tokenType: .AccessToken, value: unwrappedValue)
}
}
}
Expand All @@ -255,7 +255,7 @@ public class TrustedPersistantOAuth2Session: OAuth2Session {
*/
public var refreshTokenExpirationDate: NSDate? {
get {
var dateAsString = self.keychain.read(self.accountId, tokenType: .RefreshExpirationDate)
let dateAsString = self.keychain.read(self.accountId, tokenType: .RefreshExpirationDate)
if let unwrappedDate:String = dateAsString {
return NSDate(dateString: unwrappedDate)
} else {
Expand All @@ -264,7 +264,7 @@ public class TrustedPersistantOAuth2Session: OAuth2Session {
}
set(value) {
if let unwrappedValue = value {
let result = self.keychain.save(self.accountId, tokenType: .RefreshExpirationDate, value: unwrappedValue.toString())
_ = self.keychain.save(self.accountId, tokenType: .RefreshExpirationDate, value: unwrappedValue.toString())
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions AeroGearOAuth2Tests/ConfigTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class ConfigTests: XCTestCase {
clientId: "clientid",
clientSecret: "secret",
scopes:["photo_upload, publish_actions"])
println(facebookConfig.scopes)
print(facebookConfig.scopes)
XCTAssert(facebookConfig.scopes[0].rangeOfString("public_profile") == nil, "no public_profile defined per default")
}

Expand All @@ -65,7 +65,7 @@ class ConfigTests: XCTestCase {
clientSecret: "secret",
scopes:["photo_upload, publish_actions"],
isOpenIDConnect: true)
println(facebookConfig.scopes)
print(facebookConfig.scopes)
XCTAssert(facebookConfig.scopes[0] == "photo_upload, publish_actions, public_profile", "public_profile defined for Open ID Connect config, facebook does not use openid")

}
Expand Down