WordClockESP/lib/framework/SecurityManager.h

81 lines
2.0 KiB
C
Raw Normal View History

#ifndef SecurityManager_h
#define SecurityManager_h
2019-05-06 14:50:19 +00:00
#include <ArduinoJsonJWT.h>
2019-05-29 22:48:16 +00:00
#include <ESPAsyncWebServer.h>
#include <list>
2019-04-29 23:30:43 +00:00
#define DEFAULT_JWT_SECRET "esp8266-react"
2019-05-18 18:35:27 +00:00
#define AUTHORIZATION_HEADER "Authorization"
#define AUTHORIZATION_HEADER_PREFIX "Bearer "
#define AUTHORIZATION_HEADER_PREFIX_LEN 7
2019-04-29 23:30:43 +00:00
2019-05-02 23:31:20 +00:00
#define MAX_JWT_SIZE 128
2019-04-29 23:30:43 +00:00
class User {
public:
String username;
String password;
bool admin;
public:
User(String username, String password, bool admin) : username(username), password(password), admin(admin) {
}
2019-04-29 23:30:43 +00:00
};
class Authentication {
public:
User* user;
boolean authenticated;
public:
Authentication(User& user) : user(new User(user)), authenticated(true) {
}
Authentication() : user(nullptr), authenticated(false) {
}
~Authentication() {
delete (user);
}
};
typedef std::function<boolean(Authentication& authentication)> AuthenticationPredicate;
2019-04-29 23:30:43 +00:00
2019-05-29 22:48:16 +00:00
class AuthenticationPredicates {
public:
static bool NONE_REQUIRED(Authentication& authentication) {
return true;
};
static bool IS_AUTHENTICATED(Authentication& authentication) {
return authentication.authenticated;
};
static bool IS_ADMIN(Authentication& authentication) {
return authentication.authenticated && authentication.user->admin;
};
2019-05-29 22:48:16 +00:00
};
2019-04-29 23:30:43 +00:00
2019-05-29 22:48:16 +00:00
class SecurityManager {
public:
/*
* Authenticate, returning the user if found
*/
virtual Authentication authenticate(String username, String password) = 0;
/*
* Check the request header for the Authorization token
*/
virtual Authentication authenticateRequest(AsyncWebServerRequest* request) = 0;
/*
* Generate a JWT for the user provided
*/
virtual String generateJWT(User* user) = 0;
/**
* Wrap the provided request to provide validation against an AuthenticationPredicate.
*/
virtual ArRequestHandlerFunction wrapRequest(ArRequestHandlerFunction onRequest,
AuthenticationPredicate predicate) = 0;
2019-04-29 23:30:43 +00:00
};
#endif // end SecurityManager_h