Exemple #1
0
 public async Task<ClaimsIdentity> Authenticate(UserDTO userDto)
 {
     ClaimsIdentity claim = null;
     // находим пользователя
     ApplicationUser user = await Database.UserManager.FindAsync(userDto.Email, userDto.Password);
     // авторизуем его и возвращаем объект ClaimsIdentity
     if(user!=null)
         claim= await Database.UserManager.CreateIdentityAsync(user,
                                     DefaultAuthenticationTypes.ApplicationCookie);
     return claim;
 }
Exemple #2
0
        // начальная инициализация бд
        public async Task SetInitialData(UserDTO adminDto, List<string> roles)
        {
            foreach (string roleName in roles)
            {
                var role = await Database.RoleManager.FindByNameAsync(roleName);
                if (role == null)
                {
                    role = new ApplicationRole { Name = roleName };
                    await Database.RoleManager.CreateAsync(role);
                }
            }

            await Create(adminDto);
        }
Exemple #3
0
        public async Task<OperationDetails> Create(UserDTO userDto)
        {

            ApplicationUser user = await Database.UserManager.FindByEmailAsync(userDto.Email);
            if (user == null)
            {                 
                user = new ApplicationUser { Email = userDto.Email, UserName = userDto.Email };
                await Database.UserManager.CreateAsync(user, userDto.Password);
                // добавляем роль
                await Database.UserManager.AddToRoleAsync(user.Id, userDto.Role);
                // создаем профиль клиента
                ClientProfile clientProfile = new ClientProfile { Id = user.Id, Surname = userDto.Surname, Name = userDto.Name ,Login="******"+Database.UserManager.Users.Count()};
                Database.ClientManager.Create(clientProfile);
                await Database.SaveAsync();
                return new OperationDetails(true, "Register successful", "");

            }
            else
            {
                return new OperationDetails(false, "User with same email already exists", "Email");
            }
        }
        public async Task<OperationDetails> Create(UserDTO userDto)
        {
            ApplicationUser user = await Database.UserManager.FindByEmailAsync(userDto.Email);
            if (user == null)
            {
                user = new ApplicationUser { Email = userDto.Email, UserName = userDto.Email };
                await Database.UserManager.CreateAsync(user, userDto.Password);
                
                // добавляем роль
                await Database.UserManager.AddToRoleAsync(user.Id, userDto.Role);
                // создаем профиль клиента
                ClientProfile clientProfile = new ClientProfile { Id = user.Id, UserId = userDto.UserId };
                Database.ClientManager.Create(clientProfile);
                await Database.SaveAsync();
                return new OperationDetails(true, "Регистрация успешно пройдена", "");

            }
            else
            {
                return new OperationDetails(false, "Пользователь с таким логином уже существует", "Email");
            }
        }
        public async Task<ActionResult> Login(LoginModel model)
        {
            await SetInitialDataAsync();

            if (ModelState.IsValid)
            {
                UserDTO userDto = new UserDTO { Email = model.Email, Password = model.Password };
                ClaimsIdentity claim = await UserService.Authenticate(userDto);
                if (claim == null)
                {
                    ModelState.AddModelError("", "Wrong login or password.");
                }
                else
                {
                    AuthenticationManager.SignOut();
                    AuthenticationManager.SignIn(new AuthenticationProperties
                    {
                        IsPersistent = true
                    }, claim);
                    return RedirectToAction("Index", "Home");
                }
            }
            return View(model);
        }
        public async Task<ActionResult> Register(RegisterModel model)
        {
            await SetInitialDataAsync();

            if (ModelState.IsValid)
            {
                UserDTO userDto = new UserDTO
                {
                    Email = model.Email,
                    Password = model.Password,
                    Role = "user",
                    UserId = Guid.NewGuid().ToString()
                };
                OperationDetails operationDetails = await UserService.Create(userDto);
                if (operationDetails.Succedeed)
                    return View("SuccessRegister");
                else
                    ModelState.AddModelError(operationDetails.Property, operationDetails.Message);
            }
            return View(model);
        }
Exemple #7
0
        public string ChangeUserInfo(UserDTO user)
        {
            try
            {
                if (string.IsNullOrEmpty(user.Name))
                    return "Please enter name";

                if (string.IsNullOrEmpty(user.Surname))
                    return "Please enter surname";
                if (GetUserByLogin(user.Login) != null && GetUserByLogin(user.Login).Id != user.Id)
                    return "This URL is busy";
                if (user.Login.StartsWith("id")&& user.Login.Substring(2).All(char.IsDigit)&&(GetUserByLogin(user.Login) != null && GetUserByLogin(user.Login).Id != user.Id||
                  GetUserByLogin(user.Login) == null))
                {
                    return "This URL is busy";
                }
                if (!(user.Login.All(c => Char.IsLetterOrDigit(c) || c == '_') && user.Login.Any(char.IsLetter)))
                    return "URL can contain only letters, numbers and '_' and must have at least one letter!";


                var config = new MapperConfiguration(cfg => cfg.CreateMap<UserDTO, ClientProfile>());
                var mapper = config.CreateMapper();
                Database.Users.Update(mapper.Map<ClientProfile>(user));
                Database.Save();
                return null;
            }
            catch (Exception)
            {
                return "Internal server error";
            }
        }
        public async Task<ActionResult> Register(RegisterModel model)
        {

            await SetInitialDataAsync();

            if (ModelState.IsValid)
            {
                UserDTO userDto = new UserDTO
                {
                    Email = model.Email,
                    Password = model.Password,
                    Surname = model.Surname,
                    Name = model.Name,
                    Login = model.Login,
                    Role = "user",
                };
                OperationDetails operationDetails = await UserService.Create(userDto);
                if (operationDetails.Succedeed)
                {
                    ClaimsIdentity claim = await UserService.Authenticate(userDto);

                    if (claim == null)
                    {
                        ModelState.AddModelError("", "Wrong login or password.");
                    }
                    else
                    {
                        AuthenticationManager.SignOut();
                        AuthenticationManager.SignIn(new AuthenticationProperties
                        {
                            IsPersistent = true
                        }, claim);
                        return Redirect("/" + userDto.Login);
                    }
                    //  return View("SuccessRegister");
                }
                else
                    ModelState.AddModelError(operationDetails.Property, operationDetails.Message);
            }
            return View(model);
        }