Add endpoint /api/login

This commit is contained in:
Alex Ling 2021-10-08 10:07:40 +00:00
parent 8a732804ae
commit 80344c3bf0
2 changed files with 27 additions and 3 deletions

View File

@ -54,8 +54,9 @@ class AuthHandler < Kemal::Handler
end end
def call(env) def call(env)
# Skip all authentication if requesting /login, /logout, or a static file # Skip all authentication if requesting /login, /logout, /api/login,
if request_path_startswith(env, ["/login", "/logout"]) || # or a static file
if request_path_startswith(env, ["/login", "/logout", "/api/login"]) ||
requesting_static_file env requesting_static_file env
return call_next(env) return call_next(env)
end end

View File

@ -23,7 +23,7 @@ struct APIRouter
# Authentication # Authentication
All endpoints require authentication. After logging in, your session ID would be stored as a cookie named `mango-sessid-#{Config.current.port}`, which can be used to authenticate the API access. Note that all admin API endpoints (`/api/admin/...`) require the logged-in user to have admin access. All endpoints except `/api/login` require authentication. After logging in, your session ID would be stored as a cookie named `mango-sessid-#{Config.current.port}`, which can be used to authenticate the API access. Note that all admin API endpoints (`/api/admin/...`) require the logged-in user to have admin access.
# Terminologies # Terminologies
@ -56,6 +56,29 @@ struct APIRouter
"error" => String?, "error" => String?,
} }
Koa.describe "Authenticates a user", <<-MD
After successful login, the cookie `mango-sessid-#{Config.current.port}` will contain a valid session ID that can be used for subsequent requests
MD
Koa.body schema: {
"username" => String,
"password" => String,
}
Koa.tag "users"
post "/api/login" do |env|
begin
username = env.params.json["username"].as String
password = env.params.json["password"].as String
token = Storage.default.verify_user(username, password).not_nil!
env.session.string "token", token
"Authenticated"
rescue e
Logger.error e
env.response.status_code = 403
e.message
end
end
Koa.describe "Returns a page in a manga entry" Koa.describe "Returns a page in a manga entry"
Koa.path "tid", desc: "Title ID" Koa.path "tid", desc: "Title ID"
Koa.path "eid", desc: "Entry ID" Koa.path "eid", desc: "Entry ID"