-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAuthenticationService.swift
93 lines (73 loc) · 2.93 KB
/
AuthenticationService.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//
// AuthenticationService.swift
// MobileAcebook
//
// Created by Josué Estévez Fernández on 01/10/2023.
//
import Foundation
class AuthenticationService: AuthenticationServiceProtocol {
struct Response: Codable {
let message : String
}
func signUp(user: User, completion: @escaping (Bool) -> Void){
guard let url = URL(string: "http://localhost:3000/users") else {
completion(false)
return
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
do {
urlRequest.httpBody = try JSONEncoder().encode(user)
} catch {
print("Error encoding user: \(error)")
completion(false)
return
}
let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in
guard let httpResponse = response as? HTTPURLResponse, let data = data else {
completion(false)
return
}
if !(200...299).contains(httpResponse.statusCode) {
print("HTTP error: \(httpResponse.statusCode)")
completion(false)
return
}
do {
let jsonResponse = try JSONDecoder().decode(Response.self, from: data)
print("Response message: \(jsonResponse.message)")
if jsonResponse.message != "Something went wrong" {
completion(true) // Signup successful
} else {
completion(false) // Signup failed
}
} catch {
print("JSON decoding error: \(error)")
completion(false)
}
}
task.resume()
}
func login(userLogin: UserLogin) -> Bool {
guard let url = URL(string: "http://localhost:3000/tokens") else {return false}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body = userLogin
urlRequest.httpBody = try? JSONEncoder().encode(userLogin)
let task = URLSession.shared.dataTask(with : urlRequest) {data, response, error in
guard let data = data else {return}
do {
let response = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
print("Valid user")
print(response)
}
catch {
print(error)
}
}
task.resume()
return true
}
}