Пример #1
0
		public static void InitTest(TestContext context)
		{
			var authInfo = new AuthInfo("unittest");

			var client = new RestClient(MockHttp.BaseUrl);
			client.HttpFactory = new SimpleFactory<SampleDataMockHttp>();
			Api = new MockedAppHarborClient(authInfo, client);

			var clientEmptyListData = new RestClient(MockHttp.BaseUrl);
			clientEmptyListData.HttpFactory = new SimpleFactory<EmptyListDataMockHttp>();
			EmptyListDataApi = new MockedAppHarborClient(authInfo, clientEmptyListData);

			var clientExistingData = new RestClient(MockHttp.BaseUrl);
			clientExistingData.HttpFactory = new SimpleFactory<ExistingDataMockHttp>();
			ExistingDataDataApi = new MockedAppHarborClient(authInfo, clientExistingData);

			ApplicationSlug = ":application";
		}
Пример #2
0
        public static void InitTest(TestContext context)
        {
            var authInfo = new AuthInfo()
            {
                AccessToken = "unittest"
            };

            var client = new RestSharp.RestClient(MockHttp.BaseURL);
            client.HttpFactory = new RestSharp.SimpleFactory<SampleDataMockHttp>();
            Api = new AppHarborApi(authInfo, client);

            var clientEmptyListData = new RestSharp.RestClient(MockHttp.BaseURL);
            clientEmptyListData.HttpFactory = new RestSharp.SimpleFactory<EmptyListDataMockHttp>();
            EmptyListDataApi = new AppHarborApi(authInfo, clientEmptyListData);

            var clientExistingData = new RestSharp.RestClient(MockHttp.BaseURL);
            clientExistingData.HttpFactory = new RestSharp.SimpleFactory<ExistingDataMockHttp>();
            ExistingDataDataApi = new AppHarborApi(authInfo, clientExistingData);

            ApplicationID = ":application";
        }
        byte[] SetAuthInfo(UUID principalID, Dictionary <string, object> request)
        {
            AuthInfo existingInfo = m_AuthenticationService.GetAuthInfo(principalID);

            if (existingInfo == null)
            {
                return(FailureResult());
            }

            if (request.ContainsKey("AccountType"))
            {
                existingInfo.AccountType = request["AccountType"].ToString();
            }

            if (request.ContainsKey("PasswordHash"))
            {
                existingInfo.PasswordHash = request["PasswordHash"].ToString();
            }

            if (request.ContainsKey("PasswordSalt"))
            {
                existingInfo.PasswordSalt = request["PasswordSalt"].ToString();
            }

            if (request.ContainsKey("WebLoginKey"))
            {
                existingInfo.WebLoginKey = request["WebLoginKey"].ToString();
            }

            if (!m_AuthenticationService.SetAuthInfo(existingInfo))
            {
                m_log.ErrorFormat(
                    "[AUTHENTICATION SERVER POST HANDLER]: Authentication info store failed for account {0} {1} {2}",
                    existingInfo.PrincipalID);

                return(FailureResult());
            }

            return(SuccessResult());
        }
        public ActionResult AccountManagerPicture(string databaseName, string customerId, string companyId)
        {
            APIAuth  auth     = new APIAuth(Request, Response);
            AuthInfo authInfo = auth.CheckLogin();

            if (authInfo.IsAuthenticated)
            {
                Customer localCust = new Customer();
                localCust.DatabaseName = databaseName;
                localCust.CustomerId   = customerId;
                localCust.CompanyId    = companyId;

                //Check if this user has access to this customer
                var userCustomers = db.GetUserCustomersSync(authInfo.User.Id);

                if (userCustomers.Count(x => x.CustomerKey == localCust.CustomerKey) > 0)
                {
                    // Get the customer's account manager's details
                    AccountManager accountManager = new OverviewDAL().GetAccountManagerDetailsSync(localCust).FirstOrDefault();

                    // Get the URL for the account manager's image
                    string accountManagerImageURL = DownloadsHelper.GetAccountManagerImageURL(accountManager.Email);

                    // Download the account manager image
                    WebClient webClient = new WebClient();
                    byte[]    accountManagerImageBytes = webClient.DownloadData(accountManagerImageURL);

                    // Return the account manager image as bytes
                    return(File(accountManagerImageBytes, System.Net.Mime.MediaTypeNames.Image.Jpeg));
                }
                else
                {
                    return(auth.Forbidden());
                }
            }
            else
            {
                return(auth.Forbidden());
            }
        }
Пример #5
0
        /// <summary>
        /// Create a Twitch chatbot.
        /// </summary>
        public ChatController(AuthInfo info)
        {
            var _state = _stateMachine = new StateMachine <State, Trigger>(State.SignedOff);

            _state.OnTransitioned((transition =>
            {
                _log.DebugFormat("{0} => {1}", transition.Source.ToString("G"), transition.Destination.ToString("G"));
            }));

            _state.Configure(State.Conceived)
            .Permit(Trigger.DisconnectRequested, State.SignedOff);

            _state.Configure(State.SignedOff)
            .SubstateOf(State.Conceived)
            .OnEntry(() => Task.Run(() => Whisperer.Stop()))
            .OnEntry(() => Task.Run(() => Talker.Stop()))
            .Ignore(Trigger.ChatbotsUnready)
            .Permit(Trigger.ConnectRequested, State.Connecting);

            _state.Configure(State.Connecting)
            .SubstateOf(State.Conceived)
            .OnEntry(() => Task.Run(() => Whisperer.Start()))
            .OnEntry(() => Task.Run(() => Talker.Start()))
            .Ignore(Trigger.ConnectRequested)
            .Ignore(Trigger.ChatbotsUnready)
            .Permit(Trigger.ChatbotsReady, State.Ready);

            _state.Configure(State.Ready)
            .SubstateOf(State.Conceived)
            .Ignore(Trigger.ChatbotsReady)
            .OnEntry(() => Ready?.Invoke(this, EventArgs.Empty))
            .OnExit(() => Unready?.Invoke(this, EventArgs.Empty));

            Whisperer          = new ChatBot(info, true);
            Whisperer.Ready   += CheckBotStates;
            Whisperer.Unready += CheckBotStates;
            Talker             = new ChatBot(info, false);
            Talker.Ready      += CheckBotStates;
            Talker.Unready    += CheckBotStates;
        }
