| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614 |
- // Copyright 2020 Google LLC
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- import Foundation
- import Combine
- import XCTest
- import FirebaseAuth
- class SignInWithCredentialTests: XCTestCase {
- override class func setUp() {
- FirebaseApp.configureForTests()
- }
- override class func tearDown() {
- FirebaseApp.app()?.delete { success in
- if success {
- print("Shut down app successfully.")
- } else {
- print("💥 There was a problem when shutting down the app..")
- }
- }
- }
- override func setUp() {
- do {
- try Auth.auth().signOut()
- } catch {}
- }
- static let apiKey = Credentials.apiKey
- static let accessTokenTimeToLive: TimeInterval = 60 * 60
- static let refreshToken = "REFRESH_TOKEN"
- static let accessToken = "ACCESS_TOKEN"
- static let email = "johnnyappleseed@apple.com"
- static let password = "secret"
- static let localID = "LOCAL_ID"
- static let displayName = "Johnny Appleseed"
- static let passwordHash = "UkVEQUNURUQ="
- static let oAuthSessionID = "sessionID"
- static let oAuthRequestURI = "requestURI"
- static let googleID = "GOOGLE_ID"
- static let googleAccessToken = "GOOGLE_ACCESS_TOKEN"
- static let googleDisplayName = "Google Doe"
- static let googleEmail = "user@gmail.com"
- static let googleProfile: [String: String] = {
- [
- "iss": "https://accounts.google.com\\",
- "email": googleEmail,
- "given_name": "User",
- "family_name": "Doe",
- ]
- }()
- static let verificationCode = "12345678"
- static let verificationID = "55432"
- static let fakeEmailSignInlink =
- "https://test.app.goo.gl/?link=https://test.firebaseapp.com/__/auth/action?apiKey%3DtestAPIKey%26mode%3DsignIn%26oobCode%3Dtestoobcode%26continueUrl%3Dhttps://test.apps.com&ibi=com.test.com&ifl=https://test.firebaseapp.com/__/auth/action?apiKey%3DtestAPIKey%26mode%3DsignIn%26oobCode%3Dtestoobcode%26continueUrl%3Dhttps://test.apps.com"
- static let fakeOOBCode = "testoobcode"
- class MockEmailLinkSignInResponse: FIREmailLinkSignInResponse {
- override var idToken: String { SignInWithCredentialTests.accessToken }
- override var refreshToken: String { SignInWithCredentialTests.refreshToken }
- override var approximateExpirationDate: Date {
- Date(timeIntervalSinceNow: SignInWithCredentialTests.accessTokenTimeToLive)
- }
- }
- class MockVerifyPasswordResponse: FIRVerifyPasswordResponse {
- override var idToken: String? { SignInWithCredentialTests.accessToken }
- override var refreshToken: String? { SignInWithCredentialTests.refreshToken }
- override var approximateExpirationDate: Date? {
- Date(timeIntervalSinceNow: SignInWithCredentialTests.accessTokenTimeToLive)
- }
- }
- class MockVerifyAssertionResponse: FIRVerifyAssertionResponse {
- override var federatedID: String? { SignInWithCredentialTests.googleID }
- override var providerID: String? { GoogleAuthProviderID }
- override var localID: String? { SignInWithCredentialTests.localID }
- override var displayName: String? { SignInWithCredentialTests.displayName }
- override var username: String? { SignInWithCredentialTests.displayName }
- override var profile: [String: NSObject]? {
- SignInWithCredentialTests.googleProfile as [String: NSString]
- }
- override var idToken: String { SignInWithCredentialTests.accessToken }
- override var refreshToken: String { SignInWithCredentialTests.refreshToken }
- override var approximateExpirationDate: Date {
- Date(timeIntervalSinceNow: SignInWithCredentialTests.accessTokenTimeToLive)
- }
- }
- class MockVerifyPhoneNumberResponse: FIRVerifyPhoneNumberResponse {
- override var idToken: String? { SignInWithCredentialTests.accessToken }
- override var refreshToken: String? { SignInWithCredentialTests.refreshToken }
- override var approximateExpirationDate: Date? {
- Date(timeIntervalSinceNow: SignInWithCredentialTests.accessTokenTimeToLive)
- }
- }
- class MockGetAccountInfoResponseUser: FIRGetAccountInfoResponseUser {
- override var localID: String { SignInWithCredentialTests.localID }
- override var email: String { SignInWithCredentialTests.email }
- override var displayName: String { SignInWithCredentialTests.displayName }
- }
- class MockGetAccountInfoResponse: FIRGetAccountInfoResponse {
- override var users: [FIRGetAccountInfoResponseUser] {
- return [MockGetAccountInfoResponseUser(dictionary: [:])]
- }
- }
- class MockAuthBackend: AuthBackendImplementationMock {
- var emailLinkSignInCallback: Result<FIREmailLinkSignInResponse, Error> =
- .success(MockEmailLinkSignInResponse())
- override func emailLinkSignin(_ request: FIREmailLinkSignInRequest,
- callback: @escaping FIREmailLinkSigninResponseCallback) {
- XCTAssertEqual(request.apiKey, SignInWithCredentialTests.apiKey)
- XCTAssertEqual(request.email, SignInWithCredentialTests.email)
- XCTAssertEqual(request.oobCode, SignInWithCredentialTests.fakeOOBCode)
- switch emailLinkSignInCallback {
- case let .success(response):
- callback(response, nil)
- case let .failure(error):
- callback(nil, error)
- }
- }
- override func verifyPhoneNumber(_ request: FIRVerifyPhoneNumberRequest,
- callback: @escaping FIRVerifyPhoneNumberResponseCallback) {
- XCTAssertEqual(request.verificationCode, SignInWithCredentialTests.verificationCode)
- XCTAssertEqual(request.verificationID, SignInWithCredentialTests.verificationID)
- XCTAssertEqual(request.operation, FIRAuthOperationType.signUpOrSignIn)
- let response = MockVerifyPhoneNumberResponse()
- response.isNewUser = true
- callback(response, nil)
- }
- var verifyAssertionCallBack: Result<FIRVerifyAssertionResponse, Error> =
- .success(MockVerifyAssertionResponse())
- override func verifyAssertion(_ request: FIRVerifyAssertionRequest,
- callback: @escaping FIRVerifyAssertionResponseCallback) {
- XCTAssertEqual(request.apiKey, SignInWithCredentialTests.apiKey)
- XCTAssertEqual(request.providerID, GoogleAuthProviderID)
- XCTAssertTrue(request.returnSecureToken)
- switch verifyAssertionCallBack {
- case let .success(response):
- callback(response, nil)
- case let .failure(error):
- callback(nil, error)
- }
- }
- var verifyPasswordCallback: Result<FIRVerifyPasswordResponse, Error> =
- .success(MockVerifyPasswordResponse())
- override func verifyPassword(_ request: FIRVerifyPasswordRequest,
- callback: @escaping FIRVerifyPasswordResponseCallback) {
- XCTAssertEqual(request.apiKey, SignInWithCredentialTests.apiKey)
- XCTAssertEqual(request.email, SignInWithCredentialTests.email)
- XCTAssertEqual(request.password, SignInWithCredentialTests.password)
- XCTAssertTrue(request.returnSecureToken)
- switch verifyPasswordCallback {
- case let .success(response):
- callback(response, nil)
- case let .failure(error):
- callback(nil, error)
- }
- }
- override func getAccountInfo(_ request: FIRGetAccountInfoRequest,
- callback: @escaping FIRGetAccountInfoResponseCallback) {
- XCTAssertEqual(request.apiKey, SignInWithCredentialTests.apiKey)
- XCTAssertEqual(request.accessToken, SignInWithCredentialTests.accessToken)
- callback(MockGetAccountInfoResponse(), nil)
- }
- }
- func testSignInWithEmailCredentialSuccess() {
- // given
- FIRAuthBackend.setBackendImplementation(MockAuthBackend())
- var cancellables = Set<AnyCancellable>()
- let userSignInExpectation = expectation(description: "User signed in")
- let emailCredential = EmailAuthProvider.credential(
- withEmail: Self.email,
- password: Self.password
- )
- // when
- Auth.auth()
- .signIn(with: emailCredential)
- .sink { completion in
- switch completion {
- case .finished:
- print("Finished")
- case let .failure(error):
- XCTFail("💥 Something went wrong: \(error)")
- }
- } receiveValue: { authDataResult in
- let user = authDataResult.user
- XCTAssertNotNil(user)
- XCTAssertEqual(user.uid, Self.localID)
- XCTAssertEqual(user.displayName, Self.displayName)
- XCTAssertEqual(user.email, Self.email)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertEqual(user.providerData.count, 0)
- userSignInExpectation.fulfill()
- }
- .store(in: &cancellables)
- // then
- wait(for: [userSignInExpectation], timeout: expectationTimeout)
- }
- func testSignInWithEmailCredentialFailure() {
- // given
- let authBackend = MockAuthBackend()
- authBackend
- .verifyPasswordCallback = .failure(FIRAuthErrorUtils.userDisabledError(withMessage: nil))
- FIRAuthBackend.setBackendImplementation(authBackend)
- var cancellables = Set<AnyCancellable>()
- let userSignInExpectation = expectation(description: "User disabled")
- let emailCredential = EmailAuthProvider.credential(
- withEmail: Self.email,
- password: Self.password
- )
- // when
- Auth.auth()
- .signIn(with: emailCredential)
- .sink { completion in
- if case let .failure(error as NSError) = completion {
- XCTAssertEqual(error.code, AuthErrorCode.userDisabled.rawValue)
- userSignInExpectation.fulfill()
- }
- } receiveValue: { authDataResult in
- XCTFail("💥 result unexpected")
- }
- .store(in: &cancellables)
- // then
- wait(for: [userSignInExpectation], timeout: expectationTimeout)
- }
- func testSignInWithEmailCredentialEmptyPassword() {
- // given
- FIRAuthBackend.setBackendImplementation(MockAuthBackend())
- var cancellables = Set<AnyCancellable>()
- let userSignInExpectation = expectation(description: "User wrong password")
- let emailCredential = EmailAuthProvider.credential(withEmail: Self.email, password: "")
- // when
- Auth.auth()
- .signIn(with: emailCredential)
- .sink { completion in
- if case let .failure(error as NSError) = completion {
- XCTAssertEqual(error.code, AuthErrorCode.wrongPassword.rawValue)
- userSignInExpectation.fulfill()
- }
- } receiveValue: { authDataResult in
- XCTFail("💥 result unexpected")
- }
- .store(in: &cancellables)
- // then
- wait(for: [userSignInExpectation], timeout: expectationTimeout)
- }
- func testSignInWithGoogleAccountExistsError() {
- // given
- let authBackend = MockAuthBackend()
- let mockVerifyAssertionResponse = MockVerifyAssertionResponse()
- mockVerifyAssertionResponse.needConfirmation = true
- authBackend.verifyAssertionCallBack = .success(mockVerifyAssertionResponse)
- FIRAuthBackend.setBackendImplementation(authBackend)
- var cancellables = Set<AnyCancellable>()
- let userSignInExpectation = expectation(description: "User Google exists")
- let googleCredential = GoogleAuthProvider.credential(
- withIDToken: Self.googleID,
- accessToken: Self.googleAccessToken
- )
- // when
- Auth.auth()
- .signIn(with: googleCredential)
- .sink { completion in
- if case let .failure(error as NSError) = completion {
- XCTAssertEqual(
- error.code,
- AuthErrorCode.accountExistsWithDifferentCredential.rawValue
- )
- userSignInExpectation.fulfill()
- }
- } receiveValue: { authDataResult in
- XCTFail("💥 result unexpected")
- }
- .store(in: &cancellables)
- // then
- wait(for: [userSignInExpectation], timeout: expectationTimeout)
- }
- func testSignInWithGoogleCredentialSuccess() {
- // given
- FIRAuthBackend.setBackendImplementation(MockAuthBackend())
- var cancellables = Set<AnyCancellable>()
- let userSignInExpectation = expectation(description: "User signed in")
- let googleCredential = GoogleAuthProvider.credential(
- withIDToken: Self.googleID,
- accessToken: Self.googleAccessToken
- )
- // when
- Auth.auth()
- .signIn(with: googleCredential)
- .sink { completion in
- switch completion {
- case .finished:
- print("Finished")
- case let .failure(error):
- XCTFail("💥 Something went wrong: \(error)")
- }
- } receiveValue: { authDataResult in
- let user = authDataResult.user
- XCTAssertNotNil(user)
- XCTAssertEqual(user.uid, Self.localID)
- XCTAssertEqual(user.displayName, Self.displayName)
- XCTAssertEqual(user.email, Self.email)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertEqual(user.providerData.count, 0)
- userSignInExpectation.fulfill()
- }
- .store(in: &cancellables)
- // then
- wait(for: [userSignInExpectation], timeout: expectationTimeout)
- }
- func testSignInWithGoogleCredentialFailure() {
- // given
- let authBackend = MockAuthBackend()
- authBackend
- .verifyAssertionCallBack = .failure(FIRAuthErrorUtils
- .emailAlreadyInUseError(withEmail: nil))
- FIRAuthBackend.setBackendImplementation(authBackend)
- var cancellables = Set<AnyCancellable>()
- let userSignInExpectation = expectation(description: "User signed in")
- let googleCredential = GoogleAuthProvider.credential(
- withIDToken: Self.googleID,
- accessToken: Self.googleAccessToken
- )
- // when
- Auth.auth()
- .signIn(with: googleCredential)
- .sink { completion in
- if case let .failure(error as NSError) = completion {
- XCTAssertEqual(error.code, AuthErrorCode.emailAlreadyInUse.rawValue)
- userSignInExpectation.fulfill()
- }
- } receiveValue: { authDataResult in
- XCTFail("💥 result unexpected")
- }
- .store(in: &cancellables)
- // then
- wait(for: [userSignInExpectation], timeout: expectationTimeout)
- }
- func testSignInWithCredentialSuccess() {
- // given
- FIRAuthBackend.setBackendImplementation(MockAuthBackend())
- var cancellables = Set<AnyCancellable>()
- let userSignInExpectation = expectation(description: "User signed in")
- let googleCredential = GoogleAuthProvider.credential(
- withIDToken: Self.googleID,
- accessToken: Self.googleAccessToken
- )
- // when
- Auth.auth()
- .signIn(with: googleCredential)
- .sink { completion in
- switch completion {
- case .finished:
- print("Finished")
- case let .failure(error):
- XCTFail("💥 Something went wrong: \(error)")
- }
- } receiveValue: { authDataResult in
- let user = authDataResult.user
- XCTAssertNotNil(user)
- XCTAssertEqual(user.uid, Self.localID)
- XCTAssertEqual(user.displayName, Self.displayName)
- XCTAssertEqual(user.email, Self.email)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertEqual(user.providerData.count, 0)
- XCTAssertEqual(authDataResult.additionalUserInfo?.username, Self.displayName)
- XCTAssertEqual(
- authDataResult.additionalUserInfo?.profile,
- Self.googleProfile as [String: NSString]
- )
- userSignInExpectation.fulfill()
- }
- .store(in: &cancellables)
- // then
- wait(for: [userSignInExpectation], timeout: expectationTimeout)
- }
- func testPhoneAuthSuccess() {
- // given
- FIRAuthBackend.setBackendImplementation(MockAuthBackend())
- var cancellables = Set<AnyCancellable>()
- let userSignInExpectation = expectation(description: "User signed in")
- let credential = PhoneAuthProvider.provider()
- .credential(withVerificationID: Self.verificationID,
- verificationCode: Self.verificationCode)
- // when
- Auth.auth()
- .signIn(with: credential)
- .sink { completion in
- switch completion {
- case .finished:
- print("Finished")
- case let .failure(error):
- XCTFail("💥 Something went wrong: \(error)")
- }
- } receiveValue: { authDataResult in
- let user = authDataResult.user
- XCTAssertNotNil(user)
- XCTAssertEqual(user.uid, Self.localID)
- XCTAssertEqual(user.displayName, Self.displayName)
- XCTAssertEqual(user.email, Self.email)
- XCTAssertFalse(user.isAnonymous)
- XCTAssertEqual(user.providerData.count, 0)
- userSignInExpectation.fulfill()
- }
- .store(in: &cancellables)
- // then
- wait(for: [userSignInExpectation], timeout: expectationTimeout)
- }
- func testPhoneAuthMissingVerificationCode() {
- // given
- FIRAuthBackend.setBackendImplementation(MockAuthBackend())
- var cancellables = Set<AnyCancellable>()
- let userSignInExpectation = expectation(description: "User missing verification code")
- let credential = PhoneAuthProvider.provider()
- .credential(withVerificationID: Self.verificationID, verificationCode: "")
- // when
- Auth.auth()
- .signIn(with: credential)
- .sink { completion in
- if case let .failure(error as NSError) = completion {
- XCTAssertEqual(error.code, AuthErrorCode.missingVerificationCode.rawValue)
- userSignInExpectation.fulfill()
- }
- } receiveValue: { authDataResult in
- XCTFail("💥 result unexpected")
- }
- .store(in: &cancellables)
- // then
- wait(for: [userSignInExpectation], timeout: expectationTimeout)
- }
- func testPhoneAuthMissingVerificationID() {
- // given
- FIRAuthBackend.setBackendImplementation(MockAuthBackend())
- var cancellables = Set<AnyCancellable>()
- let userSignInExpectation = expectation(description: "User missing verification ID")
- let credential = PhoneAuthProvider.provider()
- .credential(withVerificationID: "", verificationCode: Self.verificationCode)
- // when
- Auth.auth()
- .signIn(with: credential)
- .sink { completion in
- if case let .failure(error as NSError) = completion {
- XCTAssertEqual(error.code, AuthErrorCode.missingVerificationID.rawValue)
- userSignInExpectation.fulfill()
- }
- } receiveValue: { authDataResult in
- XCTFail("💥 result unexpected")
- }
- .store(in: &cancellables)
- // then
- wait(for: [userSignInExpectation], timeout: expectationTimeout)
- }
- func testSignInWithEmailLinkCredentialSuccess() {
- // given
- FIRAuthBackend.setBackendImplementation(MockAuthBackend())
- var cancellables = Set<AnyCancellable>()
- let userSignInExpectation = expectation(description: "User signed in")
- let emailCrendential = EmailAuthProvider.credential(
- withEmail: Self.email,
- link: Self.fakeEmailSignInlink
- )
- // when
- Auth.auth()
- .signIn(with: emailCrendential)
- .sink { completion in
- switch completion {
- case .finished:
- print("Finished")
- case let .failure(error):
- XCTFail("💥 Something went wrong: \(error)")
- }
- } receiveValue: { authDataResult in
- let user = authDataResult.user
- XCTAssertNotNil(user)
- XCTAssertEqual(user.refreshToken, Self.refreshToken)
- XCTAssertEqual(user.displayName, Self.displayName)
- XCTAssertEqual(user.email, Self.email)
- XCTAssertFalse(user.isAnonymous)
- userSignInExpectation.fulfill()
- }
- .store(in: &cancellables)
- // then
- wait(for: [userSignInExpectation], timeout: expectationTimeout)
- }
- func testSignInWithEmailLinkCredentialFailure() {
- // given
- let authBackend = MockAuthBackend()
- authBackend
- .emailLinkSignInCallback = .failure(FIRAuthErrorUtils.userDisabledError(withMessage: nil))
- FIRAuthBackend.setBackendImplementation(authBackend)
- var cancellables = Set<AnyCancellable>()
- let userSignInExpectation = expectation(description: "User disabled")
- let emailCrendential = EmailAuthProvider.credential(
- withEmail: Self.email,
- link: Self.fakeEmailSignInlink
- )
- // when
- Auth.auth()
- .signIn(with: emailCrendential)
- .sink { completion in
- if case let .failure(error as NSError) = completion {
- XCTAssertNotNil(error.userInfo[NSLocalizedDescriptionKey])
- XCTAssertEqual(error.code, AuthErrorCode.userDisabled.rawValue)
- userSignInExpectation.fulfill()
- }
- } receiveValue: { authDataResult in
- XCTFail("💥 result unexpected")
- }
- .store(in: &cancellables)
- // then
- wait(for: [userSignInExpectation], timeout: expectationTimeout)
- }
- }
|