public void Show_LoginWin(object sender, RoutedEventArgs e)
        {
            if (Properties.Settings.Default.logged)
            {
                Properties.Settings.Default.logged   = false;
                Properties.Settings.Default.remember = false;
                Properties.Settings.Default.Id       = 0;
                Properties.Settings.Default.NickName = "";
                Properties.Settings.Default.Token    = "";
                Properties.Settings.Default.Save();
                ApiRequests.client.DefaultRequestHeaders.Remove("Auth-token");

                user = null;
                nickNameLabel.Content = "Guest";
            }
            else
            {
                logWin       = new LoginWin();
                logWin.Owner = this;
                logWin.ShowDialog();
                if (Properties.Settings.Default.logged)
                {
                    user = new UserAuthenticated(Properties.Settings.Default.Id, Properties.Settings.Default.NickName, Properties.Settings.Default.Token);
                    nickNameLabel.Content = user.NickName;
                }
            }
        }
        private async void Login_Click(object sender, RoutedEventArgs e)
        {
            string nickname = nickNameLoginBox.Text;
            string password = passwordLoginBox.Password;
            bool   remember = (bool)rememberBtn.IsChecked;

            LoginForm loginForm = new LoginForm(nickname, password);

            HttpResponseMessage httpResponse = await ApiRequests.Login(loginForm);

            if (httpResponse.StatusCode == HttpStatusCode.OK)
            {
                UserAuthenticated user = await httpResponse.Content.ReadAsAsync <UserAuthenticated>();

                Finish_Login(user, remember);
            }
            else if (httpResponse.StatusCode == HttpStatusCode.BadRequest)
            {
                nickNameLoginBox.BorderBrush = Brushes.Red;
                passwordLoginBox.BorderBrush = Brushes.Red;
                string msgResponse = await httpResponse.Content.ReadAsStringAsync();

                Process_Error(msgResponse);
            }
            else
            {
                string msgResponse = "There is problem with server connection. Try again later.";
                Process_Error(msgResponse);
            }
        }
        private void SetUserFSS(ref UserAuthenticated userAuth, int empID)
        {
            DateTime today = DateTime.UtcNow.ToUtcID();

            IRepository <FSS> repoFSS = _unitOfWork.GetRepository <FSS>();

            repoFSS.Condition = PredicateBuilder.True <FSS>().And(x => x.NIK == empID && x.ValidTo >= today);

            FSS fss = repoFSS.Find().FirstOrDefault();

            if (fss == null)
            {
                return;
            }

            bool allowByNIK = false;

            userAuth.IsRoleValid = true;
            userAuth.NIK         = fss.NIK;
            userAuth.Fullname    = fss.FullName;
            if (fss.UploadValidTo != null)
            {
                if (fss.UploadValidTo.Value.Date >= today.Date)
                {
                    allowByNIK = true;
                }
            }
            //userAuth.IsAbleToWrite = fss.AllowedByNIK == null ? false : true;
            userAuth.IsAbleToWrite = allowByNIK;
        }
Exemple #4
0
        public async Task <int> UpdateNameChannel(UpdateNameChannel request)
        {
            var user = await _userManager.FindByEmailAsync(request.Email);

            if (user != null)
            {
                var names = request.Name.Split(' ');
                user.FirtsName = names[0];
                if (names.Length == 1)
                {
                    user.LastName = "";
                }
                else
                {
                    user.LastName = "";
                    for (var i = 1; i < names.Length; i++)
                    {
                        user.LastName += names[i] + " ";
                    }
                }

                //Update user in list static of system
                UserAuthenticated.UpdateNameChannel(user);

                var ntService = await _notificationService.UpdateNameChannel(user.Id, request.Name.Trim());

                var msService = await _messageService.UpdateNameChannel(user.Id, request.Name.Trim());

                _context.Update(user);
                return(await _context.SaveChangesAsync());
            }
            return(-1);
        }
        public async Task <IActionResult> Logout()
        {
            UserAuthenticated.LogOutUser(User.Identity.Name);
            await _signInManager.SignOutAsync();

            return(Redirect("Index"));
        }
        public async Task <IActionResult> SearchVideo(int?page, string nameSearch)
        {
            ViewBag.nameSearch = nameSearch;
            var user = UserAuthenticated.GetUser(User.Identity.Name);

            if (user != null)
            {
                ViewBag.IdUser     = user.Id;
                ViewBag.PlayList   = _playListService.GetAll().Where(x => x.UserId == ViewBag.IdUser).ToList();
                ViewBag.UserFollow = _userService.GetUserFollow(user.UserName);
            }
            else
            {
                ViewBag.UserFollow = _userService.GetChannel();
            }

            GetNotificationHome();
            if (page == null)
            {
                page = 1;
            }
            var pageNumber   = page ?? 1;
            var pageSize     = 5;
            var listVideo_Vm = GetSearchVideo_vm(nameSearch).OrderByDescending(x => x.Id).ToList();

            return(View(await listVideo_Vm.ToPagedListAsync(pageNumber, pageSize)));
        }
        private void SetUserBUM(ref UserAuthenticated userAuth, int empID)
        {
            DateTime today = DateTime.UtcNow.ToUtcID();

            IRepository <BUM> repoBUM = _unitOfWork.GetRepository <BUM>();

            repoBUM.Condition = PredicateBuilder.True <BUM>().And(x => x.NIK == empID && x.ValidTo >= today);

            BUM bum = repoBUM.Find().FirstOrDefault();

            if (bum == null)
            {
                return;
            }

            userAuth.IsRoleValid = true;
            userAuth.NIK         = bum.NIK;
            userAuth.Fullname    = bum.FullName;

            if (RoleCode.RM.Equals(bum.Role))
            {
                userAuth.RoleCode = RoleCode.RM;
            }
            else if (RoleCode.BUM.Equals(bum.Role))
            {
                userAuth.RoleCode = RoleCode.BUM;
            }
            else
            {
                userAuth.IsRoleValid = false;
            }
        }
