// public LoginAuth AddLoginAuth(LoginAuth loginAuth)
        // {
        //     _context.LoginAuths.Add(loginAuth);
        //     _context.SaveChanges();
        //     return loginAuth;
        // }
        public IActionResult Authenticate(LoginAuth loginAuth)
        {
            var _login = _context.LoginAuths.SingleOrDefault(e => e.username == loginAuth.username && e.password == loginAuth.password);

            if (_login == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }
            var tokenHandler    = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, _login.username),
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes("miname potatona banana")), SecurityAlgorithms.HmacSha256Signature)
            };
            var token    = tokenHandler.CreateToken(tokenDescriptor);
            var loginNew = new {
                id       = _login.id,
                username = _login.username,
                token    = tokenHandler.WriteToken(token)
            };

            return(Ok(loginNew));
        }
예제 #2
0
        public async Task <IActionResult> Edit(web_CusDB.tblCus model)
        {
            if (model.CodeMelli.IsCodemeli() == false)
            {
                ModelState.AddModelError("CodeMelli", "کد ملی اشتباه است");
            }

            if (ModelState.IsValid)
            {
                var db = new web_CusDB.db_Context();
                var us = db.TblCustomers.Single(a => a.Id == User._getuserId());


                us.Name      = model.Name;
                us.CodeMelli = model.CodeMelli;
                us.Addras    = model.Addras;

                us.CodeCusMainSystem = us.checkCodeCusMain().Code;
                db.SaveChanges();

                await LoginAuth._loginAsync(this.HttpContext, us);

                return(RedirectToAction("Index"));
            }
            return(View(model));
        }
        public ActionResult Auth(LoginAuth formData, string returnUrl)
        {
            var user = Database.Session.Query <User>().FirstOrDefault(u => u.Username == formData.Username);

            if (user == null)
            {
                Eogrenme.Models.User.FakeHash();
            }

            if (user == null || !user.CheckPassword(formData.Password))
            {
                ModelState.AddModelError("Username", "Username or password is incorrect");
            }

            if (!ModelState.IsValid)
            {
                return(View());
            }


            FormsAuthentication.SetAuthCookie(formData.Username, true);


            if (!String.IsNullOrWhiteSpace(returnUrl))
            {
                return(Redirect(returnUrl));
            }

            return(RedirectToRoute("Home"));
        }
예제 #4
0
        // POST api/<controller>
        public HttpResponseMessage Post([FromBody] LoginAuth auth)
        {
            if ((auth == null) || (string.IsNullOrEmpty(auth.groupid)) || (string.IsNullOrEmpty(auth.userid)))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Missing authentication information"));
            }
            else
            {
                Repository repository  = new Repository();
                var        fbGroup     = repository.FindGroupByCodeAndKey(auth.groupid, auth.apikey);
                var        mfUser      = repository.GetUserById(auth.userid);
                var        groupMember = repository.UserGroupMembership(mfUser ?? new MFUser(), fbGroup ?? new Group());

                if (groupMember == null)
                {
                    if (mfUser == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "User not found"));
                    }

                    if (fbGroup == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid credentials"));
                    }

                    repository.DefaultGroup(mfUser, fbGroup, GroupRoleEnum.member);
                    repository.SaveChanges();

                    groupMember = repository.UserGroupMembership(mfUser, fbGroup);
                    if (groupMember == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid credentials"));
                    }
                }

                if ((string.IsNullOrEmpty(groupMember.AccessToken)) ||
                    ((groupMember.AccessExpiration.HasValue == false) || (groupMember.AccessExpiration.Value < DateTime.Now.ToUniversalTime())))
                {
                    groupMember.AccessToken      = Guid.NewGuid().ToString();
                    groupMember.AccessExpiration = DateTime.Now.AddDays(1).ToUniversalTime();
                    repository.SaveChanges();
                }
                else
                {
                    groupMember.AccessExpiration = DateTime.Now.AddDays(1).ToUniversalTime();
                    repository.SaveChanges();
                }

                var result = new AuthResult
                {
                    token      = groupMember.AccessToken,
                    expiration = groupMember.AccessExpiration.Value,
                    role       = groupMember.Role,
                    name       = mfUser.Name
                };

                return(Request.CreateResponse(HttpStatusCode.OK, result));
            }
        }