Пример #6
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (StatusCode != 0)
            {
                hash ^= StatusCode.GetHashCode();
            }
            if (RequestId != 0UL)
            {
                hash ^= RequestId.GetHashCode();
            }
            hash ^= requests_.GetHashCode();
            hash ^= unknown6_.GetHashCode();
            if (Latitude != 0D)
            {
                hash ^= Latitude.GetHashCode();
            }
            if (Longitude != 0D)
            {
                hash ^= Longitude.GetHashCode();
            }
            if (Altitude != 0D)
            {
                hash ^= Altitude.GetHashCode();
            }
            if (authInfo_ != null)
            {
                hash ^= AuthInfo.GetHashCode();
            }
            if (authTicket_ != null)
            {
                hash ^= AuthTicket.GetHashCode();
            }
            if (MsSinceLastLocationfix != 0L)
            {
                hash ^= MsSinceLastLocationfix.GetHashCode();
            }
            return(hash);
        }
Пример #7
0
 public ActionResult AuthAdd(AuthInfo info)
 {
     if (info.ID == 0)
     {
         AuthInfo hasInfo = _systemService.GetModel <AuthInfo>(new { info.AuthCode });
         if (hasInfo != null && hasInfo.ID > 0)
         {
             Result.IsOk = false;
             Result.Msg  = "权限编码已存在";
         }
         else
         {
             if (_systemService.Insert(info) > 0)
             {
                 Result.IsOk = true;
                 Result.Msg  = "添加成功";
             }
             else
             {
                 Result.IsOk = false;
                 Result.Msg  = "添加失败";
             }
         }
     }
     else
     {
         if (_systemService.Update(info))
         {
             Result.IsOk = true;
             Result.Msg  = "更新成功";
         }
         else
         {
             Result.IsOk = false;
             Result.Msg  = "更新失败";
         }
     }
     return(Json(Result));
 }
        public AuthenticationResponse GetAccessToken(Guid publicToken)
        {
            AuthInfo authInfo = _authInfoRepository.GetAuthInfoByPublicToken(publicToken);

            if (authInfo != null)
            {
                //TODO: user already has private token
                string privateToken = IssueToken(authInfo.UserId.ToString(), authInfo.Role);
                authInfo.PrivateToken = privateToken;
                _authInfoRepository.SaveChanges();
                return(new AuthenticationResponse
                {
                    Token = privateToken,
                    Succes = true
                });
            }
            return(new AuthenticationResponse
            {
                Error = "Public token not found",
                Succes = false
            });
        }
Пример #9
0
        public AuthInfo Login(User user)
        {
            var    authInfo   = new AuthInfo();
            var    loggedUser = AuthenticateUser(user);
            string token      = string.Empty;

            if (loggedUser != null)
            {
                token = GenerateJSONWebToken(loggedUser);
                if (!string.IsNullOrEmpty(token))
                {
                    authInfo.UserFirstName  = loggedUser.UserFirstName;
                    authInfo.UserMiddleName = loggedUser.UserMiddleName;
                    authInfo.UserLastName   = loggedUser.UserLastName;
                    authInfo.UserName       = loggedUser.UserName;
                    authInfo.RoleId         = loggedUser.RoleName;
                    authInfo.token          = token;
                    authInfo.RefreshToken   = RandomString(50);
                }
            }
            return(authInfo);
        }
 ///GENMHASH:993553CEE69195BA14AFB76D2E2EC427:C9C73743BA068D281F188DCE3E989A79
 public RegistrySourceTriggerImpl WithRepositoryAuthentication(TokenType tokenType, string token)
 {
     if (IsInCreateMode())
     {
         AuthInfo authInfo = new AuthInfo()
         {
             TokenType = tokenType.ToString(),
             Token     = token
         };
         this.inner.SourceRepository.SourceControlAuthProperties = authInfo;
     }
     else
     {
         AuthInfoUpdateParameters authInfoUpdateParameters = new AuthInfoUpdateParameters()
         {
             TokenType = tokenType.ToString(),
             Token     = token
         };
         this.sourceTriggerUpdateParameters.SourceRepository.SourceControlAuthProperties = authInfoUpdateParameters;
     }
     return(this);
 }
Пример #11
0
 public ServicesTest(IAuthService authService, IUserRepository userRepository, IFileService fileService, ITokenGeneratorService tokenService)
 {
     _authService           = authService;
     _fileService           = fileService;
     _userRepository        = userRepository;
     _tokenGeneratorService = tokenService;
     _Goodinfo = new AuthInfo {
         Username = "******", Password = "******"
     };
     _UsernameTakenRegister = new AuthInfo {
         Username = "******", Password = "******"
     };
     _BadUsernameLogin = new AuthInfo {
         Username = "******", Password = "******"
     };
     _BadPasswordRegister = new AuthInfo {
         Username = "******", Password = "******"
     };
     _BadPasswordLogin = new AuthInfo {
         Username = "******", Password = "******"
     };
 }