Exemple #8
0
 public ScheduleItemComment(string body, DateTime created, UserAuthenticated creator, long creatorIP, string creatorUserAgent, Guid id, Language language, DateTime modified, ScheduleItemCommentSmall parent, ScheduleItemSmall scheduleItem, string slug, EntityState state)
     : base(body, created, creator, creatorIP, creatorUserAgent, id, language, modified, null, state)
 {
     Parent       = parent;
     ScheduleItem = scheduleItem;
     Slug         = slug;
 }
        public IActionResult Login([FromBody] UserLogin item)
        {
            if (string.IsNullOrWhiteSpace(item.Username) || string.IsNullOrWhiteSpace(item.Password))
            {
                return(BadRequest("Please enter in your Username and Password"));
            }

            // Get the User and Authenticate
            User user = _userRepository.GetAllQuery()
                        .Where(x => x.Username.Equals(item.Username))
                        .FirstOrDefault();

            if (user != null)
            {
                if (_authenticationService.VerifyPassword(item.Password, user.Password_Hash))
                {
                    UserAuthenticated authenticatedUser = new UserAuthenticated();
                    authenticatedUser.ID        = user.ID;
                    authenticatedUser.Username  = user.Username;
                    authenticatedUser.AuthToken = user.AuthToken;
                    return(new ObjectResult(authenticatedUser));
                }
            }

            // Run the hashing algorithm a couple times to make it harder to determine partial success/failure based off of Server Response Times
            // In addition to slowing down brute force attempts
            for (int i = 0; i < 3; i++)
            {
                _authenticationService.FakeHash();
            }
            return(BadRequest("Either your username or password is invalid. Please try again."));
        }
        public IActionResult Popular(int?page)
        {
            var user = UserAuthenticated.GetUser(User.Identity.Name);

            if (user != null)
            {
                ViewBag.UserFollow = _userService.GetUserFollow(user.UserName);
                ViewBag.IdUser     = user.Id;
                ViewBag.PlayList   = _playListService.GetAll().Where(x => x.UserId == ViewBag.IdUser).ToList();
            }
            else
            {
                ViewBag.UserFollow = _userService.GetChannel();
            }
            ViewBag.ForCus = 1;
            GetNotificationHome();
            if (page == null)
            {
                page = 1;
            }
            int pageNumber = page ?? 1;
            int pageSize   = 5;
            var listVideo  = _videoService.GetAll().OrderByDescending(x => x.ViewCount).
                             Where(x => x.ViewCount > 0).ToList();
            var listUser     = _userService.GetAll();
            var listvideo_vm = _videoService.GetVideo_Vm(listVideo, listUser).ToPagedList(pageNumber, pageSize);

            return(View(listvideo_vm));
        }
        public async Task <IActionResult> VerifyEmail(string userId, string token, int check)
        {
            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(BadRequest());
            }
            token = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(token));
            var result = await _userManager.ConfirmEmailAsync(user, token);

            if (result.Succeeded)
            {
                if (check == 1 || check == 2)
                {
                    //Check user authenticated

                    UserAuthenticated.checkUserAuthenticated(user);
                    //--- end
                    ViewBag.Flag          = true;
                    ViewBag.InfoUserLogin = user;
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    await _userManager.AddToRoleAsync(user, "User");

                    return(View());
                }
                if (check == 3)
                {
                    ViewBag.Flag = false;
                    return(View(user));
                }
            }
            return(BadRequest());
        }
