97 lines
2.7 KiB
Swift
97 lines
2.7 KiB
Swift
import Foundation
|
|
import CryptoSwift
|
|
|
|
|
|
final class AuthController {
|
|
|
|
static let serviceName = "FriendvatarsService"
|
|
|
|
static var isSignedIn: Bool {
|
|
guard let currentUser = Settings.currentUser else {
|
|
return false
|
|
}
|
|
|
|
do {
|
|
let password = try KeychainPasswordItem(service: serviceName, account: currentUser.email).readPassword()
|
|
return password.count > 0
|
|
} catch {
|
|
return false
|
|
}
|
|
}
|
|
|
|
static func random(length: Int = 20) -> String {
|
|
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
var randomString: String = ""
|
|
|
|
for _ in 0..<length {
|
|
let randomValue = arc4random_uniform(UInt32(base.count))
|
|
randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
|
|
}
|
|
return randomString
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class func passwordHash(from email: String, password: String) -> String {
|
|
|
|
func random(length: Int = 20) -> String {
|
|
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
var randomString: String = ""
|
|
|
|
for _ in 0..<length {
|
|
let randomValue = arc4random_uniform(UInt32(base.count))
|
|
randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
|
|
}
|
|
return randomString
|
|
}
|
|
let randomSalt = random()
|
|
print(randomSalt)
|
|
let salt = "x4vV8bGgqqmQwgCoyXFQj+(o.nUNQhVP7ND"
|
|
return "\(password).\(email).\(salt)".sha256()
|
|
}
|
|
|
|
class func logIn(_ user: User, password: String) throws {
|
|
do {
|
|
let finalHash = passwordHash(from: user.email, password: password)
|
|
let keychainPassword = try KeychainPasswordItem(service: serviceName, account: user.email).readPassword()
|
|
print(keychainPassword)
|
|
if(keychainPassword == finalHash) {
|
|
Settings.currentUser = user
|
|
NotificationCenter.default.post(name: .loginStatusChanged, object: nil)
|
|
}
|
|
} catch {
|
|
print("nie dziala")
|
|
}
|
|
|
|
}
|
|
|
|
class func signIn(_ user: User, password: String) throws {
|
|
let finalHash = passwordHash(from: user.email, password: password)
|
|
try KeychainPasswordItem(service: serviceName, account: user.email).savePassword(finalHash)
|
|
|
|
Settings.currentUser = user
|
|
NotificationCenter.default.post(name: .loginStatusChanged, object: nil)
|
|
}
|
|
|
|
class func signOut() throws {
|
|
guard let currentUser = Settings.currentUser else {
|
|
return
|
|
}
|
|
|
|
//try KeychainPasswordItem(service: serviceName, account: currentUser.email).deleteItem()
|
|
|
|
Settings.currentUser = nil
|
|
NotificationCenter.default.post(name: .loginStatusChanged, object: nil)
|
|
}
|
|
|
|
}
|
|
|
|
extension Notification.Name {
|
|
|
|
static let loginStatusChanged = Notification.Name("com.razeware.auth.changed")
|
|
|
|
}
|