Пример #12
0
        /// <summary>
        /// 指示指定的控件是否已获得授权
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            bool result = false;
            //前端请求api时会将token存放在名为"auth"的请求头中
            var authHeader = from t in actionContext.Request.Headers where t.Key == "auth" select t.Value.FirstOrDefault();

            if (authHeader != null)
            {
                string token = authHeader.FirstOrDefault();//获取token
                if (!string.IsNullOrEmpty(token))
                {
                    try
                    {
                        AuthInfo json         = new AuthInfo();
                        var      tokenService = EngineContext.Current.Resolve <ITokenService>();
                        //TOKEN解密
                        result = tokenService.TokenDecryption(token, out errMsg, out json);
                        if (result)
                        {
                            actionContext.RequestContext.RouteData.Values.Add("auth", json);
                        }
                        return(result);
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }
                }
                else
                {
                    errMsg = "头部文件中未传入用户token";
                }
            }
            else
            {
                errMsg = "头部文件中未传入用户token";
            }
            return(result);
        }
Пример #13
0
        public static async Task <List <string> > ProcessImageAsync(IOcrClient ocrClient, string strFilePath)
        {
            AuthInfo AuthInfo = new AuthInfo
            {
                Host          = "https://cloud-eu.ocrsdk.com",
                ApplicationId = @"eda2b839-3717-48aa-80b5-fb500fd78909",
                Password      = @"E2EXXLkQnGXthipqNBfd5FDR"
            };
            var    parameters = ProcessingParamsBuilder.GetMrzProcessingParams();
            string filePath   = strFilePath;

            using (var fileStream = new FileStream(@filePath, FileMode.Open))
            {
                var taskInfo = await ocrClient.ProcessMrzAsync(
                    parameters,
                    fileStream,
                    Path.GetFileName(filePath),
                    waitTaskFinished : true);

                return(taskInfo.ResultUrls);
            }
        }
        private void TcpConnectionEstablished(TcpPackageConnection connection)
        {
            if (_state != ConnectionState.Connecting || _connection != connection || connection.IsClosed)
            {
                LogDebug(
                    "IGNORED (_state {0}, _conn.Id {1:B}, conn.Id {2:B}, conn.closed {3}): TCP connection to [{4}, L{5}] established.",
                    _state, _connection == null ? Guid.Empty : _connection.ConnectionId, connection.ConnectionId,
                    connection.IsClosed, connection.RemoteEndPoint, connection.LocalEndPoint);
                return;
            }

            LogDebug("TCP connection to [{0}, L{1}, {2:B}] established.", connection.RemoteEndPoint,
                     connection.LocalEndPoint, connection.ConnectionId);
            _heartbeatInfo = new HeartbeatInfo(_packageNumber, true, _stopwatch.Elapsed);

            if (_settings.DefaultUserCredentials != null)
            {
                _connectingPhase = ConnectingPhase.Authentication;

                _authInfo = new AuthInfo(Guid.NewGuid(), _stopwatch.Elapsed);
                var package = _settings.DefaultUserCredentials.AuthToken != null
                                        ? new TcpPackage(TcpCommand.Authenticate,
                                                         TcpFlags.Authenticated,
                                                         _authInfo.CorrelationId,
                                                         _settings.DefaultUserCredentials.AuthToken,
                                                         null)
                                        : new TcpPackage(TcpCommand.Authenticate,
                                                         TcpFlags.Authenticated,
                                                         _authInfo.CorrelationId,
                                                         _settings.DefaultUserCredentials.Username,
                                                         _settings.DefaultUserCredentials.Password,
                                                         null);
                _connection.EnqueueSend(package);
            }
            else
            {
                GoToIdentifyState();
            }
        }
        public HttpResponseMessage Login([FromBody] LoginInfo loginInfo)
        {
            User user = db.User.Where(usr => usr.Email == loginInfo.Email && usr.PasswordHash == loginInfo.PasswordHash).FirstOrDefault();

            if (user == null)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, "Such user does not exist"));
            }

            Guid refreshToken = Guid.NewGuid();

            user.RefreshToken = refreshToken;
            user.RefreshTokenExpirationDate = DateTime.UtcNow.AddDays(1);
            db.SaveChanges();

            AuthInfo authenticationInfo = new AuthInfo()
            {
                UserId = user.Id, NickName = user.Nickname, JWT_Token = JWT_Manager.GenerateToken(user.Id, user.Nickname, 5), RefreshToken = user.RefreshToken.ToString()
            };

            return(Request.CreateResponse(HttpStatusCode.OK, authenticationInfo));
        }
Пример #16
0
        public void CanHandleDisabledHTTPS()
        {
            // Setup
            string server   = "server_test";
            string owner    = "owner_test";
            string repoName = "repo_name";
            var    authInfo = new AuthInfo()
            {
                Decoded = "authInfo"
            };

            // Act
            RemoteRepository repo = new RemoteRepository(server, owner, repoName, authInfo, true);

            // Setup
            Assert.AreEqual(server, repo.Server);
            Assert.AreEqual(owner, repo.Owner);
            Assert.AreEqual(repoName, repo.Name);
            Assert.AreEqual(authInfo, repo.Auth);
            Assert.AreEqual($"http://{server}/{owner}/{repoName}", repo.Url);
            Assert.AreEqual($"http://{authInfo.Decoded}@{server}/{owner}/{repoName}", repo.GitUrl);
        } /* End of Function - CanHandleDisabledHTTPS */
        public async Task <AuthInfo> Register(User user)
        {
            AuthInfo response = await this.webApi.Register(user);

            var jwt = response.accessToken;

            string[] jwtEncodedSegments = jwt.Split('.');
            var      payloadSegment     = jwtEncodedSegments[1];

            var decodePayload      = System.Convert.FromBase64String(payloadSegment);
            var decodedUtf8Payload = Encoding.UTF8.GetString(decodePayload);

            var authInfo = JsonSerializer.Deserialize <AuthInfo>(decodedUtf8Payload.ToString());

            authInfo.accessToken = jwt;

            await this.localStorageService.SetItem("todo:auth", authInfo);

            AuthInfo = authInfo;

            return(response);
        }
