コード例 #1
0
        public async Task <JsonResult> SignUp([FromBody] SignUpModel model)
        {
            var dbUser = await _dbContext.Users.FirstOrDefaultAsync(x => x.Login == model.Login)
                         .ConfigureAwait(false);

            if (dbUser != null)
            {
                throw new Exception("Пользователь с таким логином уже существует");
            }

            // Хешируем пароли
            var salt = PasswordHelpers.GenerateSalt();
            var hash = PasswordHelpers.EncryptPassword(model.Pass, salt);

            // Шифруем личные данные
            var IV         = PasswordHelpers.GetIV();
            var firstName  = PasswordHelpers.EncryptData(model.FirstName, IV);
            var surName    = PasswordHelpers.EncryptData(model.Surname, IV);
            var email      = PasswordHelpers.EncryptData(model.Email, IV);
            var middleName = string.IsNullOrEmpty(model.MiddleName) ? null : PasswordHelpers.EncryptData(model.MiddleName, IV);
            var birthdate  = string.IsNullOrEmpty(model.BirthDate) ? null : PasswordHelpers.EncryptData(model.BirthDate, IV);
            var city       = string.IsNullOrEmpty(model.City) ? null : PasswordHelpers.EncryptData(model.City, IV);

            var user = new User
            {
                Login = model.Login,
                Pass  = new Pass
                {
                    Password = hash,
                    Salt     = salt
                },
                IV         = IV,
                FirstName  = firstName,
                Surname    = surName,
                MiddleName = middleName,
                City       = city,
                BirthDate  = birthdate,
                Email      = email
            };

            await _dbContext.AddAsync(user)
            .ConfigureAwait(false);

            await _dbContext.SaveChangesAsync(true)
            .ConfigureAwait(false);

            return(new JsonResult(new OkResponse
            {
                message = "Регистрация пройдена успешно"
            }));
        }
コード例 #2
0
ファイル: AccountController.cs プロジェクト: cbrooker/Armor
        public ActionResult ResetPassword(ResetPasswordViewModel model)
        {
            try
            {
                User user = service.GetUserByID(Guid.Parse(model.UserID));
                user.Password           = PasswordHelpers.EncryptPassword(model.NewPassword);
                user.ForgotPasswordHash = null;

                service.Save(user);

                //this.StoreSuccess("Your password has been updated, you can now login!");

                return(RedirectToAction("login"));
            }
            catch (Exception ex)
            {
                //this.StoreError("There was a problem updating your password");
                return(View());
            }
        }
コード例 #3
0
ファイル: AccountController.cs プロジェクト: cbrooker/Armor
        public ActionResult Create(CreateAccountModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    //If there are no UserRoles in the Roles table shit breaks, Add them if not present
                    UserRoleService URS = new UserRoleService();
                    if (URS.GetCount() == 0)
                    {
                        UserRole UR = new UserRole();
                        UR.Name = "Administrator";
                        URS.Save(UR);
                        UR      = new UserRole();
                        UR.Name = "User";
                        URS.Save(UR);
                    }


                    //Armor.Data.User user = Mapper.Map<CreateAccountModel, Armor.Data.User>(model);
                    User Newuser = new User();

                    Newuser.Address            = model.Address;
                    Newuser.City               = model.City;
                    Newuser.CreatedDate        = DateTime.UtcNow;
                    Newuser.EmailAddress       = model.EmailAddress;
                    Newuser.FaxNumber          = model.Fax;
                    Newuser.FirstName          = model.FirstName;
                    Newuser.ForgotPasswordHash = new Guid();
                    Newuser.GSTInformation     = model.GSTInformation;
                    Newuser.IsActive           = true;
                    Newuser.LastName           = model.LastName;
                    Newuser.Password           = PasswordHelpers.EncryptPassword(model.Password);
                    Newuser.PhoneNumber        = model.Phone;
                    Newuser.PostalCode         = model.PostalCode;
                    Newuser.Province           = model.Province;
                    Newuser.RoleID             = URS.GetByRoleName("User").ID;

                    service.Save(Newuser);


                    // build a message to send to the user.
                    //string validateUrl = string.Format("{0}account/validate/{1}", App.BaseUrl, Helpers.base64Encode(user.EmailAddress));

                    //TemplateParser parser = new TemplateParser();
                    //Dictionary<string, string> replacements = new Dictionary<string, string>();
                    //replacements.Add("[BASE_URL]", App.BaseUrl);
                    //replacements.Add("[FIRST_NAME]", user.EmailAddress);
                    //replacements.Add("[VALIDATE_ACCOUNT_URL]", validateUrl);

                    //string message = parser.Replace(AccountEmails.ValidateAccount, replacements);

                    //EmailSender sender = new EmailSender();
                    //sender.Send(App.MailConfiguration, model.EmailAddress, "", "Thank you for registering on epilogger.com", message);

                    //this.StoreSuccess("Your account was created successfully<br /><br/>Please check your inbox for our validation message, your account will be inaccessable until you validate it.");

                    return(RedirectToAction("login", "account"));
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ViewRes.SharedString.CreateAccountProblem + " - " + ex.Message.ToString());
                    return(View(model));
                }
            }
            else
            {
                return(View(model));
            }
        }
