-
Web Dev Bootcamp TIL Day-15(Flask login/register/JWT)TIL 2022. 5. 9. 20:53
- In Python, functions are first-class objects - functions can be passed around and used as arguments
- It’s possible to define functions inside other functions - such functions are called inner functions.
- Python also allows you to use functions as return values.
Decorator Functions:
wraps functions w/ additional functionality
def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper def say_whee(): print("Whee!") say_whee = my_decorator(say_whee)
@app.route('/api/register', methods=['POST']) def api_register(): id_receive = request.form['id_give'] pw_receive = request.form['pw_give'] nickname_receive = request.form['nickname_give'] pw_hash = hashlib.sha256(pw_receive.encode('utf-8')).hexdigest() db.user.insert_one( {'id': id_receive, 'pw': pw_hash, 'nick': nickname_receive}) return jsonify({'result': 'success'}) # [로그인 API] # id, pw를 받아서 맞춰보고, 토큰을 만들어 발급합니다. @app.route('/api/login', methods=['POST']) def api_login(): id_receive = request.form['id_give'] pw_receive = request.form['pw_give'] # 회원가입 때와 같은 방법으로 pw를 암호화합니다. pw_hash = hashlib.sha256(pw_receive.encode('utf-8')).hexdigest() # id, 암호화된pw을 가지고 해당 유저를 찾습니다. result = db.user.find_one({'id': id_receive, 'pw': pw_hash}) # 찾으면 JWT 토큰을 만들어 발급합니다. if result is not None: # JWT 토큰에는, payload와 시크릿키가 필요합니다. # 시크릿키가 있어야 토큰을 디코딩(=암호화 풀기)해서 payload 값을 볼 수 있습니다. # 아래에선 id와 exp를 담았습니다. 즉, JWT 토큰을 풀면 유저ID 값을 알 수 있습니다. # exp에는 만료시간을 넣어줍니다. 만료시간이 지나면, 시크릿키로 토큰을 풀 때 만료되었다고 에러가 납니다. payload = { 'id': id_receive, 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=5) } token = jwt.encode(payload, SECRET_KEY, algorithm='HS256') # token을 줍니다. return jsonify({'result': 'success', 'token': token}) # 찾지 못하면 else: return jsonify({'result': 'fail', 'msg': '아이디/비밀번호가 일치하지 않습니다.'})
@app.route('/') def home(): # 현재 이용자의 컴퓨터에 저장된 cookie 에서 mytoken 을 가져옵니다. token_receive = request.cookies.get('mytoken') try: # 암호화되어있는 token의 값을 우리가 사용할 수 있도록 디코딩(암호화 풀기)해줍니다! payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256']) user_info = db.user.find_one({"id": payload['id']}) return render_template('index.html', nickname=user_info["nick"]) # 만약 해당 token의 로그인 시간이 만료되었다면, 아래와 같은 코드를 실행합니다. except jwt.ExpiredSignatureError: return redirect(url_for("login", msg="로그인 시간이 만료되었습니다.")) except jwt.exceptions.DecodeError: # 만약 해당 token이 올바르게 디코딩되지 않는다면, 아래와 같은 코드를 실행합니다. return redirect(url_for("login", msg="로그인 정보가 존재하지 않습니다."))
'TIL' 카테고리의 다른 글
Web Dev Bootcamp Day-20(Machine Learning cont.) (0) 2022.05.13 Web Dev Bootcamp TIL Day-19(Machine Learning Start) (0) 2022.05.13 Web Dev Bootcamp TIL Day-13 (JWT & ERD) (0) 2022.05.05 Web Dev Bootcamp TIL Day-12 (Flaskgram Clone Start) (0) 2022.05.04 Web Dev Bootcamp TIL Day-11(Djangogram fin.) (2) 2022.05.02