Пример #18
0
        public void DefaultsCorrectly()
        {
            // Setup
            string server   = "server_test";
            string owner    = "owner_test";
            string repoName = "repo_name";
            var    authInfo = new AuthInfo()
            {
                Decoded = "authInfo"
            };

            // Act
            RemoteRepository repo = new RemoteRepository(server, owner, repoName, authInfo, false);

            // Setup
            Assert.AreEqual(server, repo.Server);
            Assert.AreEqual(owner, repo.Owner);
            Assert.AreEqual(repoName, repo.Name);
            Assert.AreEqual(authInfo, repo.Auth);
            Assert.AreEqual($"https://{server}/{owner}/{repoName}", repo.Url);
            Assert.AreEqual($"https://{authInfo.Decoded}@{server}/{owner}/{repoName}", repo.GitUrl);
        } /* End of Function - DefaultsCorrectly */
Пример #19
0
        public AuthInfo GetAppMasterAuth(int pageType = (int)TmpType.小程序专业模板, string authName = null, string accessUrl = null)
        {
            List <NavMenu>  allMenu  = NavMenuBLL.SingleModel.GetListByPageType(pageType);
            List <AuthMenu> authMenu = new List <AuthMenu>();

            allMenu?.ForEach(item =>
            {
                authMenu.Add(new AuthMenu {
                    ItemId = item.Id, Read = true, Write = true
                });
            });
            AuthInfo authInfo = new AuthInfo
            {
                AuthMenu     = authMenu,
                MasterAccess = true,
                AuthName     = authName,
                AllMenu      = allMenu,
                CurrRoute    = accessUrl,
            };

            return(authInfo);
        }
Пример #20
0
        public LoginResult Post([FromBody] LoginRequest request)
        {
            LoginResult rs = new LoginResult();

            //假设用户名为"admin",密码为"123"
            if (request.UserName == "admin" && request.Password == "123")
            {
                //如果用户登录成功,则可以得到该用户的身份数据。当然实际开发中,这里需要在数据库中获得该用户的角色及权限
                AuthInfo authInfo = new AuthInfo
                {
                    IsAdmin = true,
                    Roles   = new List <string> {
                        "admin", "owner"
                    },
                    UserName = "******"
                };
                try
                {
                    //生成token,SecureKey是配置的web.config中,用于加密token的key,打死也不能告诉别人
                    byte[] key = Encoding.Default.GetBytes(ConfigurationManager.AppSettings["SecureKey"]);
                    //采用HS256加密算法
                    string token = JWT.JsonWebToken.Encode(authInfo, key, JWT.JwtHashAlgorithm.HS256);
                    rs.Token   = token;
                    rs.Success = true;
                }
                catch
                {
                    rs.Success = false;
                    rs.Message = "登陆失败";
                }
            }
            else
            {
                rs.Success = false;
                rs.Message = "用户名或密码不正确";
            }
            return(rs);
        }
