public HttpResponseMessage CheckLogin(LoginQuery query)
        {
            var returnObj = new ResultObject<List<string>>();
            List<string> retList = new List<string>();

            //检验验证码正确与否
            string valiad_right = HttpContext.Current.Session["code"] as string;

            if (string.Compare(query.valiad, valiad_right) == 0)
            {
                //检验用户名正确与否
                Manager manager = null;
                string result = ManageService.LoginWebSiteAnalysis(query.username, query.userpwd, out manager);
                if (result == ResponseCode.Ok)//正确
                {
                    //设置验证成功,保存用户名到session中
                    HttpContext.Current.Session["LoginAccount"] = query.username;
                    returnObj.Status = ServerStatus.Success;
                }
                else if (result == ResponseCode.Managaer.MangerNoPermission)
                {
                    returnObj.Status = ServerStatus.Unauthorized;
                }
                else
                {
                    returnObj.Status = ServerStatus.SearchFailed;
                }

            }
            else
            {
                returnObj.Status = ServerStatus.SearchFailed;
            }

            returnObj.ReturnData = retList;

            return Request.CreateResponse<ResultObject<List<string>>>(HttpStatusCode.OK, returnObj);
        }
Exemplo n.º 2
0
        public IActionResult Login([FromBody] LoginQuery user)
        {
            if (user == null)
            {
                return(BadRequest("Invalid client request"));
            }
            var secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"));
            var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
            var claims            = new List <Claim>();
            var tokeOptions       = new JwtSecurityToken(
                issuer: "http://localhost:4200",
                audience: "https://localhost:44361",
                claims: claims,
                expires: DateTime.Now.AddMinutes(5),
                signingCredentials: signinCredentials
                );
            var tokenString = "";

            LoginResult loginResult = new LoginResult();

            if (user.UserName == "superman" && user.Password == "superman")
            {
                claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(ClaimTypes.Role, "Editor"),
                    new Claim(ClaimTypes.Role, "Manager")
                };

                tokeOptions = new JwtSecurityToken(
                    issuer: "http://localhost:4200",
                    audience: "https://localhost:44361",
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(5),
                    signingCredentials: signinCredentials
                    );

                tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);

                loginResult = new LoginResult
                {
                    Success      = true,
                    ErrorMessage = null,
                    Token        = tokenString,
                    Permissions  = GetPermissionsFromClaims(claims)
                };

                return(Ok(loginResult));
            }
            if (user.UserName == "editor" && user.Password == "editor")
            {
                claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(ClaimTypes.Role, "Editor")
                };

                tokeOptions = new JwtSecurityToken(
                    issuer: "http://localhost:4200",
                    audience: "https://localhost:44361",
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(5),
                    signingCredentials: signinCredentials
                    );

                tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);

                loginResult = new LoginResult
                {
                    Success      = true,
                    ErrorMessage = null,
                    Token        = tokenString,
                    Permissions  = GetPermissionsFromClaims(claims)
                };

                return(Ok(loginResult));
            }
            if (user.UserName == "manager" && user.Password == "manager")
            {
                claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(ClaimTypes.Role, "Manager")
                };

                tokeOptions = new JwtSecurityToken(
                    issuer: "http://localhost:4200",
                    audience: "https://localhost:44361",
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(5),
                    signingCredentials: signinCredentials
                    );

                tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);

                loginResult = new LoginResult
                {
                    Success      = true,
                    ErrorMessage = null,
                    Token        = tokenString,
                    Permissions  = GetPermissionsFromClaims(claims)
                };

                return(Ok(loginResult));
            }
            if (user.UserName == "user" && user.Password == "user")
            {
                claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserName)
                };

                tokeOptions = new JwtSecurityToken(
                    issuer: "http://localhost:4200",
                    audience: "https://localhost:44361",
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(5),
                    signingCredentials: signinCredentials
                    );

                tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);

                loginResult = new LoginResult
                {
                    Success      = true,
                    ErrorMessage = null,
                    Token        = tokenString,
                    Permissions  = GetPermissionsFromClaims(claims)
                };

                return(Ok(loginResult));
            }

            loginResult = new LoginResult
            {
                Success      = false,
                ErrorMessage = "Неверный логин или пароль (server)",
                Token        = null,
                Permissions  = null
            };

            return(Ok(loginResult));
        }
