예제 #1
0
        public async Task <TrainingPlanViewModel> GetEntityById(
            int?Id, AuthorizationModel model = null)
        {
            var viewModel = new TrainingPlanViewModel();

            PopulateDropDowns(viewModel);

            if (Id > 0)
            {
                var entity = await _context.TrainingPlan
                             .IgnoreQueryFilters()
                             .Include(c => c.FinYear)
                             .Include(c => c.Event)
                             .Include(c => c.TrainingPlanDistances).ThenInclude(b => b.Distance)
                             .Include(c => c.TrainingPlanMembers).ThenInclude(a => a.Member)
                             .Include(c => c.TrainingPlanRaceDefinitions).ThenInclude(a => a.RaceDefinition)
                             .FirstOrDefaultAsync(a => a.Id == Id);

                if (entity != null)
                {
                    entity.ToViewModel(viewModel);
                }
            }
            return(viewModel);
        }
예제 #2
0
파일: AuthLogic.cs 프로젝트: motipa/V7App
        public async Task <AuthorizationResponseModel> AuthorizeAsync(AuthorizationModel model)
        {
            try
            {
                if (model.AuthorizationType == _config["AuthorizationType:CredentialsType"])
                {
                    string res = await _hasher.HashAsync(model.Password);

                    return(await AuthorizeBasedOnCredentialsAsync(model.Login, model.Password, model.ApplicationId.Value, model.TenantId, model.Client, model.ClientSecret));
                }
                else if (model.AuthorizationType == _config["AuthorizationType:RefreshTokenType"])
                {
                    //  return await AuthorizeBasedOnRefreshTokenAsync(model.RefreshToken);
                    return(null);
                }

                else
                {
                    return(new AuthorizationResponseModel {
                        Exception = "Invalid authorization type"
                    });
                }
            }
            catch (Exception ex)
            {
                return(new AuthorizationResponseModel {
                    Exception = ex.Message
                });
            }
        }
        private AuthorizationModel IsAuthorized(int employeeId, string utilityCode)
        {
            AuthorizationModel model = new AuthorizationModel();

            Business.HR.EmployeeMaster objEmployeeMaster = new Business.HR.EmployeeMaster();
            Entity.HR.EmployeeMaster   employeeMaster    = new Entity.HR.EmployeeMaster();
            DataTable dtEmployee = objEmployeeMaster.EmployeeMaster_ById(new Entity.HR.EmployeeMaster()
            {
                EmployeeMasterId = employeeId
            });

            if (dtEmployee.AsEnumerable().Any())
            {
                employeeMaster = objEmployeeMaster.AuthenticateUser(dtEmployee.Rows[0]["EmployeeCode"].ToString());
            }

            if (employeeMaster != null)
            {
                string[] roles = employeeMaster.Roles.Split(',');
                model.ReturnValue = roles.Contains(utilityCode);
            }
            else
            {
                model.ReturnValue = false;
            }
            return(model);
        }
예제 #4
0
        public async Task <ProductImageViewModel> GetEntityById(
            int?Id, AuthorizationModel model = null)
        {
            var viewModel = new ProductImageViewModel {
            };

            PopulateDropDowns(viewModel);

            if (Id > 0)
            {
                var entity = await _context.ProductImage
                             .IgnoreQueryFilters()
                             .Include(c => c.Product.ProductCategory)
                             .Include(c => c.Document)
                             .Include(c => c.FeaturedImages).ThenInclude(b => b.ProductImage.Product)
                             .Include(c => c.FeaturedImages).ThenInclude(b => b.ProductImage.Document)
                             .FirstOrDefaultAsync(a => a.Id == Id);

                if (entity != null)
                {
                    entity.ToViewModel(viewModel);
                    //viewModel.ProductImageSizes = entity.ProductImageSizes.ToSelectListItem(x => x.Size.ShortName, x => x.SizeId.ToString());
                }
            }
            return(viewModel);
        }