Пример #21
0
        public void Parse(string configFile)
        {
            using (StreamReader file = new StreamReader(new FileStream(configFile, FileMode.Open)))
            {
                string line = null;
                while ((line = file.ReadLine()) != null)
                {
                    if (String.IsNullOrEmpty(line))
                    {
                        break;
                    }

                    if (line.StartsWith("#"))
                    {
                        continue;
                    }

                    try
                    {
                        string[] data = line.Split(new char[] { '=' }, 2, StringSplitOptions.None);
                        Type     type = Type.GetType("VTankBotRunner." + data[0].Trim());
                        if (type == null)
                        {
                            type = Type.GetType(data[0].Trim());
                        }

                        AuthInfo auth = AuthInfo.FromString(data[1].Trim());

                        Register(type, auth, null);
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(
                            "Warning: Found corrupted bot in file: {0}", e);
                    }
                }
            }
        }
        public ActionResult AccountManagerDetails(string databaseName, string customerId, string companyId)
        {
            APIAuth  auth     = new APIAuth(Request, Response);
            AuthInfo authInfo = auth.CheckLogin();

            if (authInfo.IsAuthenticated)
            {
                Customer localCust = new Customer();
                localCust.DatabaseName = databaseName;
                localCust.CustomerId   = customerId;
                localCust.CompanyId    = companyId;

                //Check if this user has access to this customer
                var userCustomers = db.GetUserCustomersSync(authInfo.User.Id);

                if (userCustomers.Count(x => x.CustomerKey == localCust.CustomerKey) > 0)
                {
                    //AccountManager accountManager = db.GetAccountManagerDetails(localCust).GetAwaiter().GetResult();
                    var            accountManagers = db.GetAccountManagerDetailsSync(localCust);
                    AccountManager accountManager  = accountManagers.FirstOrDefault();

                    RentalsDAL dbRental = new RentalsDAL();

                    string depotEmail = dbRental.GetOnRentEmailAddressSync(localCust).FirstOrDefault();;
                    accountManager.OnRentEmailAddress = depotEmail;

                    return(Json(accountManager, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(auth.Forbidden());
                }
            }
            else
            {
                return(auth.Forbidden());
            }
        }
Пример #23
0
        public LoginResult Post([FromBody] LoginRequest request)
        {
            LoginResult rs = new LoginResult();

            //这是是获取用户名和密码的,这里只是为了模拟
            if (request.UserName == "wangshibang" && request.Password == "123456")
            {
                AuthInfo info = new AuthInfo {
                    UserName = "******", Roles = new List <string> {
                        "Admin", "Manage"
                    }, IsAdmin = true
                };
                try
                {
                    const string secret = "To Live is to change the world";
                    //secret需要加密
                    IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
                    IJsonSerializer   serializer = new JsonNetSerializer();
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                    IJwtEncoder       encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);
                    var token = encoder.Encode(info, secret);
                    rs.Message = "XXXXX";
                    rs.Token   = token;
                    rs.Success = true;
                }
                catch (Exception ex)
                {
                    rs.Message = ex.Message;
                    rs.Success = false;
                }
            }
            else
            {
                rs.Message = "fail";
                rs.Success = false;
            }
            return(rs);
        }
Пример #24
0
        public static void Login(string usrname, string passwd)
        {
            /*
             * Check if username was provided,
             * if not return an error
             */
            if (usrname == String.Empty)
            {
                throw new InvalidOperationException("Username missing");
            }
            /*
             * log into NewsBlur
             */
            else
            {
                // Check for password, if not password provided, ommit it in the request
                AuthInfo info;
                if (passwd == String.Empty)
                {
                    info = new AuthInfo { username = usrname };
                }
                else
                {
                    info = new AuthInfo
                        {
                            username = usrname,
                            password = passwd
                        };
                }

                RestRequest request = new RestRequest("login", Method.POST);
                request.AddObject(info);
                client.ExecuteAsync(request, response =>
                {
                    Debug.WriteLine(response.Content);
                });
            }
        }
Пример #25
0
        public TokenInfo GetToken([FromBody] LoginRequest loginRequest)
        {
            TokenInfo tokenInfo = new TokenInfo();

            if (loginRequest != null)
            {
                string   userName = loginRequest.UserName;
                string   passWord = loginRequest.Password;
                bool     isAdmin  = (userName == "SWD") ? true : false;
                AuthInfo authInfo = new AuthInfo {
                    UserName = userName, Roles = new List <string>(), IsAdmin = isAdmin, ExpiryDateTime = DateTime.Now.AddDays(1)
                };
                const string secretKey = "ShunKai";//
                try
                {
                    byte[]            key        = Encoding.UTF8.GetBytes(secretKey);
                    IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
                    IJsonSerializer   serializer = new JsonNetSerializer();
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                    IJwtEncoder       encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);
                    var token = encoder.Encode(authInfo, key);
                    tokenInfo.Success = true;
                    tokenInfo.Token   = token;
                    tokenInfo.Message = "OK";
                }
                catch (Exception ex)
                {
                    tokenInfo.Success = false;
                    tokenInfo.Message = ex.Message.ToString();
                }
            }
            else
            {
                tokenInfo.Success = false;
                tokenInfo.Message = "用户信息为空";
            }
            return(tokenInfo);
        }
        public AuthInfo AuthenicationRequest(string user, string key)
        {
            if (string.IsNullOrEmpty(user))
                throw new ArgumentNullException("user");

            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            WebRequest request = WebRequest.Create(_url);

            request.Headers["X-Auth-User"] = user;
            request.Headers["X-Auth-Key"] = key;

            AuthInfo info = new AuthInfo();

            using (var response = request.GetResponse())
            {
                info.ServerManagementUrl = response.Headers["X-Server-Management-Url"];
                info.AuthToken = response.Headers["X-Auth-Token"];
            }

            return info;
        }
Пример #27
0
        public async Task <LoginResponse> Login(AuthInfo authInfo)
        {
            LoginResponse loginResponse = new LoginResponse();
            var           id            = await _userRepository.GetId(authInfo);

            UserDB userDb = await _userRepository.Get(id);

            if (userDb == null)
            {
                loginResponse.AuthResponse = AuthEnum.BadUsername;
            }
            else if (userDb.Password != authInfo.Password)
            {
                loginResponse.AuthResponse = AuthEnum.BadPassword;
            }
            else
            {
                loginResponse.AuthResponse = AuthEnum.Success;
                loginResponse.Token        = await _tokenService.CreateToken(userDb.Id);
            }

            return(loginResponse);
        }
Пример #28
0
        protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);
            var      response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
            string   msg      = " 服务端拒绝访问:你没有权限!";
            AuthInfo obj      = null;

            if (filterContext.RequestContext.RouteData.Values.Count > 0)
            {
                obj = (AuthInfo)filterContext.RequestContext.RouteData.Values["auth"];
            }
            if (obj != null && obj.timeout < DateTime.Now)
            {
                msg = "服务端拒绝访问:已超时!";
            }
            var content = new AjaxResult
            {
                State   = "0",
                Message = msg
            };

            response.Content = new StringContent(Json.Encode(content), Encoding.UTF8, "application/json");
        }
        public virtual AuthInfo GetAuthInfo(UUID principalID)
        {
            AuthenticationData data = m_Database.Get(principalID);

            if (data == null)
            {
                return(null);
            }
            else
            {
                AuthInfo info
                    = new AuthInfo()
                    {
                    PrincipalID  = data.PrincipalID,
                    AccountType  = data.Data["accountType"] as string,
                    PasswordHash = data.Data["passwordHash"] as string,
                    PasswordSalt = data.Data["passwordSalt"] as string,
                    WebLoginKey  = data.Data["webLoginKey"] as string
                    };

                return(info);
            }
        }
