겉바속촉

[Ethereum] 로그인 기능 추가 본문

IT일기(하반기)/ETHEREUM

[Ethereum] 로그인 기능 추가

겉바속촉 2020. 8. 7. 17:45
728x90
반응형

지난 번에 이어서 해보도록 할게요:)

2020/08/07 - [IT일기/ETHEREUM] - [Ethereum] db에 넣어보기

 

[Ethereum] db에 넣어보기

이번에는 db에 넣어보려고합니다:) 프로젝트 하나 생성해주세요 저는 8_IITP_etherem으로 dynamic web project 생성했습니다 그리고 maven으로 바꾸어주신후에!! 시작해볼게요 !^^! 우선 먼저 각 파일들의 위

2-juhyun-2.tistory.com

 

 

 

로그인 기능을 하는 버튼을 추가할게요

 

index.jsx에다가 다음을 추가해주세요

 

 

 

 

로그인 기능을 하는 버튼 추가

 

<button onClick={this.login} > 로그인 </button> 

 

 

 

로그인 기능을 처리하는 함수 작성 추가

 

login=(event)=>{
	window.open("login.html",'_blank','width=800,height=550');
    }

 

 

전체 index.jsx

var {Component} = React;
var {Router, Route, IndexRoute, Link} = ReactRouter;
 
class Main extends Component{
    render(){
 return(            
            <div>
                <h1>BlockChain Study</h1>
                <ul className="header" >
                    <li><Link exact to="/">Home</Link></li>
                    <li><Link to="/bitcoin">Bitcoin</Link></li>
                    <li><Link to="/ethereum">Ethereum</Link></li>
                    <li><Link to="/hyperledger">Hyperledger</Link></li>
                </ul>
                <div className="content">
                {this.props.children}
                </div>
            </div>            
        );
    }
}
class Home extends Component{
    render(){
        return(
            <div>
                <h2>HELLO</h2>
                <p>안녕하세요? BlockChain Java 웹 예제(dApp)입니다. 잘해보죠~!!!</p>
            </div>
        );
    }
}
    class BitcoinNetwork extends Component{
    state={
        blockNumber:0,
        acc1_balance:0,
        acc2_balance:0
    }
    
    bit_network_connect=()=>{
        axios.get('/bit_network/connect')
        .then((response)=>{
 console.log(response);
            this.setState({
                blockNumber:response.data.blockNumber,
                acc1_balance:response.data.acc1_balance,
                acc2_balance:response.data.acc2_balance
            });
            
        })
        .catch((error)=>{
            console.log(error);
        });
    }
    send=()=>{
        alert(this.amount.value);
    axios.post('/bit_network/send',{"amount":this.amount.value})
        .then((response)=>{
            console.log(response);
            this.setState({
                blockNumber:response.data.blockNumber,
                acc1_balance:response.data.acc1_balance,
                acc2_balance:response.data.acc2_balance
            });
        })
        .catch((error)=>{
            console.log(error);
        });
    }
    render(){
        return(
            <div>
                <h2>BitcoinNetwork</h2>
                <p><button onClick={this.bit_network_connect}>연결</button></p>
                <br/>
                block number : {this.state.blockNumber} <br/>
                acc1 balance : {this.state.acc1_balance} <br/>
                acc2 balance : {this.state.acc2_balance} <br/>
                <br/>
                <div>acc1가 acc2에게 {' '}
                <input placeholder='송금량' ref={ref=>this.amount=ref} />BTC  {' '} 
                <button onClick={this.send}  > 보내기</button><br/>               
                </div>
            </div>
        );
    }
}


/* 이더리움 연동 요청  */
class EthereumNetwork extends Component{  
	login=(event)=>{
	window.open("login.html",'_blank','width=800,height=550');
    }

   createUser=(event)=>{
	window.open("createUser.html",'_blank','width=800,height=550');
    }	
    
