Esempio n. 1
0
        public async Task <ActionResult> Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var authProxy = new AuthenticationProxy(MvcApplication.GetApiUrl(), "/api/oauth");

            var token = await authProxy.Login(model.UserName, model.Password);

            if (token == null)
            {
                ModelState.AddModelError("password", ErrorMessages.IncorrectLogin);
                return(View());
            }

            var tokenCookie = new HttpCookie("token", token.Value)
            {
                Expires  = DateTime.Now.AddSeconds(token.ExpiresIn),
                HttpOnly = false
            };

            var roleCookie = new HttpCookie("role", token.Role)
            {
                Expires  = DateTime.Now.AddSeconds(token.ExpiresIn),
                HttpOnly = true
            };

            Response.Cookies.Add(tokenCookie);
            Response.Cookies.Add(roleCookie);

            return(RedirectToAction("Index", "Dashboard"));
        }
Esempio n. 2
0
        public void Login()
        {
            AuthenticationProxy proxy = new AuthenticationProxy();
            string token = proxy.GetAccessToken();

            AuthenticationControl.AccessToken = token;
        }
        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException("username");
            }
            string tenantName;
            string tenantUsername;

            if (!Upn.TryParse(username, out tenantName, out tenantUsername))
            {
                return(false);  //invalid username format
            }
            try
            {
                if (!AuthenticationProxy.UserExists(tenantName, tenantUsername))
                {
                    return(false); //not exists
                }
                AuthenticationProxy.DeleteUser(tenantName, tenantUsername);
            }
            catch (Exception ex)
            {
                throw new ProviderException(ex.Message, ex);
            }
            return(true);
        }
Esempio n. 4
0
        // TODO: Implement lazy load pattern so each instance creation doesn't create every object instance for no reason")]
        public TMDbClient(ITMDbSettings settings) : base(settings.BaseUrl)
        {
            if (settings.ApiKey.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(settings.ApiKey));
            }

            Settings        = settings;
            Account         = new AccountProxy(this);
            Authentication  = new AuthenticationProxy(this);
            Certifications  = new CertificationsProxy(this);
            Changes         = new ChangesProxy(this);
            Collections     = new CollectionsProxy(this);
            Configuration   = new ConfigurationProxy(this);
            Credits         = new CreditsProxy(this);
            Discover        = new DiscoverProxy(this);
            Exports         = new ExportsProxy(this);
            Find            = new FindProxy(this);
            Genres          = new GenresProxy(this);
            GuestSessions   = new GuestSessionsProxy(this);
            Keywords        = new KeywordsProxy(this);
            Lists           = new ListsProxy(this);
            Movies          = new MoviesProxy(this);
            Network         = new NetworkProxy(this);
            People          = new PeopleProxy(this);
            Reviews         = new ReviewsProxy(this);
            Search          = new SearchProxy(this);
            Trending        = new TrendingProxy(this);
            TVEpisodeGroups = new TVEpisodeGroupsProxy(this);
            TVEpisodes      = new TVEpisodesProxy(this);
            TV        = new TVProxy(this);
            TVSeasons = new TVSeasonsProxy(this);
        }
Esempio n. 5
0
        public IRepository <T> Create <T>(CreateType createType = CreateType.DynamicProxy)
        {
            IRepository <T> repository = null;

            switch (createType)
            {
            case CreateType.DynamicProxy:
                repository = new DynamicProxy <IRepository <T> >().Create(new Repository <T>(),
                                                                          s => logger.Info($"{s}"),
                                                                          e => logger.Error($"{e}"),
                                                                          o => o?.ToString(),
                                                                          TaskScheduler.Current);
                break;

            case CreateType.AuthenticationProxy:
                repository = new AuthenticationProxy <IRepository <T> >().Create(Create <T>(CreateType.DynamicProxy), TaskScheduler.Current);
                break;

            case CreateType.PerformanceProxy:
                repository = new PerformanceProxy <IRepository <T> >().Create(Create <T>(CreateType.AuthenticationProxy));
                break;

            case CreateType.LoggerRepository:
                repository = new LoggerRepository <T>(new Repository <T>());
                break;
            }
            return(repository);
        }
