Beispiel #1
0
        public AccountResponse Create(CreateRequest model)
        {
            var currentAccount = accountRepository.GetAll().SingleOrDefault(x => x.Email == model.Email);

            if (currentAccount != null)
            {
                throw new Exception($"Email {model.Email} has been registered");
            }

            var account = mapper.Map <Account>(model);

            account.Created      = DateTime.UtcNow;
            account.Verified     = DateTime.UtcNow;
            account.PasswordHash = BC.HashPassword(model.Password);
            accountRepository.Add(account);
            return(mapper.Map <AccountResponse>(account));
        }
        public void ResetPassword(ResetPasswordRequest resetPasswordDTO)
        {
            var account = _repo.GetByResetToken(resetPasswordDTO.Token);

            if (account == null)
            {
                throw new AppException("Invalid or expired reset token");
            }

            //else update account and save
            account.PasswordHash        = BC.HashPassword(resetPasswordDTO.Password);
            account.PasswordResetLastOn = DateTime.UtcNow;
            account.ResetToken          = null;
            account.ResetTokenExpiresOn = null;

            _repo.Update(account);
        }
Beispiel #3
0
        public async Task <User> AddFromDTOAsync(UserAddDTO dto)
        {
            if (await this.IsEmailExistsAsync(dto.Email))
            {
                throw new Exception($"The mail ({dto.Email}) is already in use.");
            }

            var user = new User()
            {
                Name       = dto.Name,
                Password   = BC.HashPassword(dto.Password),
                Email      = dto.Email,
                Department = await _departmentRepository.Find(x => x.Name == dto.DepartmentName).FirstAsync(),
            };

            return(await this.Add(user));
        }
        public async Task ResetPassword(ResetPasswordRequest model)
        {
            var account = await _accountRepository.FindValidatedResetToken(model.Token);

            if (account == null)
            {
                throw new Exception("Invalid token");
            }

            // update password and remove reset token
            account.PasswordHash      = BC.HashPassword(model.Password);
            account.PasswordReset     = DateTime.UtcNow;
            account.ResetToken        = null;
            account.ResetTokenExpires = null;

            await _accountRepository.Update(account);
        }
        public async Task Register(RegisterUserRequestDTO model, string origin)
        {
            var user = _userData.GetByEmail(model.Email);

            if (user != null)
            {
                await SendAlreadyRegisteredEmail(user.Email, origin);

                return;
            }

            var userWithSameUsername = _userData.GetByUsername(model.Username);

            if (userWithSameUsername != null)
            {
                throw new AppException("Username already taken, please use different username.");
            }

            var newUser = _mapper.Map <User>(model);

            //first registered user is an admin
            bool isFirstAccount = _userData.GetCount() == 0;

            if (isFirstAccount)
            {
                newUser.Roles.Add(new Role {
                    RoleKey = RoleKey.admin
                });
            }
            else
            {
                newUser.Roles.Add(new Role {
                    RoleKey = RoleKey.superuser
                });
            }

            newUser.CreatedAt         = DateTime.UtcNow;
            newUser.VerificationToken = JwtToken.randomTokenString();

            newUser.Password = BC.HashPassword(model.Password);

            _userData.Add(newUser);

            await SendVerificationEmail(newUser, origin);
        }
Beispiel #6
0
        /// <summary>
        /// The ResetPassword.
        /// </summary>
        /// <param name="model">The model<see cref="ResetPasswordRequest"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task ResetPassword(ResetPasswordRequest model)
        {
            // validate
            TableQuery <User> query = new TableQuery <User>()
                                      .Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, model.UserId));
            var users = await _tableStorage.QueryAsync <User>("User", query);

            var currentUser = users.SingleOrDefault();

            // Validate password and confirmed passwrd are same.
            if (!String.IsNullOrEmpty(model.Password) && !String.IsNullOrEmpty(model.Password))
            {
                if (model.Password != model.ConfirmPassword)
                {
                    var resp = new HttpResponseMessage(HttpStatusCode.NotAcceptable)
                    {
                        Content = new StringContent(string.Format("Password and confirm password are not same!")),
                    };
                    throw new HttpResponseException(resp);
                }
                currentUser.PasswordHash = BC.HashPassword(model.Password);
            }
            else
            {
                var resp = new HttpResponseMessage(HttpStatusCode.NotAcceptable)
                {
                    Content = new StringContent(string.Format("Password and confirm password are required to change!")),
                };
                throw new HttpResponseException(resp);
            }

            currentUser.ForceChangePasswordNextLogin = false;
            currentUser.PasswordReset = DateTime.UtcNow;
            currentUser.Verified      = DateTime.UtcNow;
            currentUser.UpdatedBy     = model.UserId;

            try
            {
                await _tableStorage.UpdateAsync("User", currentUser);
            }
            catch (Exception ex)
            {
                throw new AppException("User password reset error ", ex.InnerException);
            }
        }
        public async Task <OrganizationCreationResponse> CreateOrganization(CreateOrganizationRequest request)
        {
            using (var a = contextFactory.CreateDbContext())
            {
                var existingUser = await a.Users.Where(x => x.Email == request.Email).FirstOrDefaultAsync();

                if (existingUser != null)
                {
                    throw new ArgumentException("Each email can only participate in 1 organization");
                }

                if (await a.Organizations.FirstOrDefaultAsync(x => x.Name.ToLower() == request.OrganizationName.ToLower()) != null)
                {
                    throw new ArgumentException("There is already an organization with that name!");
                }

                var org = new Organizations()
                {
                    Name = request.OrganizationName
                };

                var password = BC.HashPassword(request.Password);

                var user = new Users()
                {
                    Admin          = true,
                    Activated      = true,
                    Email          = request.Email,
                    FirstName      = request.FirstName,
                    LastName       = request.LastName,
                    OrganizationId = org.Id,
                    HashedPassword = password,
                };

                org.Users.Add(user);

                await a.AddAsync(org);

                await a.SaveChangesAsync();

                var token = generateJwtToken(user);

                return(new OrganizationCreationResponse(user, token, org));
            }
        }
Beispiel #8
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            Usuario usuario = new Usuario();

            usuario.Username = TextBoxUsuario.Text;

            string miPassword = TextBoxPassword.Text;
            string miSal      = BC.GenerateSalt();
            string miHash     = BC.HashPassword(miPassword, miSal);


            usuario.Password = miHash;
            usuario.Nivel    = Convert.ToInt32(RadioButtonListNivel.SelectedValue);

            usuarios.Add(usuario);

            Guardar();
        }
Beispiel #9
0
        public async Task <AddUserPayload> CreateUserAsync(
            AddUserInput input,
            [ScopedService] ApplicationDbContext context,
            [Service] ITokenService tokenService,
            CancellationToken cancellationToken)
        {
            var user = new User
            {
                Username       = input.Name,
                HashedPassword = BC.HashPassword(input.Password),
                BirthDate      = input.BirthDate
            };

            context.Users.Add(user);
            await context.SaveChangesAsync(cancellationToken);

            return(new AddUserPayload(user, tokenService.Create(user)));
        }
Beispiel #10
0
        async public Task <bool> AddUser([FromQuery] string userName, [FromQuery] string password)
        {
            if (CheckUserExists(userName))
            {
                return(false);
            }

            string passwordHash = BC.HashPassword(password);

            var newUser = new User {
                UserName = userName, UserPassword = passwordHash
            };

            discordCloneContext.Users.Add(newUser);
            await discordCloneContext.SaveChangesAsync();

            return(true);
        }
Beispiel #11
0
        public void ResetPassword(ResetPasswordRequest model)
        {
            var account = _context.Accounts.SingleOrDefault(a => a.ResetToken == model.Token && a.ResetTokenExpires > DateTime.UtcNow);

            if (account == null)
            {
                throw new AppException("Invalid token.");
            }

            // update
            account.PasswordHash      = BC.HashPassword(model.Password);
            account.PasswordReset     = DateTime.UtcNow;
            account.ResetToken        = null;
            account.ResetTokenExpires = null;

            _context.Accounts.Update(account);
            _context.SaveChanges();
        }
        private void btnInsert_Click(object sender, RoutedEventArgs e)
        {
            //if (txtName.Text.Equals(""))
            if (txtName.Text == "")
            {
                MessageBox.Show("Nama Wajib di masukkan");
            }
            else
            {
                var bcrypt = Bcrypt.HashPassword(txtPass.Text);
                var input  = new Supplier(txtName.Text, txtEmail.Text, bcrypt.ToString());
                context.Suppliers.Add(input);
                context.SaveChanges();
                MessageBox.Show("Data Berhasil Insert");
            }

            Refresh();
        }
        public async Task ResetPasswordAsync(ResetPasswordRequest model)
        {
            Account account = await _context.Accounts.SingleOrDefaultAsync(a =>
                                                                           a.ResetToken == model.Token &&
                                                                           a.ResetTokenExpires > DateTime.UtcNow);

            if (account == null)
            {
                throw new AppException("Invalid token");
            }

            account.PasswordHash      = BC.HashPassword(model.Password);
            account.PasswordReset     = DateTime.UtcNow;
            account.ResetToken        = null;
            account.ResetTokenExpires = null;
            _context.Accounts.Update(account);
            await _context.SaveChangesAsync();
        }
Beispiel #14
0
        //method ends

        //This method will returns the Bcrypted password
        public static string Bcrpyt_Password(string hash)
        {
            var    cost       = 14;
            var    timeTarget = 100; // Milliseconds
            long   timeTaken;
            string bcrypt_hash = "";

            do
            {
                var sw = Stopwatch.StartNew();
                bcrypt_hash = BC.HashPassword(hash, workFactor: cost);
                sw.Stop();
                timeTaken = sw.ElapsedMilliseconds;
                cost     -= 1;
            }while ((timeTaken) >= timeTarget);

            return(bcrypt_hash);
        }
Beispiel #15
0
 public Task <int> userPwdChange(Guid usrID, string oldPwd, string newPwd)
 {
     return(Task <int> .Run(() => {
         var usr = _context.users.FirstOrDefault(u => u.Id == usrID);
         if (usr == null)
         {
             return -2;
         }                               //無此ID
         if (usr.Password != oldPwd)
         {
             return -1;
         }                                          // 密碼錯誤
         usr.Password = BC.HashPassword(newPwd);
         _context.users.Update(usr);
         save();
         return _context.users.Any(u => u.Id == usrID && u.Password == usr.Password) ? 0 : -1;
     }));
 }
Beispiel #16
0
        public void Register(RegisterRequest model)
        {
            // validate
            if (_context.Users.Any(x => x.Username == model.Username))
            {
                throw new AppException("Username '" + model.Username + "' is already taken");
            }

            // map model to new user object
            var user = _mapper.Map <User>(model);

            // hash password
            user.PasswordHash = BCryptNet.HashPassword(model.Password);

            // save user
            _context.Users.Add(user);
            _context.SaveChanges();
        }
Beispiel #17
0
        public async Task <Account> RegisterAsync(Account model, string origin)
        {
            var account = await this._repository.GetByAsync((e => e.Email == model.Email));

            if (account != null)
            {
                throw new Exception("Account exist");
            }

            model.VerificationToken = this.RandomTokenString();
            model.PasswordHash      = BC.HashPassword(model.Password);

            await this._repository.CreateAsync(model);

            await this._repository.SaveChangesAsync();

            return(model);
        }
Beispiel #18
0
        public override async Task <Account> CreateAsync(Account model)
        {
            var exist = await this._repository.GetByAsync((e => e.Email == model.Email));

            if (exist != null)
            {
                throw new ApplicationException($"Email '{model.Email}' is already registered");
            }

            var account = model;

            account.Verified     = DateTime.UtcNow;
            account.PasswordHash = BC.HashPassword(model.PasswordHash);

            await this._repository.CreateAsync(account);

            return(account);
        }
Beispiel #19
0
        public async Task <TeamDto> EditTeam(Guid teamId, String password, TeamRegistrationDto team)
        {
            Team teamToUpdate = await _dbContext.Teams.SingleOrDefaultAsync(x => x.Id == teamId);

            if (teamToUpdate == null)
            {
                throw new BusinessException("");
            }
            if (!Crypt.EnhancedVerify(password, teamToUpdate.Password))
            {
                throw new BusinessException("");
            }
            teamToUpdate.Name     = team.Name;
            teamToUpdate.Password = Crypt.HashPassword(team.Password, 10, enhancedEntropy: true);
            await _dbContext.SaveChangesAsync();

            return(_teamMapper.Map(teamToUpdate));
        }
        /// <summary>
        /// The Register.
        /// </summary>
        /// <param name="model">The model<see cref="RegisterRequest"/>.</param>
        /// <returns>The <see cref="Task{object}"/>.</returns>
        public async Task <object> Register(RegisterRequest model)
        {
            // validate
            var users = await _tableStorage.GetAllAsync <User>("User");

            if (users.Any(x => x.Email == model.Email))
            {
                var resp = new HttpResponseMessage(HttpStatusCode.AlreadyReported)
                {
                    Content      = new StringContent(string.Format($"User { model.Email} already registred!")),
                    ReasonPhrase = "Already registred!"
                };
                throw new HttpResponseException(resp);
            }

            var defaultPasswrod = model.Password ?? "p@ssw0rd";
            var userId          = model.Id ?? Guid.NewGuid().ToString();
            var schoolId        = model.SchoolId ?? userId;

            var newUser = new User(schoolId, userId)
            {
                FirstName     = model.FirstName,
                LastName      = model.LastName,
                Email         = model.Email,
                PasswordHash  = BC.HashPassword(defaultPasswrod),
                Role          = model.Role,
                Active        = true,
                Verified      = DateTime.UtcNow,
                PasswordReset = DateTime.UtcNow,
                CreatedBy     = userId,
                UpdatedOn     = DateTime.UtcNow,
                UpdatedBy     = userId,
                ForceChangePasswordNextLogin = true
            };

            try
            {
                return(await _tableStorage.AddAsync("User", newUser));
            }
            catch (Exception ex)
            {
                throw new AppException("Registration Error: ", ex.InnerException);
            }
        }