	send1=(event)=>{
        alert(this.state.name);
        event.preventDefault();
        axios.post('main',{"name":this.state.name,"sign":this.state.team})
        .then((response)=>{
            console.log(response);
            this.setState({
                result1:response.data.result,
                message1:response.data.message,                
            });
			
        })
        .catch((error)=>{
            console.log(error);
        });
    }
    send2=(event)=>{
     alert(this.state.name);
        event.preventDefault();
        axios.post('main',{"name":this.state.name,"sign":this.state.team})
        .then((response)=>{
            console.log(response);
            this.setState({
                result2:response.data.result,
                message2:response.data.message,                
            });
			
        })
        .catch((error)=>{
            console.log(error);
        });
    }
    send3=(event)=>{
     alert(this.token.value);
        event.preventDefault();
        axios.post('main',{"name":this.token.value,"sign":this.state.team})
        .then((response)=>{
            console.log(response);
            this.setState({
                result3:response.data.result,
                message3:response.data.message,                
            });
			
        })
        .catch((error)=>{
            console.log(error);
        });
    }

    state = {
      name: "React",
      team : "team",
      result1 : 0,
	  result2 : 0,
	  result3 : 0,
      message1 : "no message",
      message2 : "no message",
      message3 : "no message"
    };
    onChangeTeam1 =(event)=> {	 
      console.log(event.target.name); 
      this.setState({team:event.target.name});
      
  	}
    onChangeValue1 =(event)=> {	  
      this.setState({name:event.target.value});
      console.log(this.state.team);
  	} 
  	
  	onChangeTeam2 =(event)=> {	 
      console.log(event.target.name); 
      this.setState({team:event.target.name});
      
  	}
	onChangeValue2 =(event)=> {	  
      this.setState({name:event.target.value});
      console.log(this.state.team);
  	} 
  	
  	onChangeTeam3 =(event)=> {	 
      console.log(event.target.name); 
      this.setState({team:event.target.name});
      
  	}
  	
  	
	
  	
    render(){
        return(
	     <div>
            <div>
                <h2>EthereumNetwork 연결 해보세요</h2>   
                 
                <button onClick={this.createUser} name="team1"> 회원가입 </button>
				<button onClick={this.login}>로그인</button>         
            </div>
            <br/><br/>
			<div> 
				<a href="#team1"> 1조 </a> |
				<a href="#team2"> 2조 </a> |
				<a href="#team3"> 3조 </a> |
				<a href="#team4"> 4조 </a> |
				<a href="#team5"> 5조 </a> |
				<a href="#team6"> 6조 </a> |
			</div>
			<br/><br/>
			<div id="team1">
				<a name="team1"> 1조 [아마곗돈] </a>
				<button onClick={this.onChangeTeam1} name="team1"> 1조 서비스 받기 </button>
				<br/><br/>
    			<form onSubmit={this.send1}>				
					<div onChange={this.onChangeValue1}>
				        <input type="radio" value="노트북계" name="team1" /> 노트북계
				        <input type="radio" value="쌍수계" name="team1" /> 쌍수계
				        <input type="radio" value="여행계" name="team1" /> 여행계
				    </div>
				   <input type="submit" value="입금하기" />
			    </form>
                {this.state.message1} : 총 곗돈 : {this.state.result1}
			</div>
			<div id="team2">
				<a name="team2"> 2조 [키다리아저씨]</a>
				<button onClick={this.onChangeTeam2} name="team2"> 2조 서비스 받기 </button>
				<br/>
				<form onSubmit={this.send2}>	
				    <div onChange={this.onChangeValue2}>			   
				      <input type="radio" name="team2" value="밀알복지재단"/>밀알 복지 재단<br/>
				      <input type="radio" name="team2" value="삼육재단"/>삼육 재단<br/>
				      <input type="radio" name="team2" value="한국유기동물복지 협회"/>한국 유기동물 복지 협회<br/>
				    </div>
					<input type="submit" value="후원하기"/>
				 </form>
				{this.state.message2} : 총 후원금 : {this.state.result2}
			</div>
			<div id="team3">
				<a name="team3"> 3조 </a>
				<button onClick={this.onChangeTeam3} name="team3"> 3조 서비스 받기 </button>
				 <br/>
				   <b>장동건</b>님과의 거래진행중...
				   <br/>
				   <br/>
				   <img alt=""
				      src="https://funshop.akamaized.net/abroad/025/12727/nike-adapt-bb_0.jpg"
				      width="400" border="1"/>
				   <br/>
				   <br/> 상품명 : 나이키
				   <br/> 거래 가격 : 5,000원
				   <br/>
				   <br/>
				   <form onSubmit={this.send3}>
				       <b>토큰</b> 
				       <input ref={ref=>this.token=ref} /><input type="submit" value="토큰 보내기"/>
				   </form>
				   {this.state.message3} : 총 토큰: {this.state.result3}
			</div>
			<div>
				<a name="team4"> 4조 </a>
			</div>
			<div>
				<a name="team5"> 5조 </a>
			</div>
			<div>
				<a name="team6"> 6조 </a>
			</div>
		  </div>
        );
    }
}
class HyperledgerNetwork extends Component{  
 render(){
        return(
            <div>
                <h2>HyperledgerNetwork 연결 해보세요</h2>                
            </div>
        );
    }
}
    ReactDOM.render(
    (<Router>
        <Route path="/" component={Main} >   
            <Route path="bitcoin" component={BitcoinNetwork}/>
            <Route path="ethereum" component={EthereumNetwork} />
            <Route path="hyperledger" component={HyperledgerNetwork} />
            <IndexRoute component={Home} />
        </Route>
    </Router>)
    ,document.getElementById("root")
);

 

 

