public async Task <JsonResult> Add([FromBody] WorktaskUpdateModel model) { var worktask = model.worktask; int projectId = worktask.ProjectId; int userId = int.Parse(User.Identity.Name); // Проверяем доступ var linkedProject = await _context.GetLinkedAcceptedProject(projectId, userId) .ConfigureAwait(false); if (linkedProject == null) { throw new Exception(TextResource.API_NoAccess); } worktask.CreatedDate = DateTime.UtcNow; var addedTask = await _context.AddAsync(worktask) .ConfigureAwait(false); await _context.SaveChangesAsync(true) .ConfigureAwait(false); return(new JsonResult(new WorktaskAddResponse { worktask = worktask })); }
public async Task <JsonResult> Reject([FromQuery] uint?id) { int projectId = this.ParseValue(id); int userId = int.Parse(User.Identity.Name); // Проверяем, что есть доступ var linkedProject = _dbContext.GetLinkedProjectForUser(projectId, userId); if (linkedProject == null) { throw new Exception(TextResource.API_YouAreNotInvited); } if (linkedProject.Accepted) { throw new Exception(TextResource.API_InviteAccepted); } _dbContext.Remove(linkedProject); await _dbContext.SaveChangesAsync() .ConfigureAwait(false); return(new JsonResult(new OkResponse { message = "Вы отказались от приглашения в проект" })); }
public async Task <JsonResult> UpdateUser(UpdateUserModel model) { byte roleId = byte.Parse(model.rightId); int projectId = int.Parse(model.projectId); int userId = int.Parse(User.Identity.Name); // Проверка доступа var linkedProjectRequestUser = await _context.GetLinkedAcceptedProject(projectId, userId) .ConfigureAwait(false); if (linkedProjectRequestUser == null || linkedProjectRequestUser.RoleId == 1) { throw new Exception(TextResource.API_NoAccess); } // Проверка существования проекта var linkedProject = await _context.LinkedProjects.FirstOrDefaultAsync(x => x.User.Login == model.userLogin && x.ProjectId == projectId) .ConfigureAwait(false); if (linkedProject == null) { throw new Exception(TextResource.API_NotExistLinkedProject); } linkedProject.RoleId = ( byte )roleId; await _context.SaveChangesAsync(true) .ConfigureAwait(false); // Обновляем значение в кэше await _context.GetLinkedAcceptedProject(linkedProject.ProjectId, linkedProject.UserId, true) .ConfigureAwait(false); return(new JsonResult(new RoleUpdateUserResponse { project = linkedProject.Project, roleId = roleId }, _jsonOptions)); }
public static async Task GenerateToken(string id, Token user, TimetrackerContext context, bool isNew = false) { var claims = new List <Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, id) }; var claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); var now = DateTime.UtcNow; var expiredIn = now.Add(tokenDurability); var jwt = new JwtSecurityToken( issuer: TimetrackerAuthorizationOptions.ISSUER, audience: TimetrackerAuthorizationOptions.AUDIENCE, notBefore: now, claims: claimsIdentity.Claims, expires: expiredIn, signingCredentials: new SigningCredentials( TimetrackerAuthorizationOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256) ); var access_token = new JwtSecurityTokenHandler().WriteToken(jwt); var refresh_token = Guid.NewGuid().ToString().Replace("-", ""); user.AccessToken = access_token; user.RefreshToken = refresh_token; user.TokenExpiredDate = expiredIn; if (isNew) { await context.AddAsync(user) .ConfigureAwait(false); } await context.SaveChangesAsync(true) .ConfigureAwait(false); }
public async Task <JsonResult> Update([FromBody] UpdateStateModel model) { var dbWorkTask = await _context.Worktasks.FirstOrDefaultAsync(x => x.Id == model.TaskId) .ConfigureAwait(false); if (dbWorkTask == null) { throw new Exception(TextResource.API_NotExistWorktaskId); } var stateExist = await _context.States.AnyAsync(x => x.Id == model.StateId) .ConfigureAwait(false); if (!stateExist) { throw new Exception(TextResource.API_NotExistStateId); } int projectId = dbWorkTask.ProjectId; int userId = int.Parse(User.Identity.Name); var linkedProject = _context.GetLinkedAcceptedProject(projectId, userId); if (linkedProject == null) { throw new Exception(TextResource.API_NoAccess); } // Если на задачу кто-то тречит - заставить их прекратить var runningWorktracks = _context.Worktracks.Where(x => x.WorktaskId == dbWorkTask.Id && x.Running); if (model.StateId == 6 && runningWorktracks.Any()) { var tracks = runningWorktracks.ToList(); var users = tracks.Select(x => x.UserId); foreach (var userName in users) { await _hub.Value.Clients.Group(userName.ToString()).SendAsync("getActiveTracking", false, null, false, TextResource.API_TrackingTaskClosed) .ConfigureAwait(false); } var now = DateTime.UtcNow; tracks.ForEach(x => { x.Running = false; x.StoppedTime = now; }); _context.UpdateRange(tracks); } dbWorkTask.StateId = ( byte )model.StateId; _context.Update(dbWorkTask); await _context.SaveChangesAsync(true) .ConfigureAwait(false); return(new JsonResult(new OkResponse { message = "Вы успешно изменили состояние задачи" })); }
public async Task <IActionResult> SignIn([FromBody] SignInModel model) { // Валидация if (string.IsNullOrEmpty(model.login.Trim()) || string.IsNullOrEmpty(model.pass.Trim())) { throw new Exception(TextResource.Auth_EmptyValues); } if (model.login.Length < 5 || model.login.Length > 20) { throw new Exception(TextResource.Auth_LoginWrongLength); } if (model.pass.Length < 4 || model.pass.Length > 30) { throw new Exception(TextResource.Auth_PassWrongLength); } var dbUser = await _dbContext.Users.FirstOrDefaultAsync(x => x.Login == model.login) .ConfigureAwait(false); if (dbUser == null) { throw new Exception("Неправильный логин или пароль"); } var password = PasswordHelpers.EncryptPassword(model.pass, dbUser.Pass.Salt); if (!PasswordHelpers.SlowEquals(password, dbUser.Pass.Password)) { throw new Exception("Неправильный логин или пароль"); } var now = DateTime.UtcNow; var user = new { dbUser.Id, dbUser.Login, dbUser.FirstName, dbUser.MiddleName, dbUser.Surname, dbUser.Email, dbUser.BirthDate, dbUser.City }; var dbToken = await _dbContext.Tokens.FirstOrDefaultAsync(x => x.Id == dbUser.TokenId) .ConfigureAwait(false); if (dbToken != null && dbToken.TokenExpiredDate >= now) { return(new JsonResult(new SignInResponse { access_token = dbToken.AccessToken, refresh_token = dbToken.RefreshToken, expired_in = (dbToken.TokenExpiredDate - now).TotalSeconds, user = user })); } bool isFirst = false; // Если пользователь авторизуется впервые if (dbToken == null) { dbToken = new Token(); isFirst = true; } await TokenHelpers.GenerateToken(dbUser.Id.ToString(), dbToken, _dbContext, isFirst) .ConfigureAwait(false); dbUser.TokenId = dbToken.Id; await _dbContext.SaveChangesAsync(true) .ConfigureAwait(false); return(new JsonResult(new SignInResponse { access_token = dbToken.AccessToken, refresh_token = dbToken.RefreshToken, expired_in = (dbToken.TokenExpiredDate - now).TotalSeconds, user = user })); }
public async Task <JsonResult> Update(MyPageModel model) { var dbUser = await _dbContext.GetUserAsync(User.Identity.Name, true) .ConfigureAwait(false); var passwordChanged = !string.IsNullOrEmpty(model.Pass); if (passwordChanged) { var password = PasswordHelpers.EncryptPassword(model.CurrentPass, dbUser.Pass.Salt); if (!PasswordHelpers.SlowEquals(password, dbUser.Pass.Password)) { throw new Exception(TextResource.API_NoAccess); } var salt = PasswordHelpers.GenerateSalt(); var hash = PasswordHelpers.EncryptPassword(model.Pass, salt); dbUser.Pass.Password = hash; dbUser.Pass.Salt = salt; } var IV = dbUser.IV; var firstName = PasswordHelpers.EncryptData(model.FirstName, IV); var surName = PasswordHelpers.EncryptData(model.Surname, IV); var email = PasswordHelpers.EncryptData(model.Email, IV); var middleName = string.IsNullOrEmpty(model.MiddleName) ? null : PasswordHelpers.EncryptData(model.MiddleName, IV); var birthdate = string.IsNullOrEmpty(model.BirthDate) ? null : PasswordHelpers.EncryptData(model.BirthDate, IV); var city = string.IsNullOrEmpty(model.City) ? null : PasswordHelpers.EncryptData(model.City, IV); dbUser.FirstName = firstName; dbUser.Surname = surName; dbUser.MiddleName = middleName; dbUser.City = city; dbUser.Email = email; dbUser.BirthDate = birthdate; _dbContext.Update(dbUser); await _dbContext.SaveChangesAsync() .ConfigureAwait(false); var user = new { dbUser.Login, FirstName = model.FirstName, Surname = model.Surname, MiddleName = model.MiddleName, City = model.City, Email = model.Email, BirthDate = model.BirthDate }; await _dbContext.GetUserAsync(User.Identity.Name, true) .ConfigureAwait(false); return(new JsonResult(new { status = HttpStatusCode.OK, newUser = user, passwordChanged = passwordChanged }, _jsonOptions)); }
public async Task StartTracking(int?taskId) { var worktaskId = taskId.Value; var userName = Context.User.Identity.Name; int userId = int.Parse(Context.User.Identity.Name); var anyActiveWorktrack = await _dbContext.Worktracks.AsNoTracking() .AnyAsync(x => x.User.Id == userId && x.Running) .ConfigureAwait(false); if (anyActiveWorktrack) { await Clients.Caller.SendAsync("getActiveTracking", false, null, false, "У вас уже есть задача, которая отслеживается.") .ConfigureAwait(false); return; } var worktaskData = await _dbContext.Worktasks.AsNoTracking() .Where(x => x.Id == worktaskId) .Select(x => new { x.ProjectId, x.State }) .FirstOrDefaultAsync() .ConfigureAwait(false); if (worktaskData == null) { await Clients.Caller.SendAsync("getActiveTracking", false, null, false, "Не существует задачи с таким идентификатором") .ConfigureAwait(false); return; } var projectId = worktaskData.ProjectId; if (_dbContext.GetLinkedAcceptedProject(projectId, userId) == null) { await Clients.Caller.SendAsync("getActiveTracking", false, null, false, "У вас недостаточно прав, чтобы отслеживать эту задачу.") .ConfigureAwait(false); return; } if (worktaskData.State.Id == 6) { await Clients.Caller.SendAsync("getActiveTracking", false, null, false, "Данная задача уже закрыта") .ConfigureAwait(false); return; } var now = DateTime.UtcNow; var worktrack = await _dbContext.AddAsync(new Worktrack { UserId = userId, StartedTime = now, StoppedTime = now, WorktaskId = worktaskId, Running = true }) .ConfigureAwait(false); await _dbContext.SaveChangesAsync() .ConfigureAwait(false); var group = Clients.Group(userName); await group.SendAsync("getActiveTracking", true, worktrack.Entity, true, string.Empty) .ConfigureAwait(false); }