예제 #5
0
        public IActionResult Purge()
        {
            int   athleteId = HttpContext.Session.GetInt32("AthleteId") ?? 0;
            Token token     = _context.Athletes
                              .Include(athlete => athlete.Token)
                              .FirstOrDefault(athlete => athlete.AthleteId == athleteId)
                              .Token;

            // If token expires with one hour, refresh token
            if (token.ExpiresAt < DateTime.Now.AddSeconds(3600))
            {
                AuthorizationModel tokenModel = StravaController
                                                .loadNewToken(token.RefreshToken).Result;
                token.AccessToken  = tokenModel.Access_Token;
                token.RefreshToken = tokenModel.Refresh_Token;
                token.ExpiresAt    = DateTime.Now.AddSeconds(tokenModel.Expires_In);
                token.ExpiresIn    = TimeSpan.FromSeconds(tokenModel.Expires_In);
            }
            Processor.Deauthorization(token.AccessToken);
            Athlete athleteToDelete = _context.Athletes
                                      .FirstOrDefault(athlete => athlete.AthleteId == athleteId);

            _context.Remove(athleteToDelete);
            _context.Remove(token);
            _context.SaveChanges();
            HttpContext.Session.Clear();
            return(RedirectToAction("Index", "Home"));
        }
        private async void Enter_Click(object sender, RoutedEventArgs e)
        {
            if (_state == State.Authorization)
            {
                var model = new AuthorizationModel()
                {
                    username = Edit_Login.Text,
                    password = Edit_Password.Password
                };

                if (!IsModelValid(model))
                {
                    return;
                }

                await Context.Authorize(model);
            }
            else if (_state == State.Registration)
            {
                var item = (ComboBoxItem)Combo_Role.SelectedValue;

                Role role = (Role)Enum.Parse(typeof(Role), (string)item.Content);

                var model = new RegistrationModel()
                {
                    username = Edit_Login.Text,
                    password = Edit_Password.Password,
                    Role     = role
                };

                if (!(await Context.Register(model)))
                {
                    Text_Errors.Text = Context.ErrorMessages;
                }
                else
                {
                    Change_Click(null, null);
                }

                return;
            }

            if (Context.IsAuthorized)
            {
                ((App)Application.Current).FinishAuthorization();

                this.Close();
            }
            else
            {
                string message = "Authorization has failed. Check if login and password had been inputed correctly";

                if (Context.ErrorMessages != null)
                {
                    message += "\n" + Context.ErrorMessages;
                }

                Text_Errors.Text = message;
            }
        }
예제 #7
0
        public async Task <IActionResult> CreateList(
            [FromBody, Bind("Listidentifier", "Keyword")] AuthorizationModel listAuth)
        {
            if (!listAuth.Validate())
            {
                return(BadRequest(ErrorModel.BadRequest()));
            }

            listAuth.LowerIdentifier();

            if (db.Lists.FirstOrDefault(l => l.Identifier == listAuth.ListIdentifier) != null)
            {
                return(BadRequest(ErrorModel.AlreadyExists()));
            }

            var list = new List(listAuth.ListIdentifier, listAuth.Keyword);

            var masterKey = SecureRandom.GenerateMasterKey(32);

            list.MasterKeyHash = Hashing.CreatePasswordHash(masterKey);

            await db.Lists.AddAsync(list);

            await db.SaveChangesAsync();

            var outList = new ListCreated(list, masterKey);

            return(Created("list", outList));
        }
예제 #8
0
        public async Task <IActionResult> Login([FromBody, Bind("ListIdentifier", "Keyword")] AuthorizationModel auth)
        {
            if (!auth.Validate())
            {
                return(BadRequest(ErrorModel.BadRequest()));
            }

            auth.LowerIdentifier();

            var list = db.Lists.FirstOrDefault(l => l.Identifier == auth.ListIdentifier);

            if (list == null)
            {
                return(Unauthorized());
            }

            if (!keywordAccess.ValidateLogin(list, auth.Keyword))
            {
                return(Unauthorized());
            }

            var claims = new List <Claim>
            {
                new Claim(ExtendedClaimTypes.ListIdentifier, list.Identifier),
                new Claim(ExtendedClaimTypes.ListGUID, list.GUID.ToString()),
            };

            var identity  = new ClaimsIdentity(claims, "login");
            var principal = new ClaimsPrincipal(identity);

            await HttpContext.SignInAsync(principal);

            return(Ok());
        }