コード例 #4
0
        public async Task <IActionResult> SignIn([FromBody] SignInModel model)
        {
            // Валидация
            if (string.IsNullOrEmpty(model.login.Trim()) || string.IsNullOrEmpty(model.pass.Trim()))
            {
                throw new Exception(TextResource.Auth_EmptyValues);
            }

            if (model.login.Length < 5 || model.login.Length > 20)
            {
                throw new Exception(TextResource.Auth_LoginWrongLength);
            }

            if (model.pass.Length < 4 || model.pass.Length > 30)
            {
                throw new Exception(TextResource.Auth_PassWrongLength);
            }

            var dbUser = await _dbContext.Users.FirstOrDefaultAsync(x => x.Login == model.login)
                         .ConfigureAwait(false);

            if (dbUser == null)
            {
                throw new Exception("Неправильный логин или пароль");
            }

            var password = PasswordHelpers.EncryptPassword(model.pass, dbUser.Pass.Salt);

            if (!PasswordHelpers.SlowEquals(password, dbUser.Pass.Password))
            {
                throw new Exception("Неправильный логин или пароль");
            }

            var now = DateTime.UtcNow;

            var user = new
            {
                dbUser.Id,
                dbUser.Login,
                dbUser.FirstName,
                dbUser.MiddleName,
                dbUser.Surname,
                dbUser.Email,
                dbUser.BirthDate,
                dbUser.City
            };

            var dbToken = await _dbContext.Tokens.FirstOrDefaultAsync(x => x.Id == dbUser.TokenId)
                          .ConfigureAwait(false);

            if (dbToken != null && dbToken.TokenExpiredDate >= now)
            {
                return(new JsonResult(new SignInResponse
                {
                    access_token = dbToken.AccessToken,
                    refresh_token = dbToken.RefreshToken,
                    expired_in = (dbToken.TokenExpiredDate - now).TotalSeconds,
                    user = user
                }));
            }

            bool isFirst = false;

            // Если пользователь авторизуется впервые
            if (dbToken == null)
            {
                dbToken = new Token();
                isFirst = true;
            }

            await TokenHelpers.GenerateToken(dbUser.Id.ToString(), dbToken, _dbContext, isFirst)
            .ConfigureAwait(false);

            dbUser.TokenId = dbToken.Id;

            await _dbContext.SaveChangesAsync(true)
            .ConfigureAwait(false);

            return(new JsonResult(new SignInResponse
            {
                access_token = dbToken.AccessToken,
                refresh_token = dbToken.RefreshToken,
                expired_in = (dbToken.TokenExpiredDate - now).TotalSeconds,
                user = user
            }));
        }
コード例 #5
0
        public async Task <JsonResult> Update(MyPageModel model)
        {
            var dbUser = await _dbContext.GetUserAsync(User.Identity.Name, true)
                         .ConfigureAwait(false);

            var passwordChanged = !string.IsNullOrEmpty(model.Pass);

            if (passwordChanged)
            {
                var password = PasswordHelpers.EncryptPassword(model.CurrentPass, dbUser.Pass.Salt);
                if (!PasswordHelpers.SlowEquals(password, dbUser.Pass.Password))
                {
                    throw new Exception(TextResource.API_NoAccess);
                }

                var salt = PasswordHelpers.GenerateSalt();
                var hash = PasswordHelpers.EncryptPassword(model.Pass, salt);
                dbUser.Pass.Password = hash;
                dbUser.Pass.Salt     = salt;
            }

            var IV         = dbUser.IV;
            var firstName  = PasswordHelpers.EncryptData(model.FirstName, IV);
            var surName    = PasswordHelpers.EncryptData(model.Surname, IV);
            var email      = PasswordHelpers.EncryptData(model.Email, IV);
            var middleName = string.IsNullOrEmpty(model.MiddleName) ? null : PasswordHelpers.EncryptData(model.MiddleName, IV);
            var birthdate  = string.IsNullOrEmpty(model.BirthDate) ? null : PasswordHelpers.EncryptData(model.BirthDate, IV);
            var city       = string.IsNullOrEmpty(model.City) ? null : PasswordHelpers.EncryptData(model.City, IV);

            dbUser.FirstName  = firstName;
            dbUser.Surname    = surName;
            dbUser.MiddleName = middleName;
            dbUser.City       = city;
            dbUser.Email      = email;
            dbUser.BirthDate  = birthdate;

            _dbContext.Update(dbUser);

            await _dbContext.SaveChangesAsync()
            .ConfigureAwait(false);

            var user = new
            {
                dbUser.Login,
                FirstName  = model.FirstName,
                Surname    = model.Surname,
                MiddleName = model.MiddleName,
                City       = model.City,
                Email      = model.Email,
                BirthDate  = model.BirthDate
            };

            await _dbContext.GetUserAsync(User.Identity.Name, true)
            .ConfigureAwait(false);

            return(new JsonResult(new
            {
                status = HttpStatusCode.OK,
                newUser = user,
                passwordChanged = passwordChanged
            }, _jsonOptions));
        }