Esempio n. 6
0
        public async Task <ActionResult> Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var authProxy = new AuthenticationProxy(WebConfigurationManager.AppSettings["WebApiUrl"], "/api/oauth");

            var token = await authProxy.Login(model.UserName, model.Password);

            if (token == null)
            {
                ModelState.AddModelError("password", "Wachtwoord of gebruikersnaam is onjuist");
                return(View());
            }

            var tokenCookie = new HttpCookie("token", token.Value)
            {
                Expires  = DateTime.Now.AddMinutes(token.ExpiresIn),
                HttpOnly = true
            };

            Response.Cookies.Add(tokenCookie);

            return(RedirectToAction("Index", "Dashboard"));
        }
 public SignInViewModel()
 {
     _authenticationProxy = new AuthenticationProxy();
     TitleText            = "Zaloguj się";
     SignInCommand        = new RelayCommand(SignInAction, SignInCanExecute);
     OnPageLoadCommand    = new RelayCommand(OnPageLoad);
     _cts = new CancellationTokenSource();
 }
        public override bool ValidateUser(string username, string password)
        {
            string tenantName;
            string tenantUsername;

            if (!Upn.TryParse(username, out tenantName, out tenantUsername))
            {
                return(false);
            }
            return(AuthenticationProxy.ValidateUser(tenantName, tenantUsername, password));
        }
Esempio n. 9
0
        public async Task <ActionResult> EditPassword(PasswordViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var authProxy = new AuthenticationProxy(WebConfigurationManager.AppSettings["WebApiUrl"], "user");

            await authProxy.UpdatePassword(viewModel.Id, viewModel.NewPassword, "bearer", Request.Cookies["token"].Value);

            return(RedirectToAction("Index"));
        }
Esempio n. 10
0
        public string SendFiles(byte[][] files, string[] filename)
        {
            AuthenticationProxy proxy2 = new AuthenticationProxy();
            MSG msgi = new MSG()
            {
                Op_name   = "LoadFiles",
                FileName  = filename,
                data      = files,
                TokenUser = "",
            };

            msgi = proxy2.Dispatching(msgi);
            return(msgi.Op_statut.ToString());
        }
Esempio n. 11
0
        private async Task EnsureReportAccess(Report report)
        {
            var loginProxy = new AuthenticationProxy(MvcApplication.GetApiUrl(), "/api/oauth");
            var token      = await loginProxy.LoginAnonymous(report.AnonymousToken);

            // TODO: add error handling
            var authCookie = new HttpCookie("token", token.Value)
            {
                Expires = DateTime.Now.AddMinutes(token.ExpiresIn)
            };
            var cookie = new HttpCookie("report", report.Id.ToString());

            Response.Cookies.Add(cookie);
            Response.Cookies.Add(authCookie);
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            AuthenticationProxy proxy = new AuthenticationProxy();

            string[]           files = new string[] { "" };
            Server_WCF_IIS.MSG msg   = new Server_WCF_IIS.MSG();
            msg.Op_name   = "LoginByToken";
            msg.TokenApp  = "456e7472657a20766f7472652070687261736520696369";
            msg.TokenUser = "";
            // TODO add msg.Files

            msg = proxy.Dispatching(msg);

            Console.WriteLine("Value op statut : {0}, info: {1}", msg.Op_statut.ToString(), msg.Op_infos);
            Console.Read();
        }
Esempio n. 13
0
        private async Task EnsureReportAccess(Report report)
        {
            var loginProxy = new AuthenticationProxy(WebConfigurationManager.AppSettings["WebApiUrl"], "/api/oauth");
            var token      = await loginProxy.LoginAnonymous(report.AnonymousToken);

            // TODO: add error handling
            var authCookie = new HttpCookie("token", token.Value)
            {
                // TODO: let the web api determine the expiration time of the token. Right now, this doesn't
                // work because both types of token (for the reporter and the dashboard) have the same expiration
                // value, which is set in Startup.cs.
                Expires = DateTime.Now.AddMinutes(10)
            };
            var cookie = new HttpCookie("report", report.Id.ToString());

            Response.Cookies.Add(cookie);
            Response.Cookies.Add(authCookie);
        }
        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            string tenantName;
            string tenantUsername;

            if (!Upn.TryParse(username, out tenantName, out tenantUsername))
            {
                throw new ArgumentException(string.Format("The username {0} is invalid!", username));
            }
            AdamUser adamUser = AuthenticationProxy.GetAdamUser(tenantName, tenantUsername);

            if (adamUser == null)
            {
                return(null);
            }
            object providerUserKey = new SecurityIdentifier(adamUser.Sid, 0);

            return(new ActiveDirectoryMembershipUser(this.Name, adamUser.PrincipleName, providerUserKey, adamUser.Email, string.Empty, string.Empty
                                                     , true, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now));
        }
