private SearchOutput Search(DataInput <SearchInput> requestDto, UserTypeEnum searchUserType, int fieldNumber) { if (CheckAuthority(requestDto.CurrentUser, searchUserType)) { return(ApplyPaging(requestDto.Dto, new List <UserOutput>().AsQueryable())); } if (requestDto.Dto != null) { requestDto.Dto.SearchEqual = (new string[] { "groups" }).ToList(); } List <Expression <Func <UserOutput, bool> > > listExpresion = GetExpressions <UserOutput>(requestDto.Dto, fieldNumber); var user = GetUserContact(requestDto.CurrentUser); IQueryable <UserOutput> queryResult = GetAllType(user.UserType.Equals(UserTypeEnum.SuperAdmin) ? searchUserType : user.UserType, user.CountryId ?? null) .Select(row => new UserOutput(row, row.UserType.Equals(UserTypeEnum.Staff) || row.UserType.Equals(UserTypeEnum.Employee) ? GetGroupContact(row.Groups) : null)); if (queryResult == null) { return(ApplyPaging(requestDto.Dto, new List <UserOutput>().AsQueryable())); } queryResult = SearchAuthority(queryResult, user, searchUserType); if (listExpresion != null) { foreach (Expression <Func <UserOutput, bool> > expression in listExpresion) { queryResult = queryResult.Where(expression); } } queryResult = ApplyOrderBy(requestDto.Dto, queryResult); return(ApplyPaging(requestDto.Dto, queryResult)); }
private IEnumerable <UserAssignmentInfo> GetUsersAssignByUser(User user, bool isSuper = false) { if (user.UserType.Equals(UserTypeEnum.Employee)) { return(new List <UserAssignmentInfo>()); } UserTypeEnum type = (UserTypeEnum)Enum.Parse(typeof(UserTypeEnum), Enum.GetName(typeof(UserTypeEnum), (int)user.UserType + 1), true); IEnumerable <User> users = _userRepository.GetMany(x => x.UserType.Equals(type)).WhereIf(user.CountryId != null, x => x.CountryId.Equals(user.CountryId)); if (!isSuper) { if (string.IsNullOrEmpty(user.Users)) { return(new List <UserAssignmentInfo>()); } users = users.Where(u => user.Users.SplitTrim(_comma).Any(x => x == u.Code)); } return(users.Select(row => new UserAssignmentInfo() { Code = row.Code, Username = row.Username, FullName = row.FullName, Users = GetUsersAssignByUser(row, row.UserType.Equals(UserTypeEnum.SuperAdmin)) })); }
private string GenerateToken(UserTypeEnum type, long id, string name, int gender) { // http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token var claimsIdentity = new ClaimsIdentity(new[] { new Claim(JtClaimTypes.UserType, ((int)type).ToString()), new Claim(JtClaimTypes.Id, id.ToString()), new Claim(JtClaimTypes.AccountName, name), new Claim(JtClaimTypes.Gender, gender.ToString()), }); var securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(JtConstants.JwtSecurityKey)); var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var audience = _configuration["Jwt:Audience"]; var issuer = _configuration["Jwt:Issuer"]; double duration = Convert.ToDouble(_configuration["Jwt:Duration"]); DateTime issuedAt = DateTime.UtcNow; DateTime expires = issuedAt.AddHours(duration); // create the jwt var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateJwtSecurityToken( audience: audience, issuer: issuer, subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials); var tokenString = tokenHandler.WriteToken(token); return(tokenString); }
private static string GetJavascriptDefaultPermissionsArray(UserTypeEnum userType) { //Functionality[] defaultFunctionalities = client.GetDefaultFunctionalitiesForUserGroup(SessionObject.CurrentBitplateUser, setName); string jsArray = "["; foreach (FunctionalityEnum funcEnumValue in Enum.GetValues(typeof(FunctionalityEnum))) { int functionNumber = (int)funcEnumValue; if (userType == UserTypeEnum.Moderators) { if (functionNumber >= 1000 && functionNumber < 2000) { jsArray += functionNumber + ","; } } else if (userType == UserTypeEnum.Designers) { if (functionNumber >= 1000 && functionNumber < 3000) { jsArray += functionNumber + ","; } } else if (userType == UserTypeEnum.SiteAdmins) { jsArray += functionNumber + ","; } } jsArray = jsArray.Substring(0, jsArray.Length - 1); jsArray += "]"; return(jsArray); }
public async Task RegisterAsync(UserTypeEnum userType, CreateUserCommand command) { var user = new User { Name = command.FirstName, UserName = UserHelper.GetUserName(userType, command.Email), Surname = command.LastName, Degree = command.AcademicTitle, Email = command.Email, Specialization = command.Specialization, University = command.University }; // only participant have avatar if (userType == UserTypeEnum.Participant) { user.Photo = await _fileManager.SaveFileAsync(command.Avatar); } var createUserResult = await _userManager.CreateAsync(user, command.Password); if (createUserResult.Succeeded) { await _userManager.AddToRoleAsync(user, userType.ToString()); var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); await _emailSender.SendConfirmationEmailAsync(user.Id, user.Email, token); } }
/* * Return the number of appointments * coming next */ public int GetComingNextAppointmentsNumber(UserTypeEnum userType, int userId) { return(GetCurrentUserAppointments(userType, userId).Where(appointment => appointment.Date.TimeOfDay > DateTime.Now.TimeOfDay) .Where(appointment => appointment.Date.Date == DateTime.Today) .Where(appointment => appointment.Status == Status.ACCEPTED) .Count()); }
/// <summary> /// Redirect to the page for the current user type if /// it is not the allowed type. Super user can go anywhere. /// </summary> /// <param name="allowed"></param> /// <returns></returns> protected bool Redirect(UserTypeEnum allowed) { if (Session["UserType"] == null) { Response.Redirect("Login.aspx"); return(true); } UserTypeEnum uType = (UserTypeEnum)Session["UserType"]; if ((uType == allowed) || (uType == UserTypeEnum.Super)) { return(false); } switch (uType) { case UserTypeEnum.Student: Response.Redirect("GameScreen.aspx"); break; case UserTypeEnum.Teacher: Response.Redirect("TeacherHome.aspx"); break; case UserTypeEnum.Administrator: Response.Redirect("AdminHome.aspx"); break; } return(true); }
private IEnumerable <DropdownList> GetUsersHasNotBeenAssignedByGroups(UserTypeEnum userType, string countryId, string groups = null) { IEnumerable <User> TManagers = GetAllType(UserTypeEnum.Manager, countryId); IEnumerable <User> TStaff = GetAllType(UserTypeEnum.Staff, countryId); IEnumerable <User> TEmployee = GetAllType(UserTypeEnum.Employee, countryId); switch (userType) { case UserTypeEnum.Manager: TManagers = TManagers.AsQueryable().Where(x => !string.IsNullOrEmpty(x.Users)); TStaff = TStaff.Where(s => !TManagers.Any(m => m.Users.SplitTrim(_comma).Any(x => x.Equals(s.Code)))).AsQueryable() .WhereIf(!string.IsNullOrEmpty(groups), x => groups.SplitTrim(_comma).Any(g => g.Equals(x.Groups))); return(TStaff.Count() > 0 ? TStaff.AsQueryable().Select(x => new DropdownList(x.Code, x.Username)).AsEnumerable() : new List <DropdownList>()); case UserTypeEnum.Staff: TStaff = TStaff.AsQueryable().Where(x => !string.IsNullOrEmpty(x.Users)); TStaff = TStaff.Where(s => !TManagers.Any(m => m.Users.SplitTrim(_comma).Any(x => x.Equals(s.Code)))).AsQueryable() .WhereIf(!string.IsNullOrEmpty(groups), x => groups.SplitTrim(_comma).Any(g => g.Equals(x.Groups))); return(TEmployee.Count() > 0 ? TEmployee.AsQueryable().Select(x => new DropdownList(x.Code, x.Username)).AsEnumerable() : new List <DropdownList>()); case UserTypeEnum.SuperAdmin: case UserTypeEnum.Employee: default: return(new List <DropdownList>()); } }
public static string GetEnumDisplayName(this UserTypeEnum userTypeEnum) { return(userTypeEnum.GetType().GetMember(userTypeEnum.ToString()) .First() .GetCustomAttribute <DisplayAttribute>() .Name); }
private Guid Create(string currentUser, UserTypeEnum userType, ErrorCodeEnum exitedUser, ErrorCodeEnum exitedEmail, EnumIDGenerate genCode, dynamic dataObject) { if (!(dataObject is ManagerInput || dataObject is StaffInput || dataObject is EmployeeInput)) { throw new BadData(); } if (ExistedUser(dataObject.Username)) { Log.Information("Username {Username} existed!", (string)dataObject.Username); throw new DefinedException(exitedUser); } else { if (CheckAuthority(currentUser, userType)) { Log.Information("Account {Username} not authorized!", currentUser); throw new DefinedException(ErrorCodeEnum.NotAuthorized); } if (ExisedEmail((string)dataObject.Email)) { Log.Information("Email {Email} existed!", (string)dataObject.Email); throw new DefinedException(exitedEmail); } if (((string)dataObject.Username).HasSpecial()) { Log.Information("User {Username} wrong format!", (string)dataObject.Username); throw new DefinedException(ErrorCodeEnum.ExitedSpecialInUsername); } if (!((string)dataObject.Password).CheckPassFormat()) { Log.Information("Password {Password} wrong format!", (string)dataObject.Password); throw new DefinedException(ErrorCodeEnum.PasswordWrongFormat); } string codeLate = _userRepository.GetAll().OrderBy(x => x.CreatedDate).Last().Code.Base64ToString(); var Code = genCode.GenerateCode(Convert.ToInt32(codeLate) + 1); User user = new User { Id = Guid.NewGuid(), Code = Code, CountryId = (string)dataObject.CountryId, Username = (string)dataObject.Username, FullName = (string)dataObject.FullName, Users = dataObject is EmployeeInput ? null : GenerateUsers(userType, (string)dataObject.CountryId, (string)dataObject.Groups), Groups = dataObject is ManagerInput ? (string)dataObject.Groups : (string)dataObject.Group, Address = (string)dataObject.Address, Email = (string)dataObject.Email, Phone = (string)dataObject.PhoneNo, UserType = userType, Status = dataObject is EmployeeInput ? StatusEnum.Available : StatusEnum.Active, StartDate = (DateTime?)dataObject.StartDate, ExpiredDate = (DateTime?)dataObject.ExpiredDate, Password = string.IsNullOrEmpty(dataObject.Password) ? GeneratePassword() : dataObject.Password, CreatedBy = currentUser, }; user = _userRepository.Insert(user); //_emailService.SendNewPassword(user.Email, EncryptService.Decrypt(user.Password), user.FullName, null); Log.Information("Create " + user.UserTypeStr + ": {Username} Successfully", user.Username); return(user.Id); } }
/* * Return the coming next * appointment for a specific staff */ public Appointment GetComingNextAppointment(UserTypeEnum userType, int userId) { return(GetCurrentUserAppointments(userType, userId).Where(appointment => appointment.Date > DateTime.Now) .Where(appointment => appointment.Status == Status.ACCEPTED) .OrderBy(appointment => appointment.Date) .FirstOrDefault()); }
public bool AuthenticateUser(string username, string password, UserTypeEnum userType) { LoggedUser = null; UserType = null; AppContext ctx = new AppContext(); switch (userType) { case UserTypeEnum.Administrator: AdministratorRepository adminRepo = new AdministratorRepository(new AppContext()); LoggedUser = unitOfWork.AdminRepository.GetByUsername(username); break; case UserTypeEnum.Student: StudentRepository studentRepo = new StudentRepository(new AppContext()); LoggedUser = unitOfWork.StudentRepository.GetByUsername(username); break; case UserTypeEnum.Teacher: TeacherRepository teacherRepo = new TeacherRepository(new AppContext()); LoggedUser = unitOfWork.TeacherRepository.GetByUsername(username); break; } if (LoggedUser != null) { if (PasswordHasher.Equals(password, LoggedUser.Salt, LoggedUser.Hash)) { UserType = userType; return true; } LoggedUser = null; } return false; }
public async Task LoginAsyncSignInSuccessedCreateJwtToken(UserTypeEnum userType) { var command = new LoginUserCommand() { Email = _faker.Person.Email, Password = _faker.Internet.Password(), TokenId = _faker.Random.Guid() }; var userName = UserHelper.GetUserName(userType, command.Email); var user = new User() { Id = 1 }; var jwtToken = ""; _userManagerMock.Setup(x => x.FindByNameAsync(userName)).ReturnsAsync(user); _signInManagerMock.Setup(x => x.PasswordSignInAsync(user, command.Password, false, false)).ReturnsAsync(SignInResult.Success); _jwtHandlerMock.Setup(x => x.CreateToken(user.Id, userType.ToString())).Returns(jwtToken); var err = await Record.ExceptionAsync(async() => await _userService.LoginAsync(userType, command)); err.Should().BeNull(); _signInManagerMock.Verify(x => x.PasswordSignInAsync(user, command.Password, false, false), Times.Once); _jwtHandlerMock.Verify(x => x.CreateToken(user.Id, userType.ToString()), Times.Once); }
public User(string userName, int userID, DateTime userCreatedDate, UserTypeEnum userCategory) { this._userID = userID; this._userName = userName; this._userCreatedDate = userCreatedDate; this._userCategory = userCategory; this._userSince = GetUsersAge(_userCreatedDate); }
public static string ToDescriptionString(this UserTypeEnum val) { DescriptionAttribute[] attributes = (DescriptionAttribute[])val .GetType() .GetField(val.ToString()) .GetCustomAttributes(typeof(DescriptionAttribute), false); return(attributes.Length > 0 ? attributes[0].Description : string.Empty); }
/* * Return the number of new appointments * in the last 24 hours * for a specific staff */ public int GetNewAppointmentsIn24Hours(UserTypeEnum userType, int userId) { var now = DateTime.Now; return(GetCurrentUserAppointments(userType, userId).Where(appointment => appointment.CreatedAt > now.AddHours(-24) && appointment.CreatedAt <= now) .Where(appointment => appointment.Status == Status.ACCEPTED) .Count()); }
public IActionResult GetUsersAllTypeAssignByCountry(string userType, string country = null) { userType = userType.FirstCharToUpper(); UserTypeEnum type = (userType.Equals(UserTypeEnum.SuperAdmin.ToString()) || userType.Equals(UserTypeEnum.Manager.ToString()) || userType.Equals(UserTypeEnum.Staff.ToString()) || userType.Equals(UserTypeEnum.Employee.ToString())) ? (UserTypeEnum)Enum.Parse(typeof(UserTypeEnum), userType, true) : (UserTypeEnum)Enum.Parse(typeof(UserTypeEnum), UserTypeEnum.Unknow.ToString(), true); return(Json(data: _commonService.GetUsersAllTypeAssignByCountry(type, country))); }
public static Client ToUserExtension(this AuthenticationRequest request, UserTypeEnum userType) { return(new Client { Email = request.Email, Password = request.Password, Type = userType.ToString() }); }
/* * Return the new appointments in * the last 24h */ public int GetLast24HoursWaitingAppointments(UserTypeEnum userType, int userId) { var now = DateTime.Now; var newAppointmentsIn24Hours = GetCurrentUserAppointments(userType, userId).Where(appointment => appointment.CreatedAt > now.AddHours(-24) && appointment.CreatedAt <= now) .Where(appointment => appointment.Status == Status.WAIT) .Count(); return(newAppointmentsIn24Hours); }
public static User ToUser(AuthenticationRequest request, UserTypeEnum userType) { return(new User { username = request.username, password = request.password, Type = userType.ToString() }); }
public void GetUserNameCorectly(UserTypeEnum role) { var email = _faker.Person.Email; var expected = $"{role}:{email}"; var returned = UserHelper.GetUserName(role, email); returned.Should().Be(expected); }
/* * Return the list of * the current staff * todays appointments */ public IEnumerable <Appointment> GetTodaysAppointments(UserTypeEnum userType, int id) { var predicate = GetAppointmentIdPredicate(userType, id); return(_appointmentRepository.GetAll(predicate, x => x.Staff, x => x.Patient) .Where(appointment => appointment.Date.Date == DateTime.Today) .Where(appointment => appointment.Status == Status.ACCEPTED) .OrderBy(appointment => appointment.Date)); }
public static User ToUserExtension(this AuthenticationRequest request, UserTypeEnum userType) { return(new User { Username = request.Username, Password = request.Password, Type = userType.ToString() }); }
public IEnumerable <IDiscount> GetDiscount(IProduct product, UserTypeEnum userType) { string sql = "select * from Discount where fk_product = @productid and fk_ValidForUserType = @userType"; using (var connection = SimpleDbConnection()) { var res = connection.Query <Discount>(sql, new { productid = product.Id, userType = (int)userType }).AsList(); return(res); } }
public ResultModel RegisterEmployee(UserTypeEnum type, int userId, int id) { ResultModel result = new ResultModel(); try { using (LibContext context = new LibContext()) { if (type == UserTypeEnum.Librarian) { GenericRepository <Librarians> generic = new GenericRepository <Librarians>(context); var librarian = generic.FindById(id); if (librarian != null) { librarian.UserId = userId; generic.Update(librarian); } else { result.Code = OperationStatusEnum.UnexpectedError; result.Message = "Неверный идентификатор сотрудника"; } } else if (type == UserTypeEnum.Provider) { GenericRepository <Providers> generic = new GenericRepository <Providers>(context); var provider = generic.FindById(id); if (provider != null) { provider.UserId = userId; generic.Update(provider); } else { result.Code = OperationStatusEnum.UnexpectedError; result.Message = "Неверный идентификатор сотрудника"; } } else { result.Code = OperationStatusEnum.UnexpectedError; result.Message = "Ошибка присваивания роли пользователя"; } } } catch (Exception ex) { result.Code = OperationStatusEnum.UnexpectedError; result.Message = ex.StackTrace; } return(result); }
public IEnumerable <Course> LoadAllCourses(string companyId, UserTypeEnum userType) { var result = unitOfWork.CourseRepository.GetAllAsNoTracking().Where(x => x.CompanyId == companyId && !x.IsDeleted); if (userType == Models.Users.UserTypeEnum.External) { return(result.Where(x => x.CourseAccess == CourseAccessEnum.ExtenralUsersOnly || x.CourseAccess == CourseAccessEnum.BothUsers)); } else // internal { return(result.Where(x => x.CourseAccess == CourseAccessEnum.InternalUsersOnly || x.CourseAccess == CourseAccessEnum.BothUsers)); } }
/* * Return the number of * appointments compare to yesterday */ public int GetNumberOfAppointmentsCompareToYesterday(UserTypeEnum userType, int userId) { var yesterday = DateTime.Today.AddDays(-1); var yesterdayAppointments = GetCurrentUserAppointments(userType, userId).Where(appointment => appointment.Date.Date == yesterday) .Where(appointment => appointment.Status == Status.ACCEPTED) .Count(); var todayAppointments = GetCurrentUserAppointments(userType, userId).Where(appointment => appointment.Date.Date == DateTime.Today) .Where(appointment => appointment.Status == Status.ACCEPTED) .Count(); return(todayAppointments - yesterdayAppointments); }
public async Task <int> GetTagIdAsync(UserTypeEnum typeSCode) { int tagId = 0; string tagName = ""; //var fans1 = await UserTagApi.UserTagListAsync(AppConfig.AppId, "oPM5Uv81jfyJqWbVxWAH-RUqsCAs"); var tags = await UserTagApi.GetAsync(AppConfig.AppId); var groupSe = await _wechatgroupRepository.GetAll().Where(G => G.TypeName == typeSCode.ToString()).FirstOrDefaultAsync(); foreach (var item in tags.tags) { if (item.name == typeSCode.ToString()) { tagId = item.id; tagName = item.name; } } if (string.IsNullOrEmpty(tagName)) { var result = await UserTagApi.CreateAsync(AppConfig.AppId, typeSCode.ToString()); if (groupSe == null) { WeChatGroupListDto group = new WeChatGroupListDto(); if (result.errcode == 0) { group.TagId = result.tag.id; group.TagName = result.tag.name; group.TypeName = typeSCode.ToString(); group.TypeCode = typeSCode; await CreateWeChatGroupAsync(group.MapTo <WeChatGroupEditDto>()); } } return(result.tag.id); } else { if (groupSe == null) { WeChatGroupListDto group = new WeChatGroupListDto(); group.TagId = tagId; group.TagName = tagName; group.TypeName = typeSCode.ToString(); group.TypeCode = typeSCode; await CreateWeChatGroupAsync(group.MapTo <WeChatGroupEditDto>()); } return(tagId); } }
public void LoginAsyncWhenCredentialsAreIncorrectThrowExcpetion(UserTypeEnum userType) { var command = new LoginUserCommand() { Email = _faker.Person.Email }; var userName = UserHelper.GetUserName(userType, command.Email); _userManagerMock.Setup(x => x.FindByNameAsync(userName)).ReturnsAsync((User)null); Func <Task> err = async() => await _userService.LoginAsync(userType, command); err.Should().Throw <Exception>(); }
/// <summary> /// Our securityProviderFactory groups object-creation of a set of classes of a common theme. /// </summary> private static ISecurityProviderFactory GetSecurityProviderFactory(UserTypeEnum userType) { if (userType == UserTypeEnum.SuperUser) { return(new SuperUserSecurityProviderFactory()); } else if (userType == UserTypeEnum.BasicUser) { return(new BasicUserSecurityProviderFactory()); } else { throw new ArgumentException($"Unknown user-type {userType}"); } }
public void RegisterTemporaryUser(string companyId, string updaterId, string email, string password, string firstName, string lastName, UserTypeEnum userType, List <string> groups, List <string> roles) { if (unitOfWork.UserRepository.GetAll() .Any(x1 => x1.IsDeleted == false && x1.Email == email && x1.CompanyAccesses.Any(x2 => x2.CompanyId == companyId))) { throw new UserException("Email " + email + " is already taken."); } var company = unitOfWork.CompanyRepository.GetById(companyId); company.AddUser(email, firstName, lastName, password, userType, UserStatusEnum.Active, true, AcquisitionEnum.OnPremise, groups, roles); unitOfWork.CompanyRepository.Update(company); unitOfWork.SaveChanges(); }
public UserSecurityManager(UserTypeEnum userType) { if (userType == UserTypeEnum.BasicUser) { IAuthenticator authenticator = new BasicUserAuthenticator(); IAuthorizer authorizer = new BasicUserAuthorizer(); } else if (userType == UserTypeEnum.SuperUser) { IAuthenticator authenticator = new SuperUserAuthenticator(); IAuthorizer authorizer = new SuperUserAuthorizer(); } else { throw new ArgumentException("No such user-type"); } }
public Affiliate(DateTime userCreatedDate, UserTypeEnum userCategory) : base(userCreatedDate, userCategory) { }
public Customer(DateTime userCreatedDate, UserTypeEnum userCategory) : base(userCreatedDate, userCategory) { }
public static void AuthenticateUser(string username, string password, UserTypeEnum userType) { AuthenticationServiceInstance.AuthenticateUser(username, password, userType); }
public User(DateTime userCreatedDate, UserTypeEnum userCategory) { this._userCreatedDate = userCreatedDate; this._userCategory = userCategory; this._userSince = GetUsersAge(_userCreatedDate); }
public Employee(DateTime userCreatedDate, UserTypeEnum userCategory) : base(userCreatedDate, userCategory) { }