예제 #5
0
//클래스 저장
    public void Save()
    {
        BinaryFormatter bf   = new BinaryFormatter();
        FileStream      file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
        LoginAuth       data = new LoginAuth();

        data = loginAuth;
        bf.Serialize(file, data);
        file.Close();
    }
예제 #6
0
 public void Load()
 {
     if (File.Exists(Application.persistentDataPath + "/ playerInfo.dat"))
     {
         BinaryFormatter bf   = new BinaryFormatter();
         FileStream      file = File.Open(Application.persistentDataPath + "/ playerInfo.dat", FileMode.Open);
         LoginAuth       data = (LoginAuth)bf.Deserialize(file);
         file.Close();
         loginAuth = data;
     }
 }
예제 #7
0
        /// <summary>
        /// Check existence user with login and password
        /// </summary>
        public bool ExistsUser(LoginAuth auth)
        {
            string login    = auth.login;
            string password = auth.password;

            var query = Query.And(
                Query <DbUserLogin> .EQ(user => user.login, login),
                Query <DbUserLogin> .EQ(user => user.password, password)
                );

            return(this.UserLogins.Count(query) > 0);
        }
예제 #8
0
        /// <summary>
        /// Get from database user with permissions
        /// </summary>
        /// <param name="auth">Authentication object</param>
        /// <returns>Founded user or null</returns>
        public DbUserLogin GetUser(LoginAuth auth)
        {
            string login    = auth.login;
            string password = auth.password;

            var query = Query.And(
                Query <DbUserLogin> .EQ(user => user.login, login),
                Query <DbUserLogin> .EQ(user => user.password, password)
                );

            return(UserLogins.FindOne(query));
        }
예제 #9
0
    public void login(string email, string user, string pass)
    {
        LoginAuth loginAuth = new LoginAuth(email, user, pass);

        if (loginAuth != null)
        {
            gameManager.loginManager.login(loginAuth);
        }
        else
        {
            Debug.LogWarning("Failed to login, loginAuth is null");
        }
    }
예제 #10
0
    /// <summary>
    /// Update weapon. If user loses a weapon or merges a weapon, they lose th weapo
    /// </summary>
    /// <param name="weapon">Weapon.</param>
//	public void saveWeapon(Weapon weapon){
//		LoginAuth loginAuth = loginManager.getLoginAuth ();
//		if (loginAuth != null){
//			saveManager.save(weapon, loginAuth);
//		} else{
//			Debug.Log ("fail to save weapon, loginAuth is null");
//		}
//	}

    /// <summary>
    /// Dungeons the complete. get new weapons for the user.
    /// </summary>
    public void getRandomWeapon(DungeonData dungeonData)
    {
        LoginAuth loginAuth = loginManager.getLoginAuth();

        if (loginAuth != null)
        {
            saveManager.getRandomWeapon(dungeonData, loginAuth);
        }
        else
        {
            Debug.Log("fail to get new weapons for user, loginAuth is null");
        }
    }
예제 #11
0
    public void createNewUser(string email, string user, string pass)
    {
        LoginAuth loginAuth = new LoginAuth(email, user, pass);

        if (loginAuth != null)
        {
            gameManager.loginManager.createUser(loginAuth);
        }
        else
        {
            Debug.LogWarning("Failed to create new user, loginAuth is null");
        }
    }
예제 #12
0
        public async Task <ActionResult <UserDto> > Authenticate([FromBody] LoginAuth userlogin)
        {
            if (userlogin == null || string.IsNullOrEmpty(userlogin.User) || string.IsNullOrEmpty(userlogin.Password))
            {
                return(BadRequest(new ApiError(400, "parameters null", Logger)));
            }

            async Task <User> Action()
            {
                return(await _repository.Authenticate(userlogin.User, userlogin.Password, _appSettings.Secret).ConfigureAwait(false));
            }

            return(await ManageError <UserDto, User>(Action).ConfigureAwait(false));
        }
예제 #13
0
        public static async Task <HttpStatusCode> UpdatePassword(string Email, string Password)
        {
            var parms = new LoginAuth
            {
                groupid  = RaceDayConfiguration.Instance.APIGroup,
                email    = Email,
                password = Password,
                apikey   = RaceDayConfiguration.Instance.APIKey,
            };

            var client = new RestClient(RaceDayConfiguration.Instance.APIUrl);
            await client.SimpleApi(COMMAND_LOGIN, "PUT", parms);

            return(client.StatusCode);
        }
