Ejemplo n.º 1
0
        public async Task <IActionResult> Register(RegisterViewModel rvm)
        {
            if (!ModelState.IsValid)
            {
                return(View(rvm));
            }

            var User = new User
            {
                UserName = rvm.Email,
                Name     = rvm.Name,
                Surname  = rvm.Surname,
                Age      = rvm.Age,
                Email    = rvm.Email,
            };
            var result = await _userManager.CreateAsync(User, rvm.Password);

            AuthEvent authEvent = new AuthEvent();

            authEvent.GreetingOnEmail += EmailGreeting;//Добавляем приветствие

            if (result.Succeeded)
            {
                authEvent.Greeting(rvm.Email, rvm.Name);
                await _signInManager.SignInAsync(User, false);

                return(RedirectToAction("Index", "Home"));
            }
            return(View());
        }
Ejemplo n.º 2
0
        public async Task <AuthEvent> AddEvent(AuthEventType eventType, string subject, ApplicationUser user = null)
        {
            var maxEventCount = Int32.Parse(_configuration["Cierge:Events:MaxStored"] ?? "50");

            if (maxEventCount <= 0)
            {
                return(null);
            }

            var authEvent = new AuthEvent()
            {
                UserId          = user?.Id,
                ClientIPAddress = _httpContext.HttpContext.Connection.RemoteIpAddress.ToString(),
                ClientUserAgent = _httpContext.HttpContext.Request.Headers["User-Agent"].ToString(),
                OccurrenceTime  = DateTimeOffset.UtcNow,
                Type            = eventType,
                Subject         = subject
            };

            // Remove oldest event if surpassing number of max events to store
            var eventCount = _dbContext.AuthEvents.Count(e => e.UserId == user.Id);

            if (eventCount == maxEventCount)
            {
                var oldestEvent = _dbContext.AuthEvents
                                  .Aggregate((agg, next) => next.OccurrenceTime < agg.OccurrenceTime ? next : agg);
                _dbContext.Remove(oldestEvent);
            }

            await _dbContext.AuthEvents.AddAsync(authEvent);

            await _dbContext.SaveChangesAsync();

            return(authEvent);
        }
Ejemplo n.º 3
0
        private async Task <TokenResponse> RequestToken(string tokenRequestBody)
        {
            // sends the request
            HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create(tokenEndpoint);

            tokenRequest.Method = "POST";
            // tokenRequest.Headers.Add(HttpRequestHeader.Authorization, string.Format("Basic {0}", clientSecret));
            tokenRequest.ContentType = "application/x-www-form-urlencoded";
            //tokenRequest.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            byte[] _byteVersion = Encoding.ASCII.GetBytes(tokenRequestBody);
            tokenRequest.ContentLength = _byteVersion.Length;
            Stream stream = tokenRequest.GetRequestStream();
            await stream.WriteAsync(_byteVersion, 0, _byteVersion.Length);

            stream.Close();

            try
            {
                // gets the response
                WebResponse tokenResponse = await tokenRequest.GetResponseAsync();

                using (StreamReader reader = new StreamReader(tokenResponse.GetResponseStream()))
                {
                    // reads response body
                    string responseText = await reader.ReadToEndAsync();

                    var token = JsonConvert.DeserializeObject <TokenResponse>(responseText);
                    currentToken = token;

                    AuthEvent.Invoke(this, true);

                    SaveToken();

                    return(token);
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    var response = ex.Response as HttpWebResponse;
                    if (response != null)
                    {
                        Console.WriteLine("HTTP: " + response.StatusCode);
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            // reads response body
                            string responseText = await reader.ReadToEndAsync();

                            Console.WriteLine(responseText);
                        }
                    }
                }
            }

            AuthEvent.Invoke(this, false);

            return(null);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Processes the message
        /// </summary>
        /// <param name="connectionBase">The connection base</param>
        /// <param name="message">The playerio message</param>
        /// <param name="handled">Whether the message was already handled</param>
        public void Process(ConnectionBase connectionBase, Message message, bool handled)
        {
            string userId = message.GetString(0);
            string auth   = message.GetString(1);

            AuthEvent authEvent = new AuthEvent(userId, auth);

            connectionBase.RaiseServerEvent <AuthEvent>(authEvent);
        }
