gpt4 book ai didi

ios - 快速注销后 token 不会变空

转载 作者:行者123 更新时间:2023-11-28 14:39:38 24 4
gpt4 key购买 nike

我有一个使用 API 进行身份验证的快速应用程序,一切正常,当用户注销时,登录 token 应该被清除,以便可以收集新用户的详细信息并将新 token 传递到 header 中,但我注意到当我尝试登录另一个用户时,以前的用户 token 保留在标题中,从而阻止新用户登录。我在按下注销按钮时清除登录值,但我不知道为什么 token 值保留在标题中。我的代码如下所示

let defaults = UserDefaults.standard

var isLoggedIn : Bool {

get {
return defaults.bool(forKey: LOGGED_IN_KEY)
}
set {
defaults.set(newValue, forKey: LOGGED_IN_KEY)
}
}

var authToken: String {
get {
return defaults.value(forKey: TOKEN_KEY) as? String ?? ""
}
set {
defaults.set(newValue, forKey: TOKEN_KEY)
}
}

var userUsername: String {
get {
return defaults.value(forKey: USER_USERNAME) as? String ?? ""
}
set {
defaults.set(newValue, forKey: USER_USERNAME)
}
}
//MARK :- LOGGIN
func findUserByUserName(completion: @escaping CompletionHandler) -> Void {

Alamofire.request(URL_USER_BY_USERNAME, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: TOKEN_HEADER).validate().responseJSON { (response) in

print("URL USER BY HEADER \(self.authToken)")

if response.result.error == nil {

guard let data = response.data else {return}
let jsonString = String(data: data, encoding: .utf8)
print(jsonString as Any)
self.setUserInfo(data: data)

completion(true)
}
else {


completion(false)
debugPrint("ERROR 22222\(response.result.error as Any)")
}
}
}


func setUserInfo(data: Data) -> Void {
do {
let json = try JSON(data: data)
let pk = json["pk"].intValue
let username = json["username"].stringValue
let email = json["email"].stringValue
let firstName = json["first_name"].stringValue
let lastName = json["last_nameme"].stringValue

print("THE USERNAME IZZZZ \(username)")

UserDataService.instance.setUserData(pk: pk, username: username, email: email, firstName: firstName, lastName: lastName)

} catch {
print(error)
}

func loginUser(email: String, password: String, completion: @escaping CompletionHandler) -> Void {

let usernameEmail = email.lowercased()

let body: [String: Any] = [
"username": usernameEmail,
"email": "",
"password": password,
]

Alamofire.request(URL_LOGIN, method: .post, parameters: body, encoding: JSONEncoding.default, headers: HEADER).validate().responseJSON { (response) in

if response.result.error == nil {
print("LOGIN SUCCESFULL \(self.authToken)")

do {


guard let data = response.data else {return}
let jsonString = String(data: data, encoding: .utf8)
print("HELLOOO \(jsonString as Any)")
let json = try JSON(data: data)
self.authToken = json["key"].stringValue
self.userUsername = email



self.isLoggedIn = true

completion(true)
print("LOGIN SUCCESFULL TOKEN1111 \(self.authToken)")

} catch {
print("errorrrrr")
}

} else {
completion(false)
debugPrint("ERROR YENNNNN \(response.result.error as Any)")
}
}
}


//MARK :- LOGGIN
func findUserByEmail(completion: @escaping CompletionHandler) -> Void {

let body: [String: Any] = [
"username": AuthService.instance.userUsername,

]

Alamofire.request(URL_USER_BY_EMAIL, method: .put, parameters: body, encoding: JSONEncoding.default, headers: TOKEN_HEADER).validate().responseJSON { (response) in

print("URL USER BY HEADER \(self.authToken)")

if response.result.error == nil {

guard let data = response.data else {return}
print("USERUSERNAME \(self.authToken)")
let jsonString = String(data: data, encoding: .utf8)
print(jsonString as Any)
self.setUserInfo(data: data)

completion(true)
}
else {


completion(false)
debugPrint("ERROR 22222\(response.result.error as Any)")
}
}
}

token 常量

let TOKEN_HEADER = [
"Authorization": "Token \(AuthService.instance.authToken)",
"Content-Type": "application/json; charset=utf-8"
]

用户服务

func setUserData(pk: Int, username: String, email: String, firstName: String, lastName: String) -> Void {

self.pk = pk
self.username = username
self.email = email
self.firstName = firstName
self.lastName = lastName
}


func logoutUser() -> Void {
self.pk = 0
self.username = ""
self.email = ""
self.firstName = ""
self.lastName = ""
AuthService.instance.isLoggedIn = false
AuthService.instance.authToken = ""
AuthService.instance.userUsername = ""
}

注销

@IBAction func logoutPressed(_ sender: Any) {
UserDataService.instance.logoutUser()
print("LOGOUT TOKEN \(AuthService.instance.authToken)")
UserDataService.instance.setUserData(pk: 0, username: "", email: "", firstName: "", lastName: "")
AuthService.instance.authToken = ""
NotificationCenter.default.post(name: NOTIFY_USER_DATA_DID_CHANGE, object: nil)

dismiss(animated: true, completion: nil)
}

将根据要求提供更多代码

最佳答案

问题是您认为无论何时调用 TOKEN_HEADER 都会从中获取最新值

 let TOKEN_HEADER = [
"Authorization": "Token \(AuthService.instance.authToken)",
"Content-Type": "application/json; charset=utf-8"
]

但这不会发生,因为无论 token 值是什么,变量从第一次初始化中获取它的值,因此您必须通过像这样再次对字符串进行硬编码来重构将 header 发送到 Alamofire

func findUserByUserName(completion: @escaping CompletionHandler) -> Void {

let updated_HEADER = [
"Authorization": "Token \(AuthService.instance.authToken)",
"Content-Type": "application/json; charset=utf-8"
]

Alamofire.request(URL_USER_BY_USERNAME,
method: .get, parameters: nil, encoding: JSONEncoding.default,
headers:updated_HEADER).validate().responseJSON { (response) in }

}

关于ios - 快速注销后 token 不会变空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50632589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com