• Система автоматизации с открытым исходным кодом на базе esp8266/esp32 микроконтроллеров и приложения IoT Manager. Наша группа в Telegram

Решено Web сервер - ! нужна авторизация

Alex1

New member
@kab Cegth
Temp: -0.8 C`
Temp: -2.0 C`
Temp: 112.6 C`

t += (str1.substring(0, str1.length() - 1)); это наверно самое правильное решение
Отличная работа . Вам ))
 

kab

New member
@Alex1
Наверно, на сегодня достаточно
на будущее:
Когда будет желание - посмотри два поста насчет авторизации повнимательней - начинай делать - и подключай меня
 

Alex1

New member
********* Огромное спасибо КАВ за помощь ********** который мне помог, тема закрыта, ключевой отрезок кода
Код:
  //Check if header is present and correct
   bool is_authentified(){
   Serial.println("Enter is_authentified");
   if (server.hasHeader("Cookie")){  
   Serial.print("Found cookie: ");
   String cookie = server.header("Cookie");
   Serial.println(cookie);
   if (cookie.indexOf("ESPSESSIONID=1") != -1) {
   Serial.println("Authentification Successful");
   return true;
    }
  }
   Serial.println("Authentification Failed");
   return false;   
   }

  //login page, also called for disconnect
  void handleLogin(){
  String msg;
  if (server.hasHeader("Cookie")){  
    Serial.print("Found cookie: ");
    String cookie = server.header("Cookie");
    Serial.println(cookie);
   }
  if (server.hasArg("DISCONNECT")){
    Serial.println("Disconnection");
    String header = "HTTP/1.1 301 OK\r\nSet-Cookie: ESPSESSIONID=0\r\nLocation: /login\r\nCache-Control: no-cache\r\n\r\n";
    server.sendContent(header);
    return;
   }
  if (server.hasArg("USERNAME") && server.hasArg("PASSWORD")){
    if (server.arg("USERNAME") == "admin" &&  server.arg("PASSWORD") == "admin" ){
     String header = "HTTP/1.1 301 OK\r\nSet-Cookie: ESPSESSIONID=1\r\nLocation: /\r\nCache-Control: no-cache\r\n\r\n";
     server.sendContent(header);
     Serial.println("Log in Successful");
     return;
    }
  msg = "<p style=\"text-align: left; font-style: italic; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:16px; color:red; \">Error username/password! Try again.</p>";
  Serial.println("Log in Failed");
  }


  String content = "<html><head><meta http-equiv= Content-Type content=text/html; charset=utf-8><style>{font-family:Verdana, Arial, Helvetica, sans-serif; font-size:16px;}body{background-color:rgba(0, 155, 255, 0.36);}</style><body><form action='/login' method='POST'>Enter: User login and password: <body><html><br><br>";
  content += "User:  <input type='text' name='USERNAME' placeholder='user name'><br><br>";
  content += "Pass:  <input type='password' name='PASSWORD' placeholder='user password'><br><br>";
  content += "<input type='submit' name='SUBMIT' value='Click to continue - OK'></form>" + msg + "<br>";
  content += "You also can go <a href='/inline'>here</a></body></html>";
  server.send(200, "text/html", content);
}

//root page can be accessed only if authentification is ok
  void handleRoot(){
  Serial.println("Enter handleRoot");
  String header;
  if (!is_authentified()){
    String header = "HTTP/1.1 301 OK\r\nLocation: /login\r\nCache-Control: no-cache\r\n\r\n";
    server.sendContent(header);
    return;
  }
response();
  sensors.requestTemperatures();
 
Видимо я самый бестолковый на этом сайте, но сделать авторизацию не могу. Три дня потратил в пустую. Скетч у меня конечно другой и сделан не мной. Обычный градусник. Подскажите как сделать вход по паролю.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS D2 // пин GPIO-4 к которому подключено реле
#define RELAY D1 // пин GPIO-5 к которому подключен датчик температуры DS18b20
bool relay = false; // разомкнуто для низкоуровнего реле при включении микроконтроллера.
float temp;
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

// Вместо звездочек свои параметры WiFi сети
const char* ssid = ",,,,,,,,";
const char* password = ",,,,,,,,";

ESP8266WebServer server(80); // Порт сервера

void setup() {
// Последовательный порт для отладки
Serial.begin(115200);

// Инициализация выхода реле
pinMode(RELAY, OUTPUT);
digitalWrite(RELAY, relay); // при включении микроконтроллера низкоуровневое реле разомкнуто

// Инициализация датчика температуры DS18b20
sensors.begin();

// Подлючение к WiFi
WiFi.mode(WIFI_STA);
// присваиваем статичесий IP адрес
WiFi.config(IPAddress(192,168,0,96),IPAddress(192,168,0,1),IPAddress(255,255,255,0),IPAddress(192,168,0,1));
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() == WL_CONNECTED) {
// Запуск WEB-сервера
server.on ( "/", HTTP);
server.onNotFound ( HTTP);
server.begin();
Serial.println ();
Serial.print( "HTTP server start! Open http://");
Serial.println(WiFi.localIP());
}
else {
Serial.printf("WiFi started is fail");
}
}

void loop() {
server.handleClient();
delay(50);
}

/*
Оработчик главной страницы сервера
*/
void HTTP(void) {
bool stat = false;
sensors.requestTemperatures(); // Опрос датчиков
temp = sensors.getTempCByIndex(0);
if ( server.hasArg("stat") ) {
if ( strncmp(server.arg("stat").c_str(), "1", 1) == 0 )stat = true;
}
else {
stat = relay;
}

String website = "";

website =
"<html>\
<head>\
<meta charset=\"utf-8\" />\
<title>WiFi control temр</title>\
<style>\
body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: blue; }\
</style>\
</head>\
<body>\
<h1 style=\"color: black;\">Температура</h1>\
<h1>Температура: \n";
website += (float)temp;
website += "°С";
website += "\</h3>\n";

if ( stat ) {
website += "\
<h3>Реле: Включено</br>\
<a style=\"color: red;\" href=\"/?stat=0\">Выключить</a></h1>\
";
}
else {
website += "\
<h3>Обогрев: Выключено</br>\
<a style=\"color: red;\" href=\"/?stat=1\">Включить</a><h1>\
";
}
website += "\
</body>\
</html>";
server.send ( 200, "text/html", website );
Serial.println (temp);
if ( stat != relay ) {
relay = stat;
digitalWrite(RELAY, relay);
if (relay)Serial.println("Power is ON");
else Serial.println("Power is OFF");
}

}
 

Slacky

Member
@Александр Юрьевич.
Добавляем вот сюда

Код:
void HTTP(void) {
  bool stat = false;
  if (условие_при_котором_нужна_авторизация) {
    if (!server.authenticate(ВашLogin, ВашPassword))
      return server.requestAuthentication();
  }
 
@Александр Юрьевич.
Добавляем вот сюда

Код:
void HTTP(void) {
  bool stat = false;
  if (условие_при_котором_нужна_авторизация) {
    if (!server.authenticate(ВашLogin, ВашPassword))
      return server.requestAuthentication();
  }
Спасибо Федор! А что такое "условие_при_котором_нужна_авторизация"? Авторизация нужна при входе на веб страницу, чтобы зайти мог только тот кто знает пароль и логин.
 
Вот так ругается Ардуина:

D:\Саша\Домашняя автоматика\Termometr_Proba\Termometr_Proba.ino: In function 'void HTTP()':

Termometr_Proba:72: error: 'admin' was not declared in this scope

exit status 1
'admin' was not declared in this scope
 
Вставил в строку №25 "server.authenticate("admin", "1111")".
Ардуина ругается:
Termometr_Proba:25: error: 'server' does not name a type

D:\Саша\Домашняя автоматика\Termometr_Proba\Termometr_Proba.ino: In function 'void HTTP()':

Termometr_Proba:72: error: 'admin' was not declared in this scope

exit status 1
'server' does not name a type
 

Slacky

Member
Последнее редактирование:
  • Like
Реакции: kab
Спасибо Федор!
Заработало. По сравнению с Вами чувствую себя ущербным.
Но больше всего меня удивляет откуда Вы берете терпение на общение с такими как я?
 
Сверху Снизу