Exemple #12
0
 public PostComment(string body, DateTime created, UserAuthenticated creator, long creatorIP, string creatorUserAgent, Guid id, Language language, DateTime modified, PostCommentSmall parent, PostSmall post, string slug, EntityState state)
     : base(body, created, creator, creatorIP, creatorUserAgent, id, language, modified, null, state)
 {
     Parent = parent;
     Post   = post;
     Slug   = slug;
 }
        public static UserAuthenticated GetUser(this IUserService userService, string name, string password)
        {
            UserAuthenticated user = userService.GetUser(name);

            if (user != null)
            {
                string data = userService.GetModuleData(user.ID, "FormsAuthentication");

                if (data != null)
                {
                    string[] splitData = data.Split('|');

                    if (splitData.Length != 2)
                    {
                        throw new InvalidOperationException("Password and PasswordSalt could not be read from module data");
                    }

                    string userPasswordSalt = splitData[0];
                    string userPassword     = splitData[1];

                    if (userPassword == password.SaltAndHash(userPasswordSalt))
                    {
                        return(user);
                    }
                }
            }

            return(null);
        }
Exemple #14
0
        public UserViewModel(IUser user)
        {
            this.user = user;

            if (user is UserAnonymous)
            {
                userAnonymous = (UserAnonymous)user;

                DisplayName = user.Name;
                Email       = userAnonymous.Email;
                EmailHash   = userAnonymous.EmailHash;
                Url         = userAnonymous.Url;
            }
            else if (user is UserAuthenticated)
            {
                userAuthenticated = (UserAuthenticated)user;

                DisplayName = userAuthenticated.DisplayName;
                Email       = userAuthenticated.Email;
                EmailHash   = userAuthenticated.EmailHash;
                Url         = "";
            }
            else if (user is UserUnregistered)
            {
                userUnregistered = (UserUnregistered)user;

                DisplayName = "";
                Email       = "";
                EmailHash   = "";
                Url         = "";
            }
        }
Exemple #15
0
        private void SetUserNSM(ref UserAuthenticated userAuth, int empID)
        {
            DateTime today = DateTime.UtcNow.ToUtcID();

            IRepository <NSM> repoNSM = _unitOfWork.GetRepository <NSM>();

            repoNSM.Condition = PredicateBuilder.True <NSM>().And(x => x.NIK == empID && x.ValidTo >= today);

            NSM nsm = repoNSM.Find().FirstOrDefault();

            if (nsm == null)
            {
                return;
            }

            userAuth.IsRoleValid = true;
            userAuth.NIK         = nsm.NIK;
            userAuth.Fullname    = nsm.FullName;

            if (nsm.Plant != null)
            {
                // set as kacab
                userAuth.RoleCode = RoleCode.KaCab;
                userAuth.Plant    = nsm.Plant;
            }
        }
        public IActionResult GetAllPlayList(int id, string nameSearch = null)
        {
            var user = UserAuthenticated.GetUser(User.Identity.Name);

            if (id != 0)
            {
                var playlist  = _detailService.GetAll().Where(x => x.PlayListId == id).ToList();
                var listVideo = (from plist in playlist
                                 join lvideo in _videoService.GetAll() on plist.VideoId equals lvideo.Id
                                 where lvideo.HidenVideo
                                 select lvideo).ToList();
                if (nameSearch != null)
                {
                    nameSearch = ConvertUnSigned.convertToUnSign(nameSearch).ToLower().Trim();
                    listVideo  = listVideo.Where(x => ConvertUnSigned.convertToUnSign(x.Name).
                                                 ToLower().Trim().Contains(nameSearch)).ToList();
                }

                if (listVideo.Count > 0)
                {
                    return(Content(JsonConvert.SerializeObject(_videoService.GetAllVideoPlayList(listVideo, user))));
                }
                else
                {
                    return(Content("null"));
                }
            }

            return(null);
        }
Exemple #17
0
        private void Login_Click(object sender, RoutedEventArgs e)
        {
            ToggleError(null);

            string name     = TextBox_Name.Text;
            string password = TextBox_Password.Password;

            try
            {
                AuthenticationModel authModel = NotesApi.GetAuthenticationModel(name, password);

                IRestResponse <UserDto> response = NotesApi.Execute <UserDto>("Authentication/Login", Method.POST, authModel);

                UserDto result = NotesApi.GetData(response);

                if (string.IsNullOrEmpty(result.Token))
                {
                    throw new Exception("Failed to login");
                }

                UserAuthenticated?.Invoke(this, new AuthenticationEventArgs
                {
                    User = result
                });
            }
            catch (Exception x)
            {
                ToggleError(x.Message);
            }
        }
Exemple #18
0
        void IExceptionFilter.OnException(ExceptionContext context)
        {
            AccountBusiness business = new AccountBusiness();

            userAuth = business.GetUserAuth();

            if (userAuth != null)
            {
                context.Controller.ViewBag.UserAuth = userAuth;

                context.Result = new ViewResult
                {
                    ViewName = "~/Views/Error/Index500.cshtml",
                    TempData = context.Controller.TempData,
                    ViewData = context.Controller.ViewData
                };
            }
            else
            {
                business.Logout();

                var url = new UrlHelper(context.RequestContext);

                context.Controller.TempData["AlertMessage"] = new AlertMessage(StaticMessage.ERR_SESSION_EXPIRED);
                context.Result = new RedirectResult(url.Action("Login", "Account"));
            }

            context.ExceptionHandled = true;
        }
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            OxiteViewModel model = filterContext.Controller.ViewData.Model as OxiteViewModel;

            if (model != null)
            {
                UserAuthenticated user = model.User.ToUserAuthenticated();

                if (user != null)
                {
                    UserRegistration registration = pdc09Service.GetUserRegistration(user);
                    bool             isRegistered = registration.IsRegistered;

                    if (!isRegistered && (!registration.LastRegistrationCheck.HasValue || registration.LastRegistrationCheck.Value.AddMinutes(15) < DateTime.UtcNow))
                    {
                        using (RegistrationService.PDC09Service service = new RegistrationService.PDC09Service())
                        {
                            service.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["PDCRegistration.Username"], ConfigurationManager.AppSettings["PDCRegistration.Password"]);

                            try
                            {
                                isRegistered = service.IsRegistered((string)user.AuthenticationValues["PUID"]);
                            }
                            catch {}
                        }

                        pdc09Service.SetUserRegistration(user, isRegistered);
                    }

                    user.AuthenticationValues["IsRegistered"] = isRegistered;
                }
            }
        }
Exemple #20
0
 private void setupCreatorFields(UserAuthenticated creator)
 {
     CreatorUserID    = creator.ID;
     CreatorName      = !string.IsNullOrEmpty(creator.DisplayName) ? creator.DisplayName : creator.Name;
     CreatorEmail     = creator.Email;
     CreatorEmailHash = creator.EmailHash;
     CreatorUrl       = "";
 }
        public IActionResult GetSignedInUser()
        {
            UserAuthenticated user = new UserAuthenticated();

            user.Authenticated = User.Identity.IsAuthenticated;
            user.UserName      = User.Identity.Name;
            return(Ok(user));
        }
Exemple #22
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Trace.Write("(Controller)Action Executing: " +
                                                  filterContext.ActionDescriptor.ActionName);

            base.OnActionExecuting(filterContext);
            var url = new UrlHelper(filterContext.RequestContext);

            var viewBag = filterContext.Controller.ViewBag;

            AccountBusiness business = new AccountBusiness();

            try
            {
                userAuth = business.GetUserAuth();

                if (userAuth != null)
                {
                    if (!userAuth.IsActive)
                    {
                        business.Logout();

                        filterContext.Controller.TempData["AlertMessage"] = new AlertMessage(StaticMessage.ERR_USER_INACTIVE);
                        filterContext.Result = new RedirectResult(url.Action("Login", "Account"));
                    }
                    else if (!userAuth.IsRoleValid)
                    {
                        business.Logout();

                        filterContext.Controller.TempData["AlertMessage"] = new AlertMessage(StaticMessage.ERR_ROLE_INVALID);
                        filterContext.Result = new RedirectResult(url.Action("Login", "Account"));
                    }
                    else
                    {
                        viewBag.UserAuth = userAuth;

                        if (!IsModuleAllowed(userAuth.RoleCode))
                        {
                            filterContext.Controller.TempData["AlertMessage"] = new AlertMessage(StaticMessage.ERR_ACCESS_DENIED);
                            filterContext.Result = new RedirectResult(url.Action("Index", "Dashboard"));
                        }
                    }
                }
                else
                {
                    business.Logout();

                    filterContext.Controller.TempData["AlertMessage"] = new AlertMessage(StaticMessage.ERR_SESSION_EXPIRED);
                    filterContext.Result = new RedirectResult(url.Action("Login", "Account"));
                }
            }
            catch (Exception ex)
            {
                business.Logout();

                filterContext.Result = new RedirectResult(url.Action("Login", "Account"));
            }
        }
        public IActionResult VideoWatched()
        {
            var userLogin = UserAuthenticated.GetUser(User.Identity.Name);

            ViewBag.IdUser   = userLogin.Id;
            ViewBag.PlayList = _playListService.GetAll().Where(x => x.UserId == ViewBag.IdUser).ToList();
            GetNotificationHome();
            return(View());
        }
        public IActionResult MyPlayList()
        {
            GetNotificationHome();
            ViewBag.ForCus = 2;
            var user   = UserAuthenticated.GetUser(User.Identity.Name);
            var listvm = _detailService.GetDetailPlayList(user, null).OrderByDescending(x => x.Id).ToList();

            return(View(listvm.ToPagedList(1, 4)));
        }
