Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- import SwiftKeychainWrapper
- import SwiftyJSON
- class Session {
- var curUser: User?
- init() {
- if let accessToken = KeychainWrapper.standard.string(forKey: ACCESS_TOKEN) {
- EndpointManager.authenticatUser(accessToken: accessToken)
- }
- }
- func login(email: String, password: String, responseDelegate: ResponseDelegate) {
- let parameters: Dictionary<String, Any> = [
- "user[email]": email,
- "user[password]": password
- ]
- EndpointManager.sendRequest(with: parameters, request: .login) {
- [weak self] data in
- if let errors = data.dictionary?["errors"] {
- responseDelegate.onFail(error: Error(data: errors))
- } else if let user = data.dictionary?["user"] {
- self?.curUser = User(data: user)
- self?.persistUser(accessToken: data["user"]["access_token"].stringValue)
- responseDelegate.onSuccess()
- } else {
- responseDelegate.onFail(error: Error(data:
- ["Unkown data received from api server"]))
- }
- }
- }
- func signup(name: String, email: String, password: String, responseDelegate: ResponseDelegate) {
- let parameters: Dictionary<String, Any> = [
- "user[name]": name,
- "user[email]": email,
- "user[password]": password
- ]
- EndpointManager.sendRequest(with: parameters, request: .signup) {
- [weak self] data in
- if let errors = data.dictionary?["errors"] {
- responseDelegate.onFail(error: Error(data: errors))
- } else if let user = data.dictionary?["user"] {
- self?.curUser = User(data: user)
- self?.persistUser(accessToken: data["user"]["access_token"].stringValue)
- responseDelegate.onSuccess()
- } else {
- responseDelegate.onFail(error: Error(data:
- ["Unkown data received from api server"]))
- }
- }
- }
- func logOut() {
- removeUser()
- }
- func isLoggedIn() -> Bool {
- return KeychainWrapper.standard.hasValue(forKey: ACCESS_TOKEN)
- }
- func getUserData(getCached: Bool, responseDelegate: ResponseDelegate) {
- if !getCached || curUser == nil {
- EndpointManager.sendRequest(with: nil, request: .get_user) {
- [weak self] data in
- if let errors = data.dictionary?["errors"] {
- responseDelegate.onFail(error: Error(data: errors))
- } else if let user = data.dictionary?["user"] {
- self?.curUser = User(data: user)
- responseDelegate.onSuccess()
- } else {
- responseDelegate.onFail(error: Error(data: "Unkown data received from api server"))
- }
- }
- } else {
- responseDelegate.onSuccess()
- }
- }
- // Mark: - save user access_token to keychain
- private func persistUser(accessToken: String) {
- KeychainWrapper.standard.set(accessToken, forKey: ACCESS_TOKEN)
- EndpointManager.authenticatUser(accessToken: accessToken)
- }
- // Mark: - remove user access_token from keychain
- private func removeUser() {
- KeychainWrapper.standard.removeObject(forKey: ACCESS_TOKEN)
- EndpointManager.deauthenticatUser()
- curUser = nil
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement