Skip to content

Commit

Permalink
#31 회원가입, 로그인, 로그아웃, 자동 로그인 코드 작성
Browse files Browse the repository at this point in the history
  • Loading branch information
otcroz committed Jun 29, 2022
1 parent d323313 commit 19b8190
Show file tree
Hide file tree
Showing 10 changed files with 148 additions and 65 deletions.
2 changes: 1 addition & 1 deletion SHAPEUP2022/.idea/deploymentTargetDropDown.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,27 @@ class JoinCreate : Fragment(){
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding = FragmentJoinCreateBinding.inflate(inflater, container, false)

// EditText binding
val input_name = binding.inputName
val input_id = binding.newId
val new_password = binding.inputNewpassword
val check_password = binding.checkPassword

// 버튼 view 바인딩
val binding = FragmentJoinCreateBinding.inflate(inflater, container, false)
binding.nextCreate.setOnClickListener{
//회원 등록
registerUser(input_name.text.toString(), input_id.text.toString(), new_password.text.toString())

// 화면 이동
(activity as JoinActivity).replaceFragment(JoinShare())
}

binding.nextCreate.isEnabled = false
binding.nextCreate.setBackgroundColor(Color.parseColor("#d3d3d3"));

// EditText binding
val input_name = binding.inputName
val input_id = binding.newId
val new_password = binding.inputNewpassword
val check_password = binding.checkPassword


// 핸들러 적용
var textWatcher = object : TextWatcher {
Expand Down Expand Up @@ -87,30 +93,27 @@ class JoinCreate : Fragment(){



/* 회원가입 */
Log.d("mobileApp", "회원가입 버튼을 누름")


return binding.root
}

private fun registerUser(userName: String, email: String, password: String){
val call: Call<RegisterRes> = MyApplication.networkServiceAuth.register(
RegisterReq("test5","[email protected]", "55555555")
RegisterReq(userName,email, password)
)

call?.enqueue(object : Callback<RegisterRes>{
override fun onResponse(call: Call<RegisterRes>, response: Response<RegisterRes>) {
if(response.isSuccessful){
Log.d("mobileApp", "$response")
Log.d("mobileApp", "$response ${response.body()}")
}
}

override fun onFailure(call: Call<RegisterRes>, t: Throwable) {
Log.d("mobileApp", "onFailure $t")
}
})





return binding.root
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@ package com.example.shape_up_2022
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.shape_up_2022.databinding.SignInBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


class LoginActivity : AppCompatActivity() {

Expand All @@ -19,38 +23,39 @@ class LoginActivity : AppCompatActivity() {
binding.gotoSignUp.setOnClickListener{
val intent = Intent(this, JoinActivity::class.java)
startActivity(intent)
this.finish()
finish()
}

// 로그인 버튼을 눌렀을 때
binding.btnLogin.setOnClickListener{
val inputID = binding.inputId.text.toString() // 아이디에 대한 String
val inputPW = binding.inputPw.text.toString() // 비밀번호에 대한 String

// DB에서 아이디가 있는지 검색, 아이디가 있으면 아이디에 해당하는 비밀번호가 맞는지 검색
if (inputID == "" || inputPW == ""){ // ID or 패스워드를 입력하지 않았을 때
Log.d("app_test", "다시 입력하세요")
binding.reEnterIdPw.visibility = View.VISIBLE
}
else if (inputID == "1234"){ // 해당하는 아이디가 존재할 때
if(inputPW == "1234"){
Log.d("app_test", "로그인 완료")

// intent: mainActivity로 이동
val intent = Intent(
this, MainActivity::class.java)
startActivity(intent)
this.finish()
// 로그인 이력 저장, 다음에는 로그인 창 없이 바로 메인 페이지로 이동하도록 구현
} else{ // 비밀번호가 틀린 경우

// DB에 저장된 아이디 값
val call: Call<LoginRes> = MyApplication.networkServiceAuth.login(
LoginReq(inputID, inputPW)
)

call?.enqueue(object : Callback<LoginRes> {
override fun onResponse(call: Call<LoginRes>, response: Response<LoginRes>) {
if(response.isSuccessful){
Log.d("mobileApp", "$response ${response.body()}")
// 프리퍼런스에 값 저장
SaveSharedPreference.setUserEmail(baseContext, inputID)

// 메인 페이지로 이동
val intent = Intent(baseContext, MainActivity::class.java)
startActivity(intent)
finish()
}
}

override fun onFailure(call: Call<LoginRes>, t: Throwable) {
Log.d("mobileApp", "onFailure $t")
Toast.makeText(baseContext, "아이디 또는 비밀번호를 확인해주세요.", Toast.LENGTH_SHORT).show()
}
}
else{ // 아이디와 비밀번호가 틀린 경우

Log.d("app_test", "로그인 실패 ${inputID}, ${inputPW}")
// 리렌더링 후 아이디와 비밀번호가 틀렸음을 알린다. (모달 띄우는 것보다는 xml에서 알리면 좋을 듯)
}
})

}
//간편 로그인 연동 => api
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ class MyApplication: Application() {
var networkServiceAuth: NetworkService
val retrofitAuth: Retrofit
get() = Retrofit.Builder()
.baseUrl("http://ec2-13-124-250-65.ap-northeast-2.compute.amazonaws.com:5000/")
.baseUrl("http://192.168.219.105:5000")
.addConverterFactory(GsonConverterFactory.create())
.build()

// "http://ec2-13-124-250-65.ap-northeast-2.compute.amazonaws.com:5000/"
init{
networkService2 = retrofit2.create(NetworkService2::class.java)
networkServiceAuth = retrofitAuth.create(NetworkService::class.java)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@ import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import com.example.shape_up_2022.databinding.ActivityMyPageBinding
import com.google.android.youtube.player.internal.t
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.Exception

class MyPageActivity : AppCompatActivity() {
Expand Down Expand Up @@ -43,6 +48,36 @@ class MyPageActivity : AppCompatActivity() {
}
}

// 로그아웃
val email = SaveSharedPreference.getUserEmail(this)!!.toString()
Log.d("mobileApp", "${email}")
binding.logoutBtn.setOnClickListener {
val call: Call<LogoutRes> = MyApplication.networkServiceAuth.logout(
)

call?.enqueue(object : Callback<LogoutRes> {
override fun onResponse(call: Call<LogoutRes>, response: Response<LogoutRes>) {
if(response.isSuccessful){
Log.d("mobileApp", "$response ${response.body()}")

// 저장했던 preference clear
SaveSharedPreference.clearUserEmail(baseContext)

// StartActivity로 이동
val intent = Intent(baseContext, TempMainActivity::class.java)
startActivity(intent)
finish()
}
}

override fun onFailure(call: Call<LogoutRes>, t: Throwable) {
Log.d("mobileApp", "onFailure $t")
Toast.makeText(baseContext, "토스트 메세지 띄우기 입니다.", Toast.LENGTH_SHORT).show()
}
})
}

// 프로필 사진 변경
binding.changeprofile.setOnClickListener{
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
intent.type="image/*"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@ import retrofit2.Call
import retrofit2.http.*

interface NetworkService {
@POST("api/user/register")
@POST("api/users/register")
fun register(
@Body user: RegisterReq,
): Call<RegisterRes>

@POST("api/user/login")
@POST("api/users/login")
fun login(
@Body user: LoginReq,
): Call<LoginRes>

@GET("api/user/logout")
@GET("api/users/logout")
fun logout(
@Body user: LogoutReq

): Call<LogoutRes>

}
Expand All @@ -29,6 +29,6 @@ data class LoginReq(val email: String, val password: String)

data class LoginRes(val loginSuccess: String, val message: String)

data class LogoutReq(val _id: String, val email: String, val password: String)
data class LogoutReq(val email: String)

data class LogoutRes(val success: String)
data class LogoutRes(val success: String, val err: String)
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.example.shape_up_2022

import android.content.Context
import android.content.SharedPreferences
import androidx.preference.PreferenceManager

class SaveSharedPreference {
companion object{
fun getSharedPreferences(ctx: Context): SharedPreferences? {
return PreferenceManager.getDefaultSharedPreferences(ctx)
}

fun setUserEmail(ctx: Context, email: String) {
val editor = getSharedPreferences(ctx)!!.edit()
editor.putString("username", email)
editor.commit()
}

fun getUserEmail(ctx: Context?): String? {
return getSharedPreferences(ctx!!)!!.getString("username", "")
}

fun clearUserEmail(ctx: Context?) {
val editor = getSharedPreferences(ctx!!)!!.edit()
editor.clear()
editor.commit()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,25 @@ class StartActivity : AppCompatActivity() {
setContentView(binding.root) // 액티비티 화면 출력

//버튼 이벤트에 따른 인텐트 연결
// 1. 로그인
binding.btnLogin.setOnClickListener {
val intent = Intent(this, LoginActivity::class.java)
if(SaveSharedPreference.getUserEmail(this)?.length != 0){
val intent = Intent(baseContext, MainActivity::class.java)
startActivity(intent)
this.finish()
}
finish()
} else{
// 1. 로그인
binding.btnLogin.setOnClickListener {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
this.finish()
}

// 2. 회원가입
binding.btnJoin.setOnClickListener {
Log.d("app_test", "JoinActivity")
val intent = Intent(this, JoinActivity::class.java)
startActivity(intent)
this.finish()
// 2. 회원가입
binding.btnJoin.setOnClickListener {
Log.d("app_test", "JoinActivity")
val intent = Intent(this, JoinActivity::class.java)
startActivity(intent)
this.finish()
}
}

}
}
6 changes: 6 additions & 0 deletions SHAPEUP2022/app/src/main/res/layout/activity_my_page.xml
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,12 @@
android:src="@android:drawable/ic_menu_share"
android:scaleType="centerCrop" />

<Button
android:id="@+id/logout_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="로그아웃" />

</LinearLayout>

<LinearLayout
Expand Down
6 changes: 3 additions & 3 deletions SHAPEUP2022/app/src/main/res/layout/fragment_join_create.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@
android:layout_marginBottom="15dp"
android:padding="16dp"
android:background="@drawable/rectangle_base"
android:hint="새 아이디"
android:inputType="text"
android:hint="이메일"
android:inputType="textEmailAddress"
android:textSize="20dp"
android:elevation="4dp" />

Expand All @@ -53,7 +53,7 @@
android:layout_marginBottom="15dp"
android:padding="16dp"
android:background="@drawable/rectangle_base"
android:hint="비밀번호"
android:hint="비밀번호"
android:inputType="textPassword"
android:textSize="20dp"
android:elevation="4dp" />
Expand Down

0 comments on commit 19b8190

Please sign in to comment.