Beispiel #21
0
        public async Task <IActionResult> Register([FromBody] User user)
        {
            try {
                //Check if user already exists
                var alreadyExists = await _context.users
                                    .FromSqlRaw("SELECT * FROM users WHERE users.email = {0}", user.email).ToListAsync();

                if (alreadyExists.Count() > 0)
                {
                    var errorResponse = new {
                        error = "User already exists.",
                        ok    = false
                    };
                    return(Json(errorResponse));
                }
                else
                {
                    Console.WriteLine("Inserting a new User {0}", user.email);

                    User     newUser         = new User();
                    DateTime currentDateTime = DateTime.Now;

                    newUser          = user;
                    newUser.created  = currentDateTime;
                    newUser.password = BC.HashPassword(user.password);

                    _context.Add(newUser);
                    _context.SaveChanges();

                    return(Json(newUser));
                }
            } catch (Exception e) {
                //Error
                Console.WriteLine("Error Stack {0}", e.Message);
                Console.WriteLine("Error Stack {0}", e);

                var errorResponse = new {
                    error        = true,
                    ok           = false,
                    errorMessage = e.Message
                };
                return(Json(errorResponse));
            }
        }
Beispiel #22
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity <User>().HasKey(q => q.Id);
            modelBuilder.Entity <User>().ToTable("Users");
            modelBuilder.Entity <User>().Ignore(q => q.FullName);
            modelBuilder.Entity <User>().HasData(new List <User>()
            {
                new User()
                {
                    Id                   = Guid.NewGuid(),
                    UserName             = "******",
                    PasswordHash         = BC.HashPassword("YYyy12!@"),
                    Email                = "*****@*****.**",
                    FirstName            = "Younes",
                    LastName             = "Baghaei",
                    EmailConfirmed       = true,
                    NormalizedEmail      = "*****@*****.**",
                    PhoneNumber          = "123456789",
                    PhoneNumberConfirmed = true,
                    NormalizedUserName   = "******",
                    TwoFactorEnabled     = false
                }
            });

            modelBuilder.Entity <RefreshToken>().HasKey(q => q.Id);
            modelBuilder.Entity <RefreshToken>().ToTable("RefreshTokens");
            modelBuilder.Entity <RefreshToken>().HasOne(q => q.User);

            modelBuilder.Entity <IdentityRole>().ToTable("Roles")
            .HasData(new List <IdentityRole>()
            {
                new IdentityRole("Guest"),
                new IdentityRole("User"),
                new IdentityRole("Admin"),
            });

            modelBuilder.Entity <IdentityUserRole <Guid> >().ToTable("UserRoles");
            modelBuilder.Entity <IdentityUserClaim <Guid> >().ToTable("UserClaims");
            modelBuilder.Entity <IdentityRoleClaim <Guid> >().ToTable("RoleClaims");
            modelBuilder.Entity <IdentityUserToken <Guid> >().ToTable("UserTokens");
            modelBuilder.Entity <IdentityUserLogin <Guid> >().ToTable("UserLogins");
        }