예제 #9
0
        public async Task <IActionResult> AuthorizeAsync([FromBody] AuthorizationModel authorizationModel)
        {
            var user = await _dbContext.Users
                       .Include(i => i.UserRoles)
                       .ThenInclude(i => i.Role)
                       .FirstOrDefaultAsync(i =>
                                            i.UserName == authorizationModel.UserName &&
                                            i.Password == authorizationModel.Password);

            if (user == null)
            {
                _logger.LogError($"User [{authorizationModel.UserName}] was not found in the DB. UserName or Password is not correct");
                return(BadRequest($"Wrong credentials for user [{authorizationModel.UserName}]"));
            }

            var token = JwtUtil.NewJwtToken(authorizationModel.UserName, _authOptions.JwtSecret,
                                            _authOptions.JwtExpirationSeconds);

            var response = new AuthorizationResponseModel
            {
                Token     = token,
                FirstName = user.FirstName,
                LastName  = user.LastName,
                UserName  = user.UserName,
                IsAdmin   = user.UserRoles.Any(i => i.Role?.Name == "Admin")
            };

            return(Ok(response));
        }
예제 #10
0
        //呼叫service 利用authoID查詢autho資料
        public AuthorizationPresentationModel SearchDataByAuthoID()
        {
            AuthorizationPresentationModel authoPresentModel = new AuthorizationPresentationModel();

            if (this._authoModel.GetAuthoID() == null || this._authoModel.GetAuthoID() == "")
            {
                MessageBox.Show("請輸入權限ID");
            }
            else
            {
                //MessageBox.Show("yes");
                _authoService = new AuthorizationService(this._authoModel);
                _authoModel   = _authoService.searchByAuthoID();

                authoPresentModel.SetAuthoID(_authoModel.GetAuthoID());
                authoPresentModel.SetAuthoName(_authoModel.GetAuthoName());
                authoPresentModel.SetAuthoValue(_authoModel.GetAuthoValue());

                if (_authoModel.GetAuthoName() == null || _authoModel.GetAuthoName() == "")
                {
                    MessageBox.Show("此權限ID不存在!");
                    //MessageBox.Show(_authoModel.GetAuthoID());
                    authoPresentModel.SetAuthoID(null);
                }
            }
            return(authoPresentModel);
        }
예제 #11
0
        public ActionResult Authorize(string appId, string responseType, string scope, string state, string callBack)
        {
            if (string.IsNullOrEmpty(responseType))
            {
                responseType = "code";
            }
            if (string.IsNullOrEmpty(scope))
            {
                scope = "base_info";
            }
            if (!this.HttpContext.User.Identity.IsAuthenticated)
            {
                return(this.RedirectToAction("login", new
                {
                    returnUrl = $"/Connect/Authorize?appId={appId}&responseType={responseType}&scope={scope}&state={state}&callBack={callBack}"
                }));
            }

            AuthorizationModel model = new AuthorizationModel()
            {
                AppId        = appId,
                ResponseType = responseType,
                Scope        = scope,
                CallBack     = callBack,
                State        = state,
            };

            if (scope == "base_info")
            {
                return(Authorize(model));
            }
            return(View(model));
        }
