Exemplo n.º 1
0
        public ActionResult Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = UserService.GetUserbyEmail(model.Email);

            if (user != null)
            {
                SetMessage("Lo sentimos, correo electrónico no disponible. Inténtelo de nuevo con uno distinto.", BootstrapAlertTypes.Danger);
                return(View(model));
            }

            var createdUser = UserService.CreateUser_And_MembershipAccount(model.Email, model.Password, model.UserName);

            if (createdUser == null)
            {
                SetMessage("Lo sentimos, ha ocurrido un error al intentar realizar el registro. Inténtelo de nuevo.", BootstrapAlertTypes.Success);
                return(View(model));
            }

            RoleService.AddUserToRole(model.Email, "Admin");
            //RoleService.AddUserToRole(model.Email, "Influencer");

            SetMessage("Registro exitoso. Se ha enviado un email de confirmación. Es necesario validar tu cuenta para poder iniciar sesión.", BootstrapAlertTypes.Success);
            return(RedirectToAction("Login", "Account"));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> AddUserToRole(AddToRoleModel model)
        {
            var userToRole = await _roleService.AddUserToRole(model);

            if (userToRole == null)
            {
                return(BadRequest(userToRole));
            }
            return(Ok(userToRole));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> AddUserToRole(AddToRoleDto model)
        {
            try
            {
                await _roleService.AddUserToRole(model);

                return(Ok());
            }
            catch (AppException ex)
            {
                return(BadRequest(new { message = ex.Message }));
            }
        }
Exemplo n.º 4
0
        public JsonResult AddUserProfile(string userName, string displayName, string password, string email, string systemAdmin, string entryAdmin, string pushAdmin, string viewAdmin)
        {
            WebSecurity.CreateUserAndAccount(userName, password, new { UserName = userName, DisplayName = displayName, Email = email, ReceiveEmail = true, StatusId = "StatusActive", UpdBy = Membership.GetUser().UserName, UpdAt = DateTime.Now, InsBy = Membership.GetUser().UserName, InsAt = DateTime.Now }, false);
            if (systemAdmin.Equals("true"))
            {
                _roleService.AddUserToRole(userName, Constant.Role.SystemAdmin);
            }
            if (entryAdmin.Equals("true"))
            {
                _roleService.AddUserToRole(userName, Constant.Role.EntryAdmin);
            }
            if (pushAdmin.Equals("true"))
            {
                _roleService.AddUserToRole(userName, Constant.Role.PushAdmin);
            }
            if (viewAdmin.Equals("true"))
            {
                _roleService.AddUserToRole(userName, Constant.Role.ViewAdmin);
            }

            return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 5
0
        public async Task <Response <NoDataDto> > ConfirmEmailAsync(UserConfirmEmailDto userConfirmEmailDto)
        {
            var user = await _userManager.FindByEmailAsync(userConfirmEmailDto.Email);

            if (await _securityService.IsValidCode(user.Id, userConfirmEmailDto.Code))
            {
                user.EmailConfirmed = true;
                var result = await _roleService.AddUserToRole(new AddUserToRoleDto { UserId = user.Id, RoleName = "Üye" });

                if (result.StatusCode < 205)
                {
                    _unitOfWork.Save();
                    return(Response <NoDataDto> .Success(200));
                }
                else
                {
                    return(Response <NoDataDto> .Fail("Lütfen daha sonra tekrar deneyiniz", 500));
                }
            }
            return(Response <NoDataDto> .Fail("Geçersiz email veya kod girdiniz.", 404));
        }
        public async Task <ApplicationUser> RegisterUSerByAdmin(RegisterAdminDto request)
        {
            return(await ProcessRequest(async() =>
            {
                if (request.Password != request.ConfirmPassword)
                {
                    throw new AppException(_logger, "ConfirmPassword  is not the same Password");
                }

                var userName = await _unitOfWork.User.FindByNameAsync(request.UserName);
                if (userName != null)
                {
                    throw new AppException(_logger, $"User Name: {request.UserName} is already taken");
                }

                var userEmail = await _unitOfWork.User.FindByEmailAsync(request.Email);
                if (userEmail != null)
                {
                    throw new AppException(_logger, $"User Email: {request.Email} is already taken");
                }

                if (!request.Dob.HasValue)
                {
                    throw new AppException(_logger, "Date of birth is required");
                }

                var user = _mapper.Map <ApplicationUser>(request);

                if (user == null)
                {
                    throw new AppException(_logger, "Register Failed");
                }

                byte[] passwordHash, passwordSalt;
                CreatePasswordHash(request.Password, out passwordHash, out passwordSalt);

                user.PasswordHash = passwordHash;
                user.PasswordSalt = passwordSalt;
                user.NormalizedUserName = request.UserName.ToUpper();
                user.NormalizedEmail = request.Email.ToUpper();
                user.SecurityStamp = Guid.NewGuid().ToString("D");

                await _unitOfWork.User.CreateAsync(user);

                var claims = new List <Claim>()
                {
                    new Claim(ClaimTypes.GivenName, request.FirstName),
                    new Claim(ClaimTypes.Surname, request.LastName),
                    new Claim(ClaimTypes.Email, request.Email)
                };

                foreach (var claim in claims)
                {
                    var userClaim = new ApplicationUserClaim()
                    {
                        UserId = user.Id,
                        ClaimType = claim.Type,
                        ClaimValue = claim.Value
                    };

                    await _unitOfWork.UserClaim.CreateAsync(userClaim);
                }

                await _unitOfWork.SaveAsync();
                var listRoleModel = new ArrayList();

                if (request.ListRoleName == null)
                {
                    var role = new AddToRoleDto()
                    {
                        RoleName = "USER",
                        UserName = request.UserName
                    };
                    await _roleService.AddUserToRole(role);
                }
                else
                {
                    foreach (var role in request.ListRoleName)
                    {
                        var roleModel = new AddToRoleDto()
                        {
                            UserName = request.UserName,
                            RoleName = role
                        };
                        listRoleModel.Add(roleModel);
                    }
                }

                if (listRoleModel == null)
                {
                    throw new AppException(_logger, "Add Role Failed");
                }
                foreach (AddToRoleDto roleModel in listRoleModel)
                {
                    await _roleService.AddUserToRole(roleModel);
                }

                return user;
            }));
        }
Exemplo n.º 7
0
        public ActionResult SaveUserChanges()
        {
            var response = new JsonResponse();

            response.Message = "";

            var checkboxstring = Request["cbString"];

            string[] arrUserNameRoleName;
            string[] arrUserName   = null;
            string[] arrRoleName   = null;
            string[] arrUserStatus = null;
            string[] arrItem;
            var      count = 0;

            try
            {
                if (checkboxstring != "")
                {
                    checkboxstring      = checkboxstring.Substring(0, checkboxstring.Length - 1);
                    arrUserNameRoleName = checkboxstring.Split('#');

                    arrUserName   = new string[arrUserNameRoleName.Count()];
                    arrRoleName   = new string[arrUserNameRoleName.Count()];
                    arrUserStatus = new string[arrUserNameRoleName.Count()];

                    foreach (string item in arrUserNameRoleName)
                    {
                        arrItem = item.Split('_');

                        arrUserName[count]   = arrItem[0];
                        arrRoleName[count]   = arrItem[1];
                        arrUserStatus[count] = arrItem[2];
                        count++;
                    }

                    //check user and theire roles...
                    for (int i = 0; i < arrUserName.Count(); i++)
                    {
                        if (arrUserName[i] == "krishna")
                        {
                            //check,is user already in this role...
                            if (roleService.IsUserInRole(arrUserName[i], arrRoleName[i]))
                            {
                                //if user already exists in this role,then remove this user role...
                                roleService.RemoveUserFromRole(arrUserName[i], arrRoleName[i]);
                            }

                            //add role for user,if particular checkbox is checked...
                            if (arrUserStatus[i] == "checked")
                            {
                                roleService.AddUserToRole(arrUserName[i], arrRoleName[i]);
                            }
                        }
                    }

                    response.Message = "Save Changes Successfully";
                    return(Json(response));
                }

                return(Json(response));
            }
            catch (Exception)
            {
                return(Json(response));
            }
        }
        public ActionResult Create(OrganisationEditModel editModel)
        {
            try
            {
                sw.Organisation organisation = editModel.org;
                if (NameExist(organisation.Name))
                {
                    ModelState.AddModelError("Name", "Employer Name Already exist");
                }

                if (ModelState.IsValid)
                {
                    var applNoResp = generateEmployerNumber(organisation.Name, organisation.CommencementDate ?? DateTime.Now);
                    if (applNoResp.Key == true)
                    {
                        organisation.RegNumber = applNoResp.Value;
                    }
                    organisation.StatusID     = 1;
                    organisation.BranchID     = getBranchID();
                    organisation.ModifiedBy   = User.Identity.Name;
                    organisation.ModifiedDate = DateTime.Now;
                    organisation.CreatedBy    = User.Identity.Name;
                    organisation.DateCreated  = DateTime.Now;
                    swdb.Organisation.Add(organisation);
                    swdb.SaveChanges();

                    MembershipUser newUser;
                    //MembershipCreateStatus status;
                    newUser = membershipService.CreateUser(organisation.RegNumber, organisation.RegNumber, organisation.ContactEmailAddress);

                    roleService.AddUserToRole(organisation.RegNumber, "Organisation Admin");
                    // organisation.Users.Add(newUser);

                    sw.Users user = swdb.Users.FirstOrDefault(x => x.UserName == organisation.RegNumber);
                    organisation.Users.Add(user);
                    swdb.SaveChanges();

                    //int[] acnts = editModel.SelectedAcountTypes;

                    //if (acnts != null)
                    //{
                    //    foreach (int account in acnts)
                    //    {
                    //        OrganisationPortfolio orgPort = db.OrganisationPortfolio.Where(x => x.OrgID == organisation.Id && x.AccountTypeID == account).FirstOrDefault();
                    //        if (orgPort == null)
                    //        {
                    //            OrganisationPortfolio detail = new OrganisationPortfolio();
                    //            detail.AccountTypeID = account;
                    //            detail.OrgID = organisation.Id;
                    //            detail.AccountState = 1;
                    //            detail.LastPayment = DateTime.Now;
                    //            detail.ModifiedBy = User.Identity.Name;
                    //            detail.ModifiedDate = DateTime.Now;
                    //            detail.TotalPayments = 0;
                    //            detail.TotalOverPaid = 0;
                    //            detail.TotalPenalty = 0;
                    //            db.OrganisationPortfolio.AddObject(detail);
                    //            db.SaveChanges();
                    //        }
                    //    }
                    //}



                    TempData["message"] = "<b>" + organisation.Name + "</b> was Successfully Created";
                    return(RedirectToAction("Index"));
                }

                editModel.orgTypes = new SelectList(swdb.OrganisationType, "Id", "Name", organisation.OrganisationTypeId).ToList();
                //editModel.OfficeBranch = new SelectList(db.OfficeBranch, "Id", "BranchName", organisation.BranchID).ToList();
                //editModel.accountTypes = db.AccountType.ToList();
                //editModel.SelectedAcountTypes = db.OrganisationPortfolio.Where(x => x.ID == -1).Select(x => x.AccountTypeID ?? 0).ToArray();

                return(View(editModel));
            }
            catch (Exception ex)
            {
                // Log with Elmah
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                TempData["message"] = Settings.Default.GenericExceptionMessage;
                return(RedirectToAction("Index", "Home", new { area = "Admin" }));
            }
        }
Exemplo n.º 9
0
 public async Task <IActionResult> AddUserToRole(AddUserToRoleDto dto)
 {
     return(ActionResultInstance(await _roleService.AddUserToRole(dto)));
 }
Exemplo n.º 10
0
        public async Task <MessageReponse> RegisterUSer(RegisterUserModel model)
        {
            if (model.Password != model.ConfirmPassword)
            {
                return(new MessageReponse()
                {
                    Message = "ConfirmPassword does not map Password ",
                    IsSuccess = true,
                });
            }
            var userName = await _userManager.FindByNameAsync(model.UserName);

            if (userName != null)
            {
                return(new MessageReponse()
                {
                    Message = "UserName already exists !",
                    IsSuccess = false,
                });
            }
            var userEmail = await _userManager.FindByEmailAsync(model.Email);

            if (userEmail != null)
            {
                return(new MessageReponse()
                {
                    Message = "UserEmail already exists !",
                    IsSuccess = false,
                });
            }
            if (!model.Dob.HasValue)
            {
                return(new MessageReponse()
                {
                    Message = "Dob is Required !",
                    IsSuccess = false,
                });
            }

            var user = new AppUser()
            {
                UserName    = model.UserName.ToUpper(),
                Email       = model.Email.ToUpper(),
                FirstName   = model.FirstName.ToUpper(),
                LastName    = model.LastName.ToUpper(),
                PhoneNumber = model.PhoneNumber,
                Dob         = model.Dob,
            };



            var result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                var claims = new List <Claim>()
                {
                    new Claim(ClaimTypes.GivenName, model.FirstName),
                    new Claim(ClaimTypes.Surname, model.LastName),
                    new Claim(ClaimTypes.Email, model.Email),
                };
                await _userManager.AddClaimsAsync(user, claims);

                var listRoleModel = new ArrayList();
                if (model.ListRoleName == null)
                {
                    return(new MessageReponse()
                    {
                        Message = "This user is not belong to any role !",
                        IsSuccess = true,
                    });
                }
                foreach (var role in model.ListRoleName)
                {
                    var roleModel = new AddToRoleModel()
                    {
                        UserName = model.UserName,
                        RoleName = role
                    };
                    listRoleModel.Add(roleModel);
                }

                if (listRoleModel == null)
                {
                    return(new MessageReponse()
                    {
                        Message = "Add role failed !",
                        IsSuccess = false,
                    });
                }
                foreach (AddToRoleModel roleModel in listRoleModel)
                {
                    await _roleService.AddUserToRole(roleModel);
                }
                return(new MessageReponse()
                {
                    Message = "Register Successed !",
                    IsSuccess = true,
                });
            }
            return(new MessageReponse()
            {
                Message = "Register Failed !",
                IsSuccess = false,
            });
        }
Exemplo n.º 11
0
        public async Task <string> ExternalLoginCallback()
        {
            return(await ProcessRequest(async() =>
            {
                ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    throw new AppException(_logger, "Failed to get information");
                }

                ApplicationUser userEmailExists = await _unitOfWork.User.FindByEmailAsync(info.Principal.FindFirst(ClaimTypes.Email).Value);
                if (userEmailExists == null)
                {
                    ApplicationUser appUser = new ApplicationUser()
                    {
                        Email = info.Principal.FindFirst(ClaimTypes.Email).Value,
                        UserName = info.Principal.FindFirst(ClaimTypes.Email).Value,
                        FirstName = info.Principal.FindFirst(ClaimTypes.GivenName).Value,
                        LastName = info.Principal.FindFirst(ClaimTypes.Surname).Value,
                        EmailConfirmed = true,
                    };

                    await _unitOfWork.User.CreateAsync(appUser);
                    await _unitOfWork.SaveAsync();

                    List <Claim> claims = new List <Claim>()
                    {
                        new Claim(ClaimTypes.GivenName, appUser.FirstName),
                        new Claim(ClaimTypes.Surname, appUser.LastName),
                        new Claim(ClaimTypes.Email, appUser.Email),
                    };

                    AddToRoleDto role = new AddToRoleDto()
                    {
                        RoleName = "USER",
                        UserName = appUser.UserName
                    };

                    await _roleService.AddUserToRole(role);
                    foreach (var claim in claims)
                    {
                        var userClaim = new ApplicationUserClaim()
                        {
                            UserId = appUser.Id,
                            ClaimType = claim.Type,
                            ClaimValue = claim.Value
                        };

                        await _unitOfWork.UserClaim.CreateAsync(userClaim);
                    }

                    await _unitOfWork.SaveAsync();

                    return _tokenService.GenerateJWTToken(appUser, 1);
                }
                else
                {
                    userEmailExists.Email = info.Principal.FindFirst(ClaimTypes.Email).Value;
                    userEmailExists.FirstName = info.Principal.FindFirst(ClaimTypes.GivenName).Value;
                    userEmailExists.LastName = info.Principal.FindFirst(ClaimTypes.Surname).Value;
                    userEmailExists.UserName = info.Principal.FindFirst(ClaimTypes.Email).Value;
                    userEmailExists.EmailConfirmed = true;

                    _unitOfWork.User.Update(userEmailExists);
                    await _unitOfWork.SaveAsync();

                    return _tokenService.GenerateJWTToken(userEmailExists, 1);
                }
            }));
        }
        public async Task <IActionResult> ExternalLoginCallback()
        {
            ExternalLoginInfo info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                throw new Exception("Failed get infor");
            }
            //var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
            //string[] userInfo = { info.Principal.FindFirst(ClaimTypes.Name).Value, info.Principal.FindFirst(ClaimTypes.Email).Value };

            //var token = info.AuthenticationTokens.Single(x => x.Name == "access_token").Value;

            var userEmailExists = await _userManager.FindByEmailAsync(info.Principal.FindFirst(ClaimTypes.Email).Value);

            if (userEmailExists == null)
            {
                AppUser appUser = new AppUser()
                {
                    Email          = info.Principal.FindFirst(ClaimTypes.Email).Value,
                    UserName       = info.Principal.FindFirst(ClaimTypes.Email).Value,
                    FirstName      = info.Principal.FindFirst(ClaimTypes.GivenName).Value,
                    LastName       = info.Principal.FindFirst(ClaimTypes.Surname).Value,
                    EmailConfirmed = true,
                };
                IdentityResult identityResult = await _userManager.CreateAsync(appUser);

                if (identityResult.Succeeded)
                {
                    var claims = new List <Claim>()
                    {
                        new Claim(ClaimTypes.GivenName, appUser.FirstName),
                        new Claim(ClaimTypes.Surname, appUser.LastName),
                        new Claim(ClaimTypes.Email, appUser.Email),
                    };
                    var role = new AddToRoleModel()
                    {
                        RoleName = "USER",
                        UserName = appUser.UserName
                    };
                    await _roleService.AddUserToRole(role);

                    await _userManager.AddClaimsAsync(appUser, claims);

                    var googleToken = await _tokenService.GenerateJWTToken(appUser.UserName, 1);

                    return(Ok(googleToken));
                }
                return(BadRequest());
            }
            else
            {
                userEmailExists.Email          = info.Principal.FindFirst(ClaimTypes.Email).Value;
                userEmailExists.FirstName      = info.Principal.FindFirst(ClaimTypes.GivenName).Value;
                userEmailExists.LastName       = info.Principal.FindFirst(ClaimTypes.Surname).Value;
                userEmailExists.UserName       = info.Principal.FindFirst(ClaimTypes.Email).Value;
                userEmailExists.EmailConfirmed = true;
                IdentityResult identityResult = await _userManager.UpdateAsync(userEmailExists);

                //if (identityResult.Succeeded)
                //{



                //        await _signInManager.SignInAsync(userEmailExists, false);
                //        return Ok();

                //}
                var googleToken = await _tokenService.GenerateJWTToken(userEmailExists.UserName, 1);

                return(Ok(googleToken));
            }
        }