Пример #30
0
        /// <summary>
        /// Read a local file with authentication info
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private static AuthInfo GetAuthInfo(string filePath = null)
        {
            try
            {
                if (string.IsNullOrEmpty(filePath))
                {
                    string executabledirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
                    string fileName            = "credentials_dev.json";
                    filePath = Path.Combine(executabledirectory, fileName);
                }

                Console.WriteLine("Reading credentials file {0}", filePath);

                string   contents = File.ReadAllText(filePath);
                AuthInfo info     = JsonConvert.DeserializeObject <AuthInfo>(contents);
                return(info);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error reading credentials file: " + ex.Message);
                throw ex;
            }
        }
        public HttpRequestMessage BuildLoginRequest(AuthInfo authInfo, SessionInfo sessionInfo)
        {
            var requestUri = BuildLoginUrl(sessionInfo);

            var data = new LoginRequestData()
            {
                LoginName         = authInfo.User,
                Password          = authInfo.Password,
                AccountName       = authInfo.Account,
                ClientAppId       = _clientInfo.DriverName,
                ClientAppVersion  = _clientInfo.DriverVersion,
                ClientEnvironment = _clientInfo.Environment
            };

            var requestBody = new LoginRequest()
            {
                Data = data
            };
            var jsonBody = JsonSerializer.Serialize(requestBody, _jsonSerializerOptions);
            var request  = BuildJsonRequestMessage(requestUri, HttpMethod.Post, jsonBody);

            return(request);
        }
        /// <summary>
        ///     On Selecting a server, this retuens the details to the model
        /// </summary>
        /// <param name="serverId"></param>
        /// <returns></returns>
        /// <remarks>
        ///      Date:   24/06/2018
        ///      Author: Stephen McCutcheon
        /// </remarks>
        public ActionResult Details(string serverId)
        {
            using (var apiClient = new MyServersApiClient())
            {
                var authInfo = new AuthInfo
                {
                    Username = Settings.Default.APIUserName,
                    Password = Settings.Default.APIPassword
                };

                ServerDetailModel detailsModel;
                var serversDetails = GetServerDetails(serverId, apiClient, authInfo, out detailsModel);


                GetReversDnsDetails(serversDetails, detailsModel);

                GetBandWidthInfo(apiClient, authInfo, serversDetails, detailsModel);

                GetMonitoringInfo(apiClient, authInfo, serversDetails, detailsModel);

                return(View(detailsModel));
            }
        }
        /// <summary>
        ///    This loads teh view from the model and implements paging so
        ///    not all rows are returend on 10 at a time
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <returns></returns>
        /// <remarks>
        ///      Date:   24/06/2018
        ///      Author: Stephen McCutcheon
        /// </remarks>
        public ActionResult Index(int?pageNumber)
        {
            using (var apiClient = new MyServersApiClient())
            {
                var authInfo = new AuthInfo
                {
                    Username = Settings.Default.APIUserName,
                    Password = Settings.Default.APIPassword
                };

                //Gets all the Top Level Domains Details
                var topLevelDomains = apiClient.GetAllTLDs(authInfo);


                //Page checks to ensure the page number does not go off the
                //end of pages. Basically if you try and access a page before or after
                //itdefaults back to the first or last page accordingly
                int startPos;
                var viewModels = SetMaxAndMinPagesViewModels(pageNumber, topLevelDomains, out startPos);

                //Set the apprioprate values in the Modl
                foreach (var domain in topLevelDomains.Skip(startPos).Take(10))
                {
                    var domainItem = new DomainItem
                    {
                        DomainId   = domain.TLD,
                        DomainCost = domain.Cost.ToString("C"),
                        MaxPeriod  = domain.MaxPeriod,
                        MinPeriod  = domain.MinPeriod
                    };

                    viewModels.Items.Add(domainItem);
                }

                return(View(viewModels));
            }
        }
Пример #34
0
            // Schedule the job
            public Unlocker()
            {
                UserInfo?userInfo = GetUserInfo();

                if (!userInfo.HasValue)
                {
                    m_Result[0] = new UnlockResult {
                        Value = UnlockResult.Status.NoUser
                    };
                    return;
                }

                var authInfo = new AuthInfo(userInfo.Value);

                if (UnityEngine.PlayerPrefs.HasKey("Havok.Auth.Token") && UnityEngine.PlayerPrefs.HasKey("Havok.Auth.TokenExpiry"))
                {
                    try
                    {
                        authInfo.HavokToken              = Convert.ToUInt64(UnityEngine.PlayerPrefs.GetString("Havok.Auth.Token"));
                        authInfo.HavokTokenExpiry        = Convert.ToInt64(UnityEngine.PlayerPrefs.GetString("Havok.Auth.TokenExpiry"));
                        authInfo.HavokSubscriptionExpiry = Convert.ToInt64(UnityEngine.PlayerPrefs.GetString("Havok.Auth.SubscriptionExpiry"));
                    }
                    catch (FormatException)
                    {
                        // The saved prefs don't match what we expect, just ignore them
                    }
                }

                m_AuthInfo[0] = authInfo;
                m_Result[0]   = new UnlockResult {
                    Value = UnlockResult.Status.Invalid
                };
                m_jobHandle = new UnlockJob()
                {
                    AuthInfo = m_AuthInfo, Result = m_Result
                }.Schedule();
            }
Пример #35
0
 /// <summary>
 /// Initailizes a new instance of <see cref="CommonRepository"/> class.
 /// </summary>
 public CommonRepository(IFlickrElement xmlElement, AuthInfo authInfo, Type interfaceType)
     : this(xmlElement, interfaceType, new AuthenticationInformationFlickrSettingsProvider(authInfo))
 {
     //intentionally left blank
 }
 public RackSpaceCloudServersAPI(AuthInfo authInfo)
 {
     this._authInfo = authInfo;
 }
