Advertisement
Guest User

Untitled

a guest
Feb 8th, 2017
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.67 KB | None | 0 0
  1. final class AuthenticationController: ResourceRepresentable {
  2.  
  3. func login(_ request: Request) throws -> ResponseRepresentable {
  4.  
  5. let type = try request.extract() as SessionType
  6.  
  7. guard let credentials = request.auth.header?.usernamePassword else {
  8. throw AuthError.noAuthorizationHeader
  9. }
  10.  
  11. switch type {
  12. case .customer:
  13. try request.userSubject().login(credentials: credentials, persist: true)
  14. case .vendor:
  15. try request.vendorSubject().login(credentials: credentials, persist: true)
  16. case .none:
  17. throw Abort.custom(status: .badRequest, message: "Can not log in with a session type of none.")
  18. }
  19.  
  20. let modelSubject: JSONConvertible = type == .customer ? try request.customer() : try request.vendor()
  21. return try Response(status: .ok, json: modelSubject.makeJSON())
  22. }
  23.  
  24. func makeResource() -> Resource<String> {
  25. return Resource(
  26. store: login
  27. )
  28. }
  29. }
  30.  
  31. extension Authorization {
  32. public var usernamePassword: UsernamePassword? {
  33. guard let range = header.range(of: "Basic ") else {
  34. return nil
  35. }
  36.  
  37. let authString = header.substring(from: range.upperBound)
  38.  
  39. let decodedAuthString = authString.base64DecodedString
  40. guard let separatorRange = decodedAuthString.range(of: ":") else {
  41. return nil
  42. }
  43.  
  44. let username = decodedAuthString.substring(to: separatorRange.lowerBound)
  45. let password = decodedAuthString.substring(from: separatorRange.upperBound)
  46.  
  47. return UsernamePassword(username: username, password: password)
  48. }
  49. }
  50.  
  51. extension Request {
  52.  
  53. var sessionType: SessionType {
  54. if (try? customer()) != nil {
  55. return .customer
  56. } else if (try? vendor()) != nil {
  57. return .vendor
  58. } else {
  59. return .none
  60. }
  61. }
  62.  
  63. func customer() throws -> Customer {
  64. let subject = try userSubject()
  65.  
  66. guard let details = subject.authDetails else {
  67. throw AuthError.notAuthenticated
  68. }
  69.  
  70. guard let customer = details.account as? Customer else {
  71. throw AuthError.invalidAccountType
  72. }
  73.  
  74. return customer
  75. }
  76.  
  77. func vendor() throws -> Vendor {
  78. let subject = try vendorSubject()
  79.  
  80. guard let details = subject.authDetails else {
  81. throw AuthError.notAuthenticated
  82. }
  83.  
  84. guard let vendor = details.account as? Vendor else {
  85. throw AuthError.invalidAccountType
  86. }
  87.  
  88. return vendor
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement