Beispiel #1
0
        public UserModel Add(Domain.User user)
        {
            var model = new UserModel(user);

            _context.Add(model);
            return(model);
        }
Beispiel #2
0
        /// <summary>
        /// Obtiene el contexto de seguridad dado el guid.
        /// </summary>
        /// <param name="userId">Id del usuario</param>
        /// <returns>Contexto de Seguridad</returns>
        public static SecurityContext GetSecurityContextByUserGuid(int userId)
        {
            if (_securityContexts == null)
                _securityContexts = new Dictionary<string, SecurityContext>();

            if (!_securityContexts.ContainsKey(userId.ToString()))
            {
                lock (_lock)
                {
                    Domain.User securityUser = new Domain.User(userId);

                    if (securityUser == null)
                        throw new UserNotExistException();

                    Dictionary<string, string> userRoles = UserService.GetUserRoles(securityUser.IdUser);
                    Dictionary<string, string> userAreas = UserService.GetUserAreas(securityUser.IdUser);

                    SecurityContext securityContext = new SecurityContext(securityUser, userRoles, userAreas);

                    _securityContexts.Add(securityUser.IdUser.ToString(), securityContext);
                    return securityContext;
                }
            }
            else
                return _securityContexts[userId.ToString()];
        }
Beispiel #3
0
        public async Task <Register.Response> Register(Register.Request request, CancellationToken cancellationToken)
        {
            var response = await _identity.CreateUser(new CreateUser.Request
            {
                Username = request.Username,
                Email    = request.Email,
                Password = request.Password,
                Role     = RoleConstants.UserRole
            }, cancellationToken);

            if (response.IsSuccess)
            {
                var domainUser = new Domain.User
                {
                    Id          = response.UserId,
                    Username    = request.Username,
                    Name        = request.Name,
                    LastName    = request.LastName,
                    Email       = request.Email,
                    CreatedDate = DateTime.UtcNow,
                    Phone       = request.Phone
                };

                await _repository.Save(domainUser, cancellationToken);

                return(new Register.Response
                {
                    UserId = response.UserId
                });
            }

            throw new UserRegisterException(string.Join(",", response.Errors));
        }
Beispiel #4
0
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="input"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task Handle(CreateUserDomainEvent input, CancellationToken cancellationToken)
        {
            var user = new Domain.User(input.UserName, input.PhoneNumber, input.Password, input.TenantId);
            await _userRepository.AddAsync(user);

            await _userRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
        }
Beispiel #5
0
        public ActionResult Create(Domain.User user, FormCollection collection)
        {
            JsonResult ret = new JsonResult();

            try
            {
                user.CreatorID    = (int)LoginUser.ID;
                user.CreationTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                if (user.UIsLock == null)
                {
                    user.UIsLock = 0;
                }
                db.User.Add(user);
                db.SaveChanges();
                ret.Data = JsonConvert.SerializeObject(new
                {
                    status  = 0,
                    message = ""
                });
            }
            catch (Exception ex)
            {
                ret.Data = JsonConvert.SerializeObject(new
                {
                    status  = 1,
                    message = ex.Message
                });
                RecordException(ex);
            }
            return(ret);
        }
        public HttpResponseMessage authenticate(Domain.Login mLogin)
        {
            Domain.User mUser = new Domain.User();


            HttpResponseMessage response = null;

            try
            {
                mUser = userService.Authenticate(mLogin.username, mLogin.Password);
                if (mUser != null)
                {
                    IEnumerable <string> permissions;
                    using (var ctx = new DataAccess.registroclinicoEntities())
                    {
                        permissions = ctx.role_permissions.Where(s => s.Role_id == mUser.roleId).Select(s => s.permissions).ToArray();
                    }

                    response = Request.CreateResponse(HttpStatusCode.OK, new { id = mUser.id, name = $"{mUser.firstName} {mUser.lastNameFather} {mUser.lastNameMother}", permissions = permissions });
                }
                else
                {
                    response = Request.CreateResponse(HttpStatusCode.Forbidden, "Invalid username or password!");
                }
            }
            catch (Exception ex)
            {
                response = Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
            return(response);
        }
        public void SignIn(Domain.User user, bool createPersistentCookie)
        {
            var now   = DateTime.UtcNow.ToLocalTime();
            var roles = _userRoleService.GetRoleName(user.RoleID);

            var ticket = new FormsAuthenticationTicket(1, user.UserName, now, now.Add(_expirationTimeSpan),
                                                       createPersistentCookie, roles, FormsAuthentication.FormsCookiePath);
            var encryptedTicket = FormsAuthentication.Encrypt(ticket);
            var cookie          = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
            {
                HttpOnly = true
            };

            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            cookie.Secure = FormsAuthentication.RequireSSL;

            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }

            HttpContext.Response.Cookies.Add(cookie);

            _cachedUser = user;
        }
            private async Task <User> CreateUser(Command request, Domain.User user, CancellationToken cancellationToken)
            {
                await UserBusinessRules(request, cancellationToken);

                var duplicate = await _context.User.Where(x => x.FirstName == request.FirstName &&
                                                          x.LastName == request.LastName &&
                                                          x.SexId == request.SexId).FirstOrDefaultAsync(cancellationToken);

                if (duplicate != null)
                {
                    throw new Exception("User Already Exists.");
                }

                var newUser = await _context.User.AddAsync(user, cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                var record = await _context.User
                             .AsNoTracking()
                             .Where(x => x.Id == newUser.Entity.Id)
                             .ProjectTo <User>(_mapper.ConfigurationProvider)
                             .FirstOrDefaultAsync(cancellationToken);

                return(record);
            }
Beispiel #9
0
        public async Task <IActionResult> ManageUsers(bool isAdmin, string userId)
        {
            Domain.User user = await UserManager.FindByIdAsync(userId);

            if (isAdmin)
            {
                if (await UserManager.IsInRoleAsync(user, "Admin"))
                {
                    await UserManager.RemoveFromRoleAsync(user, "Admin");
                }
                else
                {
                    await UserManager.AddToRoleAsync(user, "Admin");
                }
            }
            else
            {
                if (await UserManager.IsInRoleAsync(user, "Admin"))
                {
                    await UserManager.RemoveFromRoleAsync(user, "Admin");
                }
                else
                {
                    await UserManager.AddToRoleAsync(user, "Admin");
                }
            }

            return(RedirectToAction("ManageUsers"));
        }
Beispiel #10
0
        private string GeneratedTokenAuth(Domain.User login, DateTime createdAt, DateTime expirationDate)
        {
            try
            {
                ClaimsIdentity identity = new ClaimsIdentity(
                    new GenericIdentity(login.AcessKey, "Login"),
                    new[] {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                    new Claim(JwtRegisteredClaimNames.UniqueName, login.AcessKey)
                }
                    );

                var handler       = new JwtSecurityTokenHandler();
                var securityToken = handler.CreateToken(new SecurityTokenDescriptor
                {
                    Issuer             = _tokenConfigurations.Issuer,
                    Audience           = _tokenConfigurations.Audience,
                    SigningCredentials = _signingConfigurations.SigningCredentials,
                    Subject            = identity,
                    NotBefore          = createdAt,
                    Expires            = expirationDate
                });
                return(handler.WriteToken(securityToken));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #11
0
        public AuthenticateResponse Handle(AuthenticateRequest request)
        {
            var user = databaseAdapter.GetUserByUserName(request.UserName);

            if (user == null)
            {
                user = new Domain.User
                {
                    Id       = Guid.NewGuid(),
                    UserName = request.UserName
                };
            }

            var token = apiTokenService.GenerateToken(new GenerateTokenRequest
            {
                UserId = user.Id.ToString()
            });

            user.RefreshToken          = token.RefreshToken.Token;
            user.RefreshTokenExpiresAt = token.RefreshToken.Expires;

            databaseAdapter.UpsertUser(user);

            return(new AuthenticateResponse
            {
                Token = token.Token,
                RefreshToken = token.RefreshToken.Token
            });
        }
Beispiel #12
0
 internal UserModel(Domain.User user)
 {
     this.Address = user.Address;
     this.Age     = user.Age;
     this.Name    = user.FullName;
     this.Id      = user.UserID;
 }
Beispiel #13
0
        private void approveDenyDailyLeave(bool isApprove, Domain.User currentUser, TimeSheetManager timeSheetManager, DailyLeaveManager dlm, DailyLeave dailyLeave, string userDescription)
        {
            if (dailyLeave.WorkflowStage.Type == "Final")
            {
                throw new Exception("هم اکنون تایید نهایی می باشد");
            }
            var isManager = timeSheetManager.IsUserOrganisationMnager(dailyLeave.UserID, currentUser);

            if (dailyLeave.WorkflowStage.Type == "Manager" && !isManager)
            {
                throw new Exception("آیتم منتظر تایید مدیر ستادی است");
            }

            var data = new ApproveAndDenyJson()
            {
                id              = dailyLeave.ID.ToString(),
                date            = DateTime.Now,
                description     = userDescription,
                workflowStageID = dailyLeave.WorkflowStageID
            };

            if (isApprove)
            {
                dlm.Approve(dailyLeave);
                HistoryUtilities.RegisterApproveHistory(data, this._uow, currentUser);
            }
            else
            {
                dlm.Deny(dailyLeave);
                HistoryUtilities.RegisterApproveHistory(data, this._uow, currentUser);
            }
        }
Beispiel #14
0
        public void Update_FirstNameUpdated()
        {
            var id        = "3fd8cb2c-45a2-4e91-a56f-808c53234f32";
            var email     = "*****@*****.**";
            var firstName = "Edward";
            var surname   = "Bernays";
            var password  = "******";
            var user      = new Domain.User()
            {
                Id        = id,
                Password  = password,
                Email     = email,
                FirstName = firstName,
                Surname   = surname
            };

            var newFirstName = "edwardinho";

            user.Update(password, email, newFirstName, surname);

            user.Id.Should().Be(id);
            user.Email.Should().Be(email);
            user.FirstName.Should().Be(newFirstName);
            user.Surname.Should().Be(surname);
            user.Password.Should().Be(password);
        }
Beispiel #15
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                UserService serviceUser = new UserService();
                User userLogin = new Domain.User();
                userLogin.Login = model.UserName;
                userLogin.AddressMail = model.UserName;
                userLogin.Pwd = Utils.ConvertToHash(model.Password);
                Domain.User user = serviceUser.UserAcess(userLogin);
                if (user != null)
                {
                    SignInAsync(user, model.RememberMe);
                    if (user.LastAccess.HasValue == false || user.LastAccess.Value == DateTime.MinValue)
                        return RedirectToAction("Manager", model);

                    serviceUser.UserLastAcess(user.Id);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("UserName", "Usuário ou senha inválido.");
                }
            }
			
            return View("Index", model);
        }
Beispiel #16
0
        public async Task <IIdentifierResult> HandleAsync(ICreateUser command, ICorrelationContext context)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            var user = new Domain.User(command.Id, command.FullName, command.EmailAddress, command.IsAdministrator, command.IsActive);
            await _repository.AddAsync(user);


            try
            {
                await _repository.SaveChanges();
            }
            catch (EntityAlreadyExistsException)
            {
                throw new BaristaException("user_already_exists", $"A user with the ID '{command.Id}' already exists.");
            }


            await _busPublisher.Publish(new UserCreated(user.Id, user.FullName, user.EmailAddress, user.IsAdministrator, user.IsActive));

            return(new IdentifierResult(user.Id));
        }
Beispiel #17
0
        public async Task <object> CreateUser(CreateUserModel model)
        {
            var user = new Domain.User(model.userName, model.password);
            await _unitOfWork.Add(user);

            return(await _unitOfWork.CommitAsync());
        }
Beispiel #18
0
        private void SendMailForResellerSignUp(ResellerSignup objReseller)
        {
            try
            {
                var                    ToEmail     = Site.Settings.Where(ss => ss.SiteID == Site.ID && ss.Key.ToLower() == SettingConstants.CURRENT_SITE_TOEMAIL.ToLower()).FirstOrDefault();
                SiteSettings           thankyou    = Site.Settings.Where(o => o.Key == WBSSLStore.Domain.SettingConstants.CURRENT_SITE_THANKYOUPAGE && o.SiteID == Site.ID).FirstOrDefault();
                var                    objEmailQue = DependencyResolver.Current.GetService <WBSSLStore.Service.IEmailQueueService>();
                WBSSLStore.Domain.User objUser     = new Domain.User();
                objUser.FirstName                   = objReseller.FirstName;
                objUser.LastName                    = objReseller.LastName;
                objUser.Email                       = objReseller.Email;
                objUser.Address                     = new Address();
                objUser.Address.Street              = objReseller.Street;
                objUser.Address.City                = objReseller.City;
                objUser.Address.CompanyName         = objReseller.CompanyName;
                objUser.Address.Country             = new Country();
                objUser.Address.Country.CountryName = objReseller.CountryName;
                objUser.Address.State               = objReseller.State;
                objUser.Address.Fax                 = objReseller.Fax;
                objUser.Address.Phone               = objReseller.Phone;
                objUser.CompanyName                 = objReseller.CountryName;
                objUser.HeardBy                     = objReseller.HearedBy;

                objEmailQue.PrepareEmailQueue(Site.ID, WBHelper.CurrentLangID(), EmailType.ADMIN_NEW_RESELLER, SiteCacher.SiteSMTPDetail().ID, !string.IsNullOrEmpty(Convert.ToString(ToEmail.Value)) ? Convert.ToString(ToEmail.Value) : "*****@*****.**", objUser);
                objEmailQue.PrepareEmailQueue(Site.ID, WBHelper.CurrentLangID(), EmailType.RESELLER_WELCOME_EMAIL, SiteCacher.SiteSMTPDetail().ID, Convert.ToString(objReseller.Email), objUser);
                _unitOfWork.Commit();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #19
0
        private ExcelPackage ProcessUserProfileData(ExcelPackage package, Domain.User user)
        {
            var profileWorksheet = package.Workbook.Worksheets.Add("Profil");

            profileWorksheet.Cells[1, 1, 1, 2].Value = "Vos données";
            profileWorksheet.Cells[1, 1, 1, 2].Merge = true;

            profileWorksheet.Cells[2, 1].Value = "Nom";
            profileWorksheet.Cells[2, 2].Value = user.LastName;
            profileWorksheet.Cells[3, 1].Value = "Prénom";
            profileWorksheet.Cells[3, 2].Value = user.FirstName;
            profileWorksheet.Cells[4, 1].Value = "Adresse e-mail";
            profileWorksheet.Cells[4, 2].Value = user.Email;
            profileWorksheet.Cells[5, 1].Value = "Numéro de mobile";
            profileWorksheet.Cells[5, 2].Value = user.Phone;
            profileWorksheet.Cells[6, 1].Value = "Image de profil";
            profileWorksheet.Cells[6, 2].Value = user.Picture;
            profileWorksheet.Cells[7, 1].Value = "Date de création du compte";
            profileWorksheet.Cells[7, 2].Value = user.CreatedOn.ToString("dd/MM/yyyy HH:mm");
            profileWorksheet.Cells[8, 1].Value = "Date de dernière mise à jour";
            profileWorksheet.Cells[8, 2].Value =
                (user.UpdatedOn.HasValue ? user.UpdatedOn.Value : user.CreatedOn).ToString("dd/MM/yyyy HH:mm");
            profileWorksheet.Cells[9, 1].Value = "Points";
            profileWorksheet.Cells[9, 2].Value = user.TotalPoints;

            return(package);
        }
            public async Task <OutputUser> Handle(RegisterCommand request, CancellationToken cancellationToken)
            {
                if (await _context.Users.Where(x => x.Email.ToLower() == request.Email.ToLower()).AnyAsync())
                {
                    throw new ErrorException(HttpStatusCode.BadRequest, new { Email = "Email already exists" });
                }

                if (await _context.Users.Where(x => x.UserName.ToLower() == request.Username.ToLower()).AnyAsync())
                {
                    throw new ErrorException(HttpStatusCode.BadRequest, new { Username = "******" });
                }

                var user = new Domain.User
                {
                    FullName = request.FullName,
                    Email    = request.Email,
                    UserName = request.Username
                };

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

                if (result.Succeeded)
                {
                    return(new OutputUser
                    {
                        fullName = user.FullName,
                        token = _jwtGenerator.CreateToken(user),
                        userName = user.UserName,
                        image = user.photoUrl
                    });
                }

                throw new Exception("Problem creating user");
            }
Beispiel #21
0
 //code omitted for brevity
 public void Save(Domain.User user)
 {
     //Pseudo-code
     //1) Validate Domain.User
     //2) Convert Domain.User to Persistence.User
     //3) Persist Persistence.User
 }
Beispiel #22
0
        public async Task <Domain.User> UpdateUser(Domain.User user)
        {
            var currentUser = await _context.Users.SingleOrDefaultAsync(x => x.Login == user.Login.ToString());

            if (currentUser == null)
            {
                return(null);
            }

            currentUser.PhoneNumber  = user.PhoneNumber.ToString();
            currentUser.EmailAddress = user.EmailAddress.ToString();

            await _context.SaveChangesAsync();

            //var result = _mapper.Map<Domain.User>(currentUser);
            var result = new Domain.User(currentUser.UserId,
                                         currentUser.FirstName,
                                         currentUser.LastName,
                                         new Domain.Login(currentUser.Login),
                                         new Domain.Password(new Domain.Hash(currentUser.Password)),
                                         new Domain.Email(currentUser.EmailAddress),
                                         new Domain.PhoneNumber(currentUser.PhoneNumber),
                                         user.LastAccessAt);

            return(result);
        }
        public bool Process(Domain.User user)
        {
            _logger.Log(LogLevel.Info, string.Format("Processing New User Registration for {0}, Starting.", user.UserId));

            if (!String.IsNullOrEmpty(user.MobileNumber))
            {
                _logger.Log(LogLevel.Info, string.Format("Processing New User Registration for {0}. Sending Verification Codes.", user.UserId));

                //get random alpha numerics
                user.MobileVerificationCode1 = "1234";
                user.MobileVerificationCode2 = "4321";

                user.UserStatus = UserStatus.Pending;

                _ctx.SaveChanges();

                string message = String.Format(_mobileValidationMessage, user.MobileVerificationCode1, user.MobileVerificationCode2);

                //sms mobile verification codes
                _smsService.SendSMS(user.ApiKey, user.MobileNumber, message);

                //send registration email
                string emailSubject = _welcomeEmailSubject;

                var replacementElements = new List <KeyValuePair <string, string> >();
                replacementElements.Add(new KeyValuePair <string, string>("EMAILADDRESS", user.EmailAddress));
                replacementElements.Add(new KeyValuePair <string, string>("LINK_ACTIVATION", String.Format(_activationUrl, user.ConfirmationToken)));

                _emailService.SendEmail(user.EmailAddress, emailSubject, _templateName, replacementElements);
            }

            _logger.Log(LogLevel.Info, string.Format("Processing New User Registration for {0}. Finished.", user.UserId));

            return(true);
        }
Beispiel #24
0
        //Handles the creation of a new user
        public async Task HandleCreate(Contracts.RegisterUser cmd)
        {
            //check if user already exists in event store
            if (await _store
                .Exists <Domain.User, UserId>(
                    new UserId(cmd.UserId)
                    ))
            {
                throw new InvalidOperationException(
                          $"Entity with id {cmd.UserId} already exists"
                          );
            }

            //create new instance of user from the command
            var user = new Domain.User(
                new UserId(cmd.UserId),
                Name.FromString(cmd.Name)
                );

            //save the new user to the event store
            await _store
            .Save <Domain.User, UserId>(
                user
                );
        }
Beispiel #25
0
        public void UpdateUser(Domain.User user)
        {
            _userRepository.UpdateUser(user);

            // rerender page
            _renderService.BuildUserPage(user.Id);
        }
Beispiel #26
0
        public void Fill(Domain.User user)
        {
            user.name          = nameTextBox.Text;
            user.firstName     = firstNameTextBox.Text;
            user.email         = emailTextBox.Text.Trim();
            user.active        = activeBox.IsChecked.Value;
            user.administrator = adminCheckBox.IsChecked.Value;
            user.login         = loginTextBox.Text.Trim();
            user.password      = passwordTextBox.Password;
            if (!user.IsAdmin())
            {
                string profilS = (string)profilcomboBox.SelectedItem;
                user.profil = getProfilByName(profilS);;

                //Domain.Profil profil = (Domain.Profil)profilcomboBox.SelectedItem;
                //user.profil = profil;
            }
            foreach (UIElement el in this.RelationPanel.panel.Children)
            {
                UserRelations.UserRelationItemPanel item = (UserRelations.UserRelationItemPanel)el;
                if (item.userComboBox.SelectedItem == null && item.roleComboBox.SelectedItem == null)
                {
                    continue;
                }
                Domain.Relation relation = new Domain.Relation();
                item.RelationItem.owner = item.userComboBox.SelectedItem as string;
                item.RelationItem.role  = item.roleComboBox.SelectedItem as string;
            }
        }
Beispiel #27
0
        public SignupResponse SignupUser(SignupRaw raw)
        {
            // Convert from Raw --> Domain Entity
            var user = new Domain.User {
                Email            = new Email(raw.Email),
                Name             = new Name(raw.Name),
                Password         = new Password(raw.Password),
                CreatedAt        = DateTime.Now,
                ProfileImagePath = new ImagePath(),
                Username         = new Username(raw.Username),
            };

            // Check uniqueness of email
            if (!_userRepository.CheckEmailUniqueness(user.Email))
            {
                return(new SignupResponse(false, SignupResponseError.EmailUniqueness));
            }

            // Check uniqueness of username
            if (!_userRepository.CheckUsernameUniqueness(user.Username))
            {
                return(new SignupResponse(false, SignupResponseError.UsernameUniqueness));
            }

            // Add user to context and save to DB
            var model = _userRepository.Add(user);

            _userRepository.SaveChanges();

            // create tokens
            var access  = _createToken(TokenType.Access, model.Id);
            var refresh = _createToken(TokenType.Refresh, model.Id);

            return(new SignupResponse(true, model.Id, access, refresh));
        }
Beispiel #28
0
        public virtual ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (_userService.Authenticate(model.UserName, model.Password))
                {
                    Domain.User user                    = _userService.GetByUserName(model.UserName);
                    string      userData                = string.Join(DMSIdentity.UserDataSeparator.ToString(), user.UserId, user.ToString());
                    HttpCookie  authCookie              = FormsAuthentication.GetAuthCookie(model.UserName, false);
                    FormsAuthenticationTicket ticket    = FormsAuthentication.Decrypt(authCookie.Value);
                    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData, authCookie.Path);
                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);

                    Response.Cookies.Add(authCookie);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction(MVC.Home.Index()));
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, LoginResources.IncorrectUsernameOrPassword);
                }
            }

            return(View());
        }