Esempio n. 15
0
        public object BeforeCall(string operationName, object[] inputs)
        {
            var header = (AuthenticationHeader)null;
            try
            {
                header = OperationContext.Current.RequestContext.RequestMessage.Headers.GetHeader<AuthenticationHeader>("AuthenticationHeader", "");
            }
            catch (Exception)
            {

            }
            if (header == null) {
                throw new Exception("Неопознаный запрос");
            }
            using (var proxy = new AuthenticationProxy()) {
                if (!proxy.IsAuthorized(header.Data)) {
                    throw new Exception("Неавторизованный запрос");
                }
            }
            return null;
        }
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException("username");
            }
            string tenantName;
            string tenantUsername;

            if (!Upn.TryParse(username, out tenantName, out tenantUsername))
            {
                return(false);
            }
            CheckPassword(oldPassword, MinRequiredPasswordLength, "oldPassword");
            CheckPassword(oldPassword, MinRequiredPasswordLength, "newPassword");
            if (newPassword.Length < this.MinRequiredPasswordLength)
            {
                throw new ArgumentException(string.Format("The length of the passowrd {0} must not be shorter than {1} characters!", "newPassword", MinRequiredPasswordLength));
            }
            int num1 = 0;

            for (int num2 = 0; num2 < newPassword.Length; num2++)
            {
                if (!char.IsLetterOrDigit(newPassword, num2))
                {
                    num1++;
                }
            }
            if (num1 < this.MinRequiredNonAlphanumericCharacters)
            {
                throw new ArgumentException(string.Format("Non alpha numeric characters of {0} must be more than {1}", "newPassword", MinRequiredNonAlphanumericCharacters));
            }
            if ((this.PasswordStrengthRegularExpression.Length > 0) && !Regex.IsMatch(newPassword, this.PasswordStrengthRegularExpression))
            {
                throw new ArgumentException(string.Format("The format of the password {0} is not correct!", "newPassword"));
            }

            AuthenticationProxy.ChangePassword(tenantName, tenantUsername, oldPassword, newPassword);
            return(true);
        }
Esempio n. 17
0
    protected string ConvertToUsername(Guid?userId)
    {
        if (userId == null)
        {
            return(string.Empty);
        }
        string principleName = AuthenticationProxy.GetUpnByUserId((Guid)userId);

        if (string.IsNullOrEmpty(principleName))
        {
            return(string.Empty);
        }
        ProfileCommon profile = Profile.GetProfile(principleName);

        if (profile != null && !string.IsNullOrEmpty(profile.FullName))
        {
            return(profile.FullName);
        }
        else
        {
            return(new Upn(principleName).Username);
        }
    }
Esempio n. 18
0
        public object BeforeCall(string operationName, object[] inputs)
        {
            var header = (AuthenticationHeader)null;

            try
            {
                header = OperationContext.Current.RequestContext.RequestMessage.Headers.GetHeader <AuthenticationHeader>("AuthenticationHeader", "");
            }
            catch (Exception)
            {
            }
            if (header == null)
            {
                throw new Exception("Неопознаный запрос");
            }
            using (var proxy = new AuthenticationProxy()) {
                if (!proxy.IsAuthorized(header.Data))
                {
                    throw new Exception("Неавторизованный запрос");
                }
            }
            return(null);
        }
        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            //extract tenant name from the current user upn
            string tenantName;
            string username;

            Upn.TryParse(HttpContext.Current.User.Identity.Name, out tenantName, out username);

            MembershipUserCollection collection = new MembershipUserCollection();

            string[] usernames = AuthenticationProxy.GetUsers(tenantName);
            totalRecords = usernames.Length;
            int start = pageIndex * pageSize;

            if (start >= 0 && start < totalRecords)
            {
                for (int i = start; i < totalRecords && i < start + pageSize; i++)
                {
                    collection.Add(System.Web.Security.Membership.GetUser((new Upn(tenantName, usernames[i])).ToString()));
                }
            }
            return(collection);
        }
Esempio n. 20
0
 public string Login(string email, string password, string AppToken)
 {
     if (email.Length == 0 || password.Length == 0 || !Regex.IsMatch(email, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
     {
         return("False");
     }
     else
     {
         //Logique metier
         AuthenticationProxy proxy = new AuthenticationProxy();
         string[]            files = new string[] { "" };
         Server_WCF_IIS.MSG  msg   = new Server_WCF_IIS.MSG()
         {
             Op_name   = "LoginByToken",
             TokenApp  = AppToken,
             TokenUser = "",
             Password  = password,
             Email     = email
         };
         // TODO add msg.Files
         msg = proxy.Dispatching(msg);
         return(msg.Op_statut.ToString());
     }
 }
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            status = MembershipCreateStatus.Success;
            string tenantName;
            string tenantUsername;

            if (string.IsNullOrEmpty(username))
            {
                status = MembershipCreateStatus.InvalidUserName;
                return(null);
            }

            if (!Upn.TryParse(username, out tenantName, out tenantUsername))
            {
                status = MembershipCreateStatus.InvalidUserName;
                return(null);
            }

            if (string.IsNullOrEmpty(email))
            {
                status = MembershipCreateStatus.InvalidEmail;
                return(null);
            }

            if (string.IsNullOrEmpty(password) || password.Length < MinRequiredPasswordLength)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return(null);
            }

            int i = 0;

            for (int j = 0; j < password.Length; j++)
            {
                if (!char.IsLetterOrDigit(password, j))
                {
                    i++;
                }
            }
            if (i < MinRequiredNonAlphanumericCharacters)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return(null);
            }
            if ((PasswordStrengthRegularExpression.Length > 0) && !Regex.IsMatch(password, PasswordStrengthRegularExpression))
            {
                status = MembershipCreateStatus.InvalidPassword;
                return(null);
            }
            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);

            base.OnValidatingPassword(args);
            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return(null);
            }

            try
            {
                if (AuthenticationProxy.UserExists(tenantName, tenantUsername))
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                    return(null);
                }
                AuthenticationProxy.CreateUser(tenantName, tenantUsername, password, email);
            }
            catch (Exception ex)
            {
                throw new ProviderException(ex.Message, ex);
            }
            return(GetUser(username, false));
        }
