aboutsummaryrefslogtreecommitdiff
path: root/src/zenhttp/security/passwordsecurityfilter.cpp
blob: 87d8cc2754d72b27ff184c154276721dac81ff56 (plain) (blame)
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
// Copyright Epic Games, Inc. All Rights Reserved.

#include "zenhttp/security/passwordsecurityfilter.h"

#include <zencore/base64.h>
#include <zencore/compactbinaryutil.h>
#include <zencore/fmtutils.h>

namespace zen {

using namespace std::literals;

PasswordHttpFilter::Configuration
PasswordHttpFilter::ReadConfiguration(CbObjectView Config)
{
	Configuration Result;
	if (CbObjectView PasswordType = Config["basic"sv].AsObjectView(); PasswordType)
	{
		Result.AuthenticationTypeString	  = "Basic ";
		std::string_view Username		  = PasswordType["username"sv].AsString();
		std::string_view Password		  = PasswordType["password"sv].AsString();
		std::string		 UsernamePassword = fmt::format("{}:{}", Username, Password);
		Result.PasswordConfig.Password.resize(Base64::GetEncodedDataSize(uint32_t(UsernamePassword.length())));
		Base64::Encode(reinterpret_cast<const uint8_t*>(UsernamePassword.data()),
					   uint32_t(UsernamePassword.size()),
					   const_cast<char*>(Result.PasswordConfig.Password.data()));
	}
	Result.PasswordConfig.ProtectMachineLocalRequests = Config["protect-machine-local-requests"sv].AsBool();
	Result.PasswordConfig.UnprotectedUris			  = compactbinary_helpers::ReadArray<std::string>("unprotected-uris"sv, Config);
	return Result;
}

IHttpRequestFilter::Result
PasswordHttpFilter::FilterRequest(HttpServerRequest& Request)
{
	std::string_view Password;
	std::string_view AuthorizationHeader	   = Request.GetAuthorizationHeader();
	size_t			 AuthorizationHeaderLength = AuthorizationHeader.length();
	if (AuthorizationHeaderLength > m_AuthenticationTypeString.length())
	{
		if (StrCaseCompare(AuthorizationHeader.data(), m_AuthenticationTypeString.c_str(), m_AuthenticationTypeString.length()) == 0)
		{
			Password = AuthorizationHeader.substr(m_AuthenticationTypeString.length());
		}
	}

	bool IsAllowed =
		m_PasswordSecurity.IsAllowed(Password, Request.Service().BaseUri(), Request.RelativeUri(), Request.IsLocalMachineRequest());
	if (IsAllowed)
	{
		return Result::Accepted;
	}
	return Result::Forbidden;
}

}  // namespace zen