RedditWebAuthHelper.swift 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. "login.microsoftonline.com",
  11. "login.live.com",
  12. "account.live.com",
  13. "login.microsoft.com",
  14. "www.facebook.com",
  15. "m.facebook.com",
  16. "facebook.com",
  17. "auth0.com",
  18. ]
  19. if oauthHosts.contains(where: { host == $0 || host.hasSuffix(".\($0)") }) {
  20. return true
  21. }
  22. if host == "google.com" || host.hasSuffix(".google.com") {
  23. let path = url.path.lowercased()
  24. return path.contains("oauth")
  25. || path.contains("signin")
  26. || path.contains("gsi")
  27. }
  28. if host == "facebook.com" || host.hasSuffix(".facebook.com") {
  29. let path = url.path.lowercased()
  30. return path.contains("oauth") || path.contains("login") || path.contains("dialog")
  31. }
  32. if host.hasSuffix(".auth0.com") {
  33. return true
  34. }
  35. return false
  36. }
  37. static func isRedditURL(_ url: URL) -> Bool {
  38. guard let host = url.host?.lowercased() else { return false }
  39. let redditHosts = [
  40. "reddit.com",
  41. "www.reddit.com",
  42. "old.reddit.com",
  43. "new.reddit.com",
  44. "accounts.reddit.com",
  45. "oauth.reddit.com",
  46. "reddit.app.link",
  47. "redd.it",
  48. ]
  49. return redditHosts.contains(where: { host == $0 || host.hasSuffix(".\($0)") })
  50. }
  51. static func looksLikeLoggedInURL(_ url: URL) -> Bool {
  52. guard isRedditURL(url) else { return false }
  53. let path = url.path.lowercased()
  54. let blockedPaths = [
  55. "/login",
  56. "/register",
  57. "/password",
  58. "/account/login",
  59. ]
  60. if blockedPaths.contains(where: { path.hasPrefix($0) }) {
  61. return false
  62. }
  63. if url.host?.lowercased() == "accounts.reddit.com" {
  64. return path.isEmpty || path == "/" || path.hasPrefix("/api/")
  65. }
  66. return true
  67. }
  68. static func oauthCallbackHost(for url: URL) -> String {
  69. guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
  70. return "accounts.reddit.com"
  71. }
  72. let redirectURI = components.queryItems?.first(where: { $0.name == "redirect_uri" })?.value
  73. ?? components.queryItems?.first(where: { $0.name == "redirect_url" })?.value
  74. if let redirectURI,
  75. let redirectURL = URL(string: redirectURI),
  76. let host = redirectURL.host?.lowercased(),
  77. isRedditURL(redirectURL) {
  78. return host
  79. }
  80. return "accounts.reddit.com"
  81. }
  82. }