02. 로그인 연동 / api 설계
Server/Study 2019. 7. 1. 02:38서버의 db에 uid를 저장하고 어플 시작시 확인 후 미 로그인 시 로그인할 수 있게 만들었다.
근데 gpgs를 연동까지 해놨는데 apk빌드해서 nox에 설치해보니 아무것도 실행이 안된다..
왜이럴까
image를 convert하여 주고 받는 것도 만들긴 했는데, serialize가 안된다.
해결법을 찾아보려 했지만 안돼서 다른 방법을 찾아야 할 것 같다.
더이상 머리가 굴러가지 않아서 쉬어야겠다.
Server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | const express = require('express'); const mysql = require('mysql'); const fs = require('fs'); const app = express(); //인코딩펑션 function base64_encode(file) { var bitmap = fs.readFileSync(file); return new Buffer(bitmap).toString('base64'); } //db접속 const connectDB = (callback) => { var connection = mysql.createConnection( { host : '127.0.0.1', user : 'root', password : '', database : 'testServer', port : '3306' } ); connection.connect((err) => { if(err) { console.log(err); connection.end(); throw err; } else { console.log("DataBase에 접속하였습니다."); callback(connection); } }); }; app.use(express.json()); //json을 사용함 //getimage app.route("/api/getimage").post((req, res) => { const data = req.body; connectDB((connection) => { var sql = `select * from images where uid = '${data.uid}' and imageid = '${data.imageid}'`; console.log(sql); connection.query(sql, (err, result, fields) => { console.log("getimage query 실행됨"); if(err) { console.log(err.errorno); res.json({ cmd : 1301, errorno : err.errorno }); } else { console.log("get image 성공!"); res.json({ cmd : 200, imagebit : result.imagebit }); } }); }); }); //uploadimage app.route("/api/uploadimage").post((req, res) => { const data = req.body; connectDB((connection) => { var sql = `insert into images(uid, imagebit) values ('${data.uid}', '${data.imagebit}')`; console.log(sql); connection.query(sql, (err, result, fields) => { console.log("upload image query 실행됨"); if(err) { console.log(err.errorno); res.json({ cmd : 1401, errorno : err.errorno }); } else { console.log("upload image 성공!"); res.json({ cmd : 200 }); } }); connection.end(); }); }); //회원가입 app.route("/api/join").post((req, res) => { const data = req.body; console.log("uid in join : " + data.uid); connectDB((connection) => { var sql = `insert into users(uid, androidlogin, androidid, nickname) values ('${data.uid}', '${data.androidlogin}', '${data.androidid}', '${data.nickname}')`; console.log(sql); connection.query(sql, (err, result, fields) => { console.log("쿼리실행됨"); if(err) { //insert중 에러 console.log(err.errorno); res.json({ cmd : 1101, errorno : err.errorno }); } else { console.log("성공"); console.log(result); res.json({ cmd : 200 }) } connection.end(); }); }); }); //로그인 app.route("/api/login").post((req, res) => { const data = req.body; console.log("유저아이디 : " + data.uid); var uid = data.uid; var checkfield = "uid"; if(data.androidlogin == 1) { uid = data.androidid; checkfield = "androidid"; } connectDB((connection) => { var sql = `select * from users where ${checkfield} = '${uid}'`; console.log("쿼리문 : " + sql); connection.query(sql, (err, results, fields) => { if(err) { //db검색중 에러 console.log(err); res.json({ cmd : 1001, errorno : err.errorno }); } else { console.log(results); if(results[0] === undefined) { //없는 유저 res.json({ cmd : 1101, errorno : 9001 }); } else { console.log(results[0].nickname); res.json({ cmd : 200, nickname : results[0].nickname }); } } }); }); }); app.listen(3005, () => { console.log("서버시작, 3005번 포트"); }); | cs |
Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 | using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using UnityEngine; using UnityEngine.UI; using GooglePlayGames; using UnityEngine.SocialPlatforms; using UnityEngine.Networking; using System; using System.IO; using System.Text; using Newtonsoft.Json; public class packet { public int cmd; } public class res_join : packet { public int errorno; } public class res_login : packet { public int errorno; public string nickname; } public class res_uploadimage : packet { public int errorno; } public class res_getimage : packet { public int errorno; public string imagebit; } public class req_join : packet { public string uid; public int androidlogin; public string androidid; public string nickname; } public class req_login : packet { public string uid; public int androidlogin; public string androidid; } public class req_uploadimage : packet { public string uid; public string imagebit; } public class req_getimage : packet { public string uid; public int imageid; } public class App : MonoBehaviour { public Button btnSendImage; public Button btnGetImage; public Button btnLoginGuest; public Button btnLoginGoogle; public Text txtNickName; public Text txtNull; public GameObject welcome; public Image image; [SerializeField] public Sprite exampleImage; private string serverPath = "http://127.0.0.1:3005"; private string uid; private string androidId; // Start is called before the first frame update void Start() { this.SetBtnsEvent(); this.Init(); } private void Init() { this.uid = SystemInfo.deviceUniqueIdentifier; this.androidId = PlayGamesPlatform.Instance.localUser.id; Debug.Log(this.uid); Debug.Log(this.androidId.Length); if (this.androidId == "") { this.Login((resultLogin) => { if (resultLogin == false) { this.txtNull.gameObject.SetActive(true); this.btnLoginGoogle.gameObject.SetActive(true); this.btnLoginGuest.gameObject.SetActive(true); } else { this.txtNull.gameObject.SetActive(false); this.welcome.SetActive(true); this.btnLoginGoogle.gameObject.SetActive(false); this.btnLoginGuest.gameObject.SetActive(false); this.btnSendImage.gameObject.SetActive(true); this.btnGetImage.gameObject.SetActive(true); } }); } } private void SetBtnsEvent() { //이미지보내기 this.btnSendImage.onClick.AddListener(() => { //this.UploadImage((result) => //{ //}); }); //이미지저장 this.btnGetImage.onClick.AddListener(() => { }); //게스트로그인 this.btnLoginGuest.onClick.AddListener(() => { this.Join((resultJoin) => { if(resultJoin) { this.Login((resultLogin) => { if (resultLogin) { this.txtNull.gameObject.SetActive(false); this.welcome.SetActive(true); this.btnLoginGoogle.gameObject.SetActive(false); this.btnLoginGuest.gameObject.SetActive(false); this.btnSendImage.gameObject.SetActive(true); this.btnGetImage.gameObject.SetActive(true); } }); } }); }); //구글로그인 this.btnLoginGoogle.onClick.AddListener(() => { Social.localUser.Authenticate((bool success) => { if(success) { this.Join((resultJoin) => { this.Login((resultLogin) => { if (resultLogin) { this.txtNull.gameObject.SetActive(false); this.welcome.SetActive(true); this.btnLoginGoogle.gameObject.SetActive(false); this.btnLoginGuest.gameObject.SetActive(false); this.btnSendImage.gameObject.SetActive(true); this.btnGetImage.gameObject.SetActive(true); } }); } , true); } else { Debug.Log("구글 연결실패"); this.txtNull.text = "구글 연동에 실패했습니다."; } }); }); } private void GetImgae(Action<bool> OnCompleteGetImage) { var reqGetImage = new req_getimage(); reqGetImage.cmd = 1300; reqGetImage.uid = this.uid; reqGetImage.imageid = 1; var json = JsonConvert.SerializeObject(reqGetImage); StartCoroutine(this.Post("api/getimage", json, (result) => { var responseResult = JsonConvert.DeserializeObject<res_getimage>(result); if(responseResult.cmd == 200) { Debug.Log("get image 성공"); byte[] imageData = Convert.FromBase64String(responseResult.imagebit); var texture = new Texture2D(1, 1, TextureFormat.ARGB32, false, true); texture.hideFlags = HideFlags.HideAndDontSave; texture.filterMode = FilterMode.Point; texture.LoadImage(imageData); var rect = new Rect(0, 0, texture.width, texture.height); this.image.sprite = Sprite.Create(texture, rect, new Vector2(0.5f, 0.5f)); OnCompleteGetImage(true); } else { Debug.Log("get 실패"); Debug.Log(responseResult.errorno); OnCompleteGetImage(false); } })); } private void UploadImage(Action<bool> OnCompleteUpload) { var reqUploadImage = new req_uploadimage(); reqUploadImage.cmd = 1400; reqUploadImage.uid = this.uid; var sprite = this.exampleImage; var texture = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height); var pixels = sprite.texture.GetPixels((int)sprite.textureRect.x, (int)sprite.textureRect.y , (int)sprite.textureRect.width, (int)sprite.textureRect.height); texture.SetPixels(pixels); texture.Apply(); MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, texture); var bytes = ms.ToArray(); var data = Convert.ToBase64String(bytes); StartCoroutine(this.Post("api/uploadimage", data, (result) => { var responseResult = JsonConvert.DeserializeObject<res_uploadimage>(result); if(responseResult.cmd == 200) { Debug.Log("upload 성공!"); OnCompleteUpload(true); } else { Debug.Log("업로드실패"); Debug.Log(responseResult.errorno); OnCompleteUpload(false); } })); } private void Login(Action<bool> OnCompleteLogin, bool androidLogin = false) { var reqLogin = new req_login(); reqLogin.cmd = 1100; reqLogin.uid = this.uid; if (androidLogin) { reqLogin.androidlogin = 1; reqLogin.androidid = PlayGamesPlatform.Instance.localUser.id; } else { reqLogin.androidlogin = 0; } var json = JsonConvert.SerializeObject(reqLogin); StartCoroutine(this.Post("api/login", json, (result) => { var responseResult = JsonConvert.DeserializeObject<res_login>(result); if (responseResult.cmd == 200) { Debug.Log("로그인성공"); this.txtNickName.text = responseResult.nickname; OnCompleteLogin(true); } if (responseResult.errorno == 9001) { Debug.Log("uid가 존재하지 않습니다."); OnCompleteLogin(false); } })); } private void Join(Action<bool> OnCompleteJoin, bool androidLogin = false) { var reqJoin = new req_join(); reqJoin.cmd = 1200; reqJoin.uid = this.uid; reqJoin.nickname = "홍길동"; if (androidLogin) { reqJoin.androidlogin = 1; reqJoin.androidid = PlayGamesPlatform.Instance.localUser.id; } else { reqJoin.androidlogin = 0; reqJoin.androidid = "x"; } var json = JsonConvert.SerializeObject(reqJoin); StartCoroutine(this.Post("api/join", json, (result) => { var responseResult = JsonConvert.DeserializeObject<res_join>(result); if (responseResult.cmd == 200) { Debug.Log("회원가입성공"); OnCompleteJoin(true); } if (responseResult.errorno == 1062) { Debug.Log("중복아이디"); OnCompleteJoin(false); } })); } private IEnumerator Post(string uri, string data, Action<string> OnResponse) { var url = string.Format("{0}/{1}", this.serverPath, uri); var req = new UnityWebRequest(url, "POST"); byte[] body = Encoding.UTF8.GetBytes(data); req.uploadHandler = new UploadHandlerRaw(body); req.downloadHandler = new DownloadHandlerBuffer(); req.SetRequestHeader("Content-Type", "application/json"); yield return req.SendWebRequest(); OnResponse(req.downloadHandler.text); } } | cs |
'Server > Study' 카테고리의 다른 글
03. Node.js 서버에 연동하여 Image Upload 및 Download하기 (1) | 2019.07.01 |
---|---|
01. 로그인/회원가입 (0) | 2019.06.28 |
01. 참고사이트 (0) | 2019.06.28 |