当前位置:网站首页>Implementation of the function of recording login status
Implementation of the function of recording login status
2022-06-11 15:09:00 【III VII】
1.Redis Related introduction ;
C++ Connect redis Tools :
hiredis install
cd /home/shiyanlou
wget https://github.com/redis/hiredis/archive/v0.14.0.tar.gz
tar -xzf v0.14.0.tar.gz
cd hiredis-0.14.0/
make
sudo make install
## Copy path
sudo cp /usr/local/lib/libhiredis.so.0.14 /usr/lib/
The test program :
#include <iostream>
#include <hiredis/hiredis.h>
using namespace std;
int main(){
redisContext *c = redisConnect("127.0.0.1",6379);
if(c->err){
redisFree(c);
cout<<" The connection fails "<<endl;
return 1;
}
cout<<" Successful connection "<<endl;
redisReply *r = (redisReply*)redisCommand(c,"PING");
cout<<r->str<<endl;
return 0;
}
open redis:
cd /usr/bin
./redis-server
Open a new terminal :
g++ -o test_redis test_redis.cpp -lhiredis
./test_redis## Run the program
2 Server side
2.1 Function Overview :
utilize Redis Record user login status (HASH type , The key is sessionid, The value is session object , Key expires in five minutes ), When the user logs in successfully, the server will generate a random algorithm sessionid Send to client to save , When the customer logs in, the priority will be given to sending sessionid Go to the server to check , If the check is passed, you do not need to enter the account and password to log in .
2.2 Header file addition :
global.h
#ifndef _GLOBAL_H
#define _GLOBAL_H
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <iostream>
#include <thread>
#include <vector>
#include <mysql/mysql.h>
#include <unordered_map>
#include <pthread.h>
#include <set>
#include <hiredis/hiredis.h> // Add
using namespace std;
#endif
2.3HandleRequest Code changes :
- redis The connection of :
// Connect redis database
redisContext *redis_target = redisConnect("127.0.0.1",6379);
if(redis_target->err){
redisFree(redis_target);
cout<<" Connect redis Failure "<<endl;
}
- See if it exists session
// Receive first cookie have a look redis Do you want to save the login status of this user
if(str.find("cookie:")!=str.npos){
string cookie=str.substr(7);
// Query the cookie Whether there is :hget cookie name
string redis_str="hget "+cookie+" name";
redisReply *r = (redisReply*)redisCommand(redis_target,redis_str.c_str());
string send_res;
// There is
if(r->str){
cout<<" Inquire about redis result :"<<r->str<<endl;
send_res=r->str;
}
// non-existent
else
send_res="NULL";
send(conn,send_res.c_str(),send_res.length()+1,0);
}
- Generate sessionId And send the
Generate SessionId Algorithm :10 position sessionid, Each is randomly generated from upper case letters, lower case letters and numbers ;
// Sign in
else if(str.find("login")!=str.npos){
int p1=str.find("login"),p2=str.find("pass:");
name=str.substr(p1+5,p2-5);
pass=str.substr(p2+5,str.length()-p2-4);
string search="SELECT * FROM USER WHERE NAME=\"";
search+=name;
search+="\";";
cout<<"sql sentence :"<<search<<endl;
auto search_res=mysql_query(con,search.c_str());
auto result=mysql_store_result(con);
int col=mysql_num_fields(result);// Get the number of columns
int row=mysql_num_rows(result);// Get the number of lines
// Query user name
if(search_res==0&&row!=0){
cout<<" The query is successful \n";
auto info=mysql_fetch_row(result);// Get a line of information
cout<<" Query user name :"<<info[0]<<" password :"<<info[1]<<endl;
// The password is correct
if(info[1]==pass){
cout<<" The login password is correct \n\n";
string str1="ok";
if_login=true;
login_name=name;
pthread_mutex_lock(&name_sock_mutx); // locked
name_sock_map[login_name]=conn;// Record the correspondence between the name and the file descriptor
pthread_mutex_unlock(&name_sock_mutx); // Unlock
// Random generation sessionid And send it to the client
srand(time(NULL));// Initialize random number seed
for(int i=0;i<10;i++){
int type=rand()%3;//type by 0 On behalf of the digital , by 1 For lowercase letters , by 2 Represents capital letters
if(type==0)
str1+='0'+rand()%9;
else if(type==1)
str1+='a'+rand()%26;
else if(type==2)
str1+='A'+rand()%26;
}
// take sessionid Deposit in redis
string redis_str="hset "+str1.substr(2)+" name "+login_name;
redisReply *r = (redisReply*)redisCommand(redis_target,redis_str.c_str());
// Set the lifetime , Default 300 second
redis_str="expire "+str1.substr(2)+" 300";
r=(redisReply*)redisCommand(redis_target,redis_str.c_str());
cout<<" Randomly generated sessionid by :"<<str1.substr(2)<<endl;
send(conn,str1.c_str(),str1.length()+1,0);
}
// Wrong password
else{
cout<<" Login password error \n\n";
char str1[100]="wrong";
send(conn,str1,strlen(str1),0);
}
}
// User name not found
else{
cout<<" The query fails \n\n";
char str1[100]="wrong";
send(conn,str1,strlen(str1),0);
}
}
3. client
3.1 Function Overview
General steps : Create locally cookie.txt File store sessionId;
First login , Accept sessionid Store in cookie.txt among ;
Send it to the server , and redis Compare the data in ;
The server sends the result to the client ;
If the comparison is successful , Then login directly successfully ;
3.2 contrast sessionId;
ifstream f("cookie.txt");
string cookie_str;
if(f.good()){
f>>cookie_str;
f.close();
cookie_str="cookie:"+cookie_str;
// take cookie Send to server
send(sock,cookie_str.c_str(),cookie_str.length()+1,0);
// Receive server reply
char cookie_ans[100];
memset(cookie_ans,0,sizeof(cookie_ans));
recv(sock,cookie_ans,sizeof(cookie_ans),0);
// Determine whether the server reply passed
string ans_str(cookie_ans);
if(ans_str!="NULL"){
//redis Query to cookie, adopt
if_login=true;
login_name=ans_str;
}
3.3 Login NEW cookie.txt
// Start processing registration 、 Login Events
while(1){
if(if_login)
break;
cin>>choice;
if(choice==0)
break;
// register
else if(choice==2){
cout<<" Registered user name :";
cin>>name;
while(1){
cout<<" password :";
cin>>pass;
cout<<" Confirm the password :";
cin>>pass1;
if(pass==pass1)
break;
else
cout<<" The two passwords don't match !\n\n";
}
name="name:"+name;
pass="pass:"+pass;
string str=name+pass;
send(conn,str.c_str(),str.length(),0);
cout<<" Registered successfully !\n";
cout<<"\n Continue to enter the options you want :";
}
// Sign in
else if(choice==1&&!if_login){
while(1){
cout<<" user name :";
cin>>name;
cout<<" password :";
cin>>pass;
string str="login"+name;
str+="pass:";
str+=pass;
send(sock,str.c_str(),str.length(),0);// Send login information
char buffer[1000];
memset(buffer,0,sizeof(buffer));
recv(sock,buffer,sizeof(buffer),0);// Receiving response
string recv_str(buffer);
if(recv_str.substr(0,2)=="ok"){
if_login=true;
login_name=name;
string tmpstr=recv_str.substr(2);
tmpstr="cat > cookie.txt <<end \n"+tmpstr+"\nend";
system(tmpstr.c_str());
cout<<" Landing successful \n\n";
break;
}
else
cout<<" Wrong password or user name !\n\n";
}
}
}
// Landing successful
while(if_login&&1)```
## 4 Function display ;
Server side

client :

边栏推荐
- Cartoon: interesting "cake cutting" problem
- High number_ Chapter 6 infinite series__ Marklaurin series
- 2021 go developer survey
- 19. insertion, deletion and pruning of binary search tree
- Uniapp settings page Jump effect - navigateto switching effect - Global animationtype animation
- Raspberry school literacy
- Implementation of gray-scale publishing scheme for microservice architecture based on gateway and Nacos
- Mysql database optimization details
- 当开源遇见 KPI,全球化 VS 本土化,开源的理想与现实该如何和解?
- Managing technology debt in a microservice architecture
猜你喜欢

Summary of some classic embedded C interview questions

C language simple webserver

Database optimization

111. minimum depth of binary tree

Oauth2的理解

深度剖析「圈組」關系系統設計 | 「圈組」技術系列文章
[mysql_12] MySQL data types
![[verification of SystemVerilog] ~ test platform, hardware design description, excitation generator, monitor and comparator](/img/3a/0cc26400eeb4b388face09b9a10f27.png)
[verification of SystemVerilog] ~ test platform, hardware design description, excitation generator, monitor and comparator

Implementation of gray-scale publishing scheme for microservice architecture based on gateway and Nacos

Arthas实践操作文档记录
随机推荐
Hashicopy之nomad应用编排方案03(运行一个job)
Implementation of gray-scale publishing scheme for microservice architecture based on gateway and Nacos
【SystemVerilog 之 验证】~ 测试平台、硬件设计描述、激励发生器、监测器、比较器
数据库优化
清北力压耶鲁,MIT蝉联第一,2023QS世界大学排名最新发布
C语言简易版webserver
数据分析系统的设计与实现
Cisco Rui submitted the registration of sci tech Innovation Board: proposed to raise 600million yuan, with annual revenue of 222million yuan
浙江大学搞出了一款无人机,自动规避障碍,像鸟一样穿过树林,真正的蜂群来了...
Flutter 3.0正式发布:稳定支持6大平台,字节跳动是主要用户
Tencent interviewers share their interview experience, how to evaluate the interviewers' technical and personal comprehensive quality, and give you some suggestions on the interview
中国技术出海,TiDB 数据库海外探索之路 | 卓越技术团队访谈录
With a loss of 13.6 billion yuan in three years, can listing revive Weima?
Architectural concept exploration: Taking the development of card games as an example
uniapp开发微信小程序,从构建到上线
浅谈居家办公后的感想| 社区征文
Hamad application layout scheme 02 of hashicopy
2021 年度 Go 开发者调查
大道至簡 | 設計 ViT 到底怎麼配置Self-Attention才是最合理的?
Knowledge of affairs