login.html 작성

DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/reset.css" type="text/css" media="screen">
    <link rel="stylesheet" href="css/style.css" type="text/css" media="screen">
    <link rel="stylesheet" href="css/grid.css" type="text/css" media="screen">   
    <script src="js/jquery-1.6.2.min.js" type="text/javascript"></script>     
    
    <!-- 리액트 관련-->
    <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    
</head>
<body>
    <div id="login" />
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script type="text/babel" src="login.jsx"></script>
</body>
</html>

 

 

login.jsx 작성

 

class LoginUser extends React.Component{
  send=()=>{
 		axios.post('main',{"sign":"login","id":this.id.value,"p_w":this.pw.value})
        .then((response)=>{
            console.log(response);
            alert(response.data.message);
            window.opener = null;
			window.open('', '_self');
			window.close();
			
        })
        .catch((error)=>{
            console.log(error);
        });
    }
    
 
    render(){     
 
        const main={
 
            width:'500px',
 
            height:'300px',
 
            margin:'30px auto'
 
            }
 
        const first={
 
            width:'400px',
 
            height:'400px',
 
            boxShadow:'0 0 0 1px rgba(14,41,57,0.12),0 2px 5px rgba(14,41,57,0.44),inset 0 -1px 2px rgba(14,41,57,0.15)',
 
            float:'left',
 
            padding:'10px 50px 0',
 
            background:'linear-gradient(#fff,#f2f6f9)'
 
            }
       
 
            const label={
 
            fontSize:'17px'            
     }
 
            const     input={
 
            width:'400px',
 
            padding:'5px',
 
            marginTop:'10px',
 
            marginBottom:'10px',
 
            borderRadius:'5px',
 
            border:'1px solid #cbcbcb',
 
            boxShadow:'inset 0 1px 2px rgba(0,0,0,0.18)',
 
            fontSize:'16px'
 
            }
 
            const select={
 
                padding:'13px'
 
            }

 
            const input_type_submit={
 
            background:'linear-gradient(to bottom,#22abe9 5%,#36caf0 100%)',
 
            boxShadow:'inset 0 1px 0 0 #7bdcf4',
 
            border:'1px solid #0F799E',
 
            color:'#fff',
 
            fontSize:'19px',
            
 			fontWeight:'700',
 
            cursor:'pointer',
 
            textShadow:'0 1px 0 #13506D'            
 
            }
 
            const center={
 
                align:'center'
 
            }
 
            
 
        return (          
 
            <div style={main}>
 
                <div style={first}>
 
                
                
	                <h1>login</h1>
	 
	                <h4>Please fill all entries.</h4><hr/>
	 
	                <label style={label}>ID :</label>
	 
	                <input style={input}  placeholder="아이디" ref={ref=>this.id=ref}/>
	 
	                <label style={label}>PW :</label>
	 
	                <input style={input}  placeholder="패스워드" ref={ref=>this.pw=ref}/>	 
	               
	                
	                <input style={input_type_submit} onClick={this.send} type="submit" value="Send"/> 
	                
	             
                
 
                </div>
 
            </div>           
 
        )
 
    }
 
}
 
 
ReactDOM.render( 
 
    <LoginUser / > ,
 
    document.getElementById('login')
 
);

 

 

UserDAO도 다음 해당하는 부분으로 고쳐주세요

