userver: userver/server/handlers/auth/auth_checker_factory.hpp Source File
Loading...
Searching...
No Matches
auth_checker_factory.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/server/handlers/auth/auth_checker_factory.hpp
4/// @brief Authorization factory registration and base classes.
5
6#include <stdexcept>
7#include <string>
8#include <string_view>
9#include <vector>
10
11#include <userver/components/component_context.hpp>
12#include <userver/server/handlers/auth/auth_checker_base.hpp>
13#include <userver/server/handlers/handler_config.hpp>
14#include <userver/utils/not_null.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace server::handlers::auth {
19
20/// Base class for all the authorization factory checkers.
22public:
23 virtual ~AuthCheckerFactoryBase() = default;
24
25 virtual AuthCheckerBasePtr MakeAuthChecker(const HandlerAuthConfig&) const = 0;
26};
27
28namespace impl {
29
30using AuthCheckerFactoryFactory = utils::UniqueRef<AuthCheckerFactoryBase> (*)(const components::ComponentContext&);
31
32void DoRegisterAuthCheckerFactory(std::string_view auth_type, AuthCheckerFactoryFactory factory);
33
34utils::UniqueRef<AuthCheckerFactoryBase> MakeAuthCheckerFactory(
35 std::string_view auth_type,
36 const components::ComponentContext& context
37);
38
39std::vector<std::string> GetAllAuthTypes();
40
41template <typename AuthCheckerFactory>
42utils::UniqueRef<AuthCheckerFactoryBase> MakeAuthCheckerFactory(const components::ComponentContext& context) {
43 return utils::MakeUniqueRef<AuthCheckerFactory>(context);
44}
45
46} // namespace impl
47
48/// @brief Function to call from main() to register an authorization checker.
49///
50/// @tparam AuthCheckerFactory must:
51/// 1) inherit from @ref server::handlers::auth::AuthCheckerFactoryBase;
52/// 2) have a constructor from `const components::ComponentContext&`.
53/// @param auth_type Handler auth type to associate with the factory.
54template <typename AuthCheckerFactory>
55void RegisterAuthCheckerFactory(std::string_view auth_type) {
56 if (auth_type.empty()) {
57 throw std::invalid_argument("Auth checker type must not be empty; pass the handler auth type to register");
58 }
59 impl::DoRegisterAuthCheckerFactory(auth_type, &impl::MakeAuthCheckerFactory<AuthCheckerFactory>);
60}
61
62/// @brief Registers an authorization checker using its `kAuthType` member.
63/// @tparam AuthCheckerFactory additionally must have a
64/// `static constexpr std::string_view kAuthType = "..."` member.
65template <typename AuthCheckerFactory>
67 RegisterAuthCheckerFactory<AuthCheckerFactory>(std::string_view{AuthCheckerFactory::kAuthType});
68}
69
70} // namespace server::handlers::auth
71
72USERVER_NAMESPACE_END