Пример #37
0
			public MockedAppHarborClient(AuthInfo authInfo, RestClient restClient)
				: base(authInfo, restClient)
			{
			}
Пример #38
0
 public InstagramAPI(InstagramConfig instagramConfig, AuthInfo authInfo, string endpoint) {
     InstagramConfig = instagramConfig;
     AuthInfo = authInfo;
     Uri = InstagramConfig.APIURI + endpoint;
 }
Пример #39
0
        public static AuthInfo authAccount(string pin)
        {
            using (WebClient wc = new WebClient())
            {
                NameValueCollection nvc = new NameValueCollection
                {
                    {"client_id", APIKeys.ImgurClientID },
                    {"client_secret", APIKeys.ImgurClientSecret },
                    {"grant_type", "pin" },
                    {"pin", pin },
                };
                wc.Headers.Add("Authorization", Imgur.getAuth());
                AuthInfo info = new AuthInfo();
                try
                {
                    byte[] response = wc.UploadValues("https://api.imgur.com/oauth2/token", nvc);
                    string res = System.Text.Encoding.Default.GetString(response);
                    var JsonReader = JsonReaderWriterFactory.CreateJsonReader(response, new System.Xml.XmlDictionaryReaderQuotas());
                    var root = System.Xml.Linq.XElement.Load(JsonReader);
                    info.access_token = root.Element("access_token").Value;
                    info.expires_in = root.Element("expires_in").Value;
                    info.token_type = root.Element("token_type").Value;
                    info.scope = root.Element("scope").Value;
                    info.refresh_token = root.Element("refresh_token").Value;
                    info.account_id = Int32.Parse(root.Element("account_id").Value);
                    info.account_username = root.Element("account_username").Value;
                    info.success = true;
                }
                catch (Exception e)
                {
                    info.success = false;
                    info.ex = e;
                }
                return info;

            }
        }
Пример #40
0
 /// <summary>
 /// Initalizes a new instance of the <see cref="FlickrContext"/> class.
 /// </summary>
 public FlickrContext(AuthInfo authInfo)
     : this(new FlickrElementProxy(new WebRequestProxy()))
 {
     this.authenticationInformation = authInfo;
     this.queryFactory = new AuthQueryFactory(elementProxy, authInfo);
 }
Пример #41
0
        static void Main(string[] args)
        {
            authInfo = new AuthInfo
            {
                SystemId = "x",
                SystemPassword = "******",
                UserName = "******",
                Password = "******",
                ConnectionMode = ConnectionMode.Production
            };
            apiClient = new Client(authInfo);
            apiClient.CreateSession();

            while (true)
            {
                QuerySQS();
                Console.WriteLine("Waiting for new Message");
                System.Threading.Thread.Sleep(5000);
            }
        }
Пример #42
0
 public static bool TryLogin(string login, string password)
 {
     var auth = new AuthInfo(login, password);
     var gal = Server.GetGalaxyMap(auth);
     if (gal != null) {
         CurrentLogin = auth;
         return true;
     }
     return false;
 }