Ejemplo n.º 5
0
        public ServerPlayer Authenticate(AuthEvent ev)
        {
            Log.Debug($"Authenticating account {ev.Login}");
            Account acc;

            if (!AccountsByLogin.TryGetValue(ev.Login, out acc))
            {
                acc          = new Account();
                acc.ID       = Guid.NewGuid();
                acc.Login    = ev.Login;
                acc.Password = ev.Password;
                AddAccount(acc);
                Log.Info($"Registered new account {acc.Login}");
                acc.Player = new ServerPlayer(_server);
                acc.Player.ConnectionID  = ev.ConnectionID;
                Players[ev.ConnectionID] = acc.Player;
                acc.Player.Send(new AuthResultEvent()
                {
                    PlayerID = acc.Player.UserID,
                    Success  = true
                });
                if (ev.SpecVersion < StrategyGame.Specs.Version)
                {
                    acc.Player.Send(new GameSpecResponse(_game));
                }
                return(acc.Player);
            }
            else
            {
                if (acc.Password != ev.Password)
                {
                    Log.Error($"Account {ev.Login} entered bad password");
                    acc.Player.Send(new AuthResultEvent()
                    {
                        PlayerID = acc.Player.UserID,
                        Success  = false
                    });
                    return(null);
                }
                acc.Player.ConnectionID  = ev.ConnectionID;
                Players[ev.ConnectionID] = acc.Player;
                Log.Info($"Account {ev.Login} connected");
                if (ev.SpecVersion < StrategyGame.Specs.Version)
                {
                    acc.Player.Send(new GameSpecResponse(_game));
                }
                acc.Player.Send(new AuthResultEvent()
                {
                    PlayerID = acc.Player.UserID,
                    Success  = true
                });
                return(acc.Player);
            }
        }
Ejemplo n.º 6
0
        public async Task StartAuth()
        {
            var savedToken = Properties.Settings.Default.AuthToken;

            if (savedToken != null)
            {
                // Attempt to use auth code
                currentToken = savedToken;

                var accountManager = App.provider.GetService(typeof(AccountManager)) as AccountManager;

                var result = false;

                try
                {
                    result = await accountManager.GetAccount(true) != null;
                }
                catch (UnauthorizedAccessException _)
                {
                    // Do nothing
                }

                if (result)
                {
                    // Token success
                    AuthEvent.Invoke(this, true);
                    return;
                }
                else
                {
                    AuthEvent.Invoke(this, false);
                }

                try
                {
                    result = await RefreshToken() != null && await accountManager.GetAccount(true) != null;
                }
                catch (UnauthorizedAccessException _)
                {
                    // Do nothing
                }

                if (result)
                {
                    // Refresh succeeded and token success
                    AuthEvent.Invoke(this, true);
                    return;
                }

                currentToken = null;
            }
        }
Ejemplo n.º 7
0
    public void Authenticate()
    {
        Log.Debug("Sending Auth");
        var login = Login.text;
        var pass  = Password.text;
        var ev    = new AuthEvent()
        {
            Login    = login,
            Password = pass
        };

        MainBehaviour.Networking.Send <AuthEvent>(ev);
    }
Ejemplo n.º 8
0
        public void TestRawSerialization()
        {
            Serialization.LoadSerializers();
            var authEvent = new AuthEvent()
            {
                Login    = "******",
                Password = "******"
            };
            var bytes  = Serialization.FromEventRaw(authEvent);
            var event2 = (AuthEvent)Serialization.ToEventRaw(bytes);

            Assert.AreEqual(authEvent.Login, event2.Login);
            Assert.AreEqual(authEvent.Password, event2.Password);
        }
Ejemplo n.º 9
0
    public static void authenticationAsGuest() // █ аунтификация из под готся
    {
        MAIN main = MAIN.getMain;

        main.sessionID = PlayerPrefs.GetString(AuthType.GUEST.ToString(), "");
        main.authType  = AuthType.GUEST;
        if (main.sessionID != "")
        {
            main.tryRestoreSessionID = true;
            AuthEvent.OnSidAuth(main.sessionID);
        }
        else
        {
            main.tryRestoreSessionID = false;
            AuthEvent.OnGuestAuth();
        }
    }
