Skip to content

Commit f625b91

Browse files
committed
adding change password route
1 parent 5a4ac50 commit f625b91

2 files changed

Lines changed: 44 additions & 1 deletion

File tree

Sources/LocalAuthentication/Routing/Routes.swift

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ public func mainAuthenticationRoutes() -> [[String: Any]] {
3434
routes.append(["method":"post", "uri":"/api/v1/register", "handler":LocalAuthJSONHandlers.register])
3535
/// Login post route
3636
routes.append(["method":"post", "uri":"/api/v1/login", "handler":LocalAuthJSONHandlers.login])
37+
/// Change Password post route
38+
routes.append(["method":"post", "uri":"/api/v1/changepassword", "handler":LocalAuthJSONHandlers.changePassword])
3739

3840

3941

Sources/LocalAuthentication/Routing/jsonroutes/JSONHandler.me.swift

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ extension LocalAuthJSONHandlers {
1717
public static func me(data: [String:Any]) throws -> RequestHandler {
1818
return {
1919
request, response in
20-
print("request.session?.userid: \(request.session?.userid)")
2120
if let i = request.session?.userid, !i.isEmpty {
2221
let acc = Account()
2322
do {
@@ -41,5 +40,47 @@ extension LocalAuthJSONHandlers {
4140
}
4241
}
4342

43+
// POST request for current user change password
44+
public static func changePassword(data: [String:Any]) throws -> RequestHandler {
45+
return {
46+
request, response in
47+
if let i = request.session?.userid, !i.isEmpty {
48+
let acc = Account()
49+
do {
50+
try acc.get(i)
51+
52+
// start chpwd
53+
if let postBody = request.postBodyString, !postBody.isEmpty {
54+
do {
55+
let postBodyJSON = try postBody.jsonDecode() as? [String: String] ?? [String: String]()
56+
if let password = postBodyJSON["password"], !password.isEmpty {
57+
acc.makePassword(password)
58+
try acc.save()
59+
_ = try response.setBody(json: ["error": "none", "msg":"Your password has been changed."])
60+
response.completed()
61+
return
62+
} else {
63+
LocalAuthHandlers.error(request, response, error: "Please supply a vaid password", code: .badRequest)
64+
return
65+
}
66+
} catch {
67+
LocalAuthHandlers.error(request, response, error: "Invalid JSON", code: .badRequest)
68+
return
69+
}
70+
} else {
71+
LocalAuthHandlers.error(request, response, error: "Change Password Error: Insufficient Data", code: .badRequest)
72+
return
73+
}
74+
// end chpwd
75+
} catch {
76+
LocalAuthHandlers.error(request, response, error: "AccountError", code: .badRequest)
77+
return
78+
}
79+
} else {
80+
LocalAuthHandlers.error(request, response, error: "NotLoggedIn", code: .badRequest)
81+
return
82+
}
83+
}
84+
}
4485

4586
}

0 commit comments

Comments
 (0)