Exemplo n.º 3
0
        public async Task <Login[]> GetLogins(LoginQuery query, int?limit = null)
        {
            FilterDefinition <Login> filter = Builders <Login> .Filter.Empty;

            if (query.FromTimestamp != null)
            {
                filter &= Builders <Login> .Filter.Gte(x => x.TimeStamp, query.FromTimestamp);
            }

            if (query.ToTimestamp != null)
            {
                filter &= Builders <Login> .Filter.Lte(x => x.TimeStamp, query.ToTimestamp);
            }

            if (query.FromX != null)
            {
                filter &= Builders <Login> .Filter.Gte(x => x.Player.Location.X, query.FromX);
            }

            if (query.FromY != null)
            {
                filter &= Builders <Login> .Filter.Gte(x => x.Player.Location.Y, query.FromY);
            }

            if (query.ToX != null)
            {
                filter &= Builders <Login> .Filter.Lte(x => x.Player.Location.X, query.ToX);
            }

            if (query.ToY != null)
            {
                filter &= Builders <Login> .Filter.Lte(x => x.Player.Location.Y, query.ToY);
            }

            if (query.PlayerRole != null)
            {
                filter &= Builders <Login> .Filter.Gte(x => x.Player.Role, (AccessRole)query.PlayerRole);
            }

            if (query.Type != null)
            {
                filter &= Builders <Login> .Filter.Eq(x => x.Type, (LoginType)query.Type);
            }

            if (query.Player != null)
            {
                filter &= Builders <Login> .Filter.Eq(x => x.Player.Name, query.Player);
            }

            if (query.PlayerAccount != null)
            {
                filter &= Builders <Login> .Filter.Eq(x => x.Player.AccountName, query.PlayerAccount);
            }

            var find = _loginCollection.Find(filter);

            if (limit != null)
            {
                find = find.Limit(limit);
            }

            List <Login> logins = await find.ToListAsync();

            return(logins.ToArray());
        }
Exemplo n.º 4
0
 public async Task <ActionResult <LoggedUser> > Login(LoginQuery query) =>
 await Mediator.Send(query);
Exemplo n.º 5
0
 public async Task <ActionResult <UserViewModel> > LoginAsync(LoginQuery query)
 {
     Thread.Sleep(5000);
     return(await Mediator.Send(query));
 }
Exemplo n.º 6
0
        public ActionResult Login(LoginQuery query)
        {
            try
            {
                if (Session["ValidateCode"] == null)
                {
                    return(Json(new { state = 1, msg = "验证码已过期,请重新输入" }));
                }
                if (Session["ValidateCode"].ToString().ToLower() != query.ValidCode.ToLower())  //验证码忽略大小写
                {
                    return(Json(new { state = 1, msg = "验证码错误" }));
                }

                //判断用户信息
                var item = UserManager.GetInstance().GetItemByLoginName(query.LoginName);
                if (item == null)
                {
                    return(Json(new { state = 1, msg = "此用户不存在." }));
                }
                if (query.PassWord != EncryAndDecryptHelper.Decryption(item.password))
                {
                    return(Json(new { state = 1, msg = "用户密码不对." }));
                }
                var roleList = UserForRoleManager.GetInstance().GetListRole(item.id);
                if (roleList.Count == 0)
                {
                    return(Json(new { state = 1, msg = "当前用户暂未分配角色,不能使用系统." }));
                }

                //用户全部角色集合
                string arrRoleid = "";
                roleList.ForEach(m => arrRoleid += m.roleid + ",");

                //用户可查看菜单集合
                var    menulist  = RoleForMenuManager.GetInstance().GetListMenuId(roleList);
                string arrMenuid = "";
                menulist.ForEach(m => arrMenuid += m.ToString() + ",");

                //记住用户名和密码
                if (query.Rember != null)
                {
                    //放进cookie中
                    Response.Cookies.Add(new HttpCookie("cookieLoginname", query.LoginName));
                    Response.Cookies.Add(new HttpCookie("cookiePassword", query.PassWord));
                    Response.Cookies["cookieLoginname"].Expires = DateTime.Now.AddDays(3);
                    Response.Cookies["cookiePassword"].Expires  = DateTime.Now.AddDays(3);
                }
                //验证通过将用户信息记录进session
                SessionHelper.SetSession("userinfo", item);
                SessionHelper.SetSession("userid", item.id);
                SessionHelper.SetSession("username", item.username);
                SessionHelper.SetSession("rolelist", arrRoleid);                //角色集合
                SessionHelper.SetSession("menulist", menulist);                 //菜单集合
                SessionHelper.SetSessionTimeout(20);

                //写登录日志
                LoginLogManager.GetInstance().SaveItem();
                return(Json(new { state = 0, msg = "登录成功." }));
            }
            catch (Exception e)
            {
                LogHelper.log.Error(e.Message);
                return(Json(new { state = 1, msg = e.Message }));
            }
        }