Esempio n. 22
0
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var api         = context.ActionDescriptor.AttributeRouteInfo.Template;
            var isEnableLog = IsEnableLog(context);

            try
            {
                // 设置当前访问信息
                string clientInfo = context.HttpContext.Connection?.RemoteIpAddress.ToString();
                string requestId  = context.HttpContext.Request.Headers["requestId"];
                if (string.IsNullOrEmpty(requestId))
                {
                    requestId = context.HttpContext.TraceIdentifier;
                    context.HttpContext.Request.Headers["requestId"] = requestId;
                }
                app.ActionArguments          = context.ActionArguments;
                AppManager.CurrentAppContext = app;

                // 记录日志
                if (isEnableLog)
                {
                    string parm = JsonConvert.SerializeObject(app.ActionArguments);
                    app.LogRequest(requestId, context.ActionDescriptor.DisplayName, parm, clientInfo, context.ActionDescriptor.AttributeRouteInfo.Template);
                }

                // 读取或设置sessionId和language
                if (IsEnableCookie(context))
                {
                    InitCookies(api);
                }

                // 访问限制,登录等方法不受限制
                if (AuthenticationProxy.IsCheckGateway(context))
                {
                    var clientIp = context.HttpContext.Connection?.RemoteIpAddress.ToString();
                    if (!string.IsNullOrEmpty(clientIp))
                    {
                        GatewayManager.Check(clientIp);
                    }
                }

                var authentication = app.GetService <IAuthenticationProxy>();

                // 鉴权-检查用户token,设置当前用户上下文
                var token = (context.HttpContext.Request.Headers[ApiDocManager.TokenHeaderName]).ToString().Replace("Bearer ", "");
                if (AuthenticationProxy.IsCheckToken(context) || !string.IsNullOrEmpty(token))
                {
                    if (ConfigManager.Configuration["EnableApiDoc"] == "1" && string.IsNullOrEmpty(token))
                    {
                        token = ConfigManager.Configuration["DefaultToken"];
                    }
                    authentication.SetCurrentUser(token, context);
                }
                authentication.SetCurrentGuest(app.SessionID);

                // 检查数据
                VaildateModel(context);

                // 异步
                var asyncTask = AsyncTaskManager.GetTaskInfo(context, app.User?.UserID.ToString());
                if (asyncTask != null)
                {
                    var resultValue = ResultBuilder.AsSuccess(asyncTask);
                    context.Result = new JsonResult(resultValue);
                    return;
                }

                // 从缓存返回
                var cacheResult = CacheManager.ReadCache(context, app);
                if (cacheResult != null)
                {
                    cacheResult.RequestId = context.HttpContext.TraceIdentifier;
                    var cacheTimeRate = CacheTimeSettings.GetCacheTimeRate();
                    var cacheSeconds  = CacheManager.CalcCacheSeconds(context.ActionDescriptor as ControllerActionDescriptor, out var cacheTimeSetting);
                    var seconds       = cacheTimeRate.HttpCacheTime * cacheSeconds;
                    if (seconds < 10)
                    {
                        seconds = 10;
                    }
                    if (seconds > 60)
                    {
                        seconds = 60;
                    }

                    context.HttpContext.Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
                    {
                        Public = true,
                        MaxAge = TimeSpan.FromSeconds(seconds)
                    };
                    context.Result = new JsonResult(cacheResult);
                    return;
                }
            }
            // 不捕获异常,由ExceptionFilter处理。
            finally
            {
                if (context.Result != null)
                {
                    CleanOnActionClose();
                    if (isEnableLog)
                    {
                        app.LogResponseResult(context.Result);
                        app.EndRequest();
                    }
                }
            }
        }