当前位置:网站首页>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 

 Insert picture description here
hiredis common API

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 :

  1. 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;
}
  1. 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);
}
  1. 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 
![ Insert picture description here ](https://img-blog.csdnimg.cn/0952f357597843d991329a9fdba01bfa.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LiJ4oWm,size_20,color_FFFFFF,t_70,g_se,x_16)
 client :
![ Insert picture description here ](https://img-blog.csdnimg.cn/fb2619ce366a4ed7ab9372b3e99a9fe8.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LiJ4oWm,size_19,color_FFFFFF,t_70,g_se,x_16)

原网站

版权声明
本文为[III VII]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203012031545816.html