예제 #14
0
        public string login(string name, string pwd)
        {
            string retVal = "";

            try
            {
                //todo:HIS系统先验证用户名和密码

                //调用接口认证
                LoginAuth service = new LoginAuth();

                //直接塞参数进入Dictionary,由框架自动组装顺序
                Dictionary <string, string> requestParam = new Dictionary <string, string>();
                requestParam.Add("USER_CODE", name);
                requestParam.Add("USER_PASS", pwd);

                //使用executeSql重载的Dictionary参数方法
                string response = service.executeSql(requestParam);
                Dictionary <string, string> responseDict = service.getResponseResultWrapperMap();
                //登录失败
                if (service.getExecuteStatus() == false)
                {
                    retVal = "";
                    //记日志
                    XnhLogger.log(this.GetType().ToString() + service.getExecuteResultPlainString());
                }
                else
                {
                    //登录成功,缓存用户信息,服务器缓存以每个用户的user_id作为区分的cookie
                    string user_id = responseDict["USER_ID"];
                    foreach (KeyValuePair <string, string> item in responseDict)
                    {
                        BufferUtil.setBuffer(user_id, item.Key, item.Value);
                    }

                    retVal = MsgConvert.Dict2Json(responseDict);
                }
            }
            catch (Exception ex)
            {
                XnhLogger.log(this.GetType().ToString() + " " + ex.StackTrace);
                retVal = "";
            }

            return(retVal);
        }
예제 #15
0
        // PUT api/Login
        //
        // Change user password for user with matching email.  Requires groupid=JYMF, email, apikey, and new password
        //
        public HttpResponseMessage Put([FromBody] LoginAuth auth)
        {
            if ((auth == null) ||
                (string.IsNullOrEmpty(auth.groupid)) ||
                (string.IsNullOrEmpty(auth.email)) ||
                (string.IsNullOrEmpty(auth.password)) ||
                (string.IsNullOrEmpty(auth.apikey)))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Missing authentication information"));
            }
            else
            {
                Repository repository  = new Repository();
                var        fbGroup     = repository.FindGroupByCodeAndKey(auth.groupid, auth.apikey);
                var        mfUser      = repository.GetUserByEmail(auth.email);
                var        groupMember = repository.UserGroupMembership(mfUser ?? new MFUser(), fbGroup ?? new Group());

                if (mfUser == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "User not found"));
                }

                if (fbGroup == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid credentials"));
                }

                if (groupMember == null)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid credentials"));
                }

                if ((string.IsNullOrEmpty(groupMember.AccessToken)) ||
                    ((groupMember.AccessExpiration.HasValue == false) || (groupMember.AccessExpiration.Value < DateTime.Now.ToUniversalTime())))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid login"));
                }

                // Update password
                //
                mfUser.Password = auth.password;
                repository.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
        }
예제 #16
0
 public ActionResult Login([Bind(Include = "Id,Email,NickName,Password")] User user)
 {
     if (ModelState.IsValid)
     {
         User userinfo = LoginAuth.Auth(user.Email, user.Password);
         if (userinfo != null)
         {
             SessionHelper.SetSession("id", userinfo.Id);
             return(RedirectToAction("Index", "Home"));
         }
         else
         {
             return(View(user));
         }
     }
     return(View("Error"));
 }
예제 #17
0
        public async Task <ActionResult <UserDto> > UpdatePassword([FromBody] LoginAuth userlogin)
        {
            async Task <User> Action()
            {
                bool isUpdate = await _repository.UpdatePassword(userlogin.User, userlogin.Password).ConfigureAwait(false);

                if (isUpdate)
                {
                    return(await _repository.Get(userlogin.User).ConfigureAwait(false));
                }
                else
                {
                    throw new Exception("Update not executed");
                }
            }

            return(await ManageError <UserDto, User>(Action).ConfigureAwait(false));
        }
예제 #18
0
        public static async Task <string> Authorize()
        {
            var auth = new LoginAuth
            {
                groupid = RaceDayConfiguration.Instance.APIGroup,
                email   = RaceDayUser.CurrentUser.Email,
                apikey  = RaceDayConfiguration.Instance.APIKey
            };

            var client      = new RestClient(RaceDayConfiguration.Instance.APIUrl);
            var loginResult = await client.PostApi <AuthResult>(COMMAND_LOGIN, auth, HttpStatusCode.OK);

            if (loginResult != null)
            {
                RaceDayUser.LoginUser(loginResult, RaceDayUser.CurrentUser.IsPersistent);
            }

            return(RaceDayUser.CurrentUser.Token);
        }
