public async Task <ActionResult <LoginResultDTOout> > Login(UserLoginDataDTOin data) { AcUser user = um.Users.FirstOrDefault(x => x.UserName == data.UserNameOrEmail || x.Email == data.UserNameOrEmail); if (user == null) { return(StatusCode(401, new { error = "username or password mismatch!" })); } await sm.SignInAsync(user, false, data.Password); if (sm.IsSignedIn(User)) { return(StatusCode(401, new { error = "username or password mismatch!" })); } await sm.SignOutAsync(); string token = await jwtService.CreateJWT(user); var result = new LoginResultDTOout { authToken = token }; return(result); }
public async Task <string> CreateJWT(AcUser u) { //Preferences here var blockedUserNames = userBlockingsRepository.All().Where(x => !x.IsDeleted && x.DefenderId == u.Id).Select(x => x.Irritator.UserName).ToArray(); var roles = await um.GetRolesAsync(u); List <Claim> claims = new List <Claim>() { new Claim(ClaimTypes.Name, u.UserName), new Claim("roles", string.Join("|", roles)), new Claim("fullName", $"{u.FirstName} {u.LastName}"), new Claim("cookRank", ((int)u.CookRank).ToString()), new Claim("_id", u.Id), new Claim("avPic", u.AvatarPicture), new Claim("blocked", string.Join("|", blockedUserNames)) }; var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddDays(GlobalConstants.TokenExpirationDays), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(this.jwtSettings.Secret.ToByteArray()), SecurityAlgorithms.HmacSha256Signature), Issuer = this.jwtSettings.Issuer }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return(tokenHandler.WriteToken(token)); }
public AcUser Authenticate(string email, string password) { if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) { return(null); } var userWithRole = ( from usr in _context.AcUser join rol in _context.AcRole on usr.UsrRolId equals rol.RolId where usr.UsrEmail == email select new { User = usr, RolName = rol } ).SingleOrDefault(); AcUser user = userWithRole.User; user.UsrRol = userWithRole.RolName; // check if username exists if (user == null) { return(null); } // check if password is correct if (!VerifyPasswordHash(password, user.UsrCryptedPassword, user.UsrPasswordSalt)) { return(null); } // authentication successful return(user); }
private async Task SeedUsers() { foreach (var kvp in SeederConstants.RolesUsersCount) { for (int i = 1; i <= kvp.Value; i++) { string userName = kvp.Key + i; Gender gender = (Gender)(i % 3); CookRank cookRank = (CookRank)(1 + i % 7); var user = new AcUser() { FirstName = SeederConstants.PersonNames[gender][0], LastName = SeederConstants.PersonNames[gender][1], UserName = userName, Gender = gender, Email = userName + "@gmail.com", AvatarPicture = SeederConstants.AvatarPictures[gender], Description = SeederConstants.UserDescription, CookRank = cookRank, SecurityStamp = Guid.NewGuid().ToString() }; var res = await um.CreateAsync(user, SeederConstants.UserPassword); if (res.Succeeded) await um.AddToRoleAsync(user, kvp.Key); } } }
public IActionResult Register([FromBody] UserDto userDto) { // map dto to entity var userReq = _mapper.Map <AcUser>(userDto); string newPassword; if (userDto.GenPassword) { newPassword = Functions.RandString(8); } else { newPassword = userDto.LoginPassword; } try { // check if admin AcUser user = new AcUser(); if (userDto.UsrEmail != null) { user = _userService.Create(userReq, newPassword); if (userDto.GenPassword) { _mailService.Send(user.UsrEmail, "Your password is: " + newPassword, "Mobilisis User Account"); } } else { List <AcTrigger> trgs = _triggerService.GetByValue(userDto.PhoneNumber); if (trgs.Count > 0) { throw new AppException("Phone number already exists."); } userReq.UsrEmail = "guest-" + userDto.PhoneNumber; userReq.UsrName = "guest-" + userDto.PhoneNumber; userReq.UsrActivity = 1; user = _userService.Create(userReq, newPassword); _triggerService.Create(user.UsrId, "Sms", userDto.PhoneNumber, 1); _triggerService.Create(user.UsrId, "Phone", userDto.PhoneNumber, 1); AcAccess acs = _accessService.Create(new AccessDto { ObjId = userDto.guestObjId, UsrId = user.UsrId, ValidFrom = userDto.guestValidFrom, ValidTo = userDto.guestValidTo }); _mailService.SendSMS(userDto.PhoneNumber, "You were added access to following object: " + acs.AcsObj.ObjName); // send sms } return(Ok(user.UsrId)); } catch (AppException ex) { // return error message if there was an exception return(BadRequest(new { message = ex.Message })); } }
// Get user's mobile phone number if available, otherwise an empty string. // Demonstrates how to retrieve user properties beyond the regular default set. private static string mobile(string prncpl) { string phone = null; AcUser user = _users.getUser(prncpl); if (user != null) { phone = user.Other.ContainsKey("Mobile") ? (string)user.Other["Mobile"] : null; } return((String.IsNullOrEmpty(phone)) ? String.Empty : phone + "(m)"); }
// Get user's business phone number if available, otherwise an empty string. private static string business(string prncpl) { string phone = null; AcUser user = _users.getUser(prncpl); if (user != null) { phone = user.Business; } return((String.IsNullOrEmpty(phone)) ? String.Empty : phone + "(b)"); }
public async Task UpdateUserUnreadCount(string userName) { if (!EnlistedMembersConections.ContainsKey(userName)) { return; //Noone monitors update of count... } AcUser userFound = await userManager.Users.FirstOrDefaultAsync(x => x.UserName == userName); int unreadCount = await messageService.UnreadMessagesCountAsync(userFound.Id); List <string> userConIds = EnlistedMembersConections[userName].ToList(); await Clients.Clients(userConIds).SendAsync("updateUnrCount", unreadCount); }
public List <ObjectsWithLogData> getObjectsLastOpened() { List <FilterEventLogDto> lastOpened = (from evl in _context.AcEventLog join evs in _context.AcEventStatus on evl.EvlEvsId equals evs.EvsId join obj1 in _context.AcObject on evl.EvlObjId equals obj1.ObjId into AcObject from obj in AcObject.DefaultIfEmpty() join usr1 in _context.AcUser on evl.EvlUsrId equals usr1.UsrId into AcUser from usr in AcUser.DefaultIfEmpty() join trt in _context.AcTriggerType on evl.EvlTrtId equals trt.TrtId where evl.EvlObjId != null && (from log2 in _context.AcEventLog where log2.EvlObjId == evl.EvlObjId && log2.EvlEvsId == 10 orderby log2.EvlDate descending select log2.EvlId ).First().Equals(evl.EvlId) select new FilterEventLogDto { EventLogId = evl.EvlId, Date = evl.EvlDate, TriggerValue = evl.EvlTrgValue, UserName = usr.UsrName, UserSurname = usr.UsrSurname, TriggerName = trt.TrtName, ObjectName = obj.ObjName, EventStatusName = evs.EvsName, ObjectId = evl.EvlObjId }).ToList(); List <ObjectsWithLogData> lstt = (from obj in _context.AcObject join lst in lastOpened on obj.ObjId equals lst.ObjectId into lstl from v in lstl.DefaultIfEmpty() select new ObjectsWithLogData { ObjId = obj.ObjId, ObjName = obj.ObjName, ObjOpen = obj.ObjOpen, ObjAuto = obj.ObjAuto, ObjActivity = obj.ObjActivity, ObjGps = obj.ObjGps, ObjAction = obj.ObjAction, ObjObtTypeId = obj.ObjObtTypeId, Date = v.Date, TriggerValue = v.TriggerValue, UserName = v.UserName, UserSurname = v.UserSurname, TriggerName = v.TriggerName, EventStatusName = v.EventStatusName }).ToList(); return(lstt); }
public UserTrigger getUserByTriggerType(string value, string type) { UserTrigger userTrigger = ( from trgt in _context.AcTriggerType join trg in _context.AcTrigger on new { Key1 = trgt.TrtId, Key2 = value } equals new { Key1 = trg.TrgTrtId, Key2 = trg.TrgValue } into AcTrigger from q in AcTrigger.DefaultIfEmpty() join us in _context.AcUser on q.TrgUsrId equals us.UsrId into AcUser from l in AcUser.DefaultIfEmpty() where trgt.TrtName == type select new UserTrigger { TrgtId = trgt.TrtId, UsrId = q.TrgUsrId, TrgActivity = q.TrgActivity, UsrActivity = l.UsrActivity } ).SingleOrDefault(); return(userTrigger); }
public void Update(AcUser userParam, string password = null) { var user = _context.AcUser.Find(userParam.UsrId); if (user == null) { throw new AppException("User not found"); } if (userParam.UsrEmail != user.UsrEmail) { // username has changed so check if the new username is already taken //if (_context.AcUser.Any(x => x.UsrEmail == userParam.UsrEmail)) if ((from usr in _context.AcUser where usr.UsrEmail == userParam.UsrEmail select usr).SingleOrDefault() != null) { throw new AppException("Username " + userParam.UsrEmail + " is already taken"); } } // update user properties user.UsrName = userParam.UsrName; user.UsrSurname = userParam.UsrSurname; user.UsrEmail = userParam.UsrEmail; // update password if it was entered if (!string.IsNullOrWhiteSpace(password)) { byte[] passwordHash, passwordSalt; CreatePasswordHash(password, out passwordHash, out passwordSalt); user.UsrCryptedPassword = passwordHash; user.UsrPasswordSalt = passwordSalt; } _context.AcUser.Update(user); _context.SaveChanges(); }
public AcUser Create(AcUser user, string password) { // validation if (string.IsNullOrWhiteSpace(password) && string.IsNullOrWhiteSpace(user.UsrEmail)) { throw new AppException("Password and Email are required"); } Console.WriteLine(user.UsrEmail); var order = _context.AcUser.FirstOrDefault(x => x.UsrEmail == user.UsrEmail); if (order != null) { throw new AppException("Email already taken"); } if (user.UsrRolId == 0) { user.UsrRolId = (from rol in _context.AcRole where rol.RolName == "Gost" select rol.RolId).SingleOrDefault(); } byte[] passwordHash, passwordSalt; CreatePasswordHash(password, out passwordHash, out passwordSalt); user.UsrCryptedPassword = passwordHash; user.UsrPasswordSalt = passwordSalt; user.UsrActivity = 1; _context.AcUser.Add(user); _context.SaveChanges(); return(user); }
// Run the AccuRev hist command for all streams in PromoCount.exe.config, generate the results and send it // to the daily log file PromoCountResults-YYYY-MM-DD.log created (or updated) in the same folder where // PromoCount.exe resides. Returns true if the operation succeeded, false otherwise. AcUtilsException // caught and logged in %LOCALAPPDATA%\AcTools\Logs\PromoCount-YYYY-MM-DD.log on hist command failure. // Exception caught and logged in same for a range of exceptions. private static async Task <bool> promoCountAsync() { bool ret = false; // assume failure try { Dictionary <AcStream, Task <AcResult> > map = new Dictionary <AcStream, Task <AcResult> >(_selStreams.Count); Func <AcStream, Task <AcResult> > run = (stream) => { // start-end times reversed as workaround for AccuRev issue 15780 Task <AcResult> result = AcCommand.runAsync( $@"hist -fx -k promote -s ""{stream}"" -t ""{_endTime} - {_startTime}"""); lock (_locker) { map.Add(stream, result); } return(result); }; var tasks = from s in _depots.SelectMany(d => d.Streams) where _selStreams.OfType <StreamElement>().Any(se => se.Stream == s.Name) select run(s); AcResult[] arr = await Task.WhenAll(tasks); // finish running hist commands in parallel if (arr == null || arr.Any(r => r.RetVal != 0)) { return(false); } log($"Promotions to select streams from {_startTime} to {_endTime}.{Environment.NewLine}"); int tgrandtot = 0; int vgrandtot = 0; foreach (var ii in map.OrderBy(n => n.Key)) { log($"{ii.Key} {{{$"promotions\\versions"}}}:"); // key is stream AcResult r = ii.Value.Result; XElement xml = XElement.Parse(r.CmdResult); ILookup <string, XElement> look = xml.Elements("transaction") .ToLookup(n => (string)n.Attribute("user"), n => n); int tsubtot = 0; int vsubtot = 0; foreach (var jj in look.OrderBy(n => _users.getUser(n.Key))) { AcUser user = _users.getUser(jj.Key); int tnum = jj.Count(); int vnum = jj.Elements("version").Count(); string val = $"{{{tnum}\\{vnum}}}"; log($"\t{user.ToString().PadRight(40, '.')}{val.PadLeft(13, '.')}"); tsubtot += tnum; tgrandtot += tnum; vsubtot += vnum; vgrandtot += vnum; } log($"\tTotal {tsubtot} promotions and {vsubtot} versions.{Environment.NewLine}"); } log($"Grand total of {tgrandtot} promotions and {vgrandtot} versions."); ret = true; } catch (AcUtilsException ecx) { AcDebug.Log($"AcUtilsException caught and logged in Program.promoCountAsync{Environment.NewLine}{ecx.Message}"); } catch (Exception ecx) { AcDebug.Log($"Exception caught and logged in Program.promoCountAsync{Environment.NewLine}{ecx.Message}"); } return(ret); }
public static void EnsureCreated(TodoDBContext context) { if (context.Database.EnsureCreated()) { var user = new AcUser { Email = "*****@*****.**", FirstName = "Burak", LastName = "Portakal", Password = "******",//testtest UserName = "******", Salt = "tOoByYVHjUQ4Ue+SWZPmEQ==", CreateDate = DateTime.Now }; context.AcUsers.Add(user); context.AcTaskStatuses.Add(new AcTaskStatus { Status = "Todo" }); context.AcTaskStatuses.Add(new AcTaskStatus { Status = "InProgress" }); context.AcTaskStatuses.Add(new AcTaskStatus { Status = "Completed" }); context.AcTaskPriorities.Add(new AcTaskPriority { Priority = "P1" }); context.AcTaskPriorities.Add(new AcTaskPriority { Priority = "P2" }); context.AcTaskPriorities.Add(new AcTaskPriority { Priority = "P3" }); context.AcCategories.Add(new AcCategory { CategoryName = "Project", User = user }); context.AcTasks.Add(new AcTask { Name = "Test task", CategoryId = 1, Status = 1, TaskPriorityId = 1, User = user, IsDeleted = false, CreateDate = DateTime.Now }); context.AcTasks.Add(new AcTask { Name = "Test task 2", CategoryId = 1, Status = 1, TaskPriorityId = 1, User = user, IsDeleted = false, CreateDate = DateTime.Now }); context.SaveChanges(); } }
//public List<ObjectsWithLogData> getObjects() //{ //List<ObjectsWithLogData> Allobjects = ( // from evl in _context.AcEventLog // join evs in _context.AcEventStatus on evl.EvlEvsId equals evs.EvsId // join obj1 in _context.AcObject on evl.EvlObjId equals obj1.ObjId into AcObject // from obj in AcObject.DefaultIfEmpty() // join usr1 in _context.AcUser on evl.EvlUsrId equals usr1.UsrId into AcUser // from usr in AcUser.DefaultIfEmpty() // join trt in _context.AcTriggerType on evl.EvlTrtId equals trt.TrtId // where req.ObjId == evl.evlObjId // select new ObjectsWithLogData // { // EventLogId = evl.EvlId, // Date = evl.EvlDate, // TriggerValue = evl.EvlTrgValue, // UserName = usr.UsrName, // UserSurname = usr.UsrSurname, // TriggerName = trt.TrtName, // ObjectName = obj.ObjName, // EventStatusName = evs.EvsName // } //).OrderByDescending(x => x.Date).ToList(); //return Allobjects; //} public List <FilterEventLogDto> getEventLogs(int?id) { List <FilterEventLogDto> eventLogs = ( from evl in _context.AcEventLog join evs in _context.AcEventStatus on evl.EvlEvsId equals evs.EvsId join obj1 in _context.AcObject on evl.EvlObjId equals obj1.ObjId into AcObject from obj in AcObject.DefaultIfEmpty() join usr1 in _context.AcUser on evl.EvlUsrId equals usr1.UsrId into AcUser from usr in AcUser.DefaultIfEmpty() join trt in _context.AcTriggerType on evl.EvlTrtId equals trt.TrtId where id == null || evl.EvlUsrId == id select new FilterEventLogDto { EventLogId = evl.EvlId, Date = evl.EvlDate, TriggerValue = evl.EvlTrgValue, UserName = usr.UsrName, UserSurname = usr.UsrSurname, TriggerName = trt.TrtName, ObjectName = obj.ObjName, EventStatusName = evs.EvsName } ).OrderByDescending(x => x.Date).ToList(); return(eventLogs); }