Exemple #25
0
    private void HandleLogInSuccess(LoginResult response)
    {
        Logger.Instance.Log("Login  -   HandleLogInSuccess");
        var entityToken = response.EntityToken;

        this.playFabId = response.PlayFabId;
        this.entityId  = entityToken.Entity.Id;
        UserAuthenticated?.Invoke();
    }
        public async Task <IActionResult> ExternalCallback()
        {
            string email = null;
            var    info  = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(RedirectToAction("Login"));
            }
            if (info.LoginProvider == "Facebook")
            {
                email = info.Principal.Claims.ToArray()[1].Value;
            }
            else
            {
                email = info.Principal.Claims.ToArray()[4].Value;
            }
            // Sign in the user with this external login provider if the user already has a login.
            var users = await _userService.FindUser(email);

            if (users != null)
            {
                if (users.Status && users.LockoutEnabled)
                {
                    UserAuthenticated.checkUserAuthenticated(users);
                    await _signInManager.SignInAsync(users, isPersistent : false, info.LoginProvider);

                    return(RedirectToAction("Index"));
                }
                else
                {
                    if (users.LockoutEnabled == false)
                    {
                        return(Redirect("Login/?checkLock=1"));
                    }
                    if (users.Status == false)
                    {
                        return(Redirect("Login/?checkLock=2"));
                    }
                }
            }
            else
            {
                var user    = _userService.SetAttributeUser(info).Result;
                var result1 = await _userManager.CreateAsync(user);

                if (result1.Succeeded)
                {
                    GenerationTokenEmail(user, ConfirmEmailAccount.External.ToString());
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(Redirect("EmailVerification"));
                }
            }
            return(View());
        }
Exemple #27
0
        public async Task CopyContext(AzureContext sourceContext)
        {
            this.AzureEnvironment = sourceContext.AzureEnvironment;
            await this.SetTenantContext(sourceContext.AzureTenant);

            await this.SetSubscriptionContext(sourceContext.AzureSubscription);

            this.TokenProvider.AuthenticationResult = sourceContext.TokenProvider.AuthenticationResult;
            await UserAuthenticated?.Invoke(this);
        }
Exemple #28
0
 public ContentItem(Guid siteID, Guid pageID, string name, string displayName, string body, UserAuthenticated creator, DateTime?published)
 {
     Site        = new SiteSmall(siteID);
     Page        = pageID != Guid.Empty ? new Page(pageID) : null;
     Name        = name;
     DisplayName = displayName;
     Body        = body;
     Creator     = creator;
     Published   = published;
 }
Exemple #29
0
        public async Task CopyContext(AzureContext sourceContext)
        {
            this.AzureEnvironment = sourceContext.AzureEnvironment;
            await this.SetTenantContext(sourceContext.AzureTenant);

            await this.SetSubscriptionContext(sourceContext.AzureSubscription);

            this.LoginPromptBehavior = sourceContext.LoginPromptBehavior;
            await UserAuthenticated?.Invoke(this);
        }
Exemple #30
0
        public Post ToPost(EntityState state, UserAuthenticated creator, Func <string, string> normalizeTag)
        {
            List <PostTag> tags = new List <PostTag>(Tags.Count());

            foreach (string tagName in Tags)
            {
                tags.Add(new PostTag(normalizeTag(tagName), tagName));
            }

            return(new Post(new Blog(BlogName), Body, BodyShort, CommentingDisabled, creator, Published, Slug, state, tags, Title));
        }