예제 #19
0
        public static void loginTest()
        {
            IService service = new LoginAuth();

            //直接塞参数进入Dictionary,由框架自动组装顺序
            Dictionary <string, string> requestParam = new Dictionary <string, string>();

            requestParam.Add("USER_CODE", "123456");
            requestParam.Add("USER_PASS", "xxxxx");

            //使用executeSql重载的Dictionary参数方法
            string response = service.executeSql("", requestParam, "&");
            Dictionary <string, string> responseDict = service.getResponseResultWrapperMap();

            //通过Dictionary直接获取值
            string USER_ID   = responseDict["USER_ID"];
            string USER_CODE = responseDict["USER_CODE"];
            //...
        }
예제 #20
0
        public DbUserLogin CreateUser(LoginAuth auth, Email email, FacebookId fbId, VkontakteId vkId)
        {
            DbUserLogin dbUser = new DbUserLogin {
                creationTime  = CommonUtils.SecondsFrom1970(),
                email         = email.value,
                gameRef       = Guid.NewGuid().ToString(),
                login         = auth.login,
                password      = auth.password,
                facebookId    = fbId.value,
                vkontakteId   = vkId.value,
                nebulaCredits = NEBULA_CREDITS_AT_START,
                steamId       = string.Empty,
                deviceId      = string.Empty
            };

            var result = UserLogins.Save(dbUser);

            return(dbUser);
        }
예제 #21
0
        public static async Task <AuthResult> Login(string emailInput, string passwordInput)
        {
            // Create the input model
            //
            var loginAuth = new LoginAuth
            {
                groupid  = RaceDayConfiguration.Instance.APIGroup,
                email    = emailInput,
                password = passwordInput,
                apikey   = RaceDayConfiguration.Instance.APIKey
            };

            // Configure the REST client
            //
            var client      = new RestClient(RaceDayConfiguration.Instance.APIUrl);
            var loginResult = await client.PostApi <AuthResult>(COMMAND_LOGIN, loginAuth, HttpStatusCode.OK);

            return(loginResult);
        }
예제 #22
0
        // GET api/Login
        //
        // Password request for member with matching emil.  Requires GroupId=JYMF, Email, and ApiKey
        //
        public HttpResponseMessage Get([FromUri] LoginAuth auth)
        {
            if ((auth == null) ||
                (string.IsNullOrEmpty(auth.groupid)) ||
                (string.IsNullOrEmpty(auth.email)) ||
                (string.IsNullOrEmpty(auth.apikey)))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Missing authentication information"));
            }

            Repository repository  = new Repository();
            var        fbGroup     = repository.FindGroupByCodeAndKey(auth.groupid, auth.apikey);
            var        mfUser      = repository.GetUserByEmail(auth.email);
            var        groupMember = repository.UserGroupMembership(mfUser ?? new MFUser(), fbGroup ?? new Group());

            if (groupMember == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "User not found"));
            }

            // Send password.  If no password, then generate one and send
            //
            if (string.IsNullOrEmpty(mfUser.Password))
            {
                mfUser.Password = Membership.GeneratePassword(8, 1);
                repository.SaveChanges();
            }

            // Send the email containing the password
            //
            var smtp    = new SmtpClient();         // Settings in config file
            var message = new MailMessage("*****@*****.**", mfUser.Email);

            message.Subject    = "Your JYMF RaceDay password";
            message.IsBodyHtml = true;
            message.Body       = File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_Data/ForgotPassword.txt")).Replace("@EMAIL@", mfUser.Email).Replace("@PASSWORD@", mfUser.Password);

            smtp.Send(message);

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
예제 #23
0
 public ActionResult LogIn(LoginAuth model)
 {
     if (ModelState.IsValid)
     {
         // поиск пользователя в бд
         User user = null;
         using (UserContext db = new UserContext())
         {
             user = db.Users.FirstOrDefault(u => u.Name == model.Name && u.Password == model.Password);
         }
         if (user != null)
         {
             FormsAuthentication.SetAuthCookie(model.Name, true);
             return(RedirectToAction("List", "Home"));
         }
         else
         {
             ModelState.AddModelError("", "Поьзователя с таким логином и паролем нет в базе");
         }
     }
     return(View(model));
 }
