Skip to content

Commit

Permalink
fix issue #6 - user should stay logged in between sessions - udacity/…
Browse files Browse the repository at this point in the history
  • Loading branch information
Brent Mifsud committed Jun 2, 2019
1 parent d446b1c commit 0d343be
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 14 deletions.
2 changes: 1 addition & 1 deletion TheMovieManager/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
if components?.scheme == "themoviemanager" && components?.path == "authenticate" {
let loginVC = window?.rootViewController as! LoginViewController

TMDBClient.getSessionId(completion: loginVC.handleSessionIDResponse(success:error:))
TMDBClient.requestSessionId(completion: loginVC.handleSessionIDResponse(success:error:))
}
return true
}
Expand Down
12 changes: 11 additions & 1 deletion TheMovieManager/Controller/LoginViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ class LoginViewController: UIViewController {
usernameTextField.text = ""
passwordTextField.text = ""
}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

let sessionId = TMDBClient.getSessionId()

if !sessionId.isEmpty {
performSegue(withIdentifier: "completeLogin", sender: nil)
}
}

@IBAction func loginTapped(_ sender: UIButton) {
setLoggingIn(true)
Expand Down Expand Up @@ -71,7 +81,7 @@ extension LoginViewController {

func handleLoginResponse(success: Bool, error: Error?) {
if success {
TMDBClient.getSessionId(completion: self.handleSessionIDResponse(success:error:))
TMDBClient.requestSessionId(completion: self.handleSessionIDResponse(success:error:))
} else {
setLoggingIn(false)
showLoginFailure(message: error?.localizedDescription ?? "")
Expand Down
34 changes: 22 additions & 12 deletions TheMovieManager/Model/TMDB Client/TMDBClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ class TMDBClient {

static let encoder = JSONEncoder()
static let decoder = JSONDecoder()
static let sessionIdKey = "sessionId"

private struct Auth {
static var accountId = 0
static var requestToken = ""
static var sessionId = ""
static var sessionId = getSessionId()
}

enum Endpoints {
Expand All @@ -28,7 +29,7 @@ class TMDBClient {
case getWatchlist
case getRequestToken
case login
case getSessionId
case retrieveSessionId
case webAuth
case deleteSession
case getFavorites
Expand All @@ -39,15 +40,15 @@ class TMDBClient {

var stringValue: String {
switch self {
case .getWatchlist: return Endpoints.base + "/account/\(Auth.accountId)/watchlist/movies" + Endpoints.apiKeyParam + "&session_id=\(Auth.sessionId)"
case .getRequestToken: return Endpoints.base + "/authentication/token/new" + Endpoints.apiKeyParam
case .login: return Endpoints.base + "/authentication/token/validate_with_login" + Endpoints.apiKeyParam
case .getSessionId: return Endpoints.base + "/authentication/session/new" + Endpoints.apiKeyParam
case .retrieveSessionId: return Endpoints.base + "/authentication/session/new" + Endpoints.apiKeyParam
case .webAuth: return "https://www.themoviedb.org/authenticate/\(Auth.requestToken)?redirect_to=themoviemanager:authenticate"
case .deleteSession: return Endpoints.base + "/authentication/session" + Endpoints.apiKeyParam
case .getFavorites: return Endpoints.base + "/account/\(Auth.accountId)/favorite/movies" + Endpoints.apiKeyParam + "&session_id=\(Auth.sessionId)"
case .markWatchlist: return Endpoints.base + "/account/\(Auth.accountId)/watchlist" + Endpoints.apiKeyParam + "&session_id=\(Auth.sessionId)" + "&sort_by=created_at.desc"
case .markFavorite: return Endpoints.base + "/account/\(Auth.accountId)/favorite" + Endpoints.apiKeyParam + "&session_id=\(Auth.sessionId)" + "&sort_by=created_at.asc"
case .getWatchlist: return Endpoints.base + "/account/\(Auth.accountId)/watchlist/movies" + Endpoints.apiKeyParam + "&session_id=\(getSessionId())"
case .getFavorites: return Endpoints.base + "/account/\(Auth.accountId)/favorite/movies" + Endpoints.apiKeyParam + "&session_id=\(getSessionId())"
case .markWatchlist: return Endpoints.base + "/account/\(Auth.accountId)/watchlist" + Endpoints.apiKeyParam + "&session_id=\(getSessionId())" + "&sort_by=created_at.desc"
case .markFavorite: return Endpoints.base + "/account/\(Auth.accountId)/favorite" + Endpoints.apiKeyParam + "&session_id=\(getSessionId())" + "&sort_by=created_at.asc"
case .getPosterImage(let posterPath): return Endpoints.basePoster + posterPath
case .search(let movieQuery, let page): return Endpoints.base + "/search/\(MediaType.movie)" + Endpoints.apiKeyParam + "&query=\(movieQuery.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")" + "&page=\(page)"
}
Expand Down Expand Up @@ -123,11 +124,11 @@ class TMDBClient {
}
}

class func getSessionId(completion: @escaping (Bool, Error?) -> Void){
class func requestSessionId(completion: @escaping (Bool, Error?) -> Void){
let body = PostSession(requestToken: Auth.requestToken)
taskForPostRequest(url: Endpoints.getSessionId.url, body: body, responseType: SessionResponse.self) { (response, error) in
taskForPostRequest(url: Endpoints.retrieveSessionId.url, body: body, responseType: SessionResponse.self) { (response, error) in
if let response = response {
Auth.sessionId = response.sessionId
setSessionId(sessionId: response.sessionId)
completion(true, nil)
} else {
completion(false, error)
Expand All @@ -147,15 +148,15 @@ class TMDBClient {
}

class func logout(completion: @escaping (Bool, Error?) -> Void){
let body = LogoutRequest(sessionId: Auth.sessionId)
let body = LogoutRequest(sessionId: getSessionId())
var request = URLRequest(url: Endpoints.deleteSession.url)
request.httpMethod = "DELETE"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! encoder.encode(body)

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
setSessionId(sessionId: "")
Auth.requestToken = ""
Auth.sessionId = ""
completion(true, nil)
}
task.resume()
Expand All @@ -175,6 +176,15 @@ class TMDBClient {
}
task.resume()
}

class func setSessionId(sessionId: String) {
UserDefaults.standard.set(sessionId, forKey: TMDBClient.sessionIdKey)
UserDefaults.standard.synchronize()
}

class func getSessionId() -> String {
return UserDefaults.standard.string(forKey: TMDBClient.sessionIdKey) ?? ""
}

}

Expand Down

0 comments on commit 0d343be

Please sign in to comment.