내배캠 25일차

·2022년 12월 8일
0

내일배움캠프

목록 보기
26/142
post-thumbnail

TODO

  • 암호화오류수정
  • 아이디저장
  • 아이디찾기
  • 회원탈퇴
  • app.py 합치고 배포까지

HTML, JS, CSS로 디자인
Python, JS, Flask, DBeaver, Jquery, Ajax, MySQL를 이용해서 서버에서 데이터를 처리
GIT, Sourcetree 이용해서 협업

로그인코드정리(app.py)

# 로그인
@app.route('/user/login', methods=['POST'])
def user_login():
    db = pymysql.connect(
        user='',
        password='',
        host='',
        port=3306,
        database='project2b2',
        charset='utf8'
    )
    curs = db.cursor()

    userId = request.form['id']
    password = request.form['password']

    # 입력된 비밀번호를 바이트 코드로 변환
    byte_input = password.encode('UTF-8')

    # hash = bcrypt.hashpw(password.decode('utf-8'), bcrypt.gensalt())
    # print(pw_check)
    # userName = request.form['name']

    sql = f'select id,password,name,email,image,description from user where user.id = "{userId}"'

    curs.execute(sql)
    result = curs.fetchone()
    list_result = list(result)
    # 기존 저장된 값을 연산을 위해 hex에서 바이트로 변경
    origin_pw = bytes.fromhex(list_result[1])
    pw_check = bcrypt.checkpw(byte_input, origin_pw)
    # pw_check = bcrypt.check_password_hash(hash, list_result[1])
    # print(list_result[1])
    db.commit()  # 삽입,삭제,수정할때, 최종적으로 데이터베이스를 만져줄때만
    db.close()

    if result is None:
        # print('none')
        return jsonify({'msg': '회원이 아닙니다.'})

    else:
        if not pw_check:
            return jsonify({'msg': '비밀번호가 일치하지 않습니다.'})

        else:
            session['id'] = result[0]
            session['name'] = result[2]
            session['email'] = result[3]
            session['image'] = result[4]
            session['description'] = result[5]
            return jsonify({'msg': '로그인 성공'})

아이디찾기(app.py)

# 아이디찾기-----------------------------------------------------
@app.route('/find/id', methods=['POST'])
def findId():
    db = pymysql.connect(
        user='',
        password='',
        host='',
        port=3306,
        database='project2b2',
        charset='utf8'
    )
    curs = db.cursor()

    email = request.form['email']

    sql_check = f'select id from `user` where email = "{email}" '

    curs.execute(sql_check)
    result = curs.fetchone()

    db.commit()
    db.close()

    if result is None:
        return jsonify({'msg': '회원이 아닙니다.'})

    return jsonify({'msg': result[0]})

아이디찾기(login.js)

// 아이디찾기 ------------------------------------------------------
function findId() {
  let find_email = prompt("이메일을 입력하세요");

  if (find_email === "") {
    alert("빈칸을 채워주세요.");
    return findId();
  }

  $.ajax({
    type: "POST",
    url: "/find/id",
    data: {
      email: find_email,
    },
    success: function (response) {
      if (response["msg"] == "회원이 아닙니다.") {
        alert(response["msg"]);
        return;
      }
      alert(response["msg"]);
      window.location.href = "/login";
    },
  });
}

회원탈퇴(app.py)

# 회원탈퇴-----------------------------------------------------
@app.route('/delete/user', methods=['POST'])
def deleteUser():
    db = pymysql.connect(
        user='',
        password='',
        host='',
        port=3306,
        database='project2b2',
        charset='utf8'
    )
    curs = db.cursor()

    idf = request.form['idf']
    pwf = request.form['pwf']
    byte_input = pwf.encode('UTF-8')

    sql_check = f'select password from `user` where id = "{idf}" '

    curs.execute(sql_check)
    result = curs.fetchone()
    if result is None:
        return jsonify({'msg': '회원이 아닙니다.'})

    origin_pw = bytes.fromhex(result[0])
    pw_check = bcrypt.checkpw(byte_input, origin_pw)
    db.commit()
    db.close()

    if pw_check is None:
        return jsonify({'msg': '회원이 아닙니다.'})

    db = pymysql.connect(
        user='',
        password='',
        host='',
        port=3306,
        database='project2b2',
        charset='utf8'
    )
    curs = db.cursor()

    idf = request.form['idf']
    pwf = request.form['pwf']

    sql_check = f'delete from `user` where id = "{idf}" '

    curs.execute(sql_check)
    db.commit()
    db.close()

    return jsonify({'msg': '회원탈퇴가 되었습니다.'})

