어제까지 만들던 파일을 이용하여 서버와 연결, 회원가입 시 데이터베이스에 ID, 암호화된 PW가 들어간다.
로그인 할 경우 데이터베이스에 있는 아이디와 비밀번호(해쉬값)이 일치하는 것이 있다면 로그인이 되도록 만들었다.
from pymongo import MongoClient
import jwt
import datetime
import hashlib
from flask import Flask, render_template, jsonify, request, redirect, url_for
# from werkzeug.utils import secure_filename
from datetime import datetime, timedelta
app = Flask(__name__)
# app.config["TEMPLATES_AUTO_RELOAD"] = True
# app.config['UPLOAD_FOLDER'] = "./static/profile_pics"
SECRET_KEY = 'SPARTA'
client = MongoClient('mongodb://13.124.117.232', 27017, username="test", password="test") # aws연결
# client = MongoClient('localhost', 27017) # 로컬연결
db = client.dbsparta_plus_week4
@app.route('/')
def home():
token_receive = request.cookies.get('mytoken')
try:
payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])
return render_template('index.html')
except jwt.ExpiredSignatureError:
return redirect(url_for("login", msg="로그인 시간이 만료되었습니다."))
except jwt.exceptions.DecodeError:
return redirect(url_for("login", msg="로그인 정보가 존재하지 않습니다."))
@app.route('/login')
def login():
msg = request.args.get("msg")
return render_template('login.html', msg=msg)
@app.route('/sign_in', methods=['POST'])
def sign_in():
username_receive = request.form['username_give']
password_receive = request.form['password_give']
pw_hash = hashlib.sha256(password_receive.encode('utf-8')).hexdigest()
result = db.users.find_one({'username': username_receive, 'password': pw_hash})
if result is not None: #result 찾음
payload = {
'id': username_receive,
'exp': datetime.utcnow() + timedelta(seconds=60 * 60 * 24) # 로그인 24시간 유지
}
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256').decode('utf-8')
return jsonify({'result': 'success', 'token': token})
# result 못찾음
else:
return jsonify({'result': 'fail', 'msg': '가입하지 않은 아이디이거나, 잘못된 비밀번호입니다.'})
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>로그인 페이지</title>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<link rel="stylesheet" href="../static/css/login.css">
<script>
function sign_in() {
let username = $("#input-username").val()
let password = $("#input-password").val()
if (username == "") {
alert('아이디를 입력하세요!')
$("#input-username").focus()
return;
} else {
$("#help-id-login").text("")
}
if (password == "") {
alert('비밀번호를 입력하세요!')
$("#input-password").focus()
return;
} else {
$("#help-password-login").text("")
}
$.ajax({
type: "POST",
url: "/sign_in",
data: {
username_give: username,
password_give: password
},
success: function (response) {
if (response['result'] == 'success') {
$.cookie('mytoken', response['token'], {path: '/'});
window.location.replace("/")
} else {
alert(response['msg'])
}
}
});
}
</script>
<link rel="stylesheet" href="../static/login.css">
</head>
<body>
<h1 class="main_title"> 조난99 </h1>
<div class="big_login_box">
<div class="input-group mb-3" id="login-box">
<input id="input-username" type="text" class="form-control" placeholder="아이디를 입력해주세요." aria-label="Recipient's username"
aria-describedby="button-addon2" style="height:50px; width: 500px; margin-bottom: 5px"><br>
<input id="input-password" type="password" class="form-control" placeholder="비밀번호를 입력해주세요."
aria-label="Recipient's username" aria-describedby="button-addon2" style="height:50px; width: 500px"><br>
<button onclick="sign_in()" class="btn btn-outline-secondary" type="button" id="button-login"
style="height:50px; width: 500px; margin-top: 20px">로그인
</button>
<br>
<button onclick="location.href='sign_up.html'" class="btn btn-outline-secondary"
type="button" id="button-sign_up" style="height:50px; width: 500px; margin-top: 3px">회원가입
</button>
</div>
</div>
</body>
</html>
임포트한 것들은 대부분 패키지를 설치해줘야된다.
비밀번호를 그대로 데이터베이스에 넣으면 공격에 취약하기 때문에 해쉬함수를 통해 암호화하고 넣는다.
오후에 협업하는 과정에서 로컬환경에서는 되는데 해당 파일들을 수정하다 보니 기능이 안먹거나 오타가 나거나 하며 문제가 생기는 경우가 발생했다. 깃허브에서 팀프로젝트를 진행할 경우 한번에 크게 수정하여 푸쉬하는 것보다 수정의 내용이 많을 수록 이런 오류를 찾기가 힘들어지다보니 귀찮더라도기능별로 작게 나눠 commit을 하여 알아보기에 좋게, 파일이 꼬이지 않게 하는 것이 중요하다.