Flutter
...
Authentication
플러터에서 Parse 사용자 로그인/로그아웃 구현 방법
15 분
플러터에서 파스 서버를 사용한 사용자 로그인 및 로그아웃 소개 지난 가이드에서 파스를 사용한 플러터의 사용자 등록을 구현한 후, 동일한 parseuser 클래스를 사용하여 사용자를 로그인하고 로그아웃하는 방법을 배우게 됩니다 가입 후, 로그인 작업이 자동으로 수행되며 새로운 사용자 세션이 생성됩니다 로그아웃 작업은 로그인한 사용자의 활성 세션 객체를 삭제합니다 이 가이드에서는 parse server를 위한 flutter 플러그인 을 사용하여 플러터 앱에서 parseuser 클래스를 사용하여 로그인/로그아웃을 수행하는 방법을 배우게 됩니다 목표 플러터 앱을 위한 사용자 로그인/로그아웃 기능을 파스를 사용하여 구축하는 것입니다 전제 조건 이 튜토리얼을 완료하려면 다음이 필요합니다 flutter 버전 2 2 x 이상 https //flutter dev/docs/get started/install android studio https //developer android com/studio 또는 vs code 설치 (과 플러그인 dart 및 flutter) back4app에서 생성된 앱 참고 새 parse 앱 튜토리얼 을 따라 back4app에서 parse 앱을 만드는 방법을 배우세요 back4app에 연결된 flutter 앱 참고 flutter 프로젝트에 parse sdk 설치 하여 back4app에 연결된 flutter 프로젝트를 만드세요 이전 가이드를 완료하여 parseuser parseuser 클래스에 대한 더 나은 이해를 얻으세요 android 또는 ios에서 실행되는 장치(또는 가상 장치) 로그인/로그아웃 앱 이해하기 로그인/로그아웃 프로세스를 더 잘 이해하기 위해, 우리는 사용자가 귀하의 계정에 로그인하고 로그아웃할 수 있는 앱을 만들 것입니다 이 가이드의 주요 초점이 flutter와 parse를 사용하는 것이기 때문에 flutter 애플리케이션 코드는 설명하지 않겠습니다 다음 단계를 따르면 back4app 데이터베이스에서 로그인 및 로그아웃 앱을 구축할 수 있습니다 시작해 봅시다! 다음 단계에서는 로그인/로그아웃 앱을 만들 수 있습니다 1 로그인/로그아웃 앱 템플릿 만들기 이전 가이드에서 flutter 프로젝트를 엽니다 parse server용 flutter 플러그인 main dart main dart 파일을 열고 모든 코드를 정리한 후 다음으로 교체합니다 1 import 'package\ flutter/material dart'; 2 import 'package\ parse server sdk flutter/parse server sdk dart'; 3 4 void main() async { 5 widgetsflutterbinding ensureinitialized(); 6 7 final keyapplicationid = 'your app id here'; 8 final keyclientkey = 'your client key here'; 9 final keyparseserverurl = 'https //parseapi back4app com'; 10 11 await parse() initialize(keyapplicationid, keyparseserverurl, 12 clientkey keyclientkey, debug true); 13 14 runapp(myapp()); 15 } 16 17 class myapp extends statelesswidget { 18 @override 19 widget build(buildcontext context) { 20 return materialapp( 21 title 'flutter login/logout', 22 theme themedata( 23 primaryswatch colors blue, 24 visualdensity visualdensity adaptiveplatformdensity, 25 ), 26 home homepage(), 27 ); 28 } 29 } 30 31 class homepage extends statefulwidget { 32 @override 33 homepagestate createstate() => homepagestate(); 34 } 35 36 class homepagestate extends state\<homepage> { 37 final controllerusername = texteditingcontroller(); 38 final controllerpassword = texteditingcontroller(); 39 bool isloggedin = false; 40 41 @override 42 widget build(buildcontext context) { 43 return scaffold( 44 appbar appbar( 45 title const text('flutter login/logout'), 46 ), 47 body center( 48 child singlechildscrollview( 49 padding const edgeinsets all(8), 50 child column( 51 crossaxisalignment crossaxisalignment stretch, 52 children \[ 53 container( 54 height 200, 55 child image network( 56 'http //blog back4app com/wp content/uploads/2017/11/logo b4a 1 768x175 1 png'), 57 ), 58 center( 59 child const text('flutter on back4app', 60 style 61 textstyle(fontsize 18, fontweight fontweight bold)), 62 ), 63 sizedbox( 64 height 16, 65 ), 66 center( 67 child const text('user login/logout', 68 style textstyle(fontsize 16)), 69 ), 70 sizedbox( 71 height 16, 72 ), 73 textfield( 74 controller controllerusername, 75 enabled !isloggedin, 76 keyboardtype textinputtype text, 77 textcapitalization textcapitalization none, 78 autocorrect false, 79 decoration inputdecoration( 80 border outlineinputborder( 81 borderside borderside(color colors black)), 82 labeltext 'username'), 83 ), 84 sizedbox( 85 height 8, 86 ), 87 textfield( 88 controller controllerpassword, 89 enabled !isloggedin, 90 obscuretext true, 91 keyboardtype textinputtype text, 92 textcapitalization textcapitalization none, 93 autocorrect false, 94 decoration inputdecoration( 95 border outlineinputborder( 96 borderside borderside(color colors black)), 97 labeltext 'password'), 98 ), 99 sizedbox( 100 height 16, 101 ), 102 container( 103 height 50, 104 child textbutton( 105 child const text('login'), 106 onpressed isloggedin ? null () => douserlogin(), 107 ), 108 ), 109 sizedbox( 110 height 16, 111 ), 112 container( 113 height 50, 114 child textbutton( 115 child const text('logout'), 116 onpressed !isloggedin ? null () => douserlogout(), 117 ), 118 ) 119 ], 120 ), 121 ), 122 )); 123 } 124 125 void showsuccess(string message) { 126 showdialog( 127 context context, 128 builder (buildcontext context) { 129 return alertdialog( 130 title const text("success!"), 131 content text(message), 132 actions \<widget>\[ 133 new textbutton( 134 child const text("ok"), 135 onpressed () { 136 navigator of(context) pop(); 137 }, 138 ), 139 ], 140 ); 141 }, 142 ); 143 } 144 145 void showerror(string errormessage) { 146 showdialog( 147 context context, 148 builder (buildcontext context) { 149 return alertdialog( 150 title const text("error!"), 151 content text(errormessage), 152 actions \<widget>\[ 153 new textbutton( 154 child const text("ok"), 155 onpressed () { 156 navigator of(context) pop(); 157 }, 158 ), 159 ], 160 ); 161 }, 162 ); 163 } 164 165 void douserlogin() async { 166 167 } 168 169 void douserlogout() async { 170 171 } 172 } 173 함수 debug debug 의 parse() initialize parse() initialize 매개변수가 true true , parse api 호출을 콘솔에 표시할 수 있습니다 이 설정은 코드 디버깅에 도움이 될 수 있습니다 릴리스 버전에서는 디버그를 비활성화하는 것이 좋습니다 2 템플릿을 back4app 프로젝트에 연결하기 애플리케이션 id와 클라이언트 키 자격 증명을 찾으려면 back4app 웹사이트 https //www back4app com/ 로 이동하여 앱 대시보드에서 확인하세요 코드를 main dart main dart 에서 back4app의 애플리케이션 id와 클라이언트 키 값으로 업데이트하세요 keyapplicationid = 앱 id keyclientkey = 클라이언트 키 프로젝트를 실행하면 앱이 이미지와 같이 로드됩니다 3 사용자 로그인 코드 사용자 로그인 기능은 세션 세션 객체를 생성하여 로그인한 사용자 로그인한 사용자 를 가리키고 유효한 사용자 세션을 로컬 스토리지에 저장합니다 향후 currentuser currentuser 와 같은 메서드 호출은 성공적으로 사용자 사용자 데이터를 검색하고 sessiontoken sessiontoken 을 세션 세션 객체에 대해 생성된 대시보드 대시보드 에서 가져옵니다 파일 main dart main dart 에서 함수 douserlogin douserlogin 을 검색합니다 douserlogin douserlogin 내부의 코드를 다음으로 교체합니다 1 final username = controllerusername text trim(); 2 final password = controllerpassword text trim(); 3 4 final user = parseuser(username, password, null); 5 6 var response = await user login(); 7 8 if (response success) { 9 showsuccess("user was successfully login!"); 10 setstate(() { 11 isloggedin = true; 12 }); 13 } else { 14 showerror(response error! message); 15 } 이 기능을 구축하려면 다음 단계를 따르세요 새로운 parseuser parseuser 클래스 인스턴스를 다음 명령으로 생성합니다 parseuser(username, password, null); parseuser(username, password, null); 앱에 입력된 데이터를 사용하여 이메일 필드는 필요하지 않으며 null로 입력해야 합니다 다음의 login login 함수를 호출합니다 이 함수는 session session 을(를) parse 대시보드의 데이터베이스에 생성하고 토큰을 로컬 저장소에 저장합니다 사용자 로그인이 성공했는지 확인합니다 성공하지 않았다면 오류 설명 메시지를 표시합니다 완전한 함수는 다음과 같아야 합니다 1 void douserlogin() async { 2 final username = controllerusername text trim(); 3 final password = controllerpassword text trim(); 4 5 final user = parseuser(username, password, null); 6 7 var response = await user login(); 8 9 if (response success) { 10 showsuccess("user was successfully login!"); 11 setstate(() { 12 isloggedin = true; 13 }); 14 } else { 15 showerror(response error! message); 16 } 17 } 테스트하려면 android studio/vscode에서 run run 버튼을 클릭하세요 원하는 사용자 자격 증명을 제공한 후, 로그인 버튼을 눌렀을 때 모든 것이 성공적이라면 이 메시지를 볼 수 있습니다 잘못된 자격 증명으로 사용자를 로그인하려고 하면 오류 처리를 테스트할 수 있습니다 비밀번호 없이 로그인하려고 하면 또 다른 오류가 발생합니다 4 사용자 로그아웃 코드 사용자 로그아웃 기능은 세션 세션 객체를 삭제합니다 이 객체는 로그인 기능에서 생성되었습니다 이 세션은 장치에서 지워지고 parse 서버의 모든 연결된 서비스에서 로그아웃됩니다 함수 douserlogout douserlogout 를 파일 main dart main dart douserlogout douserlogout 의 코드를 다음으로 교체하세요 1 final user = await parseuser currentuser() as parseuser; 2 var response = await user logout(); 3 4 if (response success) { 5 showsuccess("user was successfully logout!"); 6 setstate(() { 7 isloggedin = false; 8 }); 9 } else { 10 showerror(response error! message); 11 } 이 함수를 만들기 위해 다음 단계를 따르세요 함수를 사용하여 현재 로그인된 사용자를 가져옵니다 parseuser currentuser() parseuser currentuser() 다음에 대해 logout logout 함수를 호출합니다 parseuser parseuser 객체는 데이터베이스에서 session session 을 삭제하고 로컬 저장소의 토큰을 정리합니다 사용자 로그아웃이 성공했는지 확인합니다 성공하지 않았다면 오류 설명 메시지를 표시합니다 전체 코드는 다음과 같아야 합니다 1 void douserlogout() async { 2 final user = await parseuser currentuser() as parseuser; 3 var response = await user logout(); 4 5 if (response success) { 6 showsuccess("user was successfully logout!"); 7 setstate(() { 8 isloggedin = false; 9 }); 10 } else { 11 showerror(response error! message); 12 } 13 } 테스트하려면 android studio/vscode에서 run run 버튼을 클릭하세요 원하는 사용자 자격 증명을 제공한 후, 모든 것이 성공적이었다면 로그인 버튼을 누른 후 이 메시지를 볼 수 있습니다 “로그아웃” 버튼을 클릭하세요 완료되었습니다! 이 가이드의 끝에서, back4app을 통해 parse server의 핵심 기능을 사용하여 앱의 parse 사용자에 로그인하고 로그아웃할 수 있습니다!