Ejemplo n.º 10
0
        public override Boolean ValidateConfigFields(Dictionary <String, Object> config, AuthEvent Log)
        {
            AuthEvent iLog = new AuthEvent(delegate(Object sender, AuthEventType type, string text)
            {
                if (Log != null)
                {
                    Log(sender, type, text);
                }
            });

            if (!CheckInputConfig(config, iLog))
            {
                return(false);
            }

            //Verifica as informações próprias deste plugin
            return(true);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Log in through armorgames
        /// </summary>
        /// <param name="config">The config</param>
        /// <returns>The established client if valid; otherwise null</returns>
        public Client LogIn(Config config)
        {
            string loginCookie = GetArmorgamesLoginCookie();

            if (loginCookie == null)
            {
                return(null);
            }

            ArmorgamesFlashvars flashVars = GetFlashvars(loginCookie);

            if (flashVars == null)
            {
                return(null);
            }

            FluidClient guestClient = new FluidClient(new GuestAuth());

            if (!guestClient.LogIn())
            {
                return(null);
            }

            SecureConnection secureConnection = guestClient.GetSecureConnection();

            if (secureConnection == null)
            {
                return(null);
            }

            secureConnection.SendAuth(flashVars.UserId, flashVars.AuthToken);
            AuthEvent armorGamesAuth = secureConnection.WaitForServerEvent <AuthEvent>();

            if (armorGamesAuth.IsAuthenitcated())
            {
                return(PlayerIO.Connect(config.GameID, "secure", armorGamesAuth.UserID, armorGamesAuth.AuthToken, "armorgames"));
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 12
0
 // когда получили данные об игроке от ВК
 public void onProfileComplete(string msg)
 {
     if (msg != null && (msg != "" || msg != "false"))
     {
         //MAIN main =
         //main.setMessage("onProfileComplete: success: " + msg);
         user = JsonUtility.FromJson <AuthUserInfo>(msg);
         //main.sessionID = PlayerPrefs.GetString(AuthType.VK.ToString(), "");
         if (main.sessionID == "")
         {
             AuthEvent.OnAuthVk(user, AuthTypes.Vk);
         }
         else
         {
             AuthEvent.onQuickAuthVk(user, AuthTypes.Vk);
         }
     }
     else
     {
         main.setMessage("onProfileComplete: error: " + msg);
     }
 }
Ejemplo n.º 13
0
 public AuthEventArgs(AuthEvent authEvent)
 {
     AuthResponse = authEvent;
 }
Ejemplo n.º 14
0
 public void On_ClientAuth(AuthEvent ae)
 {
     SetHookWorking("On_ClientAuth");
     Broadcast(ae.Name + " authenticated on the server with IP " + ae.IP + " and ID " + ae.GameID);
 }
Ejemplo n.º 15
0
 public abstract Boolean ValidateConfigFields(Dictionary <String, Object> config, AuthEvent log);
Ejemplo n.º 16
0
 public void onEvent(AuthEvent evt)
 {
     this.token     = evt.Token;
     this.expiresIn = evt.ExpiresIn;
 }
Ejemplo n.º 17
0
 public void OnClientAuth(AuthEvent ae)
 {
     this.Invoke("On_ClientAuth", ae);
 }
Ejemplo n.º 18
0
        protected Boolean CheckInputConfig(Dictionary <String, Object> config, AuthEvent Log)
        {
            if (config == null)
            {
                Log(this, AuthEventType.Error, "Config is null");
                return(false);
            }

            foreach (AuthConfigFields conf in this.GetConfigFields())
            {
                if (conf.Required)
                {
                    if (!config.ContainsKey(conf.Key) || (config[conf.Key] == null) || (config[conf.Key].ToString().Trim() == ""))
                    {
                        Log(this, AuthEventType.Error, conf.Name + " not set");
                        return(false);
                    }
                    else
                    {
                        //Realiza os testes de try
                        switch (conf.Type)
                        {
                        case AuthConfigTypes.Boolean:
                            try
                            {
                                Boolean tst = Boolean.Parse(config[conf.Key].ToString());
                            }
                            catch (Exception ex)
                            {
                                Log(this, AuthEventType.Error, "Error on try value of '" + conf.Name + "': " + ex.Message);
                                return(false);
                            }
                            break;

                        case AuthConfigTypes.Uri:
                            try
                            {
                                Uri tst = new Uri(config[conf.Key].ToString());
                            }
                            catch (Exception ex)
                            {
                                Log(this, AuthEventType.Error, "Error on try value of '" + conf.Name + "': " + ex.Message);
                                return(false);
                            }
                            break;

                        case AuthConfigTypes.Int32:
                            try
                            {
                                Int32 tst = Int32.Parse(config[conf.Key].ToString());
                            }
                            catch (Exception ex)
                            {
                                Log(this, AuthEventType.Error, "Error on try value of '" + conf.Name + "': " + ex.Message);
                                return(false);
                            }
                            break;

                        case AuthConfigTypes.Int64:
                            try
                            {
                                Int64 tst = Int64.Parse(config[conf.Key].ToString());
                            }
                            catch (Exception ex)
                            {
                                Log(this, AuthEventType.Error, "Error on try value of '" + conf.Name + "': " + ex.Message);
                                return(false);
                            }
                            break;

                        case AuthConfigTypes.DateTime:
                            try
                            {
                                DateTime tst = DateTime.Parse(config[conf.Key].ToString());
                            }
                            catch (Exception ex)
                            {
                                Log(this, AuthEventType.Error, "Error on try value of '" + conf.Name + "': " + ex.Message);
                                return(false);
                            }
                            break;

                        case AuthConfigTypes.String:
                        case AuthConfigTypes.Password:
                            //Nada
                            break;
                        }
                    }
                }
            }

            return(true);
        }