RedditWebAuthHelper.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import Foundation
  2. enum RedditWebAuthHelper {
  3. static let redditHomeURL = URL(string: "https://www.reddit.com")!
  4. static func isOAuthProviderURL(_ url: URL) -> Bool {
  5. guard let host = url.host?.lowercased() else { return false }
  6. let oauthHosts = [
  7. "accounts.google.com",
  8. "appleid.apple.com",
  9. "idmsa.apple.com",
  10. ]
  11. if oauthHosts.contains(where: { host == $0 || host.hasSuffix(".\($0)") }) {
  12. return true
  13. }
  14. if host == "google.com" || host.hasSuffix(".google.com") {
  15. let path = url.path.lowercased()
  16. return path.contains("oauth")
  17. || path.contains("signin")
  18. || path.contains("gsi")
  19. }
  20. return false
  21. }
  22. static func isRedditURL(_ url: URL) -> Bool {
  23. guard let host = url.host?.lowercased() else { return false }
  24. let redditHosts = [
  25. "reddit.com",
  26. "www.reddit.com",
  27. "old.reddit.com",
  28. "new.reddit.com",
  29. "accounts.reddit.com",
  30. "oauth.reddit.com",
  31. "reddit.app.link",
  32. "redd.it",
  33. ]
  34. return redditHosts.contains(where: { host == $0 || host.hasSuffix(".\($0)") })
  35. }
  36. static func looksLikeLoggedInURL(_ url: URL) -> Bool {
  37. guard isRedditURL(url) else { return false }
  38. let path = url.path.lowercased()
  39. let blockedPaths = [
  40. "/login",
  41. "/register",
  42. "/password",
  43. "/account/login",
  44. ]
  45. if blockedPaths.contains(where: { path.hasPrefix($0) }) {
  46. return false
  47. }
  48. if url.host?.lowercased() == "accounts.reddit.com" {
  49. return path.isEmpty || path == "/" || path.hasPrefix("/api/")
  50. }
  51. return true
  52. }
  53. static func oauthCallbackHost(for url: URL) -> String {
  54. guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
  55. return "accounts.reddit.com"
  56. }
  57. let redirectURI = components.queryItems?.first(where: { $0.name == "redirect_uri" })?.value
  58. ?? components.queryItems?.first(where: { $0.name == "redirect_url" })?.value
  59. if let redirectURI,
  60. let redirectURL = URL(string: redirectURI),
  61. let host = redirectURL.host?.lowercased(),
  62. isRedditURL(redirectURL) {
  63. return host
  64. }
  65. return "accounts.reddit.com"
  66. }
  67. }