Beispiel #29
0
        public CommandResult <Domain.User> Register(Domain.User user)
        {
            var errors = _AddValidator.ValidateAdd(user);

            if (errors.Any())
            {
                return(new CommandResult <Domain.User>
                {
                    Entity = null,
                    RowsAffected = 0,
                    ValidationErrors = errors
                });
            }

            user.Salt     = _HashService.GenerateSalt();
            user.Password = _HashService.HashString(user.Password, user.Salt);

            _DbContext.Users.Add(user);
            _DbContext.SaveChanges();

            return(new CommandResult <Domain.User>
            {
                Entity = user,
                RowsAffected = 1,
                ValidationErrors = new List <string>()
            });
        }
Beispiel #30
0
        public async Task <IActionResult> AddUser()
        {
            string email    = HttpContext.Request.Form["email"];
            string name     = HttpContext.Request.Form["Name"];
            string surname  = HttpContext.Request.Form["Surname"];
            string login    = HttpContext.Request.Form["Login"];
            string password = HttpContext.Request.Form["Password"];
            string userTyp  = HttpContext.Request.Form["userTyp"];

            using (var context = new RealEstateOfficeContext())
            {
                var usr = new Domain.User();
                usr.Emailaddress = email;
                usr.Name         = name;
                usr.Surname      = surname;
                usr.Login        = login;
                usr.Password     = UserDatabaseContext.codePassword(password);
                usr.UserType     = Convert.ToInt32(userTyp);

                context.Add(usr);
                await context.SaveChangesAsync();
            }

            return(RedirectToAction("Index", "Users"));
        }
