import hashlib from flask import request,jsonify,render_template,redirect,url_for from flask_restx import Resource, Api, Namespace, fields from database.database import DB import datetime import jwt users = {} Auth = Namespace( name="Auth", description="사용자 인증을 위한 API", ) user_fields = Auth.model('User', { # Model 객체 생성 'id': fields.String(description='a User Name', required=True, example="id") }) user_fields_auth = Auth.inherit('User Auth', user_fields, { 'password': fields.String(description='Password', required=True) }) user_fields_register = Auth.inherit('User reigster', user_fields, { 'password': fields.String(description='Password', required=True),'email': fields.String(description='email', required=True),'user_sex': fields.String(description='sex', required=True),'phone': fields.String(description='phone', required=True) }) @Auth.route('/id') class AuthCheck(Resource): @Auth.doc(responses={200: 'Success'}) @Auth.doc(responses={500: 'Register Failed'}) def post(self): db=DB() id = request.json['id'] value=db.db_check_id(id) if value != None: return { "message": "중복 아이디가 있습니다" }, 500 else: return { 'message': '사용가능한 아이디입니다' # str으로 반환하여 return }, 200 @Auth.route('/register') class AuthRegister(Resource): @Auth.expect(user_fields_register) @Auth.doc(responses={200: 'Success'}) @Auth.doc(responses={500: 'Register Failed'}) def post(self): db=DB() id = request.json['id'] password = request.json['password'] user_email = request.json['email'] sex = request.json['user_sex'] phone = request.json['phone'] pw_has = hashlib.sha256(password.encode('utf-8')).hexdigest() value=db.db_login(id,password) if value != None: return { "message": "Register Failed" }, 500 else: db.db_add_id(id,pw_has,user_email,sex,phone) return { 'Authorization': id # str으로 반환하여 return }, 200 @Auth.route('/login') class AuthLogin(Resource): @Auth.expect(user_fields_auth) @Auth.doc(responses={200: 'Success'}) @Auth.doc(responses={404: 'User Not Found'}) @Auth.doc(responses={500: 'Auth Failed'}) def post(self): db=DB() id = request.json['id'] password = request.json['password'] pw_hash = hashlib.sha256(password.encode('utf-8')).hexdigest() result = db.db_login(id,pw_hash) if result is not None: payload = { 'id' : id, 'exp' : datetime.datetime.utcnow() + datetime.timedelta(seconds=70) } token = jwt.encode(payload, "secret", algorithm='HS256') return jsonify({'result': 'success', 'token': token}) else: return jsonify({'result': 'fail', 'msg': '아이디/비밀번호가 일치하지 않습니다.'}) @Auth.route('/secession') class AuthSecession(Resource): def post(self): db=DB() id = request.json['token'] payload = jwt.decode(id, "secret", algorithms=['HS256']) db.db_delete_id(payload['id']) return {'secession':'success'}