DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `account`.`user_checkPassword`(vPassword VARCHAR(255))
BEGIN
/**
 * Comprueba si la contraseña cumple los requisitos de seguridad
 * establecidos. Lanza una excepción si no se cumplen.
 *
 * @param vPassword Contraseña a comprobar
 */
	DECLARE vChr CHAR(1);
	DECLARE vPasswordOk TINYINT;
	DECLARE vI TINYINT DEFAULT 1;
	DECLARE vNAlpha TINYINT DEFAULT 0;
	DECLARE vNUpper TINYINT DEFAULT 0;
	DECLARE vNDigits TINYINT DEFAULT 0;
	DECLARE vNPunct TINYINT DEFAULT 0;

	WHILE vI <= CHAR_LENGTH(vPassword)
	DO
		SET vChr = SUBSTRING(vPassword, vI, 1);

		IF vChr REGEXP '[[:alpha:]]'
		THEN
			SET vNAlpha = vNAlpha+1;
			
			IF vChr REGEXP '[A-Z]'
			THEN
				SET vNUpper = vNUpper+1;
			END IF;
		ELSEIF vChr REGEXP '[[:digit:]]'
		THEN
			SET vNDigits = vNDigits+1;
		ELSEIF vChr REGEXP '[[:punct:]]'
		THEN
			SET vNPunct = vNPunct+1;
		END IF;

		SET vI = vI+1;
	END WHILE;

	SELECT
		CHAR_LENGTH(vPassword) >= length
		AND vNAlpha >= nAlpha
		AND vNUpper >= nUpper
		AND vNDigits >= nDigits
		AND vNPunct >= nPunct
			INTO vPasswordOk
			FROM userPassword LIMIT 1;

	IF NOT vPasswordOk THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'Password does not meet requirements';
	END IF;
END$$
DELIMITER ;
