1%% This Source Code Form is subject to the terms of the Mozilla Public
2%% License, v. 2.0. If a copy of the MPL was not distributed with this
3%% file, You can obtain one at https://mozilla.org/MPL/2.0/.
4%%
5%% Copyright (c) 2007-2021 VMware, Inc. or its affiliates.  All rights reserved.
6%%
7
8
9%% A `rabbit_credential_validator` implementation that matches
10%% password against a pre-configured regular expression.
11-module(rabbit_credential_validator_password_regexp).
12
13-include_lib("rabbit_common/include/rabbit.hrl").
14
15-behaviour(rabbit_credential_validator).
16
17%%
18%% API
19%%
20
21-export([validate/2]).
22%% for tests
23-export([validate/3]).
24
25-spec validate(rabbit_types:username(), rabbit_types:password()) -> 'ok' | {'error', string()}.
26
27validate(Username, Password) ->
28    {ok, Proplist} = application:get_env(rabbit, credential_validator),
29    Regexp         = case proplists:get_value(regexp, Proplist) of
30                         undefined -> {error, "rabbit.credential_validator.regexp config key is undefined"};
31                         Value     -> rabbit_data_coercion:to_list(Value)
32                     end,
33    validate(Username, Password, Regexp).
34
35
36-spec validate(rabbit_types:username(), rabbit_types:password(), string()) -> 'ok' | {'error', string(), [any()]}.
37
38validate(_Username, Password, Pattern) ->
39    case re:run(rabbit_data_coercion:to_list(Password), Pattern) of
40        {match, _} -> ok;
41        nomatch    -> {error, "provided password does not match the validator regular expression"}
42    end.
43