예제 #12
0
        private async Task <IdentityModel> GetAuthorizedData(AuthorizationModel authorizationModel)
        {
            var identityModel = new IdentityModel
            {
                Auth = authorizationModel
            };

            using (var httpClient = new HttpClient())
            {
                var authorization = new
                {
                    authorization_code = authorizationModel.Code,
                    code_verifier      = authorizationModel.CodeVerifier,
                    client_id          = _config.GetValue <string>("MeuIDCredentials:ClientId"),
                    client_secret      = _config.GetValue <string>("MeuIDCredentials:ClientSecret"),
                    grant_type         = "authorization_code"
                };

                var authorizationContent = new StringContent(
                    JsonSerializer.Serialize(authorization), Encoding.UTF8, "application/json");

                var token = await GetAccessToken(httpClient, authorizationContent);

                if (!string.IsNullOrEmpty(token.AccessToken))
                {
                    identityModel = await GetUserData(identityModel, httpClient, token);
                }
            }

            return(identityModel);
        }
        public ViewResult MaterialType(string code, string state)
        {
            try
            {
                var util  = new GetOpenIdUtil(WeixinSetting);
                var model = util.GetOpenId(code);
                var url   = $"{BaseUrl}Agent/ExistAgentByOpenID?openid={model.openid}";
                var task  = url.GetStringAsync();

                //var openIdExist= HttpHelper.HttpGetRequest(url);
                var result = JsonConvert.DeserializeObject <AuthModel>(task.Result);
                //ViewData["e"] = openIdExist;

                //return View("~/Views/material/Index.cshtml");
                if (result.Code.Equals("200"))
                {
                    ViewData["openId"] = model.openid;
                    var materialModel = new Material {
                        ID = 0, Level = 0, ProduceTypeId = 0
                    };
                    return(View(materialModel));
                }
                var authModel = new AuthorizationModel {
                    RedirectController = "Material", RedirectAction = "AuthMaterialType", OpenId = model.openid
                };
                return(View("~/Views/Authorization/Authorization.cshtml", authModel));
            }
            catch (Exception e) {
                ViewData["e"] = e.Message;
                return(View("~/Views/material/Index.cshtml"));
            }
        }
        public ActionResult AuthorizationItemEdit(int authorizationId, AuthorizationModel authorizationModel)
        {
            try
            {
                var authorizationItems = RoleModuleService.GetAll(authorizationId);
                foreach (var authorizationItem in authorizationItems)
                {
                    RoleModuleService.DeleteReal(authorizationItem.Id);
                }

                var newItems = authorizationModel.RoleModules?.ToList();
                if (newItems != null)
                {
                    foreach (var item in newItems)
                    {
                        var a = new RoleModule
                        {
                            RoleId   = authorizationId,
                            ModuleId = item
                        };
                        RoleModuleService.Add(a);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error("Hata oluştu - " + new StackTrace().GetFrame(0).GetMethod().Name, e);
            }
            return(RedirectToAction("AuthorizationList"));
        }
        public IActionResult Authorize(AuthorizationModel authorizationModel)
        {
            try
            {
                var response = new AuthorizationResponseModel();

                var user = GetUsers().FirstOrDefault(u => u.Login == authorizationModel.Login);

                if (user == null)
                {
                    return(Ok(response));
                }

                response.IsKnownUser = true;

                if (user.Password != authorizationModel.Password)
                {
                    return(Ok(response));
                }

                response.IsAuthorized = true;
                response.Role         = user.Role;

                return(Ok(response));
            }
            catch (Exception exception)
            {
                return(BadRequest(exception));
            }
        }
예제 #16
0
        public async Task <QuoteViewModel> GetEntityById(
            int?Id, AuthorizationModel model = null)
        {
            var viewModel = new QuoteViewModel();

            PopulateDropDowns(viewModel);

            if (Id > 0)
            {
                var entity = await _context.Quote
                             .IgnoreQueryFilters()
                             .Include(a => a.QuoteStatus)
                             .Include(a => a.QuoteUser)
                             .Include(a => a.QuoteDetails).ThenInclude(a => a.Subscriptions)
                             .Include(a => a.QuoteDetails).ThenInclude(a => a.SubscriptionTypeRuleAudit.SubscriptionTypeRule.SubscriptionType)
                             .Include(a => a.OrderDetails).ThenInclude(a => a.ProductSize.Product)
                             .FirstOrDefaultAsync(a => a.Id == Id);

                viewModel = entity.ToViewModel(viewModel);

                viewModel.PayFast = entity.ToPayFastViewModel(viewModel.TotalAmount
                                                              , new SaveResult());
            }

            viewModel.QuoteStatuses = _quoteStatusBL.GetEntityList();
            return(viewModel);
        }
예제 #17
0
        private async void Login_Click(object sender, RoutedEventArgs e)
        {
            var model = new AuthorizationModel()
            {
                username = Login.Text,
                password = Password.Password
            };

            if (!validator.IsModelValid(model))
            {
                Error_list.Content = validator.ValidationResults;
                return;
            }

            await Context.Authorization(model);

            if (Context.IsAuthorized)
            {
                ((App)Application.Current).FinishAuthorization();
                this.Close();
            }
            else
            {
                Error_list.Content = "Authorization has failed. Check if login and password had been inputed correctly";
            }
        }
예제 #18
0
        public async Task <WinnerViewModel> GetEntityById(
            int?Id, AuthorizationModel model = null)
        {
            var viewModel = new WinnerViewModel();

            PopulateDropDowns(viewModel);

            if (Id > 0)
            {
                var entity = await _context.Winner
                             .IgnoreQueryFilters()
                             .Include(c => c.FinYear)
                             .Include(c => c.Award.Gender)
                             .Include(c => c.Member.Person)
                             .Include(c => c.Award.Frequency)
                             .Include(c => c.CalendarMonth)
                             .Include(c => c.Award.Gender)
                             .FirstOrDefaultAsync(a => a.Id == Id);

                if (entity != null)
                {
                    entity.ToViewModel(viewModel);
                    viewModel.Awards  = _awardBL.GetSelectListItems_byFrequencyId(entity.Award.FrequencyId);
                    viewModel.Members = _context.Member.Include(a => a.Person).Where(a => a.Person.GenderId == entity.Award.GenderId).ToSelectListItem(a => a.Person.FullName, x => x.Id.ToString());
                }
            }
            return(viewModel);
        }
예제 #19
0
        public static async Task <AuthorizationModel> RefreshExpiredToken(string refreshToken)
        {
            string url        = $"https://www.strava.com/oauth/token";
            var    postValues = new Dictionary <string, string> {
                { "client_id", ClientInfo.myClientId },
                { "client_secret", ClientInfo.myClientSecret },
                { "grant_type", "refresh_token" },
                { "refresh_token", refreshToken }
            };

            var content = new FormUrlEncodedContent(postValues);

            Console.WriteLine("Refreshing Expired Token");
            Console.WriteLine(content);
            using (var response = await client.PostAsync(url, content))
            {
                Console.WriteLine("Status Code: " + response.StatusCode);
                // build status code to meet our needs
                if (response.StatusCode.ToString() == "OK")
                {
                    AuthorizationModel result = await response
                                                .Content
                                                .ReadAsAsync <AuthorizationModel>();

                    return(result);
                }
                else
                {
                    throw new Exception(response.ReasonPhrase);
                }
            }
        }
예제 #20
0
        public async Task <SystemDocumentViewModel> GetEntityById(
            int?Id, AuthorizationModel model = null)
        {
            var viewModel = new SystemDocumentViewModel {
            };

            PopulateDropDowns(viewModel);

            if (Id > 0)
            {
                var entity = await _context.SystemDocument
                             .Include(a => a.Document.DocumentType)
                             .Include(a => a.FinYear)
                             .IgnoreQueryFilters()

                             .Include(c => c.Document)
                             .FirstOrDefaultAsync(a => a.Id == Id);

                if (entity != null)
                {
                    entity.ToViewModel(viewModel);
                    //viewModel.SystemDocumentSizes = entity.SystemDocumentSizes.ToSelectListItem(x => x.Size.ShortName, x => x.SizeId.ToString());
                }
            }
            return(viewModel);
        }
        public async Task <IActionResult> Post([FromBody] AuthorizationModel authorization)
        {
            try
            {
                if (authorization == null)
                {
                    throw new Exception("Missing parameter (authorization)!");
                }

                var value = await this._Dao.Create(authorization);

                return(Created($"authorization/{value.IdMenu}/{value.IdRole}", value));
            }
            catch (Exception ex)
            {
                switch (ex.InnerException)
                {
                case Exception exception:
                    return(BadRequest(exception.Message));

                // Not InnerException
                default:
                    return(NoContent());
                }
            }
        }
예제 #22
0
        public IActionResult OrderList(string code)
        {
            var util  = new GetOpenIdUtil(WeixinSetting);
            var model = util.GetOpenId(code);

            //验证openId是否存在接口
            var url = $"{Setting.BaseUrl}WeChat/Openid?Openid={model.openid}";

            var task   = url.GetStringAsync();
            var result = JsonConvert.DeserializeObject <AuthModel>(task.Result);

            if (result.result == 0)
            {
                ViewData["openId"] = model.openid;
                return(View());
            }

            var authorizationModel = new AuthorizationModel {
                RedirectController = "Order", RedirectAction = "AuthOrderList", OpenId = model.openid
            };

            return(RedirectToAction("Authorization", "Authorization", authorizationModel));

            //ViewData["openId"] = model.openid;
            //var authorizationModel = new AuthorizationModel { RedirectController = "Order", RedirectAction = "AuthOrderList" };
            //return View("~/Views/Authorization/Authorization.cshtml", authorizationModel);
        }
 public ActionResult AuthorizationEdit(int authorizationId, AuthorizationModel authorizationModel)
 {
     try
     {
         if (authorizationId == 0)
         {
             var item = new Role
             {
                 Name        = authorizationModel.Role.Name,
                 Description = authorizationModel.Role.Description,
             };
             RoleService.Add(item);
             Logger.Info(CurrentUser.Id + " idli kullanıcı " + item.Id + " idli yetki grubunu ekledi");
         }
         else
         {
             var item = RoleService.Get(authorizationId);
             item.Name        = authorizationModel.Role.Name;
             item.Description = authorizationModel.Role.Description;
             RoleService.Update(item);
             Logger.Info(CurrentUser.Id + " idli kullanıcı " + item.Id + " idli yetki grubunu güncelledi");
         }
     }
     catch (Exception e)
     {
         Logger.Error("Hata oluştu - " + new StackTrace().GetFrame(0).GetMethod().Name, e);
     }
     return(RedirectToAction("AuthorizationList"));
 }
예제 #24
0
        public async Task <MemberStagingViewModel> GetEntityById(
            int?Id, AuthorizationModel model = null)
        {
            var viewModel = new MemberStagingViewModel {
            };

            PopulateDropDowns(viewModel);

            if (Id > 0)
            {
                var test   = _context.MemberStaging.FirstOrDefault();
                var entity = await _context.MemberStaging
                             .Include(c => c.Address)
                             .Include(c => c.Address.Suburb.Town.City.Province.Country)
                             .Include(c => c.CreatedUser)
                             .Include(c => c.Country)
                             .Include(c => c.UpdatedUser)
                             .Include(c => c.CreatedUser)
                             .FirstOrDefaultAsync(a => a.Id == Id);

                if (entity != null)
                {
                    entity.ToViewModel(viewModel);

                    viewModel.Address = entity.Address.ToViewModel(new AddressViewModel());

                    viewModel.Address.Cities = this._context.City.Where(a => a.ProvinceId == viewModel.Address.CountryId).ToSelectListItem(a => a.Name, x => x.Id.ToString());
                }
            }
            return(viewModel);
        }
예제 #25
0
        public async Task <CalendarViewModel> GetEntityById(
            int?Id, AuthorizationModel model = null)
        {
            var viewModel = new CalendarViewModel {
                ScheduleDate = DateTime.Now
            };

            PopulateDropDowns(viewModel);

            if (Id > 0)
            {
                var entity = await _context.Calendar
                             .IgnoreQueryFilters()
                             .Include(c => c.Event)
                             .Include(c => c.FinYear)
                             .Include(c => c.Venue)
                             .Include(c => c.TimeTrials)
                             .Include(c => c.Moderators)
                             .FirstOrDefaultAsync(a => a.Id == Id);

                if (entity != null)
                {
                    entity.ToViewModel(viewModel);
                }
            }
            return(viewModel);
        }
예제 #26
0
        public async Task <IActionResult> Authorization(AuthorizationModel authorizationModel)
        {
            if (ModelState.IsValid)
            {
                var user = await _databaseContext.Users.Where(u => u.Email == authorizationModel.Email)
                           .AsNoTracking()
                           .FirstOrDefaultAsync();

                if (user == null)
                {
                    ModelState.AddModelError(
                        nameof(AuthorizationModel.Email),
                        _localizer["Користувача зі вказаною адресою електронної пошти не знайдено!"].Value
                        );
                }
                else if (user.IsBanned)
                {
                    ModelState.AddModelError(
                        nameof(AuthorizationModel.Email),
                        _localizer["Ваш обліковий запис було заблоковано за порушення умов роботи з системою!"].Value
                        );
                }
                else
                {
                    var signInResult = await _signInManager.PasswordSignInAsync(
                        user,
                        authorizationModel.Password,
                        authorizationModel.RememberMe,
                        false
                        );

                    if (signInResult.IsLockedOut)
                    {
                        ModelState.AddModelError(
                            nameof(AuthorizationModel.Email),
                            _localizer["Ваш обліковий запис тимчасово відключено через значну кількість спроб авторизації у системі! Повторіть спробу авторизації через деякий час та проінформуйте вашого куратора."].Value
                            );
                    }
                    else if (signInResult.Succeeded)
                    {
                        if (!string.IsNullOrWhiteSpace(authorizationModel.ReturnUrl) &&
                            Url.IsLocalUrl(authorizationModel.ReturnUrl))
                        {
                            return(LocalRedirect(authorizationModel.ReturnUrl));
                        }

                        return(RedirectToAction("Home", "Welcome"));
                    }
                    else
                    {
                        ModelState.AddModelError(
                            nameof(AuthorizationModel.Email),
                            _localizer["Перевірте правильність введеної вами інформації! Можливо, вам слід скористатися сервісом відновлення доступу до системи?"].Value
                            );
                    }
                }
            }

            return(View(ViewsDirectoryPath + "Authorization.cshtml", authorizationModel));
        }
예제 #27
0
        public void ExecuteAuthotizationCommand(object parameter)
        {
            AuthorizationModel authorization = new AuthorizationModel(LoginAndPassword.Login, LoginAndPassword.Password);

            if (!authorization.CheckLogin())
            {
                _dialogManager.ShowMessage($"Пользователя с логином {LoginAndPassword.Login}не существует");
                LoginAndPassword.Login    = null;
                LoginAndPassword.Password = null;
                return;
            }

            if (!authorization.CheckAccessLevel())
            {
                _dialogManager.ShowMessage("Недостаточно прав для входа в приложение");
                LoginAndPassword.Login    = null;
                LoginAndPassword.Password = null;
                return;
            }


            if (!authorization.CheckPassword())
            {
                _dialogManager.ShowMessage("Неправильный пароль");
                LoginAndPassword.Password = null;
                return;
            }
            _user = authorization.GetUser;
            GoNext();
        }
        public JsonResult RefreshAccessToken(string refreshToken, string clientId, string clientSecret, string serverUrl)
        {
            string json = string.Empty;

            if (ModelState.IsValid &&
                !string.IsNullOrEmpty(refreshToken) &&
                !string.IsNullOrEmpty(clientId) &&
                !string.IsNullOrEmpty(clientSecret) &&
                !string.IsNullOrEmpty(serverUrl))
            {
                var model = new AccessModel();

                try
                {
                    var authParameters = new AuthParameters()
                    {
                        ClientId     = clientId,
                        ClientSecret = clientSecret,
                        ServerUrl    = serverUrl,
                        RefreshToken = refreshToken,
                        GrantType    = "refresh_token"
                    };

                    var nopAuthorizationManager = new AuthorizationManager(authParameters.ClientId,
                                                                           authParameters.ClientSecret, authParameters.ServerUrl);

                    string responseJson = nopAuthorizationManager.RefreshAuthorizationData(authParameters);

                    AuthorizationModel authorizationModel =
                        JsonConvert.DeserializeObject <AuthorizationModel>(responseJson);

                    model.AuthorizationModel = authorizationModel;
                    model.UserAccessModel    = new UserAccessModel()
                    {
                        ClientId  = clientId,
                        ServerUrl = serverUrl
                    };

                    // Here we use the temp data because this method is called via ajax and here we can't hold a session.
                    // This is needed for the GetCustomers method in the CustomersController.
                    TempData["accessToken"] = authorizationModel.AccessToken;
                    TempData["serverUrl"]   = serverUrl;
                }
                catch (Exception ex)
                {
                    json = string.Format("error: '{0}'", ex.Message);

                    return(Json(json, JsonRequestBehavior.AllowGet));
                }

                json = JsonConvert.SerializeObject(model.AuthorizationModel);
            }
            else
            {
                json = "error: 'something went wrong'";
            }

            return(Json(json, JsonRequestBehavior.AllowGet));
        }
예제 #29
0
        public async Task <TokenModel> GenerateToken(AuthorizationModel authorization)
        {
            var token   = TokenModel.Create(authorization);
            var content = JsonConvert.SerializeObject(token);
            await _database.HashSetAsync(GetHashId() + authorization.UserName, authorization.UserName, content);

            return(token);
        }
        private bool IsValidUser(AuthorizationModel model)
        {
            var user = _userRepository.GetByUsername(model.Username);

            return
                (model.Username == user.Username &&
                 _hashHelper.GetHashAsString(model.Password) == user.Password);
        }