회원탈퇴(login.js)

// 회원탈퇴 ------------------------------------------------------
function deleteUser() {
  let find_id = prompt("아이디를 입력하세요");
  let find_pw;

  if (find_id === "") {
    alert("빈칸을 채워주세요.");
    return deleteUser();
  } else {
    find_pw = prompt("비밀번호를 입력하세요");

    if (find_pw === "") {
      alert("빈칸을 채워주세요.");
      return deleteUser();
    }
    console.log(find_id, find_pw, 0);
  }
  console.log(find_id, 2);
  console.log(find_id, find_pw, 1);

  $.ajax({
    type: "POST",
    url: "/delete/user",
    data: {
      idf: find_id,
      pwf: find_pw
    },
    success: function (response) {
      if (response["msg"] == "회원이 아닙니다.") {
        alert(response["msg"]);
        return;
      }
      alert(response["msg"]);
      window.location.href = "/login";
    },
  });
}

아이디저장-쿠키사용(login.js)

// 아이디저장(쿠키사용)------------------------------------------------------------------------------
$(document).ready(function () {
  // 저장된 쿠키값을 가져와서 ID 칸에 넣어준다. 없으면 공백으로 들어감.
  var key = getCookie("key");
  $("#userid").val(key);

  // 그 전에 ID를 저장해서 처음 페이지 로딩 시, 입력 칸에 저장된 ID가 표시된 상태라면,
  if ($("#userid").val() != "") {
    $("#checkId").attr("checked", true); // ID 저장하기를 체크 상태로 두기.
  }

  $("#checkId").change(function () {
    // 체크박스에 변화가 있다면,
    if ($("#checkId").is(":checked")) {
      // ID 저장하기 체크했을 때,
      setCookie("key", $("#userid").val(), 7); // 7일 동안 쿠키 보관
    } else {
      // ID 저장하기 체크 해제 시,
      deleteCookie("key");
    }
  });

  // ID 저장하기를 체크한 상태에서 ID를 입력하는 경우, 이럴 때도 쿠키 저장.
  $("#userid").keyup(function () {
    // ID 입력 칸에 ID를 입력할 때,
    if ($("#checkId").is(":checked")) {
      // ID 저장하기를 체크한 상태라면,
      setCookie("key", $("#userid").val(), 7); // 7일 동안 쿠키 보관
    }
  });
});
// 쿠키 저장하기
// setCookie => saveid함수에서 넘겨준 시간이 현재시간과 비교해서 쿠키를 생성하고 지워주는 역할
function setCookie(cookieName, value, exdays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var cookieValue =
    escape(value) + (exdays == null ? "" : "; expires=" + exdate.toGMTString());
  document.cookie = cookieName + "=" + cookieValue;
}

// 쿠키 삭제
function deleteCookie(cookieName) {
  var expireDate = new Date();
  expireDate.setDate(expireDate.getDate() - 1);
  document.cookie = cookieName + "= " + "; expires=" + expireDate.toGMTString();
}

// 쿠키 가져오기
function getCookie(cookieName) {
  cookieName = cookieName + "=";
  var cookieData = document.cookie;
  var start = cookieData.indexOf(cookieName);
  var cookieValue = "";
  if (start != -1) {
    // 쿠키가 존재하면
    start += cookieName.length;
    var end = cookieData.indexOf(";", start);
    if (end == -1)
      // 쿠키 값의 마지막 위치 인덱스 번호 설정
      end = cookieData.length;
    console.log("end위치  : " + end);
    cookieValue = cookieData.substring(start, end);
  }
  return unescape(cookieValue);
}

완성된 페이지

개발 is in 페이지

profile
개발자 꿈나무

0개의 댓글