Exemplo n.º 7
0
 public async Task <IActionResult> Login([FromBody] LoginQuery query)
 {
     return(Ok(await Mediator.Send(query)));
 }
Exemplo n.º 8
0
        public IActionResult PhoneCode(LoginQuery loginQuery)
        {
            var data = _loginServices.PhoneCode(loginQuery);

            return(Success(data));
        }
Exemplo n.º 9
0
        /// <summary>
        /// This method verifies the login information sent by
        /// the client, and returns encrypted data for the client
        /// to verify as well
        /// </summary>
        public static void ProcessLogin(GPCMClient client, Dictionary <string, string> recv, GPCMConnectionUpdate OnSuccessfulLogin, GPCMStatusChanged OnStatusChanged)
        {
            uint partnerID = 0;

            // Make sure we have all the required data to process this login
            //if (!recv.ContainsKey("challenge") || !recv.ContainsKey("response"))
            //{
            //    GameSpyUtils.SendGPError(client, GPErrorCode.General, "Invalid response received from the client!");
            //    client.DisconnectByReason(DisconnectReason.InvalidLoginQuery);
            //    return;
            //}
            if (IsContainAllKeys(recv) != GPErrorCode.NoError)
            {
                GameSpyUtils.SendGPError(client, GPErrorCode.General, "Invalid response received from the client!");
                client.DisconnectByReason(DisconnectReason.InvalidLoginQuery);
                return;
            }


            // Parse the partnerid, required since it changes the challenge for Unique nick and User login
            ParseRequestToPlayerInfo(client, recv, ref partnerID);


            // Dispose connection after use
            try
            {
                // Try and fetch the user from the database

                Dictionary <string, object> queryResult;

                try
                {
                    if (client.PlayerInfo.PlayerUniqueNick.Length > 0)
                    {
                        queryResult = LoginQuery.GetUserFromUniqueNick(recv);
                    }
                    else if (client.PlayerInfo.PlayerAuthToken.Length > 0)
                    {
                        //TODO! Add the database entry
                        GameSpyUtils.SendGPError(client, GPErrorCode.General, "AuthToken is not supported yet");
                        return;
                    }
                    else
                    {
                        queryResult = LoginQuery.GetUserFromNickAndEmail(recv);
                    }
                }
                catch (Exception ex)
                {
                    LogWriter.Log.WriteException(ex);
                    GameSpyUtils.SendGPError(client, GPErrorCode.DatabaseError, "This request cannot be processed because of a database error.");
                    return;
                }

                //if no match found we disconnect the game
                if (queryResult == null)
                {
                    if (client.PlayerInfo.PlayerUniqueNick.Length > 0)
                    {
                        GameSpyUtils.SendGPError(client, GPErrorCode.LoginBadUniquenick, "The uniquenick provided is incorrect!");
                    }
                    else
                    {
                        GameSpyUtils.SendGPError(client, GPErrorCode.LoginBadUniquenick, "The information provided is incorrect!");
                    }
                    client.DisconnectByReason(DisconnectReason.InvalidUsername);
                    return;
                }

                // Check if user is banned
                string           msg;
                DisconnectReason reason;
                GPErrorCode      error = CheckUsersAccountAvailability(queryResult, out msg, out reason);
                if (error != GPErrorCode.NoError)
                {
                    GameSpyUtils.SendGPError(client, error, msg);
                    client.DisconnectByReason(reason);
                    return;
                }

                // we finally set the player variables and return challengeData
                string challengeData = SetPlayerInfo(client, queryResult, recv);
                string sendingBuffer;
                // Use the GenerateProof method to compare with the "response" value. This validates the given password
                if (recv["response"] == GenerateProof(recv["challenge"], client.ServerChallengeKey, challengeData, client.PlayerInfo.PlayerAuthToken.Length > 0 ? 0 : partnerID, client.PlayerInfo))
                {
                    // Create session key
                    client.SessionKey = Crc.ComputeChecksum(client.PlayerInfo.PlayerUniqueNick);

                    //actually we should store sesskey in database at namespace table, when we want someone's profile we just
                    //access to the sesskey to find the uniquenick for particular game
                    LoginQuery.UpdateSessionKey(recv, client.SessionKey, client.PlayerInfo);

                    // Password is correct
                    sendingBuffer = string.Format(@"\lc\2\sesskey\{0}\proof\{1}\userid\{2}\profileid\{2}\uniquenick\{3}\lt\{4}__\id\1\final\",
                                                  client.SessionKey,
                                                  GenerateProof(client.ServerChallengeKey, recv["challenge"], challengeData, client.PlayerInfo.PlayerAuthToken.Length > 0 ? 0 : partnerID, client.PlayerInfo), // Do this again, Params are reversed!
                                                  client.PlayerInfo.PlayerId,
                                                  client.PlayerInfo.PlayerUniqueNick,
                                                  // Generate LT whatever that is (some sort of random string, 22 chars long)
                                                  GameSpyLib.Common.Random.GenerateRandomString(22, GameSpyLib.Common.Random.StringType.Hex)
                                                  );
                    //Send response to client
                    client.Send(sendingBuffer);
                    // Log Incoming Connections
                    //LogWriter.Log.Write(LogLevel.Info, "{0,-8} [Login] {1} - {2} - {3}", client.ServerName, client.PlayerInfo.PlayerNick, client.PlayerInfo.PlayerId, RemoteEndPoint);
                    //string statusString = string.Format(" [Login Success!] Nick:{0} - Profileid:{1} - IP:{2}", client.PlayerInfo.PlayerNick, client.PlayerInfo.PlayerId, client.RemoteEndPoint);
                    client.StatusToLog("Login Success", client.PlayerInfo.PlayerNick, client.PlayerInfo.PlayerId, client.RemoteEndPoint, null);
                    // Update status last, and call success login
                    client.PlayerInfo.LoginStatus          = LoginStatus.Completed;
                    client.PlayerInfo.PlayerStatus         = PlayerStatus.Online;
                    client.PlayerInfo.PlayerStatusString   = "Online";
                    client.PlayerInfo.PlayerStatusLocation = "";
                    client.CompletedLoginProcess           = true;

                    OnSuccessfulLogin?.Invoke(client);
                    OnStatusChanged?.Invoke(client);
                    SendBuddiesHandler.HandleSendBuddies(client, recv);
                }
                else
                {
                    // Log Incoming Connection
                    string statusString = string.Format(@"[Login Failed!] Nick:{0} - Profileid:{1} - IP:{2}", client.PlayerInfo.PlayerNick, client.PlayerInfo.PlayerId, client.RemoteEndPoint);
                    client.ToLog(LogLevel.Info, statusString);
                    // Password is incorrect with database value.
                    client.Send(@"\error\\err\260\fatal\\errmsg\The password provided is incorrect.\id\1\final\");
                    client.DisconnectByReason(DisconnectReason.InvalidPassword);
                }
            }
            catch (Exception ex)
            {
                LogWriter.Log.Write(ex.ToString(), LogLevel.Error);
                client.DisconnectByReason(DisconnectReason.GeneralError);
                return;
            }
        }
Exemplo n.º 10
0
        public async Task <IActionResult> UserExist(LoginQuery loginQuery)
        {
            var data = await _loginServices.UserExist(loginQuery);

            return(Success(data));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Register(LoginQuery loginQuery)
        {
            var data = await _loginServices.Register(loginQuery);

            return(Success(data));
        }
Exemplo n.º 12
0
        public async Task <IActionResult> Login([FromForm] LoginQuery loginQuery)
        {
            var response = await queryBus.Send(loginQuery);

            return(Ok(response));
        }
Exemplo n.º 13
0
        public LoginQuery Map(LoginRequest request)
        {
            var result = new LoginQuery(request.Login, request.Password);

            return(result);
        }
Exemplo n.º 14
0
        public HttpResponseMessage Login([FromBody] JObject data)
        {
            JToken parameterUsername = data["Username"];
            JToken parameterPassword = data["Password"];

            try
            {
                if (string.IsNullOrEmpty(parameterUsername.ToString()))
                {
                    throw new ArgumentNullException(nameof(parameterUsername));
                }

                if (string.IsNullOrEmpty(parameterPassword.ToString()))
                {
                    throw new ArgumentNullException(nameof(parameterPassword));
                }

                LoginQuery loginQuery = new LoginQuery()
                {
                    Username = parameterUsername.ToString(),
                    Password = parameterPassword.ToString()
                };

                LoginQueryHandler loginQueryHandler = new LoginQueryHandler(loginQuery, UnityContainer);

                Guid personUid = loginQueryHandler.Handle();

                HttpCookie requestCookie = HttpContext.Current.Request.Cookies.Get(ConfigurationManager.AppSettings["SessionCookieName"]);

                if (requestCookie == null)
                {
                    CreateSessionQuery createSessionQuery = new CreateSessionQuery()
                    {
                        Session = new SessionDomainModel()
                        {
                            LoginUID   = personUid,
                            ExpireDate = DateTimeOffset.Now.AddDays(1)
                        }
                    };

                    CreateSessionQueryHandler createSessionQueryHandler = new CreateSessionQueryHandler(createSessionQuery, new UnityContainer());

                    var guid = createSessionQueryHandler.Handle().ToString();

                    HttpCookie cookie = new HttpCookie(ConfigurationManager.AppSettings["SessionCookieName"])
                    {
                        Value    = guid,
                        Domain   = HttpContext.Current.Request.Url.Host,
                        Expires  = DateTime.Now.AddDays(1),
                        HttpOnly = false,
                    };

                    var ersponse = HttpContext.Current.Response;

                    HttpContext.Current.Response.AppendCookie(cookie);

                    return(Request.CreateResponse(HttpStatusCode.OK, guid));
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Exemplo n.º 15
0
 public LoginController(LoginQuery lQuery, IConfiguration connfig)
 {
     _lQuery = lQuery;
     _config = connfig;
 }
Exemplo n.º 16
0
 public void Setup()
 {
     LoginQuery = new LoginQuery();
 }
Exemplo n.º 17
0
 void LoginQuery(Messenger messenger, string key, LoginQuery query)
 {
     _server._messenger.Send("Login", query);
 }
Exemplo n.º 18
0
        /// <summary>
        /// Creates a new instance of <see cref="GPCMClient"/>
        /// </summary>
        public GPCMServer(string serverName, DatabaseDriver driver, IPEndPoint bindTo, int maxConnections) : base(serverName, bindTo, maxConnections)
        {
            //GPCMHandler.DBQuery = new GPCMDBQuery(driver);

            DB = new DBQueryBase(driver);

            GPCMClient.OnDisconnect += ClientDisconnected;

            GPCMClient.OnSuccessfulLogin += ClientSuccessfulLogin;

            // Setup timer. Every 15 seconds should be sufficient
            if (PollTimer == null || !PollTimer.Enabled)
            {
                PollTimer          = new System.Timers.Timer(15000);
                PollTimer.Elapsed += (s, e) =>
                {
                    // Send keep alive to all connected clients
                    if (Clients.Count > 0)
                    {
                        Parallel.ForEach(Clients.Values, client => KAHandler.SendKeepAlive(client));
                    }

                    // DisconnectByReason hanging connections
                    if (Processing.Count > 0)
                    {
                        Parallel.ForEach(Processing.Values, client => CheckTimeout(client));
                    }
                };
                PollTimer.Start();
            }

            // Setup timer. Every 5 seconds should be sufficient
            if (StatusTimer == null || !StatusTimer.Enabled)
            {
                StatusTimer          = new System.Timers.Timer(5000);
                StatusTimer.Elapsed += (s, e) =>
                {
                    // Return if we are empty
                    if (PlayerStatusQueue.IsEmpty)
                    {
                        return;
                    }

                    //var transaction =DB.BeginTransaction();

                    try
                    {
                        long       timestamp = ((DateTimeOffset)DateTime.UtcNow).ToUnixTimeSeconds();
                        GPCMClient result;
                        while (PlayerStatusQueue.TryDequeue(out result))
                        {
                            // Skip if this player never finished logging in
                            if (result == null)
                            {
                                continue;
                            }

                            if (!result.CompletedLoginProcess)
                            {
                                continue;
                            }
                            LoginQuery.UpdateStatus(timestamp, result.RemoteEndPoint.Address, result.PlayerInfo.PlayerId, (uint)result.PlayerInfo.PlayerStatus);
                        }
                        //transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogWriter.Log.WriteException(ex);
                        // transaction.Rollback();
                    }
                };
                StatusTimer.Start();
            }

            // Set connection handling
            ConnectionEnforceMode = EnforceMode.DuringPrepare;

            // TODO: Change this
            //FullErrorMessage = Config.GetValue("Settings", "LoginServerFullMessage").Replace("\"", "");
            FullErrorMessage = "";

            StartAcceptAsync();
        }
Exemplo n.º 19
0
 public async Task <IActionResult> Login([FromBody] LoginQuery query)
 {
     return(await SendRequest <LoginQuery, LoginQueryResponse>(query));
 }
Exemplo n.º 20
0
 public IActionResult Post([FromBody] LoginQuery query)
 {
     return(StatusCode(201, _queryHandler.Handle(query)));
 }
Exemplo n.º 21
0
 public LoginQueryHandler(LoginQuery query, IUnityContainer unityContainer) : base(unityContainer)
 {
     _query = query;
 }
Exemplo n.º 22
0
 public async Task <ActionResult <UserDto> > LogIn(LoginQuery query)
 => await Mediator.Send(query);
Exemplo n.º 23
0
        public async Task <IActionResult> Login([FromBody] LoginQuery value)
        {
            var result = await Mediator.Send(value);

            return(Ok(result));
        }
 public async Task <IActionResult> LoginAsync([FromBody] LoginQuery query)
 => Ok(await Mediator.Send(query));
 public async Task <ActionResult <UserAuthenticationModel> > LoginAsync(LoginQuery query)
 {
     return(await mediator.Send(query));
 }
Exemplo n.º 26
0
 public Task <LoginResult> Login([FromBody] LoginQuery model)
 {
     return(_mediator.Send <LoginResult>(model));
 }
Exemplo n.º 27
0
 public async Task <ActionResult <User> > Login(LoginQuery query)
 {
     return(await Mediator.Send(query));
 }
        public async Task <ActionResult <LoginUserViewModel> > Login([FromQuery] bool?isPersistent, LoginQuery query)
        {
            try
            {
                var user = await _mediator.Send(query);
                await LoginUser(isPersistent ?? false, user);

                return(user);
            }
            catch (LoginFailedException)
            {
                return(BadRequest());
            }
        }