예제 #24
0
        public ActionResult UpdateGiaoDich(int ID, string NoiDung, string PhuPhi, int TinhTrang)
        {
            PhuPhi = (PhuPhi + "").Replace(",", "");
            var nd = LoginAuth.StaffInfo(Session);

            //1. Update tình trạng
            SqlModule.ExcuteCommand($"UPDATE BookingHotel SET Booking_Status={TinhTrang},Booking_Surcharge='{PhuPhi}' WHERE BookingHotel_ID=" + ID);
            //2. Lưu lại lịch sử
            SqlModule.ExcuteCommand($@"INSERT INTO [dbo].[BookingHotel_history]
           ([BookingHotel_ID]
           ,[Content]
           ,[Booking_Status]
           ,[CreatedBy]
           ,[Created])
           VALUES
           ({ID}
           ,N'{NoiDung}'
           ,{TinhTrang}
           ,{nd.User_ID}
           ,getdate())");
            return(JsonMax("OK"));
        }
예제 #25
0
        private OperationResponse LoginViaServer(LoginOperationRequest operation)
        {
            string      password  = StringChiper.Decrypt(operation.encryptedPassword);
            LoginAuth   loginAuth = new LoginAuth(operation.login, password);
            DbUserLogin user      = application.GetUser(loginAuth);

            string platform = GetPlatform(operation);

            LoginOperationResponse response = null;

            if (user == null)
            {
                response = new LoginOperationResponse {
                    facebookId  = operation.facebookId,
                    GameRefId   = string.Empty,
                    Login       = operation.login,
                    method      = (byte)LoginMethod.server,
                    returnCode  = (int)LoginReturnCode.UserNotFound,
                    vkontakteId = operation.vkontakteId,
                    deviceId    = string.Empty
                };
            }
            else
            {
                response = new LoginOperationResponse {
                    facebookId  = user.facebookId,
                    GameRefId   = user.gameRef,
                    Login       = user.login,
                    method      = (byte)LoginMethod.server,
                    returnCode  = (int)LoginReturnCode.Ok,
                    vkontakteId = user.vkontakteId,
                    deviceId    = string.Empty
                };
                AddUserToCollection(user, platform);
            }
            return(new OperationResponse(operation.OperationRequest.OperationCode, response));
        }
예제 #26
0
        public async Task <User> SignIn(LoginAuth login)
        {
            var user = await _userManager.FindByEmailAsync(login.Email);

            if (user == null)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }

            var result = await _signInManager
                         .CheckPasswordSignInAsync(user, login.Password, false);

            if (result.Succeeded)
            {
                //generate token
                return(new User
                {
                    DisplayName = user.DisplayName,
                    Token = _jwtGenerator.CreateToken(user),
                    Username = user.UserName,
                });
            }
            throw new RestException(HttpStatusCode.Unauthorized);
        }