Beispiel #23
0
        public async Task <AccountResponse> Update(int id, UpdateRequest model, string origin)
        {
            var account = await _unitOfWork.Accounts.GetById(id);

            var isEmailChanged = false;

            // validate
            if (account.Email != model.Email)
            {
                if (_unitOfWork.Accounts.ExistsByEmail(model.Email))
                {
                    throw new AppException($"Email '{model.Email}' is already taken");
                }

                isEmailChanged            = true;
                account.VerificationToken = randomTokenString();
                account.Verified          = null;
            }

            if (account.DisplayName != model.DisplayName && _unitOfWork.Accounts.ExistsByDisplayName(model.DisplayName))
            {
                throw new AppException($"Kullanıcı adı '{model.DisplayName}' zaten kayıtlı");
            }

            // hash password if it was entered
            if (!string.IsNullOrEmpty(model.Password))
            {
                account.PasswordHash = BC.HashPassword(model.Password);
            }

            // copy model to account and save
            _mapper.Map(model, account);
            account.Updated = DateTimeOffset.UtcNow;

            _unitOfWork.Accounts.Update(account);
            _unitOfWork.Complete();

            if (isEmailChanged)
            {
                sendVerificationEmail(account, origin);
            }

            return(_mapper.Map <AccountResponse>(account));
        }
        public ActionResult <AccountResponse> Create(CreateRequest model)
        {
            // validate
            if (_repository.Account.AccountExists(model.Email))
            {
                throw new AppException($"Email '{model.Email}' is already registered");
            }

            // map model to new account object
            var account = _mapper.Map <Account>(model);

            // hash password
            account.PasswordHash = BC.HashPassword(model.Password);

            _repository.Account.Create(account);
            var accountResponse = _mapper.Map <AccountResponse>(account);

            return(Ok(accountResponse));
        }
        public async Task RegisterUser(Register model)
        {
            var personnel = new ApplicationUser
            {
                Username     = model.Username,
                Firstname    = model.Firstname,
                Lastname     = model.Lastname,
                Middlename   = model.Middlename,
                Phone1       = model.Mobile,
                Phone2       = model.Phone,
                Email        = model.Email,
                Locationid   = model.Location != null || model.Location != "" ? Convert.ToInt16(model.Location):4,
                Image        = model.ImageLocation,
                Passwordhash = BC.HashPassword(model.Password)
            };

            _context.ApplicationUser.Add(personnel);
            await _context.SaveChangesAsync();
        }
Beispiel #26
0
        public async Task <AddUserPayload> RegisterAsync(AddUserInput input, [ScopedService] AppDbContext dbContext, CancellationToken cancellationToken)
        {
            var hashedPassword = BC.HashPassword(input.Password);

            var newUser = new User
            {
                Name     = input.Name,
                Email    = input.Email,
                Password = hashedPassword,
                Address  = input.Address
            };

            dbContext.Users.Add(newUser);
            await dbContext.SaveChangesAsync(cancellationToken);

            var payload = new AddUserPayload(newUser);

            return(payload);
        }
        internal async Task CreateUser(string username, string password)
        {
            //var response = await Db.User.Where(Q => Q.Username == username).FirstOrDefaultAsync();

            //if(response != null)
            //{
            //    return ;
            //}

            var hash = Hashing.HashPassword(password, 12);

            Db.User.Add(new User
            {
                UserId   = Guid.NewGuid(),
                Username = username,
                Password = hash
            });
            await Db.SaveChangesAsync();
        }
        public UserAccountResponse Create(CreateUserAccountRequest newAccountDTO)
        {
            //validate that the email is not already in use
            if (_repo.Exists(newAccountDTO.Email))
            {
                throw new AppException($"Email  {newAccountDTO.Email} is already registered");
            }
            var newAccount = _mapper.Map <UserAccount>(newAccountDTO);

            newAccount.CreatedOn  = DateTime.UtcNow;
            newAccount.VerifiedOn = DateTime.UtcNow;

            //hashpassword
            newAccount.PasswordHash = BC.HashPassword(newAccountDTO.Password);
            //save
            _repo.Create(newAccount);

            return(_mapper.Map <UserAccountResponse>(newAccount));
        }
        public bool ResetPassword(ResetPasswordRequestDTO model)
        {
            var user = _userData.GetByResetToken(model.Token);

            if (user == null)
            {
                throw new AppException("Invalid token");
            }
            if (user.ResetTokenExpiresAt < DateTime.UtcNow)
            {
                throw new AppException("Invalid token");
            }

            user.Password            = BC.HashPassword(model.Password);
            user.PasswordResetAt     = DateTime.UtcNow;
            user.ResetToken          = null;
            user.ResetTokenExpiresAt = DateTime.MinValue;

            return(_userData.Update(user));
        }
Beispiel #30
0
        public async Task <CardDto> Register(CardCredentialsDto cardCredentials)
        {
            (string number, string pin, int userId) = cardCredentials;

            Card card = new()
            {
                Number         = number, Pin = BC.HashPassword(pin), UserId = userId,
                CheckingBranch = new CheckingBranch
                {
                    Balance = 0m
                },
                User = await Context.Users.FindAsync(cardCredentials.UserId)
            };

            await Context.AddAsync(card);

            await Context.SaveChangesAsync();

            return(Mapper.Map <CardDto>(card));
        }