Beispiel #31
0
        public TokenDTO Login(UserLoginDTO userLoginDTO)
        {
            try
            {
                Domain.User login = _userRepository.GetUserLogin(userLoginDTO.Login, userLoginDTO.Password);

                if (login == null)
                {
                    throw new Exception("Usuário e/ou senha incorretos!");
                }

                DateTime createdAt      = DateTime.Now;
                DateTime expirationDate = createdAt + TimeSpan.FromSeconds(_tokenConfigurations.Seconds);
                string   token          = GeneratedTokenAuth(login, createdAt, expirationDate);

                return(new TokenDTO
                {
                    Authenticated = true,
                    CreatedAt = createdAt,
                    ExpirationDate = expirationDate,
                    Token = token,
                    Name = login.Name
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #32
0
        public void LoginTest()
        {
            IManager manager = BLFactory.GetManager();

            var user = new Domain.User("swk5", "swk5", "*****@*****.**");        
            manager.Registrate(user);

            manager.Login(user);
            var activeUser = manager.GetActiveUser();
            Assert.Equal(user, activeUser);
        }
Beispiel #33
0
        public AddUserResponse AddUser(AddUserRequest request)
        {
            var user = new Domain.User() { Name = request.Name };

            _userRepository.Add(user);

            _context.SaveChanges();

            return new AddUserResponse()
                       {
                           StatusCode = StatusOk,
                           UserId = user.UserId
                       };
        }
Beispiel #34
0
        private void CreateAdmin()
        {
            using (var session = DomainAccess.Instance.CurrentSession.OpenSession())
            {
                Security.PasswordManager pwdmng = new Security.PasswordManager();
                using (ITransaction transaction = session.BeginTransaction())
                {
                    Domain.User adminusr = new Domain.User();
                    adminusr.UserID = 0;
                    adminusr.Username = "******";
                    adminusr.FullName = "Miguel Jimenez";
                    adminusr.Password = pwdmng.HashPassword(adminusr.Username, "123456789");
                    session.Save(adminusr);
                    transaction.Commit();
                }

            }
        }
Beispiel #35
0
        /*public static HostConfigSection HostConfig
        {
            get { return _HostConfig; }
        }*/

        #endregion

        public static void DoLogin(string username, string password)
        {
            _logonUser = AuthorizationService.Login(username, password);
        }
        public Domain.User GetDomainObject(bool getChildrenObject, bool getParent)
        {
            Domain.User dto = new Domain.User();
            dto.ID = this.UserID;
            dto.Name = this.Name;
            dto.EmailAddress = this.EmailAddress;
            dto.Organization = this.Organization;
            dto.Title = this.Title;

            dto.RoleID = this.RoleID;
            dto.Role = DataAccess.Roles.Find(i => i.ID == this.RoleID);

            dto.TimeZoneID = this.TimeZoneID;
            dto.TimeZone = DataAccess.TimeZones.Find(i => i.ID == this.TimeZoneID);

            dto.LastLoginDate = this.LastLoginDate;

            dto.DateCreated = this.DateCreated;
            dto.DateModified = this.DateModified;

            if (getChildrenObject)
            {
                // Get login history
                dto.LoginHistory = UserLoginHistory.GetLoginHistory(this.UserID);
            }

            if (getParent)
            {
                // Get evaluation history
            }
            return dto;
        }
        public ActionResult Login(LoginViewModel model, string returnUrl, bool captchaValid, string captchaErrorMessage)
        {
            if (ModelState.IsValid)
            {
                User user = new Domain.User();
                var loginType = CheckInputType(model.UserName);
                user = _wcfService.InvokeService<IUserService, User>(svc => svc.GetUserByUsername(model.UserName, loginType));
                if (user != null)
                {
                    var userLogin = user.UserLogins.FirstOrDefault();
                    if (!user.Active)
                        ModelState.AddModelError("", "Your account has been disabled. Please contact your administrator.");
                    var hashedPassword = Common.Common.CreatePasswordHash(model.Password, userLogin.saltkey);
                    if (hashedPassword.Equals(userLogin.Password))
                    {
                        var userHistry = user.UserLogins.Select(x => x.UserHistories.FirstOrDefault(y => y.IpAddress == GetClientIpAddress())).ToList();
                        var hashedPasswordCap = Common.Common.CreatePasswordCapHash(model.Password, userLogin.saltkey, userLogin.Captcha);
                        if (userHistry == null)
                        {
                            //if (!hashedPasswordCap.Equals(userLogin.PasswordCap))
                            //{
                            if (model.IsCaptchaDisplay.HasValue)
                            {
                                if (captchaValid)
                                {
                                    var encryptedCaptcha = EncryptionExtensions.Encrypt(model.CaptchaUserInput);
                                    model.Captcha = encryptedCaptcha;
                                    try
                                    {
                                        var userHistryViewModel = new UserHistoryViewModel()
                                        {
                                            Captcha = model.Captcha,
                                            IpAddress = GetClientIpAddress(),
                                            PasswordCap = hashedPasswordCap,
                                            SaltKey = user.UserLogins.First().saltkey,
                                            UserId = user.Id
                                        };
                                        var mappedModel = Mapper.Map<UserHistoryViewModel, UserHistory>(userHistryViewModel);
                                        var userHistory = _wcfService.InvokeService<IUserService, UserHistory>((svc) => svc.AddUserHistory(mappedModel));
                                    }
                                    catch (Exception e)
                                    {

                                    }
                                }
                            }
                            //}
                        }
                        else
                        {
                            var passwordCapFromDb = userHistry;
                            if (!passwordCapFromDb.Equals(hashedPasswordCap))
                            {
                                _wcfService.InvokeService<IUserService>((svc) => svc.UpdateUserLogin(userHistry.FirstOrDefault()));
                            }
                            else
                            {
                                SessionContext.SuspiciousErrorMessage = "NOTE: Please change your password immediately.";
                            }
                        }

                        AuthenticateUser(user, userLogin);

                        if (returnUrl != null)
                        {
                            return RedirectToLocal(returnUrl);
                        }
                        else
                        {
                            if (user.OrganizationId == 0)
                                return RedirectToAction("Organization", "Dashboard");
                            else
                            {
                                if (user.OrganizationId.HasValue)
                                {
                                    var organization = _wcfService.InvokeService<IOrganizationService, Organization>((svc) => svc.GetOrganizationById(user.OrganizationId.Value));
                                    var docFolder = organization.LibraryFolders.FirstOrDefault(x => x.FolderName == "Documents");
                                    if (!docFolder.LibraryAssets.IsCollectionValid())
                                    {
                                        return RedirectToAction("OrganizationDocs", "Dashboard");
                                    }
                                    else if (!organization.Roles.IsCollectionValid())
                                    {
                                        return RedirectToAction("AddRole", "Dashboard");
                                    }
                                    else
                                    {
                                        return RedirectToAction("Index", "Dashboard");
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Please enter a valid Username/Password");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Please enter a valid Username/Password");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Beispiel #38
0
        // TODO: Map all properties.
        private Domain.User MapClientUserToDomain(Models.User userCTO)
        {
            var blockedUsers = new List<BsonDocument>();
            // TODO: Ugh!
            foreach(String username in userCTO.BlockedUsers)
            {
                var blockedUser = new BsonDocument();
                var user = userRepository.Get(username);
                blockedUser.Add(new BsonElement("_id", user.Id));
                blockedUser.Add(new BsonElement("Username", user.Username));
                blockedUsers.Add(blockedUser);
            }
            var userDTO = new Domain.User()
            {
                Id = new ObjectId(userCTO.Id),
                Username = userCTO.Username,
                Password = userCTO.Password,
                BlockedUsers = blockedUsers,
                Avatar = userCTO.AvatarId
            };

            return userDTO;
        }
Beispiel #39
0
 public FubuPrincipal(IIdentity identity, Domain.User user)
     : this(identity)
 {
     _user = user;
 }