예제 #27
0
        public async Task <IActionResult> Login(string mob, string code)
        {
            if (mob.IsEmpty())
            {
                return(View( ));
            }

            if (mob.IsMobile())
            {
                ViewBag.mob = mob;
                var db = new web_CusDB.db_Context();
                var us = db.TblCustomers.SingleOrDefault(a => a.Mob == mob);

                if (code.IsEmpty())
                {
                    if (this.Request.googleRecapch3Check(web_CusDB.stat.CapchSecretKey) == false)
                    {
                        ViewBag.mob = null;
                        ViewBag.err = "لطفاً تایید کنید که ربات نیستید.";
                        ModelState.AddModelError(string.Empty, "لطفاً تایید کنید که ربات نیستید.");
                        return(View());
                    }


                    if (us == null)
                    {
                        us = new web_CusDB.tblCus
                        {
                            Id                   = Guid.NewGuid(),
                            Mob                  = mob,
                            dateAdd              = DateTime.Now,
                            Addras               = "",
                            CodeMelli            = "",
                            Name                 = "",
                            CodeCusMainSystemAcc = ""
                        };


                        db.TblCustomers.Add(us);
                    }
                    if (us._DateCodeSms.GetValueOrDefault().AddMinutes(2) > DateTime.Now)
                    {
                        ViewBag.txt = "کد قبلا برای شما ارسال گردیده است";
                        return(View());
                    }

                    var dbmain = new web_db.sardweb_Context();
                    sms sms    = new sms()
                    {
                        numfrom  = dbmain.TblConf.SingleOrDefault(a => a.Key == web_db.TblConf.KeyEnum.Main_NumSms).Value,
                        password = dbmain.TblConf.SingleOrDefault(a => a.Key == web_db.TblConf.KeyEnum.Main_PassSms).Value,
                        username = dbmain.TblConf.SingleOrDefault(a => a.Key == web_db.TblConf.KeyEnum.Main_UserSms).Value,
                    };

                    us._CodeSMS     = new Random().Next(1000, 99999);
                    us._DateCodeSms = DateTime.Now;
                    db.SaveChanges();
                    sms.sendsmsAsync(mob, (dbmain.TblConf.SingleOrDefault(a => a.Key == web_db.TblConf.KeyEnum.Main_SherkatName) ?? new web_db.TblConf()).Value + @$ "
                    کد ورود به سایت: " + us._CodeSMS.ToString());

                    ViewBag.txt = "کد برای شما ارسال گردید";
                    return(View());
                }
                else
                {
                    if (us._CodeSMS.ToString() == code)
                    {
                        us.CodeCusMainSystem = web_CusDB.tblCus.checkCodeCusMain(us).Code;
                        us.dateLast          = DateTime.Now;
                        db.SaveChanges();

                        await LoginAuth._loginAsync(HttpContext, us);

                        return(RedirectToAction("index", "home"));
                    }
                    else
                    {
                        ViewBag.txt = "کد ارسالی اشتباه است";
                        return(View());
                    }
                }
            }
            else
            {
                ViewBag.txt = "شماره موبایل اشتباه است";
                return(View());
            }
        }
예제 #28
0
    IEnumerator Start()
    {
        //webViewObject = (new GameObject("WebViewObject")).AddComponent<WebViewObject>();
        webViewObject.Init(
            cb: (msg) =>
        {
            Debugging.instance.DebugLog(string.Format("CallFromJS [ {0} ]", msg));
            status.text = msg;
            status.GetComponent <Animation>().Play();
            if (STATE == LOGINSTATE.receivewaitjson)
            {
                if (msg.Contains("token"))
                {
                    try
                    {
                        Debugging.instance.DebugLog($"jsonSting : {msg}");
                        loginAuth = JsonConvert.DeserializeObject <LoginAuth>(msg);
                        STATE     = LOGINSTATE.complete;
                        webViewObject.EvaluateJS(@"window.location.replace('" + Url + "');");
                        Debugging.instance.DebugLog("location.replace");

                        StartCoroutine(SendToken(REQUEST_TYPE.Post, loginAuth.member_no));
                    }
                    catch (Exception ex)
                    {
                        Debugging.instance.DebugLog($"jsonConvert file : {ex.Message}");
                    }

                    //window.location.assign('http://www.example.com');
                }
            }
        },
            err: (msg) =>
        {
            Debugging.instance.DebugLog(string.Format("CallOnError[ {0} ]", msg));
            status.text = msg;
            status.GetComponent <Animation>().Play();
        },
            started: (msg) =>
        {
            Debugging.instance.DebugLog(string.Format("CallOnStarted[ {0} ]", msg));

            if (msg.Contains(@"member/login"))
            {
                if (!msg.Contains("response_type=jwt"))
                {
                    Debugging.instance.DebugLog("page redirect");
                    webViewObject.LoadURL($"{Url}/member/login?response_type=jwt");
                }
            }
            else if (msg.Contains(@"/member/logout"))
            {
                StartCoroutine(SendToken(REQUEST_TYPE.Delete, loginAuth.member_no));
            }
        },
            hooked: (msg) =>
        {
            Debugging.instance.DebugLog(string.Format("CallOnHooked[{0}]", msg));
        },
            ld: (msg) =>
        {
            Debugging.instance.DebugLog(string.Format("CallOnLoaded[{0}]", msg));

            if (Debugging.instance.UrlText != null)
            {
                Debugging.instance.UrlText.text = msg;
            }

            if (msg.Contains(@"response_type=jwt"))
            {
                CallInnerText();
            }
            else if (msg.Contains(@"member/login"))
            {
                var cookies = webViewObject.GetCookies(Url);
                Debugging.instance.DebugLog($"cookies :: {cookies}");
            }
            else
            {
                //outher
            }


#if UNITY_EDITOR_OSX || !UNITY_ANDROID
            // NOTE: depending on the situation, you might prefer
            // the 'iframe' approach.
            // cf. https://github.com/gree/unity-webview/issues/189
#if true
            webViewObject.EvaluateJS(@"
                  if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
                    window.Unity = {
                      call: function(msg) {
                        window.webkit.messageHandlers.unityControl.postMessage(msg);
                      }
                    }
                  } else {
                    window.Unity = {
                      call: function(msg) {
                        window.location = 'unity:' + msg;
                      }
                    }
                  }
                ");
#else
            webViewObject.EvaluateJS(@"
                  if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
                    window.Unity = {
                      call: function(msg) {
                        window.webkit.messageHandlers.unityControl.postMessage(msg);
                      }
                    }
                  } else {
                    window.Unity = {
                      call: function(msg) {
                        var iframe = document.createElement('IFRAME');
                        iframe.setAttribute('src', 'unity:' + msg);
                        document.documentElement.appendChild(iframe);
                        iframe.parentNode.removeChild(iframe);
                        iframe = null;
                      }
                    }
                  }
                ");
#endif
#endif

            //ua: "custom user agent string",
            //webViewObject.EvaluateJS(@"Unity.call('ua1 = ' + navigator.userAgent)");
        },
            enableWKWebView: true);


#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
        webViewObject.bitmapRefreshCycle = 1;
#endif
        //webViewObject.SetAlertDialogEnabled(false);
        //webViewObject.SetURLPattern("", "^https://.*youtube.com", "^https://.*google.com");

        if (Screen.width < Screen.height)
        {
            webViewObject.SetMargins(0, 0, 0, (int)(Screen.height * 0.1));
        }
        else
        {
            webViewObject.SetMargins(0, 0, 0, (int)(Screen.height - 192));
        }

        //Debug.Log($"log >>> : height : {Screen.height} , 0.1 : {(int)(Screen.height * 0.1)}  차이 {Screen.height- (int)(Screen.height * 0.1)}  ");
        //Debug.Log($"log >>> : width : {Screen.width} , 0.1 : {(int)(Screen.width * 0.1)}  차이 {Screen.width - (int)(Screen.width * 0.1)}  ");
        webViewObject.SetVisibility(true);

#if !UNITY_WEBPLAYER && !UNITY_WEBGL
        if (Url.StartsWith("http"))
        {
            webViewObject.LoadURL(Url.Replace(" ", "%20"));
        }
        else
        {
            var exts = new string[] {
                ".jpg",
                ".js",
                ".html"  // should be last
            };
            foreach (var ext in exts)
            {
                var    url    = Url.Replace(".html", ext);
                var    src    = System.IO.Path.Combine(Application.streamingAssetsPath, url);
                var    dst    = System.IO.Path.Combine(Application.persistentDataPath, url);
                byte[] result = null;
                if (src.Contains("://"))
                {  // for Android
#if UNITY_2018_4_OR_NEWER
                    // NOTE: a more complete code that utilizes UnityWebRequest can be found in https://github.com/gree/unity-webview/commit/2a07e82f760a8495aa3a77a23453f384869caba7#diff-4379160fa4c2a287f414c07eb10ee36d
                    var unityWebRequest = UnityWebRequest.Get(src);
                    yield return(unityWebRequest.SendWebRequest());

                    result = unityWebRequest.downloadHandler.data;
#else
                    var www = new WWW(src);
                    yield return(www);

                    result = www.bytes;
#endif
                }
                else
                {
                    result = System.IO.File.ReadAllBytes(src);
                }
                System.IO.File.WriteAllBytes(dst, result);
                if (ext == ".html")
                {
                    webViewObject.LoadURL("file://" + dst.Replace(" ", "%20"));
                    break;
                }
            }
        }
#else
        if (Url.StartsWith("http"))
        {
            webViewObject.LoadURL(Url.Replace(" ", "%20"));
        }
        else
        {
            webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20"));
        }
        webViewObject.EvaluateJS(
            "parent.$(function() {" +
            "   window.Unity = {" +
            "       call:function(msg) {" +
            "           parent.unityWebView.sendMessage('WebViewObject', msg)" +
            "       }" +
            "   };" +
            "});");
#endif
        yield break;
    }
예제 #29
0
        public override OperationResponse Handle(OperationRequest request, SendParameters sendParameters)
        {
            RegisterUserRequest operation = new RegisterUserRequest(peer.Protocol, request);

            if (!operation.IsValid)
            {
                return(new OperationResponse(request.OperationCode)
                {
                    ReturnCode = (short)ReturnCode.InvalidOperationParameter,
                    DebugMessage = operation.GetErrorMessage()
                });
            }
            operation.Prepare();

            if (!mLoginUtils.IsLoginLengthValid(operation.login))
            {
                RegisterUserResponse responseObject = new RegisterUserResponse {
                    login      = operation.login,
                    gameRef    = string.Empty,
                    returnCode = (int)LoginReturnCode.LoginVeryShort
                };
                return(new OperationResponse(request.OperationCode, responseObject));
            }

            string password = StringChiper.Decrypt(operation.encryptedPassword);

            if (!mLoginUtils.IsPasswordLengthValid(password))
            {
                RegisterUserResponse responseObject = new RegisterUserResponse {
                    login      = operation.login,
                    gameRef    = string.Empty,
                    returnCode = (int)LoginReturnCode.PasswordVeryShort
                };
                return(new OperationResponse(request.OperationCode, responseObject));
            }

            if (!mLoginUtils.IsLoginCharactersValid(operation.login))
            {
                RegisterUserResponse responseObject = new RegisterUserResponse {
                    login      = operation.login,
                    gameRef    = string.Empty,
                    returnCode = (int)LoginReturnCode.LoginHasInvalidCharacters
                };
                return(new OperationResponse(request.OperationCode, responseObject));
            }

            if (!mLoginUtils.IsPasswordCharactersValid(password))
            {
                RegisterUserResponse responseObject = new RegisterUserResponse {
                    login      = operation.login,
                    gameRef    = string.Empty,
                    returnCode = (int)LoginReturnCode.PasswordHasInvalidCharacters
                };
                return(new OperationResponse(request.OperationCode, responseObject));
            }

            var emailChecker = new RegexUtilities();

            if (!emailChecker.IsValidEmail(operation.email))
            {
                RegisterUserResponse responseObject = new RegisterUserResponse {
                    login      = operation.login,
                    gameRef    = string.Empty,
                    returnCode = (int)LoginReturnCode.EmailInvalid
                };
                return(new OperationResponse(request.OperationCode, responseObject));
            }



            var database = application.DbUserLogins;

            if (database.ExistsUser(new LoginId(operation.login)))
            {
                RegisterUserResponse responseObject = new RegisterUserResponse {
                    login      = operation.login,
                    gameRef    = string.Empty,
                    returnCode = (int)LoginReturnCode.UserWithSameLoginAlreadyExists
                };
                return(new OperationResponse(request.OperationCode, responseObject));
            }

            var emailUser = database.GetUser(new Email(operation.email));

            if (emailUser != null)
            {
                RegisterUserResponse responseObject = new RegisterUserResponse {
                    login      = operation.login,
                    gameRef    = string.Empty,
                    returnCode = (int)LoginReturnCode.UserWithSuchEmailAlreadyExists
                };
                return(new OperationResponse(request.OperationCode, responseObject));
            }


            LoginReturnCode code = LoginReturnCode.Ok;


            LoginAuth   loginAuth = new LoginAuth(operation.login, password);
            Email       email     = new Email(operation.email);
            FacebookId  fbId      = new FacebookId(operation.facebookId);
            VkontakteId vkId      = new VkontakteId(operation.vkontakteId);

            var dbUser = database.CreateUser(loginAuth, email, fbId, vkId);

            FullUserAuth fullAuth = new FullUserAuth(loginAuth.login, dbUser.gameRef, fbId.value, vkId.value, string.Empty);


            string platform = string.Empty;

            if (operation.platform != null)
            {
                platform = operation.platform;
            }

            (peer as LoginClientPeer).SetLogin(new LoginId(loginAuth.login));
            application.LogedInUsers.OnUserLoggedIn(fullAuth, peer as LoginClientPeer);
            application.stats.OnUserLoggedIn(fullAuth, platform);

            if (code != LoginReturnCode.Ok)
            {
                RegisterUserResponse responseObject = new RegisterUserResponse {
                    login      = operation.login,
                    gameRef    = string.Empty,
                    returnCode = (int)code
                };
                return(new OperationResponse(request.OperationCode, responseObject));
            }

            RegisterUserResponse successResponseObject = new RegisterUserResponse {
                gameRef    = dbUser.gameRef,
                login      = dbUser.login,
                returnCode = (int)code
            };

            return(new OperationResponse(request.OperationCode, successResponseObject));
        }
        static void Main(string[] args)
        {
            LoginAuth auth = new LoginAuth();

            auth.MyFunc();
        }