public  String login(String id, String pw, String wallet_path) {
		StringBuffer  result=new StringBuffer();
		Connection con=null;
		PreparedStatement st=null;
		ResultSet rs=null;
		try {
			con = EConnection.getConnection(this, wallet_path);	
			st = con.prepareStatement("select * from users where id=? and pw=? ");
			st.setString(1, id);
			st.setString(2, pw);
			rs = st.executeQuery();
   		    if ( rs.next() ) {
			       result.append("pri_key: "+rs.getString("pri_key"));
			       result.append("\npub_key: "+rs.getString("pub_key"));
			       result.append("\naddress: "+rs.getString("address"));
			}

 

그래서 전체 UserDAO

package web.dao;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Optional;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.admin.methods.response.PersonalListAccounts;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;
import org.web3j.utils.Convert.Unit;
import org.xml.sax.SAXException;


public class UserDAO {
	
	
	public void transferEther(String address) throws Exception {
		
	  Web3j web3 = Web3j.build(new HttpService("HTTP://127.0.0.1:7545"));
	  System.out.println("Successfuly connected to Ethereum");
	  System.out.println("Balance: " + Convert.fromWei(web3.ethGetBalance(address, DefaultBlockParameterName.LATEST).send().getBalance().toString(), Unit.ETHER));
	  
	  Admin admin= Admin.build(new HttpService("HTTP://127.0.0.1:7545"));
	  PersonalListAccounts personalListAccounts = admin.personalListAccounts().send();
	  List<String> addressList = personalListAccounts.getAccountIds();
	  
	  // Get the latest nonce of Sender
	  String senderAddress=addressList.get(0);
      EthGetTransactionCount ethGetTransactionCount = web3.ethGetTransactionCount(senderAddress, DefaultBlockParameterName.LATEST).send();
      BigInteger nonce =  ethGetTransactionCount.getTransactionCount();

      // Recipient address
      String recipientAddress = address;

      // Value to transfer (in wei)
      BigInteger value = Convert.toWei("10", Unit.ETHER).toBigInteger();

      // Gas Parameters
      BigInteger gasLimit = BigInteger.valueOf(21000);
      BigInteger gasPrice = Convert.toWei("1", Unit.GWEI).toBigInteger();

      // Prepare the rawTransaction
      RawTransaction rawTransaction  = RawTransaction.createEtherTransaction(
                 nonce,
                 gasPrice,
                 gasLimit,  
                 recipientAddress,
                 value);

      // Sign the transaction
      Credentials credentials=Credentials.create("e03bfa27c874d8413bcffe7423c982715fa0b4d84cb37ffa2c2b2ef80d89233a");
      byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
      String hexValue = Numeric.toHexString(signedMessage);

      // Send transaction
      EthSendTransaction ethSendTransaction = web3.ethSendRawTransaction(hexValue).send();
      String transactionHash = ethSendTransaction.getTransactionHash();
      System.out.println("transactionHash: " + transactionHash);

      // Wait for transaction to be mined
      Optional<TransactionReceipt> transactionReceipt = null;
      do {
        System.out.println("checking if transaction " + transactionHash + " is mined....");
            EthGetTransactionReceipt ethGetTransactionReceiptResp = web3.ethGetTransactionReceipt(transactionHash).send();
            transactionReceipt = ethGetTransactionReceiptResp.getTransactionReceipt();
            Thread.sleep(3000); // Wait 3 sec
      } while(!transactionReceipt.isPresent());

      System.out.println("Transaction " + transactionHash + " was mined in block # " + transactionReceipt.get().getBlockNumber());
      System.out.println("Balance: " + Convert.fromWei(web3.ethGetBalance(address, DefaultBlockParameterName.LATEST).send().getBalance().toString(), Unit.ETHER));

	  
	}
	
	
	public  String createUser(String id, String pw, String name, String wallet_path) {
		String pri_key="",pub_key="",address="";
		try {
		
		  String str=WalletUtils.generateNewWalletFile(pw, new File(wallet_path), true);
		  System.out.println(str);
		  Credentials credentials = WalletUtils.loadCredentials(pw, wallet_path+str);
		  
		  ECKeyPair keyPair=credentials.getEcKeyPair();
		  pri_key=keyPair.getPrivateKey().toString()+"";
		  pub_key=keyPair.getPublicKey().toString()+"";
		  address=credentials.getAddress();
		  
		  System.out.println("pri_key:"+pri_key);		  
		  System.out.println("pub_key:"+pub_key);
		  System.out.println("address:"+address);
		  
		  transferEther(address);
		}catch(Exception e) {
			e.printStackTrace();
		}
		  
		StringBuffer  result=new StringBuffer();
		Connection con=null;
		PreparedStatement st=null;
		int rs=0;
		try {
			con = EConnection.getConnection(this,wallet_path);	
			st = con.prepareStatement("insert into Users(id,pw,name,pri_key,pub_key,address) values ( ?, ? , ? , ?, ?, ?) ");
			st.setString(1, id);
			st.setString(2, pw);
			st.setString(3, name);
			st.setString(4, pri_key);
			st.setString(5, pub_key);
			st.setString(6, address);
			rs = st.executeUpdate();
   		    
			result.append("insert row: "+rs);			
			
		} catch (SQLException e1) {
			e1.printStackTrace();
			result.append("요청처리에러발생");
		}
	
		
		if ( st != null ) try { st.close(); }catch(SQLException e){}
		if ( con != null ) try { con.close(); }catch(SQLException e){}
        
		return result.toString();
	}
	

	
	public  String login(String id, String pw, String wallet_path) {
		StringBuffer  result=new StringBuffer();
		Connection con=null;
		PreparedStatement st=null;
		ResultSet rs=null;
		try {
			con = EConnection.getConnection(this, wallet_path);	
			st = con.prepareStatement("select * from users where id=? and pw=? ");
			st.setString(1, id);
			st.setString(2, pw);
			rs = st.executeQuery();
   		    if ( rs.next() ) {
			       result.append("pri_key: "+rs.getString("pri_key"));
			       result.append("\npub_key: "+rs.getString("pub_key"));
			       result.append("\naddress: "+rs.getString("address"));
			}
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			result.append("요청처리에러발생");
		}
	
			if ( rs != null ) try { rs.close(); }catch(SQLException e){}
			if ( st != null ) try { st.close(); }catch(SQLException e){}
			if ( con != null ) try { con.close(); }catch(SQLException e){}
            
			return result.toString();
	}
	
	
	
}

 

 

EConnection 확인해주세요

 

package web.dao;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;



public class EConnection {
	static String wallet_path;
	public static Connection getConnection(Object o) {
		return getConnection(o,wallet_path);
	}
     public static Connection getConnection(Object o, String wallet_path) {
    	 EConnection.wallet_path=wallet_path;
    	 Connection con=null;
    	 Properties properties = new Properties();
    	 
    	 try {   	
    		  String str=wallet_path+"..\\WEB-INF\\config\\dbconn.properties";
    		  System.out.println(str);
    		  properties.load(new FileReader(str));
    		  String driver = properties.getProperty("jdbc.driver");
    		  System.out.println(driver);
    	      //properties.load( o.getClass().getClassLoader().getResourceAsStream(str));
    	 } catch (IOException e) {
    		System.out.println("DB 정보 로드 실패");
    	    return null;
    	 }
    	 String driver = properties.getProperty("jdbc.driver");
    	 String url = properties.getProperty("jdbc.url");
    	 String username = properties.getProperty("jdbc.username");
    	 String password = properties.getProperty("jdbc.password");
    
    	 try {
    	    Class.forName(driver); 
    	    con=DriverManager.getConnection(url,username,password);
    	 }catch(Exception e){
    		 e.printStackTrace();
    		 System.out.println("DB 연결 오류");
    		 return null;
    	 } 
    	 return con;
     }
}

 

이제 서버 restart하신 다음!!! 로그인 클릭해주세요

 

 

 

그리고 id, pw 입력 후 send 클릭!!!!

eclipse의 콘솔창을 봐주세요:)

 

 

로그인이 잘 되었네요:)

 

 

 


현재 구조는 이렇습니다

 

user가 한명씩 생성이 되면 주인이 10eth씩 전송해주는 그런 구조입니다

즉, master가 주는 것이죠

 

그럼 그러한  transaction이 smartcontract로서 block에 하나씩 저장이 되는 것입니다

 

그렇게 회원가입이 끝나고 로그인 기능을 추가했는데요

로그인 버튼을 클릭하면 회원가입을 통해 구축한 db에서 존재하는 지 정보를 찾을 수 있는 

메서드를 만들어서 비교가 되도록 짜주는 것입니다

 

 

728x90
반응형