Skip to content

Instantly share code, notes, and snippets.

@daeun1012
Last active December 7, 2017 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daeun1012/679602cd73bc3b0ad445ced94287fc26 to your computer and use it in GitHub Desktop.
Save daeun1012/679602cd73bc3b0ad445ced94287fc26 to your computer and use it in GitHub Desktop.
const val MIN_PASSWORD_LENGTH = 8 // 최소 비밀번호 길이
const val TAG = "LoginViewModel"
class LoginViewModel(lifecycleOwner: LifecycleOwner, private val loginActions: LoginActions) : ViewModel(), LifecycleObserver, LoginFragment.LoginFragmentActions {
val loginData = MutableLiveData<LoginViewData>() // view data
private val fbAuthListener: FirebaseAuth.AuthStateListener //로그인 상태 리스너
private val fbAuth = FirebaseAuth.getInstance() // firebase auth 객체
init {
// login view data 초기화
loginData.value = LoginViewData("", "", "", null, false, false, null)
// auth listener 초기화
fbAuthListener = FirebaseAuth.AuthStateListener { firebaseAuth ->
val user = firebaseAuth.currentUser
if (user != null) {
// User is signed in
LogUtil.d(TAG, "onAuthStateChanged:signed_in:" + user.uid)
} else {
// User is signed out
LogUtil.d(TAG, "onAuthStateChanged:signed_out")
}
}
// lifecycle observer 등록
lifecycleOwner.lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun registerAuthListener() {
// auth 상태 정보 listener 등록
fbAuth.addAuthStateListener(fbAuthListener)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun unregisterAuthListener() {
// auth 상태 정보 listener
fbAuth.removeAuthStateListener(fbAuthListener)
}
/**
* 이메일 확인
*/
override fun onEmailChanged(email: String) {
if (Validator.isEmailValid(email)) {
loginData.value!!.email = email
} else {
loginData.value!!.email = ""
}
}
/**
* 패스워드 확인
*/
override fun onPasswordChanged(password: String) {
if (password.length >= MIN_PASSWORD_LENGTH) {
loginData.value!!.password = password
} else {
loginData.value!!.password = ""
}
}
/**
* 이메일 로그인 시도
*/
override fun onClickEmailLogin() {
// 입력 정보 확인
val error = checkError()
if (error != null) {
loginData.value = loginData.value!!.copy(error = error, isSuccessLogin = false)
return
}
// 에러 초기화
loginData.value!!.error = null
// loading 시작 : show progressbar
loginData.value = loginData.value!!.copy(isLoading = true)
// firebase auth 이메일 로그인
fbAuth.signInWithEmailAndPassword(loginData.value!!.email, loginData.value!!.password)
.addOnCompleteListener({ task ->
// login response 처리
if (task.isSuccessful) {
loginActions.successLogin()
} else {
checkExistEmail()
}
})
}
/**
* 기존 가입 여부 확인
*/
private fun checkExistEmail() {
fbAuth.fetchProvidersForEmail(loginData.value!!.email)
.addOnCompleteListener({ task ->
// 이메일 존재
if (task.isSuccessful) {
///////// getProviders().size() will return size 1. if email ID is available.
loginData.value = loginData.value!!.copy(isAlreadyExist = task.result.providers!!.size == 1)
} else {
loginData.value = loginData.value!!.copy(isLoading = false,
isSuccessLogin = false,
error = ERROR.SERVER_ERROR
.apply {
errorMsg = task.exception?.message!!
})
loginData.value!!.error = null
}
})
}
/**
* 이메일로 가입하기
*/
fun signUpEmail() {
fbAuth.createUserWithEmailAndPassword(loginData.value!!.email, loginData.value!!.password)
.addOnCompleteListener({ task ->
//회원가입 완료
if (task.isSuccessful) {
loginActions.successLogin()
} else {
loginData.value = loginData.value!!.copy(isLoading = false,
isSuccessLogin = false,
error = ERROR.SERVER_ERROR
.apply {
errorMsg = task.exception?.message!!
})
loginData.value!!.error = null
}
})
}
/**
* 입력값 에러 확인
*/
private fun checkError(): ERROR? {
when {
TextUtils.isEmpty(loginData.value!!.email) -> return ERROR.INVALID_EMAIL
TextUtils.isEmpty(loginData.value!!.password) -> return ERROR.INVALID_PASSWORD
}
return null
}
override fun onClickFacebookLogin() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
class ViewModelFactory(private val lifecycleOwner: LifecycleOwner, private val loginActions: LoginActions) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return LoginViewModel(lifecycleOwner, loginActions) as T
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment