/// <summary>
        /// 向指定用户注册一个新的身份令牌。
        /// </summary>
        /// <param name="identity">用户的唯一标识。</param>
        /// <param name="token">产生的身份令牌。</param>
        /// <returns><c>true</c> 表示注册成功;否则返回 <c>false</c> 。</returns>
        public bool Regist(string identity, out string token)
        {
            RequestInfo info = GetRequestInfo(identity);

            if (info != null)
            {
                ILoginValidator validator = null;
                try
                {
                    validator = ServiceLocator.Current.GetInstance <ILoginValidator>(info.Client);
                }
                catch { }

                if (validator != null && validator.Validate(info.Name, info.Code))
                {
                    var data = _cache.GetOrAddXWithFunc <ConcurrentDictionary <string, DateTime> >(GetCacheKey(info), () =>
                                                                                                   Tuple.Create(new ConcurrentDictionary <string, DateTime>(Environment.ProcessorCount * 2, 16), Expiration.FromSliding(SlideDue)));

                    return(data.TryAdd(token = Guid.NewGuid().ToString("N"), DateTime.Now));
                }
            }

            token = string.Empty;
            return(false);
        }
        public void TestLogin_WithInvalidUsernameRequest_ShouldThrowValidationError()
        {
            var request = new LoginMessages.Request()
            {
                Username = "",
                Password = "******"
            };

            try
            {
                Validator.Validate(request);
                Assert.Fail("Should have thrown an exception!");
            } catch (LoginValidationException ex)
            {
                Assert.AreEqual(ex.Message, LoginValidationException.ValidationMessageFor(LoginValidationExceptions.InvalidUsername));
            }
        }
        public void Register(string name, string login, string password, string passwordConfirm, double balance)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }
            _loginValidator.Validate(login);
            _passwordValidator.Validate(password);
            if (passwordConfirm != password)
            {
                throw new ArgumentException("Password confirmation wrong", nameof(passwordConfirm));
            }

            var user = Users.FindByLogin(login);

            if (user != null)
            {
                throw new DuplicateLoginException();
            }

            Users.Add(name, login, password, balance);
        }
示例#4
0
        public LoginMessages.Response Handle(LoginMessages.Request request)
        {
            // Validate request
            try
            {
                Validator.Validate(request);
            } catch (LoginValidationException ex)
            {
                var errorResponse = new LoginMessages.Response()
                {
                    Success   = false,
                    Exception = ex
                };

                return(errorResponse);
            }

            // Authenticate Account
            Account account;

            try
            {
                account = AccountGateway.GetAccount(request.Username);
                if (account == null)
                {
                    throw LoginException.Create(LoginExceptions.IncorrectCredentials);
                }

                if (account.Password != request.Password)
                {
                    throw LoginException.Create(LoginExceptions.IncorrectCredentials);
                }
            } catch (LoginException ex)
            {
                var errorResponse = new LoginMessages.Response()
                {
                    Success   = false,
                    Exception = ex
                };

                return(errorResponse);
            }

            var sessionString = SessionCreator.CreateSession();
            var session       = new Session
            {
                Id       = sessionString,
                PlayerId = account.PlayerId,
                GameId   = null
            };

            try
            {
                SessionGateway.CreateSession(session);
            } catch (Exception e)
            {
                var message       = e.Message;
                var errorResponse = new LoginMessages.Response()
                {
                    Success   = false,
                    Exception = new Exception("Could not create a session! Error: " + message)
                };

                return(errorResponse);
            }

            var response = new LoginMessages.Response()
            {
                Success   = true,
                Session   = sessionString,
                Exception = null
            };

            return(response);
        }
示例#5
0
        /// <summary>
        /// 启动NodeServer
        /// </summary>
        public Task StartAsync()
        {
            logger.LogInformation("Server is loading services.");

            LoadServices();

            logger.LogInformation("Server load services success.");

            server.OnRecieveLoginRequest += new RecieveLoginRequestDelegate(async(loginAuthInfo) =>
            {
                var loginInfo = new LoginRequestInfo()
                {
                    Body          = loginAuthInfo.Body,
                    Attachments   = loginAuthInfo.Attachments,
                    RemoteAddress = loginAuthInfo.RemoteAddress
                };
                var loginAuthResult = await loginValidator.Validate(loginInfo);
                return(new LoginResponseData()
                {
                    AuthIdentity = loginAuthResult.AuthIdentity,
                    Attachments = loginAuthResult.Attachments,
                    AuthFailedMessage = loginAuthResult.AuthFailedMessage,
                    AuthResult = loginAuthResult.AuthResult,
                    AuthStatusCode = loginAuthResult.AuthStatusCode
                });
            });

            server.OnRecieveServiceRequest += new RecieveServiceRequestDelegate(async(byte[] message, IDictionary <string, byte[]> attachments, LoginState loginState) =>
            {
                var serviceProcessTimeBegin = DateTime.Now;
                var serviceRequest          = await serializer.DeserializeAsync(protocolStackFactory.ServiceRequestType, message) as IServiceRequest;

                RouteDescription route = null;
                try
                {
                    route = RouteManager.GetRoute(serviceRequest.ServiceId, serviceRequest.ActionId);
                }
                catch (RouteNotFoundException ex)
                {
                    logger.LogError(ex, $"RouteManager.GetRoute has error, route is not exist. ServiceId={serviceRequest.ServiceId}, ActionId={serviceRequest.ActionId}, ExceptionMessage={ex.Message}");
                    return(await CreateServiceExceptionResponseDataAsync(ServiceExceptionKeys.SERVICE_NOT_EXIST_ERROR));
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, $"RouteManager.GetRoute has error, ServiceId={serviceRequest.ServiceId}, ActionId={serviceRequest.ActionId}, ExceptionMessage={ex.Message}");
                    return(await CreateSystemExceptionResponseDataAsync(SystemExceptionKeys.SYSTEM_ERROR));
                }

                logger.LogDebug($"Get route info. ServiceId={route.ServiceId}, ActionId={route.ActionId}, ServiceType={route.ServiceType}, ActionType={route.ActionType}");

                var context = new ServiceContext(config.Host, config.Port, loginState.Identity, loginState.RemoteAddress, route, serviceRequest.ParamList, attachments);

                var serviceProcessResult = await serviceProcessor.ProcessAsync(context);

                logger.LogInformation($"Service process used time: {DateTime.Now - serviceProcessTimeBegin}, ServiceId={serviceRequest.ServiceId}, ActionId={serviceRequest.ActionId}");

                return(new ResponseData()
                {
                    Attachments = serviceProcessResult.Attachments,
                    Data = await serializer.SerializeAsync(serviceProcessResult.ServiceResponse)
                });
            });

            logger.LogInformation("Server is binding.");

            OnStarting?.Invoke(new NodeServerStartEventArg(config.Host, config.Port, RouteManager.GetAllRoutes()));

            return(server.StartAsync().ContinueWith(task =>
            {
                if (task.Exception != null)
                {
                    logger.LogError(task.Exception, $"Server start has error. Host={config.Host}, Port={config.Port}, ExceptionMessage={task.Exception.InnerException.Message}, ExceptionStackTrace={task.Exception.InnerException.StackTrace}");
                    return;
                }
                logger.LogInformation($"Server listen port {config.Port}");
                OnStarted?.Invoke(new NodeServerStartEventArg(config.Host, config.Port, RouteManager.GetAllRoutes()));
            }));
        }
示例#6
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            if (message is IByteBuffer buffer)
            {
                var id = 0l;

                /*
                 * skip length field
                 */

                buffer.SkipBytes(4);

                var header = buffer.ReadByte();

                /*
                 * process heart beat
                 */
                if (header == HEARTBEAT_HEADER)
                {
                    if (ensureRegisterd(context))
                    {
                        _checker.UpdateTimeout(context.Channel.Id.AsLongText());
                    }

                    //else ignore
                }
                else if (header == REQUEST)
                {
                    var rpcContext = _pool.Rent();

                    try
                    {
                        /*
                         *  resolve request
                         */
                        var request = new RpcRequest();

                        request.RequestId = buffer.ReadLongLE();

                        id = request.RequestId;

                        var length = buffer.ReadIntLE();

                        var path = buffer.ReadString(length, Encoding.UTF8);

                        parseQuery(request, path);

                        length = buffer.ReadIntLE();

                        request.Body = new byte[length];

                        buffer.ReadBytes(request.Body);

                        /*
                         * login check
                         */
                        if (_validator != null)// configed require  identity validate
                        {
                            try
                            {
                                if (!_checker.IsRegistered(context.Channel.Id.AsLongText()))
                                {
                                    var resposne = _validator.Validate(request.Query["id"], request.Query["password"]) ? RpcResponse.CreateResponse(200, request.RequestId)
                                                                                                                       : RpcResponse.CreateLoginFialedResponse(request.RequestId);

                                    var sendBuffer = _codex.EncodeServerResponse(resposne);

                                    var sendBuffer1 = context.Allocator.Buffer(sendBuffer.Length);

                                    sendBuffer1.WriteBytes(sendBuffer);

                                    context.WriteAndFlushAsync(sendBuffer1);
                                }
                            }
                            catch (Exception ex)
                            {
                                var sendBuffer = _codex.EncodeServerResponse(RpcResponse.CreateErrorResponse(request.RequestId));

                                var sendBuffer1 = context.Allocator.Buffer(sendBuffer.Length);

                                sendBuffer1.WriteBytes(sendBuffer);

                                context.WriteAndFlushAsync(sendBuffer1);

                                return;
                            }
                        }

                        /*
                         *  process request
                         */

                        rpcContext.Init(request, context);

                        _middleWare.ProcessRequest(rpcContext);
                    }
                    catch (Exception ex)
                    {
                        _logger?.Error(ex);

                        context.WriteAndFlushAsync(RpcResponse.CreateErrorResponse(10000));
                    }
                    finally
                    {
                        _pool.Recycle(rpcContext);
                    }
                }
            }
            else
            {
                _logger?.Warn($"unexcepted input {message}");
            }
        }