Пример #43
0
        internal static bool VerifyLocalKeyfile(string filename, out AuthInfo authinfo)
        {
            StreamReader reader = null;
            string data = "";

            authinfo = null;

            try {
                reader = new StreamReader(filename);
                data = reader.ReadToEnd();
                reader.Close();
            } catch (Exception exc) {
                MessageBox.Show("Offline key authorization failure: Could not read keyfile.\n\n\n" + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            Regex rx = new Regex(@"\s*Keyfile(\n*|\s*)?" +
                @"(?<inner>" +
                @"(?>" +
                @"\{(?<LEVEL>)" +
                @"|" +
                @"\};(?<-LEVEL>)" +
                @"|" +
                @"(?!\{|\};)." +
                @")+" +
                @"(?(LEVEL)(?!))" +
                @")"
                , RegexOptions.IgnoreCase | RegexOptions.Singleline);

            Match topmatch = rx.Match(data);

            if (!topmatch.Success) {
                MessageBox.Show("Offline key authorization failure: Could not find valid 'keyfile' block.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            string keyfile_data = topmatch.Groups["inner"].Value;

            // Once we have the top matched group, parse each line in it
            rx = new Regex(@"\s*\b(?<name>[A-Z]*)\b\s*=\s*((" + "\"" + @"\s*(?<single>.*?)\s*" + "\"" + @"\s*;)|(\{(?<multi>.*?)\};))", RegexOptions.Singleline | RegexOptions.IgnoreCase);

            // 1 = name
            // 4 = normal definition
            // 6 = multiline definition

            string version = "";
            string name = "";
            string expires = "";
            string machinecode = "";
            string featurebit = "";
            string hash = "";
            string signature = "";
            string email = "";

            foreach(Match m in rx.Matches(keyfile_data)) {
                switch(m.Groups["name"].Value.ToLower()) {
                    case "version":
                        version = m.Groups["single"].Value;
                        break;
                    case "name":
                        name = m.Groups["single"].Value;
                        break;
                    case "expires":
                        expires = m.Groups["single"].Value;
                        break;
                    case "machinecode":
                        machinecode = m.Groups["single"].Value;
                        break;
                    case "featurebit":
                        featurebit = m.Groups["single"].Value;
                        break;
                    case "hash":
                        hash = m.Groups["single"].Value;
                        break;
                    case "keysignature":
                        signature = m.Groups["multi"].Value;
                        break;
                    case "email":
                        email = m.Groups["single"].Value;
                        break;
                }
            }

            // Clean up signature
            signature = signature.Replace(" ", "");
            signature = signature.Replace("\t", "");
            signature = signature.Replace("\n", "");
            signature = signature.Replace("\r", "");

            // Check field validity
            if (version == "" || expires == "" || machinecode == "" || featurebit == "" || hash == "" || name == "" || email == "" || signature == "") {
                MessageBox.Show("Offline key authorization failure: Keyfile construction incomplete.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            // Check version
            if (version != "1.00") {
                MessageBox.Show("Offline key authorization failure: Incorrect version (Expected '1.00')", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            // Check expiration date
            try {
                DateTime dt = DateTime.Parse(expires);
                if (DateTime.Now.Ticks >= dt.Ticks) {
                    MessageBox.Show("Offline key authorization has expired.  Please visit www.torquedev.com to request a new offline authorization file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            } catch (Exception exc) {
                MessageBox.Show("Offline key authorization failure: Unable to verify date stamp.  Error returned was: " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            // Check if the machine codes match
            if (machinecode != CConfig.GetHardKey()) {
                MessageBox.Show("Offline key authorization failure: Machine code mismatch.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            // Verify hash of data
            string sighash = CConfig.SHA1(version + name + machinecode + expires + featurebit + email);

            if (sighash != hash) {
                MessageBox.Show("Offline key authorization failure: Checksum mismatch.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            // Verify signature by first loading the public key into memory
            DSA dsa = new DSACryptoServiceProvider();

            try {
                dsa.FromXmlString(CVerify.PublicKey);
            } catch (Exception exc) {
                MessageBox.Show("Offline key authorization failure: Unable to load DSA public key.  Error returned was: " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            // Verify the data against the signature
            try {
                if (!dsa.VerifySignature(Convert.FromBase64String(hash), Convert.FromBase64String(signature))) {
                    MessageBox.Show("Offline key authorization failure: File signature is invalid.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    dsa.Clear();
                    return false;
                } else {
                    // Signature checked out.  Create the passback reference
                    authinfo = new AuthInfo(version, name, expires, machinecode, featurebit, hash, signature, email);
                    return true;
                }
            } catch (Exception exc) {
                MessageBox.Show("Offline key authorization failure: DSA verification failure.  Error returned was: " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                dsa.Clear();
                return false;
            }
        }
Пример #44
0
 public Authenticated(InstagramConfig config, AuthInfo auth)
     : base(config, auth, "/search/") {
         _unauthenticated = new Unauthenticated(config);
 }
Пример #45
0
 public AuthRepository(IFlickrElement elementProxy, AuthInfo authenticationInformation)
     : base(elementProxy, authenticationInformation)
 {
     this.elementProxy = elementProxy;
     this.authenticationInformation = authenticationInformation;
 }
Пример #46
0
 public Authenticated(InstagramConfig config, AuthInfo auth)
     : base(config, auth, "/geographies/") {
         _unauthenicated = new Unauthenticated(config);
 }
        private void TcpConnectionEstablished(TcpPackageConnection connection)
        {
            if (_state != ConnectionState.Connecting || _connection != connection || connection.IsClosed)
            {
                LogDebug("IGNORED (_state {0}, _conn.Id {1:B}, conn.Id {2:B}, conn.closed {3}): TCP connection to [{4}, L{5}] established.", 
                         _state, _connection == null ? Guid.Empty : _connection.ConnectionId, connection.ConnectionId, 
                         connection.IsClosed, connection.RemoteEndPoint, connection.LocalEndPoint);
                return;
            }

            LogDebug("TCP connection to [{0}, L{1}, {2:B}] established.", connection.RemoteEndPoint, connection.LocalEndPoint, connection.ConnectionId);
            _heartbeatInfo = new HeartbeatInfo(_packageNumber, true, _stopwatch.Elapsed);

            if (_settings.DefaultUserCredentials != null)
            {
                _connectingPhase = ConnectingPhase.Authentication;

                _authInfo = new AuthInfo(Guid.NewGuid(), _stopwatch.Elapsed);
                _connection.EnqueueSend(new TcpPackage(TcpCommand.Authenticate,
                                                       TcpFlags.Authenticated,
                                                       _authInfo.CorrelationId,
                                                       _settings.DefaultUserCredentials.Username,
                                                       _settings.DefaultUserCredentials.Password, 
                                                       null));
            }
            else
            {
                GoToConnectedState();
            }
        }
 internal AuthenticationInformationFlickrSettingsProvider(AuthInfo authenticationInformation)
 {
     this.authenticationInformation = authenticationInformation;
 }
Пример #49
0
 public AuthenticaitonProvider(IFlickrElement elementProxy, AuthInfo authenticationInformation)
     : base(elementProxy, authenticationInformation)
 {
 }
Пример #50
0
 public Authenticated(InstagramConfig config, AuthInfo authInfo) :
     base(config, authInfo, "/media/") {
     _unauthenticated = new Unauthenticated(config);
 }
Пример #51
0
 public MemoryProvider(IFlickrElement elementProxy, AuthInfo authenticationInformation)
     : base(elementProxy, authenticationInformation)
 {
     this.authenticationInformation = authenticationInformation;
 }
Пример #52
0
 public TagRepository(IFlickrElement elementProxy, AuthInfo authenticationInformation, IAuthRepository authRepository)
     : base(elementProxy, authenticationInformation, typeof(ITagRepository))
 {
     this.elementProxy = elementProxy;
     this.authRepository = authRepository;
 }
Пример #53
0
 public PhotoRepository(IFlickrElement elementProxy, AuthInfo authenticationInformation)
     : base(elementProxy, authenticationInformation, typeof(IPhotoRepository))
 {
     this.elementProxy = elementProxy;
     authRepo = new AuthRepository(elementProxy, authenticationInformation);
 }